@@ -205,7 +205,7 @@ |
||
205 | 205 | /** |
206 | 206 | * removes an entry from the comments run time cache |
207 | 207 | * |
208 | - * @param mixed $id the comment's id |
|
208 | + * @param string $id the comment's id |
|
209 | 209 | */ |
210 | 210 | protected function uncache($id) { |
211 | 211 | $id = strval($id); |
@@ -39,842 +39,842 @@ |
||
39 | 39 | |
40 | 40 | class Manager implements ICommentsManager { |
41 | 41 | |
42 | - /** @var IDBConnection */ |
|
43 | - protected $dbConn; |
|
44 | - |
|
45 | - /** @var ILogger */ |
|
46 | - protected $logger; |
|
47 | - |
|
48 | - /** @var IConfig */ |
|
49 | - protected $config; |
|
50 | - |
|
51 | - /** @var IComment[] */ |
|
52 | - protected $commentsCache = []; |
|
53 | - |
|
54 | - /** @var \Closure[] */ |
|
55 | - protected $eventHandlerClosures = []; |
|
56 | - |
|
57 | - /** @var ICommentsEventHandler[] */ |
|
58 | - protected $eventHandlers = []; |
|
59 | - |
|
60 | - /** @var \Closure[] */ |
|
61 | - protected $displayNameResolvers = []; |
|
62 | - |
|
63 | - /** |
|
64 | - * Manager constructor. |
|
65 | - * |
|
66 | - * @param IDBConnection $dbConn |
|
67 | - * @param ILogger $logger |
|
68 | - * @param IConfig $config |
|
69 | - */ |
|
70 | - public function __construct( |
|
71 | - IDBConnection $dbConn, |
|
72 | - ILogger $logger, |
|
73 | - IConfig $config |
|
74 | - ) { |
|
75 | - $this->dbConn = $dbConn; |
|
76 | - $this->logger = $logger; |
|
77 | - $this->config = $config; |
|
78 | - } |
|
79 | - |
|
80 | - /** |
|
81 | - * converts data base data into PHP native, proper types as defined by |
|
82 | - * IComment interface. |
|
83 | - * |
|
84 | - * @param array $data |
|
85 | - * @return array |
|
86 | - */ |
|
87 | - protected function normalizeDatabaseData(array $data) { |
|
88 | - $data['id'] = strval($data['id']); |
|
89 | - $data['parent_id'] = strval($data['parent_id']); |
|
90 | - $data['topmost_parent_id'] = strval($data['topmost_parent_id']); |
|
91 | - $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']); |
|
92 | - if (!is_null($data['latest_child_timestamp'])) { |
|
93 | - $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']); |
|
94 | - } |
|
95 | - $data['children_count'] = intval($data['children_count']); |
|
96 | - return $data; |
|
97 | - } |
|
98 | - |
|
99 | - /** |
|
100 | - * prepares a comment for an insert or update operation after making sure |
|
101 | - * all necessary fields have a value assigned. |
|
102 | - * |
|
103 | - * @param IComment $comment |
|
104 | - * @return IComment returns the same updated IComment instance as provided |
|
105 | - * by parameter for convenience |
|
106 | - * @throws \UnexpectedValueException |
|
107 | - */ |
|
108 | - protected function prepareCommentForDatabaseWrite(IComment $comment) { |
|
109 | - if (!$comment->getActorType() |
|
110 | - || !$comment->getActorId() |
|
111 | - || !$comment->getObjectType() |
|
112 | - || !$comment->getObjectId() |
|
113 | - || !$comment->getVerb() |
|
114 | - ) { |
|
115 | - throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving'); |
|
116 | - } |
|
117 | - |
|
118 | - if ($comment->getId() === '') { |
|
119 | - $comment->setChildrenCount(0); |
|
120 | - $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC'))); |
|
121 | - $comment->setLatestChildDateTime(null); |
|
122 | - } |
|
123 | - |
|
124 | - if (is_null($comment->getCreationDateTime())) { |
|
125 | - $comment->setCreationDateTime(new \DateTime()); |
|
126 | - } |
|
127 | - |
|
128 | - if ($comment->getParentId() !== '0') { |
|
129 | - $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId())); |
|
130 | - } else { |
|
131 | - $comment->setTopmostParentId('0'); |
|
132 | - } |
|
133 | - |
|
134 | - $this->cache($comment); |
|
135 | - |
|
136 | - return $comment; |
|
137 | - } |
|
138 | - |
|
139 | - /** |
|
140 | - * returns the topmost parent id of a given comment identified by ID |
|
141 | - * |
|
142 | - * @param string $id |
|
143 | - * @return string |
|
144 | - * @throws NotFoundException |
|
145 | - */ |
|
146 | - protected function determineTopmostParentId($id) { |
|
147 | - $comment = $this->get($id); |
|
148 | - if ($comment->getParentId() === '0') { |
|
149 | - return $comment->getId(); |
|
150 | - } else { |
|
151 | - return $this->determineTopmostParentId($comment->getId()); |
|
152 | - } |
|
153 | - } |
|
154 | - |
|
155 | - /** |
|
156 | - * updates child information of a comment |
|
157 | - * |
|
158 | - * @param string $id |
|
159 | - * @param \DateTime $cDateTime the date time of the most recent child |
|
160 | - * @throws NotFoundException |
|
161 | - */ |
|
162 | - protected function updateChildrenInformation($id, \DateTime $cDateTime) { |
|
163 | - $qb = $this->dbConn->getQueryBuilder(); |
|
164 | - $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
165 | - ->from('comments') |
|
166 | - ->where($qb->expr()->eq('parent_id', $qb->createParameter('id'))) |
|
167 | - ->setParameter('id', $id); |
|
168 | - |
|
169 | - $resultStatement = $query->execute(); |
|
170 | - $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
171 | - $resultStatement->closeCursor(); |
|
172 | - $children = intval($data[0]); |
|
173 | - |
|
174 | - $comment = $this->get($id); |
|
175 | - $comment->setChildrenCount($children); |
|
176 | - $comment->setLatestChildDateTime($cDateTime); |
|
177 | - $this->save($comment); |
|
178 | - } |
|
179 | - |
|
180 | - /** |
|
181 | - * Tests whether actor or object type and id parameters are acceptable. |
|
182 | - * Throws exception if not. |
|
183 | - * |
|
184 | - * @param string $role |
|
185 | - * @param string $type |
|
186 | - * @param string $id |
|
187 | - * @throws \InvalidArgumentException |
|
188 | - */ |
|
189 | - protected function checkRoleParameters($role, $type, $id) { |
|
190 | - if ( |
|
191 | - !is_string($type) || empty($type) |
|
192 | - || !is_string($id) || empty($id) |
|
193 | - ) { |
|
194 | - throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
195 | - } |
|
196 | - } |
|
197 | - |
|
198 | - /** |
|
199 | - * run-time caches a comment |
|
200 | - * |
|
201 | - * @param IComment $comment |
|
202 | - */ |
|
203 | - protected function cache(IComment $comment) { |
|
204 | - $id = $comment->getId(); |
|
205 | - if (empty($id)) { |
|
206 | - return; |
|
207 | - } |
|
208 | - $this->commentsCache[strval($id)] = $comment; |
|
209 | - } |
|
210 | - |
|
211 | - /** |
|
212 | - * removes an entry from the comments run time cache |
|
213 | - * |
|
214 | - * @param mixed $id the comment's id |
|
215 | - */ |
|
216 | - protected function uncache($id) { |
|
217 | - $id = strval($id); |
|
218 | - if (isset($this->commentsCache[$id])) { |
|
219 | - unset($this->commentsCache[$id]); |
|
220 | - } |
|
221 | - } |
|
222 | - |
|
223 | - /** |
|
224 | - * returns a comment instance |
|
225 | - * |
|
226 | - * @param string $id the ID of the comment |
|
227 | - * @return IComment |
|
228 | - * @throws NotFoundException |
|
229 | - * @throws \InvalidArgumentException |
|
230 | - * @since 9.0.0 |
|
231 | - */ |
|
232 | - public function get($id) { |
|
233 | - if (intval($id) === 0) { |
|
234 | - throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.'); |
|
235 | - } |
|
236 | - |
|
237 | - if (isset($this->commentsCache[$id])) { |
|
238 | - return $this->commentsCache[$id]; |
|
239 | - } |
|
240 | - |
|
241 | - $qb = $this->dbConn->getQueryBuilder(); |
|
242 | - $resultStatement = $qb->select('*') |
|
243 | - ->from('comments') |
|
244 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
245 | - ->setParameter('id', $id, IQueryBuilder::PARAM_INT) |
|
246 | - ->execute(); |
|
247 | - |
|
248 | - $data = $resultStatement->fetch(); |
|
249 | - $resultStatement->closeCursor(); |
|
250 | - if (!$data) { |
|
251 | - throw new NotFoundException(); |
|
252 | - } |
|
253 | - |
|
254 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
255 | - $this->cache($comment); |
|
256 | - return $comment; |
|
257 | - } |
|
258 | - |
|
259 | - /** |
|
260 | - * returns the comment specified by the id and all it's child comments. |
|
261 | - * At this point of time, we do only support one level depth. |
|
262 | - * |
|
263 | - * @param string $id |
|
264 | - * @param int $limit max number of entries to return, 0 returns all |
|
265 | - * @param int $offset the start entry |
|
266 | - * @return array |
|
267 | - * @since 9.0.0 |
|
268 | - * |
|
269 | - * The return array looks like this |
|
270 | - * [ |
|
271 | - * 'comment' => IComment, // root comment |
|
272 | - * 'replies' => |
|
273 | - * [ |
|
274 | - * 0 => |
|
275 | - * [ |
|
276 | - * 'comment' => IComment, |
|
277 | - * 'replies' => [] |
|
278 | - * ] |
|
279 | - * 1 => |
|
280 | - * [ |
|
281 | - * 'comment' => IComment, |
|
282 | - * 'replies'=> [] |
|
283 | - * ], |
|
284 | - * … |
|
285 | - * ] |
|
286 | - * ] |
|
287 | - */ |
|
288 | - public function getTree($id, $limit = 0, $offset = 0) { |
|
289 | - $tree = []; |
|
290 | - $tree['comment'] = $this->get($id); |
|
291 | - $tree['replies'] = []; |
|
292 | - |
|
293 | - $qb = $this->dbConn->getQueryBuilder(); |
|
294 | - $query = $qb->select('*') |
|
295 | - ->from('comments') |
|
296 | - ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id'))) |
|
297 | - ->orderBy('creation_timestamp', 'DESC') |
|
298 | - ->setParameter('id', $id); |
|
299 | - |
|
300 | - if ($limit > 0) { |
|
301 | - $query->setMaxResults($limit); |
|
302 | - } |
|
303 | - if ($offset > 0) { |
|
304 | - $query->setFirstResult($offset); |
|
305 | - } |
|
306 | - |
|
307 | - $resultStatement = $query->execute(); |
|
308 | - while ($data = $resultStatement->fetch()) { |
|
309 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
310 | - $this->cache($comment); |
|
311 | - $tree['replies'][] = [ |
|
312 | - 'comment' => $comment, |
|
313 | - 'replies' => [] |
|
314 | - ]; |
|
315 | - } |
|
316 | - $resultStatement->closeCursor(); |
|
317 | - |
|
318 | - return $tree; |
|
319 | - } |
|
320 | - |
|
321 | - /** |
|
322 | - * returns comments for a specific object (e.g. a file). |
|
323 | - * |
|
324 | - * The sort order is always newest to oldest. |
|
325 | - * |
|
326 | - * @param string $objectType the object type, e.g. 'files' |
|
327 | - * @param string $objectId the id of the object |
|
328 | - * @param int $limit optional, number of maximum comments to be returned. if |
|
329 | - * not specified, all comments are returned. |
|
330 | - * @param int $offset optional, starting point |
|
331 | - * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
332 | - * that may be returned |
|
333 | - * @return IComment[] |
|
334 | - * @since 9.0.0 |
|
335 | - */ |
|
336 | - public function getForObject( |
|
337 | - $objectType, |
|
338 | - $objectId, |
|
339 | - $limit = 0, |
|
340 | - $offset = 0, |
|
341 | - \DateTime $notOlderThan = null |
|
342 | - ) { |
|
343 | - $comments = []; |
|
344 | - |
|
345 | - $qb = $this->dbConn->getQueryBuilder(); |
|
346 | - $query = $qb->select('*') |
|
347 | - ->from('comments') |
|
348 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
349 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
350 | - ->orderBy('creation_timestamp', 'DESC') |
|
351 | - ->setParameter('type', $objectType) |
|
352 | - ->setParameter('id', $objectId); |
|
353 | - |
|
354 | - if ($limit > 0) { |
|
355 | - $query->setMaxResults($limit); |
|
356 | - } |
|
357 | - if ($offset > 0) { |
|
358 | - $query->setFirstResult($offset); |
|
359 | - } |
|
360 | - if (!is_null($notOlderThan)) { |
|
361 | - $query |
|
362 | - ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
363 | - ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
364 | - } |
|
365 | - |
|
366 | - $resultStatement = $query->execute(); |
|
367 | - while ($data = $resultStatement->fetch()) { |
|
368 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
369 | - $this->cache($comment); |
|
370 | - $comments[] = $comment; |
|
371 | - } |
|
372 | - $resultStatement->closeCursor(); |
|
373 | - |
|
374 | - return $comments; |
|
375 | - } |
|
376 | - |
|
377 | - /** |
|
378 | - * @param $objectType string the object type, e.g. 'files' |
|
379 | - * @param $objectId string the id of the object |
|
380 | - * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
381 | - * that may be returned |
|
382 | - * @return Int |
|
383 | - * @since 9.0.0 |
|
384 | - */ |
|
385 | - public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) { |
|
386 | - $qb = $this->dbConn->getQueryBuilder(); |
|
387 | - $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
388 | - ->from('comments') |
|
389 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
390 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
391 | - ->setParameter('type', $objectType) |
|
392 | - ->setParameter('id', $objectId); |
|
393 | - |
|
394 | - if (!is_null($notOlderThan)) { |
|
395 | - $query |
|
396 | - ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
397 | - ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
398 | - } |
|
399 | - |
|
400 | - $resultStatement = $query->execute(); |
|
401 | - $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
402 | - $resultStatement->closeCursor(); |
|
403 | - return intval($data[0]); |
|
404 | - } |
|
405 | - |
|
406 | - /** |
|
407 | - * Get the number of unread comments for all files in a folder |
|
408 | - * |
|
409 | - * @param int $folderId |
|
410 | - * @param IUser $user |
|
411 | - * @return array [$fileId => $unreadCount] |
|
412 | - */ |
|
413 | - public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) { |
|
414 | - $qb = $this->dbConn->getQueryBuilder(); |
|
415 | - $query = $qb->select('fileid', $qb->createFunction( |
|
416 | - 'COUNT(' . $qb->getColumnName('c.id') . ')') |
|
417 | - )->from('comments', 'c') |
|
418 | - ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX( |
|
419 | - $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')), |
|
420 | - $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)) |
|
421 | - )) |
|
422 | - ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX( |
|
423 | - $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')), |
|
424 | - $qb->expr()->eq('m.object_id', 'c.object_id'), |
|
425 | - $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())) |
|
426 | - )) |
|
427 | - ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId))) |
|
428 | - ->andWhere($qb->expr()->orX( |
|
429 | - $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'), |
|
430 | - $qb->expr()->isNull('marker_datetime') |
|
431 | - )) |
|
432 | - ->groupBy('f.fileid'); |
|
433 | - |
|
434 | - $resultStatement = $query->execute(); |
|
435 | - return array_map(function ($count) { |
|
436 | - return (int)$count; |
|
437 | - }, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR)); |
|
438 | - } |
|
439 | - |
|
440 | - /** |
|
441 | - * creates a new comment and returns it. At this point of time, it is not |
|
442 | - * saved in the used data storage. Use save() after setting other fields |
|
443 | - * of the comment (e.g. message or verb). |
|
444 | - * |
|
445 | - * @param string $actorType the actor type (e.g. 'users') |
|
446 | - * @param string $actorId a user id |
|
447 | - * @param string $objectType the object type the comment is attached to |
|
448 | - * @param string $objectId the object id the comment is attached to |
|
449 | - * @return IComment |
|
450 | - * @since 9.0.0 |
|
451 | - */ |
|
452 | - public function create($actorType, $actorId, $objectType, $objectId) { |
|
453 | - $comment = new Comment(); |
|
454 | - $comment |
|
455 | - ->setActor($actorType, $actorId) |
|
456 | - ->setObject($objectType, $objectId); |
|
457 | - return $comment; |
|
458 | - } |
|
459 | - |
|
460 | - /** |
|
461 | - * permanently deletes the comment specified by the ID |
|
462 | - * |
|
463 | - * When the comment has child comments, their parent ID will be changed to |
|
464 | - * the parent ID of the item that is to be deleted. |
|
465 | - * |
|
466 | - * @param string $id |
|
467 | - * @return bool |
|
468 | - * @throws \InvalidArgumentException |
|
469 | - * @since 9.0.0 |
|
470 | - */ |
|
471 | - public function delete($id) { |
|
472 | - if (!is_string($id)) { |
|
473 | - throw new \InvalidArgumentException('Parameter must be string'); |
|
474 | - } |
|
475 | - |
|
476 | - try { |
|
477 | - $comment = $this->get($id); |
|
478 | - } catch (\Exception $e) { |
|
479 | - // Ignore exceptions, we just don't fire a hook then |
|
480 | - $comment = null; |
|
481 | - } |
|
482 | - |
|
483 | - $qb = $this->dbConn->getQueryBuilder(); |
|
484 | - $query = $qb->delete('comments') |
|
485 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
486 | - ->setParameter('id', $id); |
|
487 | - |
|
488 | - try { |
|
489 | - $affectedRows = $query->execute(); |
|
490 | - $this->uncache($id); |
|
491 | - } catch (DriverException $e) { |
|
492 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
493 | - return false; |
|
494 | - } |
|
495 | - |
|
496 | - if ($affectedRows > 0 && $comment instanceof IComment) { |
|
497 | - $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment); |
|
498 | - } |
|
499 | - |
|
500 | - return ($affectedRows > 0); |
|
501 | - } |
|
502 | - |
|
503 | - /** |
|
504 | - * saves the comment permanently |
|
505 | - * |
|
506 | - * if the supplied comment has an empty ID, a new entry comment will be |
|
507 | - * saved and the instance updated with the new ID. |
|
508 | - * |
|
509 | - * Otherwise, an existing comment will be updated. |
|
510 | - * |
|
511 | - * Throws NotFoundException when a comment that is to be updated does not |
|
512 | - * exist anymore at this point of time. |
|
513 | - * |
|
514 | - * @param IComment $comment |
|
515 | - * @return bool |
|
516 | - * @throws NotFoundException |
|
517 | - * @since 9.0.0 |
|
518 | - */ |
|
519 | - public function save(IComment $comment) { |
|
520 | - if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') { |
|
521 | - $result = $this->insert($comment); |
|
522 | - } else { |
|
523 | - $result = $this->update($comment); |
|
524 | - } |
|
525 | - |
|
526 | - if ($result && !!$comment->getParentId()) { |
|
527 | - $this->updateChildrenInformation( |
|
528 | - $comment->getParentId(), |
|
529 | - $comment->getCreationDateTime() |
|
530 | - ); |
|
531 | - $this->cache($comment); |
|
532 | - } |
|
533 | - |
|
534 | - return $result; |
|
535 | - } |
|
536 | - |
|
537 | - /** |
|
538 | - * inserts the provided comment in the database |
|
539 | - * |
|
540 | - * @param IComment $comment |
|
541 | - * @return bool |
|
542 | - */ |
|
543 | - protected function insert(IComment &$comment) { |
|
544 | - $qb = $this->dbConn->getQueryBuilder(); |
|
545 | - $affectedRows = $qb |
|
546 | - ->insert('comments') |
|
547 | - ->values([ |
|
548 | - 'parent_id' => $qb->createNamedParameter($comment->getParentId()), |
|
549 | - 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()), |
|
550 | - 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()), |
|
551 | - 'actor_type' => $qb->createNamedParameter($comment->getActorType()), |
|
552 | - 'actor_id' => $qb->createNamedParameter($comment->getActorId()), |
|
553 | - 'message' => $qb->createNamedParameter($comment->getMessage()), |
|
554 | - 'verb' => $qb->createNamedParameter($comment->getVerb()), |
|
555 | - 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'), |
|
556 | - 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'), |
|
557 | - 'object_type' => $qb->createNamedParameter($comment->getObjectType()), |
|
558 | - 'object_id' => $qb->createNamedParameter($comment->getObjectId()), |
|
559 | - ]) |
|
560 | - ->execute(); |
|
561 | - |
|
562 | - if ($affectedRows > 0) { |
|
563 | - $comment->setId(strval($qb->getLastInsertId())); |
|
564 | - $this->sendEvent(CommentsEvent::EVENT_ADD, $comment); |
|
565 | - } |
|
566 | - |
|
567 | - return $affectedRows > 0; |
|
568 | - } |
|
569 | - |
|
570 | - /** |
|
571 | - * updates a Comment data row |
|
572 | - * |
|
573 | - * @param IComment $comment |
|
574 | - * @return bool |
|
575 | - * @throws NotFoundException |
|
576 | - */ |
|
577 | - protected function update(IComment $comment) { |
|
578 | - // for properly working preUpdate Events we need the old comments as is |
|
579 | - // in the DB and overcome caching. Also avoid that outdated information stays. |
|
580 | - $this->uncache($comment->getId()); |
|
581 | - $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId())); |
|
582 | - $this->uncache($comment->getId()); |
|
583 | - |
|
584 | - $qb = $this->dbConn->getQueryBuilder(); |
|
585 | - $affectedRows = $qb |
|
586 | - ->update('comments') |
|
587 | - ->set('parent_id', $qb->createNamedParameter($comment->getParentId())) |
|
588 | - ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId())) |
|
589 | - ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount())) |
|
590 | - ->set('actor_type', $qb->createNamedParameter($comment->getActorType())) |
|
591 | - ->set('actor_id', $qb->createNamedParameter($comment->getActorId())) |
|
592 | - ->set('message', $qb->createNamedParameter($comment->getMessage())) |
|
593 | - ->set('verb', $qb->createNamedParameter($comment->getVerb())) |
|
594 | - ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime')) |
|
595 | - ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime')) |
|
596 | - ->set('object_type', $qb->createNamedParameter($comment->getObjectType())) |
|
597 | - ->set('object_id', $qb->createNamedParameter($comment->getObjectId())) |
|
598 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
599 | - ->setParameter('id', $comment->getId()) |
|
600 | - ->execute(); |
|
601 | - |
|
602 | - if ($affectedRows === 0) { |
|
603 | - throw new NotFoundException('Comment to update does ceased to exist'); |
|
604 | - } |
|
605 | - |
|
606 | - $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment); |
|
607 | - |
|
608 | - return $affectedRows > 0; |
|
609 | - } |
|
610 | - |
|
611 | - /** |
|
612 | - * removes references to specific actor (e.g. on user delete) of a comment. |
|
613 | - * The comment itself must not get lost/deleted. |
|
614 | - * |
|
615 | - * @param string $actorType the actor type (e.g. 'users') |
|
616 | - * @param string $actorId a user id |
|
617 | - * @return boolean |
|
618 | - * @since 9.0.0 |
|
619 | - */ |
|
620 | - public function deleteReferencesOfActor($actorType, $actorId) { |
|
621 | - $this->checkRoleParameters('Actor', $actorType, $actorId); |
|
622 | - |
|
623 | - $qb = $this->dbConn->getQueryBuilder(); |
|
624 | - $affectedRows = $qb |
|
625 | - ->update('comments') |
|
626 | - ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
627 | - ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
628 | - ->where($qb->expr()->eq('actor_type', $qb->createParameter('type'))) |
|
629 | - ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id'))) |
|
630 | - ->setParameter('type', $actorType) |
|
631 | - ->setParameter('id', $actorId) |
|
632 | - ->execute(); |
|
633 | - |
|
634 | - $this->commentsCache = []; |
|
635 | - |
|
636 | - return is_int($affectedRows); |
|
637 | - } |
|
638 | - |
|
639 | - /** |
|
640 | - * deletes all comments made of a specific object (e.g. on file delete) |
|
641 | - * |
|
642 | - * @param string $objectType the object type (e.g. 'files') |
|
643 | - * @param string $objectId e.g. the file id |
|
644 | - * @return boolean |
|
645 | - * @since 9.0.0 |
|
646 | - */ |
|
647 | - public function deleteCommentsAtObject($objectType, $objectId) { |
|
648 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
649 | - |
|
650 | - $qb = $this->dbConn->getQueryBuilder(); |
|
651 | - $affectedRows = $qb |
|
652 | - ->delete('comments') |
|
653 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
654 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
655 | - ->setParameter('type', $objectType) |
|
656 | - ->setParameter('id', $objectId) |
|
657 | - ->execute(); |
|
658 | - |
|
659 | - $this->commentsCache = []; |
|
660 | - |
|
661 | - return is_int($affectedRows); |
|
662 | - } |
|
663 | - |
|
664 | - /** |
|
665 | - * deletes the read markers for the specified user |
|
666 | - * |
|
667 | - * @param \OCP\IUser $user |
|
668 | - * @return bool |
|
669 | - * @since 9.0.0 |
|
670 | - */ |
|
671 | - public function deleteReadMarksFromUser(IUser $user) { |
|
672 | - $qb = $this->dbConn->getQueryBuilder(); |
|
673 | - $query = $qb->delete('comments_read_markers') |
|
674 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
675 | - ->setParameter('user_id', $user->getUID()); |
|
676 | - |
|
677 | - try { |
|
678 | - $affectedRows = $query->execute(); |
|
679 | - } catch (DriverException $e) { |
|
680 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
681 | - return false; |
|
682 | - } |
|
683 | - return ($affectedRows > 0); |
|
684 | - } |
|
685 | - |
|
686 | - /** |
|
687 | - * sets the read marker for a given file to the specified date for the |
|
688 | - * provided user |
|
689 | - * |
|
690 | - * @param string $objectType |
|
691 | - * @param string $objectId |
|
692 | - * @param \DateTime $dateTime |
|
693 | - * @param IUser $user |
|
694 | - * @since 9.0.0 |
|
695 | - */ |
|
696 | - public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) { |
|
697 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
698 | - |
|
699 | - $qb = $this->dbConn->getQueryBuilder(); |
|
700 | - $values = [ |
|
701 | - 'user_id' => $qb->createNamedParameter($user->getUID()), |
|
702 | - 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'), |
|
703 | - 'object_type' => $qb->createNamedParameter($objectType), |
|
704 | - 'object_id' => $qb->createNamedParameter($objectId), |
|
705 | - ]; |
|
706 | - |
|
707 | - // Strategy: try to update, if this does not return affected rows, do an insert. |
|
708 | - $affectedRows = $qb |
|
709 | - ->update('comments_read_markers') |
|
710 | - ->set('user_id', $values['user_id']) |
|
711 | - ->set('marker_datetime', $values['marker_datetime']) |
|
712 | - ->set('object_type', $values['object_type']) |
|
713 | - ->set('object_id', $values['object_id']) |
|
714 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
715 | - ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
716 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
717 | - ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
718 | - ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
719 | - ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
720 | - ->execute(); |
|
721 | - |
|
722 | - if ($affectedRows > 0) { |
|
723 | - return; |
|
724 | - } |
|
725 | - |
|
726 | - $qb->insert('comments_read_markers') |
|
727 | - ->values($values) |
|
728 | - ->execute(); |
|
729 | - } |
|
730 | - |
|
731 | - /** |
|
732 | - * returns the read marker for a given file to the specified date for the |
|
733 | - * provided user. It returns null, when the marker is not present, i.e. |
|
734 | - * no comments were marked as read. |
|
735 | - * |
|
736 | - * @param string $objectType |
|
737 | - * @param string $objectId |
|
738 | - * @param IUser $user |
|
739 | - * @return \DateTime|null |
|
740 | - * @since 9.0.0 |
|
741 | - */ |
|
742 | - public function getReadMark($objectType, $objectId, IUser $user) { |
|
743 | - $qb = $this->dbConn->getQueryBuilder(); |
|
744 | - $resultStatement = $qb->select('marker_datetime') |
|
745 | - ->from('comments_read_markers') |
|
746 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
747 | - ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
748 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
749 | - ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
750 | - ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
751 | - ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
752 | - ->execute(); |
|
753 | - |
|
754 | - $data = $resultStatement->fetch(); |
|
755 | - $resultStatement->closeCursor(); |
|
756 | - if (!$data || is_null($data['marker_datetime'])) { |
|
757 | - return null; |
|
758 | - } |
|
759 | - |
|
760 | - return new \DateTime($data['marker_datetime']); |
|
761 | - } |
|
762 | - |
|
763 | - /** |
|
764 | - * deletes the read markers on the specified object |
|
765 | - * |
|
766 | - * @param string $objectType |
|
767 | - * @param string $objectId |
|
768 | - * @return bool |
|
769 | - * @since 9.0.0 |
|
770 | - */ |
|
771 | - public function deleteReadMarksOnObject($objectType, $objectId) { |
|
772 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
773 | - |
|
774 | - $qb = $this->dbConn->getQueryBuilder(); |
|
775 | - $query = $qb->delete('comments_read_markers') |
|
776 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
777 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
778 | - ->setParameter('object_type', $objectType) |
|
779 | - ->setParameter('object_id', $objectId); |
|
780 | - |
|
781 | - try { |
|
782 | - $affectedRows = $query->execute(); |
|
783 | - } catch (DriverException $e) { |
|
784 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
785 | - return false; |
|
786 | - } |
|
787 | - return ($affectedRows > 0); |
|
788 | - } |
|
789 | - |
|
790 | - /** |
|
791 | - * registers an Entity to the manager, so event notifications can be send |
|
792 | - * to consumers of the comments infrastructure |
|
793 | - * |
|
794 | - * @param \Closure $closure |
|
795 | - */ |
|
796 | - public function registerEventHandler(\Closure $closure) { |
|
797 | - $this->eventHandlerClosures[] = $closure; |
|
798 | - $this->eventHandlers = []; |
|
799 | - } |
|
800 | - |
|
801 | - /** |
|
802 | - * registers a method that resolves an ID to a display name for a given type |
|
803 | - * |
|
804 | - * @param string $type |
|
805 | - * @param \Closure $closure |
|
806 | - * @throws \OutOfBoundsException |
|
807 | - * @since 11.0.0 |
|
808 | - * |
|
809 | - * Only one resolver shall be registered per type. Otherwise a |
|
810 | - * \OutOfBoundsException has to thrown. |
|
811 | - */ |
|
812 | - public function registerDisplayNameResolver($type, \Closure $closure) { |
|
813 | - if (!is_string($type)) { |
|
814 | - throw new \InvalidArgumentException('String expected.'); |
|
815 | - } |
|
816 | - if (isset($this->displayNameResolvers[$type])) { |
|
817 | - throw new \OutOfBoundsException('Displayname resolver for this type already registered'); |
|
818 | - } |
|
819 | - $this->displayNameResolvers[$type] = $closure; |
|
820 | - } |
|
821 | - |
|
822 | - /** |
|
823 | - * resolves a given ID of a given Type to a display name. |
|
824 | - * |
|
825 | - * @param string $type |
|
826 | - * @param string $id |
|
827 | - * @return string |
|
828 | - * @throws \OutOfBoundsException |
|
829 | - * @since 11.0.0 |
|
830 | - * |
|
831 | - * If a provided type was not registered, an \OutOfBoundsException shall |
|
832 | - * be thrown. It is upon the resolver discretion what to return of the |
|
833 | - * provided ID is unknown. It must be ensured that a string is returned. |
|
834 | - */ |
|
835 | - public function resolveDisplayName($type, $id) { |
|
836 | - if (!is_string($type)) { |
|
837 | - throw new \InvalidArgumentException('String expected.'); |
|
838 | - } |
|
839 | - if (!isset($this->displayNameResolvers[$type])) { |
|
840 | - throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
|
841 | - } |
|
842 | - return (string)$this->displayNameResolvers[$type]($id); |
|
843 | - } |
|
844 | - |
|
845 | - /** |
|
846 | - * returns valid, registered entities |
|
847 | - * |
|
848 | - * @return \OCP\Comments\ICommentsEventHandler[] |
|
849 | - */ |
|
850 | - private function getEventHandlers() { |
|
851 | - if (!empty($this->eventHandlers)) { |
|
852 | - return $this->eventHandlers; |
|
853 | - } |
|
854 | - |
|
855 | - $this->eventHandlers = []; |
|
856 | - foreach ($this->eventHandlerClosures as $name => $closure) { |
|
857 | - $entity = $closure(); |
|
858 | - if (!($entity instanceof ICommentsEventHandler)) { |
|
859 | - throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface'); |
|
860 | - } |
|
861 | - $this->eventHandlers[$name] = $entity; |
|
862 | - } |
|
863 | - |
|
864 | - return $this->eventHandlers; |
|
865 | - } |
|
866 | - |
|
867 | - /** |
|
868 | - * sends notifications to the registered entities |
|
869 | - * |
|
870 | - * @param $eventType |
|
871 | - * @param IComment $comment |
|
872 | - */ |
|
873 | - private function sendEvent($eventType, IComment $comment) { |
|
874 | - $entities = $this->getEventHandlers(); |
|
875 | - $event = new CommentsEvent($eventType, $comment); |
|
876 | - foreach ($entities as $entity) { |
|
877 | - $entity->handle($event); |
|
878 | - } |
|
879 | - } |
|
42 | + /** @var IDBConnection */ |
|
43 | + protected $dbConn; |
|
44 | + |
|
45 | + /** @var ILogger */ |
|
46 | + protected $logger; |
|
47 | + |
|
48 | + /** @var IConfig */ |
|
49 | + protected $config; |
|
50 | + |
|
51 | + /** @var IComment[] */ |
|
52 | + protected $commentsCache = []; |
|
53 | + |
|
54 | + /** @var \Closure[] */ |
|
55 | + protected $eventHandlerClosures = []; |
|
56 | + |
|
57 | + /** @var ICommentsEventHandler[] */ |
|
58 | + protected $eventHandlers = []; |
|
59 | + |
|
60 | + /** @var \Closure[] */ |
|
61 | + protected $displayNameResolvers = []; |
|
62 | + |
|
63 | + /** |
|
64 | + * Manager constructor. |
|
65 | + * |
|
66 | + * @param IDBConnection $dbConn |
|
67 | + * @param ILogger $logger |
|
68 | + * @param IConfig $config |
|
69 | + */ |
|
70 | + public function __construct( |
|
71 | + IDBConnection $dbConn, |
|
72 | + ILogger $logger, |
|
73 | + IConfig $config |
|
74 | + ) { |
|
75 | + $this->dbConn = $dbConn; |
|
76 | + $this->logger = $logger; |
|
77 | + $this->config = $config; |
|
78 | + } |
|
79 | + |
|
80 | + /** |
|
81 | + * converts data base data into PHP native, proper types as defined by |
|
82 | + * IComment interface. |
|
83 | + * |
|
84 | + * @param array $data |
|
85 | + * @return array |
|
86 | + */ |
|
87 | + protected function normalizeDatabaseData(array $data) { |
|
88 | + $data['id'] = strval($data['id']); |
|
89 | + $data['parent_id'] = strval($data['parent_id']); |
|
90 | + $data['topmost_parent_id'] = strval($data['topmost_parent_id']); |
|
91 | + $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']); |
|
92 | + if (!is_null($data['latest_child_timestamp'])) { |
|
93 | + $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']); |
|
94 | + } |
|
95 | + $data['children_count'] = intval($data['children_count']); |
|
96 | + return $data; |
|
97 | + } |
|
98 | + |
|
99 | + /** |
|
100 | + * prepares a comment for an insert or update operation after making sure |
|
101 | + * all necessary fields have a value assigned. |
|
102 | + * |
|
103 | + * @param IComment $comment |
|
104 | + * @return IComment returns the same updated IComment instance as provided |
|
105 | + * by parameter for convenience |
|
106 | + * @throws \UnexpectedValueException |
|
107 | + */ |
|
108 | + protected function prepareCommentForDatabaseWrite(IComment $comment) { |
|
109 | + if (!$comment->getActorType() |
|
110 | + || !$comment->getActorId() |
|
111 | + || !$comment->getObjectType() |
|
112 | + || !$comment->getObjectId() |
|
113 | + || !$comment->getVerb() |
|
114 | + ) { |
|
115 | + throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving'); |
|
116 | + } |
|
117 | + |
|
118 | + if ($comment->getId() === '') { |
|
119 | + $comment->setChildrenCount(0); |
|
120 | + $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC'))); |
|
121 | + $comment->setLatestChildDateTime(null); |
|
122 | + } |
|
123 | + |
|
124 | + if (is_null($comment->getCreationDateTime())) { |
|
125 | + $comment->setCreationDateTime(new \DateTime()); |
|
126 | + } |
|
127 | + |
|
128 | + if ($comment->getParentId() !== '0') { |
|
129 | + $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId())); |
|
130 | + } else { |
|
131 | + $comment->setTopmostParentId('0'); |
|
132 | + } |
|
133 | + |
|
134 | + $this->cache($comment); |
|
135 | + |
|
136 | + return $comment; |
|
137 | + } |
|
138 | + |
|
139 | + /** |
|
140 | + * returns the topmost parent id of a given comment identified by ID |
|
141 | + * |
|
142 | + * @param string $id |
|
143 | + * @return string |
|
144 | + * @throws NotFoundException |
|
145 | + */ |
|
146 | + protected function determineTopmostParentId($id) { |
|
147 | + $comment = $this->get($id); |
|
148 | + if ($comment->getParentId() === '0') { |
|
149 | + return $comment->getId(); |
|
150 | + } else { |
|
151 | + return $this->determineTopmostParentId($comment->getId()); |
|
152 | + } |
|
153 | + } |
|
154 | + |
|
155 | + /** |
|
156 | + * updates child information of a comment |
|
157 | + * |
|
158 | + * @param string $id |
|
159 | + * @param \DateTime $cDateTime the date time of the most recent child |
|
160 | + * @throws NotFoundException |
|
161 | + */ |
|
162 | + protected function updateChildrenInformation($id, \DateTime $cDateTime) { |
|
163 | + $qb = $this->dbConn->getQueryBuilder(); |
|
164 | + $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
165 | + ->from('comments') |
|
166 | + ->where($qb->expr()->eq('parent_id', $qb->createParameter('id'))) |
|
167 | + ->setParameter('id', $id); |
|
168 | + |
|
169 | + $resultStatement = $query->execute(); |
|
170 | + $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
171 | + $resultStatement->closeCursor(); |
|
172 | + $children = intval($data[0]); |
|
173 | + |
|
174 | + $comment = $this->get($id); |
|
175 | + $comment->setChildrenCount($children); |
|
176 | + $comment->setLatestChildDateTime($cDateTime); |
|
177 | + $this->save($comment); |
|
178 | + } |
|
179 | + |
|
180 | + /** |
|
181 | + * Tests whether actor or object type and id parameters are acceptable. |
|
182 | + * Throws exception if not. |
|
183 | + * |
|
184 | + * @param string $role |
|
185 | + * @param string $type |
|
186 | + * @param string $id |
|
187 | + * @throws \InvalidArgumentException |
|
188 | + */ |
|
189 | + protected function checkRoleParameters($role, $type, $id) { |
|
190 | + if ( |
|
191 | + !is_string($type) || empty($type) |
|
192 | + || !is_string($id) || empty($id) |
|
193 | + ) { |
|
194 | + throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
195 | + } |
|
196 | + } |
|
197 | + |
|
198 | + /** |
|
199 | + * run-time caches a comment |
|
200 | + * |
|
201 | + * @param IComment $comment |
|
202 | + */ |
|
203 | + protected function cache(IComment $comment) { |
|
204 | + $id = $comment->getId(); |
|
205 | + if (empty($id)) { |
|
206 | + return; |
|
207 | + } |
|
208 | + $this->commentsCache[strval($id)] = $comment; |
|
209 | + } |
|
210 | + |
|
211 | + /** |
|
212 | + * removes an entry from the comments run time cache |
|
213 | + * |
|
214 | + * @param mixed $id the comment's id |
|
215 | + */ |
|
216 | + protected function uncache($id) { |
|
217 | + $id = strval($id); |
|
218 | + if (isset($this->commentsCache[$id])) { |
|
219 | + unset($this->commentsCache[$id]); |
|
220 | + } |
|
221 | + } |
|
222 | + |
|
223 | + /** |
|
224 | + * returns a comment instance |
|
225 | + * |
|
226 | + * @param string $id the ID of the comment |
|
227 | + * @return IComment |
|
228 | + * @throws NotFoundException |
|
229 | + * @throws \InvalidArgumentException |
|
230 | + * @since 9.0.0 |
|
231 | + */ |
|
232 | + public function get($id) { |
|
233 | + if (intval($id) === 0) { |
|
234 | + throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.'); |
|
235 | + } |
|
236 | + |
|
237 | + if (isset($this->commentsCache[$id])) { |
|
238 | + return $this->commentsCache[$id]; |
|
239 | + } |
|
240 | + |
|
241 | + $qb = $this->dbConn->getQueryBuilder(); |
|
242 | + $resultStatement = $qb->select('*') |
|
243 | + ->from('comments') |
|
244 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
245 | + ->setParameter('id', $id, IQueryBuilder::PARAM_INT) |
|
246 | + ->execute(); |
|
247 | + |
|
248 | + $data = $resultStatement->fetch(); |
|
249 | + $resultStatement->closeCursor(); |
|
250 | + if (!$data) { |
|
251 | + throw new NotFoundException(); |
|
252 | + } |
|
253 | + |
|
254 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
255 | + $this->cache($comment); |
|
256 | + return $comment; |
|
257 | + } |
|
258 | + |
|
259 | + /** |
|
260 | + * returns the comment specified by the id and all it's child comments. |
|
261 | + * At this point of time, we do only support one level depth. |
|
262 | + * |
|
263 | + * @param string $id |
|
264 | + * @param int $limit max number of entries to return, 0 returns all |
|
265 | + * @param int $offset the start entry |
|
266 | + * @return array |
|
267 | + * @since 9.0.0 |
|
268 | + * |
|
269 | + * The return array looks like this |
|
270 | + * [ |
|
271 | + * 'comment' => IComment, // root comment |
|
272 | + * 'replies' => |
|
273 | + * [ |
|
274 | + * 0 => |
|
275 | + * [ |
|
276 | + * 'comment' => IComment, |
|
277 | + * 'replies' => [] |
|
278 | + * ] |
|
279 | + * 1 => |
|
280 | + * [ |
|
281 | + * 'comment' => IComment, |
|
282 | + * 'replies'=> [] |
|
283 | + * ], |
|
284 | + * … |
|
285 | + * ] |
|
286 | + * ] |
|
287 | + */ |
|
288 | + public function getTree($id, $limit = 0, $offset = 0) { |
|
289 | + $tree = []; |
|
290 | + $tree['comment'] = $this->get($id); |
|
291 | + $tree['replies'] = []; |
|
292 | + |
|
293 | + $qb = $this->dbConn->getQueryBuilder(); |
|
294 | + $query = $qb->select('*') |
|
295 | + ->from('comments') |
|
296 | + ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id'))) |
|
297 | + ->orderBy('creation_timestamp', 'DESC') |
|
298 | + ->setParameter('id', $id); |
|
299 | + |
|
300 | + if ($limit > 0) { |
|
301 | + $query->setMaxResults($limit); |
|
302 | + } |
|
303 | + if ($offset > 0) { |
|
304 | + $query->setFirstResult($offset); |
|
305 | + } |
|
306 | + |
|
307 | + $resultStatement = $query->execute(); |
|
308 | + while ($data = $resultStatement->fetch()) { |
|
309 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
310 | + $this->cache($comment); |
|
311 | + $tree['replies'][] = [ |
|
312 | + 'comment' => $comment, |
|
313 | + 'replies' => [] |
|
314 | + ]; |
|
315 | + } |
|
316 | + $resultStatement->closeCursor(); |
|
317 | + |
|
318 | + return $tree; |
|
319 | + } |
|
320 | + |
|
321 | + /** |
|
322 | + * returns comments for a specific object (e.g. a file). |
|
323 | + * |
|
324 | + * The sort order is always newest to oldest. |
|
325 | + * |
|
326 | + * @param string $objectType the object type, e.g. 'files' |
|
327 | + * @param string $objectId the id of the object |
|
328 | + * @param int $limit optional, number of maximum comments to be returned. if |
|
329 | + * not specified, all comments are returned. |
|
330 | + * @param int $offset optional, starting point |
|
331 | + * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
332 | + * that may be returned |
|
333 | + * @return IComment[] |
|
334 | + * @since 9.0.0 |
|
335 | + */ |
|
336 | + public function getForObject( |
|
337 | + $objectType, |
|
338 | + $objectId, |
|
339 | + $limit = 0, |
|
340 | + $offset = 0, |
|
341 | + \DateTime $notOlderThan = null |
|
342 | + ) { |
|
343 | + $comments = []; |
|
344 | + |
|
345 | + $qb = $this->dbConn->getQueryBuilder(); |
|
346 | + $query = $qb->select('*') |
|
347 | + ->from('comments') |
|
348 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
349 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
350 | + ->orderBy('creation_timestamp', 'DESC') |
|
351 | + ->setParameter('type', $objectType) |
|
352 | + ->setParameter('id', $objectId); |
|
353 | + |
|
354 | + if ($limit > 0) { |
|
355 | + $query->setMaxResults($limit); |
|
356 | + } |
|
357 | + if ($offset > 0) { |
|
358 | + $query->setFirstResult($offset); |
|
359 | + } |
|
360 | + if (!is_null($notOlderThan)) { |
|
361 | + $query |
|
362 | + ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
363 | + ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
364 | + } |
|
365 | + |
|
366 | + $resultStatement = $query->execute(); |
|
367 | + while ($data = $resultStatement->fetch()) { |
|
368 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
369 | + $this->cache($comment); |
|
370 | + $comments[] = $comment; |
|
371 | + } |
|
372 | + $resultStatement->closeCursor(); |
|
373 | + |
|
374 | + return $comments; |
|
375 | + } |
|
376 | + |
|
377 | + /** |
|
378 | + * @param $objectType string the object type, e.g. 'files' |
|
379 | + * @param $objectId string the id of the object |
|
380 | + * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
381 | + * that may be returned |
|
382 | + * @return Int |
|
383 | + * @since 9.0.0 |
|
384 | + */ |
|
385 | + public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) { |
|
386 | + $qb = $this->dbConn->getQueryBuilder(); |
|
387 | + $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
388 | + ->from('comments') |
|
389 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
390 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
391 | + ->setParameter('type', $objectType) |
|
392 | + ->setParameter('id', $objectId); |
|
393 | + |
|
394 | + if (!is_null($notOlderThan)) { |
|
395 | + $query |
|
396 | + ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
397 | + ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
398 | + } |
|
399 | + |
|
400 | + $resultStatement = $query->execute(); |
|
401 | + $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
402 | + $resultStatement->closeCursor(); |
|
403 | + return intval($data[0]); |
|
404 | + } |
|
405 | + |
|
406 | + /** |
|
407 | + * Get the number of unread comments for all files in a folder |
|
408 | + * |
|
409 | + * @param int $folderId |
|
410 | + * @param IUser $user |
|
411 | + * @return array [$fileId => $unreadCount] |
|
412 | + */ |
|
413 | + public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) { |
|
414 | + $qb = $this->dbConn->getQueryBuilder(); |
|
415 | + $query = $qb->select('fileid', $qb->createFunction( |
|
416 | + 'COUNT(' . $qb->getColumnName('c.id') . ')') |
|
417 | + )->from('comments', 'c') |
|
418 | + ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX( |
|
419 | + $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')), |
|
420 | + $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)) |
|
421 | + )) |
|
422 | + ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX( |
|
423 | + $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')), |
|
424 | + $qb->expr()->eq('m.object_id', 'c.object_id'), |
|
425 | + $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())) |
|
426 | + )) |
|
427 | + ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId))) |
|
428 | + ->andWhere($qb->expr()->orX( |
|
429 | + $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'), |
|
430 | + $qb->expr()->isNull('marker_datetime') |
|
431 | + )) |
|
432 | + ->groupBy('f.fileid'); |
|
433 | + |
|
434 | + $resultStatement = $query->execute(); |
|
435 | + return array_map(function ($count) { |
|
436 | + return (int)$count; |
|
437 | + }, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR)); |
|
438 | + } |
|
439 | + |
|
440 | + /** |
|
441 | + * creates a new comment and returns it. At this point of time, it is not |
|
442 | + * saved in the used data storage. Use save() after setting other fields |
|
443 | + * of the comment (e.g. message or verb). |
|
444 | + * |
|
445 | + * @param string $actorType the actor type (e.g. 'users') |
|
446 | + * @param string $actorId a user id |
|
447 | + * @param string $objectType the object type the comment is attached to |
|
448 | + * @param string $objectId the object id the comment is attached to |
|
449 | + * @return IComment |
|
450 | + * @since 9.0.0 |
|
451 | + */ |
|
452 | + public function create($actorType, $actorId, $objectType, $objectId) { |
|
453 | + $comment = new Comment(); |
|
454 | + $comment |
|
455 | + ->setActor($actorType, $actorId) |
|
456 | + ->setObject($objectType, $objectId); |
|
457 | + return $comment; |
|
458 | + } |
|
459 | + |
|
460 | + /** |
|
461 | + * permanently deletes the comment specified by the ID |
|
462 | + * |
|
463 | + * When the comment has child comments, their parent ID will be changed to |
|
464 | + * the parent ID of the item that is to be deleted. |
|
465 | + * |
|
466 | + * @param string $id |
|
467 | + * @return bool |
|
468 | + * @throws \InvalidArgumentException |
|
469 | + * @since 9.0.0 |
|
470 | + */ |
|
471 | + public function delete($id) { |
|
472 | + if (!is_string($id)) { |
|
473 | + throw new \InvalidArgumentException('Parameter must be string'); |
|
474 | + } |
|
475 | + |
|
476 | + try { |
|
477 | + $comment = $this->get($id); |
|
478 | + } catch (\Exception $e) { |
|
479 | + // Ignore exceptions, we just don't fire a hook then |
|
480 | + $comment = null; |
|
481 | + } |
|
482 | + |
|
483 | + $qb = $this->dbConn->getQueryBuilder(); |
|
484 | + $query = $qb->delete('comments') |
|
485 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
486 | + ->setParameter('id', $id); |
|
487 | + |
|
488 | + try { |
|
489 | + $affectedRows = $query->execute(); |
|
490 | + $this->uncache($id); |
|
491 | + } catch (DriverException $e) { |
|
492 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
493 | + return false; |
|
494 | + } |
|
495 | + |
|
496 | + if ($affectedRows > 0 && $comment instanceof IComment) { |
|
497 | + $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment); |
|
498 | + } |
|
499 | + |
|
500 | + return ($affectedRows > 0); |
|
501 | + } |
|
502 | + |
|
503 | + /** |
|
504 | + * saves the comment permanently |
|
505 | + * |
|
506 | + * if the supplied comment has an empty ID, a new entry comment will be |
|
507 | + * saved and the instance updated with the new ID. |
|
508 | + * |
|
509 | + * Otherwise, an existing comment will be updated. |
|
510 | + * |
|
511 | + * Throws NotFoundException when a comment that is to be updated does not |
|
512 | + * exist anymore at this point of time. |
|
513 | + * |
|
514 | + * @param IComment $comment |
|
515 | + * @return bool |
|
516 | + * @throws NotFoundException |
|
517 | + * @since 9.0.0 |
|
518 | + */ |
|
519 | + public function save(IComment $comment) { |
|
520 | + if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') { |
|
521 | + $result = $this->insert($comment); |
|
522 | + } else { |
|
523 | + $result = $this->update($comment); |
|
524 | + } |
|
525 | + |
|
526 | + if ($result && !!$comment->getParentId()) { |
|
527 | + $this->updateChildrenInformation( |
|
528 | + $comment->getParentId(), |
|
529 | + $comment->getCreationDateTime() |
|
530 | + ); |
|
531 | + $this->cache($comment); |
|
532 | + } |
|
533 | + |
|
534 | + return $result; |
|
535 | + } |
|
536 | + |
|
537 | + /** |
|
538 | + * inserts the provided comment in the database |
|
539 | + * |
|
540 | + * @param IComment $comment |
|
541 | + * @return bool |
|
542 | + */ |
|
543 | + protected function insert(IComment &$comment) { |
|
544 | + $qb = $this->dbConn->getQueryBuilder(); |
|
545 | + $affectedRows = $qb |
|
546 | + ->insert('comments') |
|
547 | + ->values([ |
|
548 | + 'parent_id' => $qb->createNamedParameter($comment->getParentId()), |
|
549 | + 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()), |
|
550 | + 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()), |
|
551 | + 'actor_type' => $qb->createNamedParameter($comment->getActorType()), |
|
552 | + 'actor_id' => $qb->createNamedParameter($comment->getActorId()), |
|
553 | + 'message' => $qb->createNamedParameter($comment->getMessage()), |
|
554 | + 'verb' => $qb->createNamedParameter($comment->getVerb()), |
|
555 | + 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'), |
|
556 | + 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'), |
|
557 | + 'object_type' => $qb->createNamedParameter($comment->getObjectType()), |
|
558 | + 'object_id' => $qb->createNamedParameter($comment->getObjectId()), |
|
559 | + ]) |
|
560 | + ->execute(); |
|
561 | + |
|
562 | + if ($affectedRows > 0) { |
|
563 | + $comment->setId(strval($qb->getLastInsertId())); |
|
564 | + $this->sendEvent(CommentsEvent::EVENT_ADD, $comment); |
|
565 | + } |
|
566 | + |
|
567 | + return $affectedRows > 0; |
|
568 | + } |
|
569 | + |
|
570 | + /** |
|
571 | + * updates a Comment data row |
|
572 | + * |
|
573 | + * @param IComment $comment |
|
574 | + * @return bool |
|
575 | + * @throws NotFoundException |
|
576 | + */ |
|
577 | + protected function update(IComment $comment) { |
|
578 | + // for properly working preUpdate Events we need the old comments as is |
|
579 | + // in the DB and overcome caching. Also avoid that outdated information stays. |
|
580 | + $this->uncache($comment->getId()); |
|
581 | + $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId())); |
|
582 | + $this->uncache($comment->getId()); |
|
583 | + |
|
584 | + $qb = $this->dbConn->getQueryBuilder(); |
|
585 | + $affectedRows = $qb |
|
586 | + ->update('comments') |
|
587 | + ->set('parent_id', $qb->createNamedParameter($comment->getParentId())) |
|
588 | + ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId())) |
|
589 | + ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount())) |
|
590 | + ->set('actor_type', $qb->createNamedParameter($comment->getActorType())) |
|
591 | + ->set('actor_id', $qb->createNamedParameter($comment->getActorId())) |
|
592 | + ->set('message', $qb->createNamedParameter($comment->getMessage())) |
|
593 | + ->set('verb', $qb->createNamedParameter($comment->getVerb())) |
|
594 | + ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime')) |
|
595 | + ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime')) |
|
596 | + ->set('object_type', $qb->createNamedParameter($comment->getObjectType())) |
|
597 | + ->set('object_id', $qb->createNamedParameter($comment->getObjectId())) |
|
598 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
599 | + ->setParameter('id', $comment->getId()) |
|
600 | + ->execute(); |
|
601 | + |
|
602 | + if ($affectedRows === 0) { |
|
603 | + throw new NotFoundException('Comment to update does ceased to exist'); |
|
604 | + } |
|
605 | + |
|
606 | + $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment); |
|
607 | + |
|
608 | + return $affectedRows > 0; |
|
609 | + } |
|
610 | + |
|
611 | + /** |
|
612 | + * removes references to specific actor (e.g. on user delete) of a comment. |
|
613 | + * The comment itself must not get lost/deleted. |
|
614 | + * |
|
615 | + * @param string $actorType the actor type (e.g. 'users') |
|
616 | + * @param string $actorId a user id |
|
617 | + * @return boolean |
|
618 | + * @since 9.0.0 |
|
619 | + */ |
|
620 | + public function deleteReferencesOfActor($actorType, $actorId) { |
|
621 | + $this->checkRoleParameters('Actor', $actorType, $actorId); |
|
622 | + |
|
623 | + $qb = $this->dbConn->getQueryBuilder(); |
|
624 | + $affectedRows = $qb |
|
625 | + ->update('comments') |
|
626 | + ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
627 | + ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
628 | + ->where($qb->expr()->eq('actor_type', $qb->createParameter('type'))) |
|
629 | + ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id'))) |
|
630 | + ->setParameter('type', $actorType) |
|
631 | + ->setParameter('id', $actorId) |
|
632 | + ->execute(); |
|
633 | + |
|
634 | + $this->commentsCache = []; |
|
635 | + |
|
636 | + return is_int($affectedRows); |
|
637 | + } |
|
638 | + |
|
639 | + /** |
|
640 | + * deletes all comments made of a specific object (e.g. on file delete) |
|
641 | + * |
|
642 | + * @param string $objectType the object type (e.g. 'files') |
|
643 | + * @param string $objectId e.g. the file id |
|
644 | + * @return boolean |
|
645 | + * @since 9.0.0 |
|
646 | + */ |
|
647 | + public function deleteCommentsAtObject($objectType, $objectId) { |
|
648 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
649 | + |
|
650 | + $qb = $this->dbConn->getQueryBuilder(); |
|
651 | + $affectedRows = $qb |
|
652 | + ->delete('comments') |
|
653 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
654 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
655 | + ->setParameter('type', $objectType) |
|
656 | + ->setParameter('id', $objectId) |
|
657 | + ->execute(); |
|
658 | + |
|
659 | + $this->commentsCache = []; |
|
660 | + |
|
661 | + return is_int($affectedRows); |
|
662 | + } |
|
663 | + |
|
664 | + /** |
|
665 | + * deletes the read markers for the specified user |
|
666 | + * |
|
667 | + * @param \OCP\IUser $user |
|
668 | + * @return bool |
|
669 | + * @since 9.0.0 |
|
670 | + */ |
|
671 | + public function deleteReadMarksFromUser(IUser $user) { |
|
672 | + $qb = $this->dbConn->getQueryBuilder(); |
|
673 | + $query = $qb->delete('comments_read_markers') |
|
674 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
675 | + ->setParameter('user_id', $user->getUID()); |
|
676 | + |
|
677 | + try { |
|
678 | + $affectedRows = $query->execute(); |
|
679 | + } catch (DriverException $e) { |
|
680 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
681 | + return false; |
|
682 | + } |
|
683 | + return ($affectedRows > 0); |
|
684 | + } |
|
685 | + |
|
686 | + /** |
|
687 | + * sets the read marker for a given file to the specified date for the |
|
688 | + * provided user |
|
689 | + * |
|
690 | + * @param string $objectType |
|
691 | + * @param string $objectId |
|
692 | + * @param \DateTime $dateTime |
|
693 | + * @param IUser $user |
|
694 | + * @since 9.0.0 |
|
695 | + */ |
|
696 | + public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) { |
|
697 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
698 | + |
|
699 | + $qb = $this->dbConn->getQueryBuilder(); |
|
700 | + $values = [ |
|
701 | + 'user_id' => $qb->createNamedParameter($user->getUID()), |
|
702 | + 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'), |
|
703 | + 'object_type' => $qb->createNamedParameter($objectType), |
|
704 | + 'object_id' => $qb->createNamedParameter($objectId), |
|
705 | + ]; |
|
706 | + |
|
707 | + // Strategy: try to update, if this does not return affected rows, do an insert. |
|
708 | + $affectedRows = $qb |
|
709 | + ->update('comments_read_markers') |
|
710 | + ->set('user_id', $values['user_id']) |
|
711 | + ->set('marker_datetime', $values['marker_datetime']) |
|
712 | + ->set('object_type', $values['object_type']) |
|
713 | + ->set('object_id', $values['object_id']) |
|
714 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
715 | + ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
716 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
717 | + ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
718 | + ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
719 | + ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
720 | + ->execute(); |
|
721 | + |
|
722 | + if ($affectedRows > 0) { |
|
723 | + return; |
|
724 | + } |
|
725 | + |
|
726 | + $qb->insert('comments_read_markers') |
|
727 | + ->values($values) |
|
728 | + ->execute(); |
|
729 | + } |
|
730 | + |
|
731 | + /** |
|
732 | + * returns the read marker for a given file to the specified date for the |
|
733 | + * provided user. It returns null, when the marker is not present, i.e. |
|
734 | + * no comments were marked as read. |
|
735 | + * |
|
736 | + * @param string $objectType |
|
737 | + * @param string $objectId |
|
738 | + * @param IUser $user |
|
739 | + * @return \DateTime|null |
|
740 | + * @since 9.0.0 |
|
741 | + */ |
|
742 | + public function getReadMark($objectType, $objectId, IUser $user) { |
|
743 | + $qb = $this->dbConn->getQueryBuilder(); |
|
744 | + $resultStatement = $qb->select('marker_datetime') |
|
745 | + ->from('comments_read_markers') |
|
746 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
747 | + ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
748 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
749 | + ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
750 | + ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
751 | + ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
752 | + ->execute(); |
|
753 | + |
|
754 | + $data = $resultStatement->fetch(); |
|
755 | + $resultStatement->closeCursor(); |
|
756 | + if (!$data || is_null($data['marker_datetime'])) { |
|
757 | + return null; |
|
758 | + } |
|
759 | + |
|
760 | + return new \DateTime($data['marker_datetime']); |
|
761 | + } |
|
762 | + |
|
763 | + /** |
|
764 | + * deletes the read markers on the specified object |
|
765 | + * |
|
766 | + * @param string $objectType |
|
767 | + * @param string $objectId |
|
768 | + * @return bool |
|
769 | + * @since 9.0.0 |
|
770 | + */ |
|
771 | + public function deleteReadMarksOnObject($objectType, $objectId) { |
|
772 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
773 | + |
|
774 | + $qb = $this->dbConn->getQueryBuilder(); |
|
775 | + $query = $qb->delete('comments_read_markers') |
|
776 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
777 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
778 | + ->setParameter('object_type', $objectType) |
|
779 | + ->setParameter('object_id', $objectId); |
|
780 | + |
|
781 | + try { |
|
782 | + $affectedRows = $query->execute(); |
|
783 | + } catch (DriverException $e) { |
|
784 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
785 | + return false; |
|
786 | + } |
|
787 | + return ($affectedRows > 0); |
|
788 | + } |
|
789 | + |
|
790 | + /** |
|
791 | + * registers an Entity to the manager, so event notifications can be send |
|
792 | + * to consumers of the comments infrastructure |
|
793 | + * |
|
794 | + * @param \Closure $closure |
|
795 | + */ |
|
796 | + public function registerEventHandler(\Closure $closure) { |
|
797 | + $this->eventHandlerClosures[] = $closure; |
|
798 | + $this->eventHandlers = []; |
|
799 | + } |
|
800 | + |
|
801 | + /** |
|
802 | + * registers a method that resolves an ID to a display name for a given type |
|
803 | + * |
|
804 | + * @param string $type |
|
805 | + * @param \Closure $closure |
|
806 | + * @throws \OutOfBoundsException |
|
807 | + * @since 11.0.0 |
|
808 | + * |
|
809 | + * Only one resolver shall be registered per type. Otherwise a |
|
810 | + * \OutOfBoundsException has to thrown. |
|
811 | + */ |
|
812 | + public function registerDisplayNameResolver($type, \Closure $closure) { |
|
813 | + if (!is_string($type)) { |
|
814 | + throw new \InvalidArgumentException('String expected.'); |
|
815 | + } |
|
816 | + if (isset($this->displayNameResolvers[$type])) { |
|
817 | + throw new \OutOfBoundsException('Displayname resolver for this type already registered'); |
|
818 | + } |
|
819 | + $this->displayNameResolvers[$type] = $closure; |
|
820 | + } |
|
821 | + |
|
822 | + /** |
|
823 | + * resolves a given ID of a given Type to a display name. |
|
824 | + * |
|
825 | + * @param string $type |
|
826 | + * @param string $id |
|
827 | + * @return string |
|
828 | + * @throws \OutOfBoundsException |
|
829 | + * @since 11.0.0 |
|
830 | + * |
|
831 | + * If a provided type was not registered, an \OutOfBoundsException shall |
|
832 | + * be thrown. It is upon the resolver discretion what to return of the |
|
833 | + * provided ID is unknown. It must be ensured that a string is returned. |
|
834 | + */ |
|
835 | + public function resolveDisplayName($type, $id) { |
|
836 | + if (!is_string($type)) { |
|
837 | + throw new \InvalidArgumentException('String expected.'); |
|
838 | + } |
|
839 | + if (!isset($this->displayNameResolvers[$type])) { |
|
840 | + throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
|
841 | + } |
|
842 | + return (string)$this->displayNameResolvers[$type]($id); |
|
843 | + } |
|
844 | + |
|
845 | + /** |
|
846 | + * returns valid, registered entities |
|
847 | + * |
|
848 | + * @return \OCP\Comments\ICommentsEventHandler[] |
|
849 | + */ |
|
850 | + private function getEventHandlers() { |
|
851 | + if (!empty($this->eventHandlers)) { |
|
852 | + return $this->eventHandlers; |
|
853 | + } |
|
854 | + |
|
855 | + $this->eventHandlers = []; |
|
856 | + foreach ($this->eventHandlerClosures as $name => $closure) { |
|
857 | + $entity = $closure(); |
|
858 | + if (!($entity instanceof ICommentsEventHandler)) { |
|
859 | + throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface'); |
|
860 | + } |
|
861 | + $this->eventHandlers[$name] = $entity; |
|
862 | + } |
|
863 | + |
|
864 | + return $this->eventHandlers; |
|
865 | + } |
|
866 | + |
|
867 | + /** |
|
868 | + * sends notifications to the registered entities |
|
869 | + * |
|
870 | + * @param $eventType |
|
871 | + * @param IComment $comment |
|
872 | + */ |
|
873 | + private function sendEvent($eventType, IComment $comment) { |
|
874 | + $entities = $this->getEventHandlers(); |
|
875 | + $event = new CommentsEvent($eventType, $comment); |
|
876 | + foreach ($entities as $entity) { |
|
877 | + $entity->handle($event); |
|
878 | + } |
|
879 | + } |
|
880 | 880 | } |
@@ -191,7 +191,7 @@ discard block |
||
191 | 191 | !is_string($type) || empty($type) |
192 | 192 | || !is_string($id) || empty($id) |
193 | 193 | ) { |
194 | - throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
194 | + throw new \InvalidArgumentException($role.' parameters must be string and not empty'); |
|
195 | 195 | } |
196 | 196 | } |
197 | 197 | |
@@ -413,7 +413,7 @@ discard block |
||
413 | 413 | public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) { |
414 | 414 | $qb = $this->dbConn->getQueryBuilder(); |
415 | 415 | $query = $qb->select('fileid', $qb->createFunction( |
416 | - 'COUNT(' . $qb->getColumnName('c.id') . ')') |
|
416 | + 'COUNT('.$qb->getColumnName('c.id').')') |
|
417 | 417 | )->from('comments', 'c') |
418 | 418 | ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX( |
419 | 419 | $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')), |
@@ -432,8 +432,8 @@ discard block |
||
432 | 432 | ->groupBy('f.fileid'); |
433 | 433 | |
434 | 434 | $resultStatement = $query->execute(); |
435 | - return array_map(function ($count) { |
|
436 | - return (int)$count; |
|
435 | + return array_map(function($count) { |
|
436 | + return (int) $count; |
|
437 | 437 | }, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR)); |
438 | 438 | } |
439 | 439 | |
@@ -540,7 +540,7 @@ discard block |
||
540 | 540 | * @param IComment $comment |
541 | 541 | * @return bool |
542 | 542 | */ |
543 | - protected function insert(IComment &$comment) { |
|
543 | + protected function insert(IComment & $comment) { |
|
544 | 544 | $qb = $this->dbConn->getQueryBuilder(); |
545 | 545 | $affectedRows = $qb |
546 | 546 | ->insert('comments') |
@@ -839,7 +839,7 @@ discard block |
||
839 | 839 | if (!isset($this->displayNameResolvers[$type])) { |
840 | 840 | throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
841 | 841 | } |
842 | - return (string)$this->displayNameResolvers[$type]($id); |
|
842 | + return (string) $this->displayNameResolvers[$type]($id); |
|
843 | 843 | } |
844 | 844 | |
845 | 845 | /** |
@@ -173,7 +173,7 @@ discard block |
||
173 | 173 | * If an SQLLogger is configured, the execution is logged. |
174 | 174 | * |
175 | 175 | * @param string $query The SQL query to execute. |
176 | - * @param array $params The parameters to bind to the query, if any. |
|
176 | + * @param string[] $params The parameters to bind to the query, if any. |
|
177 | 177 | * @param array $types The types the previous parameters are in. |
178 | 178 | * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional. |
179 | 179 | * |
@@ -218,7 +218,7 @@ discard block |
||
218 | 218 | * columns or sequences. |
219 | 219 | * |
220 | 220 | * @param string $seqName Name of the sequence object from which the ID should be returned. |
221 | - * @return string A string representation of the last inserted ID. |
|
221 | + * @return integer A string representation of the last inserted ID. |
|
222 | 222 | */ |
223 | 223 | public function lastInsertId($seqName = null) { |
224 | 224 | if ($seqName) { |
@@ -56,7 +56,7 @@ discard block |
||
56 | 56 | return parent::connect(); |
57 | 57 | } catch (DBALException $e) { |
58 | 58 | // throw a new exception to prevent leaking info from the stacktrace |
59 | - throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
|
59 | + throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode()); |
|
60 | 60 | } |
61 | 61 | } |
62 | 62 | |
@@ -104,7 +104,7 @@ discard block |
||
104 | 104 | // 0 is the method where we use `getCallerBacktrace` |
105 | 105 | // 1 is the target method which uses the method we want to log |
106 | 106 | if (isset($traces[1])) { |
107 | - return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
107 | + return $traces[1]['file'].':'.$traces[1]['line']; |
|
108 | 108 | } |
109 | 109 | |
110 | 110 | return ''; |
@@ -150,7 +150,7 @@ discard block |
||
150 | 150 | * @param int $offset |
151 | 151 | * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
152 | 152 | */ |
153 | - public function prepare( $statement, $limit=null, $offset=null ) { |
|
153 | + public function prepare($statement, $limit = null, $offset = null) { |
|
154 | 154 | if ($limit === -1) { |
155 | 155 | $limit = null; |
156 | 156 | } |
@@ -161,7 +161,7 @@ discard block |
||
161 | 161 | $statement = $this->replaceTablePrefix($statement); |
162 | 162 | $statement = $this->adapter->fixupStatement($statement); |
163 | 163 | |
164 | - if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) { |
|
164 | + if (\OC::$server->getSystemConfig()->getValue('log_query', false)) { |
|
165 | 165 | \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG); |
166 | 166 | } |
167 | 167 | return parent::prepare($statement); |
@@ -318,7 +318,7 @@ discard block |
||
318 | 318 | throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
319 | 319 | } |
320 | 320 | |
321 | - $tableName = $this->tablePrefix . $tableName; |
|
321 | + $tableName = $this->tablePrefix.$tableName; |
|
322 | 322 | $this->lockedTable = $tableName; |
323 | 323 | $this->adapter->lockTable($tableName); |
324 | 324 | } |
@@ -339,11 +339,11 @@ discard block |
||
339 | 339 | * @return string |
340 | 340 | */ |
341 | 341 | public function getError() { |
342 | - $msg = $this->errorCode() . ': '; |
|
342 | + $msg = $this->errorCode().': '; |
|
343 | 343 | $errorInfo = $this->errorInfo(); |
344 | 344 | if (is_array($errorInfo)) { |
345 | - $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
346 | - $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
345 | + $msg .= 'SQLSTATE = '.$errorInfo[0].', '; |
|
346 | + $msg .= 'Driver Code = '.$errorInfo[1].', '; |
|
347 | 347 | $msg .= 'Driver Message = '.$errorInfo[2]; |
348 | 348 | } |
349 | 349 | return $msg; |
@@ -355,9 +355,9 @@ discard block |
||
355 | 355 | * @param string $table table name without the prefix |
356 | 356 | */ |
357 | 357 | public function dropTable($table) { |
358 | - $table = $this->tablePrefix . trim($table); |
|
358 | + $table = $this->tablePrefix.trim($table); |
|
359 | 359 | $schema = $this->getSchemaManager(); |
360 | - if($schema->tablesExist(array($table))) { |
|
360 | + if ($schema->tablesExist(array($table))) { |
|
361 | 361 | $schema->dropTable($table); |
362 | 362 | } |
363 | 363 | } |
@@ -368,8 +368,8 @@ discard block |
||
368 | 368 | * @param string $table table name without the prefix |
369 | 369 | * @return bool |
370 | 370 | */ |
371 | - public function tableExists($table){ |
|
372 | - $table = $this->tablePrefix . trim($table); |
|
371 | + public function tableExists($table) { |
|
372 | + $table = $this->tablePrefix.trim($table); |
|
373 | 373 | $schema = $this->getSchemaManager(); |
374 | 374 | return $schema->tablesExist(array($table)); |
375 | 375 | } |
@@ -380,7 +380,7 @@ discard block |
||
380 | 380 | * @return string |
381 | 381 | */ |
382 | 382 | protected function replaceTablePrefix($statement) { |
383 | - return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
383 | + return str_replace('*PREFIX*', $this->tablePrefix, $statement); |
|
384 | 384 | } |
385 | 385 | |
386 | 386 | /** |
@@ -41,384 +41,384 @@ |
||
41 | 41 | use OCP\PreConditionNotMetException; |
42 | 42 | |
43 | 43 | class Connection extends \Doctrine\DBAL\Connection implements IDBConnection { |
44 | - /** |
|
45 | - * @var string $tablePrefix |
|
46 | - */ |
|
47 | - protected $tablePrefix; |
|
48 | - |
|
49 | - /** |
|
50 | - * @var \OC\DB\Adapter $adapter |
|
51 | - */ |
|
52 | - protected $adapter; |
|
53 | - |
|
54 | - protected $lockedTable = null; |
|
55 | - |
|
56 | - public function connect() { |
|
57 | - try { |
|
58 | - return parent::connect(); |
|
59 | - } catch (DBALException $e) { |
|
60 | - // throw a new exception to prevent leaking info from the stacktrace |
|
61 | - throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
|
62 | - } |
|
63 | - } |
|
64 | - |
|
65 | - /** |
|
66 | - * Returns a QueryBuilder for the connection. |
|
67 | - * |
|
68 | - * @return \OCP\DB\QueryBuilder\IQueryBuilder |
|
69 | - */ |
|
70 | - public function getQueryBuilder() { |
|
71 | - return new QueryBuilder( |
|
72 | - $this, |
|
73 | - \OC::$server->getSystemConfig(), |
|
74 | - \OC::$server->getLogger() |
|
75 | - ); |
|
76 | - } |
|
77 | - |
|
78 | - /** |
|
79 | - * Gets the QueryBuilder for the connection. |
|
80 | - * |
|
81 | - * @return \Doctrine\DBAL\Query\QueryBuilder |
|
82 | - * @deprecated please use $this->getQueryBuilder() instead |
|
83 | - */ |
|
84 | - public function createQueryBuilder() { |
|
85 | - $backtrace = $this->getCallerBacktrace(); |
|
86 | - \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
87 | - return parent::createQueryBuilder(); |
|
88 | - } |
|
89 | - |
|
90 | - /** |
|
91 | - * Gets the ExpressionBuilder for the connection. |
|
92 | - * |
|
93 | - * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder |
|
94 | - * @deprecated please use $this->getQueryBuilder()->expr() instead |
|
95 | - */ |
|
96 | - public function getExpressionBuilder() { |
|
97 | - $backtrace = $this->getCallerBacktrace(); |
|
98 | - \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
99 | - return parent::getExpressionBuilder(); |
|
100 | - } |
|
101 | - |
|
102 | - /** |
|
103 | - * Get the file and line that called the method where `getCallerBacktrace()` was used |
|
104 | - * |
|
105 | - * @return string |
|
106 | - */ |
|
107 | - protected function getCallerBacktrace() { |
|
108 | - $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); |
|
109 | - |
|
110 | - // 0 is the method where we use `getCallerBacktrace` |
|
111 | - // 1 is the target method which uses the method we want to log |
|
112 | - if (isset($traces[1])) { |
|
113 | - return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
114 | - } |
|
115 | - |
|
116 | - return ''; |
|
117 | - } |
|
118 | - |
|
119 | - /** |
|
120 | - * @return string |
|
121 | - */ |
|
122 | - public function getPrefix() { |
|
123 | - return $this->tablePrefix; |
|
124 | - } |
|
125 | - |
|
126 | - /** |
|
127 | - * Initializes a new instance of the Connection class. |
|
128 | - * |
|
129 | - * @param array $params The connection parameters. |
|
130 | - * @param \Doctrine\DBAL\Driver $driver |
|
131 | - * @param \Doctrine\DBAL\Configuration $config |
|
132 | - * @param \Doctrine\Common\EventManager $eventManager |
|
133 | - * @throws \Exception |
|
134 | - */ |
|
135 | - public function __construct(array $params, Driver $driver, Configuration $config = null, |
|
136 | - EventManager $eventManager = null) |
|
137 | - { |
|
138 | - if (!isset($params['adapter'])) { |
|
139 | - throw new \Exception('adapter not set'); |
|
140 | - } |
|
141 | - if (!isset($params['tablePrefix'])) { |
|
142 | - throw new \Exception('tablePrefix not set'); |
|
143 | - } |
|
144 | - parent::__construct($params, $driver, $config, $eventManager); |
|
145 | - $this->adapter = new $params['adapter']($this); |
|
146 | - $this->tablePrefix = $params['tablePrefix']; |
|
147 | - |
|
148 | - parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED); |
|
149 | - } |
|
150 | - |
|
151 | - /** |
|
152 | - * Prepares an SQL statement. |
|
153 | - * |
|
154 | - * @param string $statement The SQL statement to prepare. |
|
155 | - * @param int $limit |
|
156 | - * @param int $offset |
|
157 | - * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
|
158 | - */ |
|
159 | - public function prepare( $statement, $limit=null, $offset=null ) { |
|
160 | - if ($limit === -1) { |
|
161 | - $limit = null; |
|
162 | - } |
|
163 | - if (!is_null($limit)) { |
|
164 | - $platform = $this->getDatabasePlatform(); |
|
165 | - $statement = $platform->modifyLimitQuery($statement, $limit, $offset); |
|
166 | - } |
|
167 | - $statement = $this->replaceTablePrefix($statement); |
|
168 | - $statement = $this->adapter->fixupStatement($statement); |
|
169 | - |
|
170 | - if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) { |
|
171 | - \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG); |
|
172 | - } |
|
173 | - return parent::prepare($statement); |
|
174 | - } |
|
175 | - |
|
176 | - /** |
|
177 | - * Executes an, optionally parametrized, SQL query. |
|
178 | - * |
|
179 | - * If the query is parametrized, a prepared statement is used. |
|
180 | - * If an SQLLogger is configured, the execution is logged. |
|
181 | - * |
|
182 | - * @param string $query The SQL query to execute. |
|
183 | - * @param array $params The parameters to bind to the query, if any. |
|
184 | - * @param array $types The types the previous parameters are in. |
|
185 | - * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional. |
|
186 | - * |
|
187 | - * @return \Doctrine\DBAL\Driver\Statement The executed statement. |
|
188 | - * |
|
189 | - * @throws \Doctrine\DBAL\DBALException |
|
190 | - */ |
|
191 | - public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null) |
|
192 | - { |
|
193 | - $query = $this->replaceTablePrefix($query); |
|
194 | - $query = $this->adapter->fixupStatement($query); |
|
195 | - return parent::executeQuery($query, $params, $types, $qcp); |
|
196 | - } |
|
197 | - |
|
198 | - /** |
|
199 | - * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters |
|
200 | - * and returns the number of affected rows. |
|
201 | - * |
|
202 | - * This method supports PDO binding types as well as DBAL mapping types. |
|
203 | - * |
|
204 | - * @param string $query The SQL query. |
|
205 | - * @param array $params The query parameters. |
|
206 | - * @param array $types The parameter types. |
|
207 | - * |
|
208 | - * @return integer The number of affected rows. |
|
209 | - * |
|
210 | - * @throws \Doctrine\DBAL\DBALException |
|
211 | - */ |
|
212 | - public function executeUpdate($query, array $params = array(), array $types = array()) |
|
213 | - { |
|
214 | - $query = $this->replaceTablePrefix($query); |
|
215 | - $query = $this->adapter->fixupStatement($query); |
|
216 | - return parent::executeUpdate($query, $params, $types); |
|
217 | - } |
|
218 | - |
|
219 | - /** |
|
220 | - * Returns the ID of the last inserted row, or the last value from a sequence object, |
|
221 | - * depending on the underlying driver. |
|
222 | - * |
|
223 | - * Note: This method may not return a meaningful or consistent result across different drivers, |
|
224 | - * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY |
|
225 | - * columns or sequences. |
|
226 | - * |
|
227 | - * @param string $seqName Name of the sequence object from which the ID should be returned. |
|
228 | - * @return string A string representation of the last inserted ID. |
|
229 | - */ |
|
230 | - public function lastInsertId($seqName = null) { |
|
231 | - if ($seqName) { |
|
232 | - $seqName = $this->replaceTablePrefix($seqName); |
|
233 | - } |
|
234 | - return $this->adapter->lastInsertId($seqName); |
|
235 | - } |
|
236 | - |
|
237 | - // internal use |
|
238 | - public function realLastInsertId($seqName = null) { |
|
239 | - return parent::lastInsertId($seqName); |
|
240 | - } |
|
241 | - |
|
242 | - /** |
|
243 | - * Insert a row if the matching row does not exists. |
|
244 | - * |
|
245 | - * @param string $table The table name (will replace *PREFIX* with the actual prefix) |
|
246 | - * @param array $input data that should be inserted into the table (column name => value) |
|
247 | - * @param array|null $compare List of values that should be checked for "if not exists" |
|
248 | - * If this is null or an empty array, all keys of $input will be compared |
|
249 | - * Please note: text fields (clob) must not be used in the compare array |
|
250 | - * @return int number of inserted rows |
|
251 | - * @throws \Doctrine\DBAL\DBALException |
|
252 | - */ |
|
253 | - public function insertIfNotExist($table, $input, array $compare = null) { |
|
254 | - return $this->adapter->insertIfNotExist($table, $input, $compare); |
|
255 | - } |
|
256 | - |
|
257 | - private function getType($value) { |
|
258 | - if (is_bool($value)) { |
|
259 | - return IQueryBuilder::PARAM_BOOL; |
|
260 | - } else if (is_int($value)) { |
|
261 | - return IQueryBuilder::PARAM_INT; |
|
262 | - } else { |
|
263 | - return IQueryBuilder::PARAM_STR; |
|
264 | - } |
|
265 | - } |
|
266 | - |
|
267 | - /** |
|
268 | - * Insert or update a row value |
|
269 | - * |
|
270 | - * @param string $table |
|
271 | - * @param array $keys (column name => value) |
|
272 | - * @param array $values (column name => value) |
|
273 | - * @param array $updatePreconditionValues ensure values match preconditions (column name => value) |
|
274 | - * @return int number of new rows |
|
275 | - * @throws \Doctrine\DBAL\DBALException |
|
276 | - * @throws PreConditionNotMetException |
|
277 | - */ |
|
278 | - public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) { |
|
279 | - try { |
|
280 | - $insertQb = $this->getQueryBuilder(); |
|
281 | - $insertQb->insert($table) |
|
282 | - ->values( |
|
283 | - array_map(function($value) use ($insertQb) { |
|
284 | - return $insertQb->createNamedParameter($value, $this->getType($value)); |
|
285 | - }, array_merge($keys, $values)) |
|
286 | - ); |
|
287 | - return $insertQb->execute(); |
|
288 | - } catch (ConstraintViolationException $e) { |
|
289 | - // value already exists, try update |
|
290 | - $updateQb = $this->getQueryBuilder(); |
|
291 | - $updateQb->update($table); |
|
292 | - foreach ($values as $name => $value) { |
|
293 | - $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value))); |
|
294 | - } |
|
295 | - $where = $updateQb->expr()->andX(); |
|
296 | - $whereValues = array_merge($keys, $updatePreconditionValues); |
|
297 | - foreach ($whereValues as $name => $value) { |
|
298 | - $where->add($updateQb->expr()->eq( |
|
299 | - $name, |
|
300 | - $updateQb->createNamedParameter($value, $this->getType($value)), |
|
301 | - $this->getType($value) |
|
302 | - )); |
|
303 | - } |
|
304 | - $updateQb->where($where); |
|
305 | - $affected = $updateQb->execute(); |
|
306 | - |
|
307 | - if ($affected === 0 && !empty($updatePreconditionValues)) { |
|
308 | - throw new PreConditionNotMetException(); |
|
309 | - } |
|
310 | - |
|
311 | - return 0; |
|
312 | - } |
|
313 | - } |
|
314 | - |
|
315 | - /** |
|
316 | - * Create an exclusive read+write lock on a table |
|
317 | - * |
|
318 | - * @param string $tableName |
|
319 | - * @throws \BadMethodCallException When trying to acquire a second lock |
|
320 | - * @since 9.1.0 |
|
321 | - */ |
|
322 | - public function lockTable($tableName) { |
|
323 | - if ($this->lockedTable !== null) { |
|
324 | - throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
|
325 | - } |
|
326 | - |
|
327 | - $tableName = $this->tablePrefix . $tableName; |
|
328 | - $this->lockedTable = $tableName; |
|
329 | - $this->adapter->lockTable($tableName); |
|
330 | - } |
|
331 | - |
|
332 | - /** |
|
333 | - * Release a previous acquired lock again |
|
334 | - * |
|
335 | - * @since 9.1.0 |
|
336 | - */ |
|
337 | - public function unlockTable() { |
|
338 | - $this->adapter->unlockTable(); |
|
339 | - $this->lockedTable = null; |
|
340 | - } |
|
341 | - |
|
342 | - /** |
|
343 | - * returns the error code and message as a string for logging |
|
344 | - * works with DoctrineException |
|
345 | - * @return string |
|
346 | - */ |
|
347 | - public function getError() { |
|
348 | - $msg = $this->errorCode() . ': '; |
|
349 | - $errorInfo = $this->errorInfo(); |
|
350 | - if (is_array($errorInfo)) { |
|
351 | - $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
352 | - $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
353 | - $msg .= 'Driver Message = '.$errorInfo[2]; |
|
354 | - } |
|
355 | - return $msg; |
|
356 | - } |
|
357 | - |
|
358 | - /** |
|
359 | - * Drop a table from the database if it exists |
|
360 | - * |
|
361 | - * @param string $table table name without the prefix |
|
362 | - */ |
|
363 | - public function dropTable($table) { |
|
364 | - $table = $this->tablePrefix . trim($table); |
|
365 | - $schema = $this->getSchemaManager(); |
|
366 | - if($schema->tablesExist(array($table))) { |
|
367 | - $schema->dropTable($table); |
|
368 | - } |
|
369 | - } |
|
370 | - |
|
371 | - /** |
|
372 | - * Check if a table exists |
|
373 | - * |
|
374 | - * @param string $table table name without the prefix |
|
375 | - * @return bool |
|
376 | - */ |
|
377 | - public function tableExists($table){ |
|
378 | - $table = $this->tablePrefix . trim($table); |
|
379 | - $schema = $this->getSchemaManager(); |
|
380 | - return $schema->tablesExist(array($table)); |
|
381 | - } |
|
382 | - |
|
383 | - // internal use |
|
384 | - /** |
|
385 | - * @param string $statement |
|
386 | - * @return string |
|
387 | - */ |
|
388 | - protected function replaceTablePrefix($statement) { |
|
389 | - return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
390 | - } |
|
391 | - |
|
392 | - /** |
|
393 | - * Check if a transaction is active |
|
394 | - * |
|
395 | - * @return bool |
|
396 | - * @since 8.2.0 |
|
397 | - */ |
|
398 | - public function inTransaction() { |
|
399 | - return $this->getTransactionNestingLevel() > 0; |
|
400 | - } |
|
401 | - |
|
402 | - /** |
|
403 | - * Espace a parameter to be used in a LIKE query |
|
404 | - * |
|
405 | - * @param string $param |
|
406 | - * @return string |
|
407 | - */ |
|
408 | - public function escapeLikeParameter($param) { |
|
409 | - return addcslashes($param, '\\_%'); |
|
410 | - } |
|
411 | - |
|
412 | - /** |
|
413 | - * Check whether or not the current database support 4byte wide unicode |
|
414 | - * |
|
415 | - * @return bool |
|
416 | - * @since 11.0.0 |
|
417 | - */ |
|
418 | - public function supports4ByteText() { |
|
419 | - if (!$this->getDatabasePlatform() instanceof MySqlPlatform) { |
|
420 | - return true; |
|
421 | - } |
|
422 | - return $this->getParams()['charset'] === 'utf8mb4'; |
|
423 | - } |
|
44 | + /** |
|
45 | + * @var string $tablePrefix |
|
46 | + */ |
|
47 | + protected $tablePrefix; |
|
48 | + |
|
49 | + /** |
|
50 | + * @var \OC\DB\Adapter $adapter |
|
51 | + */ |
|
52 | + protected $adapter; |
|
53 | + |
|
54 | + protected $lockedTable = null; |
|
55 | + |
|
56 | + public function connect() { |
|
57 | + try { |
|
58 | + return parent::connect(); |
|
59 | + } catch (DBALException $e) { |
|
60 | + // throw a new exception to prevent leaking info from the stacktrace |
|
61 | + throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
|
62 | + } |
|
63 | + } |
|
64 | + |
|
65 | + /** |
|
66 | + * Returns a QueryBuilder for the connection. |
|
67 | + * |
|
68 | + * @return \OCP\DB\QueryBuilder\IQueryBuilder |
|
69 | + */ |
|
70 | + public function getQueryBuilder() { |
|
71 | + return new QueryBuilder( |
|
72 | + $this, |
|
73 | + \OC::$server->getSystemConfig(), |
|
74 | + \OC::$server->getLogger() |
|
75 | + ); |
|
76 | + } |
|
77 | + |
|
78 | + /** |
|
79 | + * Gets the QueryBuilder for the connection. |
|
80 | + * |
|
81 | + * @return \Doctrine\DBAL\Query\QueryBuilder |
|
82 | + * @deprecated please use $this->getQueryBuilder() instead |
|
83 | + */ |
|
84 | + public function createQueryBuilder() { |
|
85 | + $backtrace = $this->getCallerBacktrace(); |
|
86 | + \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
87 | + return parent::createQueryBuilder(); |
|
88 | + } |
|
89 | + |
|
90 | + /** |
|
91 | + * Gets the ExpressionBuilder for the connection. |
|
92 | + * |
|
93 | + * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder |
|
94 | + * @deprecated please use $this->getQueryBuilder()->expr() instead |
|
95 | + */ |
|
96 | + public function getExpressionBuilder() { |
|
97 | + $backtrace = $this->getCallerBacktrace(); |
|
98 | + \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
99 | + return parent::getExpressionBuilder(); |
|
100 | + } |
|
101 | + |
|
102 | + /** |
|
103 | + * Get the file and line that called the method where `getCallerBacktrace()` was used |
|
104 | + * |
|
105 | + * @return string |
|
106 | + */ |
|
107 | + protected function getCallerBacktrace() { |
|
108 | + $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); |
|
109 | + |
|
110 | + // 0 is the method where we use `getCallerBacktrace` |
|
111 | + // 1 is the target method which uses the method we want to log |
|
112 | + if (isset($traces[1])) { |
|
113 | + return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
114 | + } |
|
115 | + |
|
116 | + return ''; |
|
117 | + } |
|
118 | + |
|
119 | + /** |
|
120 | + * @return string |
|
121 | + */ |
|
122 | + public function getPrefix() { |
|
123 | + return $this->tablePrefix; |
|
124 | + } |
|
125 | + |
|
126 | + /** |
|
127 | + * Initializes a new instance of the Connection class. |
|
128 | + * |
|
129 | + * @param array $params The connection parameters. |
|
130 | + * @param \Doctrine\DBAL\Driver $driver |
|
131 | + * @param \Doctrine\DBAL\Configuration $config |
|
132 | + * @param \Doctrine\Common\EventManager $eventManager |
|
133 | + * @throws \Exception |
|
134 | + */ |
|
135 | + public function __construct(array $params, Driver $driver, Configuration $config = null, |
|
136 | + EventManager $eventManager = null) |
|
137 | + { |
|
138 | + if (!isset($params['adapter'])) { |
|
139 | + throw new \Exception('adapter not set'); |
|
140 | + } |
|
141 | + if (!isset($params['tablePrefix'])) { |
|
142 | + throw new \Exception('tablePrefix not set'); |
|
143 | + } |
|
144 | + parent::__construct($params, $driver, $config, $eventManager); |
|
145 | + $this->adapter = new $params['adapter']($this); |
|
146 | + $this->tablePrefix = $params['tablePrefix']; |
|
147 | + |
|
148 | + parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED); |
|
149 | + } |
|
150 | + |
|
151 | + /** |
|
152 | + * Prepares an SQL statement. |
|
153 | + * |
|
154 | + * @param string $statement The SQL statement to prepare. |
|
155 | + * @param int $limit |
|
156 | + * @param int $offset |
|
157 | + * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
|
158 | + */ |
|
159 | + public function prepare( $statement, $limit=null, $offset=null ) { |
|
160 | + if ($limit === -1) { |
|
161 | + $limit = null; |
|
162 | + } |
|
163 | + if (!is_null($limit)) { |
|
164 | + $platform = $this->getDatabasePlatform(); |
|
165 | + $statement = $platform->modifyLimitQuery($statement, $limit, $offset); |
|
166 | + } |
|
167 | + $statement = $this->replaceTablePrefix($statement); |
|
168 | + $statement = $this->adapter->fixupStatement($statement); |
|
169 | + |
|
170 | + if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) { |
|
171 | + \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG); |
|
172 | + } |
|
173 | + return parent::prepare($statement); |
|
174 | + } |
|
175 | + |
|
176 | + /** |
|
177 | + * Executes an, optionally parametrized, SQL query. |
|
178 | + * |
|
179 | + * If the query is parametrized, a prepared statement is used. |
|
180 | + * If an SQLLogger is configured, the execution is logged. |
|
181 | + * |
|
182 | + * @param string $query The SQL query to execute. |
|
183 | + * @param array $params The parameters to bind to the query, if any. |
|
184 | + * @param array $types The types the previous parameters are in. |
|
185 | + * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional. |
|
186 | + * |
|
187 | + * @return \Doctrine\DBAL\Driver\Statement The executed statement. |
|
188 | + * |
|
189 | + * @throws \Doctrine\DBAL\DBALException |
|
190 | + */ |
|
191 | + public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null) |
|
192 | + { |
|
193 | + $query = $this->replaceTablePrefix($query); |
|
194 | + $query = $this->adapter->fixupStatement($query); |
|
195 | + return parent::executeQuery($query, $params, $types, $qcp); |
|
196 | + } |
|
197 | + |
|
198 | + /** |
|
199 | + * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters |
|
200 | + * and returns the number of affected rows. |
|
201 | + * |
|
202 | + * This method supports PDO binding types as well as DBAL mapping types. |
|
203 | + * |
|
204 | + * @param string $query The SQL query. |
|
205 | + * @param array $params The query parameters. |
|
206 | + * @param array $types The parameter types. |
|
207 | + * |
|
208 | + * @return integer The number of affected rows. |
|
209 | + * |
|
210 | + * @throws \Doctrine\DBAL\DBALException |
|
211 | + */ |
|
212 | + public function executeUpdate($query, array $params = array(), array $types = array()) |
|
213 | + { |
|
214 | + $query = $this->replaceTablePrefix($query); |
|
215 | + $query = $this->adapter->fixupStatement($query); |
|
216 | + return parent::executeUpdate($query, $params, $types); |
|
217 | + } |
|
218 | + |
|
219 | + /** |
|
220 | + * Returns the ID of the last inserted row, or the last value from a sequence object, |
|
221 | + * depending on the underlying driver. |
|
222 | + * |
|
223 | + * Note: This method may not return a meaningful or consistent result across different drivers, |
|
224 | + * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY |
|
225 | + * columns or sequences. |
|
226 | + * |
|
227 | + * @param string $seqName Name of the sequence object from which the ID should be returned. |
|
228 | + * @return string A string representation of the last inserted ID. |
|
229 | + */ |
|
230 | + public function lastInsertId($seqName = null) { |
|
231 | + if ($seqName) { |
|
232 | + $seqName = $this->replaceTablePrefix($seqName); |
|
233 | + } |
|
234 | + return $this->adapter->lastInsertId($seqName); |
|
235 | + } |
|
236 | + |
|
237 | + // internal use |
|
238 | + public function realLastInsertId($seqName = null) { |
|
239 | + return parent::lastInsertId($seqName); |
|
240 | + } |
|
241 | + |
|
242 | + /** |
|
243 | + * Insert a row if the matching row does not exists. |
|
244 | + * |
|
245 | + * @param string $table The table name (will replace *PREFIX* with the actual prefix) |
|
246 | + * @param array $input data that should be inserted into the table (column name => value) |
|
247 | + * @param array|null $compare List of values that should be checked for "if not exists" |
|
248 | + * If this is null or an empty array, all keys of $input will be compared |
|
249 | + * Please note: text fields (clob) must not be used in the compare array |
|
250 | + * @return int number of inserted rows |
|
251 | + * @throws \Doctrine\DBAL\DBALException |
|
252 | + */ |
|
253 | + public function insertIfNotExist($table, $input, array $compare = null) { |
|
254 | + return $this->adapter->insertIfNotExist($table, $input, $compare); |
|
255 | + } |
|
256 | + |
|
257 | + private function getType($value) { |
|
258 | + if (is_bool($value)) { |
|
259 | + return IQueryBuilder::PARAM_BOOL; |
|
260 | + } else if (is_int($value)) { |
|
261 | + return IQueryBuilder::PARAM_INT; |
|
262 | + } else { |
|
263 | + return IQueryBuilder::PARAM_STR; |
|
264 | + } |
|
265 | + } |
|
266 | + |
|
267 | + /** |
|
268 | + * Insert or update a row value |
|
269 | + * |
|
270 | + * @param string $table |
|
271 | + * @param array $keys (column name => value) |
|
272 | + * @param array $values (column name => value) |
|
273 | + * @param array $updatePreconditionValues ensure values match preconditions (column name => value) |
|
274 | + * @return int number of new rows |
|
275 | + * @throws \Doctrine\DBAL\DBALException |
|
276 | + * @throws PreConditionNotMetException |
|
277 | + */ |
|
278 | + public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) { |
|
279 | + try { |
|
280 | + $insertQb = $this->getQueryBuilder(); |
|
281 | + $insertQb->insert($table) |
|
282 | + ->values( |
|
283 | + array_map(function($value) use ($insertQb) { |
|
284 | + return $insertQb->createNamedParameter($value, $this->getType($value)); |
|
285 | + }, array_merge($keys, $values)) |
|
286 | + ); |
|
287 | + return $insertQb->execute(); |
|
288 | + } catch (ConstraintViolationException $e) { |
|
289 | + // value already exists, try update |
|
290 | + $updateQb = $this->getQueryBuilder(); |
|
291 | + $updateQb->update($table); |
|
292 | + foreach ($values as $name => $value) { |
|
293 | + $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value))); |
|
294 | + } |
|
295 | + $where = $updateQb->expr()->andX(); |
|
296 | + $whereValues = array_merge($keys, $updatePreconditionValues); |
|
297 | + foreach ($whereValues as $name => $value) { |
|
298 | + $where->add($updateQb->expr()->eq( |
|
299 | + $name, |
|
300 | + $updateQb->createNamedParameter($value, $this->getType($value)), |
|
301 | + $this->getType($value) |
|
302 | + )); |
|
303 | + } |
|
304 | + $updateQb->where($where); |
|
305 | + $affected = $updateQb->execute(); |
|
306 | + |
|
307 | + if ($affected === 0 && !empty($updatePreconditionValues)) { |
|
308 | + throw new PreConditionNotMetException(); |
|
309 | + } |
|
310 | + |
|
311 | + return 0; |
|
312 | + } |
|
313 | + } |
|
314 | + |
|
315 | + /** |
|
316 | + * Create an exclusive read+write lock on a table |
|
317 | + * |
|
318 | + * @param string $tableName |
|
319 | + * @throws \BadMethodCallException When trying to acquire a second lock |
|
320 | + * @since 9.1.0 |
|
321 | + */ |
|
322 | + public function lockTable($tableName) { |
|
323 | + if ($this->lockedTable !== null) { |
|
324 | + throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
|
325 | + } |
|
326 | + |
|
327 | + $tableName = $this->tablePrefix . $tableName; |
|
328 | + $this->lockedTable = $tableName; |
|
329 | + $this->adapter->lockTable($tableName); |
|
330 | + } |
|
331 | + |
|
332 | + /** |
|
333 | + * Release a previous acquired lock again |
|
334 | + * |
|
335 | + * @since 9.1.0 |
|
336 | + */ |
|
337 | + public function unlockTable() { |
|
338 | + $this->adapter->unlockTable(); |
|
339 | + $this->lockedTable = null; |
|
340 | + } |
|
341 | + |
|
342 | + /** |
|
343 | + * returns the error code and message as a string for logging |
|
344 | + * works with DoctrineException |
|
345 | + * @return string |
|
346 | + */ |
|
347 | + public function getError() { |
|
348 | + $msg = $this->errorCode() . ': '; |
|
349 | + $errorInfo = $this->errorInfo(); |
|
350 | + if (is_array($errorInfo)) { |
|
351 | + $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
352 | + $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
353 | + $msg .= 'Driver Message = '.$errorInfo[2]; |
|
354 | + } |
|
355 | + return $msg; |
|
356 | + } |
|
357 | + |
|
358 | + /** |
|
359 | + * Drop a table from the database if it exists |
|
360 | + * |
|
361 | + * @param string $table table name without the prefix |
|
362 | + */ |
|
363 | + public function dropTable($table) { |
|
364 | + $table = $this->tablePrefix . trim($table); |
|
365 | + $schema = $this->getSchemaManager(); |
|
366 | + if($schema->tablesExist(array($table))) { |
|
367 | + $schema->dropTable($table); |
|
368 | + } |
|
369 | + } |
|
370 | + |
|
371 | + /** |
|
372 | + * Check if a table exists |
|
373 | + * |
|
374 | + * @param string $table table name without the prefix |
|
375 | + * @return bool |
|
376 | + */ |
|
377 | + public function tableExists($table){ |
|
378 | + $table = $this->tablePrefix . trim($table); |
|
379 | + $schema = $this->getSchemaManager(); |
|
380 | + return $schema->tablesExist(array($table)); |
|
381 | + } |
|
382 | + |
|
383 | + // internal use |
|
384 | + /** |
|
385 | + * @param string $statement |
|
386 | + * @return string |
|
387 | + */ |
|
388 | + protected function replaceTablePrefix($statement) { |
|
389 | + return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
390 | + } |
|
391 | + |
|
392 | + /** |
|
393 | + * Check if a transaction is active |
|
394 | + * |
|
395 | + * @return bool |
|
396 | + * @since 8.2.0 |
|
397 | + */ |
|
398 | + public function inTransaction() { |
|
399 | + return $this->getTransactionNestingLevel() > 0; |
|
400 | + } |
|
401 | + |
|
402 | + /** |
|
403 | + * Espace a parameter to be used in a LIKE query |
|
404 | + * |
|
405 | + * @param string $param |
|
406 | + * @return string |
|
407 | + */ |
|
408 | + public function escapeLikeParameter($param) { |
|
409 | + return addcslashes($param, '\\_%'); |
|
410 | + } |
|
411 | + |
|
412 | + /** |
|
413 | + * Check whether or not the current database support 4byte wide unicode |
|
414 | + * |
|
415 | + * @return bool |
|
416 | + * @since 11.0.0 |
|
417 | + */ |
|
418 | + public function supports4ByteText() { |
|
419 | + if (!$this->getDatabasePlatform() instanceof MySqlPlatform) { |
|
420 | + return true; |
|
421 | + } |
|
422 | + return $this->getParams()['charset'] === 'utf8mb4'; |
|
423 | + } |
|
424 | 424 | } |
@@ -386,6 +386,14 @@ discard block |
||
386 | 386 | return $size; |
387 | 387 | } |
388 | 388 | |
389 | + /** |
|
390 | + * @param string $path |
|
391 | + * @param boolean $recursive |
|
392 | + * @param integer $reuse |
|
393 | + * @param integer|null $folderId |
|
394 | + * @param boolean $lock |
|
395 | + * @param integer $size |
|
396 | + */ |
|
389 | 397 | private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) { |
390 | 398 | // we put this in it's own function so it cleans up the memory before we start recursing |
391 | 399 | $existingChildren = $this->getExistingChildren($folderId); |
@@ -485,6 +493,9 @@ discard block |
||
485 | 493 | } |
486 | 494 | } |
487 | 495 | |
496 | + /** |
|
497 | + * @param string|boolean $path |
|
498 | + */ |
|
488 | 499 | private function runBackgroundScanJob(callable $callback, $path) { |
489 | 500 | try { |
490 | 501 | $callback(); |
@@ -55,476 +55,476 @@ |
||
55 | 55 | * @package OC\Files\Cache |
56 | 56 | */ |
57 | 57 | class Scanner extends BasicEmitter implements IScanner { |
58 | - /** |
|
59 | - * @var \OC\Files\Storage\Storage $storage |
|
60 | - */ |
|
61 | - protected $storage; |
|
62 | - |
|
63 | - /** |
|
64 | - * @var string $storageId |
|
65 | - */ |
|
66 | - protected $storageId; |
|
67 | - |
|
68 | - /** |
|
69 | - * @var \OC\Files\Cache\Cache $cache |
|
70 | - */ |
|
71 | - protected $cache; |
|
72 | - |
|
73 | - /** |
|
74 | - * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache |
|
75 | - */ |
|
76 | - protected $cacheActive; |
|
77 | - |
|
78 | - /** |
|
79 | - * @var bool $useTransactions whether to use transactions |
|
80 | - */ |
|
81 | - protected $useTransactions = true; |
|
82 | - |
|
83 | - /** |
|
84 | - * @var \OCP\Lock\ILockingProvider |
|
85 | - */ |
|
86 | - protected $lockingProvider; |
|
87 | - |
|
88 | - public function __construct(\OC\Files\Storage\Storage $storage) { |
|
89 | - $this->storage = $storage; |
|
90 | - $this->storageId = $this->storage->getId(); |
|
91 | - $this->cache = $storage->getCache(); |
|
92 | - $this->cacheActive = !Config::getSystemValue('filesystem_cache_readonly', false); |
|
93 | - $this->lockingProvider = \OC::$server->getLockingProvider(); |
|
94 | - } |
|
95 | - |
|
96 | - /** |
|
97 | - * Whether to wrap the scanning of a folder in a database transaction |
|
98 | - * On default transactions are used |
|
99 | - * |
|
100 | - * @param bool $useTransactions |
|
101 | - */ |
|
102 | - public function setUseTransactions($useTransactions) { |
|
103 | - $this->useTransactions = $useTransactions; |
|
104 | - } |
|
105 | - |
|
106 | - /** |
|
107 | - * get all the metadata of a file or folder |
|
108 | - * * |
|
109 | - * |
|
110 | - * @param string $path |
|
111 | - * @return array an array of metadata of the file |
|
112 | - */ |
|
113 | - protected function getData($path) { |
|
114 | - $data = $this->storage->getMetaData($path); |
|
115 | - if (is_null($data)) { |
|
116 | - \OCP\Util::writeLog('OC\Files\Cache\Scanner', "!!! Path '$path' is not accessible or present !!!", \OCP\Util::DEBUG); |
|
117 | - } |
|
118 | - return $data; |
|
119 | - } |
|
120 | - |
|
121 | - /** |
|
122 | - * scan a single file and store it in the cache |
|
123 | - * |
|
124 | - * @param string $file |
|
125 | - * @param int $reuseExisting |
|
126 | - * @param int $parentId |
|
127 | - * @param array | null $cacheData existing data in the cache for the file to be scanned |
|
128 | - * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
129 | - * @return array an array of metadata of the scanned file |
|
130 | - * @throws \OC\ServerNotAvailableException |
|
131 | - * @throws \OCP\Lock\LockedException |
|
132 | - */ |
|
133 | - public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) { |
|
134 | - if ($file !== '') { |
|
135 | - try { |
|
136 | - $this->storage->verifyPath(dirname($file), basename($file)); |
|
137 | - } catch (\Exception $e) { |
|
138 | - return null; |
|
139 | - } |
|
140 | - } |
|
141 | - |
|
142 | - // only proceed if $file is not a partial file nor a blacklisted file |
|
143 | - if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) { |
|
144 | - |
|
145 | - //acquire a lock |
|
146 | - if ($lock) { |
|
147 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
148 | - $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
149 | - } |
|
150 | - } |
|
151 | - |
|
152 | - try { |
|
153 | - $data = $this->getData($file); |
|
154 | - } catch (ForbiddenException $e) { |
|
155 | - return null; |
|
156 | - } |
|
157 | - |
|
158 | - if ($data) { |
|
159 | - |
|
160 | - // pre-emit only if it was a file. By that we avoid counting/treating folders as files |
|
161 | - if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
162 | - $this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId)); |
|
163 | - \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
164 | - } |
|
165 | - |
|
166 | - $parent = dirname($file); |
|
167 | - if ($parent === '.' or $parent === '/') { |
|
168 | - $parent = ''; |
|
169 | - } |
|
170 | - if ($parentId === -1) { |
|
171 | - $parentId = $this->cache->getParentId($file); |
|
172 | - } |
|
173 | - |
|
174 | - // scan the parent if it's not in the cache (id -1) and the current file is not the root folder |
|
175 | - if ($file and $parentId === -1) { |
|
176 | - $parentData = $this->scanFile($parent); |
|
177 | - if (!$parentData) { |
|
178 | - return null; |
|
179 | - } |
|
180 | - $parentId = $parentData['fileid']; |
|
181 | - } |
|
182 | - if ($parent) { |
|
183 | - $data['parent'] = $parentId; |
|
184 | - } |
|
185 | - if (is_null($cacheData)) { |
|
186 | - /** @var CacheEntry $cacheData */ |
|
187 | - $cacheData = $this->cache->get($file); |
|
188 | - } |
|
189 | - if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) { |
|
190 | - // prevent empty etag |
|
191 | - if (empty($cacheData['etag'])) { |
|
192 | - $etag = $data['etag']; |
|
193 | - } else { |
|
194 | - $etag = $cacheData['etag']; |
|
195 | - } |
|
196 | - $fileId = $cacheData['fileid']; |
|
197 | - $data['fileid'] = $fileId; |
|
198 | - // only reuse data if the file hasn't explicitly changed |
|
199 | - if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) { |
|
200 | - $data['mtime'] = $cacheData['mtime']; |
|
201 | - if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) { |
|
202 | - $data['size'] = $cacheData['size']; |
|
203 | - } |
|
204 | - if ($reuseExisting & self::REUSE_ETAG) { |
|
205 | - $data['etag'] = $etag; |
|
206 | - } |
|
207 | - } |
|
208 | - // Only update metadata that has changed |
|
209 | - $newData = array_diff_assoc($data, $cacheData->getData()); |
|
210 | - } else { |
|
211 | - $newData = $data; |
|
212 | - $fileId = -1; |
|
213 | - } |
|
214 | - if (!empty($newData)) { |
|
215 | - // Reset the checksum if the data has changed |
|
216 | - $newData['checksum'] = ''; |
|
217 | - $data['fileid'] = $this->addToCache($file, $newData, $fileId); |
|
218 | - } |
|
219 | - if (isset($cacheData['size'])) { |
|
220 | - $data['oldSize'] = $cacheData['size']; |
|
221 | - } else { |
|
222 | - $data['oldSize'] = 0; |
|
223 | - } |
|
224 | - |
|
225 | - if (isset($cacheData['encrypted'])) { |
|
226 | - $data['encrypted'] = $cacheData['encrypted']; |
|
227 | - } |
|
228 | - |
|
229 | - // post-emit only if it was a file. By that we avoid counting/treating folders as files |
|
230 | - if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
231 | - $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId)); |
|
232 | - \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
233 | - } |
|
234 | - |
|
235 | - } else { |
|
236 | - $this->removeFromCache($file); |
|
237 | - } |
|
238 | - |
|
239 | - //release the acquired lock |
|
240 | - if ($lock) { |
|
241 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
242 | - $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
243 | - } |
|
244 | - } |
|
245 | - |
|
246 | - if ($data && !isset($data['encrypted'])) { |
|
247 | - $data['encrypted'] = false; |
|
248 | - } |
|
249 | - return $data; |
|
250 | - } |
|
251 | - |
|
252 | - return null; |
|
253 | - } |
|
254 | - |
|
255 | - protected function removeFromCache($path) { |
|
256 | - \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path)); |
|
257 | - $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path)); |
|
258 | - if ($this->cacheActive) { |
|
259 | - $this->cache->remove($path); |
|
260 | - } |
|
261 | - } |
|
262 | - |
|
263 | - /** |
|
264 | - * @param string $path |
|
265 | - * @param array $data |
|
266 | - * @param int $fileId |
|
267 | - * @return int the id of the added file |
|
268 | - */ |
|
269 | - protected function addToCache($path, $data, $fileId = -1) { |
|
270 | - \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
271 | - $this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data)); |
|
272 | - if ($this->cacheActive) { |
|
273 | - if ($fileId !== -1) { |
|
274 | - $this->cache->update($fileId, $data); |
|
275 | - return $fileId; |
|
276 | - } else { |
|
277 | - return $this->cache->put($path, $data); |
|
278 | - } |
|
279 | - } else { |
|
280 | - return -1; |
|
281 | - } |
|
282 | - } |
|
283 | - |
|
284 | - /** |
|
285 | - * @param string $path |
|
286 | - * @param array $data |
|
287 | - * @param int $fileId |
|
288 | - */ |
|
289 | - protected function updateCache($path, $data, $fileId = -1) { |
|
290 | - \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
291 | - $this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data)); |
|
292 | - if ($this->cacheActive) { |
|
293 | - if ($fileId !== -1) { |
|
294 | - $this->cache->update($fileId, $data); |
|
295 | - } else { |
|
296 | - $this->cache->put($path, $data); |
|
297 | - } |
|
298 | - } |
|
299 | - } |
|
300 | - |
|
301 | - /** |
|
302 | - * scan a folder and all it's children |
|
303 | - * |
|
304 | - * @param string $path |
|
305 | - * @param bool $recursive |
|
306 | - * @param int $reuse |
|
307 | - * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
308 | - * @return array an array of the meta data of the scanned file or folder |
|
309 | - */ |
|
310 | - public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) { |
|
311 | - if ($reuse === -1) { |
|
312 | - $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
313 | - } |
|
314 | - if ($lock) { |
|
315 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
316 | - $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
317 | - $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
318 | - } |
|
319 | - } |
|
320 | - $data = $this->scanFile($path, $reuse, -1, null, $lock); |
|
321 | - if ($data and $data['mimetype'] === 'httpd/unix-directory') { |
|
322 | - $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock); |
|
323 | - $data['size'] = $size; |
|
324 | - } |
|
325 | - if ($lock) { |
|
326 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
327 | - $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
328 | - $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
329 | - } |
|
330 | - } |
|
331 | - return $data; |
|
332 | - } |
|
333 | - |
|
334 | - /** |
|
335 | - * Get the children currently in the cache |
|
336 | - * |
|
337 | - * @param int $folderId |
|
338 | - * @return array[] |
|
339 | - */ |
|
340 | - protected function getExistingChildren($folderId) { |
|
341 | - $existingChildren = array(); |
|
342 | - $children = $this->cache->getFolderContentsById($folderId); |
|
343 | - foreach ($children as $child) { |
|
344 | - $existingChildren[$child['name']] = $child; |
|
345 | - } |
|
346 | - return $existingChildren; |
|
347 | - } |
|
348 | - |
|
349 | - /** |
|
350 | - * Get the children from the storage |
|
351 | - * |
|
352 | - * @param string $folder |
|
353 | - * @return string[] |
|
354 | - */ |
|
355 | - protected function getNewChildren($folder) { |
|
356 | - $children = array(); |
|
357 | - if ($dh = $this->storage->opendir($folder)) { |
|
358 | - if (is_resource($dh)) { |
|
359 | - while (($file = readdir($dh)) !== false) { |
|
360 | - if (!Filesystem::isIgnoredDir($file)) { |
|
361 | - $children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/'); |
|
362 | - } |
|
363 | - } |
|
364 | - } |
|
365 | - } |
|
366 | - return $children; |
|
367 | - } |
|
368 | - |
|
369 | - /** |
|
370 | - * scan all the files and folders in a folder |
|
371 | - * |
|
372 | - * @param string $path |
|
373 | - * @param bool $recursive |
|
374 | - * @param int $reuse |
|
375 | - * @param int $folderId id for the folder to be scanned |
|
376 | - * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
377 | - * @return int the size of the scanned folder or -1 if the size is unknown at this stage |
|
378 | - */ |
|
379 | - protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) { |
|
380 | - if ($reuse === -1) { |
|
381 | - $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
382 | - } |
|
383 | - $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId)); |
|
384 | - $size = 0; |
|
385 | - if (!is_null($folderId)) { |
|
386 | - $folderId = $this->cache->getId($path); |
|
387 | - } |
|
388 | - $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size); |
|
389 | - |
|
390 | - foreach ($childQueue as $child => $childId) { |
|
391 | - $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock); |
|
392 | - if ($childSize === -1) { |
|
393 | - $size = -1; |
|
394 | - } else if ($size !== -1) { |
|
395 | - $size += $childSize; |
|
396 | - } |
|
397 | - } |
|
398 | - if ($this->cacheActive) { |
|
399 | - $this->cache->update($folderId, array('size' => $size)); |
|
400 | - } |
|
401 | - $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId)); |
|
402 | - return $size; |
|
403 | - } |
|
404 | - |
|
405 | - private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) { |
|
406 | - // we put this in it's own function so it cleans up the memory before we start recursing |
|
407 | - $existingChildren = $this->getExistingChildren($folderId); |
|
408 | - $newChildren = $this->getNewChildren($path); |
|
409 | - |
|
410 | - if ($this->useTransactions) { |
|
411 | - \OC::$server->getDatabaseConnection()->beginTransaction(); |
|
412 | - } |
|
413 | - |
|
414 | - $exceptionOccurred = false; |
|
415 | - $childQueue = []; |
|
416 | - foreach ($newChildren as $file) { |
|
417 | - $child = ($path) ? $path . '/' . $file : $file; |
|
418 | - try { |
|
419 | - $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null; |
|
420 | - $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock); |
|
421 | - if ($data) { |
|
422 | - if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) { |
|
423 | - $childQueue[$child] = $data['fileid']; |
|
424 | - } else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) { |
|
425 | - // only recurse into folders which aren't fully scanned |
|
426 | - $childQueue[$child] = $data['fileid']; |
|
427 | - } else if ($data['size'] === -1) { |
|
428 | - $size = -1; |
|
429 | - } else if ($size !== -1) { |
|
430 | - $size += $data['size']; |
|
431 | - } |
|
432 | - } |
|
433 | - } catch (\Doctrine\DBAL\DBALException $ex) { |
|
434 | - // might happen if inserting duplicate while a scanning |
|
435 | - // process is running in parallel |
|
436 | - // log and ignore |
|
437 | - \OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG); |
|
438 | - $exceptionOccurred = true; |
|
439 | - } catch (\OCP\Lock\LockedException $e) { |
|
440 | - if ($this->useTransactions) { |
|
441 | - \OC::$server->getDatabaseConnection()->rollback(); |
|
442 | - } |
|
443 | - throw $e; |
|
444 | - } |
|
445 | - } |
|
446 | - $removedChildren = \array_diff(array_keys($existingChildren), $newChildren); |
|
447 | - foreach ($removedChildren as $childName) { |
|
448 | - $child = ($path) ? $path . '/' . $childName : $childName; |
|
449 | - $this->removeFromCache($child); |
|
450 | - } |
|
451 | - if ($this->useTransactions) { |
|
452 | - \OC::$server->getDatabaseConnection()->commit(); |
|
453 | - } |
|
454 | - if ($exceptionOccurred) { |
|
455 | - // It might happen that the parallel scan process has already |
|
456 | - // inserted mimetypes but those weren't available yet inside the transaction |
|
457 | - // To make sure to have the updated mime types in such cases, |
|
458 | - // we reload them here |
|
459 | - \OC::$server->getMimeTypeLoader()->reset(); |
|
460 | - } |
|
461 | - return $childQueue; |
|
462 | - } |
|
463 | - |
|
464 | - /** |
|
465 | - * check if the file should be ignored when scanning |
|
466 | - * NOTE: files with a '.part' extension are ignored as well! |
|
467 | - * prevents unfinished put requests to be scanned |
|
468 | - * |
|
469 | - * @param string $file |
|
470 | - * @return boolean |
|
471 | - */ |
|
472 | - public static function isPartialFile($file) { |
|
473 | - if (pathinfo($file, PATHINFO_EXTENSION) === 'part') { |
|
474 | - return true; |
|
475 | - } |
|
476 | - if (strpos($file, '.part/') !== false) { |
|
477 | - return true; |
|
478 | - } |
|
479 | - |
|
480 | - return false; |
|
481 | - } |
|
482 | - |
|
483 | - /** |
|
484 | - * walk over any folders that are not fully scanned yet and scan them |
|
485 | - */ |
|
486 | - public function backgroundScan() { |
|
487 | - if (!$this->cache->inCache('')) { |
|
488 | - $this->runBackgroundScanJob(function () { |
|
489 | - $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG); |
|
490 | - }, ''); |
|
491 | - } else { |
|
492 | - $lastPath = null; |
|
493 | - while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { |
|
494 | - $this->runBackgroundScanJob(function () use ($path) { |
|
495 | - $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE); |
|
496 | - }, $path); |
|
497 | - // FIXME: this won't proceed with the next item, needs revamping of getIncomplete() |
|
498 | - // to make this possible |
|
499 | - $lastPath = $path; |
|
500 | - } |
|
501 | - } |
|
502 | - } |
|
503 | - |
|
504 | - private function runBackgroundScanJob(callable $callback, $path) { |
|
505 | - try { |
|
506 | - $callback(); |
|
507 | - \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path)); |
|
508 | - if ($this->cacheActive && $this->cache instanceof Cache) { |
|
509 | - $this->cache->correctFolderSize($path); |
|
510 | - } |
|
511 | - } catch (\OCP\Files\StorageInvalidException $e) { |
|
512 | - // skip unavailable storages |
|
513 | - } catch (\OCP\Files\StorageNotAvailableException $e) { |
|
514 | - // skip unavailable storages |
|
515 | - } catch (\OCP\Files\ForbiddenException $e) { |
|
516 | - // skip forbidden storages |
|
517 | - } catch (\OCP\Lock\LockedException $e) { |
|
518 | - // skip unavailable storages |
|
519 | - } |
|
520 | - } |
|
521 | - |
|
522 | - /** |
|
523 | - * Set whether the cache is affected by scan operations |
|
524 | - * |
|
525 | - * @param boolean $active The active state of the cache |
|
526 | - */ |
|
527 | - public function setCacheActive($active) { |
|
528 | - $this->cacheActive = $active; |
|
529 | - } |
|
58 | + /** |
|
59 | + * @var \OC\Files\Storage\Storage $storage |
|
60 | + */ |
|
61 | + protected $storage; |
|
62 | + |
|
63 | + /** |
|
64 | + * @var string $storageId |
|
65 | + */ |
|
66 | + protected $storageId; |
|
67 | + |
|
68 | + /** |
|
69 | + * @var \OC\Files\Cache\Cache $cache |
|
70 | + */ |
|
71 | + protected $cache; |
|
72 | + |
|
73 | + /** |
|
74 | + * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache |
|
75 | + */ |
|
76 | + protected $cacheActive; |
|
77 | + |
|
78 | + /** |
|
79 | + * @var bool $useTransactions whether to use transactions |
|
80 | + */ |
|
81 | + protected $useTransactions = true; |
|
82 | + |
|
83 | + /** |
|
84 | + * @var \OCP\Lock\ILockingProvider |
|
85 | + */ |
|
86 | + protected $lockingProvider; |
|
87 | + |
|
88 | + public function __construct(\OC\Files\Storage\Storage $storage) { |
|
89 | + $this->storage = $storage; |
|
90 | + $this->storageId = $this->storage->getId(); |
|
91 | + $this->cache = $storage->getCache(); |
|
92 | + $this->cacheActive = !Config::getSystemValue('filesystem_cache_readonly', false); |
|
93 | + $this->lockingProvider = \OC::$server->getLockingProvider(); |
|
94 | + } |
|
95 | + |
|
96 | + /** |
|
97 | + * Whether to wrap the scanning of a folder in a database transaction |
|
98 | + * On default transactions are used |
|
99 | + * |
|
100 | + * @param bool $useTransactions |
|
101 | + */ |
|
102 | + public function setUseTransactions($useTransactions) { |
|
103 | + $this->useTransactions = $useTransactions; |
|
104 | + } |
|
105 | + |
|
106 | + /** |
|
107 | + * get all the metadata of a file or folder |
|
108 | + * * |
|
109 | + * |
|
110 | + * @param string $path |
|
111 | + * @return array an array of metadata of the file |
|
112 | + */ |
|
113 | + protected function getData($path) { |
|
114 | + $data = $this->storage->getMetaData($path); |
|
115 | + if (is_null($data)) { |
|
116 | + \OCP\Util::writeLog('OC\Files\Cache\Scanner', "!!! Path '$path' is not accessible or present !!!", \OCP\Util::DEBUG); |
|
117 | + } |
|
118 | + return $data; |
|
119 | + } |
|
120 | + |
|
121 | + /** |
|
122 | + * scan a single file and store it in the cache |
|
123 | + * |
|
124 | + * @param string $file |
|
125 | + * @param int $reuseExisting |
|
126 | + * @param int $parentId |
|
127 | + * @param array | null $cacheData existing data in the cache for the file to be scanned |
|
128 | + * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
129 | + * @return array an array of metadata of the scanned file |
|
130 | + * @throws \OC\ServerNotAvailableException |
|
131 | + * @throws \OCP\Lock\LockedException |
|
132 | + */ |
|
133 | + public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) { |
|
134 | + if ($file !== '') { |
|
135 | + try { |
|
136 | + $this->storage->verifyPath(dirname($file), basename($file)); |
|
137 | + } catch (\Exception $e) { |
|
138 | + return null; |
|
139 | + } |
|
140 | + } |
|
141 | + |
|
142 | + // only proceed if $file is not a partial file nor a blacklisted file |
|
143 | + if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) { |
|
144 | + |
|
145 | + //acquire a lock |
|
146 | + if ($lock) { |
|
147 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
148 | + $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
149 | + } |
|
150 | + } |
|
151 | + |
|
152 | + try { |
|
153 | + $data = $this->getData($file); |
|
154 | + } catch (ForbiddenException $e) { |
|
155 | + return null; |
|
156 | + } |
|
157 | + |
|
158 | + if ($data) { |
|
159 | + |
|
160 | + // pre-emit only if it was a file. By that we avoid counting/treating folders as files |
|
161 | + if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
162 | + $this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId)); |
|
163 | + \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
164 | + } |
|
165 | + |
|
166 | + $parent = dirname($file); |
|
167 | + if ($parent === '.' or $parent === '/') { |
|
168 | + $parent = ''; |
|
169 | + } |
|
170 | + if ($parentId === -1) { |
|
171 | + $parentId = $this->cache->getParentId($file); |
|
172 | + } |
|
173 | + |
|
174 | + // scan the parent if it's not in the cache (id -1) and the current file is not the root folder |
|
175 | + if ($file and $parentId === -1) { |
|
176 | + $parentData = $this->scanFile($parent); |
|
177 | + if (!$parentData) { |
|
178 | + return null; |
|
179 | + } |
|
180 | + $parentId = $parentData['fileid']; |
|
181 | + } |
|
182 | + if ($parent) { |
|
183 | + $data['parent'] = $parentId; |
|
184 | + } |
|
185 | + if (is_null($cacheData)) { |
|
186 | + /** @var CacheEntry $cacheData */ |
|
187 | + $cacheData = $this->cache->get($file); |
|
188 | + } |
|
189 | + if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) { |
|
190 | + // prevent empty etag |
|
191 | + if (empty($cacheData['etag'])) { |
|
192 | + $etag = $data['etag']; |
|
193 | + } else { |
|
194 | + $etag = $cacheData['etag']; |
|
195 | + } |
|
196 | + $fileId = $cacheData['fileid']; |
|
197 | + $data['fileid'] = $fileId; |
|
198 | + // only reuse data if the file hasn't explicitly changed |
|
199 | + if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) { |
|
200 | + $data['mtime'] = $cacheData['mtime']; |
|
201 | + if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) { |
|
202 | + $data['size'] = $cacheData['size']; |
|
203 | + } |
|
204 | + if ($reuseExisting & self::REUSE_ETAG) { |
|
205 | + $data['etag'] = $etag; |
|
206 | + } |
|
207 | + } |
|
208 | + // Only update metadata that has changed |
|
209 | + $newData = array_diff_assoc($data, $cacheData->getData()); |
|
210 | + } else { |
|
211 | + $newData = $data; |
|
212 | + $fileId = -1; |
|
213 | + } |
|
214 | + if (!empty($newData)) { |
|
215 | + // Reset the checksum if the data has changed |
|
216 | + $newData['checksum'] = ''; |
|
217 | + $data['fileid'] = $this->addToCache($file, $newData, $fileId); |
|
218 | + } |
|
219 | + if (isset($cacheData['size'])) { |
|
220 | + $data['oldSize'] = $cacheData['size']; |
|
221 | + } else { |
|
222 | + $data['oldSize'] = 0; |
|
223 | + } |
|
224 | + |
|
225 | + if (isset($cacheData['encrypted'])) { |
|
226 | + $data['encrypted'] = $cacheData['encrypted']; |
|
227 | + } |
|
228 | + |
|
229 | + // post-emit only if it was a file. By that we avoid counting/treating folders as files |
|
230 | + if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
231 | + $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId)); |
|
232 | + \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
233 | + } |
|
234 | + |
|
235 | + } else { |
|
236 | + $this->removeFromCache($file); |
|
237 | + } |
|
238 | + |
|
239 | + //release the acquired lock |
|
240 | + if ($lock) { |
|
241 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
242 | + $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
243 | + } |
|
244 | + } |
|
245 | + |
|
246 | + if ($data && !isset($data['encrypted'])) { |
|
247 | + $data['encrypted'] = false; |
|
248 | + } |
|
249 | + return $data; |
|
250 | + } |
|
251 | + |
|
252 | + return null; |
|
253 | + } |
|
254 | + |
|
255 | + protected function removeFromCache($path) { |
|
256 | + \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path)); |
|
257 | + $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path)); |
|
258 | + if ($this->cacheActive) { |
|
259 | + $this->cache->remove($path); |
|
260 | + } |
|
261 | + } |
|
262 | + |
|
263 | + /** |
|
264 | + * @param string $path |
|
265 | + * @param array $data |
|
266 | + * @param int $fileId |
|
267 | + * @return int the id of the added file |
|
268 | + */ |
|
269 | + protected function addToCache($path, $data, $fileId = -1) { |
|
270 | + \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
271 | + $this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data)); |
|
272 | + if ($this->cacheActive) { |
|
273 | + if ($fileId !== -1) { |
|
274 | + $this->cache->update($fileId, $data); |
|
275 | + return $fileId; |
|
276 | + } else { |
|
277 | + return $this->cache->put($path, $data); |
|
278 | + } |
|
279 | + } else { |
|
280 | + return -1; |
|
281 | + } |
|
282 | + } |
|
283 | + |
|
284 | + /** |
|
285 | + * @param string $path |
|
286 | + * @param array $data |
|
287 | + * @param int $fileId |
|
288 | + */ |
|
289 | + protected function updateCache($path, $data, $fileId = -1) { |
|
290 | + \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
291 | + $this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data)); |
|
292 | + if ($this->cacheActive) { |
|
293 | + if ($fileId !== -1) { |
|
294 | + $this->cache->update($fileId, $data); |
|
295 | + } else { |
|
296 | + $this->cache->put($path, $data); |
|
297 | + } |
|
298 | + } |
|
299 | + } |
|
300 | + |
|
301 | + /** |
|
302 | + * scan a folder and all it's children |
|
303 | + * |
|
304 | + * @param string $path |
|
305 | + * @param bool $recursive |
|
306 | + * @param int $reuse |
|
307 | + * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
308 | + * @return array an array of the meta data of the scanned file or folder |
|
309 | + */ |
|
310 | + public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) { |
|
311 | + if ($reuse === -1) { |
|
312 | + $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
313 | + } |
|
314 | + if ($lock) { |
|
315 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
316 | + $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
317 | + $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
318 | + } |
|
319 | + } |
|
320 | + $data = $this->scanFile($path, $reuse, -1, null, $lock); |
|
321 | + if ($data and $data['mimetype'] === 'httpd/unix-directory') { |
|
322 | + $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock); |
|
323 | + $data['size'] = $size; |
|
324 | + } |
|
325 | + if ($lock) { |
|
326 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
327 | + $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
328 | + $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
329 | + } |
|
330 | + } |
|
331 | + return $data; |
|
332 | + } |
|
333 | + |
|
334 | + /** |
|
335 | + * Get the children currently in the cache |
|
336 | + * |
|
337 | + * @param int $folderId |
|
338 | + * @return array[] |
|
339 | + */ |
|
340 | + protected function getExistingChildren($folderId) { |
|
341 | + $existingChildren = array(); |
|
342 | + $children = $this->cache->getFolderContentsById($folderId); |
|
343 | + foreach ($children as $child) { |
|
344 | + $existingChildren[$child['name']] = $child; |
|
345 | + } |
|
346 | + return $existingChildren; |
|
347 | + } |
|
348 | + |
|
349 | + /** |
|
350 | + * Get the children from the storage |
|
351 | + * |
|
352 | + * @param string $folder |
|
353 | + * @return string[] |
|
354 | + */ |
|
355 | + protected function getNewChildren($folder) { |
|
356 | + $children = array(); |
|
357 | + if ($dh = $this->storage->opendir($folder)) { |
|
358 | + if (is_resource($dh)) { |
|
359 | + while (($file = readdir($dh)) !== false) { |
|
360 | + if (!Filesystem::isIgnoredDir($file)) { |
|
361 | + $children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/'); |
|
362 | + } |
|
363 | + } |
|
364 | + } |
|
365 | + } |
|
366 | + return $children; |
|
367 | + } |
|
368 | + |
|
369 | + /** |
|
370 | + * scan all the files and folders in a folder |
|
371 | + * |
|
372 | + * @param string $path |
|
373 | + * @param bool $recursive |
|
374 | + * @param int $reuse |
|
375 | + * @param int $folderId id for the folder to be scanned |
|
376 | + * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
377 | + * @return int the size of the scanned folder or -1 if the size is unknown at this stage |
|
378 | + */ |
|
379 | + protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) { |
|
380 | + if ($reuse === -1) { |
|
381 | + $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
382 | + } |
|
383 | + $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId)); |
|
384 | + $size = 0; |
|
385 | + if (!is_null($folderId)) { |
|
386 | + $folderId = $this->cache->getId($path); |
|
387 | + } |
|
388 | + $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size); |
|
389 | + |
|
390 | + foreach ($childQueue as $child => $childId) { |
|
391 | + $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock); |
|
392 | + if ($childSize === -1) { |
|
393 | + $size = -1; |
|
394 | + } else if ($size !== -1) { |
|
395 | + $size += $childSize; |
|
396 | + } |
|
397 | + } |
|
398 | + if ($this->cacheActive) { |
|
399 | + $this->cache->update($folderId, array('size' => $size)); |
|
400 | + } |
|
401 | + $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId)); |
|
402 | + return $size; |
|
403 | + } |
|
404 | + |
|
405 | + private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) { |
|
406 | + // we put this in it's own function so it cleans up the memory before we start recursing |
|
407 | + $existingChildren = $this->getExistingChildren($folderId); |
|
408 | + $newChildren = $this->getNewChildren($path); |
|
409 | + |
|
410 | + if ($this->useTransactions) { |
|
411 | + \OC::$server->getDatabaseConnection()->beginTransaction(); |
|
412 | + } |
|
413 | + |
|
414 | + $exceptionOccurred = false; |
|
415 | + $childQueue = []; |
|
416 | + foreach ($newChildren as $file) { |
|
417 | + $child = ($path) ? $path . '/' . $file : $file; |
|
418 | + try { |
|
419 | + $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null; |
|
420 | + $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock); |
|
421 | + if ($data) { |
|
422 | + if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) { |
|
423 | + $childQueue[$child] = $data['fileid']; |
|
424 | + } else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) { |
|
425 | + // only recurse into folders which aren't fully scanned |
|
426 | + $childQueue[$child] = $data['fileid']; |
|
427 | + } else if ($data['size'] === -1) { |
|
428 | + $size = -1; |
|
429 | + } else if ($size !== -1) { |
|
430 | + $size += $data['size']; |
|
431 | + } |
|
432 | + } |
|
433 | + } catch (\Doctrine\DBAL\DBALException $ex) { |
|
434 | + // might happen if inserting duplicate while a scanning |
|
435 | + // process is running in parallel |
|
436 | + // log and ignore |
|
437 | + \OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG); |
|
438 | + $exceptionOccurred = true; |
|
439 | + } catch (\OCP\Lock\LockedException $e) { |
|
440 | + if ($this->useTransactions) { |
|
441 | + \OC::$server->getDatabaseConnection()->rollback(); |
|
442 | + } |
|
443 | + throw $e; |
|
444 | + } |
|
445 | + } |
|
446 | + $removedChildren = \array_diff(array_keys($existingChildren), $newChildren); |
|
447 | + foreach ($removedChildren as $childName) { |
|
448 | + $child = ($path) ? $path . '/' . $childName : $childName; |
|
449 | + $this->removeFromCache($child); |
|
450 | + } |
|
451 | + if ($this->useTransactions) { |
|
452 | + \OC::$server->getDatabaseConnection()->commit(); |
|
453 | + } |
|
454 | + if ($exceptionOccurred) { |
|
455 | + // It might happen that the parallel scan process has already |
|
456 | + // inserted mimetypes but those weren't available yet inside the transaction |
|
457 | + // To make sure to have the updated mime types in such cases, |
|
458 | + // we reload them here |
|
459 | + \OC::$server->getMimeTypeLoader()->reset(); |
|
460 | + } |
|
461 | + return $childQueue; |
|
462 | + } |
|
463 | + |
|
464 | + /** |
|
465 | + * check if the file should be ignored when scanning |
|
466 | + * NOTE: files with a '.part' extension are ignored as well! |
|
467 | + * prevents unfinished put requests to be scanned |
|
468 | + * |
|
469 | + * @param string $file |
|
470 | + * @return boolean |
|
471 | + */ |
|
472 | + public static function isPartialFile($file) { |
|
473 | + if (pathinfo($file, PATHINFO_EXTENSION) === 'part') { |
|
474 | + return true; |
|
475 | + } |
|
476 | + if (strpos($file, '.part/') !== false) { |
|
477 | + return true; |
|
478 | + } |
|
479 | + |
|
480 | + return false; |
|
481 | + } |
|
482 | + |
|
483 | + /** |
|
484 | + * walk over any folders that are not fully scanned yet and scan them |
|
485 | + */ |
|
486 | + public function backgroundScan() { |
|
487 | + if (!$this->cache->inCache('')) { |
|
488 | + $this->runBackgroundScanJob(function () { |
|
489 | + $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG); |
|
490 | + }, ''); |
|
491 | + } else { |
|
492 | + $lastPath = null; |
|
493 | + while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { |
|
494 | + $this->runBackgroundScanJob(function () use ($path) { |
|
495 | + $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE); |
|
496 | + }, $path); |
|
497 | + // FIXME: this won't proceed with the next item, needs revamping of getIncomplete() |
|
498 | + // to make this possible |
|
499 | + $lastPath = $path; |
|
500 | + } |
|
501 | + } |
|
502 | + } |
|
503 | + |
|
504 | + private function runBackgroundScanJob(callable $callback, $path) { |
|
505 | + try { |
|
506 | + $callback(); |
|
507 | + \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path)); |
|
508 | + if ($this->cacheActive && $this->cache instanceof Cache) { |
|
509 | + $this->cache->correctFolderSize($path); |
|
510 | + } |
|
511 | + } catch (\OCP\Files\StorageInvalidException $e) { |
|
512 | + // skip unavailable storages |
|
513 | + } catch (\OCP\Files\StorageNotAvailableException $e) { |
|
514 | + // skip unavailable storages |
|
515 | + } catch (\OCP\Files\ForbiddenException $e) { |
|
516 | + // skip forbidden storages |
|
517 | + } catch (\OCP\Lock\LockedException $e) { |
|
518 | + // skip unavailable storages |
|
519 | + } |
|
520 | + } |
|
521 | + |
|
522 | + /** |
|
523 | + * Set whether the cache is affected by scan operations |
|
524 | + * |
|
525 | + * @param boolean $active The active state of the cache |
|
526 | + */ |
|
527 | + public function setCacheActive($active) { |
|
528 | + $this->cacheActive = $active; |
|
529 | + } |
|
530 | 530 | } |
@@ -313,7 +313,7 @@ discard block |
||
313 | 313 | } |
314 | 314 | if ($lock) { |
315 | 315 | if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
316 | - $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
316 | + $this->storage->acquireLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
317 | 317 | $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
318 | 318 | } |
319 | 319 | } |
@@ -325,7 +325,7 @@ discard block |
||
325 | 325 | if ($lock) { |
326 | 326 | if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
327 | 327 | $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
328 | - $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
328 | + $this->storage->releaseLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
329 | 329 | } |
330 | 330 | } |
331 | 331 | return $data; |
@@ -414,7 +414,7 @@ discard block |
||
414 | 414 | $exceptionOccurred = false; |
415 | 415 | $childQueue = []; |
416 | 416 | foreach ($newChildren as $file) { |
417 | - $child = ($path) ? $path . '/' . $file : $file; |
|
417 | + $child = ($path) ? $path.'/'.$file : $file; |
|
418 | 418 | try { |
419 | 419 | $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null; |
420 | 420 | $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock); |
@@ -434,7 +434,7 @@ discard block |
||
434 | 434 | // might happen if inserting duplicate while a scanning |
435 | 435 | // process is running in parallel |
436 | 436 | // log and ignore |
437 | - \OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG); |
|
437 | + \OCP\Util::writeLog('core', 'Exception while scanning file "'.$child.'": '.$ex->getMessage(), \OCP\Util::DEBUG); |
|
438 | 438 | $exceptionOccurred = true; |
439 | 439 | } catch (\OCP\Lock\LockedException $e) { |
440 | 440 | if ($this->useTransactions) { |
@@ -445,7 +445,7 @@ discard block |
||
445 | 445 | } |
446 | 446 | $removedChildren = \array_diff(array_keys($existingChildren), $newChildren); |
447 | 447 | foreach ($removedChildren as $childName) { |
448 | - $child = ($path) ? $path . '/' . $childName : $childName; |
|
448 | + $child = ($path) ? $path.'/'.$childName : $childName; |
|
449 | 449 | $this->removeFromCache($child); |
450 | 450 | } |
451 | 451 | if ($this->useTransactions) { |
@@ -485,13 +485,13 @@ discard block |
||
485 | 485 | */ |
486 | 486 | public function backgroundScan() { |
487 | 487 | if (!$this->cache->inCache('')) { |
488 | - $this->runBackgroundScanJob(function () { |
|
488 | + $this->runBackgroundScanJob(function() { |
|
489 | 489 | $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG); |
490 | 490 | }, ''); |
491 | 491 | } else { |
492 | 492 | $lastPath = null; |
493 | 493 | while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { |
494 | - $this->runBackgroundScanJob(function () use ($path) { |
|
494 | + $this->runBackgroundScanJob(function() use ($path) { |
|
495 | 495 | $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE); |
496 | 496 | }, $path); |
497 | 497 | // FIXME: this won't proceed with the next item, needs revamping of getIncomplete() |
@@ -206,7 +206,7 @@ |
||
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 | */ |
@@ -44,295 +44,295 @@ |
||
44 | 44 | * Cache mounts points per user in the cache so we can easilly look them up |
45 | 45 | */ |
46 | 46 | class UserMountCache implements IUserMountCache { |
47 | - /** |
|
48 | - * @var IDBConnection |
|
49 | - */ |
|
50 | - private $connection; |
|
51 | - |
|
52 | - /** |
|
53 | - * @var IUserManager |
|
54 | - */ |
|
55 | - private $userManager; |
|
56 | - |
|
57 | - /** |
|
58 | - * Cached mount info. |
|
59 | - * Map of $userId to ICachedMountInfo. |
|
60 | - * |
|
61 | - * @var ICache |
|
62 | - **/ |
|
63 | - private $mountsForUsers; |
|
64 | - |
|
65 | - /** |
|
66 | - * @var ILogger |
|
67 | - */ |
|
68 | - private $logger; |
|
69 | - |
|
70 | - /** |
|
71 | - * @var ICache |
|
72 | - */ |
|
73 | - private $cacheInfoCache; |
|
74 | - |
|
75 | - /** |
|
76 | - * UserMountCache constructor. |
|
77 | - * |
|
78 | - * @param IDBConnection $connection |
|
79 | - * @param IUserManager $userManager |
|
80 | - * @param ILogger $logger |
|
81 | - */ |
|
82 | - public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) { |
|
83 | - $this->connection = $connection; |
|
84 | - $this->userManager = $userManager; |
|
85 | - $this->logger = $logger; |
|
86 | - $this->cacheInfoCache = new CappedMemoryCache(); |
|
87 | - $this->mountsForUsers = new CappedMemoryCache(); |
|
88 | - } |
|
89 | - |
|
90 | - public function registerMounts(IUser $user, array $mounts) { |
|
91 | - // filter out non-proper storages coming from unit tests |
|
92 | - $mounts = array_filter($mounts, function (IMountPoint $mount) { |
|
93 | - return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache(); |
|
94 | - }); |
|
95 | - /** @var ICachedMountInfo[] $newMounts */ |
|
96 | - $newMounts = array_map(function (IMountPoint $mount) use ($user) { |
|
97 | - // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet) |
|
98 | - if ($mount->getStorageRootId() === -1) { |
|
99 | - return null; |
|
100 | - } else { |
|
101 | - return new LazyStorageMountInfo($user, $mount); |
|
102 | - } |
|
103 | - }, $mounts); |
|
104 | - $newMounts = array_values(array_filter($newMounts)); |
|
105 | - |
|
106 | - $cachedMounts = $this->getMountsForUser($user); |
|
107 | - $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) { |
|
108 | - // since we are only looking for mounts for a specific user comparing on root id is enough |
|
109 | - return $mount1->getRootId() - $mount2->getRootId(); |
|
110 | - }; |
|
111 | - |
|
112 | - /** @var ICachedMountInfo[] $addedMounts */ |
|
113 | - $addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff); |
|
114 | - /** @var ICachedMountInfo[] $removedMounts */ |
|
115 | - $removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff); |
|
116 | - |
|
117 | - $changedMounts = $this->findChangedMounts($newMounts, $cachedMounts); |
|
118 | - |
|
119 | - foreach ($addedMounts as $mount) { |
|
120 | - $this->addToCache($mount); |
|
121 | - $this->mountsForUsers[$user->getUID()][] = $mount; |
|
122 | - } |
|
123 | - foreach ($removedMounts as $mount) { |
|
124 | - $this->removeFromCache($mount); |
|
125 | - $index = array_search($mount, $this->mountsForUsers[$user->getUID()]); |
|
126 | - unset($this->mountsForUsers[$user->getUID()][$index]); |
|
127 | - } |
|
128 | - foreach ($changedMounts as $mount) { |
|
129 | - $this->updateCachedMount($mount); |
|
130 | - } |
|
131 | - } |
|
132 | - |
|
133 | - /** |
|
134 | - * @param ICachedMountInfo[] $newMounts |
|
135 | - * @param ICachedMountInfo[] $cachedMounts |
|
136 | - * @return ICachedMountInfo[] |
|
137 | - */ |
|
138 | - private function findChangedMounts(array $newMounts, array $cachedMounts) { |
|
139 | - $changed = []; |
|
140 | - foreach ($newMounts as $newMount) { |
|
141 | - foreach ($cachedMounts as $cachedMount) { |
|
142 | - if ( |
|
143 | - $newMount->getRootId() === $cachedMount->getRootId() && |
|
144 | - ( |
|
145 | - $newMount->getMountPoint() !== $cachedMount->getMountPoint() || |
|
146 | - $newMount->getStorageId() !== $cachedMount->getStorageId() || |
|
147 | - $newMount->getMountId() !== $cachedMount->getMountId() |
|
148 | - ) |
|
149 | - ) { |
|
150 | - $changed[] = $newMount; |
|
151 | - } |
|
152 | - } |
|
153 | - } |
|
154 | - return $changed; |
|
155 | - } |
|
156 | - |
|
157 | - private function addToCache(ICachedMountInfo $mount) { |
|
158 | - if ($mount->getStorageId() !== -1) { |
|
159 | - $this->connection->insertIfNotExist('*PREFIX*mounts', [ |
|
160 | - 'storage_id' => $mount->getStorageId(), |
|
161 | - 'root_id' => $mount->getRootId(), |
|
162 | - 'user_id' => $mount->getUser()->getUID(), |
|
163 | - 'mount_point' => $mount->getMountPoint(), |
|
164 | - 'mount_id' => $mount->getMountId() |
|
165 | - ], ['root_id', 'user_id']); |
|
166 | - } else { |
|
167 | - // in some cases this is legitimate, like orphaned shares |
|
168 | - $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint()); |
|
169 | - } |
|
170 | - } |
|
171 | - |
|
172 | - private function updateCachedMount(ICachedMountInfo $mount) { |
|
173 | - $builder = $this->connection->getQueryBuilder(); |
|
174 | - |
|
175 | - $query = $builder->update('mounts') |
|
176 | - ->set('storage_id', $builder->createNamedParameter($mount->getStorageId())) |
|
177 | - ->set('mount_point', $builder->createNamedParameter($mount->getMountPoint())) |
|
178 | - ->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT)) |
|
179 | - ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID()))) |
|
180 | - ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT))); |
|
181 | - |
|
182 | - $query->execute(); |
|
183 | - } |
|
184 | - |
|
185 | - private function removeFromCache(ICachedMountInfo $mount) { |
|
186 | - $builder = $this->connection->getQueryBuilder(); |
|
187 | - |
|
188 | - $query = $builder->delete('mounts') |
|
189 | - ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID()))) |
|
190 | - ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT))); |
|
191 | - $query->execute(); |
|
192 | - } |
|
193 | - |
|
194 | - private function dbRowToMountInfo(array $row) { |
|
195 | - $user = $this->userManager->get($row['user_id']); |
|
196 | - if (is_null($user)) { |
|
197 | - return null; |
|
198 | - } |
|
199 | - return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path'])? $row['path']:''); |
|
200 | - } |
|
201 | - |
|
202 | - /** |
|
203 | - * @param IUser $user |
|
204 | - * @return ICachedMountInfo[] |
|
205 | - */ |
|
206 | - public function getMountsForUser(IUser $user) { |
|
207 | - if (!isset($this->mountsForUsers[$user->getUID()])) { |
|
208 | - $builder = $this->connection->getQueryBuilder(); |
|
209 | - $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
210 | - ->from('mounts', 'm') |
|
211 | - ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
212 | - ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID()))); |
|
213 | - |
|
214 | - $rows = $query->execute()->fetchAll(); |
|
215 | - |
|
216 | - $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
217 | - } |
|
218 | - return $this->mountsForUsers[$user->getUID()]; |
|
219 | - } |
|
220 | - |
|
221 | - /** |
|
222 | - * @param int $numericStorageId |
|
223 | - * @param string|null $user limit the results to a single user |
|
224 | - * @return CachedMountInfo[] |
|
225 | - */ |
|
226 | - public function getMountsForStorageId($numericStorageId, $user = null) { |
|
227 | - $builder = $this->connection->getQueryBuilder(); |
|
228 | - $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
229 | - ->from('mounts', 'm') |
|
230 | - ->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
231 | - ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT))); |
|
232 | - |
|
233 | - if ($user) { |
|
234 | - $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user))); |
|
235 | - } |
|
236 | - |
|
237 | - $rows = $query->execute()->fetchAll(); |
|
238 | - |
|
239 | - return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
240 | - } |
|
241 | - |
|
242 | - /** |
|
243 | - * @param int $rootFileId |
|
244 | - * @return CachedMountInfo[] |
|
245 | - */ |
|
246 | - public function getMountsForRootId($rootFileId) { |
|
247 | - $builder = $this->connection->getQueryBuilder(); |
|
248 | - $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
249 | - ->from('mounts', 'm') |
|
250 | - ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
251 | - ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT))); |
|
252 | - |
|
253 | - $rows = $query->execute()->fetchAll(); |
|
254 | - |
|
255 | - return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
256 | - } |
|
257 | - |
|
258 | - /** |
|
259 | - * @param $fileId |
|
260 | - * @return array |
|
261 | - * @throws \OCP\Files\NotFoundException |
|
262 | - */ |
|
263 | - private function getCacheInfoFromFileId($fileId) { |
|
264 | - if (!isset($this->cacheInfoCache[$fileId])) { |
|
265 | - $builder = $this->connection->getQueryBuilder(); |
|
266 | - $query = $builder->select('storage', 'path', 'mimetype') |
|
267 | - ->from('filecache') |
|
268 | - ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT))); |
|
269 | - |
|
270 | - $row = $query->execute()->fetch(); |
|
271 | - if (is_array($row)) { |
|
272 | - $this->cacheInfoCache[$fileId] = [ |
|
273 | - (int)$row['storage'], |
|
274 | - $row['path'], |
|
275 | - (int)$row['mimetype'] |
|
276 | - ]; |
|
277 | - } else { |
|
278 | - throw new NotFoundException('File with id "' . $fileId . '" not found'); |
|
279 | - } |
|
280 | - } |
|
281 | - return $this->cacheInfoCache[$fileId]; |
|
282 | - } |
|
283 | - |
|
284 | - /** |
|
285 | - * @param int $fileId |
|
286 | - * @param string|null $user optionally restrict the results to a single user |
|
287 | - * @return ICachedMountInfo[] |
|
288 | - * @since 9.0.0 |
|
289 | - */ |
|
290 | - public function getMountsForFileId($fileId, $user = null) { |
|
291 | - try { |
|
292 | - list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId); |
|
293 | - } catch (NotFoundException $e) { |
|
294 | - return []; |
|
295 | - } |
|
296 | - $mountsForStorage = $this->getMountsForStorageId($storageId, $user); |
|
297 | - |
|
298 | - // filter mounts that are from the same storage but a different directory |
|
299 | - return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
300 | - if ($fileId === $mount->getRootId()) { |
|
301 | - return true; |
|
302 | - } |
|
303 | - $internalMountPath = $mount->getRootInternalPath(); |
|
304 | - |
|
305 | - return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/'; |
|
306 | - }); |
|
307 | - } |
|
308 | - |
|
309 | - /** |
|
310 | - * Remove all cached mounts for a user |
|
311 | - * |
|
312 | - * @param IUser $user |
|
313 | - */ |
|
314 | - public function removeUserMounts(IUser $user) { |
|
315 | - $builder = $this->connection->getQueryBuilder(); |
|
316 | - |
|
317 | - $query = $builder->delete('mounts') |
|
318 | - ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID()))); |
|
319 | - $query->execute(); |
|
320 | - } |
|
321 | - |
|
322 | - public function removeUserStorageMount($storageId, $userId) { |
|
323 | - $builder = $this->connection->getQueryBuilder(); |
|
324 | - |
|
325 | - $query = $builder->delete('mounts') |
|
326 | - ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId))) |
|
327 | - ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
328 | - $query->execute(); |
|
329 | - } |
|
330 | - |
|
331 | - public function remoteStorageMounts($storageId) { |
|
332 | - $builder = $this->connection->getQueryBuilder(); |
|
333 | - |
|
334 | - $query = $builder->delete('mounts') |
|
335 | - ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
336 | - $query->execute(); |
|
337 | - } |
|
47 | + /** |
|
48 | + * @var IDBConnection |
|
49 | + */ |
|
50 | + private $connection; |
|
51 | + |
|
52 | + /** |
|
53 | + * @var IUserManager |
|
54 | + */ |
|
55 | + private $userManager; |
|
56 | + |
|
57 | + /** |
|
58 | + * Cached mount info. |
|
59 | + * Map of $userId to ICachedMountInfo. |
|
60 | + * |
|
61 | + * @var ICache |
|
62 | + **/ |
|
63 | + private $mountsForUsers; |
|
64 | + |
|
65 | + /** |
|
66 | + * @var ILogger |
|
67 | + */ |
|
68 | + private $logger; |
|
69 | + |
|
70 | + /** |
|
71 | + * @var ICache |
|
72 | + */ |
|
73 | + private $cacheInfoCache; |
|
74 | + |
|
75 | + /** |
|
76 | + * UserMountCache constructor. |
|
77 | + * |
|
78 | + * @param IDBConnection $connection |
|
79 | + * @param IUserManager $userManager |
|
80 | + * @param ILogger $logger |
|
81 | + */ |
|
82 | + public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) { |
|
83 | + $this->connection = $connection; |
|
84 | + $this->userManager = $userManager; |
|
85 | + $this->logger = $logger; |
|
86 | + $this->cacheInfoCache = new CappedMemoryCache(); |
|
87 | + $this->mountsForUsers = new CappedMemoryCache(); |
|
88 | + } |
|
89 | + |
|
90 | + public function registerMounts(IUser $user, array $mounts) { |
|
91 | + // filter out non-proper storages coming from unit tests |
|
92 | + $mounts = array_filter($mounts, function (IMountPoint $mount) { |
|
93 | + return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache(); |
|
94 | + }); |
|
95 | + /** @var ICachedMountInfo[] $newMounts */ |
|
96 | + $newMounts = array_map(function (IMountPoint $mount) use ($user) { |
|
97 | + // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet) |
|
98 | + if ($mount->getStorageRootId() === -1) { |
|
99 | + return null; |
|
100 | + } else { |
|
101 | + return new LazyStorageMountInfo($user, $mount); |
|
102 | + } |
|
103 | + }, $mounts); |
|
104 | + $newMounts = array_values(array_filter($newMounts)); |
|
105 | + |
|
106 | + $cachedMounts = $this->getMountsForUser($user); |
|
107 | + $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) { |
|
108 | + // since we are only looking for mounts for a specific user comparing on root id is enough |
|
109 | + return $mount1->getRootId() - $mount2->getRootId(); |
|
110 | + }; |
|
111 | + |
|
112 | + /** @var ICachedMountInfo[] $addedMounts */ |
|
113 | + $addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff); |
|
114 | + /** @var ICachedMountInfo[] $removedMounts */ |
|
115 | + $removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff); |
|
116 | + |
|
117 | + $changedMounts = $this->findChangedMounts($newMounts, $cachedMounts); |
|
118 | + |
|
119 | + foreach ($addedMounts as $mount) { |
|
120 | + $this->addToCache($mount); |
|
121 | + $this->mountsForUsers[$user->getUID()][] = $mount; |
|
122 | + } |
|
123 | + foreach ($removedMounts as $mount) { |
|
124 | + $this->removeFromCache($mount); |
|
125 | + $index = array_search($mount, $this->mountsForUsers[$user->getUID()]); |
|
126 | + unset($this->mountsForUsers[$user->getUID()][$index]); |
|
127 | + } |
|
128 | + foreach ($changedMounts as $mount) { |
|
129 | + $this->updateCachedMount($mount); |
|
130 | + } |
|
131 | + } |
|
132 | + |
|
133 | + /** |
|
134 | + * @param ICachedMountInfo[] $newMounts |
|
135 | + * @param ICachedMountInfo[] $cachedMounts |
|
136 | + * @return ICachedMountInfo[] |
|
137 | + */ |
|
138 | + private function findChangedMounts(array $newMounts, array $cachedMounts) { |
|
139 | + $changed = []; |
|
140 | + foreach ($newMounts as $newMount) { |
|
141 | + foreach ($cachedMounts as $cachedMount) { |
|
142 | + if ( |
|
143 | + $newMount->getRootId() === $cachedMount->getRootId() && |
|
144 | + ( |
|
145 | + $newMount->getMountPoint() !== $cachedMount->getMountPoint() || |
|
146 | + $newMount->getStorageId() !== $cachedMount->getStorageId() || |
|
147 | + $newMount->getMountId() !== $cachedMount->getMountId() |
|
148 | + ) |
|
149 | + ) { |
|
150 | + $changed[] = $newMount; |
|
151 | + } |
|
152 | + } |
|
153 | + } |
|
154 | + return $changed; |
|
155 | + } |
|
156 | + |
|
157 | + private function addToCache(ICachedMountInfo $mount) { |
|
158 | + if ($mount->getStorageId() !== -1) { |
|
159 | + $this->connection->insertIfNotExist('*PREFIX*mounts', [ |
|
160 | + 'storage_id' => $mount->getStorageId(), |
|
161 | + 'root_id' => $mount->getRootId(), |
|
162 | + 'user_id' => $mount->getUser()->getUID(), |
|
163 | + 'mount_point' => $mount->getMountPoint(), |
|
164 | + 'mount_id' => $mount->getMountId() |
|
165 | + ], ['root_id', 'user_id']); |
|
166 | + } else { |
|
167 | + // in some cases this is legitimate, like orphaned shares |
|
168 | + $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint()); |
|
169 | + } |
|
170 | + } |
|
171 | + |
|
172 | + private function updateCachedMount(ICachedMountInfo $mount) { |
|
173 | + $builder = $this->connection->getQueryBuilder(); |
|
174 | + |
|
175 | + $query = $builder->update('mounts') |
|
176 | + ->set('storage_id', $builder->createNamedParameter($mount->getStorageId())) |
|
177 | + ->set('mount_point', $builder->createNamedParameter($mount->getMountPoint())) |
|
178 | + ->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT)) |
|
179 | + ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID()))) |
|
180 | + ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT))); |
|
181 | + |
|
182 | + $query->execute(); |
|
183 | + } |
|
184 | + |
|
185 | + private function removeFromCache(ICachedMountInfo $mount) { |
|
186 | + $builder = $this->connection->getQueryBuilder(); |
|
187 | + |
|
188 | + $query = $builder->delete('mounts') |
|
189 | + ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID()))) |
|
190 | + ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT))); |
|
191 | + $query->execute(); |
|
192 | + } |
|
193 | + |
|
194 | + private function dbRowToMountInfo(array $row) { |
|
195 | + $user = $this->userManager->get($row['user_id']); |
|
196 | + if (is_null($user)) { |
|
197 | + return null; |
|
198 | + } |
|
199 | + return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path'])? $row['path']:''); |
|
200 | + } |
|
201 | + |
|
202 | + /** |
|
203 | + * @param IUser $user |
|
204 | + * @return ICachedMountInfo[] |
|
205 | + */ |
|
206 | + public function getMountsForUser(IUser $user) { |
|
207 | + if (!isset($this->mountsForUsers[$user->getUID()])) { |
|
208 | + $builder = $this->connection->getQueryBuilder(); |
|
209 | + $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
210 | + ->from('mounts', 'm') |
|
211 | + ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
212 | + ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID()))); |
|
213 | + |
|
214 | + $rows = $query->execute()->fetchAll(); |
|
215 | + |
|
216 | + $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
217 | + } |
|
218 | + return $this->mountsForUsers[$user->getUID()]; |
|
219 | + } |
|
220 | + |
|
221 | + /** |
|
222 | + * @param int $numericStorageId |
|
223 | + * @param string|null $user limit the results to a single user |
|
224 | + * @return CachedMountInfo[] |
|
225 | + */ |
|
226 | + public function getMountsForStorageId($numericStorageId, $user = null) { |
|
227 | + $builder = $this->connection->getQueryBuilder(); |
|
228 | + $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
229 | + ->from('mounts', 'm') |
|
230 | + ->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
231 | + ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT))); |
|
232 | + |
|
233 | + if ($user) { |
|
234 | + $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user))); |
|
235 | + } |
|
236 | + |
|
237 | + $rows = $query->execute()->fetchAll(); |
|
238 | + |
|
239 | + return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
240 | + } |
|
241 | + |
|
242 | + /** |
|
243 | + * @param int $rootFileId |
|
244 | + * @return CachedMountInfo[] |
|
245 | + */ |
|
246 | + public function getMountsForRootId($rootFileId) { |
|
247 | + $builder = $this->connection->getQueryBuilder(); |
|
248 | + $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
249 | + ->from('mounts', 'm') |
|
250 | + ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
251 | + ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT))); |
|
252 | + |
|
253 | + $rows = $query->execute()->fetchAll(); |
|
254 | + |
|
255 | + return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
256 | + } |
|
257 | + |
|
258 | + /** |
|
259 | + * @param $fileId |
|
260 | + * @return array |
|
261 | + * @throws \OCP\Files\NotFoundException |
|
262 | + */ |
|
263 | + private function getCacheInfoFromFileId($fileId) { |
|
264 | + if (!isset($this->cacheInfoCache[$fileId])) { |
|
265 | + $builder = $this->connection->getQueryBuilder(); |
|
266 | + $query = $builder->select('storage', 'path', 'mimetype') |
|
267 | + ->from('filecache') |
|
268 | + ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT))); |
|
269 | + |
|
270 | + $row = $query->execute()->fetch(); |
|
271 | + if (is_array($row)) { |
|
272 | + $this->cacheInfoCache[$fileId] = [ |
|
273 | + (int)$row['storage'], |
|
274 | + $row['path'], |
|
275 | + (int)$row['mimetype'] |
|
276 | + ]; |
|
277 | + } else { |
|
278 | + throw new NotFoundException('File with id "' . $fileId . '" not found'); |
|
279 | + } |
|
280 | + } |
|
281 | + return $this->cacheInfoCache[$fileId]; |
|
282 | + } |
|
283 | + |
|
284 | + /** |
|
285 | + * @param int $fileId |
|
286 | + * @param string|null $user optionally restrict the results to a single user |
|
287 | + * @return ICachedMountInfo[] |
|
288 | + * @since 9.0.0 |
|
289 | + */ |
|
290 | + public function getMountsForFileId($fileId, $user = null) { |
|
291 | + try { |
|
292 | + list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId); |
|
293 | + } catch (NotFoundException $e) { |
|
294 | + return []; |
|
295 | + } |
|
296 | + $mountsForStorage = $this->getMountsForStorageId($storageId, $user); |
|
297 | + |
|
298 | + // filter mounts that are from the same storage but a different directory |
|
299 | + return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
300 | + if ($fileId === $mount->getRootId()) { |
|
301 | + return true; |
|
302 | + } |
|
303 | + $internalMountPath = $mount->getRootInternalPath(); |
|
304 | + |
|
305 | + return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/'; |
|
306 | + }); |
|
307 | + } |
|
308 | + |
|
309 | + /** |
|
310 | + * Remove all cached mounts for a user |
|
311 | + * |
|
312 | + * @param IUser $user |
|
313 | + */ |
|
314 | + public function removeUserMounts(IUser $user) { |
|
315 | + $builder = $this->connection->getQueryBuilder(); |
|
316 | + |
|
317 | + $query = $builder->delete('mounts') |
|
318 | + ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID()))); |
|
319 | + $query->execute(); |
|
320 | + } |
|
321 | + |
|
322 | + public function removeUserStorageMount($storageId, $userId) { |
|
323 | + $builder = $this->connection->getQueryBuilder(); |
|
324 | + |
|
325 | + $query = $builder->delete('mounts') |
|
326 | + ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId))) |
|
327 | + ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
328 | + $query->execute(); |
|
329 | + } |
|
330 | + |
|
331 | + public function remoteStorageMounts($storageId) { |
|
332 | + $builder = $this->connection->getQueryBuilder(); |
|
333 | + |
|
334 | + $query = $builder->delete('mounts') |
|
335 | + ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
336 | + $query->execute(); |
|
337 | + } |
|
338 | 338 | } |
@@ -89,11 +89,11 @@ discard block |
||
89 | 89 | |
90 | 90 | public function registerMounts(IUser $user, array $mounts) { |
91 | 91 | // filter out non-proper storages coming from unit tests |
92 | - $mounts = array_filter($mounts, function (IMountPoint $mount) { |
|
92 | + $mounts = array_filter($mounts, function(IMountPoint $mount) { |
|
93 | 93 | return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache(); |
94 | 94 | }); |
95 | 95 | /** @var ICachedMountInfo[] $newMounts */ |
96 | - $newMounts = array_map(function (IMountPoint $mount) use ($user) { |
|
96 | + $newMounts = array_map(function(IMountPoint $mount) use ($user) { |
|
97 | 97 | // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet) |
98 | 98 | if ($mount->getStorageRootId() === -1) { |
99 | 99 | return null; |
@@ -104,7 +104,7 @@ discard block |
||
104 | 104 | $newMounts = array_values(array_filter($newMounts)); |
105 | 105 | |
106 | 106 | $cachedMounts = $this->getMountsForUser($user); |
107 | - $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) { |
|
107 | + $mountDiff = function(ICachedMountInfo $mount1, ICachedMountInfo $mount2) { |
|
108 | 108 | // since we are only looking for mounts for a specific user comparing on root id is enough |
109 | 109 | return $mount1->getRootId() - $mount2->getRootId(); |
110 | 110 | }; |
@@ -165,7 +165,7 @@ discard block |
||
165 | 165 | ], ['root_id', 'user_id']); |
166 | 166 | } else { |
167 | 167 | // in some cases this is legitimate, like orphaned shares |
168 | - $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint()); |
|
168 | + $this->logger->debug('Could not get storage info for mount at '.$mount->getMountPoint()); |
|
169 | 169 | } |
170 | 170 | } |
171 | 171 | |
@@ -196,7 +196,7 @@ discard block |
||
196 | 196 | if (is_null($user)) { |
197 | 197 | return null; |
198 | 198 | } |
199 | - return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path'])? $row['path']:''); |
|
199 | + return new CachedMountInfo($user, (int) $row['storage_id'], (int) $row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path']) ? $row['path'] : ''); |
|
200 | 200 | } |
201 | 201 | |
202 | 202 | /** |
@@ -227,7 +227,7 @@ discard block |
||
227 | 227 | $builder = $this->connection->getQueryBuilder(); |
228 | 228 | $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
229 | 229 | ->from('mounts', 'm') |
230 | - ->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
230 | + ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
231 | 231 | ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT))); |
232 | 232 | |
233 | 233 | if ($user) { |
@@ -270,12 +270,12 @@ discard block |
||
270 | 270 | $row = $query->execute()->fetch(); |
271 | 271 | if (is_array($row)) { |
272 | 272 | $this->cacheInfoCache[$fileId] = [ |
273 | - (int)$row['storage'], |
|
273 | + (int) $row['storage'], |
|
274 | 274 | $row['path'], |
275 | - (int)$row['mimetype'] |
|
275 | + (int) $row['mimetype'] |
|
276 | 276 | ]; |
277 | 277 | } else { |
278 | - throw new NotFoundException('File with id "' . $fileId . '" not found'); |
|
278 | + throw new NotFoundException('File with id "'.$fileId.'" not found'); |
|
279 | 279 | } |
280 | 280 | } |
281 | 281 | return $this->cacheInfoCache[$fileId]; |
@@ -296,13 +296,13 @@ discard block |
||
296 | 296 | $mountsForStorage = $this->getMountsForStorageId($storageId, $user); |
297 | 297 | |
298 | 298 | // filter mounts that are from the same storage but a different directory |
299 | - return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
299 | + return array_filter($mountsForStorage, function(ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
300 | 300 | if ($fileId === $mount->getRootId()) { |
301 | 301 | return true; |
302 | 302 | } |
303 | 303 | $internalMountPath = $mount->getRootInternalPath(); |
304 | 304 | |
305 | - return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/'; |
|
305 | + return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath.'/'; |
|
306 | 306 | }); |
307 | 307 | } |
308 | 308 |
@@ -52,7 +52,7 @@ |
||
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 | */ |
@@ -34,447 +34,447 @@ |
||
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 | } |
@@ -54,6 +54,9 @@ |
||
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, '/'); |
@@ -35,223 +35,223 @@ |
||
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 | } |
@@ -56,7 +56,7 @@ discard block |
||
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 |
||
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 |
||
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 | }); |
@@ -159,7 +159,7 @@ |
||
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) { |
@@ -30,172 +30,172 @@ |
||
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 | } |
@@ -176,7 +176,7 @@ |
||
176 | 176 | * Returns an associative array with all translations |
177 | 177 | * |
178 | 178 | * Called by \OC_L10N_String |
179 | - * @return array |
|
179 | + * @return string[] |
|
180 | 180 | */ |
181 | 181 | public function getTranslations() { |
182 | 182 | return $this->translations; |
@@ -28,190 +28,190 @@ |
||
28 | 28 | |
29 | 29 | class L10N implements IL10N { |
30 | 30 | |
31 | - /** @var IFactory */ |
|
32 | - protected $factory; |
|
33 | - |
|
34 | - /** @var string App of this object */ |
|
35 | - protected $app; |
|
36 | - |
|
37 | - /** @var string Language of this object */ |
|
38 | - protected $lang; |
|
39 | - |
|
40 | - /** @var string Plural forms (string) */ |
|
41 | - private $pluralFormString = 'nplurals=2; plural=(n != 1);'; |
|
42 | - |
|
43 | - /** @var string Plural forms (function) */ |
|
44 | - private $pluralFormFunction = null; |
|
45 | - |
|
46 | - /** @var string[] */ |
|
47 | - private $translations = []; |
|
48 | - |
|
49 | - /** |
|
50 | - * @param IFactory $factory |
|
51 | - * @param string $app |
|
52 | - * @param string $lang |
|
53 | - * @param array $files |
|
54 | - */ |
|
55 | - public function __construct(IFactory $factory, $app, $lang, array $files) { |
|
56 | - $this->factory = $factory; |
|
57 | - $this->app = $app; |
|
58 | - $this->lang = $lang; |
|
59 | - |
|
60 | - $this->translations = []; |
|
61 | - foreach ($files as $languageFile) { |
|
62 | - $this->load($languageFile); |
|
63 | - } |
|
64 | - } |
|
65 | - |
|
66 | - /** |
|
67 | - * The code (en, de, ...) of the language that is used for this instance |
|
68 | - * |
|
69 | - * @return string language |
|
70 | - */ |
|
71 | - public function getLanguageCode() { |
|
72 | - return $this->lang; |
|
73 | - } |
|
74 | - |
|
75 | - /** |
|
76 | - * Translating |
|
77 | - * @param string $text The text we need a translation for |
|
78 | - * @param array $parameters default:array() Parameters for sprintf |
|
79 | - * @return string Translation or the same text |
|
80 | - * |
|
81 | - * Returns the translation. If no translation is found, $text will be |
|
82 | - * returned. |
|
83 | - */ |
|
84 | - public function t($text, $parameters = array()) { |
|
85 | - return (string) new \OC_L10N_String($this, $text, $parameters); |
|
86 | - } |
|
87 | - |
|
88 | - /** |
|
89 | - * Translating |
|
90 | - * @param string $text_singular the string to translate for exactly one object |
|
91 | - * @param string $text_plural the string to translate for n objects |
|
92 | - * @param integer $count Number of objects |
|
93 | - * @param array $parameters default:array() Parameters for sprintf |
|
94 | - * @return string Translation or the same text |
|
95 | - * |
|
96 | - * Returns the translation. If no translation is found, $text will be |
|
97 | - * returned. %n will be replaced with the number of objects. |
|
98 | - * |
|
99 | - * The correct plural is determined by the plural_forms-function |
|
100 | - * provided by the po file. |
|
101 | - * |
|
102 | - */ |
|
103 | - public function n($text_singular, $text_plural, $count, $parameters = array()) { |
|
104 | - $identifier = "_${text_singular}_::_${text_plural}_"; |
|
105 | - if (isset($this->translations[$identifier])) { |
|
106 | - return (string) new \OC_L10N_String($this, $identifier, $parameters, $count); |
|
107 | - } else { |
|
108 | - if ($count === 1) { |
|
109 | - return (string) new \OC_L10N_String($this, $text_singular, $parameters, $count); |
|
110 | - } else { |
|
111 | - return (string) new \OC_L10N_String($this, $text_plural, $parameters, $count); |
|
112 | - } |
|
113 | - } |
|
114 | - } |
|
115 | - |
|
116 | - /** |
|
117 | - * Localization |
|
118 | - * @param string $type Type of localization |
|
119 | - * @param \DateTime|int|string $data parameters for this localization |
|
120 | - * @param array $options |
|
121 | - * @return string|int|false |
|
122 | - * |
|
123 | - * Returns the localized data. |
|
124 | - * |
|
125 | - * Implemented types: |
|
126 | - * - date |
|
127 | - * - Creates a date |
|
128 | - * - params: timestamp (int/string) |
|
129 | - * - datetime |
|
130 | - * - Creates date and time |
|
131 | - * - params: timestamp (int/string) |
|
132 | - * - time |
|
133 | - * - Creates a time |
|
134 | - * - params: timestamp (int/string) |
|
135 | - * - firstday: Returns the first day of the week (0 sunday - 6 saturday) |
|
136 | - * - jsdate: Returns the short JS date format |
|
137 | - */ |
|
138 | - public function l($type, $data = null, $options = array()) { |
|
139 | - // Use the language of the instance |
|
140 | - $locale = $this->getLanguageCode(); |
|
141 | - if ($locale === 'sr@latin') { |
|
142 | - $locale = 'sr_latn'; |
|
143 | - } |
|
144 | - |
|
145 | - if ($type === 'firstday') { |
|
146 | - return (int) Calendar::getFirstWeekday($locale); |
|
147 | - } |
|
148 | - if ($type === 'jsdate') { |
|
149 | - return (string) Calendar::getDateFormat('short', $locale); |
|
150 | - } |
|
151 | - |
|
152 | - $value = new \DateTime(); |
|
153 | - if ($data instanceof \DateTime) { |
|
154 | - $value = $data; |
|
155 | - } else if (is_string($data) && !is_numeric($data)) { |
|
156 | - $data = strtotime($data); |
|
157 | - $value->setTimestamp($data); |
|
158 | - } else if ($data !== null) { |
|
159 | - $value->setTimestamp($data); |
|
160 | - } |
|
161 | - |
|
162 | - $options = array_merge(array('width' => 'long'), $options); |
|
163 | - $width = $options['width']; |
|
164 | - switch ($type) { |
|
165 | - case 'date': |
|
166 | - return (string) Calendar::formatDate($value, $width, $locale); |
|
167 | - case 'datetime': |
|
168 | - return (string) Calendar::formatDatetime($value, $width, $locale); |
|
169 | - case 'time': |
|
170 | - return (string) Calendar::formatTime($value, $width, $locale); |
|
171 | - default: |
|
172 | - return false; |
|
173 | - } |
|
174 | - } |
|
175 | - |
|
176 | - /** |
|
177 | - * Returns an associative array with all translations |
|
178 | - * |
|
179 | - * Called by \OC_L10N_String |
|
180 | - * @return array |
|
181 | - */ |
|
182 | - public function getTranslations() { |
|
183 | - return $this->translations; |
|
184 | - } |
|
185 | - |
|
186 | - /** |
|
187 | - * Returnsed function accepts the argument $n |
|
188 | - * |
|
189 | - * Called by \OC_L10N_String |
|
190 | - * @return string the plural form function |
|
191 | - */ |
|
192 | - public function getPluralFormFunction() { |
|
193 | - if (is_null($this->pluralFormFunction)) { |
|
194 | - $this->pluralFormFunction = $this->factory->createPluralFunction($this->pluralFormString); |
|
195 | - } |
|
196 | - return $this->pluralFormFunction; |
|
197 | - } |
|
198 | - |
|
199 | - /** |
|
200 | - * @param $translationFile |
|
201 | - * @return bool |
|
202 | - */ |
|
203 | - protected function load($translationFile) { |
|
204 | - $json = json_decode(file_get_contents($translationFile), true); |
|
205 | - if (!is_array($json)) { |
|
206 | - $jsonError = json_last_error(); |
|
207 | - \OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']); |
|
208 | - return false; |
|
209 | - } |
|
210 | - |
|
211 | - if (!empty($json['pluralForm'])) { |
|
212 | - $this->pluralFormString = $json['pluralForm']; |
|
213 | - } |
|
214 | - $this->translations = array_merge($this->translations, $json['translations']); |
|
215 | - return true; |
|
216 | - } |
|
31 | + /** @var IFactory */ |
|
32 | + protected $factory; |
|
33 | + |
|
34 | + /** @var string App of this object */ |
|
35 | + protected $app; |
|
36 | + |
|
37 | + /** @var string Language of this object */ |
|
38 | + protected $lang; |
|
39 | + |
|
40 | + /** @var string Plural forms (string) */ |
|
41 | + private $pluralFormString = 'nplurals=2; plural=(n != 1);'; |
|
42 | + |
|
43 | + /** @var string Plural forms (function) */ |
|
44 | + private $pluralFormFunction = null; |
|
45 | + |
|
46 | + /** @var string[] */ |
|
47 | + private $translations = []; |
|
48 | + |
|
49 | + /** |
|
50 | + * @param IFactory $factory |
|
51 | + * @param string $app |
|
52 | + * @param string $lang |
|
53 | + * @param array $files |
|
54 | + */ |
|
55 | + public function __construct(IFactory $factory, $app, $lang, array $files) { |
|
56 | + $this->factory = $factory; |
|
57 | + $this->app = $app; |
|
58 | + $this->lang = $lang; |
|
59 | + |
|
60 | + $this->translations = []; |
|
61 | + foreach ($files as $languageFile) { |
|
62 | + $this->load($languageFile); |
|
63 | + } |
|
64 | + } |
|
65 | + |
|
66 | + /** |
|
67 | + * The code (en, de, ...) of the language that is used for this instance |
|
68 | + * |
|
69 | + * @return string language |
|
70 | + */ |
|
71 | + public function getLanguageCode() { |
|
72 | + return $this->lang; |
|
73 | + } |
|
74 | + |
|
75 | + /** |
|
76 | + * Translating |
|
77 | + * @param string $text The text we need a translation for |
|
78 | + * @param array $parameters default:array() Parameters for sprintf |
|
79 | + * @return string Translation or the same text |
|
80 | + * |
|
81 | + * Returns the translation. If no translation is found, $text will be |
|
82 | + * returned. |
|
83 | + */ |
|
84 | + public function t($text, $parameters = array()) { |
|
85 | + return (string) new \OC_L10N_String($this, $text, $parameters); |
|
86 | + } |
|
87 | + |
|
88 | + /** |
|
89 | + * Translating |
|
90 | + * @param string $text_singular the string to translate for exactly one object |
|
91 | + * @param string $text_plural the string to translate for n objects |
|
92 | + * @param integer $count Number of objects |
|
93 | + * @param array $parameters default:array() Parameters for sprintf |
|
94 | + * @return string Translation or the same text |
|
95 | + * |
|
96 | + * Returns the translation. If no translation is found, $text will be |
|
97 | + * returned. %n will be replaced with the number of objects. |
|
98 | + * |
|
99 | + * The correct plural is determined by the plural_forms-function |
|
100 | + * provided by the po file. |
|
101 | + * |
|
102 | + */ |
|
103 | + public function n($text_singular, $text_plural, $count, $parameters = array()) { |
|
104 | + $identifier = "_${text_singular}_::_${text_plural}_"; |
|
105 | + if (isset($this->translations[$identifier])) { |
|
106 | + return (string) new \OC_L10N_String($this, $identifier, $parameters, $count); |
|
107 | + } else { |
|
108 | + if ($count === 1) { |
|
109 | + return (string) new \OC_L10N_String($this, $text_singular, $parameters, $count); |
|
110 | + } else { |
|
111 | + return (string) new \OC_L10N_String($this, $text_plural, $parameters, $count); |
|
112 | + } |
|
113 | + } |
|
114 | + } |
|
115 | + |
|
116 | + /** |
|
117 | + * Localization |
|
118 | + * @param string $type Type of localization |
|
119 | + * @param \DateTime|int|string $data parameters for this localization |
|
120 | + * @param array $options |
|
121 | + * @return string|int|false |
|
122 | + * |
|
123 | + * Returns the localized data. |
|
124 | + * |
|
125 | + * Implemented types: |
|
126 | + * - date |
|
127 | + * - Creates a date |
|
128 | + * - params: timestamp (int/string) |
|
129 | + * - datetime |
|
130 | + * - Creates date and time |
|
131 | + * - params: timestamp (int/string) |
|
132 | + * - time |
|
133 | + * - Creates a time |
|
134 | + * - params: timestamp (int/string) |
|
135 | + * - firstday: Returns the first day of the week (0 sunday - 6 saturday) |
|
136 | + * - jsdate: Returns the short JS date format |
|
137 | + */ |
|
138 | + public function l($type, $data = null, $options = array()) { |
|
139 | + // Use the language of the instance |
|
140 | + $locale = $this->getLanguageCode(); |
|
141 | + if ($locale === 'sr@latin') { |
|
142 | + $locale = 'sr_latn'; |
|
143 | + } |
|
144 | + |
|
145 | + if ($type === 'firstday') { |
|
146 | + return (int) Calendar::getFirstWeekday($locale); |
|
147 | + } |
|
148 | + if ($type === 'jsdate') { |
|
149 | + return (string) Calendar::getDateFormat('short', $locale); |
|
150 | + } |
|
151 | + |
|
152 | + $value = new \DateTime(); |
|
153 | + if ($data instanceof \DateTime) { |
|
154 | + $value = $data; |
|
155 | + } else if (is_string($data) && !is_numeric($data)) { |
|
156 | + $data = strtotime($data); |
|
157 | + $value->setTimestamp($data); |
|
158 | + } else if ($data !== null) { |
|
159 | + $value->setTimestamp($data); |
|
160 | + } |
|
161 | + |
|
162 | + $options = array_merge(array('width' => 'long'), $options); |
|
163 | + $width = $options['width']; |
|
164 | + switch ($type) { |
|
165 | + case 'date': |
|
166 | + return (string) Calendar::formatDate($value, $width, $locale); |
|
167 | + case 'datetime': |
|
168 | + return (string) Calendar::formatDatetime($value, $width, $locale); |
|
169 | + case 'time': |
|
170 | + return (string) Calendar::formatTime($value, $width, $locale); |
|
171 | + default: |
|
172 | + return false; |
|
173 | + } |
|
174 | + } |
|
175 | + |
|
176 | + /** |
|
177 | + * Returns an associative array with all translations |
|
178 | + * |
|
179 | + * Called by \OC_L10N_String |
|
180 | + * @return array |
|
181 | + */ |
|
182 | + public function getTranslations() { |
|
183 | + return $this->translations; |
|
184 | + } |
|
185 | + |
|
186 | + /** |
|
187 | + * Returnsed function accepts the argument $n |
|
188 | + * |
|
189 | + * Called by \OC_L10N_String |
|
190 | + * @return string the plural form function |
|
191 | + */ |
|
192 | + public function getPluralFormFunction() { |
|
193 | + if (is_null($this->pluralFormFunction)) { |
|
194 | + $this->pluralFormFunction = $this->factory->createPluralFunction($this->pluralFormString); |
|
195 | + } |
|
196 | + return $this->pluralFormFunction; |
|
197 | + } |
|
198 | + |
|
199 | + /** |
|
200 | + * @param $translationFile |
|
201 | + * @return bool |
|
202 | + */ |
|
203 | + protected function load($translationFile) { |
|
204 | + $json = json_decode(file_get_contents($translationFile), true); |
|
205 | + if (!is_array($json)) { |
|
206 | + $jsonError = json_last_error(); |
|
207 | + \OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']); |
|
208 | + return false; |
|
209 | + } |
|
210 | + |
|
211 | + if (!empty($json['pluralForm'])) { |
|
212 | + $this->pluralFormString = $json['pluralForm']; |
|
213 | + } |
|
214 | + $this->translations = array_merge($this->translations, $json['translations']); |
|
215 | + return true; |
|
216 | + } |
|
217 | 217 | } |
@@ -331,7 +331,7 @@ |
||
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) { |
@@ -37,467 +37,467 @@ |
||
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 | - $loginSuccess = $userSession->tryTokenLogin($request); |
|
336 | - if (!$loginSuccess) { |
|
337 | - $loginSuccess = $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler()); |
|
338 | - } |
|
339 | - } catch (\OC\User\LoginException $e) { |
|
340 | - return false; |
|
341 | - } |
|
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 | + $loginSuccess = $userSession->tryTokenLogin($request); |
|
336 | + if (!$loginSuccess) { |
|
337 | + $loginSuccess = $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler()); |
|
338 | + } |
|
339 | + } catch (\OC\User\LoginException $e) { |
|
340 | + return false; |
|
341 | + } |
|
342 | 342 | |
343 | - if ($loginSuccess === true) { |
|
344 | - self::$logoutRequired = true; |
|
345 | - |
|
346 | - // initialize the user's filesystem |
|
347 | - \OC_Util::setupFS(\OC_User::getUser()); |
|
348 | - self::$isLoggedIn = true; |
|
349 | - |
|
350 | - return \OC_User::getUser(); |
|
351 | - } |
|
352 | - |
|
353 | - return false; |
|
354 | - } |
|
355 | - |
|
356 | - /** |
|
357 | - * respond to a call |
|
358 | - * @param OC_OCS_Result $result |
|
359 | - * @param string $format the format xml|json |
|
360 | - */ |
|
361 | - public static function respond($result, $format='xml') { |
|
362 | - $request = \OC::$server->getRequest(); |
|
363 | - |
|
364 | - // Send 401 headers if unauthorised |
|
365 | - if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) { |
|
366 | - // If request comes from JS return dummy auth request |
|
367 | - if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') { |
|
368 | - header('WWW-Authenticate: DummyBasic realm="Authorisation Required"'); |
|
369 | - } else { |
|
370 | - header('WWW-Authenticate: Basic realm="Authorisation Required"'); |
|
371 | - } |
|
372 | - header('HTTP/1.0 401 Unauthorized'); |
|
373 | - } |
|
374 | - |
|
375 | - foreach($result->getHeaders() as $name => $value) { |
|
376 | - header($name . ': ' . $value); |
|
377 | - } |
|
378 | - |
|
379 | - $meta = $result->getMeta(); |
|
380 | - $data = $result->getData(); |
|
381 | - if (self::isV2($request)) { |
|
382 | - $statusCode = self::mapStatusCodes($result->getStatusCode()); |
|
383 | - if (!is_null($statusCode)) { |
|
384 | - $meta['statuscode'] = $statusCode; |
|
385 | - OC_Response::setStatus($statusCode); |
|
386 | - } |
|
387 | - } |
|
388 | - |
|
389 | - self::setContentType($format); |
|
390 | - $body = self::renderResult($format, $meta, $data); |
|
391 | - echo $body; |
|
392 | - } |
|
393 | - |
|
394 | - /** |
|
395 | - * @param XMLWriter $writer |
|
396 | - */ |
|
397 | - private static function toXML($array, $writer) { |
|
398 | - foreach($array as $k => $v) { |
|
399 | - if ($k[0] === '@') { |
|
400 | - $writer->writeAttribute(substr($k, 1), $v); |
|
401 | - continue; |
|
402 | - } else if (is_numeric($k)) { |
|
403 | - $k = 'element'; |
|
404 | - } |
|
405 | - if(is_array($v)) { |
|
406 | - $writer->startElement($k); |
|
407 | - self::toXML($v, $writer); |
|
408 | - $writer->endElement(); |
|
409 | - } else { |
|
410 | - $writer->writeElement($k, $v); |
|
411 | - } |
|
412 | - } |
|
413 | - } |
|
414 | - |
|
415 | - /** |
|
416 | - * @return string |
|
417 | - */ |
|
418 | - public static function requestedFormat() { |
|
419 | - $formats = array('json', 'xml'); |
|
420 | - |
|
421 | - $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml'; |
|
422 | - return $format; |
|
423 | - } |
|
424 | - |
|
425 | - /** |
|
426 | - * Based on the requested format the response content type is set |
|
427 | - * @param string $format |
|
428 | - */ |
|
429 | - public static function setContentType($format = null) { |
|
430 | - $format = is_null($format) ? self::requestedFormat() : $format; |
|
431 | - if ($format === 'xml') { |
|
432 | - header('Content-type: text/xml; charset=UTF-8'); |
|
433 | - return; |
|
434 | - } |
|
435 | - |
|
436 | - if ($format === 'json') { |
|
437 | - header('Content-Type: application/json; charset=utf-8'); |
|
438 | - return; |
|
439 | - } |
|
440 | - |
|
441 | - header('Content-Type: application/octet-stream; charset=utf-8'); |
|
442 | - } |
|
443 | - |
|
444 | - /** |
|
445 | - * @param \OCP\IRequest $request |
|
446 | - * @return bool |
|
447 | - */ |
|
448 | - protected static function isV2(\OCP\IRequest $request) { |
|
449 | - $script = $request->getScriptName(); |
|
450 | - |
|
451 | - return substr($script, -11) === '/ocs/v2.php'; |
|
452 | - } |
|
453 | - |
|
454 | - /** |
|
455 | - * @param integer $sc |
|
456 | - * @return int |
|
457 | - */ |
|
458 | - public static function mapStatusCodes($sc) { |
|
459 | - switch ($sc) { |
|
460 | - case API::RESPOND_NOT_FOUND: |
|
461 | - return Http::STATUS_NOT_FOUND; |
|
462 | - case API::RESPOND_SERVER_ERROR: |
|
463 | - return Http::STATUS_INTERNAL_SERVER_ERROR; |
|
464 | - case API::RESPOND_UNKNOWN_ERROR: |
|
465 | - return Http::STATUS_INTERNAL_SERVER_ERROR; |
|
466 | - case API::RESPOND_UNAUTHORISED: |
|
467 | - // already handled for v1 |
|
468 | - return null; |
|
469 | - case 100: |
|
470 | - return Http::STATUS_OK; |
|
471 | - } |
|
472 | - // any 2xx, 4xx and 5xx will be used as is |
|
473 | - if ($sc >= 200 && $sc < 600) { |
|
474 | - return $sc; |
|
475 | - } |
|
476 | - |
|
477 | - return Http::STATUS_BAD_REQUEST; |
|
478 | - } |
|
479 | - |
|
480 | - /** |
|
481 | - * @param string $format |
|
482 | - * @return string |
|
483 | - */ |
|
484 | - public static function renderResult($format, $meta, $data) { |
|
485 | - $response = array( |
|
486 | - 'ocs' => array( |
|
487 | - 'meta' => $meta, |
|
488 | - 'data' => $data, |
|
489 | - ), |
|
490 | - ); |
|
491 | - if ($format == 'json') { |
|
492 | - return OC_JSON::encode($response); |
|
493 | - } |
|
494 | - |
|
495 | - $writer = new XMLWriter(); |
|
496 | - $writer->openMemory(); |
|
497 | - $writer->setIndent(true); |
|
498 | - $writer->startDocument(); |
|
499 | - self::toXML($response, $writer); |
|
500 | - $writer->endDocument(); |
|
501 | - return $writer->outputMemory(true); |
|
502 | - } |
|
343 | + if ($loginSuccess === true) { |
|
344 | + self::$logoutRequired = true; |
|
345 | + |
|
346 | + // initialize the user's filesystem |
|
347 | + \OC_Util::setupFS(\OC_User::getUser()); |
|
348 | + self::$isLoggedIn = true; |
|
349 | + |
|
350 | + return \OC_User::getUser(); |
|
351 | + } |
|
352 | + |
|
353 | + return false; |
|
354 | + } |
|
355 | + |
|
356 | + /** |
|
357 | + * respond to a call |
|
358 | + * @param OC_OCS_Result $result |
|
359 | + * @param string $format the format xml|json |
|
360 | + */ |
|
361 | + public static function respond($result, $format='xml') { |
|
362 | + $request = \OC::$server->getRequest(); |
|
363 | + |
|
364 | + // Send 401 headers if unauthorised |
|
365 | + if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) { |
|
366 | + // If request comes from JS return dummy auth request |
|
367 | + if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') { |
|
368 | + header('WWW-Authenticate: DummyBasic realm="Authorisation Required"'); |
|
369 | + } else { |
|
370 | + header('WWW-Authenticate: Basic realm="Authorisation Required"'); |
|
371 | + } |
|
372 | + header('HTTP/1.0 401 Unauthorized'); |
|
373 | + } |
|
374 | + |
|
375 | + foreach($result->getHeaders() as $name => $value) { |
|
376 | + header($name . ': ' . $value); |
|
377 | + } |
|
378 | + |
|
379 | + $meta = $result->getMeta(); |
|
380 | + $data = $result->getData(); |
|
381 | + if (self::isV2($request)) { |
|
382 | + $statusCode = self::mapStatusCodes($result->getStatusCode()); |
|
383 | + if (!is_null($statusCode)) { |
|
384 | + $meta['statuscode'] = $statusCode; |
|
385 | + OC_Response::setStatus($statusCode); |
|
386 | + } |
|
387 | + } |
|
388 | + |
|
389 | + self::setContentType($format); |
|
390 | + $body = self::renderResult($format, $meta, $data); |
|
391 | + echo $body; |
|
392 | + } |
|
393 | + |
|
394 | + /** |
|
395 | + * @param XMLWriter $writer |
|
396 | + */ |
|
397 | + private static function toXML($array, $writer) { |
|
398 | + foreach($array as $k => $v) { |
|
399 | + if ($k[0] === '@') { |
|
400 | + $writer->writeAttribute(substr($k, 1), $v); |
|
401 | + continue; |
|
402 | + } else if (is_numeric($k)) { |
|
403 | + $k = 'element'; |
|
404 | + } |
|
405 | + if(is_array($v)) { |
|
406 | + $writer->startElement($k); |
|
407 | + self::toXML($v, $writer); |
|
408 | + $writer->endElement(); |
|
409 | + } else { |
|
410 | + $writer->writeElement($k, $v); |
|
411 | + } |
|
412 | + } |
|
413 | + } |
|
414 | + |
|
415 | + /** |
|
416 | + * @return string |
|
417 | + */ |
|
418 | + public static function requestedFormat() { |
|
419 | + $formats = array('json', 'xml'); |
|
420 | + |
|
421 | + $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml'; |
|
422 | + return $format; |
|
423 | + } |
|
424 | + |
|
425 | + /** |
|
426 | + * Based on the requested format the response content type is set |
|
427 | + * @param string $format |
|
428 | + */ |
|
429 | + public static function setContentType($format = null) { |
|
430 | + $format = is_null($format) ? self::requestedFormat() : $format; |
|
431 | + if ($format === 'xml') { |
|
432 | + header('Content-type: text/xml; charset=UTF-8'); |
|
433 | + return; |
|
434 | + } |
|
435 | + |
|
436 | + if ($format === 'json') { |
|
437 | + header('Content-Type: application/json; charset=utf-8'); |
|
438 | + return; |
|
439 | + } |
|
440 | + |
|
441 | + header('Content-Type: application/octet-stream; charset=utf-8'); |
|
442 | + } |
|
443 | + |
|
444 | + /** |
|
445 | + * @param \OCP\IRequest $request |
|
446 | + * @return bool |
|
447 | + */ |
|
448 | + protected static function isV2(\OCP\IRequest $request) { |
|
449 | + $script = $request->getScriptName(); |
|
450 | + |
|
451 | + return substr($script, -11) === '/ocs/v2.php'; |
|
452 | + } |
|
453 | + |
|
454 | + /** |
|
455 | + * @param integer $sc |
|
456 | + * @return int |
|
457 | + */ |
|
458 | + public static function mapStatusCodes($sc) { |
|
459 | + switch ($sc) { |
|
460 | + case API::RESPOND_NOT_FOUND: |
|
461 | + return Http::STATUS_NOT_FOUND; |
|
462 | + case API::RESPOND_SERVER_ERROR: |
|
463 | + return Http::STATUS_INTERNAL_SERVER_ERROR; |
|
464 | + case API::RESPOND_UNKNOWN_ERROR: |
|
465 | + return Http::STATUS_INTERNAL_SERVER_ERROR; |
|
466 | + case API::RESPOND_UNAUTHORISED: |
|
467 | + // already handled for v1 |
|
468 | + return null; |
|
469 | + case 100: |
|
470 | + return Http::STATUS_OK; |
|
471 | + } |
|
472 | + // any 2xx, 4xx and 5xx will be used as is |
|
473 | + if ($sc >= 200 && $sc < 600) { |
|
474 | + return $sc; |
|
475 | + } |
|
476 | + |
|
477 | + return Http::STATUS_BAD_REQUEST; |
|
478 | + } |
|
479 | + |
|
480 | + /** |
|
481 | + * @param string $format |
|
482 | + * @return string |
|
483 | + */ |
|
484 | + public static function renderResult($format, $meta, $data) { |
|
485 | + $response = array( |
|
486 | + 'ocs' => array( |
|
487 | + 'meta' => $meta, |
|
488 | + 'data' => $data, |
|
489 | + ), |
|
490 | + ); |
|
491 | + if ($format == 'json') { |
|
492 | + return OC_JSON::encode($response); |
|
493 | + } |
|
494 | + |
|
495 | + $writer = new XMLWriter(); |
|
496 | + $writer->openMemory(); |
|
497 | + $writer->setIndent(true); |
|
498 | + $writer->startDocument(); |
|
499 | + self::toXML($response, $writer); |
|
500 | + $writer->endDocument(); |
|
501 | + return $writer->outputMemory(true); |
|
502 | + } |
|
503 | 503 | } |
@@ -92,7 +92,7 @@ discard block |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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(); |