Completed
Pull Request — master (#5859)
by Robin
30:39 queued 11:25
created
lib/private/AppFramework/Http.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@
 block discarded – undo
110 110
 
111 111
 	/**
112 112
 	 * Gets the correct header
113
-	 * @param Http::CONSTANT $status the constant from the Http class
113
+	 * @param integer $status the constant from the Http class
114 114
 	 * @param \DateTime $lastModified formatted last modified date
115 115
 	 * @param string $ETag the etag
116 116
 	 * @return string
Please login to merge, or discard this patch.
Indentation   +106 added lines, -106 removed lines patch added patch discarded remove patch
@@ -32,119 +32,119 @@
 block discarded – undo
32 32
 use OCP\AppFramework\Http as BaseHttp;
33 33
 
34 34
 class Http extends BaseHttp {
35
-	private $server;
36
-	private $protocolVersion;
37
-	protected $headers;
35
+    private $server;
36
+    private $protocolVersion;
37
+    protected $headers;
38 38
 
39
-	/**
40
-	 * @param array $server $_SERVER
41
-	 * @param string $protocolVersion the http version to use defaults to HTTP/1.1
42
-	 */
43
-	public function __construct($server, $protocolVersion = 'HTTP/1.1') {
44
-		$this->server = $server;
45
-		$this->protocolVersion = $protocolVersion;
39
+    /**
40
+     * @param array $server $_SERVER
41
+     * @param string $protocolVersion the http version to use defaults to HTTP/1.1
42
+     */
43
+    public function __construct($server, $protocolVersion = 'HTTP/1.1') {
44
+        $this->server = $server;
45
+        $this->protocolVersion = $protocolVersion;
46 46
 
47
-		$this->headers = [
48
-			self::STATUS_CONTINUE => 'Continue',
49
-			self::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols',
50
-			self::STATUS_PROCESSING => 'Processing',
51
-			self::STATUS_OK => 'OK',
52
-			self::STATUS_CREATED => 'Created',
53
-			self::STATUS_ACCEPTED => 'Accepted',
54
-			self::STATUS_NON_AUTHORATIVE_INFORMATION => 'Non-Authorative Information',
55
-			self::STATUS_NO_CONTENT => 'No Content',
56
-			self::STATUS_RESET_CONTENT => 'Reset Content',
57
-			self::STATUS_PARTIAL_CONTENT => 'Partial Content',
58
-			self::STATUS_MULTI_STATUS => 'Multi-Status', // RFC 4918
59
-			self::STATUS_ALREADY_REPORTED => 'Already Reported', // RFC 5842
60
-			self::STATUS_IM_USED => 'IM Used', // RFC 3229
61
-			self::STATUS_MULTIPLE_CHOICES => 'Multiple Choices',
62
-			self::STATUS_MOVED_PERMANENTLY => 'Moved Permanently',
63
-			self::STATUS_FOUND => 'Found',
64
-			self::STATUS_SEE_OTHER => 'See Other',
65
-			self::STATUS_NOT_MODIFIED => 'Not Modified',
66
-			self::STATUS_USE_PROXY => 'Use Proxy',
67
-			self::STATUS_RESERVED => 'Reserved',
68
-			self::STATUS_TEMPORARY_REDIRECT => 'Temporary Redirect',
69
-			self::STATUS_BAD_REQUEST => 'Bad request',
70
-			self::STATUS_UNAUTHORIZED => 'Unauthorized',
71
-			self::STATUS_PAYMENT_REQUIRED => 'Payment Required',
72
-			self::STATUS_FORBIDDEN => 'Forbidden',
73
-			self::STATUS_NOT_FOUND => 'Not Found',
74
-			self::STATUS_METHOD_NOT_ALLOWED => 'Method Not Allowed',
75
-			self::STATUS_NOT_ACCEPTABLE => 'Not Acceptable',
76
-			self::STATUS_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required',
77
-			self::STATUS_REQUEST_TIMEOUT => 'Request Timeout',
78
-			self::STATUS_CONFLICT => 'Conflict',
79
-			self::STATUS_GONE => 'Gone',
80
-			self::STATUS_LENGTH_REQUIRED => 'Length Required',
81
-			self::STATUS_PRECONDITION_FAILED => 'Precondition failed',
82
-			self::STATUS_REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large',
83
-			self::STATUS_REQUEST_URI_TOO_LONG => 'Request-URI Too Long',
84
-			self::STATUS_UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type',
85
-			self::STATUS_REQUEST_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable',
86
-			self::STATUS_EXPECTATION_FAILED => 'Expectation Failed',
87
-			self::STATUS_IM_A_TEAPOT => 'I\'m a teapot', // RFC 2324
88
-			self::STATUS_UNPROCESSABLE_ENTITY => 'Unprocessable Entity', // RFC 4918
89
-			self::STATUS_LOCKED => 'Locked', // RFC 4918
90
-			self::STATUS_FAILED_DEPENDENCY => 'Failed Dependency', // RFC 4918
91
-			self::STATUS_UPGRADE_REQUIRED => 'Upgrade required',
92
-			self::STATUS_PRECONDITION_REQUIRED => 'Precondition required', // draft-nottingham-http-new-status
93
-			self::STATUS_TOO_MANY_REQUESTS => 'Too Many Requests', // draft-nottingham-http-new-status
94
-			self::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large', // draft-nottingham-http-new-status
95
-			self::STATUS_INTERNAL_SERVER_ERROR => 'Internal Server Error',
96
-			self::STATUS_NOT_IMPLEMENTED => 'Not Implemented',
97
-			self::STATUS_BAD_GATEWAY => 'Bad Gateway',
98
-			self::STATUS_SERVICE_UNAVAILABLE => 'Service Unavailable',
99
-			self::STATUS_GATEWAY_TIMEOUT => 'Gateway Timeout',
100
-			self::STATUS_HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version not supported',
101
-			self::STATUS_VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates',
102
-			self::STATUS_INSUFFICIENT_STORAGE => 'Insufficient Storage', // RFC 4918
103
-			self::STATUS_LOOP_DETECTED => 'Loop Detected', // RFC 5842
104
-			self::STATUS_BANDWIDTH_LIMIT_EXCEEDED => 'Bandwidth Limit Exceeded', // non-standard
105
-			self::STATUS_NOT_EXTENDED => 'Not extended',
106
-			self::STATUS_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', // draft-nottingham-http-new-status
107
-		];
108
-	}
47
+        $this->headers = [
48
+            self::STATUS_CONTINUE => 'Continue',
49
+            self::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols',
50
+            self::STATUS_PROCESSING => 'Processing',
51
+            self::STATUS_OK => 'OK',
52
+            self::STATUS_CREATED => 'Created',
53
+            self::STATUS_ACCEPTED => 'Accepted',
54
+            self::STATUS_NON_AUTHORATIVE_INFORMATION => 'Non-Authorative Information',
55
+            self::STATUS_NO_CONTENT => 'No Content',
56
+            self::STATUS_RESET_CONTENT => 'Reset Content',
57
+            self::STATUS_PARTIAL_CONTENT => 'Partial Content',
58
+            self::STATUS_MULTI_STATUS => 'Multi-Status', // RFC 4918
59
+            self::STATUS_ALREADY_REPORTED => 'Already Reported', // RFC 5842
60
+            self::STATUS_IM_USED => 'IM Used', // RFC 3229
61
+            self::STATUS_MULTIPLE_CHOICES => 'Multiple Choices',
62
+            self::STATUS_MOVED_PERMANENTLY => 'Moved Permanently',
63
+            self::STATUS_FOUND => 'Found',
64
+            self::STATUS_SEE_OTHER => 'See Other',
65
+            self::STATUS_NOT_MODIFIED => 'Not Modified',
66
+            self::STATUS_USE_PROXY => 'Use Proxy',
67
+            self::STATUS_RESERVED => 'Reserved',
68
+            self::STATUS_TEMPORARY_REDIRECT => 'Temporary Redirect',
69
+            self::STATUS_BAD_REQUEST => 'Bad request',
70
+            self::STATUS_UNAUTHORIZED => 'Unauthorized',
71
+            self::STATUS_PAYMENT_REQUIRED => 'Payment Required',
72
+            self::STATUS_FORBIDDEN => 'Forbidden',
73
+            self::STATUS_NOT_FOUND => 'Not Found',
74
+            self::STATUS_METHOD_NOT_ALLOWED => 'Method Not Allowed',
75
+            self::STATUS_NOT_ACCEPTABLE => 'Not Acceptable',
76
+            self::STATUS_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required',
77
+            self::STATUS_REQUEST_TIMEOUT => 'Request Timeout',
78
+            self::STATUS_CONFLICT => 'Conflict',
79
+            self::STATUS_GONE => 'Gone',
80
+            self::STATUS_LENGTH_REQUIRED => 'Length Required',
81
+            self::STATUS_PRECONDITION_FAILED => 'Precondition failed',
82
+            self::STATUS_REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large',
83
+            self::STATUS_REQUEST_URI_TOO_LONG => 'Request-URI Too Long',
84
+            self::STATUS_UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type',
85
+            self::STATUS_REQUEST_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable',
86
+            self::STATUS_EXPECTATION_FAILED => 'Expectation Failed',
87
+            self::STATUS_IM_A_TEAPOT => 'I\'m a teapot', // RFC 2324
88
+            self::STATUS_UNPROCESSABLE_ENTITY => 'Unprocessable Entity', // RFC 4918
89
+            self::STATUS_LOCKED => 'Locked', // RFC 4918
90
+            self::STATUS_FAILED_DEPENDENCY => 'Failed Dependency', // RFC 4918
91
+            self::STATUS_UPGRADE_REQUIRED => 'Upgrade required',
92
+            self::STATUS_PRECONDITION_REQUIRED => 'Precondition required', // draft-nottingham-http-new-status
93
+            self::STATUS_TOO_MANY_REQUESTS => 'Too Many Requests', // draft-nottingham-http-new-status
94
+            self::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large', // draft-nottingham-http-new-status
95
+            self::STATUS_INTERNAL_SERVER_ERROR => 'Internal Server Error',
96
+            self::STATUS_NOT_IMPLEMENTED => 'Not Implemented',
97
+            self::STATUS_BAD_GATEWAY => 'Bad Gateway',
98
+            self::STATUS_SERVICE_UNAVAILABLE => 'Service Unavailable',
99
+            self::STATUS_GATEWAY_TIMEOUT => 'Gateway Timeout',
100
+            self::STATUS_HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version not supported',
101
+            self::STATUS_VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates',
102
+            self::STATUS_INSUFFICIENT_STORAGE => 'Insufficient Storage', // RFC 4918
103
+            self::STATUS_LOOP_DETECTED => 'Loop Detected', // RFC 5842
104
+            self::STATUS_BANDWIDTH_LIMIT_EXCEEDED => 'Bandwidth Limit Exceeded', // non-standard
105
+            self::STATUS_NOT_EXTENDED => 'Not extended',
106
+            self::STATUS_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', // draft-nottingham-http-new-status
107
+        ];
108
+    }
109 109
 
110 110
 
111
-	/**
112
-	 * Gets the correct header
113
-	 * @param Http::CONSTANT $status the constant from the Http class
114
-	 * @param \DateTime $lastModified formatted last modified date
115
-	 * @param string $ETag the etag
116
-	 * @return string
117
-	 */
118
-	public function getStatusHeader(
119
-		$status,
120
-		\DateTime $lastModified = null,
121
-									$ETag = null
122
-	) {
123
-		if (!is_null($lastModified)) {
124
-			$lastModified = $lastModified->format(\DateTime::RFC2822);
125
-		}
111
+    /**
112
+     * Gets the correct header
113
+     * @param Http::CONSTANT $status the constant from the Http class
114
+     * @param \DateTime $lastModified formatted last modified date
115
+     * @param string $ETag the etag
116
+     * @return string
117
+     */
118
+    public function getStatusHeader(
119
+        $status,
120
+        \DateTime $lastModified = null,
121
+                                    $ETag = null
122
+    ) {
123
+        if (!is_null($lastModified)) {
124
+            $lastModified = $lastModified->format(\DateTime::RFC2822);
125
+        }
126 126
 
127
-		// if etag or lastmodified have not changed, return a not modified
128
-		if ((isset($this->server['HTTP_IF_NONE_MATCH'])
129
-			&& trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag)
127
+        // if etag or lastmodified have not changed, return a not modified
128
+        if ((isset($this->server['HTTP_IF_NONE_MATCH'])
129
+            && trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag)
130 130
 
131
-			||
131
+            ||
132 132
 
133
-			(isset($this->server['HTTP_IF_MODIFIED_SINCE'])
134
-			&& trim($this->server['HTTP_IF_MODIFIED_SINCE']) ===
135
-				$lastModified)) {
136
-			$status = self::STATUS_NOT_MODIFIED;
137
-		}
133
+            (isset($this->server['HTTP_IF_MODIFIED_SINCE'])
134
+            && trim($this->server['HTTP_IF_MODIFIED_SINCE']) ===
135
+                $lastModified)) {
136
+            $status = self::STATUS_NOT_MODIFIED;
137
+        }
138 138
 
139
-		// we have one change currently for the http 1.0 header that differs
140
-		// from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND
141
-		// if this differs any more, we want to create childclasses for this
142
-		if ($status === self::STATUS_TEMPORARY_REDIRECT
143
-			&& $this->protocolVersion === 'HTTP/1.0') {
144
-			$status = self::STATUS_FOUND;
145
-		}
139
+        // we have one change currently for the http 1.0 header that differs
140
+        // from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND
141
+        // if this differs any more, we want to create childclasses for this
142
+        if ($status === self::STATUS_TEMPORARY_REDIRECT
143
+            && $this->protocolVersion === 'HTTP/1.0') {
144
+            $status = self::STATUS_FOUND;
145
+        }
146 146
 
147
-		return $this->protocolVersion . ' ' . $status . ' ' .
148
-			$this->headers[$status];
149
-	}
147
+        return $this->protocolVersion . ' ' . $status . ' ' .
148
+            $this->headers[$status];
149
+    }
150 150
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 
127 127
 		// if etag or lastmodified have not changed, return a not modified
128 128
 		if ((isset($this->server['HTTP_IF_NONE_MATCH'])
129
-			&& trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag)
129
+			&& trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string) $ETag)
130 130
 
131 131
 			||
132 132
 
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 			$status = self::STATUS_FOUND;
145 145
 		}
146 146
 
147
-		return $this->protocolVersion . ' ' . $status . ' ' .
147
+		return $this->protocolVersion.' '.$status.' '.
148 148
 			$this->headers[$status];
149 149
 	}
150 150
 }
Please login to merge, or discard this patch.
lib/private/Comments/Manager.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -205,7 +205,7 @@
 block discarded – undo
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);
Please login to merge, or discard this patch.
Indentation   +842 added lines, -842 removed lines patch added patch discarded remove patch
@@ -38,846 +38,846 @@
 block discarded – undo
38 38
 
39 39
 class Manager implements ICommentsManager {
40 40
 
41
-	/** @var  IDBConnection */
42
-	protected $dbConn;
43
-
44
-	/** @var  ILogger */
45
-	protected $logger;
46
-
47
-	/** @var IConfig */
48
-	protected $config;
49
-
50
-	/** @var IComment[] */
51
-	protected $commentsCache = [];
52
-
53
-	/** @var  \Closure[] */
54
-	protected $eventHandlerClosures = [];
55
-
56
-	/** @var  ICommentsEventHandler[] */
57
-	protected $eventHandlers = [];
58
-
59
-	/** @var \Closure[] */
60
-	protected $displayNameResolvers = [];
61
-
62
-	/**
63
-	 * Manager constructor.
64
-	 *
65
-	 * @param IDBConnection $dbConn
66
-	 * @param ILogger $logger
67
-	 * @param IConfig $config
68
-	 */
69
-	public function __construct(
70
-		IDBConnection $dbConn,
71
-		ILogger $logger,
72
-		IConfig $config
73
-	) {
74
-		$this->dbConn = $dbConn;
75
-		$this->logger = $logger;
76
-		$this->config = $config;
77
-	}
78
-
79
-	/**
80
-	 * converts data base data into PHP native, proper types as defined by
81
-	 * IComment interface.
82
-	 *
83
-	 * @param array $data
84
-	 * @return array
85
-	 */
86
-	protected function normalizeDatabaseData(array $data) {
87
-		$data['id'] = strval($data['id']);
88
-		$data['parent_id'] = strval($data['parent_id']);
89
-		$data['topmost_parent_id'] = strval($data['topmost_parent_id']);
90
-		$data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
91
-		if (!is_null($data['latest_child_timestamp'])) {
92
-			$data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
93
-		}
94
-		$data['children_count'] = intval($data['children_count']);
95
-		return $data;
96
-	}
97
-
98
-	/**
99
-	 * prepares a comment for an insert or update operation after making sure
100
-	 * all necessary fields have a value assigned.
101
-	 *
102
-	 * @param IComment $comment
103
-	 * @return IComment returns the same updated IComment instance as provided
104
-	 *                  by parameter for convenience
105
-	 * @throws \UnexpectedValueException
106
-	 */
107
-	protected function prepareCommentForDatabaseWrite(IComment $comment) {
108
-		if (!$comment->getActorType()
109
-			|| !$comment->getActorId()
110
-			|| !$comment->getObjectType()
111
-			|| !$comment->getObjectId()
112
-			|| !$comment->getVerb()
113
-		) {
114
-			throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
115
-		}
116
-
117
-		if ($comment->getId() === '') {
118
-			$comment->setChildrenCount(0);
119
-			$comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
120
-			$comment->setLatestChildDateTime(null);
121
-		}
122
-
123
-		if (is_null($comment->getCreationDateTime())) {
124
-			$comment->setCreationDateTime(new \DateTime());
125
-		}
126
-
127
-		if ($comment->getParentId() !== '0') {
128
-			$comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
129
-		} else {
130
-			$comment->setTopmostParentId('0');
131
-		}
132
-
133
-		$this->cache($comment);
134
-
135
-		return $comment;
136
-	}
137
-
138
-	/**
139
-	 * returns the topmost parent id of a given comment identified by ID
140
-	 *
141
-	 * @param string $id
142
-	 * @return string
143
-	 * @throws NotFoundException
144
-	 */
145
-	protected function determineTopmostParentId($id) {
146
-		$comment = $this->get($id);
147
-		if ($comment->getParentId() === '0') {
148
-			return $comment->getId();
149
-		} else {
150
-			return $this->determineTopmostParentId($comment->getId());
151
-		}
152
-	}
153
-
154
-	/**
155
-	 * updates child information of a comment
156
-	 *
157
-	 * @param string $id
158
-	 * @param \DateTime $cDateTime the date time of the most recent child
159
-	 * @throws NotFoundException
160
-	 */
161
-	protected function updateChildrenInformation($id, \DateTime $cDateTime) {
162
-		$qb = $this->dbConn->getQueryBuilder();
163
-		$query = $qb->select($qb->createFunction('COUNT(`id`)'))
164
-			->from('comments')
165
-			->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
166
-			->setParameter('id', $id);
167
-
168
-		$resultStatement = $query->execute();
169
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
170
-		$resultStatement->closeCursor();
171
-		$children = intval($data[0]);
172
-
173
-		$comment = $this->get($id);
174
-		$comment->setChildrenCount($children);
175
-		$comment->setLatestChildDateTime($cDateTime);
176
-		$this->save($comment);
177
-	}
178
-
179
-	/**
180
-	 * Tests whether actor or object type and id parameters are acceptable.
181
-	 * Throws exception if not.
182
-	 *
183
-	 * @param string $role
184
-	 * @param string $type
185
-	 * @param string $id
186
-	 * @throws \InvalidArgumentException
187
-	 */
188
-	protected function checkRoleParameters($role, $type, $id) {
189
-		if (
190
-			!is_string($type) || empty($type)
191
-			|| !is_string($id) || empty($id)
192
-		) {
193
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
194
-		}
195
-	}
196
-
197
-	/**
198
-	 * run-time caches a comment
199
-	 *
200
-	 * @param IComment $comment
201
-	 */
202
-	protected function cache(IComment $comment) {
203
-		$id = $comment->getId();
204
-		if (empty($id)) {
205
-			return;
206
-		}
207
-		$this->commentsCache[strval($id)] = $comment;
208
-	}
209
-
210
-	/**
211
-	 * removes an entry from the comments run time cache
212
-	 *
213
-	 * @param mixed $id the comment's id
214
-	 */
215
-	protected function uncache($id) {
216
-		$id = strval($id);
217
-		if (isset($this->commentsCache[$id])) {
218
-			unset($this->commentsCache[$id]);
219
-		}
220
-	}
221
-
222
-	/**
223
-	 * returns a comment instance
224
-	 *
225
-	 * @param string $id the ID of the comment
226
-	 * @return IComment
227
-	 * @throws NotFoundException
228
-	 * @throws \InvalidArgumentException
229
-	 * @since 9.0.0
230
-	 */
231
-	public function get($id) {
232
-		if (intval($id) === 0) {
233
-			throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
234
-		}
235
-
236
-		if (isset($this->commentsCache[$id])) {
237
-			return $this->commentsCache[$id];
238
-		}
239
-
240
-		$qb = $this->dbConn->getQueryBuilder();
241
-		$resultStatement = $qb->select('*')
242
-			->from('comments')
243
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
244
-			->setParameter('id', $id, IQueryBuilder::PARAM_INT)
245
-			->execute();
246
-
247
-		$data = $resultStatement->fetch();
248
-		$resultStatement->closeCursor();
249
-		if (!$data) {
250
-			throw new NotFoundException();
251
-		}
252
-
253
-		$comment = new Comment($this->normalizeDatabaseData($data));
254
-		$this->cache($comment);
255
-		return $comment;
256
-	}
257
-
258
-	/**
259
-	 * returns the comment specified by the id and all it's child comments.
260
-	 * At this point of time, we do only support one level depth.
261
-	 *
262
-	 * @param string $id
263
-	 * @param int $limit max number of entries to return, 0 returns all
264
-	 * @param int $offset the start entry
265
-	 * @return array
266
-	 * @since 9.0.0
267
-	 *
268
-	 * The return array looks like this
269
-	 * [
270
-	 *   'comment' => IComment, // root comment
271
-	 *   'replies' =>
272
-	 *   [
273
-	 *     0 =>
274
-	 *     [
275
-	 *       'comment' => IComment,
276
-	 *       'replies' => []
277
-	 *     ]
278
-	 *     1 =>
279
-	 *     [
280
-	 *       'comment' => IComment,
281
-	 *       'replies'=> []
282
-	 *     ],
283
-	 *     …
284
-	 *   ]
285
-	 * ]
286
-	 */
287
-	public function getTree($id, $limit = 0, $offset = 0) {
288
-		$tree = [];
289
-		$tree['comment'] = $this->get($id);
290
-		$tree['replies'] = [];
291
-
292
-		$qb = $this->dbConn->getQueryBuilder();
293
-		$query = $qb->select('*')
294
-			->from('comments')
295
-			->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
296
-			->orderBy('creation_timestamp', 'DESC')
297
-			->setParameter('id', $id);
298
-
299
-		if ($limit > 0) {
300
-			$query->setMaxResults($limit);
301
-		}
302
-		if ($offset > 0) {
303
-			$query->setFirstResult($offset);
304
-		}
305
-
306
-		$resultStatement = $query->execute();
307
-		while ($data = $resultStatement->fetch()) {
308
-			$comment = new Comment($this->normalizeDatabaseData($data));
309
-			$this->cache($comment);
310
-			$tree['replies'][] = [
311
-				'comment' => $comment,
312
-				'replies' => []
313
-			];
314
-		}
315
-		$resultStatement->closeCursor();
316
-
317
-		return $tree;
318
-	}
319
-
320
-	/**
321
-	 * returns comments for a specific object (e.g. a file).
322
-	 *
323
-	 * The sort order is always newest to oldest.
324
-	 *
325
-	 * @param string $objectType the object type, e.g. 'files'
326
-	 * @param string $objectId the id of the object
327
-	 * @param int $limit optional, number of maximum comments to be returned. if
328
-	 * not specified, all comments are returned.
329
-	 * @param int $offset optional, starting point
330
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
331
-	 * that may be returned
332
-	 * @return IComment[]
333
-	 * @since 9.0.0
334
-	 */
335
-	public function getForObject(
336
-		$objectType,
337
-		$objectId,
338
-		$limit = 0,
339
-		$offset = 0,
340
-		\DateTime $notOlderThan = null
341
-	) {
342
-		$comments = [];
343
-
344
-		$qb = $this->dbConn->getQueryBuilder();
345
-		$query = $qb->select('*')
346
-			->from('comments')
347
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
348
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
349
-			->orderBy('creation_timestamp', 'DESC')
350
-			->setParameter('type', $objectType)
351
-			->setParameter('id', $objectId);
352
-
353
-		if ($limit > 0) {
354
-			$query->setMaxResults($limit);
355
-		}
356
-		if ($offset > 0) {
357
-			$query->setFirstResult($offset);
358
-		}
359
-		if (!is_null($notOlderThan)) {
360
-			$query
361
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
362
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
363
-		}
364
-
365
-		$resultStatement = $query->execute();
366
-		while ($data = $resultStatement->fetch()) {
367
-			$comment = new Comment($this->normalizeDatabaseData($data));
368
-			$this->cache($comment);
369
-			$comments[] = $comment;
370
-		}
371
-		$resultStatement->closeCursor();
372
-
373
-		return $comments;
374
-	}
375
-
376
-	/**
377
-	 * @param $objectType string the object type, e.g. 'files'
378
-	 * @param $objectId string the id of the object
379
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
380
-	 * that may be returned
381
-	 * @return Int
382
-	 * @since 9.0.0
383
-	 */
384
-	public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) {
385
-		$qb = $this->dbConn->getQueryBuilder();
386
-		$query = $qb->select($qb->createFunction('COUNT(`id`)'))
387
-			->from('comments')
388
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
389
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
390
-			->setParameter('type', $objectType)
391
-			->setParameter('id', $objectId);
392
-
393
-		if (!is_null($notOlderThan)) {
394
-			$query
395
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
396
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
397
-		}
398
-
399
-		$resultStatement = $query->execute();
400
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
401
-		$resultStatement->closeCursor();
402
-		return intval($data[0]);
403
-	}
404
-
405
-	/**
406
-	 * Get the number of unread comments for all files in a folder
407
-	 *
408
-	 * @param int $folderId
409
-	 * @param IUser $user
410
-	 * @return array [$fileId => $unreadCount]
411
-	 */
412
-	public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
413
-		$qb = $this->dbConn->getQueryBuilder();
414
-		$query = $qb->select(
415
-			'fileid',
416
-			$qb->createFunction(
417
-			'COUNT(' . $qb->getColumnName('c.id') . ')'
418
-		)
419
-		)->from('comments', 'c')
420
-			->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
421
-				$qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
422
-				$qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT))
423
-			))
424
-			->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
425
-				$qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
426
-				$qb->expr()->eq('m.object_id', 'c.object_id'),
427
-				$qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID()))
428
-			))
429
-			->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)))
430
-			->andWhere($qb->expr()->orX(
431
-				$qb->expr()->gt('c.creation_timestamp', 'marker_datetime'),
432
-				$qb->expr()->isNull('marker_datetime')
433
-			))
434
-			->groupBy('f.fileid');
435
-
436
-		$resultStatement = $query->execute();
437
-		return array_map(function ($count) {
438
-			return (int)$count;
439
-		}, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR));
440
-	}
441
-
442
-	/**
443
-	 * creates a new comment and returns it. At this point of time, it is not
444
-	 * saved in the used data storage. Use save() after setting other fields
445
-	 * of the comment (e.g. message or verb).
446
-	 *
447
-	 * @param string $actorType the actor type (e.g. 'users')
448
-	 * @param string $actorId a user id
449
-	 * @param string $objectType the object type the comment is attached to
450
-	 * @param string $objectId the object id the comment is attached to
451
-	 * @return IComment
452
-	 * @since 9.0.0
453
-	 */
454
-	public function create($actorType, $actorId, $objectType, $objectId) {
455
-		$comment = new Comment();
456
-		$comment
457
-			->setActor($actorType, $actorId)
458
-			->setObject($objectType, $objectId);
459
-		return $comment;
460
-	}
461
-
462
-	/**
463
-	 * permanently deletes the comment specified by the ID
464
-	 *
465
-	 * When the comment has child comments, their parent ID will be changed to
466
-	 * the parent ID of the item that is to be deleted.
467
-	 *
468
-	 * @param string $id
469
-	 * @return bool
470
-	 * @throws \InvalidArgumentException
471
-	 * @since 9.0.0
472
-	 */
473
-	public function delete($id) {
474
-		if (!is_string($id)) {
475
-			throw new \InvalidArgumentException('Parameter must be string');
476
-		}
477
-
478
-		try {
479
-			$comment = $this->get($id);
480
-		} catch (\Exception $e) {
481
-			// Ignore exceptions, we just don't fire a hook then
482
-			$comment = null;
483
-		}
484
-
485
-		$qb = $this->dbConn->getQueryBuilder();
486
-		$query = $qb->delete('comments')
487
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
488
-			->setParameter('id', $id);
489
-
490
-		try {
491
-			$affectedRows = $query->execute();
492
-			$this->uncache($id);
493
-		} catch (DriverException $e) {
494
-			$this->logger->logException($e, ['app' => 'core_comments']);
495
-			return false;
496
-		}
497
-
498
-		if ($affectedRows > 0 && $comment instanceof IComment) {
499
-			$this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
500
-		}
501
-
502
-		return ($affectedRows > 0);
503
-	}
504
-
505
-	/**
506
-	 * saves the comment permanently
507
-	 *
508
-	 * if the supplied comment has an empty ID, a new entry comment will be
509
-	 * saved and the instance updated with the new ID.
510
-	 *
511
-	 * Otherwise, an existing comment will be updated.
512
-	 *
513
-	 * Throws NotFoundException when a comment that is to be updated does not
514
-	 * exist anymore at this point of time.
515
-	 *
516
-	 * @param IComment $comment
517
-	 * @return bool
518
-	 * @throws NotFoundException
519
-	 * @since 9.0.0
520
-	 */
521
-	public function save(IComment $comment) {
522
-		if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
523
-			$result = $this->insert($comment);
524
-		} else {
525
-			$result = $this->update($comment);
526
-		}
527
-
528
-		if ($result && !!$comment->getParentId()) {
529
-			$this->updateChildrenInformation(
530
-				$comment->getParentId(),
531
-				$comment->getCreationDateTime()
532
-			);
533
-			$this->cache($comment);
534
-		}
535
-
536
-		return $result;
537
-	}
538
-
539
-	/**
540
-	 * inserts the provided comment in the database
541
-	 *
542
-	 * @param IComment $comment
543
-	 * @return bool
544
-	 */
545
-	protected function insert(IComment &$comment) {
546
-		$qb = $this->dbConn->getQueryBuilder();
547
-		$affectedRows = $qb
548
-			->insert('comments')
549
-			->values([
550
-				'parent_id' => $qb->createNamedParameter($comment->getParentId()),
551
-				'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
552
-				'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
553
-				'actor_type' => $qb->createNamedParameter($comment->getActorType()),
554
-				'actor_id' => $qb->createNamedParameter($comment->getActorId()),
555
-				'message' => $qb->createNamedParameter($comment->getMessage()),
556
-				'verb' => $qb->createNamedParameter($comment->getVerb()),
557
-				'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
558
-				'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
559
-				'object_type' => $qb->createNamedParameter($comment->getObjectType()),
560
-				'object_id' => $qb->createNamedParameter($comment->getObjectId()),
561
-			])
562
-			->execute();
563
-
564
-		if ($affectedRows > 0) {
565
-			$comment->setId(strval($qb->getLastInsertId()));
566
-			$this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
567
-		}
568
-
569
-		return $affectedRows > 0;
570
-	}
571
-
572
-	/**
573
-	 * updates a Comment data row
574
-	 *
575
-	 * @param IComment $comment
576
-	 * @return bool
577
-	 * @throws NotFoundException
578
-	 */
579
-	protected function update(IComment $comment) {
580
-		// for properly working preUpdate Events we need the old comments as is
581
-		// in the DB and overcome caching. Also avoid that outdated information stays.
582
-		$this->uncache($comment->getId());
583
-		$this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
584
-		$this->uncache($comment->getId());
585
-
586
-		$qb = $this->dbConn->getQueryBuilder();
587
-		$affectedRows = $qb
588
-			->update('comments')
589
-			->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
590
-			->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
591
-			->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
592
-			->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
593
-			->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
594
-			->set('message', $qb->createNamedParameter($comment->getMessage()))
595
-			->set('verb', $qb->createNamedParameter($comment->getVerb()))
596
-			->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
597
-			->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
598
-			->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
599
-			->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
600
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
601
-			->setParameter('id', $comment->getId())
602
-			->execute();
603
-
604
-		if ($affectedRows === 0) {
605
-			throw new NotFoundException('Comment to update does ceased to exist');
606
-		}
607
-
608
-		$this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
609
-
610
-		return $affectedRows > 0;
611
-	}
612
-
613
-	/**
614
-	 * removes references to specific actor (e.g. on user delete) of a comment.
615
-	 * The comment itself must not get lost/deleted.
616
-	 *
617
-	 * @param string $actorType the actor type (e.g. 'users')
618
-	 * @param string $actorId a user id
619
-	 * @return boolean
620
-	 * @since 9.0.0
621
-	 */
622
-	public function deleteReferencesOfActor($actorType, $actorId) {
623
-		$this->checkRoleParameters('Actor', $actorType, $actorId);
624
-
625
-		$qb = $this->dbConn->getQueryBuilder();
626
-		$affectedRows = $qb
627
-			->update('comments')
628
-			->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
629
-			->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
630
-			->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
631
-			->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
632
-			->setParameter('type', $actorType)
633
-			->setParameter('id', $actorId)
634
-			->execute();
635
-
636
-		$this->commentsCache = [];
637
-
638
-		return is_int($affectedRows);
639
-	}
640
-
641
-	/**
642
-	 * deletes all comments made of a specific object (e.g. on file delete)
643
-	 *
644
-	 * @param string $objectType the object type (e.g. 'files')
645
-	 * @param string $objectId e.g. the file id
646
-	 * @return boolean
647
-	 * @since 9.0.0
648
-	 */
649
-	public function deleteCommentsAtObject($objectType, $objectId) {
650
-		$this->checkRoleParameters('Object', $objectType, $objectId);
651
-
652
-		$qb = $this->dbConn->getQueryBuilder();
653
-		$affectedRows = $qb
654
-			->delete('comments')
655
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
656
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
657
-			->setParameter('type', $objectType)
658
-			->setParameter('id', $objectId)
659
-			->execute();
660
-
661
-		$this->commentsCache = [];
662
-
663
-		return is_int($affectedRows);
664
-	}
665
-
666
-	/**
667
-	 * deletes the read markers for the specified user
668
-	 *
669
-	 * @param \OCP\IUser $user
670
-	 * @return bool
671
-	 * @since 9.0.0
672
-	 */
673
-	public function deleteReadMarksFromUser(IUser $user) {
674
-		$qb = $this->dbConn->getQueryBuilder();
675
-		$query = $qb->delete('comments_read_markers')
676
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
677
-			->setParameter('user_id', $user->getUID());
678
-
679
-		try {
680
-			$affectedRows = $query->execute();
681
-		} catch (DriverException $e) {
682
-			$this->logger->logException($e, ['app' => 'core_comments']);
683
-			return false;
684
-		}
685
-		return ($affectedRows > 0);
686
-	}
687
-
688
-	/**
689
-	 * sets the read marker for a given file to the specified date for the
690
-	 * provided user
691
-	 *
692
-	 * @param string $objectType
693
-	 * @param string $objectId
694
-	 * @param \DateTime $dateTime
695
-	 * @param IUser $user
696
-	 * @since 9.0.0
697
-	 * @suppress SqlInjectionChecker
698
-	 */
699
-	public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
700
-		$this->checkRoleParameters('Object', $objectType, $objectId);
701
-
702
-		$qb = $this->dbConn->getQueryBuilder();
703
-		$values = [
704
-			'user_id' => $qb->createNamedParameter($user->getUID()),
705
-			'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
706
-			'object_type' => $qb->createNamedParameter($objectType),
707
-			'object_id' => $qb->createNamedParameter($objectId),
708
-		];
709
-
710
-		// Strategy: try to update, if this does not return affected rows, do an insert.
711
-		$affectedRows = $qb
712
-			->update('comments_read_markers')
713
-			->set('user_id', $values['user_id'])
714
-			->set('marker_datetime', $values['marker_datetime'])
715
-			->set('object_type', $values['object_type'])
716
-			->set('object_id', $values['object_id'])
717
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
718
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
719
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
720
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
721
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
722
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
723
-			->execute();
724
-
725
-		if ($affectedRows > 0) {
726
-			return;
727
-		}
728
-
729
-		$qb->insert('comments_read_markers')
730
-			->values($values)
731
-			->execute();
732
-	}
733
-
734
-	/**
735
-	 * returns the read marker for a given file to the specified date for the
736
-	 * provided user. It returns null, when the marker is not present, i.e.
737
-	 * no comments were marked as read.
738
-	 *
739
-	 * @param string $objectType
740
-	 * @param string $objectId
741
-	 * @param IUser $user
742
-	 * @return \DateTime|null
743
-	 * @since 9.0.0
744
-	 */
745
-	public function getReadMark($objectType, $objectId, IUser $user) {
746
-		$qb = $this->dbConn->getQueryBuilder();
747
-		$resultStatement = $qb->select('marker_datetime')
748
-			->from('comments_read_markers')
749
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
750
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
751
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
752
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
753
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
754
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
755
-			->execute();
756
-
757
-		$data = $resultStatement->fetch();
758
-		$resultStatement->closeCursor();
759
-		if (!$data || is_null($data['marker_datetime'])) {
760
-			return null;
761
-		}
762
-
763
-		return new \DateTime($data['marker_datetime']);
764
-	}
765
-
766
-	/**
767
-	 * deletes the read markers on the specified object
768
-	 *
769
-	 * @param string $objectType
770
-	 * @param string $objectId
771
-	 * @return bool
772
-	 * @since 9.0.0
773
-	 */
774
-	public function deleteReadMarksOnObject($objectType, $objectId) {
775
-		$this->checkRoleParameters('Object', $objectType, $objectId);
776
-
777
-		$qb = $this->dbConn->getQueryBuilder();
778
-		$query = $qb->delete('comments_read_markers')
779
-			->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
780
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
781
-			->setParameter('object_type', $objectType)
782
-			->setParameter('object_id', $objectId);
783
-
784
-		try {
785
-			$affectedRows = $query->execute();
786
-		} catch (DriverException $e) {
787
-			$this->logger->logException($e, ['app' => 'core_comments']);
788
-			return false;
789
-		}
790
-		return ($affectedRows > 0);
791
-	}
792
-
793
-	/**
794
-	 * registers an Entity to the manager, so event notifications can be send
795
-	 * to consumers of the comments infrastructure
796
-	 *
797
-	 * @param \Closure $closure
798
-	 */
799
-	public function registerEventHandler(\Closure $closure) {
800
-		$this->eventHandlerClosures[] = $closure;
801
-		$this->eventHandlers = [];
802
-	}
803
-
804
-	/**
805
-	 * registers a method that resolves an ID to a display name for a given type
806
-	 *
807
-	 * @param string $type
808
-	 * @param \Closure $closure
809
-	 * @throws \OutOfBoundsException
810
-	 * @since 11.0.0
811
-	 *
812
-	 * Only one resolver shall be registered per type. Otherwise a
813
-	 * \OutOfBoundsException has to thrown.
814
-	 */
815
-	public function registerDisplayNameResolver($type, \Closure $closure) {
816
-		if (!is_string($type)) {
817
-			throw new \InvalidArgumentException('String expected.');
818
-		}
819
-		if (isset($this->displayNameResolvers[$type])) {
820
-			throw new \OutOfBoundsException('Displayname resolver for this type already registered');
821
-		}
822
-		$this->displayNameResolvers[$type] = $closure;
823
-	}
824
-
825
-	/**
826
-	 * resolves a given ID of a given Type to a display name.
827
-	 *
828
-	 * @param string $type
829
-	 * @param string $id
830
-	 * @return string
831
-	 * @throws \OutOfBoundsException
832
-	 * @since 11.0.0
833
-	 *
834
-	 * If a provided type was not registered, an \OutOfBoundsException shall
835
-	 * be thrown. It is upon the resolver discretion what to return of the
836
-	 * provided ID is unknown. It must be ensured that a string is returned.
837
-	 */
838
-	public function resolveDisplayName($type, $id) {
839
-		if (!is_string($type)) {
840
-			throw new \InvalidArgumentException('String expected.');
841
-		}
842
-		if (!isset($this->displayNameResolvers[$type])) {
843
-			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
844
-		}
845
-		return (string)$this->displayNameResolvers[$type]($id);
846
-	}
847
-
848
-	/**
849
-	 * returns valid, registered entities
850
-	 *
851
-	 * @return \OCP\Comments\ICommentsEventHandler[]
852
-	 */
853
-	private function getEventHandlers() {
854
-		if (!empty($this->eventHandlers)) {
855
-			return $this->eventHandlers;
856
-		}
857
-
858
-		$this->eventHandlers = [];
859
-		foreach ($this->eventHandlerClosures as $name => $closure) {
860
-			$entity = $closure();
861
-			if (!($entity instanceof ICommentsEventHandler)) {
862
-				throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
863
-			}
864
-			$this->eventHandlers[$name] = $entity;
865
-		}
866
-
867
-		return $this->eventHandlers;
868
-	}
869
-
870
-	/**
871
-	 * sends notifications to the registered entities
872
-	 *
873
-	 * @param $eventType
874
-	 * @param IComment $comment
875
-	 */
876
-	private function sendEvent($eventType, IComment $comment) {
877
-		$entities = $this->getEventHandlers();
878
-		$event = new CommentsEvent($eventType, $comment);
879
-		foreach ($entities as $entity) {
880
-			$entity->handle($event);
881
-		}
882
-	}
41
+    /** @var  IDBConnection */
42
+    protected $dbConn;
43
+
44
+    /** @var  ILogger */
45
+    protected $logger;
46
+
47
+    /** @var IConfig */
48
+    protected $config;
49
+
50
+    /** @var IComment[] */
51
+    protected $commentsCache = [];
52
+
53
+    /** @var  \Closure[] */
54
+    protected $eventHandlerClosures = [];
55
+
56
+    /** @var  ICommentsEventHandler[] */
57
+    protected $eventHandlers = [];
58
+
59
+    /** @var \Closure[] */
60
+    protected $displayNameResolvers = [];
61
+
62
+    /**
63
+     * Manager constructor.
64
+     *
65
+     * @param IDBConnection $dbConn
66
+     * @param ILogger $logger
67
+     * @param IConfig $config
68
+     */
69
+    public function __construct(
70
+        IDBConnection $dbConn,
71
+        ILogger $logger,
72
+        IConfig $config
73
+    ) {
74
+        $this->dbConn = $dbConn;
75
+        $this->logger = $logger;
76
+        $this->config = $config;
77
+    }
78
+
79
+    /**
80
+     * converts data base data into PHP native, proper types as defined by
81
+     * IComment interface.
82
+     *
83
+     * @param array $data
84
+     * @return array
85
+     */
86
+    protected function normalizeDatabaseData(array $data) {
87
+        $data['id'] = strval($data['id']);
88
+        $data['parent_id'] = strval($data['parent_id']);
89
+        $data['topmost_parent_id'] = strval($data['topmost_parent_id']);
90
+        $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
91
+        if (!is_null($data['latest_child_timestamp'])) {
92
+            $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
93
+        }
94
+        $data['children_count'] = intval($data['children_count']);
95
+        return $data;
96
+    }
97
+
98
+    /**
99
+     * prepares a comment for an insert or update operation after making sure
100
+     * all necessary fields have a value assigned.
101
+     *
102
+     * @param IComment $comment
103
+     * @return IComment returns the same updated IComment instance as provided
104
+     *                  by parameter for convenience
105
+     * @throws \UnexpectedValueException
106
+     */
107
+    protected function prepareCommentForDatabaseWrite(IComment $comment) {
108
+        if (!$comment->getActorType()
109
+            || !$comment->getActorId()
110
+            || !$comment->getObjectType()
111
+            || !$comment->getObjectId()
112
+            || !$comment->getVerb()
113
+        ) {
114
+            throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
115
+        }
116
+
117
+        if ($comment->getId() === '') {
118
+            $comment->setChildrenCount(0);
119
+            $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
120
+            $comment->setLatestChildDateTime(null);
121
+        }
122
+
123
+        if (is_null($comment->getCreationDateTime())) {
124
+            $comment->setCreationDateTime(new \DateTime());
125
+        }
126
+
127
+        if ($comment->getParentId() !== '0') {
128
+            $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
129
+        } else {
130
+            $comment->setTopmostParentId('0');
131
+        }
132
+
133
+        $this->cache($comment);
134
+
135
+        return $comment;
136
+    }
137
+
138
+    /**
139
+     * returns the topmost parent id of a given comment identified by ID
140
+     *
141
+     * @param string $id
142
+     * @return string
143
+     * @throws NotFoundException
144
+     */
145
+    protected function determineTopmostParentId($id) {
146
+        $comment = $this->get($id);
147
+        if ($comment->getParentId() === '0') {
148
+            return $comment->getId();
149
+        } else {
150
+            return $this->determineTopmostParentId($comment->getId());
151
+        }
152
+    }
153
+
154
+    /**
155
+     * updates child information of a comment
156
+     *
157
+     * @param string $id
158
+     * @param \DateTime $cDateTime the date time of the most recent child
159
+     * @throws NotFoundException
160
+     */
161
+    protected function updateChildrenInformation($id, \DateTime $cDateTime) {
162
+        $qb = $this->dbConn->getQueryBuilder();
163
+        $query = $qb->select($qb->createFunction('COUNT(`id`)'))
164
+            ->from('comments')
165
+            ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
166
+            ->setParameter('id', $id);
167
+
168
+        $resultStatement = $query->execute();
169
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
170
+        $resultStatement->closeCursor();
171
+        $children = intval($data[0]);
172
+
173
+        $comment = $this->get($id);
174
+        $comment->setChildrenCount($children);
175
+        $comment->setLatestChildDateTime($cDateTime);
176
+        $this->save($comment);
177
+    }
178
+
179
+    /**
180
+     * Tests whether actor or object type and id parameters are acceptable.
181
+     * Throws exception if not.
182
+     *
183
+     * @param string $role
184
+     * @param string $type
185
+     * @param string $id
186
+     * @throws \InvalidArgumentException
187
+     */
188
+    protected function checkRoleParameters($role, $type, $id) {
189
+        if (
190
+            !is_string($type) || empty($type)
191
+            || !is_string($id) || empty($id)
192
+        ) {
193
+            throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
194
+        }
195
+    }
196
+
197
+    /**
198
+     * run-time caches a comment
199
+     *
200
+     * @param IComment $comment
201
+     */
202
+    protected function cache(IComment $comment) {
203
+        $id = $comment->getId();
204
+        if (empty($id)) {
205
+            return;
206
+        }
207
+        $this->commentsCache[strval($id)] = $comment;
208
+    }
209
+
210
+    /**
211
+     * removes an entry from the comments run time cache
212
+     *
213
+     * @param mixed $id the comment's id
214
+     */
215
+    protected function uncache($id) {
216
+        $id = strval($id);
217
+        if (isset($this->commentsCache[$id])) {
218
+            unset($this->commentsCache[$id]);
219
+        }
220
+    }
221
+
222
+    /**
223
+     * returns a comment instance
224
+     *
225
+     * @param string $id the ID of the comment
226
+     * @return IComment
227
+     * @throws NotFoundException
228
+     * @throws \InvalidArgumentException
229
+     * @since 9.0.0
230
+     */
231
+    public function get($id) {
232
+        if (intval($id) === 0) {
233
+            throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
234
+        }
235
+
236
+        if (isset($this->commentsCache[$id])) {
237
+            return $this->commentsCache[$id];
238
+        }
239
+
240
+        $qb = $this->dbConn->getQueryBuilder();
241
+        $resultStatement = $qb->select('*')
242
+            ->from('comments')
243
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
244
+            ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
245
+            ->execute();
246
+
247
+        $data = $resultStatement->fetch();
248
+        $resultStatement->closeCursor();
249
+        if (!$data) {
250
+            throw new NotFoundException();
251
+        }
252
+
253
+        $comment = new Comment($this->normalizeDatabaseData($data));
254
+        $this->cache($comment);
255
+        return $comment;
256
+    }
257
+
258
+    /**
259
+     * returns the comment specified by the id and all it's child comments.
260
+     * At this point of time, we do only support one level depth.
261
+     *
262
+     * @param string $id
263
+     * @param int $limit max number of entries to return, 0 returns all
264
+     * @param int $offset the start entry
265
+     * @return array
266
+     * @since 9.0.0
267
+     *
268
+     * The return array looks like this
269
+     * [
270
+     *   'comment' => IComment, // root comment
271
+     *   'replies' =>
272
+     *   [
273
+     *     0 =>
274
+     *     [
275
+     *       'comment' => IComment,
276
+     *       'replies' => []
277
+     *     ]
278
+     *     1 =>
279
+     *     [
280
+     *       'comment' => IComment,
281
+     *       'replies'=> []
282
+     *     ],
283
+     *     …
284
+     *   ]
285
+     * ]
286
+     */
287
+    public function getTree($id, $limit = 0, $offset = 0) {
288
+        $tree = [];
289
+        $tree['comment'] = $this->get($id);
290
+        $tree['replies'] = [];
291
+
292
+        $qb = $this->dbConn->getQueryBuilder();
293
+        $query = $qb->select('*')
294
+            ->from('comments')
295
+            ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
296
+            ->orderBy('creation_timestamp', 'DESC')
297
+            ->setParameter('id', $id);
298
+
299
+        if ($limit > 0) {
300
+            $query->setMaxResults($limit);
301
+        }
302
+        if ($offset > 0) {
303
+            $query->setFirstResult($offset);
304
+        }
305
+
306
+        $resultStatement = $query->execute();
307
+        while ($data = $resultStatement->fetch()) {
308
+            $comment = new Comment($this->normalizeDatabaseData($data));
309
+            $this->cache($comment);
310
+            $tree['replies'][] = [
311
+                'comment' => $comment,
312
+                'replies' => []
313
+            ];
314
+        }
315
+        $resultStatement->closeCursor();
316
+
317
+        return $tree;
318
+    }
319
+
320
+    /**
321
+     * returns comments for a specific object (e.g. a file).
322
+     *
323
+     * The sort order is always newest to oldest.
324
+     *
325
+     * @param string $objectType the object type, e.g. 'files'
326
+     * @param string $objectId the id of the object
327
+     * @param int $limit optional, number of maximum comments to be returned. if
328
+     * not specified, all comments are returned.
329
+     * @param int $offset optional, starting point
330
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
331
+     * that may be returned
332
+     * @return IComment[]
333
+     * @since 9.0.0
334
+     */
335
+    public function getForObject(
336
+        $objectType,
337
+        $objectId,
338
+        $limit = 0,
339
+        $offset = 0,
340
+        \DateTime $notOlderThan = null
341
+    ) {
342
+        $comments = [];
343
+
344
+        $qb = $this->dbConn->getQueryBuilder();
345
+        $query = $qb->select('*')
346
+            ->from('comments')
347
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
348
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
349
+            ->orderBy('creation_timestamp', 'DESC')
350
+            ->setParameter('type', $objectType)
351
+            ->setParameter('id', $objectId);
352
+
353
+        if ($limit > 0) {
354
+            $query->setMaxResults($limit);
355
+        }
356
+        if ($offset > 0) {
357
+            $query->setFirstResult($offset);
358
+        }
359
+        if (!is_null($notOlderThan)) {
360
+            $query
361
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
362
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
363
+        }
364
+
365
+        $resultStatement = $query->execute();
366
+        while ($data = $resultStatement->fetch()) {
367
+            $comment = new Comment($this->normalizeDatabaseData($data));
368
+            $this->cache($comment);
369
+            $comments[] = $comment;
370
+        }
371
+        $resultStatement->closeCursor();
372
+
373
+        return $comments;
374
+    }
375
+
376
+    /**
377
+     * @param $objectType string the object type, e.g. 'files'
378
+     * @param $objectId string the id of the object
379
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
380
+     * that may be returned
381
+     * @return Int
382
+     * @since 9.0.0
383
+     */
384
+    public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) {
385
+        $qb = $this->dbConn->getQueryBuilder();
386
+        $query = $qb->select($qb->createFunction('COUNT(`id`)'))
387
+            ->from('comments')
388
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
389
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
390
+            ->setParameter('type', $objectType)
391
+            ->setParameter('id', $objectId);
392
+
393
+        if (!is_null($notOlderThan)) {
394
+            $query
395
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
396
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
397
+        }
398
+
399
+        $resultStatement = $query->execute();
400
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
401
+        $resultStatement->closeCursor();
402
+        return intval($data[0]);
403
+    }
404
+
405
+    /**
406
+     * Get the number of unread comments for all files in a folder
407
+     *
408
+     * @param int $folderId
409
+     * @param IUser $user
410
+     * @return array [$fileId => $unreadCount]
411
+     */
412
+    public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
413
+        $qb = $this->dbConn->getQueryBuilder();
414
+        $query = $qb->select(
415
+            'fileid',
416
+            $qb->createFunction(
417
+            'COUNT(' . $qb->getColumnName('c.id') . ')'
418
+        )
419
+        )->from('comments', 'c')
420
+            ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
421
+                $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
422
+                $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT))
423
+            ))
424
+            ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
425
+                $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
426
+                $qb->expr()->eq('m.object_id', 'c.object_id'),
427
+                $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID()))
428
+            ))
429
+            ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)))
430
+            ->andWhere($qb->expr()->orX(
431
+                $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'),
432
+                $qb->expr()->isNull('marker_datetime')
433
+            ))
434
+            ->groupBy('f.fileid');
435
+
436
+        $resultStatement = $query->execute();
437
+        return array_map(function ($count) {
438
+            return (int)$count;
439
+        }, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR));
440
+    }
441
+
442
+    /**
443
+     * creates a new comment and returns it. At this point of time, it is not
444
+     * saved in the used data storage. Use save() after setting other fields
445
+     * of the comment (e.g. message or verb).
446
+     *
447
+     * @param string $actorType the actor type (e.g. 'users')
448
+     * @param string $actorId a user id
449
+     * @param string $objectType the object type the comment is attached to
450
+     * @param string $objectId the object id the comment is attached to
451
+     * @return IComment
452
+     * @since 9.0.0
453
+     */
454
+    public function create($actorType, $actorId, $objectType, $objectId) {
455
+        $comment = new Comment();
456
+        $comment
457
+            ->setActor($actorType, $actorId)
458
+            ->setObject($objectType, $objectId);
459
+        return $comment;
460
+    }
461
+
462
+    /**
463
+     * permanently deletes the comment specified by the ID
464
+     *
465
+     * When the comment has child comments, their parent ID will be changed to
466
+     * the parent ID of the item that is to be deleted.
467
+     *
468
+     * @param string $id
469
+     * @return bool
470
+     * @throws \InvalidArgumentException
471
+     * @since 9.0.0
472
+     */
473
+    public function delete($id) {
474
+        if (!is_string($id)) {
475
+            throw new \InvalidArgumentException('Parameter must be string');
476
+        }
477
+
478
+        try {
479
+            $comment = $this->get($id);
480
+        } catch (\Exception $e) {
481
+            // Ignore exceptions, we just don't fire a hook then
482
+            $comment = null;
483
+        }
484
+
485
+        $qb = $this->dbConn->getQueryBuilder();
486
+        $query = $qb->delete('comments')
487
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
488
+            ->setParameter('id', $id);
489
+
490
+        try {
491
+            $affectedRows = $query->execute();
492
+            $this->uncache($id);
493
+        } catch (DriverException $e) {
494
+            $this->logger->logException($e, ['app' => 'core_comments']);
495
+            return false;
496
+        }
497
+
498
+        if ($affectedRows > 0 && $comment instanceof IComment) {
499
+            $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
500
+        }
501
+
502
+        return ($affectedRows > 0);
503
+    }
504
+
505
+    /**
506
+     * saves the comment permanently
507
+     *
508
+     * if the supplied comment has an empty ID, a new entry comment will be
509
+     * saved and the instance updated with the new ID.
510
+     *
511
+     * Otherwise, an existing comment will be updated.
512
+     *
513
+     * Throws NotFoundException when a comment that is to be updated does not
514
+     * exist anymore at this point of time.
515
+     *
516
+     * @param IComment $comment
517
+     * @return bool
518
+     * @throws NotFoundException
519
+     * @since 9.0.0
520
+     */
521
+    public function save(IComment $comment) {
522
+        if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
523
+            $result = $this->insert($comment);
524
+        } else {
525
+            $result = $this->update($comment);
526
+        }
527
+
528
+        if ($result && !!$comment->getParentId()) {
529
+            $this->updateChildrenInformation(
530
+                $comment->getParentId(),
531
+                $comment->getCreationDateTime()
532
+            );
533
+            $this->cache($comment);
534
+        }
535
+
536
+        return $result;
537
+    }
538
+
539
+    /**
540
+     * inserts the provided comment in the database
541
+     *
542
+     * @param IComment $comment
543
+     * @return bool
544
+     */
545
+    protected function insert(IComment &$comment) {
546
+        $qb = $this->dbConn->getQueryBuilder();
547
+        $affectedRows = $qb
548
+            ->insert('comments')
549
+            ->values([
550
+                'parent_id' => $qb->createNamedParameter($comment->getParentId()),
551
+                'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
552
+                'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
553
+                'actor_type' => $qb->createNamedParameter($comment->getActorType()),
554
+                'actor_id' => $qb->createNamedParameter($comment->getActorId()),
555
+                'message' => $qb->createNamedParameter($comment->getMessage()),
556
+                'verb' => $qb->createNamedParameter($comment->getVerb()),
557
+                'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
558
+                'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
559
+                'object_type' => $qb->createNamedParameter($comment->getObjectType()),
560
+                'object_id' => $qb->createNamedParameter($comment->getObjectId()),
561
+            ])
562
+            ->execute();
563
+
564
+        if ($affectedRows > 0) {
565
+            $comment->setId(strval($qb->getLastInsertId()));
566
+            $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
567
+        }
568
+
569
+        return $affectedRows > 0;
570
+    }
571
+
572
+    /**
573
+     * updates a Comment data row
574
+     *
575
+     * @param IComment $comment
576
+     * @return bool
577
+     * @throws NotFoundException
578
+     */
579
+    protected function update(IComment $comment) {
580
+        // for properly working preUpdate Events we need the old comments as is
581
+        // in the DB and overcome caching. Also avoid that outdated information stays.
582
+        $this->uncache($comment->getId());
583
+        $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
584
+        $this->uncache($comment->getId());
585
+
586
+        $qb = $this->dbConn->getQueryBuilder();
587
+        $affectedRows = $qb
588
+            ->update('comments')
589
+            ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
590
+            ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
591
+            ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
592
+            ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
593
+            ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
594
+            ->set('message', $qb->createNamedParameter($comment->getMessage()))
595
+            ->set('verb', $qb->createNamedParameter($comment->getVerb()))
596
+            ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
597
+            ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
598
+            ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
599
+            ->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
600
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
601
+            ->setParameter('id', $comment->getId())
602
+            ->execute();
603
+
604
+        if ($affectedRows === 0) {
605
+            throw new NotFoundException('Comment to update does ceased to exist');
606
+        }
607
+
608
+        $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
609
+
610
+        return $affectedRows > 0;
611
+    }
612
+
613
+    /**
614
+     * removes references to specific actor (e.g. on user delete) of a comment.
615
+     * The comment itself must not get lost/deleted.
616
+     *
617
+     * @param string $actorType the actor type (e.g. 'users')
618
+     * @param string $actorId a user id
619
+     * @return boolean
620
+     * @since 9.0.0
621
+     */
622
+    public function deleteReferencesOfActor($actorType, $actorId) {
623
+        $this->checkRoleParameters('Actor', $actorType, $actorId);
624
+
625
+        $qb = $this->dbConn->getQueryBuilder();
626
+        $affectedRows = $qb
627
+            ->update('comments')
628
+            ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
629
+            ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
630
+            ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
631
+            ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
632
+            ->setParameter('type', $actorType)
633
+            ->setParameter('id', $actorId)
634
+            ->execute();
635
+
636
+        $this->commentsCache = [];
637
+
638
+        return is_int($affectedRows);
639
+    }
640
+
641
+    /**
642
+     * deletes all comments made of a specific object (e.g. on file delete)
643
+     *
644
+     * @param string $objectType the object type (e.g. 'files')
645
+     * @param string $objectId e.g. the file id
646
+     * @return boolean
647
+     * @since 9.0.0
648
+     */
649
+    public function deleteCommentsAtObject($objectType, $objectId) {
650
+        $this->checkRoleParameters('Object', $objectType, $objectId);
651
+
652
+        $qb = $this->dbConn->getQueryBuilder();
653
+        $affectedRows = $qb
654
+            ->delete('comments')
655
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
656
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
657
+            ->setParameter('type', $objectType)
658
+            ->setParameter('id', $objectId)
659
+            ->execute();
660
+
661
+        $this->commentsCache = [];
662
+
663
+        return is_int($affectedRows);
664
+    }
665
+
666
+    /**
667
+     * deletes the read markers for the specified user
668
+     *
669
+     * @param \OCP\IUser $user
670
+     * @return bool
671
+     * @since 9.0.0
672
+     */
673
+    public function deleteReadMarksFromUser(IUser $user) {
674
+        $qb = $this->dbConn->getQueryBuilder();
675
+        $query = $qb->delete('comments_read_markers')
676
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
677
+            ->setParameter('user_id', $user->getUID());
678
+
679
+        try {
680
+            $affectedRows = $query->execute();
681
+        } catch (DriverException $e) {
682
+            $this->logger->logException($e, ['app' => 'core_comments']);
683
+            return false;
684
+        }
685
+        return ($affectedRows > 0);
686
+    }
687
+
688
+    /**
689
+     * sets the read marker for a given file to the specified date for the
690
+     * provided user
691
+     *
692
+     * @param string $objectType
693
+     * @param string $objectId
694
+     * @param \DateTime $dateTime
695
+     * @param IUser $user
696
+     * @since 9.0.0
697
+     * @suppress SqlInjectionChecker
698
+     */
699
+    public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
700
+        $this->checkRoleParameters('Object', $objectType, $objectId);
701
+
702
+        $qb = $this->dbConn->getQueryBuilder();
703
+        $values = [
704
+            'user_id' => $qb->createNamedParameter($user->getUID()),
705
+            'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
706
+            'object_type' => $qb->createNamedParameter($objectType),
707
+            'object_id' => $qb->createNamedParameter($objectId),
708
+        ];
709
+
710
+        // Strategy: try to update, if this does not return affected rows, do an insert.
711
+        $affectedRows = $qb
712
+            ->update('comments_read_markers')
713
+            ->set('user_id', $values['user_id'])
714
+            ->set('marker_datetime', $values['marker_datetime'])
715
+            ->set('object_type', $values['object_type'])
716
+            ->set('object_id', $values['object_id'])
717
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
718
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
719
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
720
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
721
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
722
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
723
+            ->execute();
724
+
725
+        if ($affectedRows > 0) {
726
+            return;
727
+        }
728
+
729
+        $qb->insert('comments_read_markers')
730
+            ->values($values)
731
+            ->execute();
732
+    }
733
+
734
+    /**
735
+     * returns the read marker for a given file to the specified date for the
736
+     * provided user. It returns null, when the marker is not present, i.e.
737
+     * no comments were marked as read.
738
+     *
739
+     * @param string $objectType
740
+     * @param string $objectId
741
+     * @param IUser $user
742
+     * @return \DateTime|null
743
+     * @since 9.0.0
744
+     */
745
+    public function getReadMark($objectType, $objectId, IUser $user) {
746
+        $qb = $this->dbConn->getQueryBuilder();
747
+        $resultStatement = $qb->select('marker_datetime')
748
+            ->from('comments_read_markers')
749
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
750
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
751
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
752
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
753
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
754
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
755
+            ->execute();
756
+
757
+        $data = $resultStatement->fetch();
758
+        $resultStatement->closeCursor();
759
+        if (!$data || is_null($data['marker_datetime'])) {
760
+            return null;
761
+        }
762
+
763
+        return new \DateTime($data['marker_datetime']);
764
+    }
765
+
766
+    /**
767
+     * deletes the read markers on the specified object
768
+     *
769
+     * @param string $objectType
770
+     * @param string $objectId
771
+     * @return bool
772
+     * @since 9.0.0
773
+     */
774
+    public function deleteReadMarksOnObject($objectType, $objectId) {
775
+        $this->checkRoleParameters('Object', $objectType, $objectId);
776
+
777
+        $qb = $this->dbConn->getQueryBuilder();
778
+        $query = $qb->delete('comments_read_markers')
779
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
780
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
781
+            ->setParameter('object_type', $objectType)
782
+            ->setParameter('object_id', $objectId);
783
+
784
+        try {
785
+            $affectedRows = $query->execute();
786
+        } catch (DriverException $e) {
787
+            $this->logger->logException($e, ['app' => 'core_comments']);
788
+            return false;
789
+        }
790
+        return ($affectedRows > 0);
791
+    }
792
+
793
+    /**
794
+     * registers an Entity to the manager, so event notifications can be send
795
+     * to consumers of the comments infrastructure
796
+     *
797
+     * @param \Closure $closure
798
+     */
799
+    public function registerEventHandler(\Closure $closure) {
800
+        $this->eventHandlerClosures[] = $closure;
801
+        $this->eventHandlers = [];
802
+    }
803
+
804
+    /**
805
+     * registers a method that resolves an ID to a display name for a given type
806
+     *
807
+     * @param string $type
808
+     * @param \Closure $closure
809
+     * @throws \OutOfBoundsException
810
+     * @since 11.0.0
811
+     *
812
+     * Only one resolver shall be registered per type. Otherwise a
813
+     * \OutOfBoundsException has to thrown.
814
+     */
815
+    public function registerDisplayNameResolver($type, \Closure $closure) {
816
+        if (!is_string($type)) {
817
+            throw new \InvalidArgumentException('String expected.');
818
+        }
819
+        if (isset($this->displayNameResolvers[$type])) {
820
+            throw new \OutOfBoundsException('Displayname resolver for this type already registered');
821
+        }
822
+        $this->displayNameResolvers[$type] = $closure;
823
+    }
824
+
825
+    /**
826
+     * resolves a given ID of a given Type to a display name.
827
+     *
828
+     * @param string $type
829
+     * @param string $id
830
+     * @return string
831
+     * @throws \OutOfBoundsException
832
+     * @since 11.0.0
833
+     *
834
+     * If a provided type was not registered, an \OutOfBoundsException shall
835
+     * be thrown. It is upon the resolver discretion what to return of the
836
+     * provided ID is unknown. It must be ensured that a string is returned.
837
+     */
838
+    public function resolveDisplayName($type, $id) {
839
+        if (!is_string($type)) {
840
+            throw new \InvalidArgumentException('String expected.');
841
+        }
842
+        if (!isset($this->displayNameResolvers[$type])) {
843
+            throw new \OutOfBoundsException('No Displayname resolver for this type registered');
844
+        }
845
+        return (string)$this->displayNameResolvers[$type]($id);
846
+    }
847
+
848
+    /**
849
+     * returns valid, registered entities
850
+     *
851
+     * @return \OCP\Comments\ICommentsEventHandler[]
852
+     */
853
+    private function getEventHandlers() {
854
+        if (!empty($this->eventHandlers)) {
855
+            return $this->eventHandlers;
856
+        }
857
+
858
+        $this->eventHandlers = [];
859
+        foreach ($this->eventHandlerClosures as $name => $closure) {
860
+            $entity = $closure();
861
+            if (!($entity instanceof ICommentsEventHandler)) {
862
+                throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
863
+            }
864
+            $this->eventHandlers[$name] = $entity;
865
+        }
866
+
867
+        return $this->eventHandlers;
868
+    }
869
+
870
+    /**
871
+     * sends notifications to the registered entities
872
+     *
873
+     * @param $eventType
874
+     * @param IComment $comment
875
+     */
876
+    private function sendEvent($eventType, IComment $comment) {
877
+        $entities = $this->getEventHandlers();
878
+        $event = new CommentsEvent($eventType, $comment);
879
+        foreach ($entities as $entity) {
880
+            $entity->handle($event);
881
+        }
882
+    }
883 883
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 			!is_string($type) || empty($type)
191 191
 			|| !is_string($id) || empty($id)
192 192
 		) {
193
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
193
+			throw new \InvalidArgumentException($role.' parameters must be string and not empty');
194 194
 		}
195 195
 	}
196 196
 
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 		$query = $qb->select(
415 415
 			'fileid',
416 416
 			$qb->createFunction(
417
-			'COUNT(' . $qb->getColumnName('c.id') . ')'
417
+			'COUNT('.$qb->getColumnName('c.id').')'
418 418
 		)
419 419
 		)->from('comments', 'c')
420 420
 			->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
@@ -434,8 +434,8 @@  discard block
 block discarded – undo
434 434
 			->groupBy('f.fileid');
435 435
 
436 436
 		$resultStatement = $query->execute();
437
-		return array_map(function ($count) {
438
-			return (int)$count;
437
+		return array_map(function($count) {
438
+			return (int) $count;
439 439
 		}, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR));
440 440
 	}
441 441
 
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
 	 * @param IComment $comment
543 543
 	 * @return bool
544 544
 	 */
545
-	protected function insert(IComment &$comment) {
545
+	protected function insert(IComment & $comment) {
546 546
 		$qb = $this->dbConn->getQueryBuilder();
547 547
 		$affectedRows = $qb
548 548
 			->insert('comments')
@@ -842,7 +842,7 @@  discard block
 block discarded – undo
842 842
 		if (!isset($this->displayNameResolvers[$type])) {
843 843
 			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
844 844
 		}
845
-		return (string)$this->displayNameResolvers[$type]($id);
845
+		return (string) $this->displayNameResolvers[$type]($id);
846 846
 	}
847 847
 
848 848
 	/**
Please login to merge, or discard this patch.
lib/private/DB/Connection.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
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
 block discarded – undo
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) {
Please login to merge, or discard this patch.
Indentation   +402 added lines, -402 removed lines patch added patch discarded remove patch
@@ -42,406 +42,406 @@
 block discarded – undo
42 42
 use OCP\PreConditionNotMetException;
43 43
 
44 44
 class Connection extends \Doctrine\DBAL\Connection implements IDBConnection {
45
-	/**
46
-	 * @var string $tablePrefix
47
-	 */
48
-	protected $tablePrefix;
49
-
50
-	/**
51
-	 * @var \OC\DB\Adapter $adapter
52
-	 */
53
-	protected $adapter;
54
-
55
-	protected $lockedTable = null;
56
-
57
-	public function connect() {
58
-		try {
59
-			return parent::connect();
60
-		} catch (DBALException $e) {
61
-			// throw a new exception to prevent leaking info from the stacktrace
62
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
63
-		}
64
-	}
65
-
66
-	/**
67
-	 * Returns a QueryBuilder for the connection.
68
-	 *
69
-	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
70
-	 */
71
-	public function getQueryBuilder() {
72
-		return new QueryBuilder(
73
-			$this,
74
-			\OC::$server->getSystemConfig(),
75
-			\OC::$server->getLogger()
76
-		);
77
-	}
78
-
79
-	/**
80
-	 * Gets the QueryBuilder for the connection.
81
-	 *
82
-	 * @return \Doctrine\DBAL\Query\QueryBuilder
83
-	 * @deprecated please use $this->getQueryBuilder() instead
84
-	 */
85
-	public function createQueryBuilder() {
86
-		$backtrace = $this->getCallerBacktrace();
87
-		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
88
-		return parent::createQueryBuilder();
89
-	}
90
-
91
-	/**
92
-	 * Gets the ExpressionBuilder for the connection.
93
-	 *
94
-	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
95
-	 * @deprecated please use $this->getQueryBuilder()->expr() instead
96
-	 */
97
-	public function getExpressionBuilder() {
98
-		$backtrace = $this->getCallerBacktrace();
99
-		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
100
-		return parent::getExpressionBuilder();
101
-	}
102
-
103
-	/**
104
-	 * Get the file and line that called the method where `getCallerBacktrace()` was used
105
-	 *
106
-	 * @return string
107
-	 */
108
-	protected function getCallerBacktrace() {
109
-		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
110
-
111
-		// 0 is the method where we use `getCallerBacktrace`
112
-		// 1 is the target method which uses the method we want to log
113
-		if (isset($traces[1])) {
114
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
115
-		}
116
-
117
-		return '';
118
-	}
119
-
120
-	/**
121
-	 * @return string
122
-	 */
123
-	public function getPrefix() {
124
-		return $this->tablePrefix;
125
-	}
126
-
127
-	/**
128
-	 * Initializes a new instance of the Connection class.
129
-	 *
130
-	 * @param array $params  The connection parameters.
131
-	 * @param \Doctrine\DBAL\Driver $driver
132
-	 * @param \Doctrine\DBAL\Configuration $config
133
-	 * @param \Doctrine\Common\EventManager $eventManager
134
-	 * @throws \Exception
135
-	 */
136
-	public function __construct(
137
-		array $params,
138
-		Driver $driver,
139
-		Configuration $config = null,
140
-		EventManager $eventManager = null
141
-	) {
142
-		if (!isset($params['adapter'])) {
143
-			throw new \Exception('adapter not set');
144
-		}
145
-		if (!isset($params['tablePrefix'])) {
146
-			throw new \Exception('tablePrefix not set');
147
-		}
148
-		parent::__construct($params, $driver, $config, $eventManager);
149
-		$this->adapter = new $params['adapter']($this);
150
-		$this->tablePrefix = $params['tablePrefix'];
151
-
152
-		parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
153
-	}
154
-
155
-	/**
156
-	 * Prepares an SQL statement.
157
-	 *
158
-	 * @param string $statement The SQL statement to prepare.
159
-	 * @param int $limit
160
-	 * @param int $offset
161
-	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
162
-	 */
163
-	public function prepare($statement, $limit = null, $offset = null) {
164
-		if ($limit === -1) {
165
-			$limit = null;
166
-		}
167
-		if (!is_null($limit)) {
168
-			$platform = $this->getDatabasePlatform();
169
-			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
170
-		}
171
-		$statement = $this->replaceTablePrefix($statement);
172
-		$statement = $this->adapter->fixupStatement($statement);
173
-
174
-		return parent::prepare($statement);
175
-	}
176
-
177
-	/**
178
-	 * Executes an, optionally parametrized, SQL query.
179
-	 *
180
-	 * If the query is parametrized, a prepared statement is used.
181
-	 * If an SQLLogger is configured, the execution is logged.
182
-	 *
183
-	 * @param string                                      $query  The SQL query to execute.
184
-	 * @param array                                       $params The parameters to bind to the query, if any.
185
-	 * @param array                                       $types  The types the previous parameters are in.
186
-	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
187
-	 *
188
-	 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
189
-	 *
190
-	 * @throws \Doctrine\DBAL\DBALException
191
-	 */
192
-	public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) {
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 $types = []) {
213
-		$query = $this->replaceTablePrefix($query);
214
-		$query = $this->adapter->fixupStatement($query);
215
-		return parent::executeUpdate($query, $params, $types);
216
-	}
217
-
218
-	/**
219
-	 * Returns the ID of the last inserted row, or the last value from a sequence object,
220
-	 * depending on the underlying driver.
221
-	 *
222
-	 * Note: This method may not return a meaningful or consistent result across different drivers,
223
-	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
224
-	 * columns or sequences.
225
-	 *
226
-	 * @param string $seqName Name of the sequence object from which the ID should be returned.
227
-	 * @return string A string representation of the last inserted ID.
228
-	 */
229
-	public function lastInsertId($seqName = null) {
230
-		if ($seqName) {
231
-			$seqName = $this->replaceTablePrefix($seqName);
232
-		}
233
-		return $this->adapter->lastInsertId($seqName);
234
-	}
235
-
236
-	// internal use
237
-	public function realLastInsertId($seqName = null) {
238
-		return parent::lastInsertId($seqName);
239
-	}
240
-
241
-	/**
242
-	 * Insert a row if the matching row does not exists.
243
-	 *
244
-	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
245
-	 * @param array $input data that should be inserted into the table  (column name => value)
246
-	 * @param array|null $compare List of values that should be checked for "if not exists"
247
-	 *				If this is null or an empty array, all keys of $input will be compared
248
-	 *				Please note: text fields (clob) must not be used in the compare array
249
-	 * @return int number of inserted rows
250
-	 * @throws \Doctrine\DBAL\DBALException
251
-	 */
252
-	public function insertIfNotExist($table, $input, array $compare = null) {
253
-		return $this->adapter->insertIfNotExist($table, $input, $compare);
254
-	}
255
-
256
-	private function getType($value) {
257
-		if (is_bool($value)) {
258
-			return IQueryBuilder::PARAM_BOOL;
259
-		} elseif (is_int($value)) {
260
-			return IQueryBuilder::PARAM_INT;
261
-		} else {
262
-			return IQueryBuilder::PARAM_STR;
263
-		}
264
-	}
265
-
266
-	/**
267
-	 * Insert or update a row value
268
-	 *
269
-	 * @param string $table
270
-	 * @param array $keys (column name => value)
271
-	 * @param array $values (column name => value)
272
-	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
273
-	 * @return int number of new rows
274
-	 * @throws \Doctrine\DBAL\DBALException
275
-	 * @throws PreConditionNotMetException
276
-	 * @suppress SqlInjectionChecker
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([$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([$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
-
425
-
426
-	/**
427
-	 * Create the schema of the connected database
428
-	 *
429
-	 * @return Schema
430
-	 */
431
-	public function createSchema() {
432
-		$schemaManager = new MDB2SchemaManager($this);
433
-		$migrator = $schemaManager->getMigrator();
434
-		return $migrator->createSchema();
435
-	}
436
-
437
-	/**
438
-	 * Migrate the database to the given schema
439
-	 *
440
-	 * @param Schema $toSchema
441
-	 */
442
-	public function migrateToSchema(Schema $toSchema) {
443
-		$schemaManager = new MDB2SchemaManager($this);
444
-		$migrator = $schemaManager->getMigrator();
445
-		$migrator->migrate($toSchema);
446
-	}
45
+    /**
46
+     * @var string $tablePrefix
47
+     */
48
+    protected $tablePrefix;
49
+
50
+    /**
51
+     * @var \OC\DB\Adapter $adapter
52
+     */
53
+    protected $adapter;
54
+
55
+    protected $lockedTable = null;
56
+
57
+    public function connect() {
58
+        try {
59
+            return parent::connect();
60
+        } catch (DBALException $e) {
61
+            // throw a new exception to prevent leaking info from the stacktrace
62
+            throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
63
+        }
64
+    }
65
+
66
+    /**
67
+     * Returns a QueryBuilder for the connection.
68
+     *
69
+     * @return \OCP\DB\QueryBuilder\IQueryBuilder
70
+     */
71
+    public function getQueryBuilder() {
72
+        return new QueryBuilder(
73
+            $this,
74
+            \OC::$server->getSystemConfig(),
75
+            \OC::$server->getLogger()
76
+        );
77
+    }
78
+
79
+    /**
80
+     * Gets the QueryBuilder for the connection.
81
+     *
82
+     * @return \Doctrine\DBAL\Query\QueryBuilder
83
+     * @deprecated please use $this->getQueryBuilder() instead
84
+     */
85
+    public function createQueryBuilder() {
86
+        $backtrace = $this->getCallerBacktrace();
87
+        \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
88
+        return parent::createQueryBuilder();
89
+    }
90
+
91
+    /**
92
+     * Gets the ExpressionBuilder for the connection.
93
+     *
94
+     * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
95
+     * @deprecated please use $this->getQueryBuilder()->expr() instead
96
+     */
97
+    public function getExpressionBuilder() {
98
+        $backtrace = $this->getCallerBacktrace();
99
+        \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
100
+        return parent::getExpressionBuilder();
101
+    }
102
+
103
+    /**
104
+     * Get the file and line that called the method where `getCallerBacktrace()` was used
105
+     *
106
+     * @return string
107
+     */
108
+    protected function getCallerBacktrace() {
109
+        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
110
+
111
+        // 0 is the method where we use `getCallerBacktrace`
112
+        // 1 is the target method which uses the method we want to log
113
+        if (isset($traces[1])) {
114
+            return $traces[1]['file'] . ':' . $traces[1]['line'];
115
+        }
116
+
117
+        return '';
118
+    }
119
+
120
+    /**
121
+     * @return string
122
+     */
123
+    public function getPrefix() {
124
+        return $this->tablePrefix;
125
+    }
126
+
127
+    /**
128
+     * Initializes a new instance of the Connection class.
129
+     *
130
+     * @param array $params  The connection parameters.
131
+     * @param \Doctrine\DBAL\Driver $driver
132
+     * @param \Doctrine\DBAL\Configuration $config
133
+     * @param \Doctrine\Common\EventManager $eventManager
134
+     * @throws \Exception
135
+     */
136
+    public function __construct(
137
+        array $params,
138
+        Driver $driver,
139
+        Configuration $config = null,
140
+        EventManager $eventManager = null
141
+    ) {
142
+        if (!isset($params['adapter'])) {
143
+            throw new \Exception('adapter not set');
144
+        }
145
+        if (!isset($params['tablePrefix'])) {
146
+            throw new \Exception('tablePrefix not set');
147
+        }
148
+        parent::__construct($params, $driver, $config, $eventManager);
149
+        $this->adapter = new $params['adapter']($this);
150
+        $this->tablePrefix = $params['tablePrefix'];
151
+
152
+        parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
153
+    }
154
+
155
+    /**
156
+     * Prepares an SQL statement.
157
+     *
158
+     * @param string $statement The SQL statement to prepare.
159
+     * @param int $limit
160
+     * @param int $offset
161
+     * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
162
+     */
163
+    public function prepare($statement, $limit = null, $offset = null) {
164
+        if ($limit === -1) {
165
+            $limit = null;
166
+        }
167
+        if (!is_null($limit)) {
168
+            $platform = $this->getDatabasePlatform();
169
+            $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
170
+        }
171
+        $statement = $this->replaceTablePrefix($statement);
172
+        $statement = $this->adapter->fixupStatement($statement);
173
+
174
+        return parent::prepare($statement);
175
+    }
176
+
177
+    /**
178
+     * Executes an, optionally parametrized, SQL query.
179
+     *
180
+     * If the query is parametrized, a prepared statement is used.
181
+     * If an SQLLogger is configured, the execution is logged.
182
+     *
183
+     * @param string                                      $query  The SQL query to execute.
184
+     * @param array                                       $params The parameters to bind to the query, if any.
185
+     * @param array                                       $types  The types the previous parameters are in.
186
+     * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
187
+     *
188
+     * @return \Doctrine\DBAL\Driver\Statement The executed statement.
189
+     *
190
+     * @throws \Doctrine\DBAL\DBALException
191
+     */
192
+    public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) {
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 $types = []) {
213
+        $query = $this->replaceTablePrefix($query);
214
+        $query = $this->adapter->fixupStatement($query);
215
+        return parent::executeUpdate($query, $params, $types);
216
+    }
217
+
218
+    /**
219
+     * Returns the ID of the last inserted row, or the last value from a sequence object,
220
+     * depending on the underlying driver.
221
+     *
222
+     * Note: This method may not return a meaningful or consistent result across different drivers,
223
+     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
224
+     * columns or sequences.
225
+     *
226
+     * @param string $seqName Name of the sequence object from which the ID should be returned.
227
+     * @return string A string representation of the last inserted ID.
228
+     */
229
+    public function lastInsertId($seqName = null) {
230
+        if ($seqName) {
231
+            $seqName = $this->replaceTablePrefix($seqName);
232
+        }
233
+        return $this->adapter->lastInsertId($seqName);
234
+    }
235
+
236
+    // internal use
237
+    public function realLastInsertId($seqName = null) {
238
+        return parent::lastInsertId($seqName);
239
+    }
240
+
241
+    /**
242
+     * Insert a row if the matching row does not exists.
243
+     *
244
+     * @param string $table The table name (will replace *PREFIX* with the actual prefix)
245
+     * @param array $input data that should be inserted into the table  (column name => value)
246
+     * @param array|null $compare List of values that should be checked for "if not exists"
247
+     *				If this is null or an empty array, all keys of $input will be compared
248
+     *				Please note: text fields (clob) must not be used in the compare array
249
+     * @return int number of inserted rows
250
+     * @throws \Doctrine\DBAL\DBALException
251
+     */
252
+    public function insertIfNotExist($table, $input, array $compare = null) {
253
+        return $this->adapter->insertIfNotExist($table, $input, $compare);
254
+    }
255
+
256
+    private function getType($value) {
257
+        if (is_bool($value)) {
258
+            return IQueryBuilder::PARAM_BOOL;
259
+        } elseif (is_int($value)) {
260
+            return IQueryBuilder::PARAM_INT;
261
+        } else {
262
+            return IQueryBuilder::PARAM_STR;
263
+        }
264
+    }
265
+
266
+    /**
267
+     * Insert or update a row value
268
+     *
269
+     * @param string $table
270
+     * @param array $keys (column name => value)
271
+     * @param array $values (column name => value)
272
+     * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
273
+     * @return int number of new rows
274
+     * @throws \Doctrine\DBAL\DBALException
275
+     * @throws PreConditionNotMetException
276
+     * @suppress SqlInjectionChecker
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([$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([$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
+
425
+
426
+    /**
427
+     * Create the schema of the connected database
428
+     *
429
+     * @return Schema
430
+     */
431
+    public function createSchema() {
432
+        $schemaManager = new MDB2SchemaManager($this);
433
+        $migrator = $schemaManager->getMigrator();
434
+        return $migrator->createSchema();
435
+    }
436
+
437
+    /**
438
+     * Migrate the database to the given schema
439
+     *
440
+     * @param Schema $toSchema
441
+     */
442
+    public function migrateToSchema(Schema $toSchema) {
443
+        $schemaManager = new MDB2SchemaManager($this);
444
+        $migrator = $schemaManager->getMigrator();
445
+        $migrator->migrate($toSchema);
446
+    }
447 447
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 			return parent::connect();
60 60
 		} catch (DBALException $e) {
61 61
 			// throw a new exception to prevent leaking info from the stacktrace
62
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
62
+			throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode());
63 63
 		}
64 64
 	}
65 65
 
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 		// 0 is the method where we use `getCallerBacktrace`
112 112
 		// 1 is the target method which uses the method we want to log
113 113
 		if (isset($traces[1])) {
114
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
114
+			return $traces[1]['file'].':'.$traces[1]['line'];
115 115
 		}
116 116
 
117 117
 		return '';
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 			$insertQb = $this->getQueryBuilder();
281 281
 			$insertQb->insert($table)
282 282
 				->values(
283
-					array_map(function ($value) use ($insertQb) {
283
+					array_map(function($value) use ($insertQb) {
284 284
 						return $insertQb->createNamedParameter($value, $this->getType($value));
285 285
 					}, array_merge($keys, $values))
286 286
 				);
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
325 325
 		}
326 326
 
327
-		$tableName = $this->tablePrefix . $tableName;
327
+		$tableName = $this->tablePrefix.$tableName;
328 328
 		$this->lockedTable = $tableName;
329 329
 		$this->adapter->lockTable($tableName);
330 330
 	}
@@ -345,11 +345,11 @@  discard block
 block discarded – undo
345 345
 	 * @return string
346 346
 	 */
347 347
 	public function getError() {
348
-		$msg = $this->errorCode() . ': ';
348
+		$msg = $this->errorCode().': ';
349 349
 		$errorInfo = $this->errorInfo();
350 350
 		if (is_array($errorInfo)) {
351
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
352
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
351
+			$msg .= 'SQLSTATE = '.$errorInfo[0].', ';
352
+			$msg .= 'Driver Code = '.$errorInfo[1].', ';
353 353
 			$msg .= 'Driver Message = '.$errorInfo[2];
354 354
 		}
355 355
 		return $msg;
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 	 * @param string $table table name without the prefix
362 362
 	 */
363 363
 	public function dropTable($table) {
364
-		$table = $this->tablePrefix . trim($table);
364
+		$table = $this->tablePrefix.trim($table);
365 365
 		$schema = $this->getSchemaManager();
366 366
 		if ($schema->tablesExist([$table])) {
367 367
 			$schema->dropTable($table);
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
 	 * @return bool
376 376
 	 */
377 377
 	public function tableExists($table) {
378
-		$table = $this->tablePrefix . trim($table);
378
+		$table = $this->tablePrefix.trim($table);
379 379
 		$schema = $this->getSchemaManager();
380 380
 		return $schema->tablesExist([$table]);
381 381
 	}
Please login to merge, or discard this patch.
lib/private/Files/Cache/Scanner.php 3 patches
Doc Comments   +11 added lines patch added patch discarded remove patch
@@ -386,6 +386,14 @@  discard block
 block discarded – undo
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
 block discarded – undo
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();
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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()
Please login to merge, or discard this patch.
Indentation   +474 added lines, -474 removed lines patch added patch discarded remove patch
@@ -54,478 +54,478 @@
 block discarded – undo
54 54
  * @package OC\Files\Cache
55 55
  */
56 56
 class Scanner extends BasicEmitter implements IScanner {
57
-	/**
58
-	 * @var \OC\Files\Storage\Storage $storage
59
-	 */
60
-	protected $storage;
61
-
62
-	/**
63
-	 * @var string $storageId
64
-	 */
65
-	protected $storageId;
66
-
67
-	/**
68
-	 * @var \OC\Files\Cache\Cache $cache
69
-	 */
70
-	protected $cache;
71
-
72
-	/**
73
-	 * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
74
-	 */
75
-	protected $cacheActive;
76
-
77
-	/**
78
-	 * @var bool $useTransactions whether to use transactions
79
-	 */
80
-	protected $useTransactions = true;
81
-
82
-	/**
83
-	 * @var \OCP\Lock\ILockingProvider
84
-	 */
85
-	protected $lockingProvider;
86
-
87
-	public function __construct(\OC\Files\Storage\Storage $storage) {
88
-		$this->storage = $storage;
89
-		$this->storageId = $this->storage->getId();
90
-		$this->cache = $storage->getCache();
91
-		$this->cacheActive = !Config::getSystemValue('filesystem_cache_readonly', false);
92
-		$this->lockingProvider = \OC::$server->getLockingProvider();
93
-	}
94
-
95
-	/**
96
-	 * Whether to wrap the scanning of a folder in a database transaction
97
-	 * On default transactions are used
98
-	 *
99
-	 * @param bool $useTransactions
100
-	 */
101
-	public function setUseTransactions($useTransactions) {
102
-		$this->useTransactions = $useTransactions;
103
-	}
104
-
105
-	/**
106
-	 * get all the metadata of a file or folder
107
-	 * *
108
-	 *
109
-	 * @param string $path
110
-	 * @return array an array of metadata of the file
111
-	 */
112
-	protected function getData($path) {
113
-		$data = $this->storage->getMetaData($path);
114
-		if (is_null($data)) {
115
-			\OCP\Util::writeLog('OC\Files\Cache\Scanner', "!!! Path '$path' is not accessible or present !!!", \OCP\Util::DEBUG);
116
-		}
117
-		return $data;
118
-	}
119
-
120
-	/**
121
-	 * scan a single file and store it in the cache
122
-	 *
123
-	 * @param string $file
124
-	 * @param int $reuseExisting
125
-	 * @param int $parentId
126
-	 * @param array | null $cacheData existing data in the cache for the file to be scanned
127
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
128
-	 * @return array an array of metadata of the scanned file
129
-	 * @throws \OC\ServerNotAvailableException
130
-	 * @throws \OCP\Lock\LockedException
131
-	 */
132
-	public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
133
-		if ($file !== '') {
134
-			try {
135
-				$this->storage->verifyPath(dirname($file), basename($file));
136
-			} catch (\Exception $e) {
137
-				return null;
138
-			}
139
-		}
140
-
141
-		// only proceed if $file is not a partial file nor a blacklisted file
142
-		if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) {
143
-
144
-			//acquire a lock
145
-			if ($lock) {
146
-				if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
147
-					$this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
148
-				}
149
-			}
150
-
151
-			try {
152
-				$data = $this->getData($file);
153
-			} catch (ForbiddenException $e) {
154
-				return null;
155
-			}
156
-
157
-			if ($data) {
158
-
159
-				// pre-emit only if it was a file. By that we avoid counting/treating folders as files
160
-				if ($data['mimetype'] !== 'httpd/unix-directory') {
161
-					$this->emit('\OC\Files\Cache\Scanner', 'scanFile', [$file, $this->storageId]);
162
-					\OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', ['path' => $file, 'storage' => $this->storageId]);
163
-				}
164
-
165
-				$parent = dirname($file);
166
-				if ($parent === '.' or $parent === '/') {
167
-					$parent = '';
168
-				}
169
-				if ($parentId === -1) {
170
-					$parentId = $this->cache->getParentId($file);
171
-				}
172
-
173
-				// scan the parent if it's not in the cache (id -1) and the current file is not the root folder
174
-				if ($file and $parentId === -1) {
175
-					$parentData = $this->scanFile($parent);
176
-					if (!$parentData) {
177
-						return null;
178
-					}
179
-					$parentId = $parentData['fileid'];
180
-				}
181
-				if ($parent) {
182
-					$data['parent'] = $parentId;
183
-				}
184
-				if (is_null($cacheData)) {
185
-					/** @var CacheEntry $cacheData */
186
-					$cacheData = $this->cache->get($file);
187
-				}
188
-				if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) {
189
-					// prevent empty etag
190
-					if (empty($cacheData['etag'])) {
191
-						$etag = $data['etag'];
192
-					} else {
193
-						$etag = $cacheData['etag'];
194
-					}
195
-					$fileId = $cacheData['fileid'];
196
-					$data['fileid'] = $fileId;
197
-					// only reuse data if the file hasn't explicitly changed
198
-					if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) {
199
-						$data['mtime'] = $cacheData['mtime'];
200
-						if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
201
-							$data['size'] = $cacheData['size'];
202
-						}
203
-						if ($reuseExisting & self::REUSE_ETAG) {
204
-							$data['etag'] = $etag;
205
-						}
206
-					}
207
-					// Only update metadata that has changed
208
-					$newData = array_diff_assoc($data, $cacheData->getData());
209
-				} else {
210
-					$newData = $data;
211
-					$fileId = -1;
212
-				}
213
-				if (!empty($newData)) {
214
-					// Reset the checksum if the data has changed
215
-					$newData['checksum'] = '';
216
-					$data['fileid'] = $this->addToCache($file, $newData, $fileId);
217
-				}
218
-				if (isset($cacheData['size'])) {
219
-					$data['oldSize'] = $cacheData['size'];
220
-				} else {
221
-					$data['oldSize'] = 0;
222
-				}
223
-
224
-				if (isset($cacheData['encrypted'])) {
225
-					$data['encrypted'] = $cacheData['encrypted'];
226
-				}
227
-
228
-				// post-emit only if it was a file. By that we avoid counting/treating folders as files
229
-				if ($data['mimetype'] !== 'httpd/unix-directory') {
230
-					$this->emit('\OC\Files\Cache\Scanner', 'postScanFile', [$file, $this->storageId]);
231
-					\OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', ['path' => $file, 'storage' => $this->storageId]);
232
-				}
233
-			} else {
234
-				$this->removeFromCache($file);
235
-			}
236
-
237
-			//release the acquired lock
238
-			if ($lock) {
239
-				if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
240
-					$this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
241
-				}
242
-			}
243
-
244
-			if ($data && !isset($data['encrypted'])) {
245
-				$data['encrypted'] = false;
246
-			}
247
-			return $data;
248
-		}
249
-
250
-		return null;
251
-	}
252
-
253
-	protected function removeFromCache($path) {
254
-		\OC_Hook::emit('Scanner', 'removeFromCache', ['file' => $path]);
255
-		$this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', [$path]);
256
-		if ($this->cacheActive) {
257
-			$this->cache->remove($path);
258
-		}
259
-	}
260
-
261
-	/**
262
-	 * @param string $path
263
-	 * @param array $data
264
-	 * @param int $fileId
265
-	 * @return int the id of the added file
266
-	 */
267
-	protected function addToCache($path, $data, $fileId = -1) {
268
-		if (isset($data['scan_permissions'])) {
269
-			$data['permissions'] = $data['scan_permissions'];
270
-		}
271
-		\OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
272
-		$this->emit('\OC\Files\Cache\Scanner', 'addToCache', [$path, $this->storageId, $data]);
273
-		if ($this->cacheActive) {
274
-			if ($fileId !== -1) {
275
-				$this->cache->update($fileId, $data);
276
-				return $fileId;
277
-			} else {
278
-				return $this->cache->put($path, $data);
279
-			}
280
-		} else {
281
-			return -1;
282
-		}
283
-	}
284
-
285
-	/**
286
-	 * @param string $path
287
-	 * @param array $data
288
-	 * @param int $fileId
289
-	 */
290
-	protected function updateCache($path, $data, $fileId = -1) {
291
-		\OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
292
-		$this->emit('\OC\Files\Cache\Scanner', 'updateCache', [$path, $this->storageId, $data]);
293
-		if ($this->cacheActive) {
294
-			if ($fileId !== -1) {
295
-				$this->cache->update($fileId, $data);
296
-			} else {
297
-				$this->cache->put($path, $data);
298
-			}
299
-		}
300
-	}
301
-
302
-	/**
303
-	 * scan a folder and all it's children
304
-	 *
305
-	 * @param string $path
306
-	 * @param bool $recursive
307
-	 * @param int $reuse
308
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
309
-	 * @return array an array of the meta data of the scanned file or folder
310
-	 */
311
-	public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
312
-		if ($reuse === -1) {
313
-			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
314
-		}
315
-		if ($lock) {
316
-			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
317
-				$this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
318
-				$this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
319
-			}
320
-		}
321
-		$data = $this->scanFile($path, $reuse, -1, null, $lock);
322
-		if ($data and $data['mimetype'] === 'httpd/unix-directory') {
323
-			$size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
324
-			$data['size'] = $size;
325
-		}
326
-		if ($lock) {
327
-			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
328
-				$this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
329
-				$this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
330
-			}
331
-		}
332
-		return $data;
333
-	}
334
-
335
-	/**
336
-	 * Get the children currently in the cache
337
-	 *
338
-	 * @param int $folderId
339
-	 * @return array[]
340
-	 */
341
-	protected function getExistingChildren($folderId) {
342
-		$existingChildren = [];
343
-		$children = $this->cache->getFolderContentsById($folderId);
344
-		foreach ($children as $child) {
345
-			$existingChildren[$child['name']] = $child;
346
-		}
347
-		return $existingChildren;
348
-	}
349
-
350
-	/**
351
-	 * Get the children from the storage
352
-	 *
353
-	 * @param string $folder
354
-	 * @return string[]
355
-	 */
356
-	protected function getNewChildren($folder) {
357
-		$children = [];
358
-		if ($dh = $this->storage->opendir($folder)) {
359
-			if (is_resource($dh)) {
360
-				while (($file = readdir($dh)) !== false) {
361
-					if (!Filesystem::isIgnoredDir($file)) {
362
-						$children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/');
363
-					}
364
-				}
365
-			}
366
-		}
367
-		return $children;
368
-	}
369
-
370
-	/**
371
-	 * scan all the files and folders in a folder
372
-	 *
373
-	 * @param string $path
374
-	 * @param bool $recursive
375
-	 * @param int $reuse
376
-	 * @param int $folderId id for the folder to be scanned
377
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
378
-	 * @return int the size of the scanned folder or -1 if the size is unknown at this stage
379
-	 */
380
-	protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
381
-		if ($reuse === -1) {
382
-			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
383
-		}
384
-		$this->emit('\OC\Files\Cache\Scanner', 'scanFolder', [$path, $this->storageId]);
385
-		$size = 0;
386
-		if (!is_null($folderId)) {
387
-			$folderId = $this->cache->getId($path);
388
-		}
389
-		$childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
390
-
391
-		foreach ($childQueue as $child => $childId) {
392
-			$childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
393
-			if ($childSize === -1) {
394
-				$size = -1;
395
-			} elseif ($size !== -1) {
396
-				$size += $childSize;
397
-			}
398
-		}
399
-		if ($this->cacheActive) {
400
-			$this->cache->update($folderId, ['size' => $size]);
401
-		}
402
-		$this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', [$path, $this->storageId]);
403
-		return $size;
404
-	}
405
-
406
-	private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
407
-		// we put this in it's own function so it cleans up the memory before we start recursing
408
-		$existingChildren = $this->getExistingChildren($folderId);
409
-		$newChildren = $this->getNewChildren($path);
410
-
411
-		if ($this->useTransactions) {
412
-			\OC::$server->getDatabaseConnection()->beginTransaction();
413
-		}
414
-
415
-		$exceptionOccurred = false;
416
-		$childQueue = [];
417
-		foreach ($newChildren as $file) {
418
-			$child = ($path) ? $path . '/' . $file : $file;
419
-			try {
420
-				$existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
421
-				$data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
422
-				if ($data) {
423
-					if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
424
-						$childQueue[$child] = $data['fileid'];
425
-					} elseif ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
426
-						// only recurse into folders which aren't fully scanned
427
-						$childQueue[$child] = $data['fileid'];
428
-					} elseif ($data['size'] === -1) {
429
-						$size = -1;
430
-					} elseif ($size !== -1) {
431
-						$size += $data['size'];
432
-					}
433
-				}
434
-			} catch (\Doctrine\DBAL\DBALException $ex) {
435
-				// might happen if inserting duplicate while a scanning
436
-				// process is running in parallel
437
-				// log and ignore
438
-				\OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG);
439
-				$exceptionOccurred = true;
440
-			} catch (\OCP\Lock\LockedException $e) {
441
-				if ($this->useTransactions) {
442
-					\OC::$server->getDatabaseConnection()->rollback();
443
-				}
444
-				throw $e;
445
-			}
446
-		}
447
-		$removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
448
-		foreach ($removedChildren as $childName) {
449
-			$child = ($path) ? $path . '/' . $childName : $childName;
450
-			$this->removeFromCache($child);
451
-		}
452
-		if ($this->useTransactions) {
453
-			\OC::$server->getDatabaseConnection()->commit();
454
-		}
455
-		if ($exceptionOccurred) {
456
-			// It might happen that the parallel scan process has already
457
-			// inserted mimetypes but those weren't available yet inside the transaction
458
-			// To make sure to have the updated mime types in such cases,
459
-			// we reload them here
460
-			\OC::$server->getMimeTypeLoader()->reset();
461
-		}
462
-		return $childQueue;
463
-	}
464
-
465
-	/**
466
-	 * check if the file should be ignored when scanning
467
-	 * NOTE: files with a '.part' extension are ignored as well!
468
-	 *       prevents unfinished put requests to be scanned
469
-	 *
470
-	 * @param string $file
471
-	 * @return boolean
472
-	 */
473
-	public static function isPartialFile($file) {
474
-		if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
475
-			return true;
476
-		}
477
-		if (strpos($file, '.part/') !== false) {
478
-			return true;
479
-		}
480
-
481
-		return false;
482
-	}
483
-
484
-	/**
485
-	 * walk over any folders that are not fully scanned yet and scan them
486
-	 */
487
-	public function backgroundScan() {
488
-		if (!$this->cache->inCache('')) {
489
-			$this->runBackgroundScanJob(function () {
490
-				$this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
491
-			}, '');
492
-		} else {
493
-			$lastPath = null;
494
-			while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
495
-				$this->runBackgroundScanJob(function () use ($path) {
496
-					$this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
497
-				}, $path);
498
-				// FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
499
-				// to make this possible
500
-				$lastPath = $path;
501
-			}
502
-		}
503
-	}
504
-
505
-	private function runBackgroundScanJob(callable $callback, $path) {
506
-		try {
507
-			$callback();
508
-			\OC_Hook::emit('Scanner', 'correctFolderSize', ['path' => $path]);
509
-			if ($this->cacheActive && $this->cache instanceof Cache) {
510
-				$this->cache->correctFolderSize($path);
511
-			}
512
-		} catch (\OCP\Files\StorageInvalidException $e) {
513
-			// skip unavailable storages
514
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
515
-			// skip unavailable storages
516
-		} catch (\OCP\Files\ForbiddenException $e) {
517
-			// skip forbidden storages
518
-		} catch (\OCP\Lock\LockedException $e) {
519
-			// skip unavailable storages
520
-		}
521
-	}
522
-
523
-	/**
524
-	 * Set whether the cache is affected by scan operations
525
-	 *
526
-	 * @param boolean $active The active state of the cache
527
-	 */
528
-	public function setCacheActive($active) {
529
-		$this->cacheActive = $active;
530
-	}
57
+    /**
58
+     * @var \OC\Files\Storage\Storage $storage
59
+     */
60
+    protected $storage;
61
+
62
+    /**
63
+     * @var string $storageId
64
+     */
65
+    protected $storageId;
66
+
67
+    /**
68
+     * @var \OC\Files\Cache\Cache $cache
69
+     */
70
+    protected $cache;
71
+
72
+    /**
73
+     * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
74
+     */
75
+    protected $cacheActive;
76
+
77
+    /**
78
+     * @var bool $useTransactions whether to use transactions
79
+     */
80
+    protected $useTransactions = true;
81
+
82
+    /**
83
+     * @var \OCP\Lock\ILockingProvider
84
+     */
85
+    protected $lockingProvider;
86
+
87
+    public function __construct(\OC\Files\Storage\Storage $storage) {
88
+        $this->storage = $storage;
89
+        $this->storageId = $this->storage->getId();
90
+        $this->cache = $storage->getCache();
91
+        $this->cacheActive = !Config::getSystemValue('filesystem_cache_readonly', false);
92
+        $this->lockingProvider = \OC::$server->getLockingProvider();
93
+    }
94
+
95
+    /**
96
+     * Whether to wrap the scanning of a folder in a database transaction
97
+     * On default transactions are used
98
+     *
99
+     * @param bool $useTransactions
100
+     */
101
+    public function setUseTransactions($useTransactions) {
102
+        $this->useTransactions = $useTransactions;
103
+    }
104
+
105
+    /**
106
+     * get all the metadata of a file or folder
107
+     * *
108
+     *
109
+     * @param string $path
110
+     * @return array an array of metadata of the file
111
+     */
112
+    protected function getData($path) {
113
+        $data = $this->storage->getMetaData($path);
114
+        if (is_null($data)) {
115
+            \OCP\Util::writeLog('OC\Files\Cache\Scanner', "!!! Path '$path' is not accessible or present !!!", \OCP\Util::DEBUG);
116
+        }
117
+        return $data;
118
+    }
119
+
120
+    /**
121
+     * scan a single file and store it in the cache
122
+     *
123
+     * @param string $file
124
+     * @param int $reuseExisting
125
+     * @param int $parentId
126
+     * @param array | null $cacheData existing data in the cache for the file to be scanned
127
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
128
+     * @return array an array of metadata of the scanned file
129
+     * @throws \OC\ServerNotAvailableException
130
+     * @throws \OCP\Lock\LockedException
131
+     */
132
+    public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
133
+        if ($file !== '') {
134
+            try {
135
+                $this->storage->verifyPath(dirname($file), basename($file));
136
+            } catch (\Exception $e) {
137
+                return null;
138
+            }
139
+        }
140
+
141
+        // only proceed if $file is not a partial file nor a blacklisted file
142
+        if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) {
143
+
144
+            //acquire a lock
145
+            if ($lock) {
146
+                if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
147
+                    $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
148
+                }
149
+            }
150
+
151
+            try {
152
+                $data = $this->getData($file);
153
+            } catch (ForbiddenException $e) {
154
+                return null;
155
+            }
156
+
157
+            if ($data) {
158
+
159
+                // pre-emit only if it was a file. By that we avoid counting/treating folders as files
160
+                if ($data['mimetype'] !== 'httpd/unix-directory') {
161
+                    $this->emit('\OC\Files\Cache\Scanner', 'scanFile', [$file, $this->storageId]);
162
+                    \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', ['path' => $file, 'storage' => $this->storageId]);
163
+                }
164
+
165
+                $parent = dirname($file);
166
+                if ($parent === '.' or $parent === '/') {
167
+                    $parent = '';
168
+                }
169
+                if ($parentId === -1) {
170
+                    $parentId = $this->cache->getParentId($file);
171
+                }
172
+
173
+                // scan the parent if it's not in the cache (id -1) and the current file is not the root folder
174
+                if ($file and $parentId === -1) {
175
+                    $parentData = $this->scanFile($parent);
176
+                    if (!$parentData) {
177
+                        return null;
178
+                    }
179
+                    $parentId = $parentData['fileid'];
180
+                }
181
+                if ($parent) {
182
+                    $data['parent'] = $parentId;
183
+                }
184
+                if (is_null($cacheData)) {
185
+                    /** @var CacheEntry $cacheData */
186
+                    $cacheData = $this->cache->get($file);
187
+                }
188
+                if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) {
189
+                    // prevent empty etag
190
+                    if (empty($cacheData['etag'])) {
191
+                        $etag = $data['etag'];
192
+                    } else {
193
+                        $etag = $cacheData['etag'];
194
+                    }
195
+                    $fileId = $cacheData['fileid'];
196
+                    $data['fileid'] = $fileId;
197
+                    // only reuse data if the file hasn't explicitly changed
198
+                    if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) {
199
+                        $data['mtime'] = $cacheData['mtime'];
200
+                        if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
201
+                            $data['size'] = $cacheData['size'];
202
+                        }
203
+                        if ($reuseExisting & self::REUSE_ETAG) {
204
+                            $data['etag'] = $etag;
205
+                        }
206
+                    }
207
+                    // Only update metadata that has changed
208
+                    $newData = array_diff_assoc($data, $cacheData->getData());
209
+                } else {
210
+                    $newData = $data;
211
+                    $fileId = -1;
212
+                }
213
+                if (!empty($newData)) {
214
+                    // Reset the checksum if the data has changed
215
+                    $newData['checksum'] = '';
216
+                    $data['fileid'] = $this->addToCache($file, $newData, $fileId);
217
+                }
218
+                if (isset($cacheData['size'])) {
219
+                    $data['oldSize'] = $cacheData['size'];
220
+                } else {
221
+                    $data['oldSize'] = 0;
222
+                }
223
+
224
+                if (isset($cacheData['encrypted'])) {
225
+                    $data['encrypted'] = $cacheData['encrypted'];
226
+                }
227
+
228
+                // post-emit only if it was a file. By that we avoid counting/treating folders as files
229
+                if ($data['mimetype'] !== 'httpd/unix-directory') {
230
+                    $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', [$file, $this->storageId]);
231
+                    \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', ['path' => $file, 'storage' => $this->storageId]);
232
+                }
233
+            } else {
234
+                $this->removeFromCache($file);
235
+            }
236
+
237
+            //release the acquired lock
238
+            if ($lock) {
239
+                if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
240
+                    $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
241
+                }
242
+            }
243
+
244
+            if ($data && !isset($data['encrypted'])) {
245
+                $data['encrypted'] = false;
246
+            }
247
+            return $data;
248
+        }
249
+
250
+        return null;
251
+    }
252
+
253
+    protected function removeFromCache($path) {
254
+        \OC_Hook::emit('Scanner', 'removeFromCache', ['file' => $path]);
255
+        $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', [$path]);
256
+        if ($this->cacheActive) {
257
+            $this->cache->remove($path);
258
+        }
259
+    }
260
+
261
+    /**
262
+     * @param string $path
263
+     * @param array $data
264
+     * @param int $fileId
265
+     * @return int the id of the added file
266
+     */
267
+    protected function addToCache($path, $data, $fileId = -1) {
268
+        if (isset($data['scan_permissions'])) {
269
+            $data['permissions'] = $data['scan_permissions'];
270
+        }
271
+        \OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
272
+        $this->emit('\OC\Files\Cache\Scanner', 'addToCache', [$path, $this->storageId, $data]);
273
+        if ($this->cacheActive) {
274
+            if ($fileId !== -1) {
275
+                $this->cache->update($fileId, $data);
276
+                return $fileId;
277
+            } else {
278
+                return $this->cache->put($path, $data);
279
+            }
280
+        } else {
281
+            return -1;
282
+        }
283
+    }
284
+
285
+    /**
286
+     * @param string $path
287
+     * @param array $data
288
+     * @param int $fileId
289
+     */
290
+    protected function updateCache($path, $data, $fileId = -1) {
291
+        \OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
292
+        $this->emit('\OC\Files\Cache\Scanner', 'updateCache', [$path, $this->storageId, $data]);
293
+        if ($this->cacheActive) {
294
+            if ($fileId !== -1) {
295
+                $this->cache->update($fileId, $data);
296
+            } else {
297
+                $this->cache->put($path, $data);
298
+            }
299
+        }
300
+    }
301
+
302
+    /**
303
+     * scan a folder and all it's children
304
+     *
305
+     * @param string $path
306
+     * @param bool $recursive
307
+     * @param int $reuse
308
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
309
+     * @return array an array of the meta data of the scanned file or folder
310
+     */
311
+    public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
312
+        if ($reuse === -1) {
313
+            $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
314
+        }
315
+        if ($lock) {
316
+            if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
317
+                $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
318
+                $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
319
+            }
320
+        }
321
+        $data = $this->scanFile($path, $reuse, -1, null, $lock);
322
+        if ($data and $data['mimetype'] === 'httpd/unix-directory') {
323
+            $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
324
+            $data['size'] = $size;
325
+        }
326
+        if ($lock) {
327
+            if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
328
+                $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
329
+                $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
330
+            }
331
+        }
332
+        return $data;
333
+    }
334
+
335
+    /**
336
+     * Get the children currently in the cache
337
+     *
338
+     * @param int $folderId
339
+     * @return array[]
340
+     */
341
+    protected function getExistingChildren($folderId) {
342
+        $existingChildren = [];
343
+        $children = $this->cache->getFolderContentsById($folderId);
344
+        foreach ($children as $child) {
345
+            $existingChildren[$child['name']] = $child;
346
+        }
347
+        return $existingChildren;
348
+    }
349
+
350
+    /**
351
+     * Get the children from the storage
352
+     *
353
+     * @param string $folder
354
+     * @return string[]
355
+     */
356
+    protected function getNewChildren($folder) {
357
+        $children = [];
358
+        if ($dh = $this->storage->opendir($folder)) {
359
+            if (is_resource($dh)) {
360
+                while (($file = readdir($dh)) !== false) {
361
+                    if (!Filesystem::isIgnoredDir($file)) {
362
+                        $children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/');
363
+                    }
364
+                }
365
+            }
366
+        }
367
+        return $children;
368
+    }
369
+
370
+    /**
371
+     * scan all the files and folders in a folder
372
+     *
373
+     * @param string $path
374
+     * @param bool $recursive
375
+     * @param int $reuse
376
+     * @param int $folderId id for the folder to be scanned
377
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
378
+     * @return int the size of the scanned folder or -1 if the size is unknown at this stage
379
+     */
380
+    protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
381
+        if ($reuse === -1) {
382
+            $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
383
+        }
384
+        $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', [$path, $this->storageId]);
385
+        $size = 0;
386
+        if (!is_null($folderId)) {
387
+            $folderId = $this->cache->getId($path);
388
+        }
389
+        $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
390
+
391
+        foreach ($childQueue as $child => $childId) {
392
+            $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
393
+            if ($childSize === -1) {
394
+                $size = -1;
395
+            } elseif ($size !== -1) {
396
+                $size += $childSize;
397
+            }
398
+        }
399
+        if ($this->cacheActive) {
400
+            $this->cache->update($folderId, ['size' => $size]);
401
+        }
402
+        $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', [$path, $this->storageId]);
403
+        return $size;
404
+    }
405
+
406
+    private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
407
+        // we put this in it's own function so it cleans up the memory before we start recursing
408
+        $existingChildren = $this->getExistingChildren($folderId);
409
+        $newChildren = $this->getNewChildren($path);
410
+
411
+        if ($this->useTransactions) {
412
+            \OC::$server->getDatabaseConnection()->beginTransaction();
413
+        }
414
+
415
+        $exceptionOccurred = false;
416
+        $childQueue = [];
417
+        foreach ($newChildren as $file) {
418
+            $child = ($path) ? $path . '/' . $file : $file;
419
+            try {
420
+                $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
421
+                $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
422
+                if ($data) {
423
+                    if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
424
+                        $childQueue[$child] = $data['fileid'];
425
+                    } elseif ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
426
+                        // only recurse into folders which aren't fully scanned
427
+                        $childQueue[$child] = $data['fileid'];
428
+                    } elseif ($data['size'] === -1) {
429
+                        $size = -1;
430
+                    } elseif ($size !== -1) {
431
+                        $size += $data['size'];
432
+                    }
433
+                }
434
+            } catch (\Doctrine\DBAL\DBALException $ex) {
435
+                // might happen if inserting duplicate while a scanning
436
+                // process is running in parallel
437
+                // log and ignore
438
+                \OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG);
439
+                $exceptionOccurred = true;
440
+            } catch (\OCP\Lock\LockedException $e) {
441
+                if ($this->useTransactions) {
442
+                    \OC::$server->getDatabaseConnection()->rollback();
443
+                }
444
+                throw $e;
445
+            }
446
+        }
447
+        $removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
448
+        foreach ($removedChildren as $childName) {
449
+            $child = ($path) ? $path . '/' . $childName : $childName;
450
+            $this->removeFromCache($child);
451
+        }
452
+        if ($this->useTransactions) {
453
+            \OC::$server->getDatabaseConnection()->commit();
454
+        }
455
+        if ($exceptionOccurred) {
456
+            // It might happen that the parallel scan process has already
457
+            // inserted mimetypes but those weren't available yet inside the transaction
458
+            // To make sure to have the updated mime types in such cases,
459
+            // we reload them here
460
+            \OC::$server->getMimeTypeLoader()->reset();
461
+        }
462
+        return $childQueue;
463
+    }
464
+
465
+    /**
466
+     * check if the file should be ignored when scanning
467
+     * NOTE: files with a '.part' extension are ignored as well!
468
+     *       prevents unfinished put requests to be scanned
469
+     *
470
+     * @param string $file
471
+     * @return boolean
472
+     */
473
+    public static function isPartialFile($file) {
474
+        if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
475
+            return true;
476
+        }
477
+        if (strpos($file, '.part/') !== false) {
478
+            return true;
479
+        }
480
+
481
+        return false;
482
+    }
483
+
484
+    /**
485
+     * walk over any folders that are not fully scanned yet and scan them
486
+     */
487
+    public function backgroundScan() {
488
+        if (!$this->cache->inCache('')) {
489
+            $this->runBackgroundScanJob(function () {
490
+                $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
491
+            }, '');
492
+        } else {
493
+            $lastPath = null;
494
+            while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
495
+                $this->runBackgroundScanJob(function () use ($path) {
496
+                    $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
497
+                }, $path);
498
+                // FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
499
+                // to make this possible
500
+                $lastPath = $path;
501
+            }
502
+        }
503
+    }
504
+
505
+    private function runBackgroundScanJob(callable $callback, $path) {
506
+        try {
507
+            $callback();
508
+            \OC_Hook::emit('Scanner', 'correctFolderSize', ['path' => $path]);
509
+            if ($this->cacheActive && $this->cache instanceof Cache) {
510
+                $this->cache->correctFolderSize($path);
511
+            }
512
+        } catch (\OCP\Files\StorageInvalidException $e) {
513
+            // skip unavailable storages
514
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
515
+            // skip unavailable storages
516
+        } catch (\OCP\Files\ForbiddenException $e) {
517
+            // skip forbidden storages
518
+        } catch (\OCP\Lock\LockedException $e) {
519
+            // skip unavailable storages
520
+        }
521
+    }
522
+
523
+    /**
524
+     * Set whether the cache is affected by scan operations
525
+     *
526
+     * @param boolean $active The active state of the cache
527
+     */
528
+    public function setCacheActive($active) {
529
+        $this->cacheActive = $active;
530
+    }
531 531
 }
Please login to merge, or discard this patch.
lib/private/Files/Config/UserMountCache.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -206,7 +206,7 @@
 block discarded – undo
206 206
 	}
207 207
 
208 208
 	/**
209
-	 * @param $fileId
209
+	 * @param integer $fileId
210 210
 	 * @return array
211 211
 	 * @throws \OCP\Files\NotFoundException
212 212
 	 */
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,6 @@
 block discarded – undo
24 24
 
25 25
 namespace OC\Files\Config;
26 26
 
27
-use OC\DB\QueryBuilder\Literal;
28 27
 use OCA\Files_Sharing\SharedMount;
29 28
 use OCP\DB\QueryBuilder\IQueryBuilder;
30 29
 use OCP\Files\Config\ICachedMountInfo;
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -87,11 +87,11 @@  discard block
 block discarded – undo
87 87
 
88 88
 	public function registerMounts(IUser $user, array $mounts) {
89 89
 		// filter out non-proper storages coming from unit tests
90
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
90
+		$mounts = array_filter($mounts, function(IMountPoint $mount) {
91 91
 			return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
92 92
 		});
93 93
 		/** @var ICachedMountInfo[] $newMounts */
94
-		$newMounts = array_map(function (IMountPoint $mount) use ($user) {
94
+		$newMounts = array_map(function(IMountPoint $mount) use ($user) {
95 95
 			// filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
96 96
 			if ($mount->getStorageRootId() === -1) {
97 97
 				return null;
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 		$newMounts = array_values(array_filter($newMounts));
103 103
 
104 104
 		$cachedMounts = $this->getMountsForUser($user);
105
-		$mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
105
+		$mountDiff = function(ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
106 106
 			// since we are only looking for mounts for a specific user comparing on root id is enough
107 107
 			return $mount1->getRootId() - $mount2->getRootId();
108 108
 		};
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 			], ['root_id', 'user_id']);
164 164
 		} else {
165 165
 			// in some cases this is legitimate, like orphaned shares
166
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
166
+			$this->logger->debug('Could not get storage info for mount at '.$mount->getMountPoint());
167 167
 		}
168 168
 	}
169 169
 
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 		if (is_null($user)) {
195 195
 			return null;
196 196
 		}
197
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path']) ? $row['path'] : '');
197
+		return new CachedMountInfo($user, (int) $row['storage_id'], (int) $row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path']) ? $row['path'] : '');
198 198
 	}
199 199
 
200 200
 	/**
@@ -268,12 +268,12 @@  discard block
 block discarded – undo
268 268
 			$row = $query->execute()->fetch();
269 269
 			if (is_array($row)) {
270 270
 				$this->cacheInfoCache[$fileId] = [
271
-					(int)$row['storage'],
271
+					(int) $row['storage'],
272 272
 					$row['path'],
273
-					(int)$row['mimetype']
273
+					(int) $row['mimetype']
274 274
 				];
275 275
 			} else {
276
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
276
+				throw new NotFoundException('File with id "'.$fileId.'" not found');
277 277
 			}
278 278
 		}
279 279
 		return $this->cacheInfoCache[$fileId];
@@ -294,13 +294,13 @@  discard block
 block discarded – undo
294 294
 		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
295 295
 
296 296
 		// filter mounts that are from the same storage but a different directory
297
-		return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
297
+		return array_filter($mountsForStorage, function(ICachedMountInfo $mount) use ($internalPath, $fileId) {
298 298
 			if ($fileId === $mount->getRootId()) {
299 299
 				return true;
300 300
 			}
301 301
 			$internalMountPath = $mount->getRootInternalPath();
302 302
 
303
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
303
+			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath.'/';
304 304
 		});
305 305
 	}
306 306
 
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 			$slash
345 345
 		);
346 346
 
347
-		$userIds = array_map(function (IUser $user) {
347
+		$userIds = array_map(function(IUser $user) {
348 348
 			return $user->getUID();
349 349
 		}, $users);
350 350
 
Please login to merge, or discard this patch.
Indentation   +329 added lines, -329 removed lines patch added patch discarded remove patch
@@ -42,333 +42,333 @@
 block discarded – undo
42 42
  * Cache mounts points per user in the cache so we can easilly look them up
43 43
  */
44 44
 class UserMountCache implements IUserMountCache {
45
-	/**
46
-	 * @var IDBConnection
47
-	 */
48
-	private $connection;
49
-
50
-	/**
51
-	 * @var IUserManager
52
-	 */
53
-	private $userManager;
54
-
55
-	/**
56
-	 * Cached mount info.
57
-	 * Map of $userId to ICachedMountInfo.
58
-	 *
59
-	 * @var ICache
60
-	 **/
61
-	private $mountsForUsers;
62
-
63
-	/**
64
-	 * @var ILogger
65
-	 */
66
-	private $logger;
67
-
68
-	/**
69
-	 * @var ICache
70
-	 */
71
-	private $cacheInfoCache;
72
-
73
-	/**
74
-	 * UserMountCache constructor.
75
-	 *
76
-	 * @param IDBConnection $connection
77
-	 * @param IUserManager $userManager
78
-	 * @param ILogger $logger
79
-	 */
80
-	public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) {
81
-		$this->connection = $connection;
82
-		$this->userManager = $userManager;
83
-		$this->logger = $logger;
84
-		$this->cacheInfoCache = new CappedMemoryCache();
85
-		$this->mountsForUsers = new CappedMemoryCache();
86
-	}
87
-
88
-	public function registerMounts(IUser $user, array $mounts) {
89
-		// filter out non-proper storages coming from unit tests
90
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
91
-			return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
92
-		});
93
-		/** @var ICachedMountInfo[] $newMounts */
94
-		$newMounts = array_map(function (IMountPoint $mount) use ($user) {
95
-			// filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
96
-			if ($mount->getStorageRootId() === -1) {
97
-				return null;
98
-			} else {
99
-				return new LazyStorageMountInfo($user, $mount);
100
-			}
101
-		}, $mounts);
102
-		$newMounts = array_values(array_filter($newMounts));
103
-
104
-		$cachedMounts = $this->getMountsForUser($user);
105
-		$mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
106
-			// since we are only looking for mounts for a specific user comparing on root id is enough
107
-			return $mount1->getRootId() - $mount2->getRootId();
108
-		};
109
-
110
-		/** @var ICachedMountInfo[] $addedMounts */
111
-		$addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff);
112
-		/** @var ICachedMountInfo[] $removedMounts */
113
-		$removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff);
114
-
115
-		$changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
116
-
117
-		foreach ($addedMounts as $mount) {
118
-			$this->addToCache($mount);
119
-			$this->mountsForUsers[$user->getUID()][] = $mount;
120
-		}
121
-		foreach ($removedMounts as $mount) {
122
-			$this->removeFromCache($mount);
123
-			$index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
124
-			unset($this->mountsForUsers[$user->getUID()][$index]);
125
-		}
126
-		foreach ($changedMounts as $mount) {
127
-			$this->updateCachedMount($mount);
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * @param ICachedMountInfo[] $newMounts
133
-	 * @param ICachedMountInfo[] $cachedMounts
134
-	 * @return ICachedMountInfo[]
135
-	 */
136
-	private function findChangedMounts(array $newMounts, array $cachedMounts) {
137
-		$changed = [];
138
-		foreach ($newMounts as $newMount) {
139
-			foreach ($cachedMounts as $cachedMount) {
140
-				if (
141
-					$newMount->getRootId() === $cachedMount->getRootId() &&
142
-					(
143
-						$newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
144
-						$newMount->getStorageId() !== $cachedMount->getStorageId() ||
145
-						$newMount->getMountId() !== $cachedMount->getMountId()
146
-					)
147
-				) {
148
-					$changed[] = $newMount;
149
-				}
150
-			}
151
-		}
152
-		return $changed;
153
-	}
154
-
155
-	private function addToCache(ICachedMountInfo $mount) {
156
-		if ($mount->getStorageId() !== -1) {
157
-			$this->connection->insertIfNotExist('*PREFIX*mounts', [
158
-				'storage_id' => $mount->getStorageId(),
159
-				'root_id' => $mount->getRootId(),
160
-				'user_id' => $mount->getUser()->getUID(),
161
-				'mount_point' => $mount->getMountPoint(),
162
-				'mount_id' => $mount->getMountId()
163
-			], ['root_id', 'user_id']);
164
-		} else {
165
-			// in some cases this is legitimate, like orphaned shares
166
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
167
-		}
168
-	}
169
-
170
-	private function updateCachedMount(ICachedMountInfo $mount) {
171
-		$builder = $this->connection->getQueryBuilder();
172
-
173
-		$query = $builder->update('mounts')
174
-			->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
175
-			->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
176
-			->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
177
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
178
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
179
-
180
-		$query->execute();
181
-	}
182
-
183
-	private function removeFromCache(ICachedMountInfo $mount) {
184
-		$builder = $this->connection->getQueryBuilder();
185
-
186
-		$query = $builder->delete('mounts')
187
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
188
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
189
-		$query->execute();
190
-	}
191
-
192
-	private function dbRowToMountInfo(array $row) {
193
-		$user = $this->userManager->get($row['user_id']);
194
-		if (is_null($user)) {
195
-			return null;
196
-		}
197
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path']) ? $row['path'] : '');
198
-	}
199
-
200
-	/**
201
-	 * @param IUser $user
202
-	 * @return ICachedMountInfo[]
203
-	 */
204
-	public function getMountsForUser(IUser $user) {
205
-		if (!isset($this->mountsForUsers[$user->getUID()])) {
206
-			$builder = $this->connection->getQueryBuilder();
207
-			$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
208
-				->from('mounts', 'm')
209
-				->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
210
-				->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
211
-
212
-			$rows = $query->execute()->fetchAll();
213
-
214
-			$this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
215
-		}
216
-		return $this->mountsForUsers[$user->getUID()];
217
-	}
218
-
219
-	/**
220
-	 * @param int $numericStorageId
221
-	 * @param string|null $user limit the results to a single user
222
-	 * @return CachedMountInfo[]
223
-	 */
224
-	public function getMountsForStorageId($numericStorageId, $user = null) {
225
-		$builder = $this->connection->getQueryBuilder();
226
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
227
-			->from('mounts', 'm')
228
-			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
229
-			->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
230
-
231
-		if ($user) {
232
-			$query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
233
-		}
234
-
235
-		$rows = $query->execute()->fetchAll();
236
-
237
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
238
-	}
239
-
240
-	/**
241
-	 * @param int $rootFileId
242
-	 * @return CachedMountInfo[]
243
-	 */
244
-	public function getMountsForRootId($rootFileId) {
245
-		$builder = $this->connection->getQueryBuilder();
246
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
247
-			->from('mounts', 'm')
248
-			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
249
-			->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
250
-
251
-		$rows = $query->execute()->fetchAll();
252
-
253
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
254
-	}
255
-
256
-	/**
257
-	 * @param $fileId
258
-	 * @return array
259
-	 * @throws \OCP\Files\NotFoundException
260
-	 */
261
-	private function getCacheInfoFromFileId($fileId) {
262
-		if (!isset($this->cacheInfoCache[$fileId])) {
263
-			$builder = $this->connection->getQueryBuilder();
264
-			$query = $builder->select('storage', 'path', 'mimetype')
265
-				->from('filecache')
266
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
267
-
268
-			$row = $query->execute()->fetch();
269
-			if (is_array($row)) {
270
-				$this->cacheInfoCache[$fileId] = [
271
-					(int)$row['storage'],
272
-					$row['path'],
273
-					(int)$row['mimetype']
274
-				];
275
-			} else {
276
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
277
-			}
278
-		}
279
-		return $this->cacheInfoCache[$fileId];
280
-	}
281
-
282
-	/**
283
-	 * @param int $fileId
284
-	 * @param string|null $user optionally restrict the results to a single user
285
-	 * @return ICachedMountInfo[]
286
-	 * @since 9.0.0
287
-	 */
288
-	public function getMountsForFileId($fileId, $user = null) {
289
-		try {
290
-			list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
291
-		} catch (NotFoundException $e) {
292
-			return [];
293
-		}
294
-		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
295
-
296
-		// filter mounts that are from the same storage but a different directory
297
-		return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
298
-			if ($fileId === $mount->getRootId()) {
299
-				return true;
300
-			}
301
-			$internalMountPath = $mount->getRootInternalPath();
302
-
303
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
304
-		});
305
-	}
306
-
307
-	/**
308
-	 * Remove all cached mounts for a user
309
-	 *
310
-	 * @param IUser $user
311
-	 */
312
-	public function removeUserMounts(IUser $user) {
313
-		$builder = $this->connection->getQueryBuilder();
314
-
315
-		$query = $builder->delete('mounts')
316
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
317
-		$query->execute();
318
-	}
319
-
320
-	public function removeUserStorageMount($storageId, $userId) {
321
-		$builder = $this->connection->getQueryBuilder();
322
-
323
-		$query = $builder->delete('mounts')
324
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
325
-			->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
326
-		$query->execute();
327
-	}
328
-
329
-	public function remoteStorageMounts($storageId) {
330
-		$builder = $this->connection->getQueryBuilder();
331
-
332
-		$query = $builder->delete('mounts')
333
-			->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
334
-		$query->execute();
335
-	}
336
-
337
-	/**
338
-	 * @param array $users
339
-	 * @return array
340
-	 * @suppress SqlInjectionChecker
341
-	 */
342
-	public function getUsedSpaceForUsers(array $users) {
343
-		$builder = $this->connection->getQueryBuilder();
344
-
345
-		$slash = $builder->createNamedParameter('/');
346
-
347
-		$mountPoint = $builder->func()->concat(
348
-			$builder->func()->concat($slash, 'user_id'),
349
-			$slash
350
-		);
351
-
352
-		$userIds = array_map(function (IUser $user) {
353
-			return $user->getUID();
354
-		}, $users);
355
-
356
-		$query = $builder->select('m.user_id', 'f.size')
357
-			->from('mounts', 'm')
358
-			->innerJoin(
359
-				'm',
360
-				'filecache',
361
-				'f',
362
-				$builder->expr()->andX(
363
-					$builder->expr()->eq('m.storage_id', 'f.storage'),
364
-					$builder->expr()->eq('f.path', $builder->createNamedParameter('files'))
365
-				)
366
-			)
367
-			->where($builder->expr()->eq('m.mount_point', $mountPoint))
368
-			->andWhere($builder->expr()->in('m.user_id', $builder->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY)));
369
-
370
-		$result = $query->execute();
371
-
372
-		return $result->fetchAll(\PDO::FETCH_KEY_PAIR);
373
-	}
45
+    /**
46
+     * @var IDBConnection
47
+     */
48
+    private $connection;
49
+
50
+    /**
51
+     * @var IUserManager
52
+     */
53
+    private $userManager;
54
+
55
+    /**
56
+     * Cached mount info.
57
+     * Map of $userId to ICachedMountInfo.
58
+     *
59
+     * @var ICache
60
+     **/
61
+    private $mountsForUsers;
62
+
63
+    /**
64
+     * @var ILogger
65
+     */
66
+    private $logger;
67
+
68
+    /**
69
+     * @var ICache
70
+     */
71
+    private $cacheInfoCache;
72
+
73
+    /**
74
+     * UserMountCache constructor.
75
+     *
76
+     * @param IDBConnection $connection
77
+     * @param IUserManager $userManager
78
+     * @param ILogger $logger
79
+     */
80
+    public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) {
81
+        $this->connection = $connection;
82
+        $this->userManager = $userManager;
83
+        $this->logger = $logger;
84
+        $this->cacheInfoCache = new CappedMemoryCache();
85
+        $this->mountsForUsers = new CappedMemoryCache();
86
+    }
87
+
88
+    public function registerMounts(IUser $user, array $mounts) {
89
+        // filter out non-proper storages coming from unit tests
90
+        $mounts = array_filter($mounts, function (IMountPoint $mount) {
91
+            return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
92
+        });
93
+        /** @var ICachedMountInfo[] $newMounts */
94
+        $newMounts = array_map(function (IMountPoint $mount) use ($user) {
95
+            // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
96
+            if ($mount->getStorageRootId() === -1) {
97
+                return null;
98
+            } else {
99
+                return new LazyStorageMountInfo($user, $mount);
100
+            }
101
+        }, $mounts);
102
+        $newMounts = array_values(array_filter($newMounts));
103
+
104
+        $cachedMounts = $this->getMountsForUser($user);
105
+        $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
106
+            // since we are only looking for mounts for a specific user comparing on root id is enough
107
+            return $mount1->getRootId() - $mount2->getRootId();
108
+        };
109
+
110
+        /** @var ICachedMountInfo[] $addedMounts */
111
+        $addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff);
112
+        /** @var ICachedMountInfo[] $removedMounts */
113
+        $removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff);
114
+
115
+        $changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
116
+
117
+        foreach ($addedMounts as $mount) {
118
+            $this->addToCache($mount);
119
+            $this->mountsForUsers[$user->getUID()][] = $mount;
120
+        }
121
+        foreach ($removedMounts as $mount) {
122
+            $this->removeFromCache($mount);
123
+            $index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
124
+            unset($this->mountsForUsers[$user->getUID()][$index]);
125
+        }
126
+        foreach ($changedMounts as $mount) {
127
+            $this->updateCachedMount($mount);
128
+        }
129
+    }
130
+
131
+    /**
132
+     * @param ICachedMountInfo[] $newMounts
133
+     * @param ICachedMountInfo[] $cachedMounts
134
+     * @return ICachedMountInfo[]
135
+     */
136
+    private function findChangedMounts(array $newMounts, array $cachedMounts) {
137
+        $changed = [];
138
+        foreach ($newMounts as $newMount) {
139
+            foreach ($cachedMounts as $cachedMount) {
140
+                if (
141
+                    $newMount->getRootId() === $cachedMount->getRootId() &&
142
+                    (
143
+                        $newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
144
+                        $newMount->getStorageId() !== $cachedMount->getStorageId() ||
145
+                        $newMount->getMountId() !== $cachedMount->getMountId()
146
+                    )
147
+                ) {
148
+                    $changed[] = $newMount;
149
+                }
150
+            }
151
+        }
152
+        return $changed;
153
+    }
154
+
155
+    private function addToCache(ICachedMountInfo $mount) {
156
+        if ($mount->getStorageId() !== -1) {
157
+            $this->connection->insertIfNotExist('*PREFIX*mounts', [
158
+                'storage_id' => $mount->getStorageId(),
159
+                'root_id' => $mount->getRootId(),
160
+                'user_id' => $mount->getUser()->getUID(),
161
+                'mount_point' => $mount->getMountPoint(),
162
+                'mount_id' => $mount->getMountId()
163
+            ], ['root_id', 'user_id']);
164
+        } else {
165
+            // in some cases this is legitimate, like orphaned shares
166
+            $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
167
+        }
168
+    }
169
+
170
+    private function updateCachedMount(ICachedMountInfo $mount) {
171
+        $builder = $this->connection->getQueryBuilder();
172
+
173
+        $query = $builder->update('mounts')
174
+            ->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
175
+            ->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
176
+            ->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
177
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
178
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
179
+
180
+        $query->execute();
181
+    }
182
+
183
+    private function removeFromCache(ICachedMountInfo $mount) {
184
+        $builder = $this->connection->getQueryBuilder();
185
+
186
+        $query = $builder->delete('mounts')
187
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
188
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
189
+        $query->execute();
190
+    }
191
+
192
+    private function dbRowToMountInfo(array $row) {
193
+        $user = $this->userManager->get($row['user_id']);
194
+        if (is_null($user)) {
195
+            return null;
196
+        }
197
+        return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path']) ? $row['path'] : '');
198
+    }
199
+
200
+    /**
201
+     * @param IUser $user
202
+     * @return ICachedMountInfo[]
203
+     */
204
+    public function getMountsForUser(IUser $user) {
205
+        if (!isset($this->mountsForUsers[$user->getUID()])) {
206
+            $builder = $this->connection->getQueryBuilder();
207
+            $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
208
+                ->from('mounts', 'm')
209
+                ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
210
+                ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
211
+
212
+            $rows = $query->execute()->fetchAll();
213
+
214
+            $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
215
+        }
216
+        return $this->mountsForUsers[$user->getUID()];
217
+    }
218
+
219
+    /**
220
+     * @param int $numericStorageId
221
+     * @param string|null $user limit the results to a single user
222
+     * @return CachedMountInfo[]
223
+     */
224
+    public function getMountsForStorageId($numericStorageId, $user = null) {
225
+        $builder = $this->connection->getQueryBuilder();
226
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
227
+            ->from('mounts', 'm')
228
+            ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
229
+            ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
230
+
231
+        if ($user) {
232
+            $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
233
+        }
234
+
235
+        $rows = $query->execute()->fetchAll();
236
+
237
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
238
+    }
239
+
240
+    /**
241
+     * @param int $rootFileId
242
+     * @return CachedMountInfo[]
243
+     */
244
+    public function getMountsForRootId($rootFileId) {
245
+        $builder = $this->connection->getQueryBuilder();
246
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
247
+            ->from('mounts', 'm')
248
+            ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
249
+            ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
250
+
251
+        $rows = $query->execute()->fetchAll();
252
+
253
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
254
+    }
255
+
256
+    /**
257
+     * @param $fileId
258
+     * @return array
259
+     * @throws \OCP\Files\NotFoundException
260
+     */
261
+    private function getCacheInfoFromFileId($fileId) {
262
+        if (!isset($this->cacheInfoCache[$fileId])) {
263
+            $builder = $this->connection->getQueryBuilder();
264
+            $query = $builder->select('storage', 'path', 'mimetype')
265
+                ->from('filecache')
266
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
267
+
268
+            $row = $query->execute()->fetch();
269
+            if (is_array($row)) {
270
+                $this->cacheInfoCache[$fileId] = [
271
+                    (int)$row['storage'],
272
+                    $row['path'],
273
+                    (int)$row['mimetype']
274
+                ];
275
+            } else {
276
+                throw new NotFoundException('File with id "' . $fileId . '" not found');
277
+            }
278
+        }
279
+        return $this->cacheInfoCache[$fileId];
280
+    }
281
+
282
+    /**
283
+     * @param int $fileId
284
+     * @param string|null $user optionally restrict the results to a single user
285
+     * @return ICachedMountInfo[]
286
+     * @since 9.0.0
287
+     */
288
+    public function getMountsForFileId($fileId, $user = null) {
289
+        try {
290
+            list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
291
+        } catch (NotFoundException $e) {
292
+            return [];
293
+        }
294
+        $mountsForStorage = $this->getMountsForStorageId($storageId, $user);
295
+
296
+        // filter mounts that are from the same storage but a different directory
297
+        return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
298
+            if ($fileId === $mount->getRootId()) {
299
+                return true;
300
+            }
301
+            $internalMountPath = $mount->getRootInternalPath();
302
+
303
+            return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
304
+        });
305
+    }
306
+
307
+    /**
308
+     * Remove all cached mounts for a user
309
+     *
310
+     * @param IUser $user
311
+     */
312
+    public function removeUserMounts(IUser $user) {
313
+        $builder = $this->connection->getQueryBuilder();
314
+
315
+        $query = $builder->delete('mounts')
316
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
317
+        $query->execute();
318
+    }
319
+
320
+    public function removeUserStorageMount($storageId, $userId) {
321
+        $builder = $this->connection->getQueryBuilder();
322
+
323
+        $query = $builder->delete('mounts')
324
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
325
+            ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
326
+        $query->execute();
327
+    }
328
+
329
+    public function remoteStorageMounts($storageId) {
330
+        $builder = $this->connection->getQueryBuilder();
331
+
332
+        $query = $builder->delete('mounts')
333
+            ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
334
+        $query->execute();
335
+    }
336
+
337
+    /**
338
+     * @param array $users
339
+     * @return array
340
+     * @suppress SqlInjectionChecker
341
+     */
342
+    public function getUsedSpaceForUsers(array $users) {
343
+        $builder = $this->connection->getQueryBuilder();
344
+
345
+        $slash = $builder->createNamedParameter('/');
346
+
347
+        $mountPoint = $builder->func()->concat(
348
+            $builder->func()->concat($slash, 'user_id'),
349
+            $slash
350
+        );
351
+
352
+        $userIds = array_map(function (IUser $user) {
353
+            return $user->getUID();
354
+        }, $users);
355
+
356
+        $query = $builder->select('m.user_id', 'f.size')
357
+            ->from('mounts', 'm')
358
+            ->innerJoin(
359
+                'm',
360
+                'filecache',
361
+                'f',
362
+                $builder->expr()->andX(
363
+                    $builder->expr()->eq('m.storage_id', 'f.storage'),
364
+                    $builder->expr()->eq('f.path', $builder->createNamedParameter('files'))
365
+                )
366
+            )
367
+            ->where($builder->expr()->eq('m.mount_point', $mountPoint))
368
+            ->andWhere($builder->expr()->in('m.user_id', $builder->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY)));
369
+
370
+        $result = $query->execute();
371
+
372
+        return $result->fetchAll(\PDO::FETCH_KEY_PAIR);
373
+    }
374 374
 }
Please login to merge, or discard this patch.
lib/private/Files/Node/LazyRoot.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -52,7 +52,7 @@
 block discarded – undo
52 52
 	 * Magic method to first get the real rootFolder and then
53 53
 	 * call $method with $args on it
54 54
 	 *
55
-	 * @param $method
55
+	 * @param string $method
56 56
 	 * @param $args
57 57
 	 * @return mixed
58 58
 	 */
Please login to merge, or discard this patch.
Indentation   +443 added lines, -443 removed lines patch added patch discarded remove patch
@@ -32,447 +32,447 @@
 block discarded – undo
32 32
  * @package OC\Files\Node
33 33
  */
34 34
 class LazyRoot implements IRootFolder {
35
-	/** @var \Closure */
36
-	private $rootFolderClosure;
37
-
38
-	/** @var IRootFolder */
39
-	private $rootFolder;
40
-
41
-	/**
42
-	 * LazyRoot constructor.
43
-	 *
44
-	 * @param \Closure $rootFolderClosure
45
-	 */
46
-	public function __construct(\Closure $rootFolderClosure) {
47
-		$this->rootFolderClosure = $rootFolderClosure;
48
-	}
49
-
50
-	/**
51
-	 * Magic method to first get the real rootFolder and then
52
-	 * call $method with $args on it
53
-	 *
54
-	 * @param $method
55
-	 * @param $args
56
-	 * @return mixed
57
-	 */
58
-	public function __call($method, $args) {
59
-		if ($this->rootFolder === null) {
60
-			$this->rootFolder = call_user_func($this->rootFolderClosure);
61
-		}
62
-
63
-		return call_user_func_array([$this->rootFolder, $method], $args);
64
-	}
65
-
66
-	/**
67
-	 * @inheritDoc
68
-	 */
69
-	public function getUser() {
70
-		return $this->__call(__FUNCTION__, func_get_args());
71
-	}
72
-
73
-	/**
74
-	 * @inheritDoc
75
-	 */
76
-	public function listen($scope, $method, callable $callback) {
77
-		$this->__call(__FUNCTION__, func_get_args());
78
-	}
79
-
80
-	/**
81
-	 * @inheritDoc
82
-	 */
83
-	public function removeListener($scope = null, $method = null, callable $callback = null) {
84
-		$this->__call(__FUNCTION__, func_get_args());
85
-	}
86
-
87
-	/**
88
-	 * @inheritDoc
89
-	 */
90
-	public function emit($scope, $method, $arguments = []) {
91
-		$this->__call(__FUNCTION__, func_get_args());
92
-	}
93
-
94
-	/**
95
-	 * @inheritDoc
96
-	 */
97
-	public function mount($storage, $mountPoint, $arguments = []) {
98
-		$this->__call(__FUNCTION__, func_get_args());
99
-	}
100
-
101
-	/**
102
-	 * @inheritDoc
103
-	 */
104
-	public function getMount($mountPoint) {
105
-		return $this->__call(__FUNCTION__, func_get_args());
106
-	}
107
-
108
-	/**
109
-	 * @inheritDoc
110
-	 */
111
-	public function getMountsIn($mountPoint) {
112
-		return $this->__call(__FUNCTION__, func_get_args());
113
-	}
114
-
115
-	/**
116
-	 * @inheritDoc
117
-	 */
118
-	public function getMountByStorageId($storageId) {
119
-		return $this->__call(__FUNCTION__, func_get_args());
120
-	}
121
-
122
-	/**
123
-	 * @inheritDoc
124
-	 */
125
-	public function getMountByNumericStorageId($numericId) {
126
-		return $this->__call(__FUNCTION__, func_get_args());
127
-	}
128
-
129
-	/**
130
-	 * @inheritDoc
131
-	 */
132
-	public function unMount($mount) {
133
-		$this->__call(__FUNCTION__, func_get_args());
134
-	}
135
-
136
-	/**
137
-	 * @inheritDoc
138
-	 */
139
-	public function get($path) {
140
-		return $this->__call(__FUNCTION__, func_get_args());
141
-	}
142
-
143
-	/**
144
-	 * @inheritDoc
145
-	 */
146
-	public function rename($targetPath) {
147
-		return $this->__call(__FUNCTION__, func_get_args());
148
-	}
149
-
150
-	/**
151
-	 * @inheritDoc
152
-	 */
153
-	public function delete() {
154
-		return $this->__call(__FUNCTION__, func_get_args());
155
-	}
156
-
157
-	/**
158
-	 * @inheritDoc
159
-	 */
160
-	public function copy($targetPath) {
161
-		return $this->__call(__FUNCTION__, func_get_args());
162
-	}
163
-
164
-	/**
165
-	 * @inheritDoc
166
-	 */
167
-	public function touch($mtime = null) {
168
-		$this->__call(__FUNCTION__, func_get_args());
169
-	}
170
-
171
-	/**
172
-	 * @inheritDoc
173
-	 */
174
-	public function getStorage() {
175
-		return $this->__call(__FUNCTION__, func_get_args());
176
-	}
177
-
178
-	/**
179
-	 * @inheritDoc
180
-	 */
181
-	public function getPath() {
182
-		return $this->__call(__FUNCTION__, func_get_args());
183
-	}
184
-
185
-	/**
186
-	 * @inheritDoc
187
-	 */
188
-	public function getInternalPath() {
189
-		return $this->__call(__FUNCTION__, func_get_args());
190
-	}
191
-
192
-	/**
193
-	 * @inheritDoc
194
-	 */
195
-	public function getId() {
196
-		return $this->__call(__FUNCTION__, func_get_args());
197
-	}
198
-
199
-	/**
200
-	 * @inheritDoc
201
-	 */
202
-	public function stat() {
203
-		return $this->__call(__FUNCTION__, func_get_args());
204
-	}
205
-
206
-	/**
207
-	 * @inheritDoc
208
-	 */
209
-	public function getMTime() {
210
-		return $this->__call(__FUNCTION__, func_get_args());
211
-	}
212
-
213
-	/**
214
-	 * @inheritDoc
215
-	 */
216
-	public function getSize() {
217
-		return $this->__call(__FUNCTION__, func_get_args());
218
-	}
219
-
220
-	/**
221
-	 * @inheritDoc
222
-	 */
223
-	public function getEtag() {
224
-		return $this->__call(__FUNCTION__, func_get_args());
225
-	}
226
-
227
-	/**
228
-	 * @inheritDoc
229
-	 */
230
-	public function getPermissions() {
231
-		return $this->__call(__FUNCTION__, func_get_args());
232
-	}
233
-
234
-	/**
235
-	 * @inheritDoc
236
-	 */
237
-	public function isReadable() {
238
-		return $this->__call(__FUNCTION__, func_get_args());
239
-	}
240
-
241
-	/**
242
-	 * @inheritDoc
243
-	 */
244
-	public function isUpdateable() {
245
-		return $this->__call(__FUNCTION__, func_get_args());
246
-	}
247
-
248
-	/**
249
-	 * @inheritDoc
250
-	 */
251
-	public function isDeletable() {
252
-		return $this->__call(__FUNCTION__, func_get_args());
253
-	}
254
-
255
-	/**
256
-	 * @inheritDoc
257
-	 */
258
-	public function isShareable() {
259
-		return $this->__call(__FUNCTION__, func_get_args());
260
-	}
261
-
262
-	/**
263
-	 * @inheritDoc
264
-	 */
265
-	public function getParent() {
266
-		return $this->__call(__FUNCTION__, func_get_args());
267
-	}
268
-
269
-	/**
270
-	 * @inheritDoc
271
-	 */
272
-	public function getName() {
273
-		return $this->__call(__FUNCTION__, func_get_args());
274
-	}
275
-
276
-	/**
277
-	 * @inheritDoc
278
-	 */
279
-	public function getUserFolder($userId) {
280
-		return $this->__call(__FUNCTION__, func_get_args());
281
-	}
282
-
283
-	/**
284
-	 * @inheritDoc
285
-	 */
286
-	public function getMimetype() {
287
-		return $this->__call(__FUNCTION__, func_get_args());
288
-	}
289
-
290
-	/**
291
-	 * @inheritDoc
292
-	 */
293
-	public function getMimePart() {
294
-		return $this->__call(__FUNCTION__, func_get_args());
295
-	}
296
-
297
-	/**
298
-	 * @inheritDoc
299
-	 */
300
-	public function isEncrypted() {
301
-		return $this->__call(__FUNCTION__, func_get_args());
302
-	}
303
-
304
-	/**
305
-	 * @inheritDoc
306
-	 */
307
-	public function getType() {
308
-		return $this->__call(__FUNCTION__, func_get_args());
309
-	}
310
-
311
-	/**
312
-	 * @inheritDoc
313
-	 */
314
-	public function isShared() {
315
-		return $this->__call(__FUNCTION__, func_get_args());
316
-	}
317
-
318
-	/**
319
-	 * @inheritDoc
320
-	 */
321
-	public function isMounted() {
322
-		return $this->__call(__FUNCTION__, func_get_args());
323
-	}
324
-
325
-	/**
326
-	 * @inheritDoc
327
-	 */
328
-	public function getMountPoint() {
329
-		return $this->__call(__FUNCTION__, func_get_args());
330
-	}
331
-
332
-	/**
333
-	 * @inheritDoc
334
-	 */
335
-	public function getOwner() {
336
-		return $this->__call(__FUNCTION__, func_get_args());
337
-	}
338
-
339
-	/**
340
-	 * @inheritDoc
341
-	 */
342
-	public function getChecksum() {
343
-		return $this->__call(__FUNCTION__, func_get_args());
344
-	}
345
-
346
-	/**
347
-	 * @inheritDoc
348
-	 */
349
-	public function getFullPath($path) {
350
-		return $this->__call(__FUNCTION__, func_get_args());
351
-	}
352
-
353
-	/**
354
-	 * @inheritDoc
355
-	 */
356
-	public function getRelativePath($path) {
357
-		return $this->__call(__FUNCTION__, func_get_args());
358
-	}
359
-
360
-	/**
361
-	 * @inheritDoc
362
-	 */
363
-	public function isSubNode($node) {
364
-		return $this->__call(__FUNCTION__, func_get_args());
365
-	}
366
-
367
-	/**
368
-	 * @inheritDoc
369
-	 */
370
-	public function getDirectoryListing() {
371
-		return $this->__call(__FUNCTION__, func_get_args());
372
-	}
373
-
374
-	/**
375
-	 * @inheritDoc
376
-	 */
377
-	public function nodeExists($path) {
378
-		return $this->__call(__FUNCTION__, func_get_args());
379
-	}
380
-
381
-	/**
382
-	 * @inheritDoc
383
-	 */
384
-	public function newFolder($path) {
385
-		return $this->__call(__FUNCTION__, func_get_args());
386
-	}
387
-
388
-	/**
389
-	 * @inheritDoc
390
-	 */
391
-	public function newFile($path) {
392
-		return $this->__call(__FUNCTION__, func_get_args());
393
-	}
394
-
395
-	/**
396
-	 * @inheritDoc
397
-	 */
398
-	public function search($query) {
399
-		return $this->__call(__FUNCTION__, func_get_args());
400
-	}
401
-
402
-	/**
403
-	 * @inheritDoc
404
-	 */
405
-	public function searchByMime($mimetype) {
406
-		return $this->__call(__FUNCTION__, func_get_args());
407
-	}
408
-
409
-	/**
410
-	 * @inheritDoc
411
-	 */
412
-	public function searchByTag($tag, $userId) {
413
-		return $this->__call(__FUNCTION__, func_get_args());
414
-	}
415
-
416
-	/**
417
-	 * @inheritDoc
418
-	 */
419
-	public function getById($id) {
420
-		return $this->__call(__FUNCTION__, func_get_args());
421
-	}
422
-
423
-	/**
424
-	 * @inheritDoc
425
-	 */
426
-	public function getFreeSpace() {
427
-		return $this->__call(__FUNCTION__, func_get_args());
428
-	}
429
-
430
-	/**
431
-	 * @inheritDoc
432
-	 */
433
-	public function isCreatable() {
434
-		return $this->__call(__FUNCTION__, func_get_args());
435
-	}
436
-
437
-	/**
438
-	 * @inheritDoc
439
-	 */
440
-	public function getNonExistingName($name) {
441
-		return $this->__call(__FUNCTION__, func_get_args());
442
-	}
443
-
444
-	/**
445
-	 * @inheritDoc
446
-	 */
447
-	public function move($targetPath) {
448
-		return $this->__call(__FUNCTION__, func_get_args());
449
-	}
450
-
451
-	/**
452
-	 * @inheritDoc
453
-	 */
454
-	public function lock($type) {
455
-		return $this->__call(__FUNCTION__, func_get_args());
456
-	}
457
-
458
-	/**
459
-	 * @inheritDoc
460
-	 */
461
-	public function changeLock($targetType) {
462
-		return $this->__call(__FUNCTION__, func_get_args());
463
-	}
464
-
465
-	/**
466
-	 * @inheritDoc
467
-	 */
468
-	public function unlock($type) {
469
-		return $this->__call(__FUNCTION__, func_get_args());
470
-	}
471
-
472
-	/**
473
-	 * @inheritDoc
474
-	 */
475
-	public function getRecent($limit, $offset = 0) {
476
-		return $this->__call(__FUNCTION__, func_get_args());
477
-	}
35
+    /** @var \Closure */
36
+    private $rootFolderClosure;
37
+
38
+    /** @var IRootFolder */
39
+    private $rootFolder;
40
+
41
+    /**
42
+     * LazyRoot constructor.
43
+     *
44
+     * @param \Closure $rootFolderClosure
45
+     */
46
+    public function __construct(\Closure $rootFolderClosure) {
47
+        $this->rootFolderClosure = $rootFolderClosure;
48
+    }
49
+
50
+    /**
51
+     * Magic method to first get the real rootFolder and then
52
+     * call $method with $args on it
53
+     *
54
+     * @param $method
55
+     * @param $args
56
+     * @return mixed
57
+     */
58
+    public function __call($method, $args) {
59
+        if ($this->rootFolder === null) {
60
+            $this->rootFolder = call_user_func($this->rootFolderClosure);
61
+        }
62
+
63
+        return call_user_func_array([$this->rootFolder, $method], $args);
64
+    }
65
+
66
+    /**
67
+     * @inheritDoc
68
+     */
69
+    public function getUser() {
70
+        return $this->__call(__FUNCTION__, func_get_args());
71
+    }
72
+
73
+    /**
74
+     * @inheritDoc
75
+     */
76
+    public function listen($scope, $method, callable $callback) {
77
+        $this->__call(__FUNCTION__, func_get_args());
78
+    }
79
+
80
+    /**
81
+     * @inheritDoc
82
+     */
83
+    public function removeListener($scope = null, $method = null, callable $callback = null) {
84
+        $this->__call(__FUNCTION__, func_get_args());
85
+    }
86
+
87
+    /**
88
+     * @inheritDoc
89
+     */
90
+    public function emit($scope, $method, $arguments = []) {
91
+        $this->__call(__FUNCTION__, func_get_args());
92
+    }
93
+
94
+    /**
95
+     * @inheritDoc
96
+     */
97
+    public function mount($storage, $mountPoint, $arguments = []) {
98
+        $this->__call(__FUNCTION__, func_get_args());
99
+    }
100
+
101
+    /**
102
+     * @inheritDoc
103
+     */
104
+    public function getMount($mountPoint) {
105
+        return $this->__call(__FUNCTION__, func_get_args());
106
+    }
107
+
108
+    /**
109
+     * @inheritDoc
110
+     */
111
+    public function getMountsIn($mountPoint) {
112
+        return $this->__call(__FUNCTION__, func_get_args());
113
+    }
114
+
115
+    /**
116
+     * @inheritDoc
117
+     */
118
+    public function getMountByStorageId($storageId) {
119
+        return $this->__call(__FUNCTION__, func_get_args());
120
+    }
121
+
122
+    /**
123
+     * @inheritDoc
124
+     */
125
+    public function getMountByNumericStorageId($numericId) {
126
+        return $this->__call(__FUNCTION__, func_get_args());
127
+    }
128
+
129
+    /**
130
+     * @inheritDoc
131
+     */
132
+    public function unMount($mount) {
133
+        $this->__call(__FUNCTION__, func_get_args());
134
+    }
135
+
136
+    /**
137
+     * @inheritDoc
138
+     */
139
+    public function get($path) {
140
+        return $this->__call(__FUNCTION__, func_get_args());
141
+    }
142
+
143
+    /**
144
+     * @inheritDoc
145
+     */
146
+    public function rename($targetPath) {
147
+        return $this->__call(__FUNCTION__, func_get_args());
148
+    }
149
+
150
+    /**
151
+     * @inheritDoc
152
+     */
153
+    public function delete() {
154
+        return $this->__call(__FUNCTION__, func_get_args());
155
+    }
156
+
157
+    /**
158
+     * @inheritDoc
159
+     */
160
+    public function copy($targetPath) {
161
+        return $this->__call(__FUNCTION__, func_get_args());
162
+    }
163
+
164
+    /**
165
+     * @inheritDoc
166
+     */
167
+    public function touch($mtime = null) {
168
+        $this->__call(__FUNCTION__, func_get_args());
169
+    }
170
+
171
+    /**
172
+     * @inheritDoc
173
+     */
174
+    public function getStorage() {
175
+        return $this->__call(__FUNCTION__, func_get_args());
176
+    }
177
+
178
+    /**
179
+     * @inheritDoc
180
+     */
181
+    public function getPath() {
182
+        return $this->__call(__FUNCTION__, func_get_args());
183
+    }
184
+
185
+    /**
186
+     * @inheritDoc
187
+     */
188
+    public function getInternalPath() {
189
+        return $this->__call(__FUNCTION__, func_get_args());
190
+    }
191
+
192
+    /**
193
+     * @inheritDoc
194
+     */
195
+    public function getId() {
196
+        return $this->__call(__FUNCTION__, func_get_args());
197
+    }
198
+
199
+    /**
200
+     * @inheritDoc
201
+     */
202
+    public function stat() {
203
+        return $this->__call(__FUNCTION__, func_get_args());
204
+    }
205
+
206
+    /**
207
+     * @inheritDoc
208
+     */
209
+    public function getMTime() {
210
+        return $this->__call(__FUNCTION__, func_get_args());
211
+    }
212
+
213
+    /**
214
+     * @inheritDoc
215
+     */
216
+    public function getSize() {
217
+        return $this->__call(__FUNCTION__, func_get_args());
218
+    }
219
+
220
+    /**
221
+     * @inheritDoc
222
+     */
223
+    public function getEtag() {
224
+        return $this->__call(__FUNCTION__, func_get_args());
225
+    }
226
+
227
+    /**
228
+     * @inheritDoc
229
+     */
230
+    public function getPermissions() {
231
+        return $this->__call(__FUNCTION__, func_get_args());
232
+    }
233
+
234
+    /**
235
+     * @inheritDoc
236
+     */
237
+    public function isReadable() {
238
+        return $this->__call(__FUNCTION__, func_get_args());
239
+    }
240
+
241
+    /**
242
+     * @inheritDoc
243
+     */
244
+    public function isUpdateable() {
245
+        return $this->__call(__FUNCTION__, func_get_args());
246
+    }
247
+
248
+    /**
249
+     * @inheritDoc
250
+     */
251
+    public function isDeletable() {
252
+        return $this->__call(__FUNCTION__, func_get_args());
253
+    }
254
+
255
+    /**
256
+     * @inheritDoc
257
+     */
258
+    public function isShareable() {
259
+        return $this->__call(__FUNCTION__, func_get_args());
260
+    }
261
+
262
+    /**
263
+     * @inheritDoc
264
+     */
265
+    public function getParent() {
266
+        return $this->__call(__FUNCTION__, func_get_args());
267
+    }
268
+
269
+    /**
270
+     * @inheritDoc
271
+     */
272
+    public function getName() {
273
+        return $this->__call(__FUNCTION__, func_get_args());
274
+    }
275
+
276
+    /**
277
+     * @inheritDoc
278
+     */
279
+    public function getUserFolder($userId) {
280
+        return $this->__call(__FUNCTION__, func_get_args());
281
+    }
282
+
283
+    /**
284
+     * @inheritDoc
285
+     */
286
+    public function getMimetype() {
287
+        return $this->__call(__FUNCTION__, func_get_args());
288
+    }
289
+
290
+    /**
291
+     * @inheritDoc
292
+     */
293
+    public function getMimePart() {
294
+        return $this->__call(__FUNCTION__, func_get_args());
295
+    }
296
+
297
+    /**
298
+     * @inheritDoc
299
+     */
300
+    public function isEncrypted() {
301
+        return $this->__call(__FUNCTION__, func_get_args());
302
+    }
303
+
304
+    /**
305
+     * @inheritDoc
306
+     */
307
+    public function getType() {
308
+        return $this->__call(__FUNCTION__, func_get_args());
309
+    }
310
+
311
+    /**
312
+     * @inheritDoc
313
+     */
314
+    public function isShared() {
315
+        return $this->__call(__FUNCTION__, func_get_args());
316
+    }
317
+
318
+    /**
319
+     * @inheritDoc
320
+     */
321
+    public function isMounted() {
322
+        return $this->__call(__FUNCTION__, func_get_args());
323
+    }
324
+
325
+    /**
326
+     * @inheritDoc
327
+     */
328
+    public function getMountPoint() {
329
+        return $this->__call(__FUNCTION__, func_get_args());
330
+    }
331
+
332
+    /**
333
+     * @inheritDoc
334
+     */
335
+    public function getOwner() {
336
+        return $this->__call(__FUNCTION__, func_get_args());
337
+    }
338
+
339
+    /**
340
+     * @inheritDoc
341
+     */
342
+    public function getChecksum() {
343
+        return $this->__call(__FUNCTION__, func_get_args());
344
+    }
345
+
346
+    /**
347
+     * @inheritDoc
348
+     */
349
+    public function getFullPath($path) {
350
+        return $this->__call(__FUNCTION__, func_get_args());
351
+    }
352
+
353
+    /**
354
+     * @inheritDoc
355
+     */
356
+    public function getRelativePath($path) {
357
+        return $this->__call(__FUNCTION__, func_get_args());
358
+    }
359
+
360
+    /**
361
+     * @inheritDoc
362
+     */
363
+    public function isSubNode($node) {
364
+        return $this->__call(__FUNCTION__, func_get_args());
365
+    }
366
+
367
+    /**
368
+     * @inheritDoc
369
+     */
370
+    public function getDirectoryListing() {
371
+        return $this->__call(__FUNCTION__, func_get_args());
372
+    }
373
+
374
+    /**
375
+     * @inheritDoc
376
+     */
377
+    public function nodeExists($path) {
378
+        return $this->__call(__FUNCTION__, func_get_args());
379
+    }
380
+
381
+    /**
382
+     * @inheritDoc
383
+     */
384
+    public function newFolder($path) {
385
+        return $this->__call(__FUNCTION__, func_get_args());
386
+    }
387
+
388
+    /**
389
+     * @inheritDoc
390
+     */
391
+    public function newFile($path) {
392
+        return $this->__call(__FUNCTION__, func_get_args());
393
+    }
394
+
395
+    /**
396
+     * @inheritDoc
397
+     */
398
+    public function search($query) {
399
+        return $this->__call(__FUNCTION__, func_get_args());
400
+    }
401
+
402
+    /**
403
+     * @inheritDoc
404
+     */
405
+    public function searchByMime($mimetype) {
406
+        return $this->__call(__FUNCTION__, func_get_args());
407
+    }
408
+
409
+    /**
410
+     * @inheritDoc
411
+     */
412
+    public function searchByTag($tag, $userId) {
413
+        return $this->__call(__FUNCTION__, func_get_args());
414
+    }
415
+
416
+    /**
417
+     * @inheritDoc
418
+     */
419
+    public function getById($id) {
420
+        return $this->__call(__FUNCTION__, func_get_args());
421
+    }
422
+
423
+    /**
424
+     * @inheritDoc
425
+     */
426
+    public function getFreeSpace() {
427
+        return $this->__call(__FUNCTION__, func_get_args());
428
+    }
429
+
430
+    /**
431
+     * @inheritDoc
432
+     */
433
+    public function isCreatable() {
434
+        return $this->__call(__FUNCTION__, func_get_args());
435
+    }
436
+
437
+    /**
438
+     * @inheritDoc
439
+     */
440
+    public function getNonExistingName($name) {
441
+        return $this->__call(__FUNCTION__, func_get_args());
442
+    }
443
+
444
+    /**
445
+     * @inheritDoc
446
+     */
447
+    public function move($targetPath) {
448
+        return $this->__call(__FUNCTION__, func_get_args());
449
+    }
450
+
451
+    /**
452
+     * @inheritDoc
453
+     */
454
+    public function lock($type) {
455
+        return $this->__call(__FUNCTION__, func_get_args());
456
+    }
457
+
458
+    /**
459
+     * @inheritDoc
460
+     */
461
+    public function changeLock($targetType) {
462
+        return $this->__call(__FUNCTION__, func_get_args());
463
+    }
464
+
465
+    /**
466
+     * @inheritDoc
467
+     */
468
+    public function unlock($type) {
469
+        return $this->__call(__FUNCTION__, func_get_args());
470
+    }
471
+
472
+    /**
473
+     * @inheritDoc
474
+     */
475
+    public function getRecent($limit, $offset = 0) {
476
+        return $this->__call(__FUNCTION__, func_get_args());
477
+    }
478 478
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Flysystem.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -54,6 +54,9 @@
 block discarded – undo
54 54
 		$this->flysystem->addPlugin(new GetWithMetadata());
55 55
 	}
56 56
 
57
+	/**
58
+	 * @param string $path
59
+	 */
57 60
 	protected function buildPath($path) {
58 61
 		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
59 62
 		return ltrim($fullPath, '/');
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 	}
57 57
 
58 58
 	protected function buildPath($path) {
59
-		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
59
+		$fullPath = \OC\Files\Filesystem::normalizePath($this->root.'/'.$path);
60 60
 		return ltrim($fullPath, '/');
61 61
 	}
62 62
 
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		} catch (FileNotFoundException $e) {
164 164
 			return false;
165 165
 		}
166
-		$names = array_map(function ($object) {
166
+		$names = array_map(function($object) {
167 167
 			return $object['basename'];
168 168
 		}, $content);
169 169
 		return IteratorDirectory::wrap($names);
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 					$tmpFile = \OCP\Files::tmpFile();
210 210
 				}
211 211
 				$source = fopen($tmpFile, $mode);
212
-				return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
212
+				return CallbackWrapper::wrap($source, null, null, function() use ($tmpFile, $fullPath) {
213 213
 					$this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214 214
 					unlink($tmpFile);
215 215
 				});
Please login to merge, or discard this patch.
Indentation   +202 added lines, -202 removed lines patch added patch discarded remove patch
@@ -35,224 +35,224 @@
 block discarded – undo
35 35
  * To use: subclass and call $this->buildFlysystem with the flysystem adapter of choice
36 36
  */
37 37
 abstract class Flysystem extends Common {
38
-	/**
39
-	 * @var Filesystem
40
-	 */
41
-	protected $flysystem;
38
+    /**
39
+     * @var Filesystem
40
+     */
41
+    protected $flysystem;
42 42
 
43
-	/**
44
-	 * @var string
45
-	 */
46
-	protected $root = '';
43
+    /**
44
+     * @var string
45
+     */
46
+    protected $root = '';
47 47
 
48
-	/**
49
-	 * Initialize the storage backend with a flyssytem adapter
50
-	 *
51
-	 * @param \League\Flysystem\AdapterInterface $adapter
52
-	 */
53
-	protected function buildFlySystem(AdapterInterface $adapter) {
54
-		$this->flysystem = new Filesystem($adapter);
55
-		$this->flysystem->addPlugin(new GetWithMetadata());
56
-	}
48
+    /**
49
+     * Initialize the storage backend with a flyssytem adapter
50
+     *
51
+     * @param \League\Flysystem\AdapterInterface $adapter
52
+     */
53
+    protected function buildFlySystem(AdapterInterface $adapter) {
54
+        $this->flysystem = new Filesystem($adapter);
55
+        $this->flysystem->addPlugin(new GetWithMetadata());
56
+    }
57 57
 
58
-	protected function buildPath($path) {
59
-		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
60
-		return ltrim($fullPath, '/');
61
-	}
58
+    protected function buildPath($path) {
59
+        $fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
60
+        return ltrim($fullPath, '/');
61
+    }
62 62
 
63
-	/**
64
-	 * {@inheritdoc}
65
-	 */
66
-	public function file_get_contents($path) {
67
-		return $this->flysystem->read($this->buildPath($path));
68
-	}
63
+    /**
64
+     * {@inheritdoc}
65
+     */
66
+    public function file_get_contents($path) {
67
+        return $this->flysystem->read($this->buildPath($path));
68
+    }
69 69
 
70
-	/**
71
-	 * {@inheritdoc}
72
-	 */
73
-	public function file_put_contents($path, $data) {
74
-		return $this->flysystem->put($this->buildPath($path), $data);
75
-	}
70
+    /**
71
+     * {@inheritdoc}
72
+     */
73
+    public function file_put_contents($path, $data) {
74
+        return $this->flysystem->put($this->buildPath($path), $data);
75
+    }
76 76
 
77
-	/**
78
-	 * {@inheritdoc}
79
-	 */
80
-	public function file_exists($path) {
81
-		return $this->flysystem->has($this->buildPath($path));
82
-	}
77
+    /**
78
+     * {@inheritdoc}
79
+     */
80
+    public function file_exists($path) {
81
+        return $this->flysystem->has($this->buildPath($path));
82
+    }
83 83
 
84
-	/**
85
-	 * {@inheritdoc}
86
-	 */
87
-	public function unlink($path) {
88
-		if ($this->is_dir($path)) {
89
-			return $this->rmdir($path);
90
-		}
91
-		try {
92
-			return $this->flysystem->delete($this->buildPath($path));
93
-		} catch (FileNotFoundException $e) {
94
-			return false;
95
-		}
96
-	}
84
+    /**
85
+     * {@inheritdoc}
86
+     */
87
+    public function unlink($path) {
88
+        if ($this->is_dir($path)) {
89
+            return $this->rmdir($path);
90
+        }
91
+        try {
92
+            return $this->flysystem->delete($this->buildPath($path));
93
+        } catch (FileNotFoundException $e) {
94
+            return false;
95
+        }
96
+    }
97 97
 
98
-	/**
99
-	 * {@inheritdoc}
100
-	 */
101
-	public function rename($source, $target) {
102
-		if ($this->file_exists($target)) {
103
-			$this->unlink($target);
104
-		}
105
-		return $this->flysystem->rename($this->buildPath($source), $this->buildPath($target));
106
-	}
98
+    /**
99
+     * {@inheritdoc}
100
+     */
101
+    public function rename($source, $target) {
102
+        if ($this->file_exists($target)) {
103
+            $this->unlink($target);
104
+        }
105
+        return $this->flysystem->rename($this->buildPath($source), $this->buildPath($target));
106
+    }
107 107
 
108
-	/**
109
-	 * {@inheritdoc}
110
-	 */
111
-	public function copy($source, $target) {
112
-		if ($this->file_exists($target)) {
113
-			$this->unlink($target);
114
-		}
115
-		return $this->flysystem->copy($this->buildPath($source), $this->buildPath($target));
116
-	}
108
+    /**
109
+     * {@inheritdoc}
110
+     */
111
+    public function copy($source, $target) {
112
+        if ($this->file_exists($target)) {
113
+            $this->unlink($target);
114
+        }
115
+        return $this->flysystem->copy($this->buildPath($source), $this->buildPath($target));
116
+    }
117 117
 
118
-	/**
119
-	 * {@inheritdoc}
120
-	 */
121
-	public function filesize($path) {
122
-		if ($this->is_dir($path)) {
123
-			return 0;
124
-		} else {
125
-			return $this->flysystem->getSize($this->buildPath($path));
126
-		}
127
-	}
118
+    /**
119
+     * {@inheritdoc}
120
+     */
121
+    public function filesize($path) {
122
+        if ($this->is_dir($path)) {
123
+            return 0;
124
+        } else {
125
+            return $this->flysystem->getSize($this->buildPath($path));
126
+        }
127
+    }
128 128
 
129
-	/**
130
-	 * {@inheritdoc}
131
-	 */
132
-	public function mkdir($path) {
133
-		if ($this->file_exists($path)) {
134
-			return false;
135
-		}
136
-		return $this->flysystem->createDir($this->buildPath($path));
137
-	}
129
+    /**
130
+     * {@inheritdoc}
131
+     */
132
+    public function mkdir($path) {
133
+        if ($this->file_exists($path)) {
134
+            return false;
135
+        }
136
+        return $this->flysystem->createDir($this->buildPath($path));
137
+    }
138 138
 
139
-	/**
140
-	 * {@inheritdoc}
141
-	 */
142
-	public function filemtime($path) {
143
-		return $this->flysystem->getTimestamp($this->buildPath($path));
144
-	}
139
+    /**
140
+     * {@inheritdoc}
141
+     */
142
+    public function filemtime($path) {
143
+        return $this->flysystem->getTimestamp($this->buildPath($path));
144
+    }
145 145
 
146
-	/**
147
-	 * {@inheritdoc}
148
-	 */
149
-	public function rmdir($path) {
150
-		try {
151
-			return @$this->flysystem->deleteDir($this->buildPath($path));
152
-		} catch (FileNotFoundException $e) {
153
-			return false;
154
-		}
155
-	}
146
+    /**
147
+     * {@inheritdoc}
148
+     */
149
+    public function rmdir($path) {
150
+        try {
151
+            return @$this->flysystem->deleteDir($this->buildPath($path));
152
+        } catch (FileNotFoundException $e) {
153
+            return false;
154
+        }
155
+    }
156 156
 
157
-	/**
158
-	 * {@inheritdoc}
159
-	 */
160
-	public function opendir($path) {
161
-		try {
162
-			$content = $this->flysystem->listContents($this->buildPath($path));
163
-		} catch (FileNotFoundException $e) {
164
-			return false;
165
-		}
166
-		$names = array_map(function ($object) {
167
-			return $object['basename'];
168
-		}, $content);
169
-		return IteratorDirectory::wrap($names);
170
-	}
157
+    /**
158
+     * {@inheritdoc}
159
+     */
160
+    public function opendir($path) {
161
+        try {
162
+            $content = $this->flysystem->listContents($this->buildPath($path));
163
+        } catch (FileNotFoundException $e) {
164
+            return false;
165
+        }
166
+        $names = array_map(function ($object) {
167
+            return $object['basename'];
168
+        }, $content);
169
+        return IteratorDirectory::wrap($names);
170
+    }
171 171
 
172
-	/**
173
-	 * {@inheritdoc}
174
-	 */
175
-	public function fopen($path, $mode) {
176
-		$fullPath = $this->buildPath($path);
177
-		$useExisting = true;
178
-		switch ($mode) {
179
-			case 'r':
180
-			case 'rb':
181
-				try {
182
-					return $this->flysystem->readStream($fullPath);
183
-				} catch (FileNotFoundException $e) {
184
-					return false;
185
-				}
186
-			case 'w':
187
-			case 'w+':
188
-			case 'wb':
189
-			case 'wb+':
190
-				$useExisting = false;
191
-				// no break
192
-			case 'a':
193
-			case 'ab':
194
-			case 'r+':
195
-			case 'a+':
196
-			case 'x':
197
-			case 'x+':
198
-			case 'c':
199
-			case 'c+':
200
-				//emulate these
201
-				if ($useExisting and $this->file_exists($path)) {
202
-					if (!$this->isUpdatable($path)) {
203
-						return false;
204
-					}
205
-					$tmpFile = $this->getCachedFile($path);
206
-				} else {
207
-					if (!$this->isCreatable(dirname($path))) {
208
-						return false;
209
-					}
210
-					$tmpFile = \OCP\Files::tmpFile();
211
-				}
212
-				$source = fopen($tmpFile, $mode);
213
-				return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
214
-					$this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
215
-					unlink($tmpFile);
216
-				});
217
-		}
218
-		return false;
219
-	}
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
+                // no break
192
+            case 'a':
193
+            case 'ab':
194
+            case 'r+':
195
+            case 'a+':
196
+            case 'x':
197
+            case 'x+':
198
+            case 'c':
199
+            case 'c+':
200
+                //emulate these
201
+                if ($useExisting and $this->file_exists($path)) {
202
+                    if (!$this->isUpdatable($path)) {
203
+                        return false;
204
+                    }
205
+                    $tmpFile = $this->getCachedFile($path);
206
+                } else {
207
+                    if (!$this->isCreatable(dirname($path))) {
208
+                        return false;
209
+                    }
210
+                    $tmpFile = \OCP\Files::tmpFile();
211
+                }
212
+                $source = fopen($tmpFile, $mode);
213
+                return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
214
+                    $this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
215
+                    unlink($tmpFile);
216
+                });
217
+        }
218
+        return false;
219
+    }
220 220
 
221
-	/**
222
-	 * {@inheritdoc}
223
-	 */
224
-	public function touch($path, $mtime = null) {
225
-		if ($this->file_exists($path)) {
226
-			return false;
227
-		} else {
228
-			$this->file_put_contents($path, '');
229
-			return true;
230
-		}
231
-	}
221
+    /**
222
+     * {@inheritdoc}
223
+     */
224
+    public function touch($path, $mtime = null) {
225
+        if ($this->file_exists($path)) {
226
+            return false;
227
+        } else {
228
+            $this->file_put_contents($path, '');
229
+            return true;
230
+        }
231
+    }
232 232
 
233
-	/**
234
-	 * {@inheritdoc}
235
-	 */
236
-	public function stat($path) {
237
-		$info = $this->flysystem->getWithMetadata($this->buildPath($path), ['timestamp', 'size']);
238
-		return [
239
-			'mtime' => $info['timestamp'],
240
-			'size' => $info['size']
241
-		];
242
-	}
233
+    /**
234
+     * {@inheritdoc}
235
+     */
236
+    public function stat($path) {
237
+        $info = $this->flysystem->getWithMetadata($this->buildPath($path), ['timestamp', 'size']);
238
+        return [
239
+            'mtime' => $info['timestamp'],
240
+            'size' => $info['size']
241
+        ];
242
+    }
243 243
 
244
-	/**
245
-	 * {@inheritdoc}
246
-	 */
247
-	public function filetype($path) {
248
-		if ($path === '' or $path === '/' or $path === '.') {
249
-			return 'dir';
250
-		}
251
-		try {
252
-			$info = $this->flysystem->getMetadata($this->buildPath($path));
253
-		} catch (FileNotFoundException $e) {
254
-			return false;
255
-		}
256
-		return $info['type'];
257
-	}
244
+    /**
245
+     * {@inheritdoc}
246
+     */
247
+    public function filetype($path) {
248
+        if ($path === '' or $path === '/' or $path === '.') {
249
+            return 'dir';
250
+        }
251
+        try {
252
+            $info = $this->flysystem->getMetadata($this->buildPath($path));
253
+        } catch (FileNotFoundException $e) {
254
+            return false;
255
+        }
256
+        return $info['type'];
257
+    }
258 258
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Quota.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -159,7 +159,7 @@
 block discarded – undo
159 159
 	 * Checks whether the given path is a part file
160 160
 	 *
161 161
 	 * @param string $path Path that may identify a .part file
162
-	 * @return string File path without .part extension
162
+	 * @return boolean File path without .part extension
163 163
 	 * @note this is needed for reusing keys
164 164
 	 */
165 165
 	private function isPartFile($path) {
Please login to merge, or discard this patch.
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -30,172 +30,172 @@
 block discarded – undo
30 30
 
31 31
 class Quota extends Wrapper {
32 32
 
33
-	/**
34
-	 * @var int $quota
35
-	 */
36
-	protected $quota;
37
-
38
-	/**
39
-	 * @var string $sizeRoot
40
-	 */
41
-	protected $sizeRoot;
42
-
43
-	/**
44
-	 * @param array $parameters
45
-	 */
46
-	public function __construct($parameters) {
47
-		$this->storage = $parameters['storage'];
48
-		$this->quota = $parameters['quota'];
49
-		$this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
50
-	}
51
-
52
-	/**
53
-	 * @return int quota value
54
-	 */
55
-	public function getQuota() {
56
-		return $this->quota;
57
-	}
58
-
59
-	/**
60
-	 * @param string $path
61
-	 * @param \OC\Files\Storage\Storage $storage
62
-	 */
63
-	protected function getSize($path, $storage = null) {
64
-		if (is_null($storage)) {
65
-			$cache = $this->getCache();
66
-		} else {
67
-			$cache = $storage->getCache();
68
-		}
69
-		$data = $cache->get($path);
70
-		if ($data instanceof ICacheEntry and isset($data['size'])) {
71
-			return $data['size'];
72
-		} else {
73
-			return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
74
-		}
75
-	}
76
-
77
-	/**
78
-	 * Get free space as limited by the quota
79
-	 *
80
-	 * @param string $path
81
-	 * @return int
82
-	 */
83
-	public function free_space($path) {
84
-		if ($this->quota < 0) {
85
-			return $this->storage->free_space($path);
86
-		} else {
87
-			$used = $this->getSize($this->sizeRoot);
88
-			if ($used < 0) {
89
-				return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
90
-			} else {
91
-				$free = $this->storage->free_space($path);
92
-				$quotaFree = max($this->quota - $used, 0);
93
-				// if free space is known
94
-				if ($free >= 0) {
95
-					$free = min($free, $quotaFree);
96
-				} else {
97
-					$free = $quotaFree;
98
-				}
99
-				return $free;
100
-			}
101
-		}
102
-	}
103
-
104
-	/**
105
-	 * see http://php.net/manual/en/function.file_put_contents.php
106
-	 *
107
-	 * @param string $path
108
-	 * @param string $data
109
-	 * @return bool
110
-	 */
111
-	public function file_put_contents($path, $data) {
112
-		$free = $this->free_space('');
113
-		if ($free < 0 or strlen($data) < $free) {
114
-			return $this->storage->file_put_contents($path, $data);
115
-		} else {
116
-			return false;
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * see http://php.net/manual/en/function.copy.php
122
-	 *
123
-	 * @param string $source
124
-	 * @param string $target
125
-	 * @return bool
126
-	 */
127
-	public function copy($source, $target) {
128
-		$free = $this->free_space('');
129
-		if ($free < 0 or $this->getSize($source) < $free) {
130
-			return $this->storage->copy($source, $target);
131
-		} else {
132
-			return false;
133
-		}
134
-	}
135
-
136
-	/**
137
-	 * see http://php.net/manual/en/function.fopen.php
138
-	 *
139
-	 * @param string $path
140
-	 * @param string $mode
141
-	 * @return resource
142
-	 */
143
-	public function fopen($path, $mode) {
144
-		$source = $this->storage->fopen($path, $mode);
145
-
146
-		// don't apply quota for part files
147
-		if (!$this->isPartFile($path)) {
148
-			$free = $this->free_space('');
149
-			if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
150
-				// only apply quota for files, not metadata, trash or others
151
-				if (strpos(ltrim($path, '/'), 'files/') === 0) {
152
-					return \OC\Files\Stream\Quota::wrap($source, $free);
153
-				}
154
-			}
155
-		}
156
-		return $source;
157
-	}
158
-
159
-	/**
160
-	 * Checks whether the given path is a part file
161
-	 *
162
-	 * @param string $path Path that may identify a .part file
163
-	 * @return string File path without .part extension
164
-	 * @note this is needed for reusing keys
165
-	 */
166
-	private function isPartFile($path) {
167
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
168
-
169
-		return ($extension === 'part');
170
-	}
171
-
172
-	/**
173
-	 * @param \OCP\Files\Storage $sourceStorage
174
-	 * @param string $sourceInternalPath
175
-	 * @param string $targetInternalPath
176
-	 * @return bool
177
-	 */
178
-	public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
179
-		$free = $this->free_space('');
180
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
181
-			return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
182
-		} else {
183
-			return false;
184
-		}
185
-	}
186
-
187
-	/**
188
-	 * @param \OCP\Files\Storage $sourceStorage
189
-	 * @param string $sourceInternalPath
190
-	 * @param string $targetInternalPath
191
-	 * @return bool
192
-	 */
193
-	public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
194
-		$free = $this->free_space('');
195
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
196
-			return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
197
-		} else {
198
-			return false;
199
-		}
200
-	}
33
+    /**
34
+     * @var int $quota
35
+     */
36
+    protected $quota;
37
+
38
+    /**
39
+     * @var string $sizeRoot
40
+     */
41
+    protected $sizeRoot;
42
+
43
+    /**
44
+     * @param array $parameters
45
+     */
46
+    public function __construct($parameters) {
47
+        $this->storage = $parameters['storage'];
48
+        $this->quota = $parameters['quota'];
49
+        $this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
50
+    }
51
+
52
+    /**
53
+     * @return int quota value
54
+     */
55
+    public function getQuota() {
56
+        return $this->quota;
57
+    }
58
+
59
+    /**
60
+     * @param string $path
61
+     * @param \OC\Files\Storage\Storage $storage
62
+     */
63
+    protected function getSize($path, $storage = null) {
64
+        if (is_null($storage)) {
65
+            $cache = $this->getCache();
66
+        } else {
67
+            $cache = $storage->getCache();
68
+        }
69
+        $data = $cache->get($path);
70
+        if ($data instanceof ICacheEntry and isset($data['size'])) {
71
+            return $data['size'];
72
+        } else {
73
+            return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
74
+        }
75
+    }
76
+
77
+    /**
78
+     * Get free space as limited by the quota
79
+     *
80
+     * @param string $path
81
+     * @return int
82
+     */
83
+    public function free_space($path) {
84
+        if ($this->quota < 0) {
85
+            return $this->storage->free_space($path);
86
+        } else {
87
+            $used = $this->getSize($this->sizeRoot);
88
+            if ($used < 0) {
89
+                return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
90
+            } else {
91
+                $free = $this->storage->free_space($path);
92
+                $quotaFree = max($this->quota - $used, 0);
93
+                // if free space is known
94
+                if ($free >= 0) {
95
+                    $free = min($free, $quotaFree);
96
+                } else {
97
+                    $free = $quotaFree;
98
+                }
99
+                return $free;
100
+            }
101
+        }
102
+    }
103
+
104
+    /**
105
+     * see http://php.net/manual/en/function.file_put_contents.php
106
+     *
107
+     * @param string $path
108
+     * @param string $data
109
+     * @return bool
110
+     */
111
+    public function file_put_contents($path, $data) {
112
+        $free = $this->free_space('');
113
+        if ($free < 0 or strlen($data) < $free) {
114
+            return $this->storage->file_put_contents($path, $data);
115
+        } else {
116
+            return false;
117
+        }
118
+    }
119
+
120
+    /**
121
+     * see http://php.net/manual/en/function.copy.php
122
+     *
123
+     * @param string $source
124
+     * @param string $target
125
+     * @return bool
126
+     */
127
+    public function copy($source, $target) {
128
+        $free = $this->free_space('');
129
+        if ($free < 0 or $this->getSize($source) < $free) {
130
+            return $this->storage->copy($source, $target);
131
+        } else {
132
+            return false;
133
+        }
134
+    }
135
+
136
+    /**
137
+     * see http://php.net/manual/en/function.fopen.php
138
+     *
139
+     * @param string $path
140
+     * @param string $mode
141
+     * @return resource
142
+     */
143
+    public function fopen($path, $mode) {
144
+        $source = $this->storage->fopen($path, $mode);
145
+
146
+        // don't apply quota for part files
147
+        if (!$this->isPartFile($path)) {
148
+            $free = $this->free_space('');
149
+            if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
150
+                // only apply quota for files, not metadata, trash or others
151
+                if (strpos(ltrim($path, '/'), 'files/') === 0) {
152
+                    return \OC\Files\Stream\Quota::wrap($source, $free);
153
+                }
154
+            }
155
+        }
156
+        return $source;
157
+    }
158
+
159
+    /**
160
+     * Checks whether the given path is a part file
161
+     *
162
+     * @param string $path Path that may identify a .part file
163
+     * @return string File path without .part extension
164
+     * @note this is needed for reusing keys
165
+     */
166
+    private function isPartFile($path) {
167
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
168
+
169
+        return ($extension === 'part');
170
+    }
171
+
172
+    /**
173
+     * @param \OCP\Files\Storage $sourceStorage
174
+     * @param string $sourceInternalPath
175
+     * @param string $targetInternalPath
176
+     * @return bool
177
+     */
178
+    public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
179
+        $free = $this->free_space('');
180
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
181
+            return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
182
+        } else {
183
+            return false;
184
+        }
185
+    }
186
+
187
+    /**
188
+     * @param \OCP\Files\Storage $sourceStorage
189
+     * @param string $sourceInternalPath
190
+     * @param string $targetInternalPath
191
+     * @return bool
192
+     */
193
+    public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
194
+        $free = $this->free_space('');
195
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
196
+            return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
197
+        } else {
198
+            return false;
199
+        }
200
+    }
201 201
 }
Please login to merge, or discard this patch.
lib/private/legacy/eventsource.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@
 block discarded – undo
88 88
 	 * send a message to the client
89 89
 	 *
90 90
 	 * @param string $type
91
-	 * @param mixed $data
91
+	 * @param string $data
92 92
 	 *
93 93
 	 * @throws \BadMethodCallException
94 94
 	 * if only one parameter is given, a typeless message will be send with that parameter as data
Please login to merge, or discard this patch.
Indentation   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -33,98 +33,98 @@
 block discarded – undo
33 33
  * use server side events with caution, to many open requests can hang the server
34 34
  */
35 35
 class OC_EventSource implements \OCP\IEventSource {
36
-	/**
37
-	 * @var bool
38
-	 */
39
-	private $fallback;
36
+    /**
37
+     * @var bool
38
+     */
39
+    private $fallback;
40 40
 
41
-	/**
42
-	 * @var int
43
-	 */
44
-	private $fallBackId = 0;
41
+    /**
42
+     * @var int
43
+     */
44
+    private $fallBackId = 0;
45 45
 
46
-	/**
47
-	 * @var bool
48
-	 */
49
-	private $started = false;
46
+    /**
47
+     * @var bool
48
+     */
49
+    private $started = false;
50 50
 
51
-	protected function init() {
52
-		if ($this->started) {
53
-			return;
54
-		}
55
-		$this->started = true;
51
+    protected function init() {
52
+        if ($this->started) {
53
+            return;
54
+        }
55
+        $this->started = true;
56 56
 
57
-		// prevent php output buffering, caching and nginx buffering
58
-		OC_Util::obEnd();
59
-		header('Cache-Control: no-cache');
60
-		header('X-Accel-Buffering: no');
61
-		$this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62
-		if ($this->fallback) {
63
-			$this->fallBackId = (int)$_GET['fallback_id'];
64
-			/**
65
-			 * FIXME: The default content-security-policy of ownCloud forbids inline
66
-			 * JavaScript for security reasons. IE starting on Windows 10 will
67
-			 * however also obey the CSP which will break the event source fallback.
68
-			 *
69
-			 * As a workaround thus we set a custom policy which allows the execution
70
-			 * of inline JavaScript.
71
-			 *
72
-			 * @link https://github.com/owncloud/core/issues/14286
73
-			 */
74
-			header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75
-			header("Content-Type: text/html");
76
-			echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
77
-		} else {
78
-			header("Content-Type: text/event-stream");
79
-		}
80
-		if (!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81
-			header('Location: '.\OC::$WEBROOT);
82
-			exit();
83
-		}
84
-		if (!(\OC::$server->getRequest()->passesCSRFCheck())) {
85
-			$this->send('error', 'Possible CSRF attack. Connection will be closed.');
86
-			$this->close();
87
-			exit();
88
-		}
89
-		flush();
90
-	}
57
+        // prevent php output buffering, caching and nginx buffering
58
+        OC_Util::obEnd();
59
+        header('Cache-Control: no-cache');
60
+        header('X-Accel-Buffering: no');
61
+        $this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62
+        if ($this->fallback) {
63
+            $this->fallBackId = (int)$_GET['fallback_id'];
64
+            /**
65
+             * FIXME: The default content-security-policy of ownCloud forbids inline
66
+             * JavaScript for security reasons. IE starting on Windows 10 will
67
+             * however also obey the CSP which will break the event source fallback.
68
+             *
69
+             * As a workaround thus we set a custom policy which allows the execution
70
+             * of inline JavaScript.
71
+             *
72
+             * @link https://github.com/owncloud/core/issues/14286
73
+             */
74
+            header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75
+            header("Content-Type: text/html");
76
+            echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
77
+        } else {
78
+            header("Content-Type: text/event-stream");
79
+        }
80
+        if (!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81
+            header('Location: '.\OC::$WEBROOT);
82
+            exit();
83
+        }
84
+        if (!(\OC::$server->getRequest()->passesCSRFCheck())) {
85
+            $this->send('error', 'Possible CSRF attack. Connection will be closed.');
86
+            $this->close();
87
+            exit();
88
+        }
89
+        flush();
90
+    }
91 91
 
92
-	/**
93
-	 * send a message to the client
94
-	 *
95
-	 * @param string $type
96
-	 * @param mixed $data
97
-	 *
98
-	 * @throws \BadMethodCallException
99
-	 * if only one parameter is given, a typeless message will be send with that parameter as data
100
-	 */
101
-	public function send($type, $data = null) {
102
-		if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
-			throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
104
-		}
105
-		$this->init();
106
-		if (is_null($data)) {
107
-			$data = $type;
108
-			$type = null;
109
-		}
110
-		if ($this->fallback) {
111
-			$response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
-				. $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
113
-			echo $response;
114
-		} else {
115
-			if ($type) {
116
-				echo 'event: ' . $type . PHP_EOL;
117
-			}
118
-			echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
119
-		}
120
-		echo PHP_EOL;
121
-		flush();
122
-	}
92
+    /**
93
+     * send a message to the client
94
+     *
95
+     * @param string $type
96
+     * @param mixed $data
97
+     *
98
+     * @throws \BadMethodCallException
99
+     * if only one parameter is given, a typeless message will be send with that parameter as data
100
+     */
101
+    public function send($type, $data = null) {
102
+        if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
+            throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
104
+        }
105
+        $this->init();
106
+        if (is_null($data)) {
107
+            $data = $type;
108
+            $type = null;
109
+        }
110
+        if ($this->fallback) {
111
+            $response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
+                . $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
113
+            echo $response;
114
+        } else {
115
+            if ($type) {
116
+                echo 'event: ' . $type . PHP_EOL;
117
+            }
118
+            echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
119
+        }
120
+        echo PHP_EOL;
121
+        flush();
122
+    }
123 123
 
124
-	/**
125
-	 * close the connection of the event source
126
-	 */
127
-	public function close() {
128
-		$this->send('__internal__', 'close'); //server side closing can be an issue, let the client do it
129
-	}
124
+    /**
125
+     * close the connection of the event source
126
+     */
127
+    public function close() {
128
+        $this->send('__internal__', 'close'); //server side closing can be an issue, let the client do it
129
+    }
130 130
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 		header('X-Accel-Buffering: no');
61 61
 		$this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62 62
 		if ($this->fallback) {
63
-			$this->fallBackId = (int)$_GET['fallback_id'];
63
+			$this->fallBackId = (int) $_GET['fallback_id'];
64 64
 			/**
65 65
 			 * FIXME: The default content-security-policy of ownCloud forbids inline
66 66
 			 * JavaScript for security reasons. IE starting on Windows 10 will
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 			 */
74 74
 			header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75 75
 			header("Content-Type: text/html");
76
-			echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
76
+			echo str_repeat('<span></span>'.PHP_EOL, 10); //dummy data to keep IE happy
77 77
 		} else {
78 78
 			header("Content-Type: text/event-stream");
79 79
 		}
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	 */
101 101
 	public function send($type, $data = null) {
102 102
 		if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
-			throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
103
+			throw new BadMethodCallException('Type needs to be alphanumeric ('.$type.')');
104 104
 		}
105 105
 		$this->init();
106 106
 		if (is_null($data)) {
@@ -109,13 +109,13 @@  discard block
 block discarded – undo
109 109
 		}
110 110
 		if ($this->fallback) {
111 111
 			$response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
-				. $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
112
+				. $this->fallBackId.',"'.$type.'",'.OCP\JSON::encode($data).')</script>'.PHP_EOL;
113 113
 			echo $response;
114 114
 		} else {
115 115
 			if ($type) {
116
-				echo 'event: ' . $type . PHP_EOL;
116
+				echo 'event: '.$type.PHP_EOL;
117 117
 			}
118
-			echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
118
+			echo 'data: '.OCP\JSON::encode($data).PHP_EOL;
119 119
 		}
120 120
 		echo PHP_EOL;
121 121
 		flush();
Please login to merge, or discard this patch.