Completed
Pull Request — master (#3770)
by Thomas
25:54
created
apps/dav/lib/Connector/Sabre/DavAclPlugin.php 4 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -47,6 +47,9 @@
 block discarded – undo
47 47
 		$this->allowUnauthenticatedAccess = false;
48 48
 	}
49 49
 
50
+	/**
51
+	 * @param string $privileges
52
+	 */
50 53
 	function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
51 54
 		$access = parent::checkPrivileges($uri, $privileges, $recursion, false);
52 55
 		if($access === false && $throwExceptions) {
Please login to merge, or discard this patch.
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -25,14 +25,11 @@
 block discarded – undo
25 25
 
26 26
 use Sabre\CalDAV\Principal\User;
27 27
 use Sabre\DAV\Exception\NotFound;
28
-use Sabre\DAV\IFile;
29 28
 use Sabre\DAV\INode;
30 29
 use \Sabre\DAV\PropFind;
31 30
 use \Sabre\DAV\PropPatch;
32
-use Sabre\DAVACL\Exception\NeedPrivileges;
33 31
 use \Sabre\HTTP\RequestInterface;
34 32
 use \Sabre\HTTP\ResponseInterface;
35
-use Sabre\HTTP\URLUtil;
36 33
 
37 34
 /**
38 35
  * Class DavAclPlugin is a wrapper around \Sabre\DAVACL\Plugin that returns 404
Please login to merge, or discard this patch.
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -43,50 +43,50 @@
 block discarded – undo
43 43
  * @package OCA\DAV\Connector\Sabre
44 44
  */
45 45
 class DavAclPlugin extends \Sabre\DAVACL\Plugin {
46
-	public function __construct() {
47
-		$this->hideNodesFromListings = true;
48
-		$this->allowUnauthenticatedAccess = false;
49
-	}
46
+    public function __construct() {
47
+        $this->hideNodesFromListings = true;
48
+        $this->allowUnauthenticatedAccess = false;
49
+    }
50 50
 
51
-	function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
52
-		$access = parent::checkPrivileges($uri, $privileges, $recursion, false);
53
-		if($access === false && $throwExceptions) {
54
-			/** @var INode $node */
55
-			$node = $this->server->tree->getNodeForPath($uri);
51
+    function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
52
+        $access = parent::checkPrivileges($uri, $privileges, $recursion, false);
53
+        if($access === false && $throwExceptions) {
54
+            /** @var INode $node */
55
+            $node = $this->server->tree->getNodeForPath($uri);
56 56
 
57
-			switch(get_class($node)) {
58
-				case 'OCA\DAV\CardDAV\AddressBook':
59
-					$type = 'Addressbook';
60
-					break;
61
-				default:
62
-					$type = 'Node';
63
-					break;
64
-			}
65
-			throw new NotFound(
66
-				sprintf(
67
-					"%s with name '%s' could not be found",
68
-					$type,
69
-					$node->getName()
70
-				)
71
-			);
72
-		}
57
+            switch(get_class($node)) {
58
+                case 'OCA\DAV\CardDAV\AddressBook':
59
+                    $type = 'Addressbook';
60
+                    break;
61
+                default:
62
+                    $type = 'Node';
63
+                    break;
64
+            }
65
+            throw new NotFound(
66
+                sprintf(
67
+                    "%s with name '%s' could not be found",
68
+                    $type,
69
+                    $node->getName()
70
+                )
71
+            );
72
+        }
73 73
 
74
-		return $access;
75
-	}
74
+        return $access;
75
+    }
76 76
 
77
-	public function propFind(PropFind $propFind, INode $node) {
78
-		// If the node is neither readable nor writable then fail unless its of
79
-		// the standard user-principal
80
-		if(!($node instanceof User)) {
81
-			$path = $propFind->getPath();
82
-			$readPermissions = $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false);
83
-			$writePermissions = $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, false);
84
-			if ($readPermissions === false && $writePermissions === false) {
85
-				$this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, true);
86
-				$this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, true);
87
-			}
88
-		}
77
+    public function propFind(PropFind $propFind, INode $node) {
78
+        // If the node is neither readable nor writable then fail unless its of
79
+        // the standard user-principal
80
+        if(!($node instanceof User)) {
81
+            $path = $propFind->getPath();
82
+            $readPermissions = $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false);
83
+            $writePermissions = $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, false);
84
+            if ($readPermissions === false && $writePermissions === false) {
85
+                $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, true);
86
+                $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, true);
87
+            }
88
+        }
89 89
 
90
-		return parent::propFind($propFind, $node);
91
-	}
90
+        return parent::propFind($propFind, $node);
91
+    }
92 92
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -50,11 +50,11 @@  discard block
 block discarded – undo
50 50
 
51 51
 	function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
52 52
 		$access = parent::checkPrivileges($uri, $privileges, $recursion, false);
53
-		if($access === false && $throwExceptions) {
53
+		if ($access === false && $throwExceptions) {
54 54
 			/** @var INode $node */
55 55
 			$node = $this->server->tree->getNodeForPath($uri);
56 56
 
57
-			switch(get_class($node)) {
57
+			switch (get_class($node)) {
58 58
 				case 'OCA\DAV\CardDAV\AddressBook':
59 59
 					$type = 'Addressbook';
60 60
 					break;
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 	public function propFind(PropFind $propFind, INode $node) {
78 78
 		// If the node is neither readable nor writable then fail unless its of
79 79
 		// the standard user-principal
80
-		if(!($node instanceof User)) {
80
+		if (!($node instanceof User)) {
81 81
 			$path = $propFind->getPath();
82 82
 			$readPermissions = $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false);
83 83
 			$writePermissions = $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, false);
Please login to merge, or discard this patch.
lib/private/Files/Storage/Storage.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -100,6 +100,7 @@  discard block
 block discarded – undo
100 100
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101 101
 	 * @param \OCP\Lock\ILockingProvider $provider
102 102
 	 * @throws \OCP\Lock\LockedException
103
+	 * @return void
103 104
 	 */
104 105
 	public function acquireLock($path, $type, ILockingProvider $provider);
105 106
 
@@ -108,6 +109,7 @@  discard block
 block discarded – undo
108 109
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109 110
 	 * @param \OCP\Lock\ILockingProvider $provider
110 111
 	 * @throws \OCP\Lock\LockedException
112
+	 * @return void
111 113
 	 */
112 114
 	public function releaseLock($path, $type, ILockingProvider $provider);
113 115
 
@@ -116,6 +118,7 @@  discard block
 block discarded – undo
116 118
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117 119
 	 * @param \OCP\Lock\ILockingProvider $provider
118 120
 	 * @throws \OCP\Lock\LockedException
121
+	 * @return void
119 122
 	 */
120 123
 	public function changeLock($path, $type, ILockingProvider $provider);
121 124
 }
Please login to merge, or discard this patch.
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -32,90 +32,90 @@
 block discarded – undo
32 32
  */
33 33
 interface Storage extends \OCP\Files\Storage {
34 34
 
35
-	/**
36
-	 * get a cache instance for the storage
37
-	 *
38
-	 * @param string $path
39
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the cache
40
-	 * @return \OC\Files\Cache\Cache
41
-	 */
42
-	public function getCache($path = '', $storage = null);
35
+    /**
36
+     * get a cache instance for the storage
37
+     *
38
+     * @param string $path
39
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the cache
40
+     * @return \OC\Files\Cache\Cache
41
+     */
42
+    public function getCache($path = '', $storage = null);
43 43
 
44
-	/**
45
-	 * get a scanner instance for the storage
46
-	 *
47
-	 * @param string $path
48
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
49
-	 * @return \OC\Files\Cache\Scanner
50
-	 */
51
-	public function getScanner($path = '', $storage = null);
44
+    /**
45
+     * get a scanner instance for the storage
46
+     *
47
+     * @param string $path
48
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
49
+     * @return \OC\Files\Cache\Scanner
50
+     */
51
+    public function getScanner($path = '', $storage = null);
52 52
 
53 53
 
54
-	/**
55
-	 * get the user id of the owner of a file or folder
56
-	 *
57
-	 * @param string $path
58
-	 * @return string
59
-	 */
60
-	public function getOwner($path);
54
+    /**
55
+     * get the user id of the owner of a file or folder
56
+     *
57
+     * @param string $path
58
+     * @return string
59
+     */
60
+    public function getOwner($path);
61 61
 
62
-	/**
63
-	 * get a watcher instance for the cache
64
-	 *
65
-	 * @param string $path
66
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
67
-	 * @return \OC\Files\Cache\Watcher
68
-	 */
69
-	public function getWatcher($path = '', $storage = null);
62
+    /**
63
+     * get a watcher instance for the cache
64
+     *
65
+     * @param string $path
66
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
67
+     * @return \OC\Files\Cache\Watcher
68
+     */
69
+    public function getWatcher($path = '', $storage = null);
70 70
 
71
-	/**
72
-	 * get a propagator instance for the cache
73
-	 *
74
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
75
-	 * @return \OC\Files\Cache\Propagator
76
-	 */
77
-	public function getPropagator($storage = null);
71
+    /**
72
+     * get a propagator instance for the cache
73
+     *
74
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
75
+     * @return \OC\Files\Cache\Propagator
76
+     */
77
+    public function getPropagator($storage = null);
78 78
 
79
-	/**
80
-	 * get a updater instance for the cache
81
-	 *
82
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
83
-	 * @return \OC\Files\Cache\Updater
84
-	 */
85
-	public function getUpdater($storage = null);
79
+    /**
80
+     * get a updater instance for the cache
81
+     *
82
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
83
+     * @return \OC\Files\Cache\Updater
84
+     */
85
+    public function getUpdater($storage = null);
86 86
 
87
-	/**
88
-	 * @return \OC\Files\Cache\Storage
89
-	 */
90
-	public function getStorageCache();
87
+    /**
88
+     * @return \OC\Files\Cache\Storage
89
+     */
90
+    public function getStorageCache();
91 91
 
92
-	/**
93
-	 * @param string $path
94
-	 * @return array
95
-	 */
96
-	public function getMetaData($path);
92
+    /**
93
+     * @param string $path
94
+     * @return array
95
+     */
96
+    public function getMetaData($path);
97 97
 
98
-	/**
99
-	 * @param string $path The path of the file to acquire the lock for
100
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101
-	 * @param \OCP\Lock\ILockingProvider $provider
102
-	 * @throws \OCP\Lock\LockedException
103
-	 */
104
-	public function acquireLock($path, $type, ILockingProvider $provider);
98
+    /**
99
+     * @param string $path The path of the file to acquire the lock for
100
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101
+     * @param \OCP\Lock\ILockingProvider $provider
102
+     * @throws \OCP\Lock\LockedException
103
+     */
104
+    public function acquireLock($path, $type, ILockingProvider $provider);
105 105
 
106
-	/**
107
-	 * @param string $path The path of the file to release the lock for
108
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109
-	 * @param \OCP\Lock\ILockingProvider $provider
110
-	 * @throws \OCP\Lock\LockedException
111
-	 */
112
-	public function releaseLock($path, $type, ILockingProvider $provider);
106
+    /**
107
+     * @param string $path The path of the file to release the lock for
108
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109
+     * @param \OCP\Lock\ILockingProvider $provider
110
+     * @throws \OCP\Lock\LockedException
111
+     */
112
+    public function releaseLock($path, $type, ILockingProvider $provider);
113 113
 
114
-	/**
115
-	 * @param string $path The path of the file to change the lock for
116
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117
-	 * @param \OCP\Lock\ILockingProvider $provider
118
-	 * @throws \OCP\Lock\LockedException
119
-	 */
120
-	public function changeLock($path, $type, ILockingProvider $provider);
114
+    /**
115
+     * @param string $path The path of the file to change the lock for
116
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117
+     * @param \OCP\Lock\ILockingProvider $provider
118
+     * @throws \OCP\Lock\LockedException
119
+     */
120
+    public function changeLock($path, $type, ILockingProvider $provider);
121 121
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -46,7 +46,6 @@
 block discarded – undo
46 46
 use OC\AppFramework\Utility\TimeFactory;
47 47
 use OC\Core\Middleware\TwoFactorMiddleware;
48 48
 use OC\RichObjectStrings\Validator;
49
-use OC\Security\Bruteforce\Throttler;
50 49
 use OCP\AppFramework\IApi;
51 50
 use OCP\AppFramework\IAppContainer;
52 51
 use OCP\Federation\ICloudIdManager;
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 	 * Put your class dependencies in here
67 67
 	 * @param string $appName the name of the app
68 68
 	 */
69
-	public function __construct($appName, $urlParams = array()){
69
+	public function __construct($appName, $urlParams = array()) {
70 70
 		parent::__construct();
71 71
 		$this['AppName'] = $appName;
72 72
 		$this['urlParams'] = $urlParams;
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 			return $this->getServer()->getAppManager();
92 92
 		});
93 93
 
94
-		$this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c){
94
+		$this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c) {
95 95
 			return new Output($this->getServer()->getWebRoot());
96 96
 		});
97 97
 
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 			return $this->getServer()->getHTTPClientService();
183 183
 		});
184 184
 
185
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
185
+		$this->registerService(IAppData::class, function(SimpleContainer $c) {
186 186
 			return $this->getServer()->getAppDataDir($c->query('AppName'));
187 187
 		});
188 188
 
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
 			return $this->getServer()->getPreviewManager();
234 234
 		});
235 235
 
236
-		$this->registerService('OCP\\IRequest', function () {
236
+		$this->registerService('OCP\\IRequest', function() {
237 237
 			return $this->getServer()->getRequest();
238 238
 		});
239 239
 		$this->registerAlias('Request', 'OCP\\IRequest');
@@ -311,32 +311,32 @@  discard block
 block discarded – undo
311 311
 			return $this->getServer()->getContentSecurityPolicyManager();
312 312
 		});
313 313
 
314
-		$this->registerService('ServerContainer', function ($c) {
314
+		$this->registerService('ServerContainer', function($c) {
315 315
 			return $this->getServer();
316 316
 		});
317 317
 		$this->registerAlias('OCP\\IServerContainer', 'ServerContainer');
318 318
 
319
-		$this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function ($c) {
319
+		$this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function($c) {
320 320
 			return $this->getServer()->getEventDispatcher();
321 321
 		});
322 322
 
323
-		$this->registerService('OCP\WorkflowEngine\IManager', function ($c) {
323
+		$this->registerService('OCP\WorkflowEngine\IManager', function($c) {
324 324
 			return $c->query('OCA\WorkflowEngine\Manager');
325 325
 		});
326 326
 
327
-		$this->registerService('OCP\\AppFramework\\IAppContainer', function ($c) {
327
+		$this->registerService('OCP\\AppFramework\\IAppContainer', function($c) {
328 328
 			return $c;
329 329
 		});
330
-		$this->registerService(IMountManager::class, function () {
330
+		$this->registerService(IMountManager::class, function() {
331 331
 			return $this->getServer()->getMountManager();
332 332
 		});
333 333
 
334 334
 		// commonly used attributes
335
-		$this->registerService('UserId', function ($c) {
335
+		$this->registerService('UserId', function($c) {
336 336
 			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
337 337
 		});
338 338
 
339
-		$this->registerService('WebRoot', function ($c) {
339
+		$this->registerService('WebRoot', function($c) {
340 340
 			return $c->query('ServerContainer')->getWebRoot();
341 341
 		});
342 342
 
@@ -344,11 +344,11 @@  discard block
 block discarded – undo
344 344
 			return Util::getDefaultEmailAddress('no-reply');
345 345
 		});
346 346
 
347
-		$this->registerService('OC_Defaults', function ($c) {
347
+		$this->registerService('OC_Defaults', function($c) {
348 348
 			return $c->getServer()->getThemingDefaults();
349 349
 		});
350 350
 
351
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
351
+		$this->registerService('OCP\Encryption\IManager', function($c) {
352 352
 			return $this->getServer()->getEncryptionManager();
353 353
 		});
354 354
 
@@ -356,7 +356,7 @@  discard block
 block discarded – undo
356 356
 			return $c->query(Validator::class);
357 357
 		});
358 358
 
359
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
359
+		$this->registerService(\OC\Security\IdentityProof\Manager::class, function($c) {
360 360
 			return new \OC\Security\IdentityProof\Manager(
361 361
 				$this->getServer()->getAppDataDir('identityproof'),
362 362
 				$this->getServer()->getCrypto()
@@ -367,15 +367,15 @@  discard block
 block discarded – undo
367 367
 		/**
368 368
 		 * App Framework APIs
369 369
 		 */
370
-		$this->registerService('API', function($c){
370
+		$this->registerService('API', function($c) {
371 371
 			$c->query('OCP\\ILogger')->debug(
372
-				'Accessing the API class is deprecated! Use the appropriate ' .
372
+				'Accessing the API class is deprecated! Use the appropriate '.
373 373
 				'services instead!'
374 374
 			);
375 375
 			return new API($c['AppName']);
376 376
 		});
377 377
 
378
-		$this->registerService('Protocol', function($c){
378
+		$this->registerService('Protocol', function($c) {
379 379
 			/** @var \OC\Server $server */
380 380
 			$server = $c->query('ServerContainer');
381 381
 			$protocol = $server->getRequest()->getHttpProtocol();
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
 			);
442 442
 		});
443 443
 
444
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
444
+		$this->registerService('TwoFactorMiddleware', function(SimpleContainer $c) use ($app) {
445 445
 			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
446 446
 			$userSession = $app->getServer()->getUserSession();
447 447
 			$session = $app->getServer()->getSession();
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
 			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
452 452
 		});
453 453
 
454
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
454
+		$this->registerService('OCSMiddleware', function(SimpleContainer $c) {
455 455
 			return new OCSMiddleware(
456 456
 				$c['Request']
457 457
 			);
@@ -465,7 +465,7 @@  discard block
 block discarded – undo
465 465
 			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
466 466
 			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
467 467
 
468
-			foreach($middleWares as $middleWare) {
468
+			foreach ($middleWares as $middleWare) {
469 469
 				$dispatcher->registerMiddleware($c[$middleWare]);
470 470
 			}
471 471
 
@@ -537,7 +537,7 @@  discard block
 block discarded – undo
537 537
 	 * @return mixed
538 538
 	 */
539 539
 	function log($message, $level) {
540
-		switch($level){
540
+		switch ($level) {
541 541
 			case 'debug':
542 542
 				$level = \OCP\Util::DEBUG;
543 543
 				break;
Please login to merge, or discard this patch.
Indentation   +489 added lines, -489 removed lines patch added patch discarded remove patch
@@ -57,518 +57,518 @@
 block discarded – undo
57 57
 
58 58
 class DIContainer extends SimpleContainer implements IAppContainer {
59 59
 
60
-	/**
61
-	 * @var array
62
-	 */
63
-	private $middleWares = array();
64
-
65
-	/**
66
-	 * Put your class dependencies in here
67
-	 * @param string $appName the name of the app
68
-	 */
69
-	public function __construct($appName, $urlParams = array()){
70
-		parent::__construct();
71
-		$this['AppName'] = $appName;
72
-		$this['urlParams'] = $urlParams;
73
-
74
-		/** @var \OC\ServerContainer $server */
75
-		$server = $this->getServer();
76
-		$server->registerAppContainer($appName, $this);
77
-
78
-		// aliases
79
-		$this->registerAlias('appName', 'AppName');
80
-		$this->registerAlias('webRoot', 'WebRoot');
81
-		$this->registerAlias('userId', 'UserId');
82
-
83
-		/**
84
-		 * Core services
85
-		 */
86
-		$this->registerService('OCP\\IAppConfig', function($c) {
87
-			return $this->getServer()->getAppConfig();
88
-		});
89
-
90
-		$this->registerService('OCP\\App\\IAppManager', function($c) {
91
-			return $this->getServer()->getAppManager();
92
-		});
93
-
94
-		$this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c){
95
-			return new Output($this->getServer()->getWebRoot());
96
-		});
97
-
98
-		$this->registerService(\OCP\Authentication\LoginCredentials\IStore::class, function() {
99
-			return $this->getServer()->query(\OCP\Authentication\LoginCredentials\IStore::class);
100
-		});
101
-
102
-		$this->registerService('OCP\\IAvatarManager', function($c) {
103
-			return $this->getServer()->getAvatarManager();
104
-		});
105
-
106
-		$this->registerService('OCP\\Activity\\IManager', function($c) {
107
-			return $this->getServer()->getActivityManager();
108
-		});
109
-		$this->registerService(\OCP\Activity\IEventMerger::class, function($c) {
110
-			return $this->getServer()->query(\OCP\Activity\IEventMerger::class);
111
-		});
112
-
113
-		$this->registerService('OCP\\ICache', function($c) {
114
-			return $this->getServer()->getCache();
115
-		});
116
-
117
-		$this->registerService('OCP\\ICacheFactory', function($c) {
118
-			return $this->getServer()->getMemCacheFactory();
119
-		});
120
-
121
-		$this->registerService('OC\\CapabilitiesManager', function($c) {
122
-			return $this->getServer()->getCapabilitiesManager();
123
-		});
124
-
125
-		$this->registerService('OCP\Comments\ICommentsManager', function($c) {
126
-			return $this->getServer()->getCommentsManager();
127
-		});
128
-
129
-		$this->registerService('OCP\\IConfig', function($c) {
130
-			return $this->getServer()->getConfig();
131
-		});
132
-
133
-		$this->registerService('OCP\\Contacts\\IManager', function($c) {
134
-			return $this->getServer()->getContactsManager();
135
-		});
136
-
137
-		$this->registerService('OCP\\IDateTimeZone', function($c) {
138
-			return $this->getServer()->getDateTimeZone();
139
-		});
140
-
141
-		$this->registerService('OCP\\IDateTimeFormatter', function($c) {
142
-			return $this->getServer()->getDateTimeFormatter();
143
-		});
144
-
145
-		$this->registerService('OCP\\IDBConnection', function($c) {
146
-			return $this->getServer()->getDatabaseConnection();
147
-		});
148
-
149
-		$this->registerService('OCP\\Diagnostics\\IEventLogger', function($c) {
150
-			return $this->getServer()->getEventLogger();
151
-		});
152
-
153
-		$this->registerService('OCP\\Diagnostics\\IQueryLogger', function($c) {
154
-			return $this->getServer()->getQueryLogger();
155
-		});
156
-
157
-		$this->registerService(ICloudIdManager::class, function($c) {
158
-			return $this->getServer()->getCloudIdManager();
159
-		});
160
-
161
-		$this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
162
-			return $this->getServer()->getMimeTypeDetector();
163
-		});
164
-
165
-		$this->registerService('OCP\\Files\\Config\\IMountProviderCollection', function($c) {
166
-			return $this->getServer()->getMountProviderCollection();
167
-		});
168
-
169
-		$this->registerService('OCP\\Files\\Config\\IUserMountCache', function($c) {
170
-			return $this->getServer()->getUserMountCache();
171
-		});
60
+    /**
61
+     * @var array
62
+     */
63
+    private $middleWares = array();
64
+
65
+    /**
66
+     * Put your class dependencies in here
67
+     * @param string $appName the name of the app
68
+     */
69
+    public function __construct($appName, $urlParams = array()){
70
+        parent::__construct();
71
+        $this['AppName'] = $appName;
72
+        $this['urlParams'] = $urlParams;
73
+
74
+        /** @var \OC\ServerContainer $server */
75
+        $server = $this->getServer();
76
+        $server->registerAppContainer($appName, $this);
77
+
78
+        // aliases
79
+        $this->registerAlias('appName', 'AppName');
80
+        $this->registerAlias('webRoot', 'WebRoot');
81
+        $this->registerAlias('userId', 'UserId');
82
+
83
+        /**
84
+         * Core services
85
+         */
86
+        $this->registerService('OCP\\IAppConfig', function($c) {
87
+            return $this->getServer()->getAppConfig();
88
+        });
89
+
90
+        $this->registerService('OCP\\App\\IAppManager', function($c) {
91
+            return $this->getServer()->getAppManager();
92
+        });
93
+
94
+        $this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c){
95
+            return new Output($this->getServer()->getWebRoot());
96
+        });
97
+
98
+        $this->registerService(\OCP\Authentication\LoginCredentials\IStore::class, function() {
99
+            return $this->getServer()->query(\OCP\Authentication\LoginCredentials\IStore::class);
100
+        });
101
+
102
+        $this->registerService('OCP\\IAvatarManager', function($c) {
103
+            return $this->getServer()->getAvatarManager();
104
+        });
105
+
106
+        $this->registerService('OCP\\Activity\\IManager', function($c) {
107
+            return $this->getServer()->getActivityManager();
108
+        });
109
+        $this->registerService(\OCP\Activity\IEventMerger::class, function($c) {
110
+            return $this->getServer()->query(\OCP\Activity\IEventMerger::class);
111
+        });
112
+
113
+        $this->registerService('OCP\\ICache', function($c) {
114
+            return $this->getServer()->getCache();
115
+        });
116
+
117
+        $this->registerService('OCP\\ICacheFactory', function($c) {
118
+            return $this->getServer()->getMemCacheFactory();
119
+        });
120
+
121
+        $this->registerService('OC\\CapabilitiesManager', function($c) {
122
+            return $this->getServer()->getCapabilitiesManager();
123
+        });
124
+
125
+        $this->registerService('OCP\Comments\ICommentsManager', function($c) {
126
+            return $this->getServer()->getCommentsManager();
127
+        });
128
+
129
+        $this->registerService('OCP\\IConfig', function($c) {
130
+            return $this->getServer()->getConfig();
131
+        });
132
+
133
+        $this->registerService('OCP\\Contacts\\IManager', function($c) {
134
+            return $this->getServer()->getContactsManager();
135
+        });
136
+
137
+        $this->registerService('OCP\\IDateTimeZone', function($c) {
138
+            return $this->getServer()->getDateTimeZone();
139
+        });
140
+
141
+        $this->registerService('OCP\\IDateTimeFormatter', function($c) {
142
+            return $this->getServer()->getDateTimeFormatter();
143
+        });
144
+
145
+        $this->registerService('OCP\\IDBConnection', function($c) {
146
+            return $this->getServer()->getDatabaseConnection();
147
+        });
148
+
149
+        $this->registerService('OCP\\Diagnostics\\IEventLogger', function($c) {
150
+            return $this->getServer()->getEventLogger();
151
+        });
152
+
153
+        $this->registerService('OCP\\Diagnostics\\IQueryLogger', function($c) {
154
+            return $this->getServer()->getQueryLogger();
155
+        });
156
+
157
+        $this->registerService(ICloudIdManager::class, function($c) {
158
+            return $this->getServer()->getCloudIdManager();
159
+        });
160
+
161
+        $this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
162
+            return $this->getServer()->getMimeTypeDetector();
163
+        });
164
+
165
+        $this->registerService('OCP\\Files\\Config\\IMountProviderCollection', function($c) {
166
+            return $this->getServer()->getMountProviderCollection();
167
+        });
168
+
169
+        $this->registerService('OCP\\Files\\Config\\IUserMountCache', function($c) {
170
+            return $this->getServer()->getUserMountCache();
171
+        });
172 172
 
173
-		$this->registerService('OCP\\Files\\IRootFolder', function($c) {
174
-			return $this->getServer()->getRootFolder();
175
-		});
173
+        $this->registerService('OCP\\Files\\IRootFolder', function($c) {
174
+            return $this->getServer()->getRootFolder();
175
+        });
176 176
 
177
-		$this->registerService('OCP\\Files\\Folder', function() {
178
-			return $this->getServer()->getUserFolder();
179
-		});
177
+        $this->registerService('OCP\\Files\\Folder', function() {
178
+            return $this->getServer()->getUserFolder();
179
+        });
180 180
 
181
-		$this->registerService('OCP\\Http\\Client\\IClientService', function($c) {
182
-			return $this->getServer()->getHTTPClientService();
183
-		});
181
+        $this->registerService('OCP\\Http\\Client\\IClientService', function($c) {
182
+            return $this->getServer()->getHTTPClientService();
183
+        });
184 184
 
185
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
186
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
187
-		});
185
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
186
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
187
+        });
188 188
 
189
-		$this->registerService('OCP\\IGroupManager', function($c) {
190
-			return $this->getServer()->getGroupManager();
191
-		});
189
+        $this->registerService('OCP\\IGroupManager', function($c) {
190
+            return $this->getServer()->getGroupManager();
191
+        });
192 192
 
193
-		$this->registerService('OCP\\Http\\Client\\IClientService', function() {
194
-			return $this->getServer()->getHTTPClientService();
195
-		});
193
+        $this->registerService('OCP\\Http\\Client\\IClientService', function() {
194
+            return $this->getServer()->getHTTPClientService();
195
+        });
196 196
 
197
-		$this->registerService('OCP\\IL10N', function($c) {
198
-			return $this->getServer()->getL10N($c->query('AppName'));
199
-		});
197
+        $this->registerService('OCP\\IL10N', function($c) {
198
+            return $this->getServer()->getL10N($c->query('AppName'));
199
+        });
200 200
 
201
-		$this->registerService('OCP\\L10N\\IFactory', function($c) {
202
-			return $this->getServer()->getL10NFactory();
203
-		});
201
+        $this->registerService('OCP\\L10N\\IFactory', function($c) {
202
+            return $this->getServer()->getL10NFactory();
203
+        });
204 204
 
205
-		$this->registerService('OCP\\ILogger', function($c) {
206
-			return $this->getServer()->getLogger();
207
-		});
205
+        $this->registerService('OCP\\ILogger', function($c) {
206
+            return $this->getServer()->getLogger();
207
+        });
208 208
 
209
-		$this->registerService('OCP\\BackgroundJob\\IJobList', function($c) {
210
-			return $this->getServer()->getJobList();
211
-		});
209
+        $this->registerService('OCP\\BackgroundJob\\IJobList', function($c) {
210
+            return $this->getServer()->getJobList();
211
+        });
212 212
 
213
-		$this->registerAlias('OCP\\AppFramework\\Utility\\IControllerMethodReflector', 'OC\AppFramework\Utility\ControllerMethodReflector');
214
-		$this->registerAlias('ControllerMethodReflector', 'OCP\\AppFramework\\Utility\\IControllerMethodReflector');
213
+        $this->registerAlias('OCP\\AppFramework\\Utility\\IControllerMethodReflector', 'OC\AppFramework\Utility\ControllerMethodReflector');
214
+        $this->registerAlias('ControllerMethodReflector', 'OCP\\AppFramework\\Utility\\IControllerMethodReflector');
215 215
 
216
-		$this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
217
-			return $this->getServer()->getMimeTypeDetector();
218
-		});
216
+        $this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
217
+            return $this->getServer()->getMimeTypeDetector();
218
+        });
219 219
 
220
-		$this->registerService('OCP\\Mail\\IMailer', function() {
221
-			return $this->getServer()->getMailer();
222
-		});
220
+        $this->registerService('OCP\\Mail\\IMailer', function() {
221
+            return $this->getServer()->getMailer();
222
+        });
223 223
 
224
-		$this->registerService('OCP\\INavigationManager', function($c) {
225
-			return $this->getServer()->getNavigationManager();
226
-		});
224
+        $this->registerService('OCP\\INavigationManager', function($c) {
225
+            return $this->getServer()->getNavigationManager();
226
+        });
227 227
 
228
-		$this->registerService('OCP\\Notification\IManager', function($c) {
229
-			return $this->getServer()->getNotificationManager();
230
-		});
228
+        $this->registerService('OCP\\Notification\IManager', function($c) {
229
+            return $this->getServer()->getNotificationManager();
230
+        });
231 231
 
232
-		$this->registerService('OCP\\IPreview', function($c) {
233
-			return $this->getServer()->getPreviewManager();
234
-		});
232
+        $this->registerService('OCP\\IPreview', function($c) {
233
+            return $this->getServer()->getPreviewManager();
234
+        });
235 235
 
236
-		$this->registerService('OCP\\IRequest', function () {
237
-			return $this->getServer()->getRequest();
238
-		});
239
-		$this->registerAlias('Request', 'OCP\\IRequest');
236
+        $this->registerService('OCP\\IRequest', function () {
237
+            return $this->getServer()->getRequest();
238
+        });
239
+        $this->registerAlias('Request', 'OCP\\IRequest');
240 240
 
241
-		$this->registerService('OCP\\ITagManager', function($c) {
242
-			return $this->getServer()->getTagManager();
243
-		});
241
+        $this->registerService('OCP\\ITagManager', function($c) {
242
+            return $this->getServer()->getTagManager();
243
+        });
244 244
 
245
-		$this->registerService('OCP\\ITempManager', function($c) {
246
-			return $this->getServer()->getTempManager();
247
-		});
245
+        $this->registerService('OCP\\ITempManager', function($c) {
246
+            return $this->getServer()->getTempManager();
247
+        });
248 248
 
249
-		$this->registerAlias('OCP\\AppFramework\\Utility\\ITimeFactory', 'OC\AppFramework\Utility\TimeFactory');
250
-		$this->registerAlias('TimeFactory', 'OCP\\AppFramework\\Utility\\ITimeFactory');
249
+        $this->registerAlias('OCP\\AppFramework\\Utility\\ITimeFactory', 'OC\AppFramework\Utility\TimeFactory');
250
+        $this->registerAlias('TimeFactory', 'OCP\\AppFramework\\Utility\\ITimeFactory');
251 251
 
252 252
 
253
-		$this->registerService('OCP\\Route\\IRouter', function($c) {
254
-			return $this->getServer()->getRouter();
255
-		});
253
+        $this->registerService('OCP\\Route\\IRouter', function($c) {
254
+            return $this->getServer()->getRouter();
255
+        });
256 256
 
257
-		$this->registerService('OCP\\ISearch', function($c) {
258
-			return $this->getServer()->getSearch();
259
-		});
257
+        $this->registerService('OCP\\ISearch', function($c) {
258
+            return $this->getServer()->getSearch();
259
+        });
260 260
 
261
-		$this->registerService('OCP\\ISearch', function($c) {
262
-			return $this->getServer()->getSearch();
263
-		});
264
-
265
-		$this->registerService('OCP\\Security\\ICrypto', function($c) {
266
-			return $this->getServer()->getCrypto();
267
-		});
261
+        $this->registerService('OCP\\ISearch', function($c) {
262
+            return $this->getServer()->getSearch();
263
+        });
264
+
265
+        $this->registerService('OCP\\Security\\ICrypto', function($c) {
266
+            return $this->getServer()->getCrypto();
267
+        });
268 268
 
269
-		$this->registerService('OCP\\Security\\IHasher', function($c) {
270
-			return $this->getServer()->getHasher();
271
-		});
272
-
273
-		$this->registerService('OCP\\Security\\ICredentialsManager', function($c) {
274
-			return $this->getServer()->getCredentialsManager();
275
-		});
276
-
277
-		$this->registerService('OCP\\Security\\ISecureRandom', function($c) {
278
-			return $this->getServer()->getSecureRandom();
279
-		});
280
-
281
-		$this->registerService('OCP\\Share\\IManager', function($c) {
282
-			return $this->getServer()->getShareManager();
283
-		});
284
-
285
-		$this->registerService('OCP\\SystemTag\\ISystemTagManager', function() {
286
-			return $this->getServer()->getSystemTagManager();
287
-		});
288
-
289
-		$this->registerService('OCP\\SystemTag\\ISystemTagObjectMapper', function() {
290
-			return $this->getServer()->getSystemTagObjectMapper();
291
-		});
292
-
293
-		$this->registerService('OCP\\IURLGenerator', function($c) {
294
-			return $this->getServer()->getURLGenerator();
295
-		});
296
-
297
-		$this->registerService('OCP\\IUserManager', function($c) {
298
-			return $this->getServer()->getUserManager();
299
-		});
300
-
301
-		$this->registerService('OCP\\IUserSession', function($c) {
302
-			return $this->getServer()->getUserSession();
303
-		});
304
-		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
305
-
306
-		$this->registerService('OCP\\ISession', function($c) {
307
-			return $this->getServer()->getSession();
308
-		});
309
-
310
-		$this->registerService('OCP\\Security\\IContentSecurityPolicyManager', function($c) {
311
-			return $this->getServer()->getContentSecurityPolicyManager();
312
-		});
313
-
314
-		$this->registerService('ServerContainer', function ($c) {
315
-			return $this->getServer();
316
-		});
317
-		$this->registerAlias('OCP\\IServerContainer', 'ServerContainer');
318
-
319
-		$this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function ($c) {
320
-			return $this->getServer()->getEventDispatcher();
321
-		});
322
-
323
-		$this->registerService('OCP\WorkflowEngine\IManager', function ($c) {
324
-			return $c->query('OCA\WorkflowEngine\Manager');
325
-		});
326
-
327
-		$this->registerService('OCP\\AppFramework\\IAppContainer', function ($c) {
328
-			return $c;
329
-		});
330
-		$this->registerService(IMountManager::class, function () {
331
-			return $this->getServer()->getMountManager();
332
-		});
333
-
334
-		// commonly used attributes
335
-		$this->registerService('UserId', function ($c) {
336
-			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
337
-		});
338
-
339
-		$this->registerService('WebRoot', function ($c) {
340
-			return $c->query('ServerContainer')->getWebRoot();
341
-		});
342
-
343
-		$this->registerService('fromMailAddress', function() {
344
-			return Util::getDefaultEmailAddress('no-reply');
345
-		});
346
-
347
-		$this->registerService('OC_Defaults', function ($c) {
348
-			return $c->getServer()->getThemingDefaults();
349
-		});
350
-
351
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
352
-			return $this->getServer()->getEncryptionManager();
353
-		});
354
-
355
-		$this->registerService(IValidator::class, function($c) {
356
-			return $c->query(Validator::class);
357
-		});
358
-
359
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
360
-			return new \OC\Security\IdentityProof\Manager(
361
-				$this->getServer()->getAppDataDir('identityproof'),
362
-				$this->getServer()->getCrypto()
363
-			);
364
-		});
365
-
366
-
367
-		/**
368
-		 * App Framework APIs
369
-		 */
370
-		$this->registerService('API', function($c){
371
-			$c->query('OCP\\ILogger')->debug(
372
-				'Accessing the API class is deprecated! Use the appropriate ' .
373
-				'services instead!'
374
-			);
375
-			return new API($c['AppName']);
376
-		});
377
-
378
-		$this->registerService('Protocol', function($c){
379
-			/** @var \OC\Server $server */
380
-			$server = $c->query('ServerContainer');
381
-			$protocol = $server->getRequest()->getHttpProtocol();
382
-			return new Http($_SERVER, $protocol);
383
-		});
384
-
385
-		$this->registerService('Dispatcher', function($c) {
386
-			return new Dispatcher(
387
-				$c['Protocol'],
388
-				$c['MiddlewareDispatcher'],
389
-				$c['ControllerMethodReflector'],
390
-				$c['Request']
391
-			);
392
-		});
393
-
394
-		/**
395
-		 * App Framework default arguments
396
-		 */
397
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
398
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
399
-		$this->registerParameter('corsMaxAge', 1728000);
400
-
401
-		/**
402
-		 * Middleware
403
-		 */
404
-		$app = $this;
405
-		$this->registerService('SecurityMiddleware', function($c) use ($app){
406
-			/** @var \OC\Server $server */
407
-			$server = $app->getServer();
408
-
409
-			return new SecurityMiddleware(
410
-				$c['Request'],
411
-				$c['ControllerMethodReflector'],
412
-				$server->getNavigationManager(),
413
-				$server->getURLGenerator(),
414
-				$server->getLogger(),
415
-				$server->getSession(),
416
-				$c['AppName'],
417
-				$app->isLoggedIn(),
418
-				$app->isAdminUser(),
419
-				$server->getContentSecurityPolicyManager(),
420
-				$server->getCsrfTokenManager(),
421
-				$server->getContentSecurityPolicyNonceManager(),
422
-				$server->getBruteForceThrottler()
423
-			);
424
-
425
-		});
426
-
427
-		$this->registerService('CORSMiddleware', function($c) {
428
-			return new CORSMiddleware(
429
-				$c['Request'],
430
-				$c['ControllerMethodReflector'],
431
-				$c['OCP\IUserSession'],
432
-				$c->getServer()->getBruteForceThrottler()
433
-			);
434
-		});
435
-
436
-		$this->registerService('SessionMiddleware', function($c) use ($app) {
437
-			return new SessionMiddleware(
438
-				$c['Request'],
439
-				$c['ControllerMethodReflector'],
440
-				$app->getServer()->getSession()
441
-			);
442
-		});
443
-
444
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
445
-			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
446
-			$userSession = $app->getServer()->getUserSession();
447
-			$session = $app->getServer()->getSession();
448
-			$urlGenerator = $app->getServer()->getURLGenerator();
449
-			$reflector = $c['ControllerMethodReflector'];
450
-			$request = $app->getServer()->getRequest();
451
-			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
452
-		});
453
-
454
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
455
-			return new OCSMiddleware(
456
-				$c['Request']
457
-			);
458
-		});
459
-
460
-		$middleWares = &$this->middleWares;
461
-		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
462
-			$dispatcher = new MiddlewareDispatcher();
463
-			$dispatcher->registerMiddleware($c['CORSMiddleware']);
464
-			$dispatcher->registerMiddleware($c['OCSMiddleware']);
465
-			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
466
-			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
467
-
468
-			foreach($middleWares as $middleWare) {
469
-				$dispatcher->registerMiddleware($c[$middleWare]);
470
-			}
471
-
472
-			$dispatcher->registerMiddleware($c['SessionMiddleware']);
473
-			return $dispatcher;
474
-		});
475
-
476
-	}
477
-
478
-
479
-	/**
480
-	 * @deprecated implements only deprecated methods
481
-	 * @return IApi
482
-	 */
483
-	function getCoreApi()
484
-	{
485
-		return $this->query('API');
486
-	}
487
-
488
-	/**
489
-	 * @return \OCP\IServerContainer
490
-	 */
491
-	function getServer()
492
-	{
493
-		return OC::$server;
494
-	}
495
-
496
-	/**
497
-	 * @param string $middleWare
498
-	 * @return boolean|null
499
-	 */
500
-	function registerMiddleWare($middleWare) {
501
-		array_push($this->middleWares, $middleWare);
502
-	}
503
-
504
-	/**
505
-	 * used to return the appname of the set application
506
-	 * @return string the name of your application
507
-	 */
508
-	function getAppName() {
509
-		return $this->query('AppName');
510
-	}
511
-
512
-	/**
513
-	 * @deprecated use IUserSession->isLoggedIn()
514
-	 * @return boolean
515
-	 */
516
-	function isLoggedIn() {
517
-		return \OC::$server->getUserSession()->isLoggedIn();
518
-	}
519
-
520
-	/**
521
-	 * @deprecated use IGroupManager->isAdmin($userId)
522
-	 * @return boolean
523
-	 */
524
-	function isAdminUser() {
525
-		$uid = $this->getUserId();
526
-		return \OC_User::isAdminUser($uid);
527
-	}
528
-
529
-	private function getUserId() {
530
-		return $this->getServer()->getSession()->get('user_id');
531
-	}
532
-
533
-	/**
534
-	 * @deprecated use the ILogger instead
535
-	 * @param string $message
536
-	 * @param string $level
537
-	 * @return mixed
538
-	 */
539
-	function log($message, $level) {
540
-		switch($level){
541
-			case 'debug':
542
-				$level = \OCP\Util::DEBUG;
543
-				break;
544
-			case 'info':
545
-				$level = \OCP\Util::INFO;
546
-				break;
547
-			case 'warn':
548
-				$level = \OCP\Util::WARN;
549
-				break;
550
-			case 'fatal':
551
-				$level = \OCP\Util::FATAL;
552
-				break;
553
-			default:
554
-				$level = \OCP\Util::ERROR;
555
-				break;
556
-		}
557
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
558
-	}
559
-
560
-	/**
561
-	 * Register a capability
562
-	 *
563
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
564
-	 */
565
-	public function registerCapability($serviceName) {
566
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
567
-			return $this->query($serviceName);
568
-		});
569
-	}
570
-
571
-	public function query($name) {
572
-		return parent::query($name);
573
-	}
269
+        $this->registerService('OCP\\Security\\IHasher', function($c) {
270
+            return $this->getServer()->getHasher();
271
+        });
272
+
273
+        $this->registerService('OCP\\Security\\ICredentialsManager', function($c) {
274
+            return $this->getServer()->getCredentialsManager();
275
+        });
276
+
277
+        $this->registerService('OCP\\Security\\ISecureRandom', function($c) {
278
+            return $this->getServer()->getSecureRandom();
279
+        });
280
+
281
+        $this->registerService('OCP\\Share\\IManager', function($c) {
282
+            return $this->getServer()->getShareManager();
283
+        });
284
+
285
+        $this->registerService('OCP\\SystemTag\\ISystemTagManager', function() {
286
+            return $this->getServer()->getSystemTagManager();
287
+        });
288
+
289
+        $this->registerService('OCP\\SystemTag\\ISystemTagObjectMapper', function() {
290
+            return $this->getServer()->getSystemTagObjectMapper();
291
+        });
292
+
293
+        $this->registerService('OCP\\IURLGenerator', function($c) {
294
+            return $this->getServer()->getURLGenerator();
295
+        });
296
+
297
+        $this->registerService('OCP\\IUserManager', function($c) {
298
+            return $this->getServer()->getUserManager();
299
+        });
300
+
301
+        $this->registerService('OCP\\IUserSession', function($c) {
302
+            return $this->getServer()->getUserSession();
303
+        });
304
+        $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
305
+
306
+        $this->registerService('OCP\\ISession', function($c) {
307
+            return $this->getServer()->getSession();
308
+        });
309
+
310
+        $this->registerService('OCP\\Security\\IContentSecurityPolicyManager', function($c) {
311
+            return $this->getServer()->getContentSecurityPolicyManager();
312
+        });
313
+
314
+        $this->registerService('ServerContainer', function ($c) {
315
+            return $this->getServer();
316
+        });
317
+        $this->registerAlias('OCP\\IServerContainer', 'ServerContainer');
318
+
319
+        $this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function ($c) {
320
+            return $this->getServer()->getEventDispatcher();
321
+        });
322
+
323
+        $this->registerService('OCP\WorkflowEngine\IManager', function ($c) {
324
+            return $c->query('OCA\WorkflowEngine\Manager');
325
+        });
326
+
327
+        $this->registerService('OCP\\AppFramework\\IAppContainer', function ($c) {
328
+            return $c;
329
+        });
330
+        $this->registerService(IMountManager::class, function () {
331
+            return $this->getServer()->getMountManager();
332
+        });
333
+
334
+        // commonly used attributes
335
+        $this->registerService('UserId', function ($c) {
336
+            return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
337
+        });
338
+
339
+        $this->registerService('WebRoot', function ($c) {
340
+            return $c->query('ServerContainer')->getWebRoot();
341
+        });
342
+
343
+        $this->registerService('fromMailAddress', function() {
344
+            return Util::getDefaultEmailAddress('no-reply');
345
+        });
346
+
347
+        $this->registerService('OC_Defaults', function ($c) {
348
+            return $c->getServer()->getThemingDefaults();
349
+        });
350
+
351
+        $this->registerService('OCP\Encryption\IManager', function ($c) {
352
+            return $this->getServer()->getEncryptionManager();
353
+        });
354
+
355
+        $this->registerService(IValidator::class, function($c) {
356
+            return $c->query(Validator::class);
357
+        });
358
+
359
+        $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
360
+            return new \OC\Security\IdentityProof\Manager(
361
+                $this->getServer()->getAppDataDir('identityproof'),
362
+                $this->getServer()->getCrypto()
363
+            );
364
+        });
365
+
366
+
367
+        /**
368
+         * App Framework APIs
369
+         */
370
+        $this->registerService('API', function($c){
371
+            $c->query('OCP\\ILogger')->debug(
372
+                'Accessing the API class is deprecated! Use the appropriate ' .
373
+                'services instead!'
374
+            );
375
+            return new API($c['AppName']);
376
+        });
377
+
378
+        $this->registerService('Protocol', function($c){
379
+            /** @var \OC\Server $server */
380
+            $server = $c->query('ServerContainer');
381
+            $protocol = $server->getRequest()->getHttpProtocol();
382
+            return new Http($_SERVER, $protocol);
383
+        });
384
+
385
+        $this->registerService('Dispatcher', function($c) {
386
+            return new Dispatcher(
387
+                $c['Protocol'],
388
+                $c['MiddlewareDispatcher'],
389
+                $c['ControllerMethodReflector'],
390
+                $c['Request']
391
+            );
392
+        });
393
+
394
+        /**
395
+         * App Framework default arguments
396
+         */
397
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
398
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
399
+        $this->registerParameter('corsMaxAge', 1728000);
400
+
401
+        /**
402
+         * Middleware
403
+         */
404
+        $app = $this;
405
+        $this->registerService('SecurityMiddleware', function($c) use ($app){
406
+            /** @var \OC\Server $server */
407
+            $server = $app->getServer();
408
+
409
+            return new SecurityMiddleware(
410
+                $c['Request'],
411
+                $c['ControllerMethodReflector'],
412
+                $server->getNavigationManager(),
413
+                $server->getURLGenerator(),
414
+                $server->getLogger(),
415
+                $server->getSession(),
416
+                $c['AppName'],
417
+                $app->isLoggedIn(),
418
+                $app->isAdminUser(),
419
+                $server->getContentSecurityPolicyManager(),
420
+                $server->getCsrfTokenManager(),
421
+                $server->getContentSecurityPolicyNonceManager(),
422
+                $server->getBruteForceThrottler()
423
+            );
424
+
425
+        });
426
+
427
+        $this->registerService('CORSMiddleware', function($c) {
428
+            return new CORSMiddleware(
429
+                $c['Request'],
430
+                $c['ControllerMethodReflector'],
431
+                $c['OCP\IUserSession'],
432
+                $c->getServer()->getBruteForceThrottler()
433
+            );
434
+        });
435
+
436
+        $this->registerService('SessionMiddleware', function($c) use ($app) {
437
+            return new SessionMiddleware(
438
+                $c['Request'],
439
+                $c['ControllerMethodReflector'],
440
+                $app->getServer()->getSession()
441
+            );
442
+        });
443
+
444
+        $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
445
+            $twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
446
+            $userSession = $app->getServer()->getUserSession();
447
+            $session = $app->getServer()->getSession();
448
+            $urlGenerator = $app->getServer()->getURLGenerator();
449
+            $reflector = $c['ControllerMethodReflector'];
450
+            $request = $app->getServer()->getRequest();
451
+            return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
452
+        });
453
+
454
+        $this->registerService('OCSMiddleware', function (SimpleContainer $c) {
455
+            return new OCSMiddleware(
456
+                $c['Request']
457
+            );
458
+        });
459
+
460
+        $middleWares = &$this->middleWares;
461
+        $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
462
+            $dispatcher = new MiddlewareDispatcher();
463
+            $dispatcher->registerMiddleware($c['CORSMiddleware']);
464
+            $dispatcher->registerMiddleware($c['OCSMiddleware']);
465
+            $dispatcher->registerMiddleware($c['SecurityMiddleware']);
466
+            $dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
467
+
468
+            foreach($middleWares as $middleWare) {
469
+                $dispatcher->registerMiddleware($c[$middleWare]);
470
+            }
471
+
472
+            $dispatcher->registerMiddleware($c['SessionMiddleware']);
473
+            return $dispatcher;
474
+        });
475
+
476
+    }
477
+
478
+
479
+    /**
480
+     * @deprecated implements only deprecated methods
481
+     * @return IApi
482
+     */
483
+    function getCoreApi()
484
+    {
485
+        return $this->query('API');
486
+    }
487
+
488
+    /**
489
+     * @return \OCP\IServerContainer
490
+     */
491
+    function getServer()
492
+    {
493
+        return OC::$server;
494
+    }
495
+
496
+    /**
497
+     * @param string $middleWare
498
+     * @return boolean|null
499
+     */
500
+    function registerMiddleWare($middleWare) {
501
+        array_push($this->middleWares, $middleWare);
502
+    }
503
+
504
+    /**
505
+     * used to return the appname of the set application
506
+     * @return string the name of your application
507
+     */
508
+    function getAppName() {
509
+        return $this->query('AppName');
510
+    }
511
+
512
+    /**
513
+     * @deprecated use IUserSession->isLoggedIn()
514
+     * @return boolean
515
+     */
516
+    function isLoggedIn() {
517
+        return \OC::$server->getUserSession()->isLoggedIn();
518
+    }
519
+
520
+    /**
521
+     * @deprecated use IGroupManager->isAdmin($userId)
522
+     * @return boolean
523
+     */
524
+    function isAdminUser() {
525
+        $uid = $this->getUserId();
526
+        return \OC_User::isAdminUser($uid);
527
+    }
528
+
529
+    private function getUserId() {
530
+        return $this->getServer()->getSession()->get('user_id');
531
+    }
532
+
533
+    /**
534
+     * @deprecated use the ILogger instead
535
+     * @param string $message
536
+     * @param string $level
537
+     * @return mixed
538
+     */
539
+    function log($message, $level) {
540
+        switch($level){
541
+            case 'debug':
542
+                $level = \OCP\Util::DEBUG;
543
+                break;
544
+            case 'info':
545
+                $level = \OCP\Util::INFO;
546
+                break;
547
+            case 'warn':
548
+                $level = \OCP\Util::WARN;
549
+                break;
550
+            case 'fatal':
551
+                $level = \OCP\Util::FATAL;
552
+                break;
553
+            default:
554
+                $level = \OCP\Util::ERROR;
555
+                break;
556
+        }
557
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
558
+    }
559
+
560
+    /**
561
+     * Register a capability
562
+     *
563
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
564
+     */
565
+    public function registerCapability($serviceName) {
566
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
567
+            return $this->query($serviceName);
568
+        });
569
+    }
570
+
571
+    public function query($name) {
572
+        return parent::query($name);
573
+    }
574 574
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/CardDavBackend.php 4 patches
Doc Comments   +11 added lines, -3 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 	/**
105 105
 	 * Return the number of address books for a principal
106 106
 	 *
107
-	 * @param $principalUri
107
+	 * @param string $principalUri
108 108
 	 * @return int
109 109
 	 */
110 110
 	public function getAddressBooksForUserCount($principalUri) {
@@ -195,6 +195,9 @@  discard block
 block discarded – undo
195 195
 		return array_values($addressBooks);
196 196
 	}
197 197
 
198
+	/**
199
+	 * @param string $principalUri
200
+	 */
198 201
 	public function getUsersOwnAddressBooks($principalUri) {
199 202
 		$principalUriOriginal = $principalUri;
200 203
 		$principalUri = $this->convertPrincipal($principalUri, true);
@@ -264,7 +267,8 @@  discard block
 block discarded – undo
264 267
 	}
265 268
 
266 269
 	/**
267
-	 * @param $addressBookUri
270
+	 * @param string $addressBookUri
271
+	 * @param string $principal
268 272
 	 * @return array|null
269 273
 	 */
270 274
 	public function getAddressBooksByUri($principal, $addressBookUri) {
@@ -953,6 +957,7 @@  discard block
 block discarded – undo
953 957
 	 *   * readOnly - boolean
954 958
 	 *   * summary - Optional, a description for the share
955 959
 	 *
960
+	 * @param integer $addressBookId
956 961
 	 * @return array
957 962
 	 */
958 963
 	public function getShares($addressBookId) {
@@ -1052,7 +1057,7 @@  discard block
 block discarded – undo
1052 1057
 
1053 1058
 	/**
1054 1059
 	 * For shared address books the sharee is set in the ACL of the address book
1055
-	 * @param $addressBookId
1060
+	 * @param integer $addressBookId
1056 1061
 	 * @param $acl
1057 1062
 	 * @return array
1058 1063
 	 */
@@ -1060,6 +1065,9 @@  discard block
 block discarded – undo
1060 1065
 		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1061 1066
 	}
1062 1067
 
1068
+	/**
1069
+	 * @param boolean $toV2
1070
+	 */
1063 1071
 	private function convertPrincipal($principalUri, $toV2) {
1064 1072
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1065 1073
 			list(, $name) = URLUtil::splitPath($principalUri);
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -745,7 +745,9 @@
 block discarded – undo
745 745
 		$stmt->execute([ $addressBookId ]);
746 746
 		$currentToken = $stmt->fetchColumn(0);
747 747
 
748
-		if (is_null($currentToken)) return null;
748
+		if (is_null($currentToken)) {
749
+		    return null;
750
+		}
749 751
 
750 752
 		$result = [
751 753
 			'syncToken' => $currentToken,
Please login to merge, or discard this patch.
Indentation   +1031 added lines, -1031 removed lines patch added patch discarded remove patch
@@ -48,1035 +48,1035 @@
 block discarded – undo
48 48
 
49 49
 class CardDavBackend implements BackendInterface, SyncSupport {
50 50
 
51
-	const PERSONAL_ADDRESSBOOK_URI = 'contacts';
52
-	const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
53
-
54
-	/** @var Principal */
55
-	private $principalBackend;
56
-
57
-	/** @var string */
58
-	private $dbCardsTable = 'cards';
59
-
60
-	/** @var string */
61
-	private $dbCardsPropertiesTable = 'cards_properties';
62
-
63
-	/** @var IDBConnection */
64
-	private $db;
65
-
66
-	/** @var Backend */
67
-	private $sharingBackend;
68
-
69
-	/** @var array properties to index */
70
-	public static $indexProperties = array(
71
-			'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
72
-			'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
73
-
74
-	/**
75
-	 * @var string[] Map of uid => display name
76
-	 */
77
-	protected $userDisplayNames;
78
-
79
-	/** @var IUserManager */
80
-	private $userManager;
81
-
82
-	/** @var EventDispatcherInterface */
83
-	private $dispatcher;
84
-
85
-	/**
86
-	 * CardDavBackend constructor.
87
-	 *
88
-	 * @param IDBConnection $db
89
-	 * @param Principal $principalBackend
90
-	 * @param IUserManager $userManager
91
-	 * @param EventDispatcherInterface $dispatcher
92
-	 */
93
-	public function __construct(IDBConnection $db,
94
-								Principal $principalBackend,
95
-								IUserManager $userManager,
96
-								EventDispatcherInterface $dispatcher = null) {
97
-		$this->db = $db;
98
-		$this->principalBackend = $principalBackend;
99
-		$this->userManager = $userManager;
100
-		$this->dispatcher = $dispatcher;
101
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'addressbook');
102
-	}
103
-
104
-	/**
105
-	 * Return the number of address books for a principal
106
-	 *
107
-	 * @param $principalUri
108
-	 * @return int
109
-	 */
110
-	public function getAddressBooksForUserCount($principalUri) {
111
-		$principalUri = $this->convertPrincipal($principalUri, true);
112
-		$query = $this->db->getQueryBuilder();
113
-		$query->select($query->createFunction('COUNT(*)'))
114
-			->from('addressbooks')
115
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116
-
117
-		return (int)$query->execute()->fetchColumn();
118
-	}
119
-
120
-	/**
121
-	 * Returns the list of address books for a specific user.
122
-	 *
123
-	 * Every addressbook should have the following properties:
124
-	 *   id - an arbitrary unique id
125
-	 *   uri - the 'basename' part of the url
126
-	 *   principaluri - Same as the passed parameter
127
-	 *
128
-	 * Any additional clark-notation property may be passed besides this. Some
129
-	 * common ones are :
130
-	 *   {DAV:}displayname
131
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
132
-	 *   {http://calendarserver.org/ns/}getctag
133
-	 *
134
-	 * @param string $principalUri
135
-	 * @return array
136
-	 */
137
-	function getAddressBooksForUser($principalUri) {
138
-		$principalUriOriginal = $principalUri;
139
-		$principalUri = $this->convertPrincipal($principalUri, true);
140
-		$query = $this->db->getQueryBuilder();
141
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
142
-			->from('addressbooks')
143
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
144
-
145
-		$addressBooks = [];
146
-
147
-		$result = $query->execute();
148
-		while($row = $result->fetch()) {
149
-			$addressBooks[$row['id']] = [
150
-				'id'  => $row['id'],
151
-				'uri' => $row['uri'],
152
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153
-				'{DAV:}displayname' => $row['displayname'],
154
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
155
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
157
-			];
158
-		}
159
-		$result->closeCursor();
160
-
161
-		// query for shared calendars
162
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
-		$principals[]= $principalUri;
164
-
165
-		$query = $this->db->getQueryBuilder();
166
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
167
-			->from('dav_shares', 's')
168
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
169
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
170
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
171
-			->setParameter('type', 'addressbook')
172
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173
-			->execute();
174
-
175
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
176
-		while($row = $result->fetch()) {
177
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
178
-			if (isset($addressBooks[$row['id']])) {
179
-				if ($readOnly) {
180
-					// New share can not have more permissions then the old one.
181
-					continue;
182
-				}
183
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
184
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
185
-					// Old share is already read-write, no more permissions can be gained
186
-					continue;
187
-				}
188
-			}
189
-
190
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
191
-			$uri = $row['uri'] . '_shared_by_' . $name;
192
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
193
-
194
-			$addressBooks[$row['id']] = [
195
-				'id'  => $row['id'],
196
-				'uri' => $uri,
197
-				'principaluri' => $principalUriOriginal,
198
-				'{DAV:}displayname' => $displayName,
199
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
200
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
201
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
202
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
203
-				$readOnlyPropertyName => $readOnly,
204
-			];
205
-		}
206
-		$result->closeCursor();
207
-
208
-		return array_values($addressBooks);
209
-	}
210
-
211
-	public function getUsersOwnAddressBooks($principalUri) {
212
-		$principalUriOriginal = $principalUri;
213
-		$principalUri = $this->convertPrincipal($principalUri, true);
214
-		$query = $this->db->getQueryBuilder();
215
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
216
-			  ->from('addressbooks')
217
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
218
-
219
-		$addressBooks = [];
220
-
221
-		$result = $query->execute();
222
-		while($row = $result->fetch()) {
223
-			$addressBooks[$row['id']] = [
224
-				'id'  => $row['id'],
225
-				'uri' => $row['uri'],
226
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
227
-				'{DAV:}displayname' => $row['displayname'],
228
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
229
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
230
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
231
-			];
232
-		}
233
-		$result->closeCursor();
234
-
235
-		return array_values($addressBooks);
236
-	}
237
-
238
-	private function getUserDisplayName($uid) {
239
-		if (!isset($this->userDisplayNames[$uid])) {
240
-			$user = $this->userManager->get($uid);
241
-
242
-			if ($user instanceof IUser) {
243
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
244
-			} else {
245
-				$this->userDisplayNames[$uid] = $uid;
246
-			}
247
-		}
248
-
249
-		return $this->userDisplayNames[$uid];
250
-	}
251
-
252
-	/**
253
-	 * @param int $addressBookId
254
-	 */
255
-	public function getAddressBookById($addressBookId) {
256
-		$query = $this->db->getQueryBuilder();
257
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
258
-			->from('addressbooks')
259
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
260
-			->execute();
261
-
262
-		$row = $result->fetch();
263
-		$result->closeCursor();
264
-		if ($row === false) {
265
-			return null;
266
-		}
267
-
268
-		return [
269
-			'id'  => $row['id'],
270
-			'uri' => $row['uri'],
271
-			'principaluri' => $row['principaluri'],
272
-			'{DAV:}displayname' => $row['displayname'],
273
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
274
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
275
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
276
-		];
277
-	}
278
-
279
-	/**
280
-	 * @param $addressBookUri
281
-	 * @return array|null
282
-	 */
283
-	public function getAddressBooksByUri($principal, $addressBookUri) {
284
-		$query = $this->db->getQueryBuilder();
285
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
286
-			->from('addressbooks')
287
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
288
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
289
-			->setMaxResults(1)
290
-			->execute();
291
-
292
-		$row = $result->fetch();
293
-		$result->closeCursor();
294
-		if ($row === false) {
295
-			return null;
296
-		}
297
-
298
-		return [
299
-				'id'  => $row['id'],
300
-				'uri' => $row['uri'],
301
-				'principaluri' => $row['principaluri'],
302
-				'{DAV:}displayname' => $row['displayname'],
303
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
304
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
305
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
306
-			];
307
-	}
308
-
309
-	/**
310
-	 * Updates properties for an address book.
311
-	 *
312
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
313
-	 * To do the actual updates, you must tell this object which properties
314
-	 * you're going to process with the handle() method.
315
-	 *
316
-	 * Calling the handle method is like telling the PropPatch object "I
317
-	 * promise I can handle updating this property".
318
-	 *
319
-	 * Read the PropPatch documentation for more info and examples.
320
-	 *
321
-	 * @param string $addressBookId
322
-	 * @param \Sabre\DAV\PropPatch $propPatch
323
-	 * @return void
324
-	 */
325
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
326
-		$supportedProperties = [
327
-			'{DAV:}displayname',
328
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
329
-		];
330
-
331
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
332
-
333
-			$updates = [];
334
-			foreach($mutations as $property=>$newValue) {
335
-
336
-				switch($property) {
337
-					case '{DAV:}displayname' :
338
-						$updates['displayname'] = $newValue;
339
-						break;
340
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
341
-						$updates['description'] = $newValue;
342
-						break;
343
-				}
344
-			}
345
-			$query = $this->db->getQueryBuilder();
346
-			$query->update('addressbooks');
347
-
348
-			foreach($updates as $key=>$value) {
349
-				$query->set($key, $query->createNamedParameter($value));
350
-			}
351
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
352
-			->execute();
353
-
354
-			$this->addChange($addressBookId, "", 2);
355
-
356
-			return true;
357
-
358
-		});
359
-	}
360
-
361
-	/**
362
-	 * Creates a new address book
363
-	 *
364
-	 * @param string $principalUri
365
-	 * @param string $url Just the 'basename' of the url.
366
-	 * @param array $properties
367
-	 * @return int
368
-	 * @throws BadRequest
369
-	 */
370
-	function createAddressBook($principalUri, $url, array $properties) {
371
-		$values = [
372
-			'displayname' => null,
373
-			'description' => null,
374
-			'principaluri' => $principalUri,
375
-			'uri' => $url,
376
-			'synctoken' => 1
377
-		];
378
-
379
-		foreach($properties as $property=>$newValue) {
380
-
381
-			switch($property) {
382
-				case '{DAV:}displayname' :
383
-					$values['displayname'] = $newValue;
384
-					break;
385
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
386
-					$values['description'] = $newValue;
387
-					break;
388
-				default :
389
-					throw new BadRequest('Unknown property: ' . $property);
390
-			}
391
-
392
-		}
393
-
394
-		// Fallback to make sure the displayname is set. Some clients may refuse
395
-		// to work with addressbooks not having a displayname.
396
-		if(is_null($values['displayname'])) {
397
-			$values['displayname'] = $url;
398
-		}
399
-
400
-		$query = $this->db->getQueryBuilder();
401
-		$query->insert('addressbooks')
402
-			->values([
403
-				'uri' => $query->createParameter('uri'),
404
-				'displayname' => $query->createParameter('displayname'),
405
-				'description' => $query->createParameter('description'),
406
-				'principaluri' => $query->createParameter('principaluri'),
407
-				'synctoken' => $query->createParameter('synctoken'),
408
-			])
409
-			->setParameters($values)
410
-			->execute();
411
-
412
-		return $query->getLastInsertId();
413
-	}
414
-
415
-	/**
416
-	 * Deletes an entire addressbook and all its contents
417
-	 *
418
-	 * @param mixed $addressBookId
419
-	 * @return void
420
-	 */
421
-	function deleteAddressBook($addressBookId) {
422
-		$query = $this->db->getQueryBuilder();
423
-		$query->delete('cards')
424
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
425
-			->setParameter('addressbookid', $addressBookId)
426
-			->execute();
427
-
428
-		$query->delete('addressbookchanges')
429
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
430
-			->setParameter('addressbookid', $addressBookId)
431
-			->execute();
432
-
433
-		$query->delete('addressbooks')
434
-			->where($query->expr()->eq('id', $query->createParameter('id')))
435
-			->setParameter('id', $addressBookId)
436
-			->execute();
437
-
438
-		$this->sharingBackend->deleteAllShares($addressBookId);
439
-
440
-		$query->delete($this->dbCardsPropertiesTable)
441
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
442
-			->execute();
443
-
444
-	}
445
-
446
-	/**
447
-	 * Returns all cards for a specific addressbook id.
448
-	 *
449
-	 * This method should return the following properties for each card:
450
-	 *   * carddata - raw vcard data
451
-	 *   * uri - Some unique url
452
-	 *   * lastmodified - A unix timestamp
453
-	 *
454
-	 * It's recommended to also return the following properties:
455
-	 *   * etag - A unique etag. This must change every time the card changes.
456
-	 *   * size - The size of the card in bytes.
457
-	 *
458
-	 * If these last two properties are provided, less time will be spent
459
-	 * calculating them. If they are specified, you can also ommit carddata.
460
-	 * This may speed up certain requests, especially with large cards.
461
-	 *
462
-	 * @param mixed $addressBookId
463
-	 * @return array
464
-	 */
465
-	function getCards($addressBookId) {
466
-		$query = $this->db->getQueryBuilder();
467
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
468
-			->from('cards')
469
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
470
-
471
-		$cards = [];
472
-
473
-		$result = $query->execute();
474
-		while($row = $result->fetch()) {
475
-			$row['etag'] = '"' . $row['etag'] . '"';
476
-			$row['carddata'] = $this->readBlob($row['carddata']);
477
-			$cards[] = $row;
478
-		}
479
-		$result->closeCursor();
480
-
481
-		return $cards;
482
-	}
483
-
484
-	/**
485
-	 * Returns a specific card.
486
-	 *
487
-	 * The same set of properties must be returned as with getCards. The only
488
-	 * exception is that 'carddata' is absolutely required.
489
-	 *
490
-	 * If the card does not exist, you must return false.
491
-	 *
492
-	 * @param mixed $addressBookId
493
-	 * @param string $cardUri
494
-	 * @return array
495
-	 */
496
-	function getCard($addressBookId, $cardUri) {
497
-		$query = $this->db->getQueryBuilder();
498
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
499
-			->from('cards')
500
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
501
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
502
-			->setMaxResults(1);
503
-
504
-		$result = $query->execute();
505
-		$row = $result->fetch();
506
-		if (!$row) {
507
-			return false;
508
-		}
509
-		$row['etag'] = '"' . $row['etag'] . '"';
510
-		$row['carddata'] = $this->readBlob($row['carddata']);
511
-
512
-		return $row;
513
-	}
514
-
515
-	/**
516
-	 * Returns a list of cards.
517
-	 *
518
-	 * This method should work identical to getCard, but instead return all the
519
-	 * cards in the list as an array.
520
-	 *
521
-	 * If the backend supports this, it may allow for some speed-ups.
522
-	 *
523
-	 * @param mixed $addressBookId
524
-	 * @param string[] $uris
525
-	 * @return array
526
-	 */
527
-	function getMultipleCards($addressBookId, array $uris) {
528
-		if (empty($uris)) {
529
-			return [];
530
-		}
531
-
532
-		$chunks = array_chunk($uris, 100);
533
-		$cards = [];
534
-
535
-		$query = $this->db->getQueryBuilder();
536
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
537
-			->from('cards')
538
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
539
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
540
-
541
-		foreach ($chunks as $uris) {
542
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
543
-			$result = $query->execute();
544
-
545
-			while ($row = $result->fetch()) {
546
-				$row['etag'] = '"' . $row['etag'] . '"';
547
-				$row['carddata'] = $this->readBlob($row['carddata']);
548
-				$cards[] = $row;
549
-			}
550
-			$result->closeCursor();
551
-		}
552
-		return $cards;
553
-	}
554
-
555
-	/**
556
-	 * Creates a new card.
557
-	 *
558
-	 * The addressbook id will be passed as the first argument. This is the
559
-	 * same id as it is returned from the getAddressBooksForUser method.
560
-	 *
561
-	 * The cardUri is a base uri, and doesn't include the full path. The
562
-	 * cardData argument is the vcard body, and is passed as a string.
563
-	 *
564
-	 * It is possible to return an ETag from this method. This ETag is for the
565
-	 * newly created resource, and must be enclosed with double quotes (that
566
-	 * is, the string itself must contain the double quotes).
567
-	 *
568
-	 * You should only return the ETag if you store the carddata as-is. If a
569
-	 * subsequent GET request on the same card does not have the same body,
570
-	 * byte-by-byte and you did return an ETag here, clients tend to get
571
-	 * confused.
572
-	 *
573
-	 * If you don't return an ETag, you can just return null.
574
-	 *
575
-	 * @param mixed $addressBookId
576
-	 * @param string $cardUri
577
-	 * @param string $cardData
578
-	 * @return string
579
-	 */
580
-	function createCard($addressBookId, $cardUri, $cardData) {
581
-		$etag = md5($cardData);
582
-
583
-		$query = $this->db->getQueryBuilder();
584
-		$query->insert('cards')
585
-			->values([
586
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
587
-				'uri' => $query->createNamedParameter($cardUri),
588
-				'lastmodified' => $query->createNamedParameter(time()),
589
-				'addressbookid' => $query->createNamedParameter($addressBookId),
590
-				'size' => $query->createNamedParameter(strlen($cardData)),
591
-				'etag' => $query->createNamedParameter($etag),
592
-			])
593
-			->execute();
594
-
595
-		$this->addChange($addressBookId, $cardUri, 1);
596
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
597
-
598
-		if (!is_null($this->dispatcher)) {
599
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
600
-				new GenericEvent(null, [
601
-					'addressBookId' => $addressBookId,
602
-					'cardUri' => $cardUri,
603
-					'cardData' => $cardData]));
604
-		}
605
-
606
-		return '"' . $etag . '"';
607
-	}
608
-
609
-	/**
610
-	 * Updates a card.
611
-	 *
612
-	 * The addressbook id will be passed as the first argument. This is the
613
-	 * same id as it is returned from the getAddressBooksForUser method.
614
-	 *
615
-	 * The cardUri is a base uri, and doesn't include the full path. The
616
-	 * cardData argument is the vcard body, and is passed as a string.
617
-	 *
618
-	 * It is possible to return an ETag from this method. This ETag should
619
-	 * match that of the updated resource, and must be enclosed with double
620
-	 * quotes (that is: the string itself must contain the actual quotes).
621
-	 *
622
-	 * You should only return the ETag if you store the carddata as-is. If a
623
-	 * subsequent GET request on the same card does not have the same body,
624
-	 * byte-by-byte and you did return an ETag here, clients tend to get
625
-	 * confused.
626
-	 *
627
-	 * If you don't return an ETag, you can just return null.
628
-	 *
629
-	 * @param mixed $addressBookId
630
-	 * @param string $cardUri
631
-	 * @param string $cardData
632
-	 * @return string
633
-	 */
634
-	function updateCard($addressBookId, $cardUri, $cardData) {
635
-
636
-		$etag = md5($cardData);
637
-		$query = $this->db->getQueryBuilder();
638
-		$query->update('cards')
639
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
640
-			->set('lastmodified', $query->createNamedParameter(time()))
641
-			->set('size', $query->createNamedParameter(strlen($cardData)))
642
-			->set('etag', $query->createNamedParameter($etag))
643
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
644
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
645
-			->execute();
646
-
647
-		$this->addChange($addressBookId, $cardUri, 2);
648
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
649
-
650
-		if (!is_null($this->dispatcher)) {
651
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
652
-				new GenericEvent(null, [
653
-					'addressBookId' => $addressBookId,
654
-					'cardUri' => $cardUri,
655
-					'cardData' => $cardData]));
656
-		}
657
-
658
-		return '"' . $etag . '"';
659
-	}
660
-
661
-	/**
662
-	 * Deletes a card
663
-	 *
664
-	 * @param mixed $addressBookId
665
-	 * @param string $cardUri
666
-	 * @return bool
667
-	 */
668
-	function deleteCard($addressBookId, $cardUri) {
669
-		try {
670
-			$cardId = $this->getCardId($addressBookId, $cardUri);
671
-		} catch (\InvalidArgumentException $e) {
672
-			$cardId = null;
673
-		}
674
-		$query = $this->db->getQueryBuilder();
675
-		$ret = $query->delete('cards')
676
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
677
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
678
-			->execute();
679
-
680
-		$this->addChange($addressBookId, $cardUri, 3);
681
-
682
-		if (!is_null($this->dispatcher)) {
683
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
684
-				new GenericEvent(null, [
685
-					'addressBookId' => $addressBookId,
686
-					'cardUri' => $cardUri]));
687
-		}
688
-
689
-		if ($ret === 1) {
690
-			if ($cardId !== null) {
691
-				$this->purgeProperties($addressBookId, $cardId);
692
-			}
693
-			return true;
694
-		}
695
-
696
-		return false;
697
-	}
698
-
699
-	/**
700
-	 * The getChanges method returns all the changes that have happened, since
701
-	 * the specified syncToken in the specified address book.
702
-	 *
703
-	 * This function should return an array, such as the following:
704
-	 *
705
-	 * [
706
-	 *   'syncToken' => 'The current synctoken',
707
-	 *   'added'   => [
708
-	 *      'new.txt',
709
-	 *   ],
710
-	 *   'modified'   => [
711
-	 *      'modified.txt',
712
-	 *   ],
713
-	 *   'deleted' => [
714
-	 *      'foo.php.bak',
715
-	 *      'old.txt'
716
-	 *   ]
717
-	 * ];
718
-	 *
719
-	 * The returned syncToken property should reflect the *current* syncToken
720
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
721
-	 * property. This is needed here too, to ensure the operation is atomic.
722
-	 *
723
-	 * If the $syncToken argument is specified as null, this is an initial
724
-	 * sync, and all members should be reported.
725
-	 *
726
-	 * The modified property is an array of nodenames that have changed since
727
-	 * the last token.
728
-	 *
729
-	 * The deleted property is an array with nodenames, that have been deleted
730
-	 * from collection.
731
-	 *
732
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
733
-	 * 1, you only have to report changes that happened only directly in
734
-	 * immediate descendants. If it's 2, it should also include changes from
735
-	 * the nodes below the child collections. (grandchildren)
736
-	 *
737
-	 * The $limit argument allows a client to specify how many results should
738
-	 * be returned at most. If the limit is not specified, it should be treated
739
-	 * as infinite.
740
-	 *
741
-	 * If the limit (infinite or not) is higher than you're willing to return,
742
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
743
-	 *
744
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
745
-	 * return null.
746
-	 *
747
-	 * The limit is 'suggestive'. You are free to ignore it.
748
-	 *
749
-	 * @param string $addressBookId
750
-	 * @param string $syncToken
751
-	 * @param int $syncLevel
752
-	 * @param int $limit
753
-	 * @return array
754
-	 */
755
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
756
-		// Current synctoken
757
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
758
-		$stmt->execute([ $addressBookId ]);
759
-		$currentToken = $stmt->fetchColumn(0);
760
-
761
-		if (is_null($currentToken)) return null;
762
-
763
-		$result = [
764
-			'syncToken' => $currentToken,
765
-			'added'     => [],
766
-			'modified'  => [],
767
-			'deleted'   => [],
768
-		];
769
-
770
-		if ($syncToken) {
771
-
772
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
773
-			if ($limit>0) {
774
-				$query .= " `LIMIT` " . (int)$limit;
775
-			}
776
-
777
-			// Fetching all changes
778
-			$stmt = $this->db->prepare($query);
779
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
780
-
781
-			$changes = [];
782
-
783
-			// This loop ensures that any duplicates are overwritten, only the
784
-			// last change on a node is relevant.
785
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
786
-
787
-				$changes[$row['uri']] = $row['operation'];
788
-
789
-			}
790
-
791
-			foreach($changes as $uri => $operation) {
792
-
793
-				switch($operation) {
794
-					case 1:
795
-						$result['added'][] = $uri;
796
-						break;
797
-					case 2:
798
-						$result['modified'][] = $uri;
799
-						break;
800
-					case 3:
801
-						$result['deleted'][] = $uri;
802
-						break;
803
-				}
804
-
805
-			}
806
-		} else {
807
-			// No synctoken supplied, this is the initial sync.
808
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
809
-			$stmt = $this->db->prepare($query);
810
-			$stmt->execute([$addressBookId]);
811
-
812
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
813
-		}
814
-		return $result;
815
-	}
816
-
817
-	/**
818
-	 * Adds a change record to the addressbookchanges table.
819
-	 *
820
-	 * @param mixed $addressBookId
821
-	 * @param string $objectUri
822
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
823
-	 * @return void
824
-	 */
825
-	protected function addChange($addressBookId, $objectUri, $operation) {
826
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
827
-		$stmt = $this->db->prepare($sql);
828
-		$stmt->execute([
829
-			$objectUri,
830
-			$addressBookId,
831
-			$operation,
832
-			$addressBookId
833
-		]);
834
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
835
-		$stmt->execute([
836
-			$addressBookId
837
-		]);
838
-	}
839
-
840
-	private function readBlob($cardData) {
841
-		if (is_resource($cardData)) {
842
-			return stream_get_contents($cardData);
843
-		}
844
-
845
-		return $cardData;
846
-	}
847
-
848
-	/**
849
-	 * @param IShareable $shareable
850
-	 * @param string[] $add
851
-	 * @param string[] $remove
852
-	 */
853
-	public function updateShares(IShareable $shareable, $add, $remove) {
854
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
855
-	}
856
-
857
-	/**
858
-	 * search contact
859
-	 *
860
-	 * @param int $addressBookId
861
-	 * @param string $pattern which should match within the $searchProperties
862
-	 * @param array $searchProperties defines the properties within the query pattern should match
863
-	 * @return array an array of contacts which are arrays of key-value-pairs
864
-	 */
865
-	public function search($addressBookId, $pattern, $searchProperties) {
866
-		$query = $this->db->getQueryBuilder();
867
-		$query2 = $this->db->getQueryBuilder();
868
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
869
-		$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
870
-		foreach ($searchProperties as $property) {
871
-				$query2->expr()->orX($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
872
-		}
873
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
874
-
875
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
876
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
877
-
878
-		$result = $query->execute();
879
-		$cards = $result->fetchAll();
880
-
881
-		$result->closeCursor();
882
-
883
-		return array_map(function($array) {
884
-			$array['carddata'] = $this->readBlob($array['carddata']);
885
-			return $array;
886
-		}, $cards);
887
-	}
888
-
889
-	/**
890
-	 * @param int $bookId
891
-	 * @param string $name
892
-	 * @return array
893
-	 */
894
-	public function collectCardProperties($bookId, $name) {
895
-		$query = $this->db->getQueryBuilder();
896
-		$result = $query->selectDistinct('value')
897
-			->from($this->dbCardsPropertiesTable)
898
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
899
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
900
-			->execute();
901
-
902
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
903
-		$result->closeCursor();
904
-
905
-		return $all;
906
-	}
907
-
908
-	/**
909
-	 * get URI from a given contact
910
-	 *
911
-	 * @param int $id
912
-	 * @return string
913
-	 */
914
-	public function getCardUri($id) {
915
-		$query = $this->db->getQueryBuilder();
916
-		$query->select('uri')->from($this->dbCardsTable)
917
-				->where($query->expr()->eq('id', $query->createParameter('id')))
918
-				->setParameter('id', $id);
919
-
920
-		$result = $query->execute();
921
-		$uri = $result->fetch();
922
-		$result->closeCursor();
923
-
924
-		if (!isset($uri['uri'])) {
925
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
926
-		}
927
-
928
-		return $uri['uri'];
929
-	}
930
-
931
-	/**
932
-	 * return contact with the given URI
933
-	 *
934
-	 * @param int $addressBookId
935
-	 * @param string $uri
936
-	 * @returns array
937
-	 */
938
-	public function getContact($addressBookId, $uri) {
939
-		$result = [];
940
-		$query = $this->db->getQueryBuilder();
941
-		$query->select('*')->from($this->dbCardsTable)
942
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
943
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
944
-		$queryResult = $query->execute();
945
-		$contact = $queryResult->fetch();
946
-		$queryResult->closeCursor();
947
-
948
-		if (is_array($contact)) {
949
-			$result = $contact;
950
-		}
951
-
952
-		return $result;
953
-	}
954
-
955
-	/**
956
-	 * Returns the list of people whom this address book is shared with.
957
-	 *
958
-	 * Every element in this array should have the following properties:
959
-	 *   * href - Often a mailto: address
960
-	 *   * commonName - Optional, for example a first + last name
961
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
962
-	 *   * readOnly - boolean
963
-	 *   * summary - Optional, a description for the share
964
-	 *
965
-	 * @return array
966
-	 */
967
-	public function getShares($addressBookId) {
968
-		return $this->sharingBackend->getShares($addressBookId);
969
-	}
970
-
971
-	/**
972
-	 * update properties table
973
-	 *
974
-	 * @param int $addressBookId
975
-	 * @param string $cardUri
976
-	 * @param string $vCardSerialized
977
-	 */
978
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
979
-		$cardId = $this->getCardId($addressBookId, $cardUri);
980
-		$vCard = $this->readCard($vCardSerialized);
981
-
982
-		$this->purgeProperties($addressBookId, $cardId);
983
-
984
-		$query = $this->db->getQueryBuilder();
985
-		$query->insert($this->dbCardsPropertiesTable)
986
-			->values(
987
-				[
988
-					'addressbookid' => $query->createNamedParameter($addressBookId),
989
-					'cardid' => $query->createNamedParameter($cardId),
990
-					'name' => $query->createParameter('name'),
991
-					'value' => $query->createParameter('value'),
992
-					'preferred' => $query->createParameter('preferred')
993
-				]
994
-			);
995
-
996
-		foreach ($vCard->children() as $property) {
997
-			if(!in_array($property->name, self::$indexProperties)) {
998
-				continue;
999
-			}
1000
-			$preferred = 0;
1001
-			foreach($property->parameters as $parameter) {
1002
-				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1003
-					$preferred = 1;
1004
-					break;
1005
-				}
1006
-			}
1007
-			$query->setParameter('name', $property->name);
1008
-			$query->setParameter('value', substr($property->getValue(), 0, 254));
1009
-			$query->setParameter('preferred', $preferred);
1010
-			$query->execute();
1011
-		}
1012
-	}
1013
-
1014
-	/**
1015
-	 * read vCard data into a vCard object
1016
-	 *
1017
-	 * @param string $cardData
1018
-	 * @return VCard
1019
-	 */
1020
-	protected function readCard($cardData) {
1021
-		return  Reader::read($cardData);
1022
-	}
1023
-
1024
-	/**
1025
-	 * delete all properties from a given card
1026
-	 *
1027
-	 * @param int $addressBookId
1028
-	 * @param int $cardId
1029
-	 */
1030
-	protected function purgeProperties($addressBookId, $cardId) {
1031
-		$query = $this->db->getQueryBuilder();
1032
-		$query->delete($this->dbCardsPropertiesTable)
1033
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1034
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1035
-		$query->execute();
1036
-	}
1037
-
1038
-	/**
1039
-	 * get ID from a given contact
1040
-	 *
1041
-	 * @param int $addressBookId
1042
-	 * @param string $uri
1043
-	 * @return int
1044
-	 */
1045
-	protected function getCardId($addressBookId, $uri) {
1046
-		$query = $this->db->getQueryBuilder();
1047
-		$query->select('id')->from($this->dbCardsTable)
1048
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1049
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1050
-
1051
-		$result = $query->execute();
1052
-		$cardIds = $result->fetch();
1053
-		$result->closeCursor();
1054
-
1055
-		if (!isset($cardIds['id'])) {
1056
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1057
-		}
1058
-
1059
-		return (int)$cardIds['id'];
1060
-	}
1061
-
1062
-	/**
1063
-	 * For shared address books the sharee is set in the ACL of the address book
1064
-	 * @param $addressBookId
1065
-	 * @param $acl
1066
-	 * @return array
1067
-	 */
1068
-	public function applyShareAcl($addressBookId, $acl) {
1069
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1070
-	}
1071
-
1072
-	private function convertPrincipal($principalUri, $toV2) {
1073
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1074
-			list(, $name) = URLUtil::splitPath($principalUri);
1075
-			if ($toV2 === true) {
1076
-				return "principals/users/$name";
1077
-			}
1078
-			return "principals/$name";
1079
-		}
1080
-		return $principalUri;
1081
-	}
51
+    const PERSONAL_ADDRESSBOOK_URI = 'contacts';
52
+    const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
53
+
54
+    /** @var Principal */
55
+    private $principalBackend;
56
+
57
+    /** @var string */
58
+    private $dbCardsTable = 'cards';
59
+
60
+    /** @var string */
61
+    private $dbCardsPropertiesTable = 'cards_properties';
62
+
63
+    /** @var IDBConnection */
64
+    private $db;
65
+
66
+    /** @var Backend */
67
+    private $sharingBackend;
68
+
69
+    /** @var array properties to index */
70
+    public static $indexProperties = array(
71
+            'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
72
+            'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
73
+
74
+    /**
75
+     * @var string[] Map of uid => display name
76
+     */
77
+    protected $userDisplayNames;
78
+
79
+    /** @var IUserManager */
80
+    private $userManager;
81
+
82
+    /** @var EventDispatcherInterface */
83
+    private $dispatcher;
84
+
85
+    /**
86
+     * CardDavBackend constructor.
87
+     *
88
+     * @param IDBConnection $db
89
+     * @param Principal $principalBackend
90
+     * @param IUserManager $userManager
91
+     * @param EventDispatcherInterface $dispatcher
92
+     */
93
+    public function __construct(IDBConnection $db,
94
+                                Principal $principalBackend,
95
+                                IUserManager $userManager,
96
+                                EventDispatcherInterface $dispatcher = null) {
97
+        $this->db = $db;
98
+        $this->principalBackend = $principalBackend;
99
+        $this->userManager = $userManager;
100
+        $this->dispatcher = $dispatcher;
101
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'addressbook');
102
+    }
103
+
104
+    /**
105
+     * Return the number of address books for a principal
106
+     *
107
+     * @param $principalUri
108
+     * @return int
109
+     */
110
+    public function getAddressBooksForUserCount($principalUri) {
111
+        $principalUri = $this->convertPrincipal($principalUri, true);
112
+        $query = $this->db->getQueryBuilder();
113
+        $query->select($query->createFunction('COUNT(*)'))
114
+            ->from('addressbooks')
115
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116
+
117
+        return (int)$query->execute()->fetchColumn();
118
+    }
119
+
120
+    /**
121
+     * Returns the list of address books for a specific user.
122
+     *
123
+     * Every addressbook should have the following properties:
124
+     *   id - an arbitrary unique id
125
+     *   uri - the 'basename' part of the url
126
+     *   principaluri - Same as the passed parameter
127
+     *
128
+     * Any additional clark-notation property may be passed besides this. Some
129
+     * common ones are :
130
+     *   {DAV:}displayname
131
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
132
+     *   {http://calendarserver.org/ns/}getctag
133
+     *
134
+     * @param string $principalUri
135
+     * @return array
136
+     */
137
+    function getAddressBooksForUser($principalUri) {
138
+        $principalUriOriginal = $principalUri;
139
+        $principalUri = $this->convertPrincipal($principalUri, true);
140
+        $query = $this->db->getQueryBuilder();
141
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
142
+            ->from('addressbooks')
143
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
144
+
145
+        $addressBooks = [];
146
+
147
+        $result = $query->execute();
148
+        while($row = $result->fetch()) {
149
+            $addressBooks[$row['id']] = [
150
+                'id'  => $row['id'],
151
+                'uri' => $row['uri'],
152
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153
+                '{DAV:}displayname' => $row['displayname'],
154
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
155
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
157
+            ];
158
+        }
159
+        $result->closeCursor();
160
+
161
+        // query for shared calendars
162
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
+        $principals[]= $principalUri;
164
+
165
+        $query = $this->db->getQueryBuilder();
166
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
167
+            ->from('dav_shares', 's')
168
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
169
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
170
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
171
+            ->setParameter('type', 'addressbook')
172
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173
+            ->execute();
174
+
175
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
176
+        while($row = $result->fetch()) {
177
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
178
+            if (isset($addressBooks[$row['id']])) {
179
+                if ($readOnly) {
180
+                    // New share can not have more permissions then the old one.
181
+                    continue;
182
+                }
183
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
184
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
185
+                    // Old share is already read-write, no more permissions can be gained
186
+                    continue;
187
+                }
188
+            }
189
+
190
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
191
+            $uri = $row['uri'] . '_shared_by_' . $name;
192
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
193
+
194
+            $addressBooks[$row['id']] = [
195
+                'id'  => $row['id'],
196
+                'uri' => $uri,
197
+                'principaluri' => $principalUriOriginal,
198
+                '{DAV:}displayname' => $displayName,
199
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
200
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
201
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
202
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
203
+                $readOnlyPropertyName => $readOnly,
204
+            ];
205
+        }
206
+        $result->closeCursor();
207
+
208
+        return array_values($addressBooks);
209
+    }
210
+
211
+    public function getUsersOwnAddressBooks($principalUri) {
212
+        $principalUriOriginal = $principalUri;
213
+        $principalUri = $this->convertPrincipal($principalUri, true);
214
+        $query = $this->db->getQueryBuilder();
215
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
216
+                ->from('addressbooks')
217
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
218
+
219
+        $addressBooks = [];
220
+
221
+        $result = $query->execute();
222
+        while($row = $result->fetch()) {
223
+            $addressBooks[$row['id']] = [
224
+                'id'  => $row['id'],
225
+                'uri' => $row['uri'],
226
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
227
+                '{DAV:}displayname' => $row['displayname'],
228
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
229
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
230
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
231
+            ];
232
+        }
233
+        $result->closeCursor();
234
+
235
+        return array_values($addressBooks);
236
+    }
237
+
238
+    private function getUserDisplayName($uid) {
239
+        if (!isset($this->userDisplayNames[$uid])) {
240
+            $user = $this->userManager->get($uid);
241
+
242
+            if ($user instanceof IUser) {
243
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
244
+            } else {
245
+                $this->userDisplayNames[$uid] = $uid;
246
+            }
247
+        }
248
+
249
+        return $this->userDisplayNames[$uid];
250
+    }
251
+
252
+    /**
253
+     * @param int $addressBookId
254
+     */
255
+    public function getAddressBookById($addressBookId) {
256
+        $query = $this->db->getQueryBuilder();
257
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
258
+            ->from('addressbooks')
259
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
260
+            ->execute();
261
+
262
+        $row = $result->fetch();
263
+        $result->closeCursor();
264
+        if ($row === false) {
265
+            return null;
266
+        }
267
+
268
+        return [
269
+            'id'  => $row['id'],
270
+            'uri' => $row['uri'],
271
+            'principaluri' => $row['principaluri'],
272
+            '{DAV:}displayname' => $row['displayname'],
273
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
274
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
275
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
276
+        ];
277
+    }
278
+
279
+    /**
280
+     * @param $addressBookUri
281
+     * @return array|null
282
+     */
283
+    public function getAddressBooksByUri($principal, $addressBookUri) {
284
+        $query = $this->db->getQueryBuilder();
285
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
286
+            ->from('addressbooks')
287
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
288
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
289
+            ->setMaxResults(1)
290
+            ->execute();
291
+
292
+        $row = $result->fetch();
293
+        $result->closeCursor();
294
+        if ($row === false) {
295
+            return null;
296
+        }
297
+
298
+        return [
299
+                'id'  => $row['id'],
300
+                'uri' => $row['uri'],
301
+                'principaluri' => $row['principaluri'],
302
+                '{DAV:}displayname' => $row['displayname'],
303
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
304
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
305
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
306
+            ];
307
+    }
308
+
309
+    /**
310
+     * Updates properties for an address book.
311
+     *
312
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
313
+     * To do the actual updates, you must tell this object which properties
314
+     * you're going to process with the handle() method.
315
+     *
316
+     * Calling the handle method is like telling the PropPatch object "I
317
+     * promise I can handle updating this property".
318
+     *
319
+     * Read the PropPatch documentation for more info and examples.
320
+     *
321
+     * @param string $addressBookId
322
+     * @param \Sabre\DAV\PropPatch $propPatch
323
+     * @return void
324
+     */
325
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
326
+        $supportedProperties = [
327
+            '{DAV:}displayname',
328
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
329
+        ];
330
+
331
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
332
+
333
+            $updates = [];
334
+            foreach($mutations as $property=>$newValue) {
335
+
336
+                switch($property) {
337
+                    case '{DAV:}displayname' :
338
+                        $updates['displayname'] = $newValue;
339
+                        break;
340
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
341
+                        $updates['description'] = $newValue;
342
+                        break;
343
+                }
344
+            }
345
+            $query = $this->db->getQueryBuilder();
346
+            $query->update('addressbooks');
347
+
348
+            foreach($updates as $key=>$value) {
349
+                $query->set($key, $query->createNamedParameter($value));
350
+            }
351
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
352
+            ->execute();
353
+
354
+            $this->addChange($addressBookId, "", 2);
355
+
356
+            return true;
357
+
358
+        });
359
+    }
360
+
361
+    /**
362
+     * Creates a new address book
363
+     *
364
+     * @param string $principalUri
365
+     * @param string $url Just the 'basename' of the url.
366
+     * @param array $properties
367
+     * @return int
368
+     * @throws BadRequest
369
+     */
370
+    function createAddressBook($principalUri, $url, array $properties) {
371
+        $values = [
372
+            'displayname' => null,
373
+            'description' => null,
374
+            'principaluri' => $principalUri,
375
+            'uri' => $url,
376
+            'synctoken' => 1
377
+        ];
378
+
379
+        foreach($properties as $property=>$newValue) {
380
+
381
+            switch($property) {
382
+                case '{DAV:}displayname' :
383
+                    $values['displayname'] = $newValue;
384
+                    break;
385
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
386
+                    $values['description'] = $newValue;
387
+                    break;
388
+                default :
389
+                    throw new BadRequest('Unknown property: ' . $property);
390
+            }
391
+
392
+        }
393
+
394
+        // Fallback to make sure the displayname is set. Some clients may refuse
395
+        // to work with addressbooks not having a displayname.
396
+        if(is_null($values['displayname'])) {
397
+            $values['displayname'] = $url;
398
+        }
399
+
400
+        $query = $this->db->getQueryBuilder();
401
+        $query->insert('addressbooks')
402
+            ->values([
403
+                'uri' => $query->createParameter('uri'),
404
+                'displayname' => $query->createParameter('displayname'),
405
+                'description' => $query->createParameter('description'),
406
+                'principaluri' => $query->createParameter('principaluri'),
407
+                'synctoken' => $query->createParameter('synctoken'),
408
+            ])
409
+            ->setParameters($values)
410
+            ->execute();
411
+
412
+        return $query->getLastInsertId();
413
+    }
414
+
415
+    /**
416
+     * Deletes an entire addressbook and all its contents
417
+     *
418
+     * @param mixed $addressBookId
419
+     * @return void
420
+     */
421
+    function deleteAddressBook($addressBookId) {
422
+        $query = $this->db->getQueryBuilder();
423
+        $query->delete('cards')
424
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
425
+            ->setParameter('addressbookid', $addressBookId)
426
+            ->execute();
427
+
428
+        $query->delete('addressbookchanges')
429
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
430
+            ->setParameter('addressbookid', $addressBookId)
431
+            ->execute();
432
+
433
+        $query->delete('addressbooks')
434
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
435
+            ->setParameter('id', $addressBookId)
436
+            ->execute();
437
+
438
+        $this->sharingBackend->deleteAllShares($addressBookId);
439
+
440
+        $query->delete($this->dbCardsPropertiesTable)
441
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
442
+            ->execute();
443
+
444
+    }
445
+
446
+    /**
447
+     * Returns all cards for a specific addressbook id.
448
+     *
449
+     * This method should return the following properties for each card:
450
+     *   * carddata - raw vcard data
451
+     *   * uri - Some unique url
452
+     *   * lastmodified - A unix timestamp
453
+     *
454
+     * It's recommended to also return the following properties:
455
+     *   * etag - A unique etag. This must change every time the card changes.
456
+     *   * size - The size of the card in bytes.
457
+     *
458
+     * If these last two properties are provided, less time will be spent
459
+     * calculating them. If they are specified, you can also ommit carddata.
460
+     * This may speed up certain requests, especially with large cards.
461
+     *
462
+     * @param mixed $addressBookId
463
+     * @return array
464
+     */
465
+    function getCards($addressBookId) {
466
+        $query = $this->db->getQueryBuilder();
467
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
468
+            ->from('cards')
469
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
470
+
471
+        $cards = [];
472
+
473
+        $result = $query->execute();
474
+        while($row = $result->fetch()) {
475
+            $row['etag'] = '"' . $row['etag'] . '"';
476
+            $row['carddata'] = $this->readBlob($row['carddata']);
477
+            $cards[] = $row;
478
+        }
479
+        $result->closeCursor();
480
+
481
+        return $cards;
482
+    }
483
+
484
+    /**
485
+     * Returns a specific card.
486
+     *
487
+     * The same set of properties must be returned as with getCards. The only
488
+     * exception is that 'carddata' is absolutely required.
489
+     *
490
+     * If the card does not exist, you must return false.
491
+     *
492
+     * @param mixed $addressBookId
493
+     * @param string $cardUri
494
+     * @return array
495
+     */
496
+    function getCard($addressBookId, $cardUri) {
497
+        $query = $this->db->getQueryBuilder();
498
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
499
+            ->from('cards')
500
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
501
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
502
+            ->setMaxResults(1);
503
+
504
+        $result = $query->execute();
505
+        $row = $result->fetch();
506
+        if (!$row) {
507
+            return false;
508
+        }
509
+        $row['etag'] = '"' . $row['etag'] . '"';
510
+        $row['carddata'] = $this->readBlob($row['carddata']);
511
+
512
+        return $row;
513
+    }
514
+
515
+    /**
516
+     * Returns a list of cards.
517
+     *
518
+     * This method should work identical to getCard, but instead return all the
519
+     * cards in the list as an array.
520
+     *
521
+     * If the backend supports this, it may allow for some speed-ups.
522
+     *
523
+     * @param mixed $addressBookId
524
+     * @param string[] $uris
525
+     * @return array
526
+     */
527
+    function getMultipleCards($addressBookId, array $uris) {
528
+        if (empty($uris)) {
529
+            return [];
530
+        }
531
+
532
+        $chunks = array_chunk($uris, 100);
533
+        $cards = [];
534
+
535
+        $query = $this->db->getQueryBuilder();
536
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
537
+            ->from('cards')
538
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
539
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
540
+
541
+        foreach ($chunks as $uris) {
542
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
543
+            $result = $query->execute();
544
+
545
+            while ($row = $result->fetch()) {
546
+                $row['etag'] = '"' . $row['etag'] . '"';
547
+                $row['carddata'] = $this->readBlob($row['carddata']);
548
+                $cards[] = $row;
549
+            }
550
+            $result->closeCursor();
551
+        }
552
+        return $cards;
553
+    }
554
+
555
+    /**
556
+     * Creates a new card.
557
+     *
558
+     * The addressbook id will be passed as the first argument. This is the
559
+     * same id as it is returned from the getAddressBooksForUser method.
560
+     *
561
+     * The cardUri is a base uri, and doesn't include the full path. The
562
+     * cardData argument is the vcard body, and is passed as a string.
563
+     *
564
+     * It is possible to return an ETag from this method. This ETag is for the
565
+     * newly created resource, and must be enclosed with double quotes (that
566
+     * is, the string itself must contain the double quotes).
567
+     *
568
+     * You should only return the ETag if you store the carddata as-is. If a
569
+     * subsequent GET request on the same card does not have the same body,
570
+     * byte-by-byte and you did return an ETag here, clients tend to get
571
+     * confused.
572
+     *
573
+     * If you don't return an ETag, you can just return null.
574
+     *
575
+     * @param mixed $addressBookId
576
+     * @param string $cardUri
577
+     * @param string $cardData
578
+     * @return string
579
+     */
580
+    function createCard($addressBookId, $cardUri, $cardData) {
581
+        $etag = md5($cardData);
582
+
583
+        $query = $this->db->getQueryBuilder();
584
+        $query->insert('cards')
585
+            ->values([
586
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
587
+                'uri' => $query->createNamedParameter($cardUri),
588
+                'lastmodified' => $query->createNamedParameter(time()),
589
+                'addressbookid' => $query->createNamedParameter($addressBookId),
590
+                'size' => $query->createNamedParameter(strlen($cardData)),
591
+                'etag' => $query->createNamedParameter($etag),
592
+            ])
593
+            ->execute();
594
+
595
+        $this->addChange($addressBookId, $cardUri, 1);
596
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
597
+
598
+        if (!is_null($this->dispatcher)) {
599
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
600
+                new GenericEvent(null, [
601
+                    'addressBookId' => $addressBookId,
602
+                    'cardUri' => $cardUri,
603
+                    'cardData' => $cardData]));
604
+        }
605
+
606
+        return '"' . $etag . '"';
607
+    }
608
+
609
+    /**
610
+     * Updates a card.
611
+     *
612
+     * The addressbook id will be passed as the first argument. This is the
613
+     * same id as it is returned from the getAddressBooksForUser method.
614
+     *
615
+     * The cardUri is a base uri, and doesn't include the full path. The
616
+     * cardData argument is the vcard body, and is passed as a string.
617
+     *
618
+     * It is possible to return an ETag from this method. This ETag should
619
+     * match that of the updated resource, and must be enclosed with double
620
+     * quotes (that is: the string itself must contain the actual quotes).
621
+     *
622
+     * You should only return the ETag if you store the carddata as-is. If a
623
+     * subsequent GET request on the same card does not have the same body,
624
+     * byte-by-byte and you did return an ETag here, clients tend to get
625
+     * confused.
626
+     *
627
+     * If you don't return an ETag, you can just return null.
628
+     *
629
+     * @param mixed $addressBookId
630
+     * @param string $cardUri
631
+     * @param string $cardData
632
+     * @return string
633
+     */
634
+    function updateCard($addressBookId, $cardUri, $cardData) {
635
+
636
+        $etag = md5($cardData);
637
+        $query = $this->db->getQueryBuilder();
638
+        $query->update('cards')
639
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
640
+            ->set('lastmodified', $query->createNamedParameter(time()))
641
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
642
+            ->set('etag', $query->createNamedParameter($etag))
643
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
644
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
645
+            ->execute();
646
+
647
+        $this->addChange($addressBookId, $cardUri, 2);
648
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
649
+
650
+        if (!is_null($this->dispatcher)) {
651
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
652
+                new GenericEvent(null, [
653
+                    'addressBookId' => $addressBookId,
654
+                    'cardUri' => $cardUri,
655
+                    'cardData' => $cardData]));
656
+        }
657
+
658
+        return '"' . $etag . '"';
659
+    }
660
+
661
+    /**
662
+     * Deletes a card
663
+     *
664
+     * @param mixed $addressBookId
665
+     * @param string $cardUri
666
+     * @return bool
667
+     */
668
+    function deleteCard($addressBookId, $cardUri) {
669
+        try {
670
+            $cardId = $this->getCardId($addressBookId, $cardUri);
671
+        } catch (\InvalidArgumentException $e) {
672
+            $cardId = null;
673
+        }
674
+        $query = $this->db->getQueryBuilder();
675
+        $ret = $query->delete('cards')
676
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
677
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
678
+            ->execute();
679
+
680
+        $this->addChange($addressBookId, $cardUri, 3);
681
+
682
+        if (!is_null($this->dispatcher)) {
683
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
684
+                new GenericEvent(null, [
685
+                    'addressBookId' => $addressBookId,
686
+                    'cardUri' => $cardUri]));
687
+        }
688
+
689
+        if ($ret === 1) {
690
+            if ($cardId !== null) {
691
+                $this->purgeProperties($addressBookId, $cardId);
692
+            }
693
+            return true;
694
+        }
695
+
696
+        return false;
697
+    }
698
+
699
+    /**
700
+     * The getChanges method returns all the changes that have happened, since
701
+     * the specified syncToken in the specified address book.
702
+     *
703
+     * This function should return an array, such as the following:
704
+     *
705
+     * [
706
+     *   'syncToken' => 'The current synctoken',
707
+     *   'added'   => [
708
+     *      'new.txt',
709
+     *   ],
710
+     *   'modified'   => [
711
+     *      'modified.txt',
712
+     *   ],
713
+     *   'deleted' => [
714
+     *      'foo.php.bak',
715
+     *      'old.txt'
716
+     *   ]
717
+     * ];
718
+     *
719
+     * The returned syncToken property should reflect the *current* syncToken
720
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
721
+     * property. This is needed here too, to ensure the operation is atomic.
722
+     *
723
+     * If the $syncToken argument is specified as null, this is an initial
724
+     * sync, and all members should be reported.
725
+     *
726
+     * The modified property is an array of nodenames that have changed since
727
+     * the last token.
728
+     *
729
+     * The deleted property is an array with nodenames, that have been deleted
730
+     * from collection.
731
+     *
732
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
733
+     * 1, you only have to report changes that happened only directly in
734
+     * immediate descendants. If it's 2, it should also include changes from
735
+     * the nodes below the child collections. (grandchildren)
736
+     *
737
+     * The $limit argument allows a client to specify how many results should
738
+     * be returned at most. If the limit is not specified, it should be treated
739
+     * as infinite.
740
+     *
741
+     * If the limit (infinite or not) is higher than you're willing to return,
742
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
743
+     *
744
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
745
+     * return null.
746
+     *
747
+     * The limit is 'suggestive'. You are free to ignore it.
748
+     *
749
+     * @param string $addressBookId
750
+     * @param string $syncToken
751
+     * @param int $syncLevel
752
+     * @param int $limit
753
+     * @return array
754
+     */
755
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
756
+        // Current synctoken
757
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
758
+        $stmt->execute([ $addressBookId ]);
759
+        $currentToken = $stmt->fetchColumn(0);
760
+
761
+        if (is_null($currentToken)) return null;
762
+
763
+        $result = [
764
+            'syncToken' => $currentToken,
765
+            'added'     => [],
766
+            'modified'  => [],
767
+            'deleted'   => [],
768
+        ];
769
+
770
+        if ($syncToken) {
771
+
772
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
773
+            if ($limit>0) {
774
+                $query .= " `LIMIT` " . (int)$limit;
775
+            }
776
+
777
+            // Fetching all changes
778
+            $stmt = $this->db->prepare($query);
779
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
780
+
781
+            $changes = [];
782
+
783
+            // This loop ensures that any duplicates are overwritten, only the
784
+            // last change on a node is relevant.
785
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
786
+
787
+                $changes[$row['uri']] = $row['operation'];
788
+
789
+            }
790
+
791
+            foreach($changes as $uri => $operation) {
792
+
793
+                switch($operation) {
794
+                    case 1:
795
+                        $result['added'][] = $uri;
796
+                        break;
797
+                    case 2:
798
+                        $result['modified'][] = $uri;
799
+                        break;
800
+                    case 3:
801
+                        $result['deleted'][] = $uri;
802
+                        break;
803
+                }
804
+
805
+            }
806
+        } else {
807
+            // No synctoken supplied, this is the initial sync.
808
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
809
+            $stmt = $this->db->prepare($query);
810
+            $stmt->execute([$addressBookId]);
811
+
812
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
813
+        }
814
+        return $result;
815
+    }
816
+
817
+    /**
818
+     * Adds a change record to the addressbookchanges table.
819
+     *
820
+     * @param mixed $addressBookId
821
+     * @param string $objectUri
822
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
823
+     * @return void
824
+     */
825
+    protected function addChange($addressBookId, $objectUri, $operation) {
826
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
827
+        $stmt = $this->db->prepare($sql);
828
+        $stmt->execute([
829
+            $objectUri,
830
+            $addressBookId,
831
+            $operation,
832
+            $addressBookId
833
+        ]);
834
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
835
+        $stmt->execute([
836
+            $addressBookId
837
+        ]);
838
+    }
839
+
840
+    private function readBlob($cardData) {
841
+        if (is_resource($cardData)) {
842
+            return stream_get_contents($cardData);
843
+        }
844
+
845
+        return $cardData;
846
+    }
847
+
848
+    /**
849
+     * @param IShareable $shareable
850
+     * @param string[] $add
851
+     * @param string[] $remove
852
+     */
853
+    public function updateShares(IShareable $shareable, $add, $remove) {
854
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
855
+    }
856
+
857
+    /**
858
+     * search contact
859
+     *
860
+     * @param int $addressBookId
861
+     * @param string $pattern which should match within the $searchProperties
862
+     * @param array $searchProperties defines the properties within the query pattern should match
863
+     * @return array an array of contacts which are arrays of key-value-pairs
864
+     */
865
+    public function search($addressBookId, $pattern, $searchProperties) {
866
+        $query = $this->db->getQueryBuilder();
867
+        $query2 = $this->db->getQueryBuilder();
868
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
869
+        $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
870
+        foreach ($searchProperties as $property) {
871
+                $query2->expr()->orX($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
872
+        }
873
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
874
+
875
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
876
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
877
+
878
+        $result = $query->execute();
879
+        $cards = $result->fetchAll();
880
+
881
+        $result->closeCursor();
882
+
883
+        return array_map(function($array) {
884
+            $array['carddata'] = $this->readBlob($array['carddata']);
885
+            return $array;
886
+        }, $cards);
887
+    }
888
+
889
+    /**
890
+     * @param int $bookId
891
+     * @param string $name
892
+     * @return array
893
+     */
894
+    public function collectCardProperties($bookId, $name) {
895
+        $query = $this->db->getQueryBuilder();
896
+        $result = $query->selectDistinct('value')
897
+            ->from($this->dbCardsPropertiesTable)
898
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
899
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
900
+            ->execute();
901
+
902
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
903
+        $result->closeCursor();
904
+
905
+        return $all;
906
+    }
907
+
908
+    /**
909
+     * get URI from a given contact
910
+     *
911
+     * @param int $id
912
+     * @return string
913
+     */
914
+    public function getCardUri($id) {
915
+        $query = $this->db->getQueryBuilder();
916
+        $query->select('uri')->from($this->dbCardsTable)
917
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
918
+                ->setParameter('id', $id);
919
+
920
+        $result = $query->execute();
921
+        $uri = $result->fetch();
922
+        $result->closeCursor();
923
+
924
+        if (!isset($uri['uri'])) {
925
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
926
+        }
927
+
928
+        return $uri['uri'];
929
+    }
930
+
931
+    /**
932
+     * return contact with the given URI
933
+     *
934
+     * @param int $addressBookId
935
+     * @param string $uri
936
+     * @returns array
937
+     */
938
+    public function getContact($addressBookId, $uri) {
939
+        $result = [];
940
+        $query = $this->db->getQueryBuilder();
941
+        $query->select('*')->from($this->dbCardsTable)
942
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
943
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
944
+        $queryResult = $query->execute();
945
+        $contact = $queryResult->fetch();
946
+        $queryResult->closeCursor();
947
+
948
+        if (is_array($contact)) {
949
+            $result = $contact;
950
+        }
951
+
952
+        return $result;
953
+    }
954
+
955
+    /**
956
+     * Returns the list of people whom this address book is shared with.
957
+     *
958
+     * Every element in this array should have the following properties:
959
+     *   * href - Often a mailto: address
960
+     *   * commonName - Optional, for example a first + last name
961
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
962
+     *   * readOnly - boolean
963
+     *   * summary - Optional, a description for the share
964
+     *
965
+     * @return array
966
+     */
967
+    public function getShares($addressBookId) {
968
+        return $this->sharingBackend->getShares($addressBookId);
969
+    }
970
+
971
+    /**
972
+     * update properties table
973
+     *
974
+     * @param int $addressBookId
975
+     * @param string $cardUri
976
+     * @param string $vCardSerialized
977
+     */
978
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
979
+        $cardId = $this->getCardId($addressBookId, $cardUri);
980
+        $vCard = $this->readCard($vCardSerialized);
981
+
982
+        $this->purgeProperties($addressBookId, $cardId);
983
+
984
+        $query = $this->db->getQueryBuilder();
985
+        $query->insert($this->dbCardsPropertiesTable)
986
+            ->values(
987
+                [
988
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
989
+                    'cardid' => $query->createNamedParameter($cardId),
990
+                    'name' => $query->createParameter('name'),
991
+                    'value' => $query->createParameter('value'),
992
+                    'preferred' => $query->createParameter('preferred')
993
+                ]
994
+            );
995
+
996
+        foreach ($vCard->children() as $property) {
997
+            if(!in_array($property->name, self::$indexProperties)) {
998
+                continue;
999
+            }
1000
+            $preferred = 0;
1001
+            foreach($property->parameters as $parameter) {
1002
+                if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1003
+                    $preferred = 1;
1004
+                    break;
1005
+                }
1006
+            }
1007
+            $query->setParameter('name', $property->name);
1008
+            $query->setParameter('value', substr($property->getValue(), 0, 254));
1009
+            $query->setParameter('preferred', $preferred);
1010
+            $query->execute();
1011
+        }
1012
+    }
1013
+
1014
+    /**
1015
+     * read vCard data into a vCard object
1016
+     *
1017
+     * @param string $cardData
1018
+     * @return VCard
1019
+     */
1020
+    protected function readCard($cardData) {
1021
+        return  Reader::read($cardData);
1022
+    }
1023
+
1024
+    /**
1025
+     * delete all properties from a given card
1026
+     *
1027
+     * @param int $addressBookId
1028
+     * @param int $cardId
1029
+     */
1030
+    protected function purgeProperties($addressBookId, $cardId) {
1031
+        $query = $this->db->getQueryBuilder();
1032
+        $query->delete($this->dbCardsPropertiesTable)
1033
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1034
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1035
+        $query->execute();
1036
+    }
1037
+
1038
+    /**
1039
+     * get ID from a given contact
1040
+     *
1041
+     * @param int $addressBookId
1042
+     * @param string $uri
1043
+     * @return int
1044
+     */
1045
+    protected function getCardId($addressBookId, $uri) {
1046
+        $query = $this->db->getQueryBuilder();
1047
+        $query->select('id')->from($this->dbCardsTable)
1048
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1049
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1050
+
1051
+        $result = $query->execute();
1052
+        $cardIds = $result->fetch();
1053
+        $result->closeCursor();
1054
+
1055
+        if (!isset($cardIds['id'])) {
1056
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1057
+        }
1058
+
1059
+        return (int)$cardIds['id'];
1060
+    }
1061
+
1062
+    /**
1063
+     * For shared address books the sharee is set in the ACL of the address book
1064
+     * @param $addressBookId
1065
+     * @param $acl
1066
+     * @return array
1067
+     */
1068
+    public function applyShareAcl($addressBookId, $acl) {
1069
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1070
+    }
1071
+
1072
+    private function convertPrincipal($principalUri, $toV2) {
1073
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1074
+            list(, $name) = URLUtil::splitPath($principalUri);
1075
+            if ($toV2 === true) {
1076
+                return "principals/users/$name";
1077
+            }
1078
+            return "principals/$name";
1079
+        }
1080
+        return $principalUri;
1081
+    }
1082 1082
 }
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 			->from('addressbooks')
115 115
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116 116
 
117
-		return (int)$query->execute()->fetchColumn();
117
+		return (int) $query->execute()->fetchColumn();
118 118
 	}
119 119
 
120 120
 	/**
@@ -145,22 +145,22 @@  discard block
 block discarded – undo
145 145
 		$addressBooks = [];
146 146
 
147 147
 		$result = $query->execute();
148
-		while($row = $result->fetch()) {
148
+		while ($row = $result->fetch()) {
149 149
 			$addressBooks[$row['id']] = [
150 150
 				'id'  => $row['id'],
151 151
 				'uri' => $row['uri'],
152 152
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153 153
 				'{DAV:}displayname' => $row['displayname'],
154
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
154
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
155 155
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
156
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
157 157
 			];
158 158
 		}
159 159
 		$result->closeCursor();
160 160
 
161 161
 		// query for shared calendars
162 162
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
-		$principals[]= $principalUri;
163
+		$principals[] = $principalUri;
164 164
 
165 165
 		$query = $this->db->getQueryBuilder();
166 166
 		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
@@ -172,8 +172,8 @@  discard block
 block discarded – undo
172 172
 			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173 173
 			->execute();
174 174
 
175
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
176
-		while($row = $result->fetch()) {
175
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
176
+		while ($row = $result->fetch()) {
177 177
 			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
178 178
 			if (isset($addressBooks[$row['id']])) {
179 179
 				if ($readOnly) {
@@ -188,18 +188,18 @@  discard block
 block discarded – undo
188 188
 			}
189 189
 
190 190
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
191
-			$uri = $row['uri'] . '_shared_by_' . $name;
192
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
191
+			$uri = $row['uri'].'_shared_by_'.$name;
192
+			$displayName = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
193 193
 
194 194
 			$addressBooks[$row['id']] = [
195 195
 				'id'  => $row['id'],
196 196
 				'uri' => $uri,
197 197
 				'principaluri' => $principalUriOriginal,
198 198
 				'{DAV:}displayname' => $displayName,
199
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
199
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
200 200
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
201
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
202
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
201
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
202
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
203 203
 				$readOnlyPropertyName => $readOnly,
204 204
 			];
205 205
 		}
@@ -219,15 +219,15 @@  discard block
 block discarded – undo
219 219
 		$addressBooks = [];
220 220
 
221 221
 		$result = $query->execute();
222
-		while($row = $result->fetch()) {
222
+		while ($row = $result->fetch()) {
223 223
 			$addressBooks[$row['id']] = [
224 224
 				'id'  => $row['id'],
225 225
 				'uri' => $row['uri'],
226 226
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
227 227
 				'{DAV:}displayname' => $row['displayname'],
228
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
228
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
229 229
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
230
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
230
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
231 231
 			];
232 232
 		}
233 233
 		$result->closeCursor();
@@ -270,9 +270,9 @@  discard block
 block discarded – undo
270 270
 			'uri' => $row['uri'],
271 271
 			'principaluri' => $row['principaluri'],
272 272
 			'{DAV:}displayname' => $row['displayname'],
273
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
273
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
274 274
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
275
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
275
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
276 276
 		];
277 277
 	}
278 278
 
@@ -300,9 +300,9 @@  discard block
 block discarded – undo
300 300
 				'uri' => $row['uri'],
301 301
 				'principaluri' => $row['principaluri'],
302 302
 				'{DAV:}displayname' => $row['displayname'],
303
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
303
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
304 304
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
305
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
305
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
306 306
 			];
307 307
 	}
308 308
 
@@ -325,19 +325,19 @@  discard block
 block discarded – undo
325 325
 	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
326 326
 		$supportedProperties = [
327 327
 			'{DAV:}displayname',
328
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
328
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description',
329 329
 		];
330 330
 
331 331
 		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
332 332
 
333 333
 			$updates = [];
334
-			foreach($mutations as $property=>$newValue) {
334
+			foreach ($mutations as $property=>$newValue) {
335 335
 
336
-				switch($property) {
336
+				switch ($property) {
337 337
 					case '{DAV:}displayname' :
338 338
 						$updates['displayname'] = $newValue;
339 339
 						break;
340
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
340
+					case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
341 341
 						$updates['description'] = $newValue;
342 342
 						break;
343 343
 				}
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
 			$query = $this->db->getQueryBuilder();
346 346
 			$query->update('addressbooks');
347 347
 
348
-			foreach($updates as $key=>$value) {
348
+			foreach ($updates as $key=>$value) {
349 349
 				$query->set($key, $query->createNamedParameter($value));
350 350
 			}
351 351
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
@@ -376,24 +376,24 @@  discard block
 block discarded – undo
376 376
 			'synctoken' => 1
377 377
 		];
378 378
 
379
-		foreach($properties as $property=>$newValue) {
379
+		foreach ($properties as $property=>$newValue) {
380 380
 
381
-			switch($property) {
381
+			switch ($property) {
382 382
 				case '{DAV:}displayname' :
383 383
 					$values['displayname'] = $newValue;
384 384
 					break;
385
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
385
+				case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
386 386
 					$values['description'] = $newValue;
387 387
 					break;
388 388
 				default :
389
-					throw new BadRequest('Unknown property: ' . $property);
389
+					throw new BadRequest('Unknown property: '.$property);
390 390
 			}
391 391
 
392 392
 		}
393 393
 
394 394
 		// Fallback to make sure the displayname is set. Some clients may refuse
395 395
 		// to work with addressbooks not having a displayname.
396
-		if(is_null($values['displayname'])) {
396
+		if (is_null($values['displayname'])) {
397 397
 			$values['displayname'] = $url;
398 398
 		}
399 399
 
@@ -471,8 +471,8 @@  discard block
 block discarded – undo
471 471
 		$cards = [];
472 472
 
473 473
 		$result = $query->execute();
474
-		while($row = $result->fetch()) {
475
-			$row['etag'] = '"' . $row['etag'] . '"';
474
+		while ($row = $result->fetch()) {
475
+			$row['etag'] = '"'.$row['etag'].'"';
476 476
 			$row['carddata'] = $this->readBlob($row['carddata']);
477 477
 			$cards[] = $row;
478 478
 		}
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
 		if (!$row) {
507 507
 			return false;
508 508
 		}
509
-		$row['etag'] = '"' . $row['etag'] . '"';
509
+		$row['etag'] = '"'.$row['etag'].'"';
510 510
 		$row['carddata'] = $this->readBlob($row['carddata']);
511 511
 
512 512
 		return $row;
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
 			$result = $query->execute();
544 544
 
545 545
 			while ($row = $result->fetch()) {
546
-				$row['etag'] = '"' . $row['etag'] . '"';
546
+				$row['etag'] = '"'.$row['etag'].'"';
547 547
 				$row['carddata'] = $this->readBlob($row['carddata']);
548 548
 				$cards[] = $row;
549 549
 			}
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
 					'cardData' => $cardData]));
604 604
 		}
605 605
 
606
-		return '"' . $etag . '"';
606
+		return '"'.$etag.'"';
607 607
 	}
608 608
 
609 609
 	/**
@@ -655,7 +655,7 @@  discard block
 block discarded – undo
655 655
 					'cardData' => $cardData]));
656 656
 		}
657 657
 
658
-		return '"' . $etag . '"';
658
+		return '"'.$etag.'"';
659 659
 	}
660 660
 
661 661
 	/**
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
 	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
756 756
 		// Current synctoken
757 757
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
758
-		$stmt->execute([ $addressBookId ]);
758
+		$stmt->execute([$addressBookId]);
759 759
 		$currentToken = $stmt->fetchColumn(0);
760 760
 
761 761
 		if (is_null($currentToken)) return null;
@@ -770,8 +770,8 @@  discard block
 block discarded – undo
770 770
 		if ($syncToken) {
771 771
 
772 772
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
773
-			if ($limit>0) {
774
-				$query .= " `LIMIT` " . (int)$limit;
773
+			if ($limit > 0) {
774
+				$query .= " `LIMIT` ".(int) $limit;
775 775
 			}
776 776
 
777 777
 			// Fetching all changes
@@ -782,15 +782,15 @@  discard block
 block discarded – undo
782 782
 
783 783
 			// This loop ensures that any duplicates are overwritten, only the
784 784
 			// last change on a node is relevant.
785
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
785
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
786 786
 
787 787
 				$changes[$row['uri']] = $row['operation'];
788 788
 
789 789
 			}
790 790
 
791
-			foreach($changes as $uri => $operation) {
791
+			foreach ($changes as $uri => $operation) {
792 792
 
793
-				switch($operation) {
793
+				switch ($operation) {
794 794
 					case 1:
795 795
 						$result['added'][] = $uri;
796 796
 						break;
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
 		$query = $this->db->getQueryBuilder();
867 867
 		$query2 = $this->db->getQueryBuilder();
868 868
 		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
869
-		$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
869
+		$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
870 870
 		foreach ($searchProperties as $property) {
871 871
 				$query2->expr()->orX($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
872 872
 		}
@@ -922,7 +922,7 @@  discard block
 block discarded – undo
922 922
 		$result->closeCursor();
923 923
 
924 924
 		if (!isset($uri['uri'])) {
925
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
925
+			throw new \InvalidArgumentException('Card does not exists: '.$id);
926 926
 		}
927 927
 
928 928
 		return $uri['uri'];
@@ -994,11 +994,11 @@  discard block
 block discarded – undo
994 994
 			);
995 995
 
996 996
 		foreach ($vCard->children() as $property) {
997
-			if(!in_array($property->name, self::$indexProperties)) {
997
+			if (!in_array($property->name, self::$indexProperties)) {
998 998
 				continue;
999 999
 			}
1000 1000
 			$preferred = 0;
1001
-			foreach($property->parameters as $parameter) {
1001
+			foreach ($property->parameters as $parameter) {
1002 1002
 				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1003 1003
 					$preferred = 1;
1004 1004
 					break;
@@ -1053,10 +1053,10 @@  discard block
 block discarded – undo
1053 1053
 		$result->closeCursor();
1054 1054
 
1055 1055
 		if (!isset($cardIds['id'])) {
1056
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1056
+			throw new \InvalidArgumentException('Card does not exists: '.$uri);
1057 1057
 		}
1058 1058
 
1059
-		return (int)$cardIds['id'];
1059
+		return (int) $cardIds['id'];
1060 1060
 	}
1061 1061
 
1062 1062
 	/**
Please login to merge, or discard this patch.
apps/files/lib/Controller/ViewController.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -35,7 +35,6 @@
 block discarded – undo
35 35
 use OCP\Files\NotFoundException;
36 36
 use OCP\IConfig;
37 37
 use OCP\IL10N;
38
-use OCP\INavigationManager;
39 38
 use OCP\IRequest;
40 39
 use OCP\IURLGenerator;
41 40
 use OCP\IUserSession;
Please login to merge, or discard this patch.
Indentation   +215 added lines, -215 removed lines patch added patch discarded remove patch
@@ -49,241 +49,241 @@
 block discarded – undo
49 49
  * @package OCA\Files\Controller
50 50
  */
51 51
 class ViewController extends Controller {
52
-	/** @var string */
53
-	protected $appName;
54
-	/** @var IRequest */
55
-	protected $request;
56
-	/** @var IURLGenerator */
57
-	protected $urlGenerator;
58
-	/** @var IL10N */
59
-	protected $l10n;
60
-	/** @var IConfig */
61
-	protected $config;
62
-	/** @var EventDispatcherInterface */
63
-	protected $eventDispatcher;
64
-	/** @var IUserSession */
65
-	protected $userSession;
66
-	/** @var IAppManager */
67
-	protected $appManager;
68
-	/** @var IRootFolder */
69
-	protected $rootFolder;
52
+    /** @var string */
53
+    protected $appName;
54
+    /** @var IRequest */
55
+    protected $request;
56
+    /** @var IURLGenerator */
57
+    protected $urlGenerator;
58
+    /** @var IL10N */
59
+    protected $l10n;
60
+    /** @var IConfig */
61
+    protected $config;
62
+    /** @var EventDispatcherInterface */
63
+    protected $eventDispatcher;
64
+    /** @var IUserSession */
65
+    protected $userSession;
66
+    /** @var IAppManager */
67
+    protected $appManager;
68
+    /** @var IRootFolder */
69
+    protected $rootFolder;
70 70
 
71
-	/**
72
-	 * @param string $appName
73
-	 * @param IRequest $request
74
-	 * @param IURLGenerator $urlGenerator
75
-	 * @param IL10N $l10n
76
-	 * @param IConfig $config
77
-	 * @param EventDispatcherInterface $eventDispatcherInterface
78
-	 * @param IUserSession $userSession
79
-	 * @param IAppManager $appManager
80
-	 * @param IRootFolder $rootFolder
81
-	 */
82
-	public function __construct($appName,
83
-								IRequest $request,
84
-								IURLGenerator $urlGenerator,
85
-								IL10N $l10n,
86
-								IConfig $config,
87
-								EventDispatcherInterface $eventDispatcherInterface,
88
-								IUserSession $userSession,
89
-								IAppManager $appManager,
90
-								IRootFolder $rootFolder
91
-	) {
92
-		parent::__construct($appName, $request);
93
-		$this->appName = $appName;
94
-		$this->request = $request;
95
-		$this->urlGenerator = $urlGenerator;
96
-		$this->l10n = $l10n;
97
-		$this->config = $config;
98
-		$this->eventDispatcher = $eventDispatcherInterface;
99
-		$this->userSession = $userSession;
100
-		$this->appManager = $appManager;
101
-		$this->rootFolder = $rootFolder;
102
-	}
71
+    /**
72
+     * @param string $appName
73
+     * @param IRequest $request
74
+     * @param IURLGenerator $urlGenerator
75
+     * @param IL10N $l10n
76
+     * @param IConfig $config
77
+     * @param EventDispatcherInterface $eventDispatcherInterface
78
+     * @param IUserSession $userSession
79
+     * @param IAppManager $appManager
80
+     * @param IRootFolder $rootFolder
81
+     */
82
+    public function __construct($appName,
83
+                                IRequest $request,
84
+                                IURLGenerator $urlGenerator,
85
+                                IL10N $l10n,
86
+                                IConfig $config,
87
+                                EventDispatcherInterface $eventDispatcherInterface,
88
+                                IUserSession $userSession,
89
+                                IAppManager $appManager,
90
+                                IRootFolder $rootFolder
91
+    ) {
92
+        parent::__construct($appName, $request);
93
+        $this->appName = $appName;
94
+        $this->request = $request;
95
+        $this->urlGenerator = $urlGenerator;
96
+        $this->l10n = $l10n;
97
+        $this->config = $config;
98
+        $this->eventDispatcher = $eventDispatcherInterface;
99
+        $this->userSession = $userSession;
100
+        $this->appManager = $appManager;
101
+        $this->rootFolder = $rootFolder;
102
+    }
103 103
 
104
-	/**
105
-	 * @param string $appName
106
-	 * @param string $scriptName
107
-	 * @return string
108
-	 */
109
-	protected function renderScript($appName, $scriptName) {
110
-		$content = '';
111
-		$appPath = \OC_App::getAppPath($appName);
112
-		$scriptPath = $appPath . '/' . $scriptName;
113
-		if (file_exists($scriptPath)) {
114
-			// TODO: sanitize path / script name ?
115
-			ob_start();
116
-			include $scriptPath;
117
-			$content = ob_get_contents();
118
-			@ob_end_clean();
119
-		}
120
-		return $content;
121
-	}
104
+    /**
105
+     * @param string $appName
106
+     * @param string $scriptName
107
+     * @return string
108
+     */
109
+    protected function renderScript($appName, $scriptName) {
110
+        $content = '';
111
+        $appPath = \OC_App::getAppPath($appName);
112
+        $scriptPath = $appPath . '/' . $scriptName;
113
+        if (file_exists($scriptPath)) {
114
+            // TODO: sanitize path / script name ?
115
+            ob_start();
116
+            include $scriptPath;
117
+            $content = ob_get_contents();
118
+            @ob_end_clean();
119
+        }
120
+        return $content;
121
+    }
122 122
 
123
-	/**
124
-	 * FIXME: Replace with non static code
125
-	 *
126
-	 * @return array
127
-	 * @throws \OCP\Files\NotFoundException
128
-	 */
129
-	protected function getStorageInfo() {
130
-		$dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
131
-		return \OC_Helper::getStorageInfo('/', $dirInfo);
132
-	}
123
+    /**
124
+     * FIXME: Replace with non static code
125
+     *
126
+     * @return array
127
+     * @throws \OCP\Files\NotFoundException
128
+     */
129
+    protected function getStorageInfo() {
130
+        $dirInfo = \OC\Files\Filesystem::getFileInfo('/', false);
131
+        return \OC_Helper::getStorageInfo('/', $dirInfo);
132
+    }
133 133
 
134
-	/**
135
-	 * @NoCSRFRequired
136
-	 * @NoAdminRequired
137
-	 *
138
-	 * @param string $dir
139
-	 * @param string $view
140
-	 * @param string $fileid
141
-	 * @return TemplateResponse|RedirectResponse
142
-	 */
143
-	public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
144
-		if ($fileid !== null) {
145
-			try {
146
-				return $this->showFile($fileid);
147
-			} catch (NotFoundException $e) {
148
-				return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
149
-			}
150
-		}
134
+    /**
135
+     * @NoCSRFRequired
136
+     * @NoAdminRequired
137
+     *
138
+     * @param string $dir
139
+     * @param string $view
140
+     * @param string $fileid
141
+     * @return TemplateResponse|RedirectResponse
142
+     */
143
+    public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
144
+        if ($fileid !== null) {
145
+            try {
146
+                return $this->showFile($fileid);
147
+            } catch (NotFoundException $e) {
148
+                return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
149
+            }
150
+        }
151 151
 
152
-		$nav = new \OCP\Template('files', 'appnavigation', '');
152
+        $nav = new \OCP\Template('files', 'appnavigation', '');
153 153
 
154
-		// Load the files we need
155
-		\OCP\Util::addStyle('files', 'files');
156
-		\OCP\Util::addStyle('files', 'upload');
157
-		\OCP\Util::addStyle('files', 'mobile');
158
-		\OCP\Util::addScript('files', 'app');
159
-		\OCP\Util::addScript('files', 'file-upload');
160
-		\OCP\Util::addScript('files', 'newfilemenu');
161
-		\OCP\Util::addScript('files', 'jquery.fileupload');
162
-		\OCP\Util::addScript('files', 'jquery-visibility');
163
-		\OCP\Util::addScript('files', 'fileinfomodel');
164
-		\OCP\Util::addScript('files', 'filesummary');
165
-		\OCP\Util::addScript('files', 'breadcrumb');
166
-		\OCP\Util::addScript('files', 'filelist');
167
-		\OCP\Util::addScript('files', 'search');
154
+        // Load the files we need
155
+        \OCP\Util::addStyle('files', 'files');
156
+        \OCP\Util::addStyle('files', 'upload');
157
+        \OCP\Util::addStyle('files', 'mobile');
158
+        \OCP\Util::addScript('files', 'app');
159
+        \OCP\Util::addScript('files', 'file-upload');
160
+        \OCP\Util::addScript('files', 'newfilemenu');
161
+        \OCP\Util::addScript('files', 'jquery.fileupload');
162
+        \OCP\Util::addScript('files', 'jquery-visibility');
163
+        \OCP\Util::addScript('files', 'fileinfomodel');
164
+        \OCP\Util::addScript('files', 'filesummary');
165
+        \OCP\Util::addScript('files', 'breadcrumb');
166
+        \OCP\Util::addScript('files', 'filelist');
167
+        \OCP\Util::addScript('files', 'search');
168 168
 
169
-		\OCP\Util::addScript('files', 'favoritesfilelist');
170
-		\OCP\Util::addScript('files', 'recentfilelist');
171
-		\OCP\Util::addScript('files', 'tagsplugin');
172
-		\OCP\Util::addScript('files', 'gotoplugin');
173
-		\OCP\Util::addScript('files', 'favoritesplugin');
174
-		\OCP\Util::addScript('files', 'recentplugin');
169
+        \OCP\Util::addScript('files', 'favoritesfilelist');
170
+        \OCP\Util::addScript('files', 'recentfilelist');
171
+        \OCP\Util::addScript('files', 'tagsplugin');
172
+        \OCP\Util::addScript('files', 'gotoplugin');
173
+        \OCP\Util::addScript('files', 'favoritesplugin');
174
+        \OCP\Util::addScript('files', 'recentplugin');
175 175
 
176
-		\OCP\Util::addScript('files', 'detailfileinfoview');
177
-		\OCP\Util::addScript('files', 'sidebarpreviewmanager');
178
-		\OCP\Util::addScript('files', 'sidebarpreviewtext');
179
-		\OCP\Util::addScript('files', 'detailtabview');
180
-		\OCP\Util::addScript('files', 'mainfileinfodetailview');
181
-		\OCP\Util::addScript('files', 'detailsview');
182
-		\OCP\Util::addStyle('files', 'detailsView');
176
+        \OCP\Util::addScript('files', 'detailfileinfoview');
177
+        \OCP\Util::addScript('files', 'sidebarpreviewmanager');
178
+        \OCP\Util::addScript('files', 'sidebarpreviewtext');
179
+        \OCP\Util::addScript('files', 'detailtabview');
180
+        \OCP\Util::addScript('files', 'mainfileinfodetailview');
181
+        \OCP\Util::addScript('files', 'detailsview');
182
+        \OCP\Util::addStyle('files', 'detailsView');
183 183
 
184
-		\OC_Util::addVendorScript('core', 'handlebars/handlebars');
184
+        \OC_Util::addVendorScript('core', 'handlebars/handlebars');
185 185
 
186
-		\OCP\Util::addScript('files', 'fileactions');
187
-		\OCP\Util::addScript('files', 'fileactionsmenu');
188
-		\OCP\Util::addScript('files', 'files');
189
-		\OCP\Util::addScript('files', 'keyboardshortcuts');
190
-		\OCP\Util::addScript('files', 'navigation');
186
+        \OCP\Util::addScript('files', 'fileactions');
187
+        \OCP\Util::addScript('files', 'fileactionsmenu');
188
+        \OCP\Util::addScript('files', 'files');
189
+        \OCP\Util::addScript('files', 'keyboardshortcuts');
190
+        \OCP\Util::addScript('files', 'navigation');
191 191
 
192
-		// mostly for the home storage's free space
193
-		// FIXME: Make non static
194
-		$storageInfo = $this->getStorageInfo();
192
+        // mostly for the home storage's free space
193
+        // FIXME: Make non static
194
+        $storageInfo = $this->getStorageInfo();
195 195
 
196
-		\OCA\Files\App::getNavigationManager()->add(
197
-			[
198
-				'id' => 'favorites',
199
-				'appname' => 'files',
200
-				'script' => 'simplelist.php',
201
-				'order' => 5,
202
-				'name' => $this->l10n->t('Favorites')
203
-			]
204
-		);
196
+        \OCA\Files\App::getNavigationManager()->add(
197
+            [
198
+                'id' => 'favorites',
199
+                'appname' => 'files',
200
+                'script' => 'simplelist.php',
201
+                'order' => 5,
202
+                'name' => $this->l10n->t('Favorites')
203
+            ]
204
+        );
205 205
 
206
-		$navItems = \OCA\Files\App::getNavigationManager()->getAll();
207
-		usort($navItems, function($item1, $item2) {
208
-			return $item1['order'] - $item2['order'];
209
-		});
210
-		$nav->assign('navigationItems', $navItems);
206
+        $navItems = \OCA\Files\App::getNavigationManager()->getAll();
207
+        usort($navItems, function($item1, $item2) {
208
+            return $item1['order'] - $item2['order'];
209
+        });
210
+        $nav->assign('navigationItems', $navItems);
211 211
 
212
-		$contentItems = [];
212
+        $contentItems = [];
213 213
 
214
-		// render the container content for every navigation item
215
-		foreach ($navItems as $item) {
216
-			$content = '';
217
-			if (isset($item['script'])) {
218
-				$content = $this->renderScript($item['appname'], $item['script']);
219
-			}
220
-			$contentItem = [];
221
-			$contentItem['id'] = $item['id'];
222
-			$contentItem['content'] = $content;
223
-			$contentItems[] = $contentItem;
224
-		}
214
+        // render the container content for every navigation item
215
+        foreach ($navItems as $item) {
216
+            $content = '';
217
+            if (isset($item['script'])) {
218
+                $content = $this->renderScript($item['appname'], $item['script']);
219
+            }
220
+            $contentItem = [];
221
+            $contentItem['id'] = $item['id'];
222
+            $contentItem['content'] = $content;
223
+            $contentItems[] = $contentItem;
224
+        }
225 225
 
226
-		$this->eventDispatcher->dispatch('OCA\Files::loadAdditionalScripts');
226
+        $this->eventDispatcher->dispatch('OCA\Files::loadAdditionalScripts');
227 227
 
228
-		$params = [];
229
-		$params['usedSpacePercent'] = (int)$storageInfo['relative'];
230
-		$params['owner'] = $storageInfo['owner'];
231
-		$params['ownerDisplayName'] = $storageInfo['ownerDisplayName'];
232
-		$params['isPublic'] = false;
233
-		$params['allowShareWithLink'] = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
234
-		$user = $this->userSession->getUser()->getUID();
235
-		$params['defaultFileSorting'] = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
236
-		$params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
237
-		$showHidden = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
238
-		$params['showHiddenFiles'] = $showHidden ? 1 : 0;
239
-		$params['fileNotFound'] = $fileNotFound ? 1 : 0;
240
-		$params['appNavigation'] = $nav;
241
-		$params['appContents'] = $contentItems;
228
+        $params = [];
229
+        $params['usedSpacePercent'] = (int)$storageInfo['relative'];
230
+        $params['owner'] = $storageInfo['owner'];
231
+        $params['ownerDisplayName'] = $storageInfo['ownerDisplayName'];
232
+        $params['isPublic'] = false;
233
+        $params['allowShareWithLink'] = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes');
234
+        $user = $this->userSession->getUser()->getUID();
235
+        $params['defaultFileSorting'] = $this->config->getUserValue($user, 'files', 'file_sorting', 'name');
236
+        $params['defaultFileSortingDirection'] = $this->config->getUserValue($user, 'files', 'file_sorting_direction', 'asc');
237
+        $showHidden = (bool) $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', false);
238
+        $params['showHiddenFiles'] = $showHidden ? 1 : 0;
239
+        $params['fileNotFound'] = $fileNotFound ? 1 : 0;
240
+        $params['appNavigation'] = $nav;
241
+        $params['appContents'] = $contentItems;
242 242
 
243
-		$response = new TemplateResponse(
244
-			$this->appName,
245
-			'index',
246
-			$params
247
-		);
248
-		$policy = new ContentSecurityPolicy();
249
-		$policy->addAllowedFrameDomain('\'self\'');
250
-		$response->setContentSecurityPolicy($policy);
243
+        $response = new TemplateResponse(
244
+            $this->appName,
245
+            'index',
246
+            $params
247
+        );
248
+        $policy = new ContentSecurityPolicy();
249
+        $policy->addAllowedFrameDomain('\'self\'');
250
+        $response->setContentSecurityPolicy($policy);
251 251
 
252
-		return $response;
253
-	}
252
+        return $response;
253
+    }
254 254
 
255
-	/**
256
-	 * Redirects to the file list and highlight the given file id
257
-	 *
258
-	 * @param string $fileId file id to show
259
-	 * @return RedirectResponse redirect response or not found response
260
-	 * @throws \OCP\Files\NotFoundException
261
-	 */
262
-	private function showFile($fileId) {
263
-		$uid = $this->userSession->getUser()->getUID();
264
-		$baseFolder = $this->rootFolder->getUserFolder($uid);
265
-		$files = $baseFolder->getById($fileId);
266
-		$params = [];
255
+    /**
256
+     * Redirects to the file list and highlight the given file id
257
+     *
258
+     * @param string $fileId file id to show
259
+     * @return RedirectResponse redirect response or not found response
260
+     * @throws \OCP\Files\NotFoundException
261
+     */
262
+    private function showFile($fileId) {
263
+        $uid = $this->userSession->getUser()->getUID();
264
+        $baseFolder = $this->rootFolder->getUserFolder($uid);
265
+        $files = $baseFolder->getById($fileId);
266
+        $params = [];
267 267
 
268
-		if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
269
-			$baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
270
-			$files = $baseFolder->getById($fileId);
271
-			$params['view'] = 'trashbin';
272
-		}
268
+        if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
269
+            $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
270
+            $files = $baseFolder->getById($fileId);
271
+            $params['view'] = 'trashbin';
272
+        }
273 273
 
274
-		if (!empty($files)) {
275
-			$file = current($files);
276
-			if ($file instanceof Folder) {
277
-				// set the full path to enter the folder
278
-				$params['dir'] = $baseFolder->getRelativePath($file->getPath());
279
-			} else {
280
-				// set parent path as dir
281
-				$params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
282
-				// and scroll to the entry
283
-				$params['scrollto'] = $file->getName();
284
-			}
285
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
286
-		}
287
-		throw new \OCP\Files\NotFoundException();
288
-	}
274
+        if (!empty($files)) {
275
+            $file = current($files);
276
+            if ($file instanceof Folder) {
277
+                // set the full path to enter the folder
278
+                $params['dir'] = $baseFolder->getRelativePath($file->getPath());
279
+            } else {
280
+                // set parent path as dir
281
+                $params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
282
+                // and scroll to the entry
283
+                $params['scrollto'] = $file->getName();
284
+            }
285
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
286
+        }
287
+        throw new \OCP\Files\NotFoundException();
288
+    }
289 289
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 	protected function renderScript($appName, $scriptName) {
110 110
 		$content = '';
111 111
 		$appPath = \OC_App::getAppPath($appName);
112
-		$scriptPath = $appPath . '/' . $scriptName;
112
+		$scriptPath = $appPath.'/'.$scriptName;
113 113
 		if (file_exists($scriptPath)) {
114 114
 			// TODO: sanitize path / script name ?
115 115
 			ob_start();
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 		$this->eventDispatcher->dispatch('OCA\Files::loadAdditionalScripts');
227 227
 
228 228
 		$params = [];
229
-		$params['usedSpacePercent'] = (int)$storageInfo['relative'];
229
+		$params['usedSpacePercent'] = (int) $storageInfo['relative'];
230 230
 		$params['owner'] = $storageInfo['owner'];
231 231
 		$params['ownerDisplayName'] = $storageInfo['ownerDisplayName'];
232 232
 		$params['isPublic'] = false;
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 		$params = [];
267 267
 
268 268
 		if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
269
-			$baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
269
+			$baseFolder = $this->rootFolder->get($uid.'/files_trashbin/files/');
270 270
 			$files = $baseFolder->getById($fileId);
271 271
 			$params['view'] = 'trashbin';
272 272
 		}
Please login to merge, or discard this patch.
cron.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -33,13 +33,13 @@  discard block
 block discarded – undo
33 33
 // Show warning if a PHP version below 5.6.0 is used
34 34
 if (version_compare(PHP_VERSION, '5.6.0') === -1) {
35 35
 	echo 'This version of Nextcloud requires at least PHP 5.6.0<br/>';
36
-	echo 'You are currently running ' . PHP_VERSION . '. Please update your PHP version.';
36
+	echo 'You are currently running '.PHP_VERSION.'. Please update your PHP version.';
37 37
 	return;
38 38
 }
39 39
 
40 40
 try {
41 41
 
42
-	require_once __DIR__ . '/lib/base.php';
42
+	require_once __DIR__.'/lib/base.php';
43 43
 
44 44
 	if (\OCP\Util::needUpgrade()) {
45 45
 		\OCP\Util::writeLog('cron', 'Update required, skipping cron', \OCP\Util::DEBUG);
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
 	$appMode = \OCP\BackgroundJob::getExecutionType();
81 81
 	if ($appMode == 'none') {
82 82
 		if (OC::$CLI) {
83
-			echo 'Background Jobs are disabled!' . PHP_EOL;
83
+			echo 'Background Jobs are disabled!'.PHP_EOL;
84 84
 		} else {
85 85
 			OC_JSON::error(array('data' => array('message' => 'Background jobs disabled!')));
86 86
 		}
@@ -93,15 +93,15 @@  discard block
 block discarded – undo
93 93
 
94 94
 		// the cron job must be executed with the right user
95 95
 		if (!function_exists('posix_getuid')) {
96
-			echo "The posix extensions are required - see http://php.net/manual/en/book.posix.php" . PHP_EOL;
96
+			echo "The posix extensions are required - see http://php.net/manual/en/book.posix.php".PHP_EOL;
97 97
 			exit(0);
98 98
 		}
99 99
 		$user = posix_getpwuid(posix_getuid());
100
-		$configUser = posix_getpwuid(fileowner(OC::$configDir . 'config.php'));
100
+		$configUser = posix_getpwuid(fileowner(OC::$configDir.'config.php'));
101 101
 		if ($user['name'] !== $configUser['name']) {
102
-			echo "Console has to be executed with the same user as the web server is operated" . PHP_EOL;
103
-			echo "Current user: " . $user['name'] . PHP_EOL;
104
-			echo "Web server user: " . $configUser['name'] . PHP_EOL;
102
+			echo "Console has to be executed with the same user as the web server is operated".PHP_EOL;
103
+			echo "Current user: ".$user['name'].PHP_EOL;
104
+			echo "Web server user: ".$configUser['name'].PHP_EOL;
105 105
 			exit(0);
106 106
 		}
107 107
 
@@ -124,11 +124,11 @@  discard block
 block discarded – undo
124 124
 				break;
125 125
 			}
126 126
 
127
-			$logger->debug('Run ' . get_class($job) . ' job with ID ' . $job->getId(), ['app' => 'cron']);
127
+			$logger->debug('Run '.get_class($job).' job with ID '.$job->getId(), ['app' => 'cron']);
128 128
 			$job->execute($jobList, $logger);
129 129
 			// clean up after unclean jobs
130 130
 			\OC_Util::tearDownFS();
131
-			$logger->debug('Finished ' . get_class($job) . ' job with ID ' . $job->getId(), ['app' => 'cron']);
131
+			$logger->debug('Finished '.get_class($job).' job with ID '.$job->getId(), ['app' => 'cron']);
132 132
 
133 133
 			$jobList->setLastJob($job);
134 134
 			$executedJobs[$job->getId()] = true;
Please login to merge, or discard this patch.
Indentation   +122 added lines, -122 removed lines patch added patch discarded remove patch
@@ -32,133 +32,133 @@
 block discarded – undo
32 32
 
33 33
 // Show warning if a PHP version below 5.6.0 is used
34 34
 if (version_compare(PHP_VERSION, '5.6.0') === -1) {
35
-	echo 'This version of Nextcloud requires at least PHP 5.6.0<br/>';
36
-	echo 'You are currently running ' . PHP_VERSION . '. Please update your PHP version.';
37
-	return;
35
+    echo 'This version of Nextcloud requires at least PHP 5.6.0<br/>';
36
+    echo 'You are currently running ' . PHP_VERSION . '. Please update your PHP version.';
37
+    return;
38 38
 }
39 39
 
40 40
 try {
41 41
 
42
-	require_once __DIR__ . '/lib/base.php';
43
-
44
-	if (\OCP\Util::needUpgrade()) {
45
-		\OCP\Util::writeLog('cron', 'Update required, skipping cron', \OCP\Util::DEBUG);
46
-		exit;
47
-	}
48
-	if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
49
-		\OCP\Util::writeLog('cron', 'We are in maintenance mode, skipping cron', \OCP\Util::DEBUG);
50
-		exit;
51
-	}
52
-
53
-	// load all apps to get all api routes properly setup
54
-	OC_App::loadApps();
55
-
56
-	\OC::$server->getSession()->close();
57
-
58
-	// initialize a dummy memory session
59
-	$session = new \OC\Session\Memory('');
60
-	$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
61
-	$session = $cryptoWrapper->wrapSession($session);
62
-	\OC::$server->setSession($session);
63
-
64
-	$logger = \OC::$server->getLogger();
65
-	$config = \OC::$server->getConfig();
66
-
67
-	// Don't do anything if ownCloud has not been installed
68
-	if (!$config->getSystemValue('installed', false)) {
69
-		exit(0);
70
-	}
71
-
72
-	\OC::$server->getTempManager()->cleanOld();
73
-
74
-	// Exit if background jobs are disabled!
75
-	$appMode = \OCP\BackgroundJob::getExecutionType();
76
-	if ($appMode == 'none') {
77
-		if (OC::$CLI) {
78
-			echo 'Background Jobs are disabled!' . PHP_EOL;
79
-		} else {
80
-			OC_JSON::error(array('data' => array('message' => 'Background jobs disabled!')));
81
-		}
82
-		exit(1);
83
-	}
84
-
85
-	if (OC::$CLI) {
86
-		// set to run indefinitely if needed
87
-		set_time_limit(0);
88
-
89
-		// the cron job must be executed with the right user
90
-		if (!function_exists('posix_getuid')) {
91
-			echo "The posix extensions are required - see http://php.net/manual/en/book.posix.php" . PHP_EOL;
92
-			exit(0);
93
-		}
94
-		$user = posix_getpwuid(posix_getuid());
95
-		$configUser = posix_getpwuid(fileowner(OC::$configDir . 'config.php'));
96
-		if ($user['name'] !== $configUser['name']) {
97
-			echo "Console has to be executed with the same user as the web server is operated" . PHP_EOL;
98
-			echo "Current user: " . $user['name'] . PHP_EOL;
99
-			echo "Web server user: " . $configUser['name'] . PHP_EOL;
100
-			exit(0);
101
-		}
102
-
103
-		// We call ownCloud from the CLI (aka cron)
104
-		if ($appMode != 'cron') {
105
-			\OCP\BackgroundJob::setExecutionType('cron');
106
-		}
107
-
108
-		// Work
109
-		$jobList = \OC::$server->getJobList();
110
-
111
-		// We only ask for jobs for 14 minutes, because after 15 minutes the next
112
-		// system cron task should spawn.
113
-		$endTime = time() + 14 * 60;
114
-
115
-		$executedJobs = [];
116
-		while ($job = $jobList->getNext()) {
117
-			if (isset($executedJobs[$job->getId()])) {
118
-				$jobList->unlockJob($job);
119
-				break;
120
-			}
121
-
122
-			$logger->debug('Run ' . get_class($job) . ' job with ID ' . $job->getId(), ['app' => 'cron']);
123
-			$job->execute($jobList, $logger);
124
-			// clean up after unclean jobs
125
-			\OC_Util::tearDownFS();
126
-			$logger->debug('Finished ' . get_class($job) . ' job with ID ' . $job->getId(), ['app' => 'cron']);
127
-
128
-			$jobList->setLastJob($job);
129
-			$executedJobs[$job->getId()] = true;
130
-			unset($job);
131
-
132
-			if (time() > $endTime) {
133
-				break;
134
-			}
135
-		}
136
-
137
-	} else {
138
-		// We call cron.php from some website
139
-		if ($appMode == 'cron') {
140
-			// Cron is cron :-P
141
-			OC_JSON::error(array('data' => array('message' => 'Backgroundjobs are using system cron!')));
142
-		} else {
143
-			// Work and success :-)
144
-			$jobList = \OC::$server->getJobList();
145
-			$job = $jobList->getNext();
146
-			if ($job != null) {
147
-				$job->execute($jobList, $logger);
148
-				$jobList->setLastJob($job);
149
-			}
150
-			OC_JSON::success();
151
-		}
152
-	}
153
-
154
-	// Log the successful cron execution
155
-	if (\OC::$server->getConfig()->getSystemValue('cron_log', true)) {
156
-		\OC::$server->getConfig()->setAppValue('core', 'lastcron', time());
157
-	}
158
-	exit();
42
+    require_once __DIR__ . '/lib/base.php';
43
+
44
+    if (\OCP\Util::needUpgrade()) {
45
+        \OCP\Util::writeLog('cron', 'Update required, skipping cron', \OCP\Util::DEBUG);
46
+        exit;
47
+    }
48
+    if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
49
+        \OCP\Util::writeLog('cron', 'We are in maintenance mode, skipping cron', \OCP\Util::DEBUG);
50
+        exit;
51
+    }
52
+
53
+    // load all apps to get all api routes properly setup
54
+    OC_App::loadApps();
55
+
56
+    \OC::$server->getSession()->close();
57
+
58
+    // initialize a dummy memory session
59
+    $session = new \OC\Session\Memory('');
60
+    $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
61
+    $session = $cryptoWrapper->wrapSession($session);
62
+    \OC::$server->setSession($session);
63
+
64
+    $logger = \OC::$server->getLogger();
65
+    $config = \OC::$server->getConfig();
66
+
67
+    // Don't do anything if ownCloud has not been installed
68
+    if (!$config->getSystemValue('installed', false)) {
69
+        exit(0);
70
+    }
71
+
72
+    \OC::$server->getTempManager()->cleanOld();
73
+
74
+    // Exit if background jobs are disabled!
75
+    $appMode = \OCP\BackgroundJob::getExecutionType();
76
+    if ($appMode == 'none') {
77
+        if (OC::$CLI) {
78
+            echo 'Background Jobs are disabled!' . PHP_EOL;
79
+        } else {
80
+            OC_JSON::error(array('data' => array('message' => 'Background jobs disabled!')));
81
+        }
82
+        exit(1);
83
+    }
84
+
85
+    if (OC::$CLI) {
86
+        // set to run indefinitely if needed
87
+        set_time_limit(0);
88
+
89
+        // the cron job must be executed with the right user
90
+        if (!function_exists('posix_getuid')) {
91
+            echo "The posix extensions are required - see http://php.net/manual/en/book.posix.php" . PHP_EOL;
92
+            exit(0);
93
+        }
94
+        $user = posix_getpwuid(posix_getuid());
95
+        $configUser = posix_getpwuid(fileowner(OC::$configDir . 'config.php'));
96
+        if ($user['name'] !== $configUser['name']) {
97
+            echo "Console has to be executed with the same user as the web server is operated" . PHP_EOL;
98
+            echo "Current user: " . $user['name'] . PHP_EOL;
99
+            echo "Web server user: " . $configUser['name'] . PHP_EOL;
100
+            exit(0);
101
+        }
102
+
103
+        // We call ownCloud from the CLI (aka cron)
104
+        if ($appMode != 'cron') {
105
+            \OCP\BackgroundJob::setExecutionType('cron');
106
+        }
107
+
108
+        // Work
109
+        $jobList = \OC::$server->getJobList();
110
+
111
+        // We only ask for jobs for 14 minutes, because after 15 minutes the next
112
+        // system cron task should spawn.
113
+        $endTime = time() + 14 * 60;
114
+
115
+        $executedJobs = [];
116
+        while ($job = $jobList->getNext()) {
117
+            if (isset($executedJobs[$job->getId()])) {
118
+                $jobList->unlockJob($job);
119
+                break;
120
+            }
121
+
122
+            $logger->debug('Run ' . get_class($job) . ' job with ID ' . $job->getId(), ['app' => 'cron']);
123
+            $job->execute($jobList, $logger);
124
+            // clean up after unclean jobs
125
+            \OC_Util::tearDownFS();
126
+            $logger->debug('Finished ' . get_class($job) . ' job with ID ' . $job->getId(), ['app' => 'cron']);
127
+
128
+            $jobList->setLastJob($job);
129
+            $executedJobs[$job->getId()] = true;
130
+            unset($job);
131
+
132
+            if (time() > $endTime) {
133
+                break;
134
+            }
135
+        }
136
+
137
+    } else {
138
+        // We call cron.php from some website
139
+        if ($appMode == 'cron') {
140
+            // Cron is cron :-P
141
+            OC_JSON::error(array('data' => array('message' => 'Backgroundjobs are using system cron!')));
142
+        } else {
143
+            // Work and success :-)
144
+            $jobList = \OC::$server->getJobList();
145
+            $job = $jobList->getNext();
146
+            if ($job != null) {
147
+                $job->execute($jobList, $logger);
148
+                $jobList->setLastJob($job);
149
+            }
150
+            OC_JSON::success();
151
+        }
152
+    }
153
+
154
+    // Log the successful cron execution
155
+    if (\OC::$server->getConfig()->getSystemValue('cron_log', true)) {
156
+        \OC::$server->getConfig()->setAppValue('core', 'lastcron', time());
157
+    }
158
+    exit();
159 159
 
160 160
 } catch (Exception $ex) {
161
-	\OCP\Util::writeLog('cron', $ex->getMessage(), \OCP\Util::FATAL);
161
+    \OCP\Util::writeLog('cron', $ex->getMessage(), \OCP\Util::FATAL);
162 162
 } catch (Error $ex) {
163
-	\OCP\Util::writeLog('cron', $ex->getMessage(), \OCP\Util::FATAL);
163
+    \OCP\Util::writeLog('cron', $ex->getMessage(), \OCP\Util::FATAL);
164 164
 }
Please login to merge, or discard this patch.
apps/files/templates/admin.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -2,17 +2,17 @@
 block discarded – undo
2 2
 
3 3
 	<div class="section">
4 4
 		<h2><?php p($l->t('File handling')); ?></h2>
5
-		<label for="maxUploadSize"><?php p($l->t( 'Maximum upload size' )); ?> </label>
5
+		<label for="maxUploadSize"><?php p($l->t('Maximum upload size')); ?> </label>
6 6
 		<span id="maxUploadSizeSettingsMsg" class="msg"></span>
7 7
 		<br />
8
-		<input type="text" name='maxUploadSize' id="maxUploadSize" value='<?php p($_['uploadMaxFilesize']) ?>' <?php if(!$_['uploadChangable']) { p('disabled'); } ?> />
9
-		<?php if($_['displayMaxPossibleUploadSize']):?>
8
+		<input type="text" name='maxUploadSize' id="maxUploadSize" value='<?php p($_['uploadMaxFilesize']) ?>' <?php if (!$_['uploadChangable']) { p('disabled'); } ?> />
9
+		<?php if ($_['displayMaxPossibleUploadSize']):?>
10 10
 			(<?php p($l->t('max. possible: ')); p($_['maxPossibleUploadSize']) ?>)
11
-		<?php endif;?>
11
+		<?php endif; ?>
12 12
 		<input type="hidden" value="<?php p($_['requesttoken']); ?>" name="requesttoken" />
13
-		<?php if($_['uploadChangable']): ?>
13
+		<?php if ($_['uploadChangable']): ?>
14 14
 			<input type="submit" id="submitMaxUpload"
15
-				   value="<?php p($l->t( 'Save' )); ?>"/>
15
+				   value="<?php p($l->t('Save')); ?>"/>
16 16
 			<p><em><?php p($l->t('With PHP-FPM it might take 5 minutes for changes to be applied.')); ?></em></p>
17 17
 		<?php else: ?>
18 18
 			<p><em><?php p($l->t('Missing permissions to edit from here.')); ?></em></p>
Please login to merge, or discard this patch.
Braces   +5 added lines, -2 removed lines patch added patch discarded remove patch
@@ -14,7 +14,10 @@
 block discarded – undo
14 14
 			<input type="submit" id="submitMaxUpload"
15 15
 				   value="<?php p($l->t( 'Save' )); ?>"/>
16 16
 			<p><em><?php p($l->t('With PHP-FPM it might take 5 minutes for changes to be applied.')); ?></em></p>
17
-		<?php else: ?>
18
-			<p><em><?php p($l->t('Missing permissions to edit from here.')); ?></em></p>
17
+		<?php else {
18
+    : ?>
19
+			<p><em><?php p($l->t('Missing permissions to edit from here.'));
20
+}
21
+?></em></p>
19 22
 		<?php endif; ?>
20 23
 	</div>
Please login to merge, or discard this patch.
apps/files/templates/list.php 1 patch
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 		<div class="actions creatable hidden">
3 3
 			<div id="uploadprogresswrapper">
4 4
 				<div id="uploadprogressbar">
5
-					<em class="label outer" style="display:none"><span class="desktop"><?php p($l->t('Uploading...'));?></span><span class="mobile"><?php p($l->t('...'));?></span></em>
5
+					<em class="label outer" style="display:none"><span class="desktop"><?php p($l->t('Uploading...')); ?></span><span class="mobile"><?php p($l->t('...')); ?></span></em>
6 6
 				</div>
7 7
 				<input type="button" class="stop icon-close" style="display:none" value="" />
8 8
 			</div>
@@ -16,10 +16,10 @@  discard block
 block discarded – undo
16 16
 	*/ ?>
17 17
 	<input type="hidden" name="permissions" value="" id="permissions">
18 18
 	<input type="hidden" id="free_space" value="<?php isset($_['freeSpace']) ? p($_['freeSpace']) : '' ?>">
19
-	<?php if(isset($_['dirToken'])):?>
19
+	<?php if (isset($_['dirToken'])):?>
20 20
 	<input type="hidden" id="publicUploadRequestToken" name="requesttoken" value="<?php p($_['requesttoken']) ?>" />
21 21
 	<input type="hidden" id="dirToken" name="dirToken" value="<?php p($_['dirToken']) ?>" />
22
-	<?php endif;?>
22
+	<?php endif; ?>
23 23
 	<input type="hidden" class="max_human_file_size"
24 24
 		   value="(max <?php isset($_['uploadMaxHumanFilesize']) ? p($_['uploadMaxHumanFilesize']) : ''; ?>)">
25 25
 </div>
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
 					<label for="select_all_files">
46 46
 						<span class="hidden-visually"><?php p($l->t('Select all'))?></span>
47 47
 					</label>
48
-					<a class="name sort columntitle" data-sort="name"><span><?php p($l->t( 'Name' )); ?></span><span class="sort-indicator"></span></a>
48
+					<a class="name sort columntitle" data-sort="name"><span><?php p($l->t('Name')); ?></span><span class="sort-indicator"></span></a>
49 49
 					<span id="selectedActionsList" class="selectedActions">
50 50
 						<a href="" class="download">
51 51
 							<span class="icon icon-download"></span>
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 				<a class="size sort columntitle" data-sort="size"><span><?php p($l->t('Size')); ?></span><span class="sort-indicator"></span></a>
59 59
 			</th>
60 60
 			<th id="headerDate" class="hidden column-mtime">
61
-				<a id="modified" class="columntitle" data-sort="mtime"><span><?php p($l->t( 'Modified' )); ?></span><span class="sort-indicator"></span></a>
61
+				<a id="modified" class="columntitle" data-sort="mtime"><span><?php p($l->t('Modified')); ?></span><span class="sort-indicator"></span></a>
62 62
 					<span class="selectedActions"><a href="" class="delete-selected">
63 63
 						<span><?php p($l->t('Delete'))?></span>
64 64
 						<span class="icon icon-delete"></span>
@@ -78,6 +78,6 @@  discard block
 block discarded – undo
78 78
 <div id="editor"></div><!-- FIXME Do not use this div in your app! It is deprecated and will be removed in the future! -->
79 79
 <div id="uploadsize-message" title="<?php p($l->t('Upload too large'))?>">
80 80
 	<p>
81
-	<?php p($l->t('The files you are trying to upload exceed the maximum size for file uploads on this server.'));?>
81
+	<?php p($l->t('The files you are trying to upload exceed the maximum size for file uploads on this server.')); ?>
82 82
 	</p>
83 83
 </div>
Please login to merge, or discard this patch.
apps/files/templates/simplelist.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -19,14 +19,14 @@
 block discarded – undo
19 19
 		<tr>
20 20
 			<th id='headerName' class="hidden column-name">
21 21
 				<div id="headerName-container">
22
-					<a class="name sort columntitle" data-sort="name"><span><?php p($l->t( 'Name' )); ?></span><span class="sort-indicator"></span></a>
22
+					<a class="name sort columntitle" data-sort="name"><span><?php p($l->t('Name')); ?></span><span class="sort-indicator"></span></a>
23 23
 				</div>
24 24
 			</th>
25 25
 			<th id="headerSize" class="hidden column-size">
26 26
 				<a class="size sort columntitle" data-sort="size"><span><?php p($l->t('Size')); ?></span><span class="sort-indicator"></span></a>
27 27
 			</th>
28 28
 			<th id="headerDate" class="hidden column-mtime">
29
-				<a id="modified" class="columntitle" data-sort="mtime"><span><?php p($l->t( 'Modified' )); ?></span><span class="sort-indicator"></span></a>
29
+				<a id="modified" class="columntitle" data-sort="mtime"><span><?php p($l->t('Modified')); ?></span><span class="sort-indicator"></span></a>
30 30
 					<span class="selectedActions"><a href="" class="delete-selected">
31 31
 						<?php p($l->t('Delete'))?>
32 32
 						<img class="svg" alt="<?php p($l->t('Delete'))?>"
Please login to merge, or discard this patch.