Completed
Push — stable12 ( b91394...cede17 )
by
unknown
30:59 queued 20:45
created
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   +377 added lines, -377 removed lines patch added patch discarded remove patch
@@ -41,381 +41,381 @@
 block discarded – undo
41 41
 use OCP\PreConditionNotMetException;
42 42
 
43 43
 class Connection extends \Doctrine\DBAL\Connection implements IDBConnection {
44
-	/**
45
-	 * @var string $tablePrefix
46
-	 */
47
-	protected $tablePrefix;
48
-
49
-	/**
50
-	 * @var \OC\DB\Adapter $adapter
51
-	 */
52
-	protected $adapter;
53
-
54
-	protected $lockedTable = null;
55
-
56
-	public function connect() {
57
-		try {
58
-			return parent::connect();
59
-		} catch (DBALException $e) {
60
-			// throw a new exception to prevent leaking info from the stacktrace
61
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
62
-		}
63
-	}
64
-
65
-	/**
66
-	 * Returns a QueryBuilder for the connection.
67
-	 *
68
-	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
69
-	 */
70
-	public function getQueryBuilder() {
71
-		return new QueryBuilder(
72
-			$this,
73
-			\OC::$server->getSystemConfig(),
74
-			\OC::$server->getLogger()
75
-		);
76
-	}
77
-
78
-	/**
79
-	 * Gets the QueryBuilder for the connection.
80
-	 *
81
-	 * @return \Doctrine\DBAL\Query\QueryBuilder
82
-	 * @deprecated please use $this->getQueryBuilder() instead
83
-	 */
84
-	public function createQueryBuilder() {
85
-		$backtrace = $this->getCallerBacktrace();
86
-		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
87
-		return parent::createQueryBuilder();
88
-	}
89
-
90
-	/**
91
-	 * Gets the ExpressionBuilder for the connection.
92
-	 *
93
-	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
94
-	 * @deprecated please use $this->getQueryBuilder()->expr() instead
95
-	 */
96
-	public function getExpressionBuilder() {
97
-		$backtrace = $this->getCallerBacktrace();
98
-		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
99
-		return parent::getExpressionBuilder();
100
-	}
101
-
102
-	/**
103
-	 * Get the file and line that called the method where `getCallerBacktrace()` was used
104
-	 *
105
-	 * @return string
106
-	 */
107
-	protected function getCallerBacktrace() {
108
-		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
109
-
110
-		// 0 is the method where we use `getCallerBacktrace`
111
-		// 1 is the target method which uses the method we want to log
112
-		if (isset($traces[1])) {
113
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
114
-		}
115
-
116
-		return '';
117
-	}
118
-
119
-	/**
120
-	 * @return string
121
-	 */
122
-	public function getPrefix() {
123
-		return $this->tablePrefix;
124
-	}
125
-
126
-	/**
127
-	 * Initializes a new instance of the Connection class.
128
-	 *
129
-	 * @param array $params  The connection parameters.
130
-	 * @param \Doctrine\DBAL\Driver $driver
131
-	 * @param \Doctrine\DBAL\Configuration $config
132
-	 * @param \Doctrine\Common\EventManager $eventManager
133
-	 * @throws \Exception
134
-	 */
135
-	public function __construct(array $params, Driver $driver, Configuration $config = null,
136
-		EventManager $eventManager = null)
137
-	{
138
-		if (!isset($params['adapter'])) {
139
-			throw new \Exception('adapter not set');
140
-		}
141
-		if (!isset($params['tablePrefix'])) {
142
-			throw new \Exception('tablePrefix not set');
143
-		}
144
-		parent::__construct($params, $driver, $config, $eventManager);
145
-		$this->adapter = new $params['adapter']($this);
146
-		$this->tablePrefix = $params['tablePrefix'];
147
-
148
-		parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
149
-	}
150
-
151
-	/**
152
-	 * Prepares an SQL statement.
153
-	 *
154
-	 * @param string $statement The SQL statement to prepare.
155
-	 * @param int $limit
156
-	 * @param int $offset
157
-	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
158
-	 */
159
-	public function prepare( $statement, $limit=null, $offset=null ) {
160
-		if ($limit === -1) {
161
-			$limit = null;
162
-		}
163
-		if (!is_null($limit)) {
164
-			$platform = $this->getDatabasePlatform();
165
-			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
166
-		}
167
-		$statement = $this->replaceTablePrefix($statement);
168
-		$statement = $this->adapter->fixupStatement($statement);
169
-
170
-		return parent::prepare($statement);
171
-	}
172
-
173
-	/**
174
-	 * Executes an, optionally parametrized, SQL query.
175
-	 *
176
-	 * If the query is parametrized, a prepared statement is used.
177
-	 * If an SQLLogger is configured, the execution is logged.
178
-	 *
179
-	 * @param string                                      $query  The SQL query to execute.
180
-	 * @param array                                       $params The parameters to bind to the query, if any.
181
-	 * @param array                                       $types  The types the previous parameters are in.
182
-	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
183
-	 *
184
-	 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
185
-	 *
186
-	 * @throws \Doctrine\DBAL\DBALException
187
-	 */
188
-	public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
189
-	{
190
-		$query = $this->replaceTablePrefix($query);
191
-		$query = $this->adapter->fixupStatement($query);
192
-		return parent::executeQuery($query, $params, $types, $qcp);
193
-	}
194
-
195
-	/**
196
-	 * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
197
-	 * and returns the number of affected rows.
198
-	 *
199
-	 * This method supports PDO binding types as well as DBAL mapping types.
200
-	 *
201
-	 * @param string $query  The SQL query.
202
-	 * @param array  $params The query parameters.
203
-	 * @param array  $types  The parameter types.
204
-	 *
205
-	 * @return integer The number of affected rows.
206
-	 *
207
-	 * @throws \Doctrine\DBAL\DBALException
208
-	 */
209
-	public function executeUpdate($query, array $params = array(), array $types = array())
210
-	{
211
-		$query = $this->replaceTablePrefix($query);
212
-		$query = $this->adapter->fixupStatement($query);
213
-		return parent::executeUpdate($query, $params, $types);
214
-	}
215
-
216
-	/**
217
-	 * Returns the ID of the last inserted row, or the last value from a sequence object,
218
-	 * depending on the underlying driver.
219
-	 *
220
-	 * Note: This method may not return a meaningful or consistent result across different drivers,
221
-	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
222
-	 * columns or sequences.
223
-	 *
224
-	 * @param string $seqName Name of the sequence object from which the ID should be returned.
225
-	 * @return string A string representation of the last inserted ID.
226
-	 */
227
-	public function lastInsertId($seqName = null) {
228
-		if ($seqName) {
229
-			$seqName = $this->replaceTablePrefix($seqName);
230
-		}
231
-		return $this->adapter->lastInsertId($seqName);
232
-	}
233
-
234
-	// internal use
235
-	public function realLastInsertId($seqName = null) {
236
-		return parent::lastInsertId($seqName);
237
-	}
238
-
239
-	/**
240
-	 * Insert a row if the matching row does not exists.
241
-	 *
242
-	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
243
-	 * @param array $input data that should be inserted into the table  (column name => value)
244
-	 * @param array|null $compare List of values that should be checked for "if not exists"
245
-	 *				If this is null or an empty array, all keys of $input will be compared
246
-	 *				Please note: text fields (clob) must not be used in the compare array
247
-	 * @return int number of inserted rows
248
-	 * @throws \Doctrine\DBAL\DBALException
249
-	 */
250
-	public function insertIfNotExist($table, $input, array $compare = null) {
251
-		return $this->adapter->insertIfNotExist($table, $input, $compare);
252
-	}
253
-
254
-	private function getType($value) {
255
-		if (is_bool($value)) {
256
-			return IQueryBuilder::PARAM_BOOL;
257
-		} else if (is_int($value)) {
258
-			return IQueryBuilder::PARAM_INT;
259
-		} else {
260
-			return IQueryBuilder::PARAM_STR;
261
-		}
262
-	}
263
-
264
-	/**
265
-	 * Insert or update a row value
266
-	 *
267
-	 * @param string $table
268
-	 * @param array $keys (column name => value)
269
-	 * @param array $values (column name => value)
270
-	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
271
-	 * @return int number of new rows
272
-	 * @throws \Doctrine\DBAL\DBALException
273
-	 * @throws PreConditionNotMetException
274
-	 */
275
-	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
276
-		try {
277
-			$insertQb = $this->getQueryBuilder();
278
-			$insertQb->insert($table)
279
-				->values(
280
-					array_map(function($value) use ($insertQb) {
281
-						return $insertQb->createNamedParameter($value, $this->getType($value));
282
-					}, array_merge($keys, $values))
283
-				);
284
-			return $insertQb->execute();
285
-		} catch (ConstraintViolationException $e) {
286
-			// value already exists, try update
287
-			$updateQb = $this->getQueryBuilder();
288
-			$updateQb->update($table);
289
-			foreach ($values as $name => $value) {
290
-				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
291
-			}
292
-			$where = $updateQb->expr()->andX();
293
-			$whereValues = array_merge($keys, $updatePreconditionValues);
294
-			foreach ($whereValues as $name => $value) {
295
-				$where->add($updateQb->expr()->eq(
296
-					$name,
297
-					$updateQb->createNamedParameter($value, $this->getType($value)),
298
-					$this->getType($value)
299
-				));
300
-			}
301
-			$updateQb->where($where);
302
-			$affected = $updateQb->execute();
303
-
304
-			if ($affected === 0 && !empty($updatePreconditionValues)) {
305
-				throw new PreConditionNotMetException();
306
-			}
307
-
308
-			return 0;
309
-		}
310
-	}
311
-
312
-	/**
313
-	 * Create an exclusive read+write lock on a table
314
-	 *
315
-	 * @param string $tableName
316
-	 * @throws \BadMethodCallException When trying to acquire a second lock
317
-	 * @since 9.1.0
318
-	 */
319
-	public function lockTable($tableName) {
320
-		if ($this->lockedTable !== null) {
321
-			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
322
-		}
323
-
324
-		$tableName = $this->tablePrefix . $tableName;
325
-		$this->lockedTable = $tableName;
326
-		$this->adapter->lockTable($tableName);
327
-	}
328
-
329
-	/**
330
-	 * Release a previous acquired lock again
331
-	 *
332
-	 * @since 9.1.0
333
-	 */
334
-	public function unlockTable() {
335
-		$this->adapter->unlockTable();
336
-		$this->lockedTable = null;
337
-	}
338
-
339
-	/**
340
-	 * returns the error code and message as a string for logging
341
-	 * works with DoctrineException
342
-	 * @return string
343
-	 */
344
-	public function getError() {
345
-		$msg = $this->errorCode() . ': ';
346
-		$errorInfo = $this->errorInfo();
347
-		if (is_array($errorInfo)) {
348
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
349
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
350
-			$msg .= 'Driver Message = '.$errorInfo[2];
351
-		}
352
-		return $msg;
353
-	}
354
-
355
-	/**
356
-	 * Drop a table from the database if it exists
357
-	 *
358
-	 * @param string $table table name without the prefix
359
-	 */
360
-	public function dropTable($table) {
361
-		$table = $this->tablePrefix . trim($table);
362
-		$schema = $this->getSchemaManager();
363
-		if($schema->tablesExist(array($table))) {
364
-			$schema->dropTable($table);
365
-		}
366
-	}
367
-
368
-	/**
369
-	 * Check if a table exists
370
-	 *
371
-	 * @param string $table table name without the prefix
372
-	 * @return bool
373
-	 */
374
-	public function tableExists($table){
375
-		$table = $this->tablePrefix . trim($table);
376
-		$schema = $this->getSchemaManager();
377
-		return $schema->tablesExist(array($table));
378
-	}
379
-
380
-	// internal use
381
-	/**
382
-	 * @param string $statement
383
-	 * @return string
384
-	 */
385
-	protected function replaceTablePrefix($statement) {
386
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
387
-	}
388
-
389
-	/**
390
-	 * Check if a transaction is active
391
-	 *
392
-	 * @return bool
393
-	 * @since 8.2.0
394
-	 */
395
-	public function inTransaction() {
396
-		return $this->getTransactionNestingLevel() > 0;
397
-	}
398
-
399
-	/**
400
-	 * Espace a parameter to be used in a LIKE query
401
-	 *
402
-	 * @param string $param
403
-	 * @return string
404
-	 */
405
-	public function escapeLikeParameter($param) {
406
-		return addcslashes($param, '\\_%');
407
-	}
408
-
409
-	/**
410
-	 * Check whether or not the current database support 4byte wide unicode
411
-	 *
412
-	 * @return bool
413
-	 * @since 11.0.0
414
-	 */
415
-	public function supports4ByteText() {
416
-		if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
417
-			return true;
418
-		}
419
-		return $this->getParams()['charset'] === 'utf8mb4';
420
-	}
44
+    /**
45
+     * @var string $tablePrefix
46
+     */
47
+    protected $tablePrefix;
48
+
49
+    /**
50
+     * @var \OC\DB\Adapter $adapter
51
+     */
52
+    protected $adapter;
53
+
54
+    protected $lockedTable = null;
55
+
56
+    public function connect() {
57
+        try {
58
+            return parent::connect();
59
+        } catch (DBALException $e) {
60
+            // throw a new exception to prevent leaking info from the stacktrace
61
+            throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
62
+        }
63
+    }
64
+
65
+    /**
66
+     * Returns a QueryBuilder for the connection.
67
+     *
68
+     * @return \OCP\DB\QueryBuilder\IQueryBuilder
69
+     */
70
+    public function getQueryBuilder() {
71
+        return new QueryBuilder(
72
+            $this,
73
+            \OC::$server->getSystemConfig(),
74
+            \OC::$server->getLogger()
75
+        );
76
+    }
77
+
78
+    /**
79
+     * Gets the QueryBuilder for the connection.
80
+     *
81
+     * @return \Doctrine\DBAL\Query\QueryBuilder
82
+     * @deprecated please use $this->getQueryBuilder() instead
83
+     */
84
+    public function createQueryBuilder() {
85
+        $backtrace = $this->getCallerBacktrace();
86
+        \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
87
+        return parent::createQueryBuilder();
88
+    }
89
+
90
+    /**
91
+     * Gets the ExpressionBuilder for the connection.
92
+     *
93
+     * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
94
+     * @deprecated please use $this->getQueryBuilder()->expr() instead
95
+     */
96
+    public function getExpressionBuilder() {
97
+        $backtrace = $this->getCallerBacktrace();
98
+        \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
99
+        return parent::getExpressionBuilder();
100
+    }
101
+
102
+    /**
103
+     * Get the file and line that called the method where `getCallerBacktrace()` was used
104
+     *
105
+     * @return string
106
+     */
107
+    protected function getCallerBacktrace() {
108
+        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
109
+
110
+        // 0 is the method where we use `getCallerBacktrace`
111
+        // 1 is the target method which uses the method we want to log
112
+        if (isset($traces[1])) {
113
+            return $traces[1]['file'] . ':' . $traces[1]['line'];
114
+        }
115
+
116
+        return '';
117
+    }
118
+
119
+    /**
120
+     * @return string
121
+     */
122
+    public function getPrefix() {
123
+        return $this->tablePrefix;
124
+    }
125
+
126
+    /**
127
+     * Initializes a new instance of the Connection class.
128
+     *
129
+     * @param array $params  The connection parameters.
130
+     * @param \Doctrine\DBAL\Driver $driver
131
+     * @param \Doctrine\DBAL\Configuration $config
132
+     * @param \Doctrine\Common\EventManager $eventManager
133
+     * @throws \Exception
134
+     */
135
+    public function __construct(array $params, Driver $driver, Configuration $config = null,
136
+        EventManager $eventManager = null)
137
+    {
138
+        if (!isset($params['adapter'])) {
139
+            throw new \Exception('adapter not set');
140
+        }
141
+        if (!isset($params['tablePrefix'])) {
142
+            throw new \Exception('tablePrefix not set');
143
+        }
144
+        parent::__construct($params, $driver, $config, $eventManager);
145
+        $this->adapter = new $params['adapter']($this);
146
+        $this->tablePrefix = $params['tablePrefix'];
147
+
148
+        parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
149
+    }
150
+
151
+    /**
152
+     * Prepares an SQL statement.
153
+     *
154
+     * @param string $statement The SQL statement to prepare.
155
+     * @param int $limit
156
+     * @param int $offset
157
+     * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
158
+     */
159
+    public function prepare( $statement, $limit=null, $offset=null ) {
160
+        if ($limit === -1) {
161
+            $limit = null;
162
+        }
163
+        if (!is_null($limit)) {
164
+            $platform = $this->getDatabasePlatform();
165
+            $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
166
+        }
167
+        $statement = $this->replaceTablePrefix($statement);
168
+        $statement = $this->adapter->fixupStatement($statement);
169
+
170
+        return parent::prepare($statement);
171
+    }
172
+
173
+    /**
174
+     * Executes an, optionally parametrized, SQL query.
175
+     *
176
+     * If the query is parametrized, a prepared statement is used.
177
+     * If an SQLLogger is configured, the execution is logged.
178
+     *
179
+     * @param string                                      $query  The SQL query to execute.
180
+     * @param array                                       $params The parameters to bind to the query, if any.
181
+     * @param array                                       $types  The types the previous parameters are in.
182
+     * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
183
+     *
184
+     * @return \Doctrine\DBAL\Driver\Statement The executed statement.
185
+     *
186
+     * @throws \Doctrine\DBAL\DBALException
187
+     */
188
+    public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
189
+    {
190
+        $query = $this->replaceTablePrefix($query);
191
+        $query = $this->adapter->fixupStatement($query);
192
+        return parent::executeQuery($query, $params, $types, $qcp);
193
+    }
194
+
195
+    /**
196
+     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
197
+     * and returns the number of affected rows.
198
+     *
199
+     * This method supports PDO binding types as well as DBAL mapping types.
200
+     *
201
+     * @param string $query  The SQL query.
202
+     * @param array  $params The query parameters.
203
+     * @param array  $types  The parameter types.
204
+     *
205
+     * @return integer The number of affected rows.
206
+     *
207
+     * @throws \Doctrine\DBAL\DBALException
208
+     */
209
+    public function executeUpdate($query, array $params = array(), array $types = array())
210
+    {
211
+        $query = $this->replaceTablePrefix($query);
212
+        $query = $this->adapter->fixupStatement($query);
213
+        return parent::executeUpdate($query, $params, $types);
214
+    }
215
+
216
+    /**
217
+     * Returns the ID of the last inserted row, or the last value from a sequence object,
218
+     * depending on the underlying driver.
219
+     *
220
+     * Note: This method may not return a meaningful or consistent result across different drivers,
221
+     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
222
+     * columns or sequences.
223
+     *
224
+     * @param string $seqName Name of the sequence object from which the ID should be returned.
225
+     * @return string A string representation of the last inserted ID.
226
+     */
227
+    public function lastInsertId($seqName = null) {
228
+        if ($seqName) {
229
+            $seqName = $this->replaceTablePrefix($seqName);
230
+        }
231
+        return $this->adapter->lastInsertId($seqName);
232
+    }
233
+
234
+    // internal use
235
+    public function realLastInsertId($seqName = null) {
236
+        return parent::lastInsertId($seqName);
237
+    }
238
+
239
+    /**
240
+     * Insert a row if the matching row does not exists.
241
+     *
242
+     * @param string $table The table name (will replace *PREFIX* with the actual prefix)
243
+     * @param array $input data that should be inserted into the table  (column name => value)
244
+     * @param array|null $compare List of values that should be checked for "if not exists"
245
+     *				If this is null or an empty array, all keys of $input will be compared
246
+     *				Please note: text fields (clob) must not be used in the compare array
247
+     * @return int number of inserted rows
248
+     * @throws \Doctrine\DBAL\DBALException
249
+     */
250
+    public function insertIfNotExist($table, $input, array $compare = null) {
251
+        return $this->adapter->insertIfNotExist($table, $input, $compare);
252
+    }
253
+
254
+    private function getType($value) {
255
+        if (is_bool($value)) {
256
+            return IQueryBuilder::PARAM_BOOL;
257
+        } else if (is_int($value)) {
258
+            return IQueryBuilder::PARAM_INT;
259
+        } else {
260
+            return IQueryBuilder::PARAM_STR;
261
+        }
262
+    }
263
+
264
+    /**
265
+     * Insert or update a row value
266
+     *
267
+     * @param string $table
268
+     * @param array $keys (column name => value)
269
+     * @param array $values (column name => value)
270
+     * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
271
+     * @return int number of new rows
272
+     * @throws \Doctrine\DBAL\DBALException
273
+     * @throws PreConditionNotMetException
274
+     */
275
+    public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
276
+        try {
277
+            $insertQb = $this->getQueryBuilder();
278
+            $insertQb->insert($table)
279
+                ->values(
280
+                    array_map(function($value) use ($insertQb) {
281
+                        return $insertQb->createNamedParameter($value, $this->getType($value));
282
+                    }, array_merge($keys, $values))
283
+                );
284
+            return $insertQb->execute();
285
+        } catch (ConstraintViolationException $e) {
286
+            // value already exists, try update
287
+            $updateQb = $this->getQueryBuilder();
288
+            $updateQb->update($table);
289
+            foreach ($values as $name => $value) {
290
+                $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
291
+            }
292
+            $where = $updateQb->expr()->andX();
293
+            $whereValues = array_merge($keys, $updatePreconditionValues);
294
+            foreach ($whereValues as $name => $value) {
295
+                $where->add($updateQb->expr()->eq(
296
+                    $name,
297
+                    $updateQb->createNamedParameter($value, $this->getType($value)),
298
+                    $this->getType($value)
299
+                ));
300
+            }
301
+            $updateQb->where($where);
302
+            $affected = $updateQb->execute();
303
+
304
+            if ($affected === 0 && !empty($updatePreconditionValues)) {
305
+                throw new PreConditionNotMetException();
306
+            }
307
+
308
+            return 0;
309
+        }
310
+    }
311
+
312
+    /**
313
+     * Create an exclusive read+write lock on a table
314
+     *
315
+     * @param string $tableName
316
+     * @throws \BadMethodCallException When trying to acquire a second lock
317
+     * @since 9.1.0
318
+     */
319
+    public function lockTable($tableName) {
320
+        if ($this->lockedTable !== null) {
321
+            throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
322
+        }
323
+
324
+        $tableName = $this->tablePrefix . $tableName;
325
+        $this->lockedTable = $tableName;
326
+        $this->adapter->lockTable($tableName);
327
+    }
328
+
329
+    /**
330
+     * Release a previous acquired lock again
331
+     *
332
+     * @since 9.1.0
333
+     */
334
+    public function unlockTable() {
335
+        $this->adapter->unlockTable();
336
+        $this->lockedTable = null;
337
+    }
338
+
339
+    /**
340
+     * returns the error code and message as a string for logging
341
+     * works with DoctrineException
342
+     * @return string
343
+     */
344
+    public function getError() {
345
+        $msg = $this->errorCode() . ': ';
346
+        $errorInfo = $this->errorInfo();
347
+        if (is_array($errorInfo)) {
348
+            $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
349
+            $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
350
+            $msg .= 'Driver Message = '.$errorInfo[2];
351
+        }
352
+        return $msg;
353
+    }
354
+
355
+    /**
356
+     * Drop a table from the database if it exists
357
+     *
358
+     * @param string $table table name without the prefix
359
+     */
360
+    public function dropTable($table) {
361
+        $table = $this->tablePrefix . trim($table);
362
+        $schema = $this->getSchemaManager();
363
+        if($schema->tablesExist(array($table))) {
364
+            $schema->dropTable($table);
365
+        }
366
+    }
367
+
368
+    /**
369
+     * Check if a table exists
370
+     *
371
+     * @param string $table table name without the prefix
372
+     * @return bool
373
+     */
374
+    public function tableExists($table){
375
+        $table = $this->tablePrefix . trim($table);
376
+        $schema = $this->getSchemaManager();
377
+        return $schema->tablesExist(array($table));
378
+    }
379
+
380
+    // internal use
381
+    /**
382
+     * @param string $statement
383
+     * @return string
384
+     */
385
+    protected function replaceTablePrefix($statement) {
386
+        return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
387
+    }
388
+
389
+    /**
390
+     * Check if a transaction is active
391
+     *
392
+     * @return bool
393
+     * @since 8.2.0
394
+     */
395
+    public function inTransaction() {
396
+        return $this->getTransactionNestingLevel() > 0;
397
+    }
398
+
399
+    /**
400
+     * Espace a parameter to be used in a LIKE query
401
+     *
402
+     * @param string $param
403
+     * @return string
404
+     */
405
+    public function escapeLikeParameter($param) {
406
+        return addcslashes($param, '\\_%');
407
+    }
408
+
409
+    /**
410
+     * Check whether or not the current database support 4byte wide unicode
411
+     *
412
+     * @return bool
413
+     * @since 11.0.0
414
+     */
415
+    public function supports4ByteText() {
416
+        if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
417
+            return true;
418
+        }
419
+        return $this->getParams()['charset'] === 'utf8mb4';
420
+    }
421 421
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 			return parent::connect();
59 59
 		} catch (DBALException $e) {
60 60
 			// throw a new exception to prevent leaking info from the stacktrace
61
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
61
+			throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode());
62 62
 		}
63 63
 	}
64 64
 
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 		// 0 is the method where we use `getCallerBacktrace`
111 111
 		// 1 is the target method which uses the method we want to log
112 112
 		if (isset($traces[1])) {
113
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
113
+			return $traces[1]['file'].':'.$traces[1]['line'];
114 114
 		}
115 115
 
116 116
 		return '';
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 	 * @param int $offset
157 157
 	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
158 158
 	 */
159
-	public function prepare( $statement, $limit=null, $offset=null ) {
159
+	public function prepare($statement, $limit = null, $offset = null) {
160 160
 		if ($limit === -1) {
161 161
 			$limit = null;
162 162
 		}
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
322 322
 		}
323 323
 
324
-		$tableName = $this->tablePrefix . $tableName;
324
+		$tableName = $this->tablePrefix.$tableName;
325 325
 		$this->lockedTable = $tableName;
326 326
 		$this->adapter->lockTable($tableName);
327 327
 	}
@@ -342,11 +342,11 @@  discard block
 block discarded – undo
342 342
 	 * @return string
343 343
 	 */
344 344
 	public function getError() {
345
-		$msg = $this->errorCode() . ': ';
345
+		$msg = $this->errorCode().': ';
346 346
 		$errorInfo = $this->errorInfo();
347 347
 		if (is_array($errorInfo)) {
348
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
349
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
348
+			$msg .= 'SQLSTATE = '.$errorInfo[0].', ';
349
+			$msg .= 'Driver Code = '.$errorInfo[1].', ';
350 350
 			$msg .= 'Driver Message = '.$errorInfo[2];
351 351
 		}
352 352
 		return $msg;
@@ -358,9 +358,9 @@  discard block
 block discarded – undo
358 358
 	 * @param string $table table name without the prefix
359 359
 	 */
360 360
 	public function dropTable($table) {
361
-		$table = $this->tablePrefix . trim($table);
361
+		$table = $this->tablePrefix.trim($table);
362 362
 		$schema = $this->getSchemaManager();
363
-		if($schema->tablesExist(array($table))) {
363
+		if ($schema->tablesExist(array($table))) {
364 364
 			$schema->dropTable($table);
365 365
 		}
366 366
 	}
@@ -371,8 +371,8 @@  discard block
 block discarded – undo
371 371
 	 * @param string $table table name without the prefix
372 372
 	 * @return bool
373 373
 	 */
374
-	public function tableExists($table){
375
-		$table = $this->tablePrefix . trim($table);
374
+	public function tableExists($table) {
375
+		$table = $this->tablePrefix.trim($table);
376 376
 		$schema = $this->getSchemaManager();
377 377
 		return $schema->tablesExist(array($table));
378 378
 	}
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
 	 * @return string
384 384
 	 */
385 385
 	protected function replaceTablePrefix($statement) {
386
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
386
+		return str_replace('*PREFIX*', $this->tablePrefix, $statement);
387 387
 	}
388 388
 
389 389
 	/**
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.
Indentation   +478 added lines, -478 removed lines patch added patch discarded remove patch
@@ -54,482 +54,482 @@
 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', array($file, $this->storageId));
162
-					\OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('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', array($file, $this->storageId));
231
-					\OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId));
232
-				}
233
-
234
-			} else {
235
-				$this->removeFromCache($file);
236
-			}
237
-
238
-			//release the acquired lock
239
-			if ($lock) {
240
-				if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
241
-					$this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
242
-				}
243
-			}
244
-
245
-			if ($data && !isset($data['encrypted'])) {
246
-				$data['encrypted'] = false;
247
-			}
248
-			return $data;
249
-		}
250
-
251
-		return null;
252
-	}
253
-
254
-	protected function removeFromCache($path) {
255
-		\OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path));
256
-		$this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path));
257
-		if ($this->cacheActive) {
258
-			$this->cache->remove($path);
259
-		}
260
-	}
261
-
262
-	/**
263
-	 * @param string $path
264
-	 * @param array $data
265
-	 * @param int $fileId
266
-	 * @return int the id of the added file
267
-	 */
268
-	protected function addToCache($path, $data, $fileId = -1) {
269
-		if (isset($data['scan_permissions'])) {
270
-			$data['permissions'] = $data['scan_permissions'];
271
-		}
272
-		\OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
273
-		$this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data));
274
-		if ($this->cacheActive) {
275
-			if ($fileId !== -1) {
276
-				$this->cache->update($fileId, $data);
277
-				return $fileId;
278
-			} else {
279
-				return $this->cache->put($path, $data);
280
-			}
281
-		} else {
282
-			return -1;
283
-		}
284
-	}
285
-
286
-	/**
287
-	 * @param string $path
288
-	 * @param array $data
289
-	 * @param int $fileId
290
-	 */
291
-	protected function updateCache($path, $data, $fileId = -1) {
292
-		\OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
293
-		$this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data));
294
-		if ($this->cacheActive) {
295
-			if ($fileId !== -1) {
296
-				$this->cache->update($fileId, $data);
297
-			} else {
298
-				$this->cache->put($path, $data);
299
-			}
300
-		}
301
-	}
302
-
303
-	/**
304
-	 * scan a folder and all it's children
305
-	 *
306
-	 * @param string $path
307
-	 * @param bool $recursive
308
-	 * @param int $reuse
309
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
310
-	 * @return array an array of the meta data of the scanned file or folder
311
-	 */
312
-	public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
313
-		if ($reuse === -1) {
314
-			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
315
-		}
316
-		if ($lock) {
317
-			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
318
-				$this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
319
-				$this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
320
-			}
321
-		}
322
-		try {
323
-			$data = $this->scanFile($path, $reuse, -1, null, $lock);
324
-			if ($data and $data['mimetype'] === 'httpd/unix-directory') {
325
-				$size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
326
-				$data['size'] = $size;
327
-			}
328
-		} finally {
329
-			if ($lock) {
330
-				if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
331
-					$this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
332
-					$this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
333
-				}
334
-			}
335
-		}
336
-		return $data;
337
-	}
338
-
339
-	/**
340
-	 * Get the children currently in the cache
341
-	 *
342
-	 * @param int $folderId
343
-	 * @return array[]
344
-	 */
345
-	protected function getExistingChildren($folderId) {
346
-		$existingChildren = array();
347
-		$children = $this->cache->getFolderContentsById($folderId);
348
-		foreach ($children as $child) {
349
-			$existingChildren[$child['name']] = $child;
350
-		}
351
-		return $existingChildren;
352
-	}
353
-
354
-	/**
355
-	 * Get the children from the storage
356
-	 *
357
-	 * @param string $folder
358
-	 * @return string[]
359
-	 */
360
-	protected function getNewChildren($folder) {
361
-		$children = array();
362
-		if ($dh = $this->storage->opendir($folder)) {
363
-			if (is_resource($dh)) {
364
-				while (($file = readdir($dh)) !== false) {
365
-					if (!Filesystem::isIgnoredDir($file)) {
366
-						$children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/');
367
-					}
368
-				}
369
-			}
370
-		}
371
-		return $children;
372
-	}
373
-
374
-	/**
375
-	 * scan all the files and folders in a folder
376
-	 *
377
-	 * @param string $path
378
-	 * @param bool $recursive
379
-	 * @param int $reuse
380
-	 * @param int $folderId id for the folder to be scanned
381
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
382
-	 * @return int the size of the scanned folder or -1 if the size is unknown at this stage
383
-	 */
384
-	protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
385
-		if ($reuse === -1) {
386
-			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
387
-		}
388
-		$this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId));
389
-		$size = 0;
390
-		if (!is_null($folderId)) {
391
-			$folderId = $this->cache->getId($path);
392
-		}
393
-		$childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
394
-
395
-		foreach ($childQueue as $child => $childId) {
396
-			$childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
397
-			if ($childSize === -1) {
398
-				$size = -1;
399
-			} else if ($size !== -1) {
400
-				$size += $childSize;
401
-			}
402
-		}
403
-		if ($this->cacheActive) {
404
-			$this->cache->update($folderId, array('size' => $size));
405
-		}
406
-		$this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId));
407
-		return $size;
408
-	}
409
-
410
-	private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
411
-		// we put this in it's own function so it cleans up the memory before we start recursing
412
-		$existingChildren = $this->getExistingChildren($folderId);
413
-		$newChildren = $this->getNewChildren($path);
414
-
415
-		if ($this->useTransactions) {
416
-			\OC::$server->getDatabaseConnection()->beginTransaction();
417
-		}
418
-
419
-		$exceptionOccurred = false;
420
-		$childQueue = [];
421
-		foreach ($newChildren as $file) {
422
-			$child = ($path) ? $path . '/' . $file : $file;
423
-			try {
424
-				$existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
425
-				$data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
426
-				if ($data) {
427
-					if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
428
-						$childQueue[$child] = $data['fileid'];
429
-					} else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
430
-						// only recurse into folders which aren't fully scanned
431
-						$childQueue[$child] = $data['fileid'];
432
-					} else if ($data['size'] === -1) {
433
-						$size = -1;
434
-					} else if ($size !== -1) {
435
-						$size += $data['size'];
436
-					}
437
-				}
438
-			} catch (\Doctrine\DBAL\DBALException $ex) {
439
-				// might happen if inserting duplicate while a scanning
440
-				// process is running in parallel
441
-				// log and ignore
442
-				\OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG);
443
-				$exceptionOccurred = true;
444
-			} catch (\OCP\Lock\LockedException $e) {
445
-				if ($this->useTransactions) {
446
-					\OC::$server->getDatabaseConnection()->rollback();
447
-				}
448
-				throw $e;
449
-			}
450
-		}
451
-		$removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
452
-		foreach ($removedChildren as $childName) {
453
-			$child = ($path) ? $path . '/' . $childName : $childName;
454
-			$this->removeFromCache($child);
455
-		}
456
-		if ($this->useTransactions) {
457
-			\OC::$server->getDatabaseConnection()->commit();
458
-		}
459
-		if ($exceptionOccurred) {
460
-			// It might happen that the parallel scan process has already
461
-			// inserted mimetypes but those weren't available yet inside the transaction
462
-			// To make sure to have the updated mime types in such cases,
463
-			// we reload them here
464
-			\OC::$server->getMimeTypeLoader()->reset();
465
-		}
466
-		return $childQueue;
467
-	}
468
-
469
-	/**
470
-	 * check if the file should be ignored when scanning
471
-	 * NOTE: files with a '.part' extension are ignored as well!
472
-	 *       prevents unfinished put requests to be scanned
473
-	 *
474
-	 * @param string $file
475
-	 * @return boolean
476
-	 */
477
-	public static function isPartialFile($file) {
478
-		if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
479
-			return true;
480
-		}
481
-		if (strpos($file, '.part/') !== false) {
482
-			return true;
483
-		}
484
-
485
-		return false;
486
-	}
487
-
488
-	/**
489
-	 * walk over any folders that are not fully scanned yet and scan them
490
-	 */
491
-	public function backgroundScan() {
492
-		if (!$this->cache->inCache('')) {
493
-			$this->runBackgroundScanJob(function () {
494
-				$this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
495
-			}, '');
496
-		} else {
497
-			$lastPath = null;
498
-			while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
499
-				$this->runBackgroundScanJob(function () use ($path) {
500
-					$this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
501
-				}, $path);
502
-				// FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
503
-				// to make this possible
504
-				$lastPath = $path;
505
-			}
506
-		}
507
-	}
508
-
509
-	private function runBackgroundScanJob(callable $callback, $path) {
510
-		try {
511
-			$callback();
512
-			\OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path));
513
-			if ($this->cacheActive && $this->cache instanceof Cache) {
514
-				$this->cache->correctFolderSize($path);
515
-			}
516
-		} catch (\OCP\Files\StorageInvalidException $e) {
517
-			// skip unavailable storages
518
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
519
-			// skip unavailable storages
520
-		} catch (\OCP\Files\ForbiddenException $e) {
521
-			// skip forbidden storages
522
-		} catch (\OCP\Lock\LockedException $e) {
523
-			// skip unavailable storages
524
-		}
525
-	}
526
-
527
-	/**
528
-	 * Set whether the cache is affected by scan operations
529
-	 *
530
-	 * @param boolean $active The active state of the cache
531
-	 */
532
-	public function setCacheActive($active) {
533
-		$this->cacheActive = $active;
534
-	}
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', array($file, $this->storageId));
162
+                    \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('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', array($file, $this->storageId));
231
+                    \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId));
232
+                }
233
+
234
+            } else {
235
+                $this->removeFromCache($file);
236
+            }
237
+
238
+            //release the acquired lock
239
+            if ($lock) {
240
+                if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
241
+                    $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
242
+                }
243
+            }
244
+
245
+            if ($data && !isset($data['encrypted'])) {
246
+                $data['encrypted'] = false;
247
+            }
248
+            return $data;
249
+        }
250
+
251
+        return null;
252
+    }
253
+
254
+    protected function removeFromCache($path) {
255
+        \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path));
256
+        $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path));
257
+        if ($this->cacheActive) {
258
+            $this->cache->remove($path);
259
+        }
260
+    }
261
+
262
+    /**
263
+     * @param string $path
264
+     * @param array $data
265
+     * @param int $fileId
266
+     * @return int the id of the added file
267
+     */
268
+    protected function addToCache($path, $data, $fileId = -1) {
269
+        if (isset($data['scan_permissions'])) {
270
+            $data['permissions'] = $data['scan_permissions'];
271
+        }
272
+        \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
273
+        $this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data));
274
+        if ($this->cacheActive) {
275
+            if ($fileId !== -1) {
276
+                $this->cache->update($fileId, $data);
277
+                return $fileId;
278
+            } else {
279
+                return $this->cache->put($path, $data);
280
+            }
281
+        } else {
282
+            return -1;
283
+        }
284
+    }
285
+
286
+    /**
287
+     * @param string $path
288
+     * @param array $data
289
+     * @param int $fileId
290
+     */
291
+    protected function updateCache($path, $data, $fileId = -1) {
292
+        \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
293
+        $this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data));
294
+        if ($this->cacheActive) {
295
+            if ($fileId !== -1) {
296
+                $this->cache->update($fileId, $data);
297
+            } else {
298
+                $this->cache->put($path, $data);
299
+            }
300
+        }
301
+    }
302
+
303
+    /**
304
+     * scan a folder and all it's children
305
+     *
306
+     * @param string $path
307
+     * @param bool $recursive
308
+     * @param int $reuse
309
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
310
+     * @return array an array of the meta data of the scanned file or folder
311
+     */
312
+    public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
313
+        if ($reuse === -1) {
314
+            $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
315
+        }
316
+        if ($lock) {
317
+            if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
318
+                $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
319
+                $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
320
+            }
321
+        }
322
+        try {
323
+            $data = $this->scanFile($path, $reuse, -1, null, $lock);
324
+            if ($data and $data['mimetype'] === 'httpd/unix-directory') {
325
+                $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
326
+                $data['size'] = $size;
327
+            }
328
+        } finally {
329
+            if ($lock) {
330
+                if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
331
+                    $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
332
+                    $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
333
+                }
334
+            }
335
+        }
336
+        return $data;
337
+    }
338
+
339
+    /**
340
+     * Get the children currently in the cache
341
+     *
342
+     * @param int $folderId
343
+     * @return array[]
344
+     */
345
+    protected function getExistingChildren($folderId) {
346
+        $existingChildren = array();
347
+        $children = $this->cache->getFolderContentsById($folderId);
348
+        foreach ($children as $child) {
349
+            $existingChildren[$child['name']] = $child;
350
+        }
351
+        return $existingChildren;
352
+    }
353
+
354
+    /**
355
+     * Get the children from the storage
356
+     *
357
+     * @param string $folder
358
+     * @return string[]
359
+     */
360
+    protected function getNewChildren($folder) {
361
+        $children = array();
362
+        if ($dh = $this->storage->opendir($folder)) {
363
+            if (is_resource($dh)) {
364
+                while (($file = readdir($dh)) !== false) {
365
+                    if (!Filesystem::isIgnoredDir($file)) {
366
+                        $children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/');
367
+                    }
368
+                }
369
+            }
370
+        }
371
+        return $children;
372
+    }
373
+
374
+    /**
375
+     * scan all the files and folders in a folder
376
+     *
377
+     * @param string $path
378
+     * @param bool $recursive
379
+     * @param int $reuse
380
+     * @param int $folderId id for the folder to be scanned
381
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
382
+     * @return int the size of the scanned folder or -1 if the size is unknown at this stage
383
+     */
384
+    protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
385
+        if ($reuse === -1) {
386
+            $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
387
+        }
388
+        $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId));
389
+        $size = 0;
390
+        if (!is_null($folderId)) {
391
+            $folderId = $this->cache->getId($path);
392
+        }
393
+        $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
394
+
395
+        foreach ($childQueue as $child => $childId) {
396
+            $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
397
+            if ($childSize === -1) {
398
+                $size = -1;
399
+            } else if ($size !== -1) {
400
+                $size += $childSize;
401
+            }
402
+        }
403
+        if ($this->cacheActive) {
404
+            $this->cache->update($folderId, array('size' => $size));
405
+        }
406
+        $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId));
407
+        return $size;
408
+    }
409
+
410
+    private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
411
+        // we put this in it's own function so it cleans up the memory before we start recursing
412
+        $existingChildren = $this->getExistingChildren($folderId);
413
+        $newChildren = $this->getNewChildren($path);
414
+
415
+        if ($this->useTransactions) {
416
+            \OC::$server->getDatabaseConnection()->beginTransaction();
417
+        }
418
+
419
+        $exceptionOccurred = false;
420
+        $childQueue = [];
421
+        foreach ($newChildren as $file) {
422
+            $child = ($path) ? $path . '/' . $file : $file;
423
+            try {
424
+                $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
425
+                $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
426
+                if ($data) {
427
+                    if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
428
+                        $childQueue[$child] = $data['fileid'];
429
+                    } else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
430
+                        // only recurse into folders which aren't fully scanned
431
+                        $childQueue[$child] = $data['fileid'];
432
+                    } else if ($data['size'] === -1) {
433
+                        $size = -1;
434
+                    } else if ($size !== -1) {
435
+                        $size += $data['size'];
436
+                    }
437
+                }
438
+            } catch (\Doctrine\DBAL\DBALException $ex) {
439
+                // might happen if inserting duplicate while a scanning
440
+                // process is running in parallel
441
+                // log and ignore
442
+                \OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG);
443
+                $exceptionOccurred = true;
444
+            } catch (\OCP\Lock\LockedException $e) {
445
+                if ($this->useTransactions) {
446
+                    \OC::$server->getDatabaseConnection()->rollback();
447
+                }
448
+                throw $e;
449
+            }
450
+        }
451
+        $removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
452
+        foreach ($removedChildren as $childName) {
453
+            $child = ($path) ? $path . '/' . $childName : $childName;
454
+            $this->removeFromCache($child);
455
+        }
456
+        if ($this->useTransactions) {
457
+            \OC::$server->getDatabaseConnection()->commit();
458
+        }
459
+        if ($exceptionOccurred) {
460
+            // It might happen that the parallel scan process has already
461
+            // inserted mimetypes but those weren't available yet inside the transaction
462
+            // To make sure to have the updated mime types in such cases,
463
+            // we reload them here
464
+            \OC::$server->getMimeTypeLoader()->reset();
465
+        }
466
+        return $childQueue;
467
+    }
468
+
469
+    /**
470
+     * check if the file should be ignored when scanning
471
+     * NOTE: files with a '.part' extension are ignored as well!
472
+     *       prevents unfinished put requests to be scanned
473
+     *
474
+     * @param string $file
475
+     * @return boolean
476
+     */
477
+    public static function isPartialFile($file) {
478
+        if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
479
+            return true;
480
+        }
481
+        if (strpos($file, '.part/') !== false) {
482
+            return true;
483
+        }
484
+
485
+        return false;
486
+    }
487
+
488
+    /**
489
+     * walk over any folders that are not fully scanned yet and scan them
490
+     */
491
+    public function backgroundScan() {
492
+        if (!$this->cache->inCache('')) {
493
+            $this->runBackgroundScanJob(function () {
494
+                $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
495
+            }, '');
496
+        } else {
497
+            $lastPath = null;
498
+            while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
499
+                $this->runBackgroundScanJob(function () use ($path) {
500
+                    $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
501
+                }, $path);
502
+                // FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
503
+                // to make this possible
504
+                $lastPath = $path;
505
+            }
506
+        }
507
+    }
508
+
509
+    private function runBackgroundScanJob(callable $callback, $path) {
510
+        try {
511
+            $callback();
512
+            \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path));
513
+            if ($this->cacheActive && $this->cache instanceof Cache) {
514
+                $this->cache->correctFolderSize($path);
515
+            }
516
+        } catch (\OCP\Files\StorageInvalidException $e) {
517
+            // skip unavailable storages
518
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
519
+            // skip unavailable storages
520
+        } catch (\OCP\Files\ForbiddenException $e) {
521
+            // skip forbidden storages
522
+        } catch (\OCP\Lock\LockedException $e) {
523
+            // skip unavailable storages
524
+        }
525
+    }
526
+
527
+    /**
528
+     * Set whether the cache is affected by scan operations
529
+     *
530
+     * @param boolean $active The active state of the cache
531
+     */
532
+    public function setCacheActive($active) {
533
+        $this->cacheActive = $active;
534
+    }
535 535
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
 		}
316 316
 		if ($lock) {
317 317
 			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
318
-				$this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
318
+				$this->storage->acquireLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
319 319
 				$this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
320 320
 			}
321 321
 		}
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
 			if ($lock) {
330 330
 				if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
331 331
 					$this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
332
-					$this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
332
+					$this->storage->releaseLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
333 333
 				}
334 334
 			}
335 335
 		}
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
 		$exceptionOccurred = false;
420 420
 		$childQueue = [];
421 421
 		foreach ($newChildren as $file) {
422
-			$child = ($path) ? $path . '/' . $file : $file;
422
+			$child = ($path) ? $path.'/'.$file : $file;
423 423
 			try {
424 424
 				$existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
425 425
 				$data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
 				// might happen if inserting duplicate while a scanning
440 440
 				// process is running in parallel
441 441
 				// log and ignore
442
-				\OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG);
442
+				\OCP\Util::writeLog('core', 'Exception while scanning file "'.$child.'": '.$ex->getMessage(), \OCP\Util::DEBUG);
443 443
 				$exceptionOccurred = true;
444 444
 			} catch (\OCP\Lock\LockedException $e) {
445 445
 				if ($this->useTransactions) {
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 		}
451 451
 		$removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
452 452
 		foreach ($removedChildren as $childName) {
453
-			$child = ($path) ? $path . '/' . $childName : $childName;
453
+			$child = ($path) ? $path.'/'.$childName : $childName;
454 454
 			$this->removeFromCache($child);
455 455
 		}
456 456
 		if ($this->useTransactions) {
@@ -490,13 +490,13 @@  discard block
 block discarded – undo
490 490
 	 */
491 491
 	public function backgroundScan() {
492 492
 		if (!$this->cache->inCache('')) {
493
-			$this->runBackgroundScanJob(function () {
493
+			$this->runBackgroundScanJob(function() {
494 494
 				$this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
495 495
 			}, '');
496 496
 		} else {
497 497
 			$lastPath = null;
498 498
 			while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
499
-				$this->runBackgroundScanJob(function () use ($path) {
499
+				$this->runBackgroundScanJob(function() use ($path) {
500 500
 					$this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
501 501
 				}, $path);
502 502
 				// FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
Please login to merge, or discard this patch.
lib/private/Files/Config/UserMountCache.php 3 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.
Indentation   +324 added lines, -324 removed lines patch added patch discarded remove patch
@@ -42,328 +42,328 @@
 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
-		$newMountRootIds = array_map(function (ICachedMountInfo $mount) {
104
-			return $mount->getRootId();
105
-		}, $newMounts);
106
-		$newMounts = array_combine($newMountRootIds, $newMounts);
107
-
108
-		$cachedMounts = $this->getMountsForUser($user);
109
-		$cachedMountRootIds = array_map(function (ICachedMountInfo $mount) {
110
-			return $mount->getRootId();
111
-		}, $cachedMounts);
112
-		$cachedMounts = array_combine($cachedMountRootIds, $cachedMounts);
113
-
114
-		$addedMounts = [];
115
-		$removedMounts = [];
116
-
117
-		foreach ($newMounts as $rootId => $newMount) {
118
-			if (!isset($cachedMounts[$rootId])) {
119
-				$addedMounts[] = $newMount;
120
-			}
121
-		}
122
-
123
-		foreach ($cachedMounts as $rootId => $cachedMount) {
124
-			if (!isset($newMounts[$rootId])) {
125
-				$removedMounts[] = $cachedMount;
126
-			}
127
-		}
128
-
129
-		$changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
130
-
131
-		foreach ($addedMounts as $mount) {
132
-			$this->addToCache($mount);
133
-			$this->mountsForUsers[$user->getUID()][] = $mount;
134
-		}
135
-		foreach ($removedMounts as $mount) {
136
-			$this->removeFromCache($mount);
137
-			$index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
138
-			unset($this->mountsForUsers[$user->getUID()][$index]);
139
-		}
140
-		foreach ($changedMounts as $mount) {
141
-			$this->updateCachedMount($mount);
142
-		}
143
-	}
144
-
145
-	/**
146
-	 * @param ICachedMountInfo[] $newMounts
147
-	 * @param ICachedMountInfo[] $cachedMounts
148
-	 * @return ICachedMountInfo[]
149
-	 */
150
-	private function findChangedMounts(array $newMounts, array $cachedMounts) {
151
-		$new = [];
152
-		foreach ($newMounts as $mount) {
153
-			$new[$mount->getRootId()] = $mount;
154
-		}
155
-		$changed = [];
156
-		foreach ($cachedMounts as $cachedMount) {
157
-			$rootId = $cachedMount->getRootId();
158
-			if (isset($new[$rootId])) {
159
-				$newMount = $new[$rootId];
160
-				if (
161
-					$newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
162
-					$newMount->getStorageId() !== $cachedMount->getStorageId() ||
163
-					$newMount->getMountId() !== $cachedMount->getMountId()
164
-				) {
165
-					$changed[] = $newMount;
166
-				}
167
-			}
168
-		}
169
-		return $changed;
170
-	}
171
-
172
-	private function addToCache(ICachedMountInfo $mount) {
173
-		if ($mount->getStorageId() !== -1) {
174
-			$this->connection->insertIfNotExist('*PREFIX*mounts', [
175
-				'storage_id' => $mount->getStorageId(),
176
-				'root_id' => $mount->getRootId(),
177
-				'user_id' => $mount->getUser()->getUID(),
178
-				'mount_point' => $mount->getMountPoint(),
179
-				'mount_id' => $mount->getMountId()
180
-			], ['root_id', 'user_id']);
181
-		} else {
182
-			// in some cases this is legitimate, like orphaned shares
183
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
184
-		}
185
-	}
186
-
187
-	private function updateCachedMount(ICachedMountInfo $mount) {
188
-		$builder = $this->connection->getQueryBuilder();
189
-
190
-		$query = $builder->update('mounts')
191
-			->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
192
-			->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
193
-			->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
194
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
195
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
196
-
197
-		$query->execute();
198
-	}
199
-
200
-	private function removeFromCache(ICachedMountInfo $mount) {
201
-		$builder = $this->connection->getQueryBuilder();
202
-
203
-		$query = $builder->delete('mounts')
204
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
205
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
206
-		$query->execute();
207
-	}
208
-
209
-	private function dbRowToMountInfo(array $row) {
210
-		$user = $this->userManager->get($row['user_id']);
211
-		if (is_null($user)) {
212
-			return null;
213
-		}
214
-		$mount_id = $row['mount_id'];
215
-		if (!is_null($mount_id)) {
216
-			$mount_id = (int)$mount_id;
217
-		}
218
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path'])? $row['path']:'');
219
-	}
220
-
221
-	/**
222
-	 * @param IUser $user
223
-	 * @return ICachedMountInfo[]
224
-	 */
225
-	public function getMountsForUser(IUser $user) {
226
-		if (!isset($this->mountsForUsers[$user->getUID()])) {
227
-			$builder = $this->connection->getQueryBuilder();
228
-			$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
229
-				->from('mounts', 'm')
230
-				->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
231
-				->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
232
-
233
-			$rows = $query->execute()->fetchAll();
234
-
235
-			$this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
236
-		}
237
-		return $this->mountsForUsers[$user->getUID()];
238
-	}
239
-
240
-	/**
241
-	 * @param int $numericStorageId
242
-	 * @param string|null $user limit the results to a single user
243
-	 * @return CachedMountInfo[]
244
-	 */
245
-	public function getMountsForStorageId($numericStorageId, $user = null) {
246
-		$builder = $this->connection->getQueryBuilder();
247
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
248
-			->from('mounts', 'm')
249
-			->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid'))
250
-			->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
251
-
252
-		if ($user) {
253
-			$query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
254
-		}
255
-
256
-		$rows = $query->execute()->fetchAll();
257
-
258
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
259
-	}
260
-
261
-	/**
262
-	 * @param int $rootFileId
263
-	 * @return CachedMountInfo[]
264
-	 */
265
-	public function getMountsForRootId($rootFileId) {
266
-		$builder = $this->connection->getQueryBuilder();
267
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
268
-			->from('mounts', 'm')
269
-			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
270
-			->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
271
-
272
-		$rows = $query->execute()->fetchAll();
273
-
274
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
275
-	}
276
-
277
-	/**
278
-	 * @param $fileId
279
-	 * @return array
280
-	 * @throws \OCP\Files\NotFoundException
281
-	 */
282
-	private function getCacheInfoFromFileId($fileId) {
283
-		if (!isset($this->cacheInfoCache[$fileId])) {
284
-			$builder = $this->connection->getQueryBuilder();
285
-			$query = $builder->select('storage', 'path', 'mimetype')
286
-				->from('filecache')
287
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
288
-
289
-			$row = $query->execute()->fetch();
290
-			if (is_array($row)) {
291
-				$this->cacheInfoCache[$fileId] = [
292
-					(int)$row['storage'],
293
-					$row['path'],
294
-					(int)$row['mimetype']
295
-				];
296
-			} else {
297
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
298
-			}
299
-		}
300
-		return $this->cacheInfoCache[$fileId];
301
-	}
302
-
303
-	/**
304
-	 * @param int $fileId
305
-	 * @param string|null $user optionally restrict the results to a single user
306
-	 * @return ICachedMountFileInfo[]
307
-	 * @since 9.0.0
308
-	 */
309
-	public function getMountsForFileId($fileId, $user = null) {
310
-		try {
311
-			list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
312
-		} catch (NotFoundException $e) {
313
-			return [];
314
-		}
315
-		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
316
-
317
-		// filter mounts that are from the same storage but a different directory
318
-		$filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
319
-			if ($fileId === $mount->getRootId()) {
320
-				return true;
321
-			}
322
-			$internalMountPath = $mount->getRootInternalPath();
323
-
324
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
325
-		});
326
-
327
-		return array_map(function (ICachedMountInfo $mount) use ($internalPath) {
328
-			return new CachedMountFileInfo(
329
-				$mount->getUser(),
330
-				$mount->getStorageId(),
331
-				$mount->getRootId(),
332
-				$mount->getMountPoint(),
333
-				$mount->getMountId(),
334
-				$mount->getRootInternalPath(),
335
-				$internalPath
336
-			);
337
-		}, $filteredMounts);
338
-	}
339
-
340
-	/**
341
-	 * Remove all cached mounts for a user
342
-	 *
343
-	 * @param IUser $user
344
-	 */
345
-	public function removeUserMounts(IUser $user) {
346
-		$builder = $this->connection->getQueryBuilder();
347
-
348
-		$query = $builder->delete('mounts')
349
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
350
-		$query->execute();
351
-	}
352
-
353
-	public function removeUserStorageMount($storageId, $userId) {
354
-		$builder = $this->connection->getQueryBuilder();
355
-
356
-		$query = $builder->delete('mounts')
357
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
358
-			->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
359
-		$query->execute();
360
-	}
361
-
362
-	public function remoteStorageMounts($storageId) {
363
-		$builder = $this->connection->getQueryBuilder();
364
-
365
-		$query = $builder->delete('mounts')
366
-			->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
367
-		$query->execute();
368
-	}
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
+        $newMountRootIds = array_map(function (ICachedMountInfo $mount) {
104
+            return $mount->getRootId();
105
+        }, $newMounts);
106
+        $newMounts = array_combine($newMountRootIds, $newMounts);
107
+
108
+        $cachedMounts = $this->getMountsForUser($user);
109
+        $cachedMountRootIds = array_map(function (ICachedMountInfo $mount) {
110
+            return $mount->getRootId();
111
+        }, $cachedMounts);
112
+        $cachedMounts = array_combine($cachedMountRootIds, $cachedMounts);
113
+
114
+        $addedMounts = [];
115
+        $removedMounts = [];
116
+
117
+        foreach ($newMounts as $rootId => $newMount) {
118
+            if (!isset($cachedMounts[$rootId])) {
119
+                $addedMounts[] = $newMount;
120
+            }
121
+        }
122
+
123
+        foreach ($cachedMounts as $rootId => $cachedMount) {
124
+            if (!isset($newMounts[$rootId])) {
125
+                $removedMounts[] = $cachedMount;
126
+            }
127
+        }
128
+
129
+        $changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
130
+
131
+        foreach ($addedMounts as $mount) {
132
+            $this->addToCache($mount);
133
+            $this->mountsForUsers[$user->getUID()][] = $mount;
134
+        }
135
+        foreach ($removedMounts as $mount) {
136
+            $this->removeFromCache($mount);
137
+            $index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
138
+            unset($this->mountsForUsers[$user->getUID()][$index]);
139
+        }
140
+        foreach ($changedMounts as $mount) {
141
+            $this->updateCachedMount($mount);
142
+        }
143
+    }
144
+
145
+    /**
146
+     * @param ICachedMountInfo[] $newMounts
147
+     * @param ICachedMountInfo[] $cachedMounts
148
+     * @return ICachedMountInfo[]
149
+     */
150
+    private function findChangedMounts(array $newMounts, array $cachedMounts) {
151
+        $new = [];
152
+        foreach ($newMounts as $mount) {
153
+            $new[$mount->getRootId()] = $mount;
154
+        }
155
+        $changed = [];
156
+        foreach ($cachedMounts as $cachedMount) {
157
+            $rootId = $cachedMount->getRootId();
158
+            if (isset($new[$rootId])) {
159
+                $newMount = $new[$rootId];
160
+                if (
161
+                    $newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
162
+                    $newMount->getStorageId() !== $cachedMount->getStorageId() ||
163
+                    $newMount->getMountId() !== $cachedMount->getMountId()
164
+                ) {
165
+                    $changed[] = $newMount;
166
+                }
167
+            }
168
+        }
169
+        return $changed;
170
+    }
171
+
172
+    private function addToCache(ICachedMountInfo $mount) {
173
+        if ($mount->getStorageId() !== -1) {
174
+            $this->connection->insertIfNotExist('*PREFIX*mounts', [
175
+                'storage_id' => $mount->getStorageId(),
176
+                'root_id' => $mount->getRootId(),
177
+                'user_id' => $mount->getUser()->getUID(),
178
+                'mount_point' => $mount->getMountPoint(),
179
+                'mount_id' => $mount->getMountId()
180
+            ], ['root_id', 'user_id']);
181
+        } else {
182
+            // in some cases this is legitimate, like orphaned shares
183
+            $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
184
+        }
185
+    }
186
+
187
+    private function updateCachedMount(ICachedMountInfo $mount) {
188
+        $builder = $this->connection->getQueryBuilder();
189
+
190
+        $query = $builder->update('mounts')
191
+            ->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
192
+            ->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
193
+            ->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
194
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
195
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
196
+
197
+        $query->execute();
198
+    }
199
+
200
+    private function removeFromCache(ICachedMountInfo $mount) {
201
+        $builder = $this->connection->getQueryBuilder();
202
+
203
+        $query = $builder->delete('mounts')
204
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
205
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
206
+        $query->execute();
207
+    }
208
+
209
+    private function dbRowToMountInfo(array $row) {
210
+        $user = $this->userManager->get($row['user_id']);
211
+        if (is_null($user)) {
212
+            return null;
213
+        }
214
+        $mount_id = $row['mount_id'];
215
+        if (!is_null($mount_id)) {
216
+            $mount_id = (int)$mount_id;
217
+        }
218
+        return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path'])? $row['path']:'');
219
+    }
220
+
221
+    /**
222
+     * @param IUser $user
223
+     * @return ICachedMountInfo[]
224
+     */
225
+    public function getMountsForUser(IUser $user) {
226
+        if (!isset($this->mountsForUsers[$user->getUID()])) {
227
+            $builder = $this->connection->getQueryBuilder();
228
+            $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
229
+                ->from('mounts', 'm')
230
+                ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
231
+                ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
232
+
233
+            $rows = $query->execute()->fetchAll();
234
+
235
+            $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
236
+        }
237
+        return $this->mountsForUsers[$user->getUID()];
238
+    }
239
+
240
+    /**
241
+     * @param int $numericStorageId
242
+     * @param string|null $user limit the results to a single user
243
+     * @return CachedMountInfo[]
244
+     */
245
+    public function getMountsForStorageId($numericStorageId, $user = null) {
246
+        $builder = $this->connection->getQueryBuilder();
247
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
248
+            ->from('mounts', 'm')
249
+            ->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid'))
250
+            ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
251
+
252
+        if ($user) {
253
+            $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
254
+        }
255
+
256
+        $rows = $query->execute()->fetchAll();
257
+
258
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
259
+    }
260
+
261
+    /**
262
+     * @param int $rootFileId
263
+     * @return CachedMountInfo[]
264
+     */
265
+    public function getMountsForRootId($rootFileId) {
266
+        $builder = $this->connection->getQueryBuilder();
267
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
268
+            ->from('mounts', 'm')
269
+            ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
270
+            ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
271
+
272
+        $rows = $query->execute()->fetchAll();
273
+
274
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
275
+    }
276
+
277
+    /**
278
+     * @param $fileId
279
+     * @return array
280
+     * @throws \OCP\Files\NotFoundException
281
+     */
282
+    private function getCacheInfoFromFileId($fileId) {
283
+        if (!isset($this->cacheInfoCache[$fileId])) {
284
+            $builder = $this->connection->getQueryBuilder();
285
+            $query = $builder->select('storage', 'path', 'mimetype')
286
+                ->from('filecache')
287
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
288
+
289
+            $row = $query->execute()->fetch();
290
+            if (is_array($row)) {
291
+                $this->cacheInfoCache[$fileId] = [
292
+                    (int)$row['storage'],
293
+                    $row['path'],
294
+                    (int)$row['mimetype']
295
+                ];
296
+            } else {
297
+                throw new NotFoundException('File with id "' . $fileId . '" not found');
298
+            }
299
+        }
300
+        return $this->cacheInfoCache[$fileId];
301
+    }
302
+
303
+    /**
304
+     * @param int $fileId
305
+     * @param string|null $user optionally restrict the results to a single user
306
+     * @return ICachedMountFileInfo[]
307
+     * @since 9.0.0
308
+     */
309
+    public function getMountsForFileId($fileId, $user = null) {
310
+        try {
311
+            list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
312
+        } catch (NotFoundException $e) {
313
+            return [];
314
+        }
315
+        $mountsForStorage = $this->getMountsForStorageId($storageId, $user);
316
+
317
+        // filter mounts that are from the same storage but a different directory
318
+        $filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
319
+            if ($fileId === $mount->getRootId()) {
320
+                return true;
321
+            }
322
+            $internalMountPath = $mount->getRootInternalPath();
323
+
324
+            return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
325
+        });
326
+
327
+        return array_map(function (ICachedMountInfo $mount) use ($internalPath) {
328
+            return new CachedMountFileInfo(
329
+                $mount->getUser(),
330
+                $mount->getStorageId(),
331
+                $mount->getRootId(),
332
+                $mount->getMountPoint(),
333
+                $mount->getMountId(),
334
+                $mount->getRootInternalPath(),
335
+                $internalPath
336
+            );
337
+        }, $filteredMounts);
338
+    }
339
+
340
+    /**
341
+     * Remove all cached mounts for a user
342
+     *
343
+     * @param IUser $user
344
+     */
345
+    public function removeUserMounts(IUser $user) {
346
+        $builder = $this->connection->getQueryBuilder();
347
+
348
+        $query = $builder->delete('mounts')
349
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
350
+        $query->execute();
351
+    }
352
+
353
+    public function removeUserStorageMount($storageId, $userId) {
354
+        $builder = $this->connection->getQueryBuilder();
355
+
356
+        $query = $builder->delete('mounts')
357
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
358
+            ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
359
+        $query->execute();
360
+    }
361
+
362
+    public function remoteStorageMounts($storageId) {
363
+        $builder = $this->connection->getQueryBuilder();
364
+
365
+        $query = $builder->delete('mounts')
366
+            ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
367
+        $query->execute();
368
+    }
369 369
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 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;
@@ -100,13 +100,13 @@  discard block
 block discarded – undo
100 100
 			}
101 101
 		}, $mounts);
102 102
 		$newMounts = array_values(array_filter($newMounts));
103
-		$newMountRootIds = array_map(function (ICachedMountInfo $mount) {
103
+		$newMountRootIds = array_map(function(ICachedMountInfo $mount) {
104 104
 			return $mount->getRootId();
105 105
 		}, $newMounts);
106 106
 		$newMounts = array_combine($newMountRootIds, $newMounts);
107 107
 
108 108
 		$cachedMounts = $this->getMountsForUser($user);
109
-		$cachedMountRootIds = array_map(function (ICachedMountInfo $mount) {
109
+		$cachedMountRootIds = array_map(function(ICachedMountInfo $mount) {
110 110
 			return $mount->getRootId();
111 111
 		}, $cachedMounts);
112 112
 		$cachedMounts = array_combine($cachedMountRootIds, $cachedMounts);
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 			], ['root_id', 'user_id']);
181 181
 		} else {
182 182
 			// in some cases this is legitimate, like orphaned shares
183
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
183
+			$this->logger->debug('Could not get storage info for mount at '.$mount->getMountPoint());
184 184
 		}
185 185
 	}
186 186
 
@@ -213,9 +213,9 @@  discard block
 block discarded – undo
213 213
 		}
214 214
 		$mount_id = $row['mount_id'];
215 215
 		if (!is_null($mount_id)) {
216
-			$mount_id = (int)$mount_id;
216
+			$mount_id = (int) $mount_id;
217 217
 		}
218
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path'])? $row['path']:'');
218
+		return new CachedMountInfo($user, (int) $row['storage_id'], (int) $row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : '');
219 219
 	}
220 220
 
221 221
 	/**
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 		$builder = $this->connection->getQueryBuilder();
247 247
 		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
248 248
 			->from('mounts', 'm')
249
-			->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid'))
249
+			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
250 250
 			->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
251 251
 
252 252
 		if ($user) {
@@ -289,12 +289,12 @@  discard block
 block discarded – undo
289 289
 			$row = $query->execute()->fetch();
290 290
 			if (is_array($row)) {
291 291
 				$this->cacheInfoCache[$fileId] = [
292
-					(int)$row['storage'],
292
+					(int) $row['storage'],
293 293
 					$row['path'],
294
-					(int)$row['mimetype']
294
+					(int) $row['mimetype']
295 295
 				];
296 296
 			} else {
297
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
297
+				throw new NotFoundException('File with id "'.$fileId.'" not found');
298 298
 			}
299 299
 		}
300 300
 		return $this->cacheInfoCache[$fileId];
@@ -315,16 +315,16 @@  discard block
 block discarded – undo
315 315
 		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
316 316
 
317 317
 		// filter mounts that are from the same storage but a different directory
318
-		$filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
318
+		$filteredMounts = array_filter($mountsForStorage, function(ICachedMountInfo $mount) use ($internalPath, $fileId) {
319 319
 			if ($fileId === $mount->getRootId()) {
320 320
 				return true;
321 321
 			}
322 322
 			$internalMountPath = $mount->getRootInternalPath();
323 323
 
324
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
324
+			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath.'/';
325 325
 		});
326 326
 
327
-		return array_map(function (ICachedMountInfo $mount) use ($internalPath) {
327
+		return array_map(function(ICachedMountInfo $mount) use ($internalPath) {
328 328
 			return new CachedMountFileInfo(
329 329
 				$mount->getUser(),
330 330
 				$mount->getStorageId(),
Please login to merge, or discard this patch.
lib/private/Files/Node/LazyRoot.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -52,7 +52,7 @@
 block discarded – undo
52 52
 	 * Magic method to first get the real rootFolder and then
53 53
 	 * call $method with $args on it
54 54
 	 *
55
-	 * @param $method
55
+	 * @param string $method
56 56
 	 * @param $args
57 57
 	 * @return mixed
58 58
 	 */
Please login to merge, or discard this patch.
Indentation   +443 added lines, -443 removed lines patch added patch discarded remove patch
@@ -34,447 +34,447 @@
 block discarded – undo
34 34
  * @package OC\Files\Node
35 35
  */
36 36
 class LazyRoot implements IRootFolder {
37
-	/** @var \Closure */
38
-	private $rootFolderClosure;
39
-
40
-	/** @var IRootFolder */
41
-	private $rootFolder;
42
-
43
-	/**
44
-	 * LazyRoot constructor.
45
-	 *
46
-	 * @param \Closure $rootFolderClosure
47
-	 */
48
-	public function __construct(\Closure $rootFolderClosure) {
49
-		$this->rootFolderClosure = $rootFolderClosure;
50
-	}
51
-
52
-	/**
53
-	 * Magic method to first get the real rootFolder and then
54
-	 * call $method with $args on it
55
-	 *
56
-	 * @param $method
57
-	 * @param $args
58
-	 * @return mixed
59
-	 */
60
-	public function __call($method, $args) {
61
-		if ($this->rootFolder === null) {
62
-			$this->rootFolder = call_user_func($this->rootFolderClosure);
63
-		}
64
-
65
-		return call_user_func_array([$this->rootFolder, $method], $args);
66
-	}
67
-
68
-	/**
69
-	 * @inheritDoc
70
-	 */
71
-	public function getUser() {
72
-		return $this->__call(__FUNCTION__, func_get_args());
73
-	}
74
-
75
-	/**
76
-	 * @inheritDoc
77
-	 */
78
-	public function listen($scope, $method, callable $callback) {
79
-		$this->__call(__FUNCTION__, func_get_args());
80
-	}
81
-
82
-	/**
83
-	 * @inheritDoc
84
-	 */
85
-	public function removeListener($scope = null, $method = null, callable $callback = null) {
86
-		$this->__call(__FUNCTION__, func_get_args());
87
-	}
88
-
89
-	/**
90
-	 * @inheritDoc
91
-	 */
92
-	public function emit($scope, $method, $arguments = array()) {
93
-		$this->__call(__FUNCTION__, func_get_args());
94
-	}
95
-
96
-	/**
97
-	 * @inheritDoc
98
-	 */
99
-	public function mount($storage, $mountPoint, $arguments = array()) {
100
-		$this->__call(__FUNCTION__, func_get_args());
101
-	}
102
-
103
-	/**
104
-	 * @inheritDoc
105
-	 */
106
-	public function getMount($mountPoint) {
107
-		return $this->__call(__FUNCTION__, func_get_args());
108
-	}
109
-
110
-	/**
111
-	 * @inheritDoc
112
-	 */
113
-	public function getMountsIn($mountPoint) {
114
-		return $this->__call(__FUNCTION__, func_get_args());
115
-	}
116
-
117
-	/**
118
-	 * @inheritDoc
119
-	 */
120
-	public function getMountByStorageId($storageId) {
121
-		return $this->__call(__FUNCTION__, func_get_args());
122
-	}
123
-
124
-	/**
125
-	 * @inheritDoc
126
-	 */
127
-	public function getMountByNumericStorageId($numericId) {
128
-		return $this->__call(__FUNCTION__, func_get_args());
129
-	}
130
-
131
-	/**
132
-	 * @inheritDoc
133
-	 */
134
-	public function unMount($mount) {
135
-		$this->__call(__FUNCTION__, func_get_args());
136
-	}
137
-
138
-	/**
139
-	 * @inheritDoc
140
-	 */
141
-	public function get($path) {
142
-		return $this->__call(__FUNCTION__, func_get_args());
143
-	}
144
-
145
-	/**
146
-	 * @inheritDoc
147
-	 */
148
-	public function rename($targetPath) {
149
-		return $this->__call(__FUNCTION__, func_get_args());
150
-	}
151
-
152
-	/**
153
-	 * @inheritDoc
154
-	 */
155
-	public function delete() {
156
-		return $this->__call(__FUNCTION__, func_get_args());
157
-	}
158
-
159
-	/**
160
-	 * @inheritDoc
161
-	 */
162
-	public function copy($targetPath) {
163
-		return $this->__call(__FUNCTION__, func_get_args());
164
-	}
165
-
166
-	/**
167
-	 * @inheritDoc
168
-	 */
169
-	public function touch($mtime = null) {
170
-		$this->__call(__FUNCTION__, func_get_args());
171
-	}
172
-
173
-	/**
174
-	 * @inheritDoc
175
-	 */
176
-	public function getStorage() {
177
-		return $this->__call(__FUNCTION__, func_get_args());
178
-	}
179
-
180
-	/**
181
-	 * @inheritDoc
182
-	 */
183
-	public function getPath() {
184
-		return $this->__call(__FUNCTION__, func_get_args());
185
-	}
186
-
187
-	/**
188
-	 * @inheritDoc
189
-	 */
190
-	public function getInternalPath() {
191
-		return $this->__call(__FUNCTION__, func_get_args());
192
-	}
193
-
194
-	/**
195
-	 * @inheritDoc
196
-	 */
197
-	public function getId() {
198
-		return $this->__call(__FUNCTION__, func_get_args());
199
-	}
200
-
201
-	/**
202
-	 * @inheritDoc
203
-	 */
204
-	public function stat() {
205
-		return $this->__call(__FUNCTION__, func_get_args());
206
-	}
207
-
208
-	/**
209
-	 * @inheritDoc
210
-	 */
211
-	public function getMTime() {
212
-		return $this->__call(__FUNCTION__, func_get_args());
213
-	}
214
-
215
-	/**
216
-	 * @inheritDoc
217
-	 */
218
-	public function getSize() {
219
-		return $this->__call(__FUNCTION__, func_get_args());
220
-	}
221
-
222
-	/**
223
-	 * @inheritDoc
224
-	 */
225
-	public function getEtag() {
226
-		return $this->__call(__FUNCTION__, func_get_args());
227
-	}
228
-
229
-	/**
230
-	 * @inheritDoc
231
-	 */
232
-	public function getPermissions() {
233
-		return $this->__call(__FUNCTION__, func_get_args());
234
-	}
235
-
236
-	/**
237
-	 * @inheritDoc
238
-	 */
239
-	public function isReadable() {
240
-		return $this->__call(__FUNCTION__, func_get_args());
241
-	}
242
-
243
-	/**
244
-	 * @inheritDoc
245
-	 */
246
-	public function isUpdateable() {
247
-		return $this->__call(__FUNCTION__, func_get_args());
248
-	}
249
-
250
-	/**
251
-	 * @inheritDoc
252
-	 */
253
-	public function isDeletable() {
254
-		return $this->__call(__FUNCTION__, func_get_args());
255
-	}
256
-
257
-	/**
258
-	 * @inheritDoc
259
-	 */
260
-	public function isShareable() {
261
-		return $this->__call(__FUNCTION__, func_get_args());
262
-	}
263
-
264
-	/**
265
-	 * @inheritDoc
266
-	 */
267
-	public function getParent() {
268
-		return $this->__call(__FUNCTION__, func_get_args());
269
-	}
270
-
271
-	/**
272
-	 * @inheritDoc
273
-	 */
274
-	public function getName() {
275
-		return $this->__call(__FUNCTION__, func_get_args());
276
-	}
277
-
278
-	/**
279
-	 * @inheritDoc
280
-	 */
281
-	public function getUserFolder($userId) {
282
-		return $this->__call(__FUNCTION__, func_get_args());
283
-	}
284
-
285
-	/**
286
-	 * @inheritDoc
287
-	 */
288
-	public function getMimetype() {
289
-		return $this->__call(__FUNCTION__, func_get_args());
290
-	}
291
-
292
-	/**
293
-	 * @inheritDoc
294
-	 */
295
-	public function getMimePart() {
296
-		return $this->__call(__FUNCTION__, func_get_args());
297
-	}
298
-
299
-	/**
300
-	 * @inheritDoc
301
-	 */
302
-	public function isEncrypted() {
303
-		return $this->__call(__FUNCTION__, func_get_args());
304
-	}
305
-
306
-	/**
307
-	 * @inheritDoc
308
-	 */
309
-	public function getType() {
310
-		return $this->__call(__FUNCTION__, func_get_args());
311
-	}
312
-
313
-	/**
314
-	 * @inheritDoc
315
-	 */
316
-	public function isShared() {
317
-		return $this->__call(__FUNCTION__, func_get_args());
318
-	}
319
-
320
-	/**
321
-	 * @inheritDoc
322
-	 */
323
-	public function isMounted() {
324
-		return $this->__call(__FUNCTION__, func_get_args());
325
-	}
326
-
327
-	/**
328
-	 * @inheritDoc
329
-	 */
330
-	public function getMountPoint() {
331
-		return $this->__call(__FUNCTION__, func_get_args());
332
-	}
333
-
334
-	/**
335
-	 * @inheritDoc
336
-	 */
337
-	public function getOwner() {
338
-		return $this->__call(__FUNCTION__, func_get_args());
339
-	}
340
-
341
-	/**
342
-	 * @inheritDoc
343
-	 */
344
-	public function getChecksum() {
345
-		return $this->__call(__FUNCTION__, func_get_args());
346
-	}
347
-
348
-	/**
349
-	 * @inheritDoc
350
-	 */
351
-	public function getFullPath($path) {
352
-		return $this->__call(__FUNCTION__, func_get_args());
353
-	}
354
-
355
-	/**
356
-	 * @inheritDoc
357
-	 */
358
-	public function getRelativePath($path) {
359
-		return $this->__call(__FUNCTION__, func_get_args());
360
-	}
361
-
362
-	/**
363
-	 * @inheritDoc
364
-	 */
365
-	public function isSubNode($node) {
366
-		return $this->__call(__FUNCTION__, func_get_args());
367
-	}
368
-
369
-	/**
370
-	 * @inheritDoc
371
-	 */
372
-	public function getDirectoryListing() {
373
-		return $this->__call(__FUNCTION__, func_get_args());
374
-	}
375
-
376
-	/**
377
-	 * @inheritDoc
378
-	 */
379
-	public function nodeExists($path) {
380
-		return $this->__call(__FUNCTION__, func_get_args());
381
-	}
382
-
383
-	/**
384
-	 * @inheritDoc
385
-	 */
386
-	public function newFolder($path) {
387
-		return $this->__call(__FUNCTION__, func_get_args());
388
-	}
389
-
390
-	/**
391
-	 * @inheritDoc
392
-	 */
393
-	public function newFile($path) {
394
-		return $this->__call(__FUNCTION__, func_get_args());
395
-	}
396
-
397
-	/**
398
-	 * @inheritDoc
399
-	 */
400
-	public function search($query) {
401
-		return $this->__call(__FUNCTION__, func_get_args());
402
-	}
403
-
404
-	/**
405
-	 * @inheritDoc
406
-	 */
407
-	public function searchByMime($mimetype) {
408
-		return $this->__call(__FUNCTION__, func_get_args());
409
-	}
410
-
411
-	/**
412
-	 * @inheritDoc
413
-	 */
414
-	public function searchByTag($tag, $userId) {
415
-		return $this->__call(__FUNCTION__, func_get_args());
416
-	}
417
-
418
-	/**
419
-	 * @inheritDoc
420
-	 */
421
-	public function getById($id) {
422
-		return $this->__call(__FUNCTION__, func_get_args());
423
-	}
424
-
425
-	/**
426
-	 * @inheritDoc
427
-	 */
428
-	public function getFreeSpace() {
429
-		return $this->__call(__FUNCTION__, func_get_args());
430
-	}
431
-
432
-	/**
433
-	 * @inheritDoc
434
-	 */
435
-	public function isCreatable() {
436
-		return $this->__call(__FUNCTION__, func_get_args());
437
-	}
438
-
439
-	/**
440
-	 * @inheritDoc
441
-	 */
442
-	public function getNonExistingName($name) {
443
-		return $this->__call(__FUNCTION__, func_get_args());
444
-	}
445
-
446
-	/**
447
-	 * @inheritDoc
448
-	 */
449
-	public function move($targetPath) {
450
-		return $this->__call(__FUNCTION__, func_get_args());
451
-	}
452
-
453
-	/**
454
-	 * @inheritDoc
455
-	 */
456
-	public function lock($type) {
457
-		return $this->__call(__FUNCTION__, func_get_args());
458
-	}
459
-
460
-	/**
461
-	 * @inheritDoc
462
-	 */
463
-	public function changeLock($targetType) {
464
-		return $this->__call(__FUNCTION__, func_get_args());
465
-	}
466
-
467
-	/**
468
-	 * @inheritDoc
469
-	 */
470
-	public function unlock($type) {
471
-		return $this->__call(__FUNCTION__, func_get_args());
472
-	}
473
-
474
-	/**
475
-	 * @inheritDoc
476
-	 */
477
-	public function getRecent($limit, $offset = 0) {
478
-		return $this->__call(__FUNCTION__, func_get_args());
479
-	}
37
+    /** @var \Closure */
38
+    private $rootFolderClosure;
39
+
40
+    /** @var IRootFolder */
41
+    private $rootFolder;
42
+
43
+    /**
44
+     * LazyRoot constructor.
45
+     *
46
+     * @param \Closure $rootFolderClosure
47
+     */
48
+    public function __construct(\Closure $rootFolderClosure) {
49
+        $this->rootFolderClosure = $rootFolderClosure;
50
+    }
51
+
52
+    /**
53
+     * Magic method to first get the real rootFolder and then
54
+     * call $method with $args on it
55
+     *
56
+     * @param $method
57
+     * @param $args
58
+     * @return mixed
59
+     */
60
+    public function __call($method, $args) {
61
+        if ($this->rootFolder === null) {
62
+            $this->rootFolder = call_user_func($this->rootFolderClosure);
63
+        }
64
+
65
+        return call_user_func_array([$this->rootFolder, $method], $args);
66
+    }
67
+
68
+    /**
69
+     * @inheritDoc
70
+     */
71
+    public function getUser() {
72
+        return $this->__call(__FUNCTION__, func_get_args());
73
+    }
74
+
75
+    /**
76
+     * @inheritDoc
77
+     */
78
+    public function listen($scope, $method, callable $callback) {
79
+        $this->__call(__FUNCTION__, func_get_args());
80
+    }
81
+
82
+    /**
83
+     * @inheritDoc
84
+     */
85
+    public function removeListener($scope = null, $method = null, callable $callback = null) {
86
+        $this->__call(__FUNCTION__, func_get_args());
87
+    }
88
+
89
+    /**
90
+     * @inheritDoc
91
+     */
92
+    public function emit($scope, $method, $arguments = array()) {
93
+        $this->__call(__FUNCTION__, func_get_args());
94
+    }
95
+
96
+    /**
97
+     * @inheritDoc
98
+     */
99
+    public function mount($storage, $mountPoint, $arguments = array()) {
100
+        $this->__call(__FUNCTION__, func_get_args());
101
+    }
102
+
103
+    /**
104
+     * @inheritDoc
105
+     */
106
+    public function getMount($mountPoint) {
107
+        return $this->__call(__FUNCTION__, func_get_args());
108
+    }
109
+
110
+    /**
111
+     * @inheritDoc
112
+     */
113
+    public function getMountsIn($mountPoint) {
114
+        return $this->__call(__FUNCTION__, func_get_args());
115
+    }
116
+
117
+    /**
118
+     * @inheritDoc
119
+     */
120
+    public function getMountByStorageId($storageId) {
121
+        return $this->__call(__FUNCTION__, func_get_args());
122
+    }
123
+
124
+    /**
125
+     * @inheritDoc
126
+     */
127
+    public function getMountByNumericStorageId($numericId) {
128
+        return $this->__call(__FUNCTION__, func_get_args());
129
+    }
130
+
131
+    /**
132
+     * @inheritDoc
133
+     */
134
+    public function unMount($mount) {
135
+        $this->__call(__FUNCTION__, func_get_args());
136
+    }
137
+
138
+    /**
139
+     * @inheritDoc
140
+     */
141
+    public function get($path) {
142
+        return $this->__call(__FUNCTION__, func_get_args());
143
+    }
144
+
145
+    /**
146
+     * @inheritDoc
147
+     */
148
+    public function rename($targetPath) {
149
+        return $this->__call(__FUNCTION__, func_get_args());
150
+    }
151
+
152
+    /**
153
+     * @inheritDoc
154
+     */
155
+    public function delete() {
156
+        return $this->__call(__FUNCTION__, func_get_args());
157
+    }
158
+
159
+    /**
160
+     * @inheritDoc
161
+     */
162
+    public function copy($targetPath) {
163
+        return $this->__call(__FUNCTION__, func_get_args());
164
+    }
165
+
166
+    /**
167
+     * @inheritDoc
168
+     */
169
+    public function touch($mtime = null) {
170
+        $this->__call(__FUNCTION__, func_get_args());
171
+    }
172
+
173
+    /**
174
+     * @inheritDoc
175
+     */
176
+    public function getStorage() {
177
+        return $this->__call(__FUNCTION__, func_get_args());
178
+    }
179
+
180
+    /**
181
+     * @inheritDoc
182
+     */
183
+    public function getPath() {
184
+        return $this->__call(__FUNCTION__, func_get_args());
185
+    }
186
+
187
+    /**
188
+     * @inheritDoc
189
+     */
190
+    public function getInternalPath() {
191
+        return $this->__call(__FUNCTION__, func_get_args());
192
+    }
193
+
194
+    /**
195
+     * @inheritDoc
196
+     */
197
+    public function getId() {
198
+        return $this->__call(__FUNCTION__, func_get_args());
199
+    }
200
+
201
+    /**
202
+     * @inheritDoc
203
+     */
204
+    public function stat() {
205
+        return $this->__call(__FUNCTION__, func_get_args());
206
+    }
207
+
208
+    /**
209
+     * @inheritDoc
210
+     */
211
+    public function getMTime() {
212
+        return $this->__call(__FUNCTION__, func_get_args());
213
+    }
214
+
215
+    /**
216
+     * @inheritDoc
217
+     */
218
+    public function getSize() {
219
+        return $this->__call(__FUNCTION__, func_get_args());
220
+    }
221
+
222
+    /**
223
+     * @inheritDoc
224
+     */
225
+    public function getEtag() {
226
+        return $this->__call(__FUNCTION__, func_get_args());
227
+    }
228
+
229
+    /**
230
+     * @inheritDoc
231
+     */
232
+    public function getPermissions() {
233
+        return $this->__call(__FUNCTION__, func_get_args());
234
+    }
235
+
236
+    /**
237
+     * @inheritDoc
238
+     */
239
+    public function isReadable() {
240
+        return $this->__call(__FUNCTION__, func_get_args());
241
+    }
242
+
243
+    /**
244
+     * @inheritDoc
245
+     */
246
+    public function isUpdateable() {
247
+        return $this->__call(__FUNCTION__, func_get_args());
248
+    }
249
+
250
+    /**
251
+     * @inheritDoc
252
+     */
253
+    public function isDeletable() {
254
+        return $this->__call(__FUNCTION__, func_get_args());
255
+    }
256
+
257
+    /**
258
+     * @inheritDoc
259
+     */
260
+    public function isShareable() {
261
+        return $this->__call(__FUNCTION__, func_get_args());
262
+    }
263
+
264
+    /**
265
+     * @inheritDoc
266
+     */
267
+    public function getParent() {
268
+        return $this->__call(__FUNCTION__, func_get_args());
269
+    }
270
+
271
+    /**
272
+     * @inheritDoc
273
+     */
274
+    public function getName() {
275
+        return $this->__call(__FUNCTION__, func_get_args());
276
+    }
277
+
278
+    /**
279
+     * @inheritDoc
280
+     */
281
+    public function getUserFolder($userId) {
282
+        return $this->__call(__FUNCTION__, func_get_args());
283
+    }
284
+
285
+    /**
286
+     * @inheritDoc
287
+     */
288
+    public function getMimetype() {
289
+        return $this->__call(__FUNCTION__, func_get_args());
290
+    }
291
+
292
+    /**
293
+     * @inheritDoc
294
+     */
295
+    public function getMimePart() {
296
+        return $this->__call(__FUNCTION__, func_get_args());
297
+    }
298
+
299
+    /**
300
+     * @inheritDoc
301
+     */
302
+    public function isEncrypted() {
303
+        return $this->__call(__FUNCTION__, func_get_args());
304
+    }
305
+
306
+    /**
307
+     * @inheritDoc
308
+     */
309
+    public function getType() {
310
+        return $this->__call(__FUNCTION__, func_get_args());
311
+    }
312
+
313
+    /**
314
+     * @inheritDoc
315
+     */
316
+    public function isShared() {
317
+        return $this->__call(__FUNCTION__, func_get_args());
318
+    }
319
+
320
+    /**
321
+     * @inheritDoc
322
+     */
323
+    public function isMounted() {
324
+        return $this->__call(__FUNCTION__, func_get_args());
325
+    }
326
+
327
+    /**
328
+     * @inheritDoc
329
+     */
330
+    public function getMountPoint() {
331
+        return $this->__call(__FUNCTION__, func_get_args());
332
+    }
333
+
334
+    /**
335
+     * @inheritDoc
336
+     */
337
+    public function getOwner() {
338
+        return $this->__call(__FUNCTION__, func_get_args());
339
+    }
340
+
341
+    /**
342
+     * @inheritDoc
343
+     */
344
+    public function getChecksum() {
345
+        return $this->__call(__FUNCTION__, func_get_args());
346
+    }
347
+
348
+    /**
349
+     * @inheritDoc
350
+     */
351
+    public function getFullPath($path) {
352
+        return $this->__call(__FUNCTION__, func_get_args());
353
+    }
354
+
355
+    /**
356
+     * @inheritDoc
357
+     */
358
+    public function getRelativePath($path) {
359
+        return $this->__call(__FUNCTION__, func_get_args());
360
+    }
361
+
362
+    /**
363
+     * @inheritDoc
364
+     */
365
+    public function isSubNode($node) {
366
+        return $this->__call(__FUNCTION__, func_get_args());
367
+    }
368
+
369
+    /**
370
+     * @inheritDoc
371
+     */
372
+    public function getDirectoryListing() {
373
+        return $this->__call(__FUNCTION__, func_get_args());
374
+    }
375
+
376
+    /**
377
+     * @inheritDoc
378
+     */
379
+    public function nodeExists($path) {
380
+        return $this->__call(__FUNCTION__, func_get_args());
381
+    }
382
+
383
+    /**
384
+     * @inheritDoc
385
+     */
386
+    public function newFolder($path) {
387
+        return $this->__call(__FUNCTION__, func_get_args());
388
+    }
389
+
390
+    /**
391
+     * @inheritDoc
392
+     */
393
+    public function newFile($path) {
394
+        return $this->__call(__FUNCTION__, func_get_args());
395
+    }
396
+
397
+    /**
398
+     * @inheritDoc
399
+     */
400
+    public function search($query) {
401
+        return $this->__call(__FUNCTION__, func_get_args());
402
+    }
403
+
404
+    /**
405
+     * @inheritDoc
406
+     */
407
+    public function searchByMime($mimetype) {
408
+        return $this->__call(__FUNCTION__, func_get_args());
409
+    }
410
+
411
+    /**
412
+     * @inheritDoc
413
+     */
414
+    public function searchByTag($tag, $userId) {
415
+        return $this->__call(__FUNCTION__, func_get_args());
416
+    }
417
+
418
+    /**
419
+     * @inheritDoc
420
+     */
421
+    public function getById($id) {
422
+        return $this->__call(__FUNCTION__, func_get_args());
423
+    }
424
+
425
+    /**
426
+     * @inheritDoc
427
+     */
428
+    public function getFreeSpace() {
429
+        return $this->__call(__FUNCTION__, func_get_args());
430
+    }
431
+
432
+    /**
433
+     * @inheritDoc
434
+     */
435
+    public function isCreatable() {
436
+        return $this->__call(__FUNCTION__, func_get_args());
437
+    }
438
+
439
+    /**
440
+     * @inheritDoc
441
+     */
442
+    public function getNonExistingName($name) {
443
+        return $this->__call(__FUNCTION__, func_get_args());
444
+    }
445
+
446
+    /**
447
+     * @inheritDoc
448
+     */
449
+    public function move($targetPath) {
450
+        return $this->__call(__FUNCTION__, func_get_args());
451
+    }
452
+
453
+    /**
454
+     * @inheritDoc
455
+     */
456
+    public function lock($type) {
457
+        return $this->__call(__FUNCTION__, func_get_args());
458
+    }
459
+
460
+    /**
461
+     * @inheritDoc
462
+     */
463
+    public function changeLock($targetType) {
464
+        return $this->__call(__FUNCTION__, func_get_args());
465
+    }
466
+
467
+    /**
468
+     * @inheritDoc
469
+     */
470
+    public function unlock($type) {
471
+        return $this->__call(__FUNCTION__, func_get_args());
472
+    }
473
+
474
+    /**
475
+     * @inheritDoc
476
+     */
477
+    public function getRecent($limit, $offset = 0) {
478
+        return $this->__call(__FUNCTION__, func_get_args());
479
+    }
480 480
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Flysystem.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -54,6 +54,9 @@
 block discarded – undo
54 54
 		$this->flysystem->addPlugin(new GetWithMetadata());
55 55
 	}
56 56
 
57
+	/**
58
+	 * @param string $path
59
+	 */
57 60
 	protected function buildPath($path) {
58 61
 		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
59 62
 		return ltrim($fullPath, '/');
Please login to merge, or discard this patch.
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -35,223 +35,223 @@
 block discarded – undo
35 35
  * To use: subclass and call $this->buildFlysystem with the flysystem adapter of choice
36 36
  */
37 37
 abstract class Flysystem extends Common {
38
-	/**
39
-	 * @var Filesystem
40
-	 */
41
-	protected $flysystem;
38
+    /**
39
+     * @var Filesystem
40
+     */
41
+    protected $flysystem;
42 42
 
43
-	/**
44
-	 * @var string
45
-	 */
46
-	protected $root = '';
43
+    /**
44
+     * @var string
45
+     */
46
+    protected $root = '';
47 47
 
48
-	/**
49
-	 * Initialize the storage backend with a flyssytem adapter
50
-	 *
51
-	 * @param \League\Flysystem\AdapterInterface $adapter
52
-	 */
53
-	protected function buildFlySystem(AdapterInterface $adapter) {
54
-		$this->flysystem = new Filesystem($adapter);
55
-		$this->flysystem->addPlugin(new GetWithMetadata());
56
-	}
48
+    /**
49
+     * Initialize the storage backend with a flyssytem adapter
50
+     *
51
+     * @param \League\Flysystem\AdapterInterface $adapter
52
+     */
53
+    protected function buildFlySystem(AdapterInterface $adapter) {
54
+        $this->flysystem = new Filesystem($adapter);
55
+        $this->flysystem->addPlugin(new GetWithMetadata());
56
+    }
57 57
 
58
-	protected function buildPath($path) {
59
-		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
60
-		return ltrim($fullPath, '/');
61
-	}
58
+    protected function buildPath($path) {
59
+        $fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
60
+        return ltrim($fullPath, '/');
61
+    }
62 62
 
63
-	/**
64
-	 * {@inheritdoc}
65
-	 */
66
-	public function file_get_contents($path) {
67
-		return $this->flysystem->read($this->buildPath($path));
68
-	}
63
+    /**
64
+     * {@inheritdoc}
65
+     */
66
+    public function file_get_contents($path) {
67
+        return $this->flysystem->read($this->buildPath($path));
68
+    }
69 69
 
70
-	/**
71
-	 * {@inheritdoc}
72
-	 */
73
-	public function file_put_contents($path, $data) {
74
-		return $this->flysystem->put($this->buildPath($path), $data);
75
-	}
70
+    /**
71
+     * {@inheritdoc}
72
+     */
73
+    public function file_put_contents($path, $data) {
74
+        return $this->flysystem->put($this->buildPath($path), $data);
75
+    }
76 76
 
77
-	/**
78
-	 * {@inheritdoc}
79
-	 */
80
-	public function file_exists($path) {
81
-		return $this->flysystem->has($this->buildPath($path));
82
-	}
77
+    /**
78
+     * {@inheritdoc}
79
+     */
80
+    public function file_exists($path) {
81
+        return $this->flysystem->has($this->buildPath($path));
82
+    }
83 83
 
84
-	/**
85
-	 * {@inheritdoc}
86
-	 */
87
-	public function unlink($path) {
88
-		if ($this->is_dir($path)) {
89
-			return $this->rmdir($path);
90
-		}
91
-		try {
92
-			return $this->flysystem->delete($this->buildPath($path));
93
-		} catch (FileNotFoundException $e) {
94
-			return false;
95
-		}
96
-	}
84
+    /**
85
+     * {@inheritdoc}
86
+     */
87
+    public function unlink($path) {
88
+        if ($this->is_dir($path)) {
89
+            return $this->rmdir($path);
90
+        }
91
+        try {
92
+            return $this->flysystem->delete($this->buildPath($path));
93
+        } catch (FileNotFoundException $e) {
94
+            return false;
95
+        }
96
+    }
97 97
 
98
-	/**
99
-	 * {@inheritdoc}
100
-	 */
101
-	public function rename($source, $target) {
102
-		if ($this->file_exists($target)) {
103
-			$this->unlink($target);
104
-		}
105
-		return $this->flysystem->rename($this->buildPath($source), $this->buildPath($target));
106
-	}
98
+    /**
99
+     * {@inheritdoc}
100
+     */
101
+    public function rename($source, $target) {
102
+        if ($this->file_exists($target)) {
103
+            $this->unlink($target);
104
+        }
105
+        return $this->flysystem->rename($this->buildPath($source), $this->buildPath($target));
106
+    }
107 107
 
108
-	/**
109
-	 * {@inheritdoc}
110
-	 */
111
-	public function copy($source, $target) {
112
-		if ($this->file_exists($target)) {
113
-			$this->unlink($target);
114
-		}
115
-		return $this->flysystem->copy($this->buildPath($source), $this->buildPath($target));
116
-	}
108
+    /**
109
+     * {@inheritdoc}
110
+     */
111
+    public function copy($source, $target) {
112
+        if ($this->file_exists($target)) {
113
+            $this->unlink($target);
114
+        }
115
+        return $this->flysystem->copy($this->buildPath($source), $this->buildPath($target));
116
+    }
117 117
 
118
-	/**
119
-	 * {@inheritdoc}
120
-	 */
121
-	public function filesize($path) {
122
-		if ($this->is_dir($path)) {
123
-			return 0;
124
-		} else {
125
-			return $this->flysystem->getSize($this->buildPath($path));
126
-		}
127
-	}
118
+    /**
119
+     * {@inheritdoc}
120
+     */
121
+    public function filesize($path) {
122
+        if ($this->is_dir($path)) {
123
+            return 0;
124
+        } else {
125
+            return $this->flysystem->getSize($this->buildPath($path));
126
+        }
127
+    }
128 128
 
129
-	/**
130
-	 * {@inheritdoc}
131
-	 */
132
-	public function mkdir($path) {
133
-		if ($this->file_exists($path)) {
134
-			return false;
135
-		}
136
-		return $this->flysystem->createDir($this->buildPath($path));
137
-	}
129
+    /**
130
+     * {@inheritdoc}
131
+     */
132
+    public function mkdir($path) {
133
+        if ($this->file_exists($path)) {
134
+            return false;
135
+        }
136
+        return $this->flysystem->createDir($this->buildPath($path));
137
+    }
138 138
 
139
-	/**
140
-	 * {@inheritdoc}
141
-	 */
142
-	public function filemtime($path) {
143
-		return $this->flysystem->getTimestamp($this->buildPath($path));
144
-	}
139
+    /**
140
+     * {@inheritdoc}
141
+     */
142
+    public function filemtime($path) {
143
+        return $this->flysystem->getTimestamp($this->buildPath($path));
144
+    }
145 145
 
146
-	/**
147
-	 * {@inheritdoc}
148
-	 */
149
-	public function rmdir($path) {
150
-		try {
151
-			return @$this->flysystem->deleteDir($this->buildPath($path));
152
-		} catch (FileNotFoundException $e) {
153
-			return false;
154
-		}
155
-	}
146
+    /**
147
+     * {@inheritdoc}
148
+     */
149
+    public function rmdir($path) {
150
+        try {
151
+            return @$this->flysystem->deleteDir($this->buildPath($path));
152
+        } catch (FileNotFoundException $e) {
153
+            return false;
154
+        }
155
+    }
156 156
 
157
-	/**
158
-	 * {@inheritdoc}
159
-	 */
160
-	public function opendir($path) {
161
-		try {
162
-			$content = $this->flysystem->listContents($this->buildPath($path));
163
-		} catch (FileNotFoundException $e) {
164
-			return false;
165
-		}
166
-		$names = array_map(function ($object) {
167
-			return $object['basename'];
168
-		}, $content);
169
-		return IteratorDirectory::wrap($names);
170
-	}
157
+    /**
158
+     * {@inheritdoc}
159
+     */
160
+    public function opendir($path) {
161
+        try {
162
+            $content = $this->flysystem->listContents($this->buildPath($path));
163
+        } catch (FileNotFoundException $e) {
164
+            return false;
165
+        }
166
+        $names = array_map(function ($object) {
167
+            return $object['basename'];
168
+        }, $content);
169
+        return IteratorDirectory::wrap($names);
170
+    }
171 171
 
172
-	/**
173
-	 * {@inheritdoc}
174
-	 */
175
-	public function fopen($path, $mode) {
176
-		$fullPath = $this->buildPath($path);
177
-		$useExisting = true;
178
-		switch ($mode) {
179
-			case 'r':
180
-			case 'rb':
181
-				try {
182
-					return $this->flysystem->readStream($fullPath);
183
-				} catch (FileNotFoundException $e) {
184
-					return false;
185
-				}
186
-			case 'w':
187
-			case 'w+':
188
-			case 'wb':
189
-			case 'wb+':
190
-				$useExisting = false;
191
-			case 'a':
192
-			case 'ab':
193
-			case 'r+':
194
-			case 'a+':
195
-			case 'x':
196
-			case 'x+':
197
-			case 'c':
198
-			case 'c+':
199
-				//emulate these
200
-				if ($useExisting and $this->file_exists($path)) {
201
-					if (!$this->isUpdatable($path)) {
202
-						return false;
203
-					}
204
-					$tmpFile = $this->getCachedFile($path);
205
-				} else {
206
-					if (!$this->isCreatable(dirname($path))) {
207
-						return false;
208
-					}
209
-					$tmpFile = \OCP\Files::tmpFile();
210
-				}
211
-				$source = fopen($tmpFile, $mode);
212
-				return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
213
-					$this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214
-					unlink($tmpFile);
215
-				});
216
-		}
217
-		return false;
218
-	}
172
+    /**
173
+     * {@inheritdoc}
174
+     */
175
+    public function fopen($path, $mode) {
176
+        $fullPath = $this->buildPath($path);
177
+        $useExisting = true;
178
+        switch ($mode) {
179
+            case 'r':
180
+            case 'rb':
181
+                try {
182
+                    return $this->flysystem->readStream($fullPath);
183
+                } catch (FileNotFoundException $e) {
184
+                    return false;
185
+                }
186
+            case 'w':
187
+            case 'w+':
188
+            case 'wb':
189
+            case 'wb+':
190
+                $useExisting = false;
191
+            case 'a':
192
+            case 'ab':
193
+            case 'r+':
194
+            case 'a+':
195
+            case 'x':
196
+            case 'x+':
197
+            case 'c':
198
+            case 'c+':
199
+                //emulate these
200
+                if ($useExisting and $this->file_exists($path)) {
201
+                    if (!$this->isUpdatable($path)) {
202
+                        return false;
203
+                    }
204
+                    $tmpFile = $this->getCachedFile($path);
205
+                } else {
206
+                    if (!$this->isCreatable(dirname($path))) {
207
+                        return false;
208
+                    }
209
+                    $tmpFile = \OCP\Files::tmpFile();
210
+                }
211
+                $source = fopen($tmpFile, $mode);
212
+                return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
213
+                    $this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214
+                    unlink($tmpFile);
215
+                });
216
+        }
217
+        return false;
218
+    }
219 219
 
220
-	/**
221
-	 * {@inheritdoc}
222
-	 */
223
-	public function touch($path, $mtime = null) {
224
-		if ($this->file_exists($path)) {
225
-			return false;
226
-		} else {
227
-			$this->file_put_contents($path, '');
228
-			return true;
229
-		}
230
-	}
220
+    /**
221
+     * {@inheritdoc}
222
+     */
223
+    public function touch($path, $mtime = null) {
224
+        if ($this->file_exists($path)) {
225
+            return false;
226
+        } else {
227
+            $this->file_put_contents($path, '');
228
+            return true;
229
+        }
230
+    }
231 231
 
232
-	/**
233
-	 * {@inheritdoc}
234
-	 */
235
-	public function stat($path) {
236
-		$info = $this->flysystem->getWithMetadata($this->buildPath($path), ['timestamp', 'size']);
237
-		return [
238
-			'mtime' => $info['timestamp'],
239
-			'size' => $info['size']
240
-		];
241
-	}
232
+    /**
233
+     * {@inheritdoc}
234
+     */
235
+    public function stat($path) {
236
+        $info = $this->flysystem->getWithMetadata($this->buildPath($path), ['timestamp', 'size']);
237
+        return [
238
+            'mtime' => $info['timestamp'],
239
+            'size' => $info['size']
240
+        ];
241
+    }
242 242
 
243
-	/**
244
-	 * {@inheritdoc}
245
-	 */
246
-	public function filetype($path) {
247
-		if ($path === '' or $path === '/' or $path === '.') {
248
-			return 'dir';
249
-		}
250
-		try {
251
-			$info = $this->flysystem->getMetadata($this->buildPath($path));
252
-		} catch (FileNotFoundException $e) {
253
-			return false;
254
-		}
255
-		return $info['type'];
256
-	}
243
+    /**
244
+     * {@inheritdoc}
245
+     */
246
+    public function filetype($path) {
247
+        if ($path === '' or $path === '/' or $path === '.') {
248
+            return 'dir';
249
+        }
250
+        try {
251
+            $info = $this->flysystem->getMetadata($this->buildPath($path));
252
+        } catch (FileNotFoundException $e) {
253
+            return false;
254
+        }
255
+        return $info['type'];
256
+    }
257 257
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 	}
57 57
 
58 58
 	protected function buildPath($path) {
59
-		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
59
+		$fullPath = \OC\Files\Filesystem::normalizePath($this->root.'/'.$path);
60 60
 		return ltrim($fullPath, '/');
61 61
 	}
62 62
 
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		} catch (FileNotFoundException $e) {
164 164
 			return false;
165 165
 		}
166
-		$names = array_map(function ($object) {
166
+		$names = array_map(function($object) {
167 167
 			return $object['basename'];
168 168
 		}, $content);
169 169
 		return IteratorDirectory::wrap($names);
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 					$tmpFile = \OCP\Files::tmpFile();
210 210
 				}
211 211
 				$source = fopen($tmpFile, $mode);
212
-				return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
212
+				return CallbackWrapper::wrap($source, null, null, function() use ($tmpFile, $fullPath) {
213 213
 					$this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214 214
 					unlink($tmpFile);
215 215
 				});
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Quota.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -159,7 +159,7 @@
 block discarded – undo
159 159
 	 * Checks whether the given path is a part file
160 160
 	 *
161 161
 	 * @param string $path Path that may identify a .part file
162
-	 * @return string File path without .part extension
162
+	 * @return boolean File path without .part extension
163 163
 	 * @note this is needed for reusing keys
164 164
 	 */
165 165
 	private function isPartFile($path) {
Please login to merge, or discard this patch.
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -30,172 +30,172 @@
 block discarded – undo
30 30
 
31 31
 class Quota extends Wrapper {
32 32
 
33
-	/**
34
-	 * @var int $quota
35
-	 */
36
-	protected $quota;
37
-
38
-	/**
39
-	 * @var string $sizeRoot
40
-	 */
41
-	protected $sizeRoot;
42
-
43
-	/**
44
-	 * @param array $parameters
45
-	 */
46
-	public function __construct($parameters) {
47
-		$this->storage = $parameters['storage'];
48
-		$this->quota = $parameters['quota'];
49
-		$this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
50
-	}
51
-
52
-	/**
53
-	 * @return int quota value
54
-	 */
55
-	public function getQuota() {
56
-		return $this->quota;
57
-	}
58
-
59
-	/**
60
-	 * @param string $path
61
-	 * @param \OC\Files\Storage\Storage $storage
62
-	 */
63
-	protected function getSize($path, $storage = null) {
64
-		if (is_null($storage)) {
65
-			$cache = $this->getCache();
66
-		} else {
67
-			$cache = $storage->getCache();
68
-		}
69
-		$data = $cache->get($path);
70
-		if ($data instanceof ICacheEntry and isset($data['size'])) {
71
-			return $data['size'];
72
-		} else {
73
-			return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
74
-		}
75
-	}
76
-
77
-	/**
78
-	 * Get free space as limited by the quota
79
-	 *
80
-	 * @param string $path
81
-	 * @return int
82
-	 */
83
-	public function free_space($path) {
84
-		if ($this->quota < 0) {
85
-			return $this->storage->free_space($path);
86
-		} else {
87
-			$used = $this->getSize($this->sizeRoot);
88
-			if ($used < 0) {
89
-				return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
90
-			} else {
91
-				$free = $this->storage->free_space($path);
92
-				$quotaFree = max($this->quota - $used, 0);
93
-				// if free space is known
94
-				if ($free >= 0) {
95
-					$free = min($free, $quotaFree);
96
-				} else {
97
-					$free = $quotaFree;
98
-				}
99
-				return $free;
100
-			}
101
-		}
102
-	}
103
-
104
-	/**
105
-	 * see http://php.net/manual/en/function.file_put_contents.php
106
-	 *
107
-	 * @param string $path
108
-	 * @param string $data
109
-	 * @return bool
110
-	 */
111
-	public function file_put_contents($path, $data) {
112
-		$free = $this->free_space('');
113
-		if ($free < 0 or strlen($data) < $free) {
114
-			return $this->storage->file_put_contents($path, $data);
115
-		} else {
116
-			return false;
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * see http://php.net/manual/en/function.copy.php
122
-	 *
123
-	 * @param string $source
124
-	 * @param string $target
125
-	 * @return bool
126
-	 */
127
-	public function copy($source, $target) {
128
-		$free = $this->free_space('');
129
-		if ($free < 0 or $this->getSize($source) < $free) {
130
-			return $this->storage->copy($source, $target);
131
-		} else {
132
-			return false;
133
-		}
134
-	}
135
-
136
-	/**
137
-	 * see http://php.net/manual/en/function.fopen.php
138
-	 *
139
-	 * @param string $path
140
-	 * @param string $mode
141
-	 * @return resource
142
-	 */
143
-	public function fopen($path, $mode) {
144
-		$source = $this->storage->fopen($path, $mode);
145
-
146
-		// don't apply quota for part files
147
-		if (!$this->isPartFile($path)) {
148
-			$free = $this->free_space('');
149
-			if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
150
-				// only apply quota for files, not metadata, trash or others
151
-				if (strpos(ltrim($path, '/'), 'files/') === 0) {
152
-					return \OC\Files\Stream\Quota::wrap($source, $free);
153
-				}
154
-			}
155
-		}
156
-		return $source;
157
-	}
158
-
159
-	/**
160
-	 * Checks whether the given path is a part file
161
-	 *
162
-	 * @param string $path Path that may identify a .part file
163
-	 * @return string File path without .part extension
164
-	 * @note this is needed for reusing keys
165
-	 */
166
-	private function isPartFile($path) {
167
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
168
-
169
-		return ($extension === 'part');
170
-	}
171
-
172
-	/**
173
-	 * @param \OCP\Files\Storage $sourceStorage
174
-	 * @param string $sourceInternalPath
175
-	 * @param string $targetInternalPath
176
-	 * @return bool
177
-	 */
178
-	public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
179
-		$free = $this->free_space('');
180
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
181
-			return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
182
-		} else {
183
-			return false;
184
-		}
185
-	}
186
-
187
-	/**
188
-	 * @param \OCP\Files\Storage $sourceStorage
189
-	 * @param string $sourceInternalPath
190
-	 * @param string $targetInternalPath
191
-	 * @return bool
192
-	 */
193
-	public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
194
-		$free = $this->free_space('');
195
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
196
-			return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
197
-		} else {
198
-			return false;
199
-		}
200
-	}
33
+    /**
34
+     * @var int $quota
35
+     */
36
+    protected $quota;
37
+
38
+    /**
39
+     * @var string $sizeRoot
40
+     */
41
+    protected $sizeRoot;
42
+
43
+    /**
44
+     * @param array $parameters
45
+     */
46
+    public function __construct($parameters) {
47
+        $this->storage = $parameters['storage'];
48
+        $this->quota = $parameters['quota'];
49
+        $this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
50
+    }
51
+
52
+    /**
53
+     * @return int quota value
54
+     */
55
+    public function getQuota() {
56
+        return $this->quota;
57
+    }
58
+
59
+    /**
60
+     * @param string $path
61
+     * @param \OC\Files\Storage\Storage $storage
62
+     */
63
+    protected function getSize($path, $storage = null) {
64
+        if (is_null($storage)) {
65
+            $cache = $this->getCache();
66
+        } else {
67
+            $cache = $storage->getCache();
68
+        }
69
+        $data = $cache->get($path);
70
+        if ($data instanceof ICacheEntry and isset($data['size'])) {
71
+            return $data['size'];
72
+        } else {
73
+            return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
74
+        }
75
+    }
76
+
77
+    /**
78
+     * Get free space as limited by the quota
79
+     *
80
+     * @param string $path
81
+     * @return int
82
+     */
83
+    public function free_space($path) {
84
+        if ($this->quota < 0) {
85
+            return $this->storage->free_space($path);
86
+        } else {
87
+            $used = $this->getSize($this->sizeRoot);
88
+            if ($used < 0) {
89
+                return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
90
+            } else {
91
+                $free = $this->storage->free_space($path);
92
+                $quotaFree = max($this->quota - $used, 0);
93
+                // if free space is known
94
+                if ($free >= 0) {
95
+                    $free = min($free, $quotaFree);
96
+                } else {
97
+                    $free = $quotaFree;
98
+                }
99
+                return $free;
100
+            }
101
+        }
102
+    }
103
+
104
+    /**
105
+     * see http://php.net/manual/en/function.file_put_contents.php
106
+     *
107
+     * @param string $path
108
+     * @param string $data
109
+     * @return bool
110
+     */
111
+    public function file_put_contents($path, $data) {
112
+        $free = $this->free_space('');
113
+        if ($free < 0 or strlen($data) < $free) {
114
+            return $this->storage->file_put_contents($path, $data);
115
+        } else {
116
+            return false;
117
+        }
118
+    }
119
+
120
+    /**
121
+     * see http://php.net/manual/en/function.copy.php
122
+     *
123
+     * @param string $source
124
+     * @param string $target
125
+     * @return bool
126
+     */
127
+    public function copy($source, $target) {
128
+        $free = $this->free_space('');
129
+        if ($free < 0 or $this->getSize($source) < $free) {
130
+            return $this->storage->copy($source, $target);
131
+        } else {
132
+            return false;
133
+        }
134
+    }
135
+
136
+    /**
137
+     * see http://php.net/manual/en/function.fopen.php
138
+     *
139
+     * @param string $path
140
+     * @param string $mode
141
+     * @return resource
142
+     */
143
+    public function fopen($path, $mode) {
144
+        $source = $this->storage->fopen($path, $mode);
145
+
146
+        // don't apply quota for part files
147
+        if (!$this->isPartFile($path)) {
148
+            $free = $this->free_space('');
149
+            if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
150
+                // only apply quota for files, not metadata, trash or others
151
+                if (strpos(ltrim($path, '/'), 'files/') === 0) {
152
+                    return \OC\Files\Stream\Quota::wrap($source, $free);
153
+                }
154
+            }
155
+        }
156
+        return $source;
157
+    }
158
+
159
+    /**
160
+     * Checks whether the given path is a part file
161
+     *
162
+     * @param string $path Path that may identify a .part file
163
+     * @return string File path without .part extension
164
+     * @note this is needed for reusing keys
165
+     */
166
+    private function isPartFile($path) {
167
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
168
+
169
+        return ($extension === 'part');
170
+    }
171
+
172
+    /**
173
+     * @param \OCP\Files\Storage $sourceStorage
174
+     * @param string $sourceInternalPath
175
+     * @param string $targetInternalPath
176
+     * @return bool
177
+     */
178
+    public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
179
+        $free = $this->free_space('');
180
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
181
+            return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
182
+        } else {
183
+            return false;
184
+        }
185
+    }
186
+
187
+    /**
188
+     * @param \OCP\Files\Storage $sourceStorage
189
+     * @param string $sourceInternalPath
190
+     * @param string $targetInternalPath
191
+     * @return bool
192
+     */
193
+    public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
194
+        $free = $this->free_space('');
195
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
196
+            return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
197
+        } else {
198
+            return false;
199
+        }
200
+    }
201 201
 }
Please login to merge, or discard this patch.
lib/private/L10N/L10N.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -176,7 +176,7 @@
 block discarded – undo
176 176
 	 * Returns an associative array with all translations
177 177
 	 *
178 178
 	 * Called by \OC_L10N_String
179
-	 * @return array
179
+	 * @return string[]
180 180
 	 */
181 181
 	public function getTranslations() {
182 182
 		return $this->translations;
Please login to merge, or discard this patch.
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -28,190 +28,190 @@
 block discarded – undo
28 28
 
29 29
 class L10N implements IL10N {
30 30
 
31
-	/** @var IFactory */
32
-	protected $factory;
33
-
34
-	/** @var string App of this object */
35
-	protected $app;
36
-
37
-	/** @var string Language of this object */
38
-	protected $lang;
39
-
40
-	/** @var string Plural forms (string) */
41
-	private $pluralFormString = 'nplurals=2; plural=(n != 1);';
42
-
43
-	/** @var string Plural forms (function) */
44
-	private $pluralFormFunction = null;
45
-
46
-	/** @var string[] */
47
-	private $translations = [];
48
-
49
-	/**
50
-	 * @param IFactory $factory
51
-	 * @param string $app
52
-	 * @param string $lang
53
-	 * @param array $files
54
-	 */
55
-	public function __construct(IFactory $factory, $app, $lang, array $files) {
56
-		$this->factory = $factory;
57
-		$this->app = $app;
58
-		$this->lang = $lang;
59
-
60
-		$this->translations = [];
61
-		foreach ($files as $languageFile) {
62
-			$this->load($languageFile);
63
-		}
64
-	}
65
-
66
-	/**
67
-	 * The code (en, de, ...) of the language that is used for this instance
68
-	 *
69
-	 * @return string language
70
-	 */
71
-	public function getLanguageCode() {
72
-		return $this->lang;
73
-	}
74
-
75
-	/**
76
-	 * Translating
77
-	 * @param string $text The text we need a translation for
78
-	 * @param array $parameters default:array() Parameters for sprintf
79
-	 * @return string Translation or the same text
80
-	 *
81
-	 * Returns the translation. If no translation is found, $text will be
82
-	 * returned.
83
-	 */
84
-	public function t($text, $parameters = array()) {
85
-		return (string) new \OC_L10N_String($this, $text, $parameters);
86
-	}
87
-
88
-	/**
89
-	 * Translating
90
-	 * @param string $text_singular the string to translate for exactly one object
91
-	 * @param string $text_plural the string to translate for n objects
92
-	 * @param integer $count Number of objects
93
-	 * @param array $parameters default:array() Parameters for sprintf
94
-	 * @return string Translation or the same text
95
-	 *
96
-	 * Returns the translation. If no translation is found, $text will be
97
-	 * returned. %n will be replaced with the number of objects.
98
-	 *
99
-	 * The correct plural is determined by the plural_forms-function
100
-	 * provided by the po file.
101
-	 *
102
-	 */
103
-	public function n($text_singular, $text_plural, $count, $parameters = array()) {
104
-		$identifier = "_${text_singular}_::_${text_plural}_";
105
-		if (isset($this->translations[$identifier])) {
106
-			return (string) new \OC_L10N_String($this, $identifier, $parameters, $count);
107
-		} else {
108
-			if ($count === 1) {
109
-				return (string) new \OC_L10N_String($this, $text_singular, $parameters, $count);
110
-			} else {
111
-				return (string) new \OC_L10N_String($this, $text_plural, $parameters, $count);
112
-			}
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * Localization
118
-	 * @param string $type Type of localization
119
-	 * @param \DateTime|int|string $data parameters for this localization
120
-	 * @param array $options
121
-	 * @return string|int|false
122
-	 *
123
-	 * Returns the localized data.
124
-	 *
125
-	 * Implemented types:
126
-	 *  - date
127
-	 *    - Creates a date
128
-	 *    - params: timestamp (int/string)
129
-	 *  - datetime
130
-	 *    - Creates date and time
131
-	 *    - params: timestamp (int/string)
132
-	 *  - time
133
-	 *    - Creates a time
134
-	 *    - params: timestamp (int/string)
135
-	 *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
136
-	 *  - jsdate: Returns the short JS date format
137
-	 */
138
-	public function l($type, $data = null, $options = array()) {
139
-		// Use the language of the instance
140
-		$locale = $this->getLanguageCode();
141
-		if ($locale === 'sr@latin') {
142
-			$locale = 'sr_latn';
143
-		}
144
-
145
-		if ($type === 'firstday') {
146
-			return (int) Calendar::getFirstWeekday($locale);
147
-		}
148
-		if ($type === 'jsdate') {
149
-			return (string) Calendar::getDateFormat('short', $locale);
150
-		}
151
-
152
-		$value = new \DateTime();
153
-		if ($data instanceof \DateTime) {
154
-			$value = $data;
155
-		} else if (is_string($data) && !is_numeric($data)) {
156
-			$data = strtotime($data);
157
-			$value->setTimestamp($data);
158
-		} else if ($data !== null) {
159
-			$value->setTimestamp($data);
160
-		}
161
-
162
-		$options = array_merge(array('width' => 'long'), $options);
163
-		$width = $options['width'];
164
-		switch ($type) {
165
-			case 'date':
166
-				return (string) Calendar::formatDate($value, $width, $locale);
167
-			case 'datetime':
168
-				return (string) Calendar::formatDatetime($value, $width, $locale);
169
-			case 'time':
170
-				return (string) Calendar::formatTime($value, $width, $locale);
171
-			default:
172
-				return false;
173
-		}
174
-	}
175
-
176
-	/**
177
-	 * Returns an associative array with all translations
178
-	 *
179
-	 * Called by \OC_L10N_String
180
-	 * @return array
181
-	 */
182
-	public function getTranslations() {
183
-		return $this->translations;
184
-	}
185
-
186
-	/**
187
-	 * Returnsed function accepts the argument $n
188
-	 *
189
-	 * Called by \OC_L10N_String
190
-	 * @return string the plural form function
191
-	 */
192
-	public function getPluralFormFunction() {
193
-		if (is_null($this->pluralFormFunction)) {
194
-			$this->pluralFormFunction = $this->factory->createPluralFunction($this->pluralFormString);
195
-		}
196
-		return $this->pluralFormFunction;
197
-	}
198
-
199
-	/**
200
-	 * @param $translationFile
201
-	 * @return bool
202
-	 */
203
-	protected function load($translationFile) {
204
-		$json = json_decode(file_get_contents($translationFile), true);
205
-		if (!is_array($json)) {
206
-			$jsonError = json_last_error();
207
-			\OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
208
-			return false;
209
-		}
210
-
211
-		if (!empty($json['pluralForm'])) {
212
-			$this->pluralFormString = $json['pluralForm'];
213
-		}
214
-		$this->translations = array_merge($this->translations, $json['translations']);
215
-		return true;
216
-	}
31
+    /** @var IFactory */
32
+    protected $factory;
33
+
34
+    /** @var string App of this object */
35
+    protected $app;
36
+
37
+    /** @var string Language of this object */
38
+    protected $lang;
39
+
40
+    /** @var string Plural forms (string) */
41
+    private $pluralFormString = 'nplurals=2; plural=(n != 1);';
42
+
43
+    /** @var string Plural forms (function) */
44
+    private $pluralFormFunction = null;
45
+
46
+    /** @var string[] */
47
+    private $translations = [];
48
+
49
+    /**
50
+     * @param IFactory $factory
51
+     * @param string $app
52
+     * @param string $lang
53
+     * @param array $files
54
+     */
55
+    public function __construct(IFactory $factory, $app, $lang, array $files) {
56
+        $this->factory = $factory;
57
+        $this->app = $app;
58
+        $this->lang = $lang;
59
+
60
+        $this->translations = [];
61
+        foreach ($files as $languageFile) {
62
+            $this->load($languageFile);
63
+        }
64
+    }
65
+
66
+    /**
67
+     * The code (en, de, ...) of the language that is used for this instance
68
+     *
69
+     * @return string language
70
+     */
71
+    public function getLanguageCode() {
72
+        return $this->lang;
73
+    }
74
+
75
+    /**
76
+     * Translating
77
+     * @param string $text The text we need a translation for
78
+     * @param array $parameters default:array() Parameters for sprintf
79
+     * @return string Translation or the same text
80
+     *
81
+     * Returns the translation. If no translation is found, $text will be
82
+     * returned.
83
+     */
84
+    public function t($text, $parameters = array()) {
85
+        return (string) new \OC_L10N_String($this, $text, $parameters);
86
+    }
87
+
88
+    /**
89
+     * Translating
90
+     * @param string $text_singular the string to translate for exactly one object
91
+     * @param string $text_plural the string to translate for n objects
92
+     * @param integer $count Number of objects
93
+     * @param array $parameters default:array() Parameters for sprintf
94
+     * @return string Translation or the same text
95
+     *
96
+     * Returns the translation. If no translation is found, $text will be
97
+     * returned. %n will be replaced with the number of objects.
98
+     *
99
+     * The correct plural is determined by the plural_forms-function
100
+     * provided by the po file.
101
+     *
102
+     */
103
+    public function n($text_singular, $text_plural, $count, $parameters = array()) {
104
+        $identifier = "_${text_singular}_::_${text_plural}_";
105
+        if (isset($this->translations[$identifier])) {
106
+            return (string) new \OC_L10N_String($this, $identifier, $parameters, $count);
107
+        } else {
108
+            if ($count === 1) {
109
+                return (string) new \OC_L10N_String($this, $text_singular, $parameters, $count);
110
+            } else {
111
+                return (string) new \OC_L10N_String($this, $text_plural, $parameters, $count);
112
+            }
113
+        }
114
+    }
115
+
116
+    /**
117
+     * Localization
118
+     * @param string $type Type of localization
119
+     * @param \DateTime|int|string $data parameters for this localization
120
+     * @param array $options
121
+     * @return string|int|false
122
+     *
123
+     * Returns the localized data.
124
+     *
125
+     * Implemented types:
126
+     *  - date
127
+     *    - Creates a date
128
+     *    - params: timestamp (int/string)
129
+     *  - datetime
130
+     *    - Creates date and time
131
+     *    - params: timestamp (int/string)
132
+     *  - time
133
+     *    - Creates a time
134
+     *    - params: timestamp (int/string)
135
+     *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
136
+     *  - jsdate: Returns the short JS date format
137
+     */
138
+    public function l($type, $data = null, $options = array()) {
139
+        // Use the language of the instance
140
+        $locale = $this->getLanguageCode();
141
+        if ($locale === 'sr@latin') {
142
+            $locale = 'sr_latn';
143
+        }
144
+
145
+        if ($type === 'firstday') {
146
+            return (int) Calendar::getFirstWeekday($locale);
147
+        }
148
+        if ($type === 'jsdate') {
149
+            return (string) Calendar::getDateFormat('short', $locale);
150
+        }
151
+
152
+        $value = new \DateTime();
153
+        if ($data instanceof \DateTime) {
154
+            $value = $data;
155
+        } else if (is_string($data) && !is_numeric($data)) {
156
+            $data = strtotime($data);
157
+            $value->setTimestamp($data);
158
+        } else if ($data !== null) {
159
+            $value->setTimestamp($data);
160
+        }
161
+
162
+        $options = array_merge(array('width' => 'long'), $options);
163
+        $width = $options['width'];
164
+        switch ($type) {
165
+            case 'date':
166
+                return (string) Calendar::formatDate($value, $width, $locale);
167
+            case 'datetime':
168
+                return (string) Calendar::formatDatetime($value, $width, $locale);
169
+            case 'time':
170
+                return (string) Calendar::formatTime($value, $width, $locale);
171
+            default:
172
+                return false;
173
+        }
174
+    }
175
+
176
+    /**
177
+     * Returns an associative array with all translations
178
+     *
179
+     * Called by \OC_L10N_String
180
+     * @return array
181
+     */
182
+    public function getTranslations() {
183
+        return $this->translations;
184
+    }
185
+
186
+    /**
187
+     * Returnsed function accepts the argument $n
188
+     *
189
+     * Called by \OC_L10N_String
190
+     * @return string the plural form function
191
+     */
192
+    public function getPluralFormFunction() {
193
+        if (is_null($this->pluralFormFunction)) {
194
+            $this->pluralFormFunction = $this->factory->createPluralFunction($this->pluralFormString);
195
+        }
196
+        return $this->pluralFormFunction;
197
+    }
198
+
199
+    /**
200
+     * @param $translationFile
201
+     * @return bool
202
+     */
203
+    protected function load($translationFile) {
204
+        $json = json_decode(file_get_contents($translationFile), true);
205
+        if (!is_array($json)) {
206
+            $jsonError = json_last_error();
207
+            \OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
208
+            return false;
209
+        }
210
+
211
+        if (!empty($json['pluralForm'])) {
212
+            $this->pluralFormString = $json['pluralForm'];
213
+        }
214
+        $this->translations = array_merge($this->translations, $json['translations']);
215
+        return true;
216
+    }
217 217
 }
Please login to merge, or discard this patch.
lib/private/legacy/api.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -331,7 +331,7 @@
 block discarded – undo
331 331
 
332 332
 	/**
333 333
 	 * http basic auth
334
-	 * @return string|false (username, or false on failure)
334
+	 * @return string (username, or false on failure)
335 335
 	 */
336 336
 	private static function loginUser() {
337 337
 		if(self::$isLoggedIn === true) {
Please login to merge, or discard this patch.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 				$requirements = array()) {
93 93
 		$name = strtolower($method).$url;
94 94
 		$name = str_replace(array('/', '{', '}'), '_', $name);
95
-		if(!isset(self::$actions[$name])) {
95
+		if (!isset(self::$actions[$name])) {
96 96
 			$oldCollection = OC::$server->getRouter()->getCurrentCollection();
97 97
 			OC::$server->getRouter()->useCollection('ocs');
98 98
 			OC::$server->getRouter()->create($name, $url)
@@ -115,17 +115,17 @@  discard block
 block discarded – undo
115 115
 		$method = $request->getMethod();
116 116
 
117 117
 		// Prepare the request variables
118
-		if($method === 'PUT') {
118
+		if ($method === 'PUT') {
119 119
 			$parameters['_put'] = $request->getParams();
120
-		} else if($method === 'DELETE') {
120
+		} else if ($method === 'DELETE') {
121 121
 			$parameters['_delete'] = $request->getParams();
122 122
 		}
123 123
 		$name = $parameters['_route'];
124 124
 		// Foreach registered action
125 125
 		$responses = array();
126
-		foreach(self::$actions[$name] as $action) {
126
+		foreach (self::$actions[$name] as $action) {
127 127
 			// Check authentication and availability
128
-			if(!self::isAuthorised($action)) {
128
+			if (!self::isAuthorised($action)) {
129 129
 				$responses[] = array(
130 130
 					'app' => $action['app'],
131 131
 					'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 					);
134 134
 				continue;
135 135
 			}
136
-			if(!is_callable($action['action'])) {
136
+			if (!is_callable($action['action'])) {
137 137
 				$responses[] = array(
138 138
 					'app' => $action['app'],
139 139
 					'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
@@ -173,15 +173,15 @@  discard block
 block discarded – undo
173 173
 			'failed' => array(),
174 174
 			);
175 175
 
176
-		foreach($responses as $response) {
177
-			if($response['shipped'] || ($response['app'] === 'core')) {
178
-				if($response['response']->succeeded()) {
176
+		foreach ($responses as $response) {
177
+			if ($response['shipped'] || ($response['app'] === 'core')) {
178
+				if ($response['response']->succeeded()) {
179 179
 					$shipped['succeeded'][$response['app']] = $response;
180 180
 				} else {
181 181
 					$shipped['failed'][$response['app']] = $response;
182 182
 				}
183 183
 			} else {
184
-				if($response['response']->succeeded()) {
184
+				if ($response['response']->succeeded()) {
185 185
 					$thirdparty['succeeded'][$response['app']] = $response;
186 186
 				} else {
187 187
 					$thirdparty['failed'][$response['app']] = $response;
@@ -190,14 +190,14 @@  discard block
 block discarded – undo
190 190
 		}
191 191
 
192 192
 		// Remove any error responses if there is one shipped response that succeeded
193
-		if(!empty($shipped['failed'])) {
193
+		if (!empty($shipped['failed'])) {
194 194
 			// Which shipped response do we use if they all failed?
195 195
 			// They may have failed for different reasons (different status codes)
196 196
 			// Which response code should we return?
197 197
 			// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
198 198
 			// Merge failed responses if more than one
199 199
 			$data = array();
200
-			foreach($shipped['failed'] as $failure) {
200
+			foreach ($shipped['failed'] as $failure) {
201 201
 				$data = array_merge_recursive($data, $failure['response']->getData());
202 202
 			}
203 203
 			$picked = reset($shipped['failed']);
@@ -206,12 +206,12 @@  discard block
 block discarded – undo
206 206
 			$headers = $picked['response']->getHeaders();
207 207
 			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
208 208
 			return $response;
209
-		} elseif(!empty($shipped['succeeded'])) {
209
+		} elseif (!empty($shipped['succeeded'])) {
210 210
 			$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
211
-		} elseif(!empty($thirdparty['failed'])) {
211
+		} elseif (!empty($thirdparty['failed'])) {
212 212
 			// Merge failed responses if more than one
213 213
 			$data = array();
214
-			foreach($thirdparty['failed'] as $failure) {
214
+			foreach ($thirdparty['failed'] as $failure) {
215 215
 				$data = array_merge_recursive($data, $failure['response']->getData());
216 216
 			}
217 217
 			$picked = reset($thirdparty['failed']);
@@ -228,8 +228,8 @@  discard block
 block discarded – undo
228 228
 		$codes = [];
229 229
 		$header = [];
230 230
 
231
-		foreach($responses as $response) {
232
-			if($response['shipped']) {
231
+		foreach ($responses as $response) {
232
+			if ($response['shipped']) {
233 233
 				$data = array_merge_recursive($response['response']->getData(), $data);
234 234
 			} else {
235 235
 				$data = array_merge_recursive($data, $response['response']->getData());
@@ -242,8 +242,8 @@  discard block
 block discarded – undo
242 242
 		// Use any non 100 status codes
243 243
 		$statusCode = 100;
244 244
 		$statusMessage = null;
245
-		foreach($codes as $code) {
246
-			if($code['code'] != 100) {
245
+		foreach ($codes as $code) {
246
+			if ($code['code'] != 100) {
247 247
 				$statusCode = $code['code'];
248 248
 				$statusMessage = $code['meta']['message'];
249 249
 				break;
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
 	 */
261 261
 	private static function isAuthorised($action) {
262 262
 		$level = $action['authlevel'];
263
-		switch($level) {
263
+		switch ($level) {
264 264
 			case API::GUEST_AUTH:
265 265
 				// Anyone can access
266 266
 				return true;
@@ -270,16 +270,16 @@  discard block
 block discarded – undo
270 270
 			case API::SUBADMIN_AUTH:
271 271
 				// Check for subadmin
272 272
 				$user = self::loginUser();
273
-				if(!$user) {
273
+				if (!$user) {
274 274
 					return false;
275 275
 				} else {
276 276
 					$userObject = \OC::$server->getUserSession()->getUser();
277
-					if($userObject === null) {
277
+					if ($userObject === null) {
278 278
 						return false;
279 279
 					}
280 280
 					$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
281 281
 					$admin = OC_User::isAdminUser($user);
282
-					if($isSubAdmin || $admin) {
282
+					if ($isSubAdmin || $admin) {
283 283
 						return true;
284 284
 					} else {
285 285
 						return false;
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 			case API::ADMIN_AUTH:
289 289
 				// Check for admin
290 290
 				$user = self::loginUser();
291
-				if(!$user) {
291
+				if (!$user) {
292 292
 					return false;
293 293
 				} else {
294 294
 					return OC_User::isAdminUser($user);
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
 	 * @return string|false (username, or false on failure)
305 305
 	 */
306 306
 	private static function loginUser() {
307
-		if(self::$isLoggedIn === true) {
307
+		if (self::$isLoggedIn === true) {
308 308
 			return \OC_User::getUser();
309 309
 		}
310 310
 
@@ -358,13 +358,13 @@  discard block
 block discarded – undo
358 358
 	 * @param OC_OCS_Result $result
359 359
 	 * @param string $format the format xml|json
360 360
 	 */
361
-	public static function respond($result, $format='xml') {
361
+	public static function respond($result, $format = 'xml') {
362 362
 		$request = \OC::$server->getRequest();
363 363
 
364 364
 		// Send 401 headers if unauthorised
365
-		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
365
+		if ($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
366 366
 			// If request comes from JS return dummy auth request
367
-			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
367
+			if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
368 368
 				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
369 369
 			} else {
370 370
 				header('WWW-Authenticate: Basic realm="Authorisation Required"');
@@ -372,8 +372,8 @@  discard block
 block discarded – undo
372 372
 			header('HTTP/1.0 401 Unauthorized');
373 373
 		}
374 374
 
375
-		foreach($result->getHeaders() as $name => $value) {
376
-			header($name . ': ' . $value);
375
+		foreach ($result->getHeaders() as $name => $value) {
376
+			header($name.': '.$value);
377 377
 		}
378 378
 
379 379
 		$meta = $result->getMeta();
@@ -395,14 +395,14 @@  discard block
 block discarded – undo
395 395
 	 * @param XMLWriter $writer
396 396
 	 */
397 397
 	private static function toXML($array, $writer) {
398
-		foreach($array as $k => $v) {
398
+		foreach ($array as $k => $v) {
399 399
 			if ($k[0] === '@') {
400 400
 				$writer->writeAttribute(substr($k, 1), $v);
401 401
 				continue;
402 402
 			} else if (is_numeric($k)) {
403 403
 				$k = 'element';
404 404
 			}
405
-			if(is_array($v)) {
405
+			if (is_array($v)) {
406 406
 				$writer->startElement($k);
407 407
 				self::toXML($v, $writer);
408 408
 				$writer->endElement();
Please login to merge, or discard this patch.
Indentation   +458 added lines, -458 removed lines patch added patch discarded remove patch
@@ -37,462 +37,462 @@
 block discarded – undo
37 37
 
38 38
 class OC_API {
39 39
 
40
-	/**
41
-	 * API authentication levels
42
-	 */
43
-
44
-	/** @deprecated Use \OCP\API::GUEST_AUTH instead */
45
-	const GUEST_AUTH = 0;
46
-
47
-	/** @deprecated Use \OCP\API::USER_AUTH instead */
48
-	const USER_AUTH = 1;
49
-
50
-	/** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
51
-	const SUBADMIN_AUTH = 2;
52
-
53
-	/** @deprecated Use \OCP\API::ADMIN_AUTH instead */
54
-	const ADMIN_AUTH = 3;
55
-
56
-	/**
57
-	 * API Response Codes
58
-	 */
59
-
60
-	/** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
61
-	const RESPOND_UNAUTHORISED = 997;
62
-
63
-	/** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
64
-	const RESPOND_SERVER_ERROR = 996;
65
-
66
-	/** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
67
-	const RESPOND_NOT_FOUND = 998;
68
-
69
-	/** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
70
-	const RESPOND_UNKNOWN_ERROR = 999;
71
-
72
-	/**
73
-	 * api actions
74
-	 */
75
-	protected static $actions = array();
76
-	private static $logoutRequired = false;
77
-	private static $isLoggedIn = false;
78
-
79
-	/**
80
-	 * registers an api call
81
-	 * @param string $method the http method
82
-	 * @param string $url the url to match
83
-	 * @param callable $action the function to run
84
-	 * @param string $app the id of the app registering the call
85
-	 * @param int $authLevel the level of authentication required for the call
86
-	 * @param array $defaults
87
-	 * @param array $requirements
88
-	 */
89
-	public static function register($method, $url, $action, $app,
90
-				$authLevel = API::USER_AUTH,
91
-				$defaults = array(),
92
-				$requirements = array()) {
93
-		$name = strtolower($method).$url;
94
-		$name = str_replace(array('/', '{', '}'), '_', $name);
95
-		if(!isset(self::$actions[$name])) {
96
-			$oldCollection = OC::$server->getRouter()->getCurrentCollection();
97
-			OC::$server->getRouter()->useCollection('ocs');
98
-			OC::$server->getRouter()->create($name, $url)
99
-				->method($method)
100
-				->defaults($defaults)
101
-				->requirements($requirements)
102
-				->action('OC_API', 'call');
103
-			self::$actions[$name] = array();
104
-			OC::$server->getRouter()->useCollection($oldCollection);
105
-		}
106
-		self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
107
-	}
108
-
109
-	/**
110
-	 * handles an api call
111
-	 * @param array $parameters
112
-	 */
113
-	public static function call($parameters) {
114
-		$request = \OC::$server->getRequest();
115
-		$method = $request->getMethod();
116
-
117
-		// Prepare the request variables
118
-		if($method === 'PUT') {
119
-			$parameters['_put'] = $request->getParams();
120
-		} else if($method === 'DELETE') {
121
-			$parameters['_delete'] = $request->getParams();
122
-		}
123
-		$name = $parameters['_route'];
124
-		// Foreach registered action
125
-		$responses = array();
126
-		foreach(self::$actions[$name] as $action) {
127
-			// Check authentication and availability
128
-			if(!self::isAuthorised($action)) {
129
-				$responses[] = array(
130
-					'app' => $action['app'],
131
-					'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
132
-					'shipped' => OC_App::isShipped($action['app']),
133
-					);
134
-				continue;
135
-			}
136
-			if(!is_callable($action['action'])) {
137
-				$responses[] = array(
138
-					'app' => $action['app'],
139
-					'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
140
-					'shipped' => OC_App::isShipped($action['app']),
141
-					);
142
-				continue;
143
-			}
144
-			// Run the action
145
-			$responses[] = array(
146
-				'app' => $action['app'],
147
-				'response' => call_user_func($action['action'], $parameters),
148
-				'shipped' => OC_App::isShipped($action['app']),
149
-				);
150
-		}
151
-		$response = self::mergeResponses($responses);
152
-		$format = self::requestedFormat();
153
-		if (self::$logoutRequired) {
154
-			\OC::$server->getUserSession()->logout();
155
-		}
156
-
157
-		self::respond($response, $format);
158
-	}
159
-
160
-	/**
161
-	 * merge the returned result objects into one response
162
-	 * @param array $responses
163
-	 * @return OC_OCS_Result
164
-	 */
165
-	public static function mergeResponses($responses) {
166
-		// Sort into shipped and third-party
167
-		$shipped = array(
168
-			'succeeded' => array(),
169
-			'failed' => array(),
170
-			);
171
-		$thirdparty = array(
172
-			'succeeded' => array(),
173
-			'failed' => array(),
174
-			);
175
-
176
-		foreach($responses as $response) {
177
-			if($response['shipped'] || ($response['app'] === 'core')) {
178
-				if($response['response']->succeeded()) {
179
-					$shipped['succeeded'][$response['app']] = $response;
180
-				} else {
181
-					$shipped['failed'][$response['app']] = $response;
182
-				}
183
-			} else {
184
-				if($response['response']->succeeded()) {
185
-					$thirdparty['succeeded'][$response['app']] = $response;
186
-				} else {
187
-					$thirdparty['failed'][$response['app']] = $response;
188
-				}
189
-			}
190
-		}
191
-
192
-		// Remove any error responses if there is one shipped response that succeeded
193
-		if(!empty($shipped['failed'])) {
194
-			// Which shipped response do we use if they all failed?
195
-			// They may have failed for different reasons (different status codes)
196
-			// Which response code should we return?
197
-			// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
198
-			// Merge failed responses if more than one
199
-			$data = array();
200
-			foreach($shipped['failed'] as $failure) {
201
-				$data = array_merge_recursive($data, $failure['response']->getData());
202
-			}
203
-			$picked = reset($shipped['failed']);
204
-			$code = $picked['response']->getStatusCode();
205
-			$meta = $picked['response']->getMeta();
206
-			$headers = $picked['response']->getHeaders();
207
-			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
208
-			return $response;
209
-		} elseif(!empty($shipped['succeeded'])) {
210
-			$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
211
-		} elseif(!empty($thirdparty['failed'])) {
212
-			// Merge failed responses if more than one
213
-			$data = array();
214
-			foreach($thirdparty['failed'] as $failure) {
215
-				$data = array_merge_recursive($data, $failure['response']->getData());
216
-			}
217
-			$picked = reset($thirdparty['failed']);
218
-			$code = $picked['response']->getStatusCode();
219
-			$meta = $picked['response']->getMeta();
220
-			$headers = $picked['response']->getHeaders();
221
-			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
222
-			return $response;
223
-		} else {
224
-			$responses = $thirdparty['succeeded'];
225
-		}
226
-		// Merge the successful responses
227
-		$data = [];
228
-		$codes = [];
229
-		$header = [];
230
-
231
-		foreach($responses as $response) {
232
-			if($response['shipped']) {
233
-				$data = array_merge_recursive($response['response']->getData(), $data);
234
-			} else {
235
-				$data = array_merge_recursive($data, $response['response']->getData());
236
-			}
237
-			$header = array_merge_recursive($header, $response['response']->getHeaders());
238
-			$codes[] = ['code' => $response['response']->getStatusCode(),
239
-				'meta' => $response['response']->getMeta()];
240
-		}
241
-
242
-		// Use any non 100 status codes
243
-		$statusCode = 100;
244
-		$statusMessage = null;
245
-		foreach($codes as $code) {
246
-			if($code['code'] != 100) {
247
-				$statusCode = $code['code'];
248
-				$statusMessage = $code['meta']['message'];
249
-				break;
250
-			}
251
-		}
252
-
253
-		return new OC_OCS_Result($data, $statusCode, $statusMessage, $header);
254
-	}
255
-
256
-	/**
257
-	 * authenticate the api call
258
-	 * @param array $action the action details as supplied to OC_API::register()
259
-	 * @return bool
260
-	 */
261
-	private static function isAuthorised($action) {
262
-		$level = $action['authlevel'];
263
-		switch($level) {
264
-			case API::GUEST_AUTH:
265
-				// Anyone can access
266
-				return true;
267
-			case API::USER_AUTH:
268
-				// User required
269
-				return self::loginUser();
270
-			case API::SUBADMIN_AUTH:
271
-				// Check for subadmin
272
-				$user = self::loginUser();
273
-				if(!$user) {
274
-					return false;
275
-				} else {
276
-					$userObject = \OC::$server->getUserSession()->getUser();
277
-					if($userObject === null) {
278
-						return false;
279
-					}
280
-					$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
281
-					$admin = OC_User::isAdminUser($user);
282
-					if($isSubAdmin || $admin) {
283
-						return true;
284
-					} else {
285
-						return false;
286
-					}
287
-				}
288
-			case API::ADMIN_AUTH:
289
-				// Check for admin
290
-				$user = self::loginUser();
291
-				if(!$user) {
292
-					return false;
293
-				} else {
294
-					return OC_User::isAdminUser($user);
295
-				}
296
-			default:
297
-				// oops looks like invalid level supplied
298
-				return false;
299
-		}
300
-	}
301
-
302
-	/**
303
-	 * http basic auth
304
-	 * @return string|false (username, or false on failure)
305
-	 */
306
-	private static function loginUser() {
307
-		if(self::$isLoggedIn === true) {
308
-			return \OC_User::getUser();
309
-		}
310
-
311
-		// reuse existing login
312
-		$loggedIn = \OC::$server->getUserSession()->isLoggedIn();
313
-		if ($loggedIn === true) {
314
-			if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
315
-				// Do not allow access to OCS until the 2FA challenge was solved successfully
316
-				return false;
317
-			}
318
-			$ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
319
-			if ($ocsApiRequest) {
320
-
321
-				// initialize the user's filesystem
322
-				\OC_Util::setupFS(\OC_User::getUser());
323
-				self::$isLoggedIn = true;
324
-
325
-				return OC_User::getUser();
326
-			}
327
-			return false;
328
-		}
329
-
330
-		// basic auth - because OC_User::login will create a new session we shall only try to login
331
-		// if user and pass are set
332
-		$userSession = \OC::$server->getUserSession();
333
-		$request = \OC::$server->getRequest();
334
-		try {
335
-			if ($userSession->tryTokenLogin($request)
336
-				|| $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
337
-				self::$logoutRequired = true;
338
-			} else {
339
-				return false;
340
-			}
341
-			// initialize the user's filesystem
342
-			\OC_Util::setupFS(\OC_User::getUser());
343
-			self::$isLoggedIn = true;
344
-
345
-			return \OC_User::getUser();
346
-		} catch (\OC\User\LoginException $e) {
347
-			return false;
348
-		}
349
-	}
350
-
351
-	/**
352
-	 * respond to a call
353
-	 * @param OC_OCS_Result $result
354
-	 * @param string $format the format xml|json
355
-	 */
356
-	public static function respond($result, $format='xml') {
357
-		$request = \OC::$server->getRequest();
358
-
359
-		// Send 401 headers if unauthorised
360
-		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
361
-			// If request comes from JS return dummy auth request
362
-			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
363
-				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
364
-			} else {
365
-				header('WWW-Authenticate: Basic realm="Authorisation Required"');
366
-			}
367
-			header('HTTP/1.0 401 Unauthorized');
368
-		}
369
-
370
-		foreach($result->getHeaders() as $name => $value) {
371
-			header($name . ': ' . $value);
372
-		}
373
-
374
-		$meta = $result->getMeta();
375
-		$data = $result->getData();
376
-		if (self::isV2($request)) {
377
-			$statusCode = self::mapStatusCodes($result->getStatusCode());
378
-			if (!is_null($statusCode)) {
379
-				$meta['statuscode'] = $statusCode;
380
-				OC_Response::setStatus($statusCode);
381
-			}
382
-		}
383
-
384
-		self::setContentType($format);
385
-		$body = self::renderResult($format, $meta, $data);
386
-		echo $body;
387
-	}
388
-
389
-	/**
390
-	 * @param XMLWriter $writer
391
-	 */
392
-	private static function toXML($array, $writer) {
393
-		foreach($array as $k => $v) {
394
-			if ($k[0] === '@') {
395
-				$writer->writeAttribute(substr($k, 1), $v);
396
-				continue;
397
-			} else if (is_numeric($k)) {
398
-				$k = 'element';
399
-			}
400
-			if(is_array($v)) {
401
-				$writer->startElement($k);
402
-				self::toXML($v, $writer);
403
-				$writer->endElement();
404
-			} else {
405
-				$writer->writeElement($k, $v);
406
-			}
407
-		}
408
-	}
409
-
410
-	/**
411
-	 * @return string
412
-	 */
413
-	public static function requestedFormat() {
414
-		$formats = array('json', 'xml');
415
-
416
-		$format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
417
-		return $format;
418
-	}
419
-
420
-	/**
421
-	 * Based on the requested format the response content type is set
422
-	 * @param string $format
423
-	 */
424
-	public static function setContentType($format = null) {
425
-		$format = is_null($format) ? self::requestedFormat() : $format;
426
-		if ($format === 'xml') {
427
-			header('Content-type: text/xml; charset=UTF-8');
428
-			return;
429
-		}
430
-
431
-		if ($format === 'json') {
432
-			header('Content-Type: application/json; charset=utf-8');
433
-			return;
434
-		}
435
-
436
-		header('Content-Type: application/octet-stream; charset=utf-8');
437
-	}
438
-
439
-	/**
440
-	 * @param \OCP\IRequest $request
441
-	 * @return bool
442
-	 */
443
-	protected static function isV2(\OCP\IRequest $request) {
444
-		$script = $request->getScriptName();
445
-
446
-		return substr($script, -11) === '/ocs/v2.php';
447
-	}
448
-
449
-	/**
450
-	 * @param integer $sc
451
-	 * @return int
452
-	 */
453
-	public static function mapStatusCodes($sc) {
454
-		switch ($sc) {
455
-			case API::RESPOND_NOT_FOUND:
456
-				return Http::STATUS_NOT_FOUND;
457
-			case API::RESPOND_SERVER_ERROR:
458
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
459
-			case API::RESPOND_UNKNOWN_ERROR:
460
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
461
-			case API::RESPOND_UNAUTHORISED:
462
-				// already handled for v1
463
-				return null;
464
-			case 100:
465
-				return Http::STATUS_OK;
466
-		}
467
-		// any 2xx, 4xx and 5xx will be used as is
468
-		if ($sc >= 200 && $sc < 600) {
469
-			return $sc;
470
-		}
471
-
472
-		return Http::STATUS_BAD_REQUEST;
473
-	}
474
-
475
-	/**
476
-	 * @param string $format
477
-	 * @return string
478
-	 */
479
-	public static function renderResult($format, $meta, $data) {
480
-		$response = array(
481
-			'ocs' => array(
482
-				'meta' => $meta,
483
-				'data' => $data,
484
-			),
485
-		);
486
-		if ($format == 'json') {
487
-			return OC_JSON::encode($response);
488
-		}
489
-
490
-		$writer = new XMLWriter();
491
-		$writer->openMemory();
492
-		$writer->setIndent(true);
493
-		$writer->startDocument();
494
-		self::toXML($response, $writer);
495
-		$writer->endDocument();
496
-		return $writer->outputMemory(true);
497
-	}
40
+    /**
41
+     * API authentication levels
42
+     */
43
+
44
+    /** @deprecated Use \OCP\API::GUEST_AUTH instead */
45
+    const GUEST_AUTH = 0;
46
+
47
+    /** @deprecated Use \OCP\API::USER_AUTH instead */
48
+    const USER_AUTH = 1;
49
+
50
+    /** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
51
+    const SUBADMIN_AUTH = 2;
52
+
53
+    /** @deprecated Use \OCP\API::ADMIN_AUTH instead */
54
+    const ADMIN_AUTH = 3;
55
+
56
+    /**
57
+     * API Response Codes
58
+     */
59
+
60
+    /** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
61
+    const RESPOND_UNAUTHORISED = 997;
62
+
63
+    /** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
64
+    const RESPOND_SERVER_ERROR = 996;
65
+
66
+    /** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
67
+    const RESPOND_NOT_FOUND = 998;
68
+
69
+    /** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
70
+    const RESPOND_UNKNOWN_ERROR = 999;
71
+
72
+    /**
73
+     * api actions
74
+     */
75
+    protected static $actions = array();
76
+    private static $logoutRequired = false;
77
+    private static $isLoggedIn = false;
78
+
79
+    /**
80
+     * registers an api call
81
+     * @param string $method the http method
82
+     * @param string $url the url to match
83
+     * @param callable $action the function to run
84
+     * @param string $app the id of the app registering the call
85
+     * @param int $authLevel the level of authentication required for the call
86
+     * @param array $defaults
87
+     * @param array $requirements
88
+     */
89
+    public static function register($method, $url, $action, $app,
90
+                $authLevel = API::USER_AUTH,
91
+                $defaults = array(),
92
+                $requirements = array()) {
93
+        $name = strtolower($method).$url;
94
+        $name = str_replace(array('/', '{', '}'), '_', $name);
95
+        if(!isset(self::$actions[$name])) {
96
+            $oldCollection = OC::$server->getRouter()->getCurrentCollection();
97
+            OC::$server->getRouter()->useCollection('ocs');
98
+            OC::$server->getRouter()->create($name, $url)
99
+                ->method($method)
100
+                ->defaults($defaults)
101
+                ->requirements($requirements)
102
+                ->action('OC_API', 'call');
103
+            self::$actions[$name] = array();
104
+            OC::$server->getRouter()->useCollection($oldCollection);
105
+        }
106
+        self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
107
+    }
108
+
109
+    /**
110
+     * handles an api call
111
+     * @param array $parameters
112
+     */
113
+    public static function call($parameters) {
114
+        $request = \OC::$server->getRequest();
115
+        $method = $request->getMethod();
116
+
117
+        // Prepare the request variables
118
+        if($method === 'PUT') {
119
+            $parameters['_put'] = $request->getParams();
120
+        } else if($method === 'DELETE') {
121
+            $parameters['_delete'] = $request->getParams();
122
+        }
123
+        $name = $parameters['_route'];
124
+        // Foreach registered action
125
+        $responses = array();
126
+        foreach(self::$actions[$name] as $action) {
127
+            // Check authentication and availability
128
+            if(!self::isAuthorised($action)) {
129
+                $responses[] = array(
130
+                    'app' => $action['app'],
131
+                    'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
132
+                    'shipped' => OC_App::isShipped($action['app']),
133
+                    );
134
+                continue;
135
+            }
136
+            if(!is_callable($action['action'])) {
137
+                $responses[] = array(
138
+                    'app' => $action['app'],
139
+                    'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
140
+                    'shipped' => OC_App::isShipped($action['app']),
141
+                    );
142
+                continue;
143
+            }
144
+            // Run the action
145
+            $responses[] = array(
146
+                'app' => $action['app'],
147
+                'response' => call_user_func($action['action'], $parameters),
148
+                'shipped' => OC_App::isShipped($action['app']),
149
+                );
150
+        }
151
+        $response = self::mergeResponses($responses);
152
+        $format = self::requestedFormat();
153
+        if (self::$logoutRequired) {
154
+            \OC::$server->getUserSession()->logout();
155
+        }
156
+
157
+        self::respond($response, $format);
158
+    }
159
+
160
+    /**
161
+     * merge the returned result objects into one response
162
+     * @param array $responses
163
+     * @return OC_OCS_Result
164
+     */
165
+    public static function mergeResponses($responses) {
166
+        // Sort into shipped and third-party
167
+        $shipped = array(
168
+            'succeeded' => array(),
169
+            'failed' => array(),
170
+            );
171
+        $thirdparty = array(
172
+            'succeeded' => array(),
173
+            'failed' => array(),
174
+            );
175
+
176
+        foreach($responses as $response) {
177
+            if($response['shipped'] || ($response['app'] === 'core')) {
178
+                if($response['response']->succeeded()) {
179
+                    $shipped['succeeded'][$response['app']] = $response;
180
+                } else {
181
+                    $shipped['failed'][$response['app']] = $response;
182
+                }
183
+            } else {
184
+                if($response['response']->succeeded()) {
185
+                    $thirdparty['succeeded'][$response['app']] = $response;
186
+                } else {
187
+                    $thirdparty['failed'][$response['app']] = $response;
188
+                }
189
+            }
190
+        }
191
+
192
+        // Remove any error responses if there is one shipped response that succeeded
193
+        if(!empty($shipped['failed'])) {
194
+            // Which shipped response do we use if they all failed?
195
+            // They may have failed for different reasons (different status codes)
196
+            // Which response code should we return?
197
+            // Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
198
+            // Merge failed responses if more than one
199
+            $data = array();
200
+            foreach($shipped['failed'] as $failure) {
201
+                $data = array_merge_recursive($data, $failure['response']->getData());
202
+            }
203
+            $picked = reset($shipped['failed']);
204
+            $code = $picked['response']->getStatusCode();
205
+            $meta = $picked['response']->getMeta();
206
+            $headers = $picked['response']->getHeaders();
207
+            $response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
208
+            return $response;
209
+        } elseif(!empty($shipped['succeeded'])) {
210
+            $responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
211
+        } elseif(!empty($thirdparty['failed'])) {
212
+            // Merge failed responses if more than one
213
+            $data = array();
214
+            foreach($thirdparty['failed'] as $failure) {
215
+                $data = array_merge_recursive($data, $failure['response']->getData());
216
+            }
217
+            $picked = reset($thirdparty['failed']);
218
+            $code = $picked['response']->getStatusCode();
219
+            $meta = $picked['response']->getMeta();
220
+            $headers = $picked['response']->getHeaders();
221
+            $response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
222
+            return $response;
223
+        } else {
224
+            $responses = $thirdparty['succeeded'];
225
+        }
226
+        // Merge the successful responses
227
+        $data = [];
228
+        $codes = [];
229
+        $header = [];
230
+
231
+        foreach($responses as $response) {
232
+            if($response['shipped']) {
233
+                $data = array_merge_recursive($response['response']->getData(), $data);
234
+            } else {
235
+                $data = array_merge_recursive($data, $response['response']->getData());
236
+            }
237
+            $header = array_merge_recursive($header, $response['response']->getHeaders());
238
+            $codes[] = ['code' => $response['response']->getStatusCode(),
239
+                'meta' => $response['response']->getMeta()];
240
+        }
241
+
242
+        // Use any non 100 status codes
243
+        $statusCode = 100;
244
+        $statusMessage = null;
245
+        foreach($codes as $code) {
246
+            if($code['code'] != 100) {
247
+                $statusCode = $code['code'];
248
+                $statusMessage = $code['meta']['message'];
249
+                break;
250
+            }
251
+        }
252
+
253
+        return new OC_OCS_Result($data, $statusCode, $statusMessage, $header);
254
+    }
255
+
256
+    /**
257
+     * authenticate the api call
258
+     * @param array $action the action details as supplied to OC_API::register()
259
+     * @return bool
260
+     */
261
+    private static function isAuthorised($action) {
262
+        $level = $action['authlevel'];
263
+        switch($level) {
264
+            case API::GUEST_AUTH:
265
+                // Anyone can access
266
+                return true;
267
+            case API::USER_AUTH:
268
+                // User required
269
+                return self::loginUser();
270
+            case API::SUBADMIN_AUTH:
271
+                // Check for subadmin
272
+                $user = self::loginUser();
273
+                if(!$user) {
274
+                    return false;
275
+                } else {
276
+                    $userObject = \OC::$server->getUserSession()->getUser();
277
+                    if($userObject === null) {
278
+                        return false;
279
+                    }
280
+                    $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
281
+                    $admin = OC_User::isAdminUser($user);
282
+                    if($isSubAdmin || $admin) {
283
+                        return true;
284
+                    } else {
285
+                        return false;
286
+                    }
287
+                }
288
+            case API::ADMIN_AUTH:
289
+                // Check for admin
290
+                $user = self::loginUser();
291
+                if(!$user) {
292
+                    return false;
293
+                } else {
294
+                    return OC_User::isAdminUser($user);
295
+                }
296
+            default:
297
+                // oops looks like invalid level supplied
298
+                return false;
299
+        }
300
+    }
301
+
302
+    /**
303
+     * http basic auth
304
+     * @return string|false (username, or false on failure)
305
+     */
306
+    private static function loginUser() {
307
+        if(self::$isLoggedIn === true) {
308
+            return \OC_User::getUser();
309
+        }
310
+
311
+        // reuse existing login
312
+        $loggedIn = \OC::$server->getUserSession()->isLoggedIn();
313
+        if ($loggedIn === true) {
314
+            if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
315
+                // Do not allow access to OCS until the 2FA challenge was solved successfully
316
+                return false;
317
+            }
318
+            $ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
319
+            if ($ocsApiRequest) {
320
+
321
+                // initialize the user's filesystem
322
+                \OC_Util::setupFS(\OC_User::getUser());
323
+                self::$isLoggedIn = true;
324
+
325
+                return OC_User::getUser();
326
+            }
327
+            return false;
328
+        }
329
+
330
+        // basic auth - because OC_User::login will create a new session we shall only try to login
331
+        // if user and pass are set
332
+        $userSession = \OC::$server->getUserSession();
333
+        $request = \OC::$server->getRequest();
334
+        try {
335
+            if ($userSession->tryTokenLogin($request)
336
+                || $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
337
+                self::$logoutRequired = true;
338
+            } else {
339
+                return false;
340
+            }
341
+            // initialize the user's filesystem
342
+            \OC_Util::setupFS(\OC_User::getUser());
343
+            self::$isLoggedIn = true;
344
+
345
+            return \OC_User::getUser();
346
+        } catch (\OC\User\LoginException $e) {
347
+            return false;
348
+        }
349
+    }
350
+
351
+    /**
352
+     * respond to a call
353
+     * @param OC_OCS_Result $result
354
+     * @param string $format the format xml|json
355
+     */
356
+    public static function respond($result, $format='xml') {
357
+        $request = \OC::$server->getRequest();
358
+
359
+        // Send 401 headers if unauthorised
360
+        if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
361
+            // If request comes from JS return dummy auth request
362
+            if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
363
+                header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
364
+            } else {
365
+                header('WWW-Authenticate: Basic realm="Authorisation Required"');
366
+            }
367
+            header('HTTP/1.0 401 Unauthorized');
368
+        }
369
+
370
+        foreach($result->getHeaders() as $name => $value) {
371
+            header($name . ': ' . $value);
372
+        }
373
+
374
+        $meta = $result->getMeta();
375
+        $data = $result->getData();
376
+        if (self::isV2($request)) {
377
+            $statusCode = self::mapStatusCodes($result->getStatusCode());
378
+            if (!is_null($statusCode)) {
379
+                $meta['statuscode'] = $statusCode;
380
+                OC_Response::setStatus($statusCode);
381
+            }
382
+        }
383
+
384
+        self::setContentType($format);
385
+        $body = self::renderResult($format, $meta, $data);
386
+        echo $body;
387
+    }
388
+
389
+    /**
390
+     * @param XMLWriter $writer
391
+     */
392
+    private static function toXML($array, $writer) {
393
+        foreach($array as $k => $v) {
394
+            if ($k[0] === '@') {
395
+                $writer->writeAttribute(substr($k, 1), $v);
396
+                continue;
397
+            } else if (is_numeric($k)) {
398
+                $k = 'element';
399
+            }
400
+            if(is_array($v)) {
401
+                $writer->startElement($k);
402
+                self::toXML($v, $writer);
403
+                $writer->endElement();
404
+            } else {
405
+                $writer->writeElement($k, $v);
406
+            }
407
+        }
408
+    }
409
+
410
+    /**
411
+     * @return string
412
+     */
413
+    public static function requestedFormat() {
414
+        $formats = array('json', 'xml');
415
+
416
+        $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
417
+        return $format;
418
+    }
419
+
420
+    /**
421
+     * Based on the requested format the response content type is set
422
+     * @param string $format
423
+     */
424
+    public static function setContentType($format = null) {
425
+        $format = is_null($format) ? self::requestedFormat() : $format;
426
+        if ($format === 'xml') {
427
+            header('Content-type: text/xml; charset=UTF-8');
428
+            return;
429
+        }
430
+
431
+        if ($format === 'json') {
432
+            header('Content-Type: application/json; charset=utf-8');
433
+            return;
434
+        }
435
+
436
+        header('Content-Type: application/octet-stream; charset=utf-8');
437
+    }
438
+
439
+    /**
440
+     * @param \OCP\IRequest $request
441
+     * @return bool
442
+     */
443
+    protected static function isV2(\OCP\IRequest $request) {
444
+        $script = $request->getScriptName();
445
+
446
+        return substr($script, -11) === '/ocs/v2.php';
447
+    }
448
+
449
+    /**
450
+     * @param integer $sc
451
+     * @return int
452
+     */
453
+    public static function mapStatusCodes($sc) {
454
+        switch ($sc) {
455
+            case API::RESPOND_NOT_FOUND:
456
+                return Http::STATUS_NOT_FOUND;
457
+            case API::RESPOND_SERVER_ERROR:
458
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
459
+            case API::RESPOND_UNKNOWN_ERROR:
460
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
461
+            case API::RESPOND_UNAUTHORISED:
462
+                // already handled for v1
463
+                return null;
464
+            case 100:
465
+                return Http::STATUS_OK;
466
+        }
467
+        // any 2xx, 4xx and 5xx will be used as is
468
+        if ($sc >= 200 && $sc < 600) {
469
+            return $sc;
470
+        }
471
+
472
+        return Http::STATUS_BAD_REQUEST;
473
+    }
474
+
475
+    /**
476
+     * @param string $format
477
+     * @return string
478
+     */
479
+    public static function renderResult($format, $meta, $data) {
480
+        $response = array(
481
+            'ocs' => array(
482
+                'meta' => $meta,
483
+                'data' => $data,
484
+            ),
485
+        );
486
+        if ($format == 'json') {
487
+            return OC_JSON::encode($response);
488
+        }
489
+
490
+        $writer = new XMLWriter();
491
+        $writer->openMemory();
492
+        $writer->setIndent(true);
493
+        $writer->startDocument();
494
+        self::toXML($response, $writer);
495
+        $writer->endDocument();
496
+        return $writer->outputMemory(true);
497
+    }
498 498
 }
Please login to merge, or discard this patch.
lib/private/legacy/eventsource.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@
 block discarded – undo
88 88
 	 * send a message to the client
89 89
 	 *
90 90
 	 * @param string $type
91
-	 * @param mixed $data
91
+	 * @param string $data
92 92
 	 *
93 93
 	 * @throws \BadMethodCallException
94 94
 	 * if only one parameter is given, a typeless message will be send with that parameter as data
Please login to merge, or discard this patch.
Indentation   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -33,98 +33,98 @@
 block discarded – undo
33 33
  * use server side events with caution, to many open requests can hang the server
34 34
  */
35 35
 class OC_EventSource implements \OCP\IEventSource {
36
-	/**
37
-	 * @var bool
38
-	 */
39
-	private $fallback;
36
+    /**
37
+     * @var bool
38
+     */
39
+    private $fallback;
40 40
 
41
-	/**
42
-	 * @var int
43
-	 */
44
-	private $fallBackId = 0;
41
+    /**
42
+     * @var int
43
+     */
44
+    private $fallBackId = 0;
45 45
 
46
-	/**
47
-	 * @var bool
48
-	 */
49
-	private $started = false;
46
+    /**
47
+     * @var bool
48
+     */
49
+    private $started = false;
50 50
 
51
-	protected function init() {
52
-		if ($this->started) {
53
-			return;
54
-		}
55
-		$this->started = true;
51
+    protected function init() {
52
+        if ($this->started) {
53
+            return;
54
+        }
55
+        $this->started = true;
56 56
 
57
-		// prevent php output buffering, caching and nginx buffering
58
-		OC_Util::obEnd();
59
-		header('Cache-Control: no-cache');
60
-		header('X-Accel-Buffering: no');
61
-		$this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62
-		if ($this->fallback) {
63
-			$this->fallBackId = (int)$_GET['fallback_id'];
64
-			/**
65
-			 * FIXME: The default content-security-policy of ownCloud forbids inline
66
-			 * JavaScript for security reasons. IE starting on Windows 10 will
67
-			 * however also obey the CSP which will break the event source fallback.
68
-			 *
69
-			 * As a workaround thus we set a custom policy which allows the execution
70
-			 * of inline JavaScript.
71
-			 *
72
-			 * @link https://github.com/owncloud/core/issues/14286
73
-			 */
74
-			header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75
-			header("Content-Type: text/html");
76
-			echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
77
-		} else {
78
-			header("Content-Type: text/event-stream");
79
-		}
80
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81
-			header('Location: '.\OC::$WEBROOT);
82
-			exit();
83
-		}
84
-		if (!(\OC::$server->getRequest()->passesCSRFCheck())) {
85
-			$this->send('error', 'Possible CSRF attack. Connection will be closed.');
86
-			$this->close();
87
-			exit();
88
-		}
89
-		flush();
90
-	}
57
+        // prevent php output buffering, caching and nginx buffering
58
+        OC_Util::obEnd();
59
+        header('Cache-Control: no-cache');
60
+        header('X-Accel-Buffering: no');
61
+        $this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62
+        if ($this->fallback) {
63
+            $this->fallBackId = (int)$_GET['fallback_id'];
64
+            /**
65
+             * FIXME: The default content-security-policy of ownCloud forbids inline
66
+             * JavaScript for security reasons. IE starting on Windows 10 will
67
+             * however also obey the CSP which will break the event source fallback.
68
+             *
69
+             * As a workaround thus we set a custom policy which allows the execution
70
+             * of inline JavaScript.
71
+             *
72
+             * @link https://github.com/owncloud/core/issues/14286
73
+             */
74
+            header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75
+            header("Content-Type: text/html");
76
+            echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
77
+        } else {
78
+            header("Content-Type: text/event-stream");
79
+        }
80
+        if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81
+            header('Location: '.\OC::$WEBROOT);
82
+            exit();
83
+        }
84
+        if (!(\OC::$server->getRequest()->passesCSRFCheck())) {
85
+            $this->send('error', 'Possible CSRF attack. Connection will be closed.');
86
+            $this->close();
87
+            exit();
88
+        }
89
+        flush();
90
+    }
91 91
 
92
-	/**
93
-	 * send a message to the client
94
-	 *
95
-	 * @param string $type
96
-	 * @param mixed $data
97
-	 *
98
-	 * @throws \BadMethodCallException
99
-	 * if only one parameter is given, a typeless message will be send with that parameter as data
100
-	 */
101
-	public function send($type, $data = null) {
102
-		if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
-			throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
104
-		}
105
-		$this->init();
106
-		if (is_null($data)) {
107
-			$data = $type;
108
-			$type = null;
109
-		}
110
-		if ($this->fallback) {
111
-			$response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
-				. $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
113
-			echo $response;
114
-		} else {
115
-			if ($type) {
116
-				echo 'event: ' . $type . PHP_EOL;
117
-			}
118
-			echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
119
-		}
120
-		echo PHP_EOL;
121
-		flush();
122
-	}
92
+    /**
93
+     * send a message to the client
94
+     *
95
+     * @param string $type
96
+     * @param mixed $data
97
+     *
98
+     * @throws \BadMethodCallException
99
+     * if only one parameter is given, a typeless message will be send with that parameter as data
100
+     */
101
+    public function send($type, $data = null) {
102
+        if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
+            throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
104
+        }
105
+        $this->init();
106
+        if (is_null($data)) {
107
+            $data = $type;
108
+            $type = null;
109
+        }
110
+        if ($this->fallback) {
111
+            $response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
+                . $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
113
+            echo $response;
114
+        } else {
115
+            if ($type) {
116
+                echo 'event: ' . $type . PHP_EOL;
117
+            }
118
+            echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
119
+        }
120
+        echo PHP_EOL;
121
+        flush();
122
+    }
123 123
 
124
-	/**
125
-	 * close the connection of the event source
126
-	 */
127
-	public function close() {
128
-		$this->send('__internal__', 'close'); //server side closing can be an issue, let the client do it
129
-	}
124
+    /**
125
+     * close the connection of the event source
126
+     */
127
+    public function close() {
128
+        $this->send('__internal__', 'close'); //server side closing can be an issue, let the client do it
129
+    }
130 130
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 		header('X-Accel-Buffering: no');
61 61
 		$this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62 62
 		if ($this->fallback) {
63
-			$this->fallBackId = (int)$_GET['fallback_id'];
63
+			$this->fallBackId = (int) $_GET['fallback_id'];
64 64
 			/**
65 65
 			 * FIXME: The default content-security-policy of ownCloud forbids inline
66 66
 			 * JavaScript for security reasons. IE starting on Windows 10 will
@@ -73,11 +73,11 @@  discard block
 block discarded – undo
73 73
 			 */
74 74
 			header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75 75
 			header("Content-Type: text/html");
76
-			echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
76
+			echo str_repeat('<span></span>'.PHP_EOL, 10); //dummy data to keep IE happy
77 77
 		} else {
78 78
 			header("Content-Type: text/event-stream");
79 79
 		}
80
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
80
+		if (!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81 81
 			header('Location: '.\OC::$WEBROOT);
82 82
 			exit();
83 83
 		}
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	 */
101 101
 	public function send($type, $data = null) {
102 102
 		if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
-			throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
103
+			throw new BadMethodCallException('Type needs to be alphanumeric ('.$type.')');
104 104
 		}
105 105
 		$this->init();
106 106
 		if (is_null($data)) {
@@ -109,13 +109,13 @@  discard block
 block discarded – undo
109 109
 		}
110 110
 		if ($this->fallback) {
111 111
 			$response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
-				. $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
112
+				. $this->fallBackId.',"'.$type.'",'.OCP\JSON::encode($data).')</script>'.PHP_EOL;
113 113
 			echo $response;
114 114
 		} else {
115 115
 			if ($type) {
116
-				echo 'event: ' . $type . PHP_EOL;
116
+				echo 'event: '.$type.PHP_EOL;
117 117
 			}
118
-			echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
118
+			echo 'data: '.OCP\JSON::encode($data).PHP_EOL;
119 119
 		}
120 120
 		echo PHP_EOL;
121 121
 		flush();
Please login to merge, or discard this patch.