Completed
Pull Request — master (#3676)
by Individual IT
12:49
created
lib/public/AppFramework/Http/StreamResponse.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@
 block discarded – undo
37 37
 	private $filePath;
38 38
 
39 39
 	/**
40
-	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
40
+	 * @param string $filePath the path to the file or a file handle which should be streamed
41 41
 	 * @since 8.1.0
42 42
 	 */
43 43
 	public function __construct ($filePath) {
Please login to merge, or discard this patch.
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -33,33 +33,33 @@
 block discarded – undo
33 33
  * @since 8.1.0
34 34
  */
35 35
 class StreamResponse extends Response implements ICallbackResponse {
36
-	/** @var string */
37
-	private $filePath;
36
+    /** @var string */
37
+    private $filePath;
38 38
 
39
-	/**
40
-	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
41
-	 * @since 8.1.0
42
-	 */
43
-	public function __construct ($filePath) {
44
-		$this->filePath = $filePath;
45
-	}
39
+    /**
40
+     * @param string|resource $filePath the path to the file or a file handle which should be streamed
41
+     * @since 8.1.0
42
+     */
43
+    public function __construct ($filePath) {
44
+        $this->filePath = $filePath;
45
+    }
46 46
 
47 47
 
48
-	/**
49
-	 * Streams the file using readfile
50
-	 *
51
-	 * @param IOutput $output a small wrapper that handles output
52
-	 * @since 8.1.0
53
-	 */
54
-	public function callback (IOutput $output) {
55
-		// handle caching
56
-		if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57
-			if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
58
-				$output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
59
-			} elseif ($output->setReadfile($this->filePath) === false) {
60
-				$output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
61
-			}
62
-		}
63
-	}
48
+    /**
49
+     * Streams the file using readfile
50
+     *
51
+     * @param IOutput $output a small wrapper that handles output
52
+     * @since 8.1.0
53
+     */
54
+    public function callback (IOutput $output) {
55
+        // handle caching
56
+        if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57
+            if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
58
+                $output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
59
+            } elseif ($output->setReadfile($this->filePath) === false) {
60
+                $output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
61
+            }
62
+        }
63
+    }
64 64
 
65 65
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
 	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
41 41
 	 * @since 8.1.0
42 42
 	 */
43
-	public function __construct ($filePath) {
43
+	public function __construct($filePath) {
44 44
 		$this->filePath = $filePath;
45 45
 	}
46 46
 
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 	 * @param IOutput $output a small wrapper that handles output
52 52
 	 * @since 8.1.0
53 53
 	 */
54
-	public function callback (IOutput $output) {
54
+	public function callback(IOutput $output) {
55 55
 		// handle caching
56 56
 		if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57 57
 			if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
Please login to merge, or discard this patch.
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.
Indentation   +483 added lines, -483 removed lines patch added patch discarded remove patch
@@ -56,510 +56,510 @@
 block discarded – undo
56 56
 
57 57
 class DIContainer extends SimpleContainer implements IAppContainer {
58 58
 
59
-	/**
60
-	 * @var array
61
-	 */
62
-	private $middleWares = array();
63
-
64
-	/**
65
-	 * Put your class dependencies in here
66
-	 * @param string $appName the name of the app
67
-	 */
68
-	public function __construct($appName, $urlParams = array()){
69
-		parent::__construct();
70
-		$this['AppName'] = $appName;
71
-		$this['urlParams'] = $urlParams;
72
-
73
-		/** @var \OC\ServerContainer $server */
74
-		$server = $this->getServer();
75
-		$server->registerAppContainer($appName, $this);
76
-
77
-		// aliases
78
-		$this->registerAlias('appName', 'AppName');
79
-		$this->registerAlias('webRoot', 'WebRoot');
80
-		$this->registerAlias('userId', 'UserId');
81
-
82
-		/**
83
-		 * Core services
84
-		 */
85
-		$this->registerService('OCP\\IAppConfig', function($c) {
86
-			return $this->getServer()->getAppConfig();
87
-		});
88
-
89
-		$this->registerService('OCP\\App\\IAppManager', function($c) {
90
-			return $this->getServer()->getAppManager();
91
-		});
92
-
93
-		$this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c){
94
-			return new Output($this->getServer()->getWebRoot());
95
-		});
96
-
97
-		$this->registerService(\OCP\Authentication\LoginCredentials\IStore::class, function() {
98
-			return $this->getServer()->query(\OCP\Authentication\LoginCredentials\IStore::class);
99
-		});
100
-
101
-		$this->registerService('OCP\\IAvatarManager', function($c) {
102
-			return $this->getServer()->getAvatarManager();
103
-		});
104
-
105
-		$this->registerService('OCP\\Activity\\IManager', function($c) {
106
-			return $this->getServer()->getActivityManager();
107
-		});
108
-		$this->registerService(\OCP\Activity\IEventMerger::class, function($c) {
109
-			return $this->getServer()->query(\OCP\Activity\IEventMerger::class);
110
-		});
111
-
112
-		$this->registerService('OCP\\ICache', function($c) {
113
-			return $this->getServer()->getCache();
114
-		});
115
-
116
-		$this->registerService('OCP\\ICacheFactory', function($c) {
117
-			return $this->getServer()->getMemCacheFactory();
118
-		});
119
-
120
-		$this->registerService('OC\\CapabilitiesManager', function($c) {
121
-			return $this->getServer()->getCapabilitiesManager();
122
-		});
123
-
124
-		$this->registerService('OCP\Comments\ICommentsManager', function($c) {
125
-			return $this->getServer()->getCommentsManager();
126
-		});
127
-
128
-		$this->registerService('OCP\\IConfig', function($c) {
129
-			return $this->getServer()->getConfig();
130
-		});
131
-
132
-		$this->registerService('OCP\\Contacts\\IManager', function($c) {
133
-			return $this->getServer()->getContactsManager();
134
-		});
135
-
136
-		$this->registerService('OCP\\IDateTimeZone', function($c) {
137
-			return $this->getServer()->getDateTimeZone();
138
-		});
139
-
140
-		$this->registerService('OCP\\IDateTimeFormatter', function($c) {
141
-			return $this->getServer()->getDateTimeFormatter();
142
-		});
143
-
144
-		$this->registerService('OCP\\IDBConnection', function($c) {
145
-			return $this->getServer()->getDatabaseConnection();
146
-		});
147
-
148
-		$this->registerService('OCP\\Diagnostics\\IEventLogger', function($c) {
149
-			return $this->getServer()->getEventLogger();
150
-		});
151
-
152
-		$this->registerService('OCP\\Diagnostics\\IQueryLogger', function($c) {
153
-			return $this->getServer()->getQueryLogger();
154
-		});
155
-
156
-		$this->registerService(ICloudIdManager::class, function($c) {
157
-			return $this->getServer()->getCloudIdManager();
158
-		});
159
-
160
-		$this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
161
-			return $this->getServer()->getMimeTypeDetector();
162
-		});
163
-
164
-		$this->registerService('OCP\\Files\\Config\\IMountProviderCollection', function($c) {
165
-			return $this->getServer()->getMountProviderCollection();
166
-		});
167
-
168
-		$this->registerService('OCP\\Files\\Config\\IUserMountCache', function($c) {
169
-			return $this->getServer()->getUserMountCache();
170
-		});
59
+    /**
60
+     * @var array
61
+     */
62
+    private $middleWares = array();
63
+
64
+    /**
65
+     * Put your class dependencies in here
66
+     * @param string $appName the name of the app
67
+     */
68
+    public function __construct($appName, $urlParams = array()){
69
+        parent::__construct();
70
+        $this['AppName'] = $appName;
71
+        $this['urlParams'] = $urlParams;
72
+
73
+        /** @var \OC\ServerContainer $server */
74
+        $server = $this->getServer();
75
+        $server->registerAppContainer($appName, $this);
76
+
77
+        // aliases
78
+        $this->registerAlias('appName', 'AppName');
79
+        $this->registerAlias('webRoot', 'WebRoot');
80
+        $this->registerAlias('userId', 'UserId');
81
+
82
+        /**
83
+         * Core services
84
+         */
85
+        $this->registerService('OCP\\IAppConfig', function($c) {
86
+            return $this->getServer()->getAppConfig();
87
+        });
88
+
89
+        $this->registerService('OCP\\App\\IAppManager', function($c) {
90
+            return $this->getServer()->getAppManager();
91
+        });
92
+
93
+        $this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c){
94
+            return new Output($this->getServer()->getWebRoot());
95
+        });
96
+
97
+        $this->registerService(\OCP\Authentication\LoginCredentials\IStore::class, function() {
98
+            return $this->getServer()->query(\OCP\Authentication\LoginCredentials\IStore::class);
99
+        });
100
+
101
+        $this->registerService('OCP\\IAvatarManager', function($c) {
102
+            return $this->getServer()->getAvatarManager();
103
+        });
104
+
105
+        $this->registerService('OCP\\Activity\\IManager', function($c) {
106
+            return $this->getServer()->getActivityManager();
107
+        });
108
+        $this->registerService(\OCP\Activity\IEventMerger::class, function($c) {
109
+            return $this->getServer()->query(\OCP\Activity\IEventMerger::class);
110
+        });
111
+
112
+        $this->registerService('OCP\\ICache', function($c) {
113
+            return $this->getServer()->getCache();
114
+        });
115
+
116
+        $this->registerService('OCP\\ICacheFactory', function($c) {
117
+            return $this->getServer()->getMemCacheFactory();
118
+        });
119
+
120
+        $this->registerService('OC\\CapabilitiesManager', function($c) {
121
+            return $this->getServer()->getCapabilitiesManager();
122
+        });
123
+
124
+        $this->registerService('OCP\Comments\ICommentsManager', function($c) {
125
+            return $this->getServer()->getCommentsManager();
126
+        });
127
+
128
+        $this->registerService('OCP\\IConfig', function($c) {
129
+            return $this->getServer()->getConfig();
130
+        });
131
+
132
+        $this->registerService('OCP\\Contacts\\IManager', function($c) {
133
+            return $this->getServer()->getContactsManager();
134
+        });
135
+
136
+        $this->registerService('OCP\\IDateTimeZone', function($c) {
137
+            return $this->getServer()->getDateTimeZone();
138
+        });
139
+
140
+        $this->registerService('OCP\\IDateTimeFormatter', function($c) {
141
+            return $this->getServer()->getDateTimeFormatter();
142
+        });
143
+
144
+        $this->registerService('OCP\\IDBConnection', function($c) {
145
+            return $this->getServer()->getDatabaseConnection();
146
+        });
147
+
148
+        $this->registerService('OCP\\Diagnostics\\IEventLogger', function($c) {
149
+            return $this->getServer()->getEventLogger();
150
+        });
151
+
152
+        $this->registerService('OCP\\Diagnostics\\IQueryLogger', function($c) {
153
+            return $this->getServer()->getQueryLogger();
154
+        });
155
+
156
+        $this->registerService(ICloudIdManager::class, function($c) {
157
+            return $this->getServer()->getCloudIdManager();
158
+        });
159
+
160
+        $this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
161
+            return $this->getServer()->getMimeTypeDetector();
162
+        });
163
+
164
+        $this->registerService('OCP\\Files\\Config\\IMountProviderCollection', function($c) {
165
+            return $this->getServer()->getMountProviderCollection();
166
+        });
167
+
168
+        $this->registerService('OCP\\Files\\Config\\IUserMountCache', function($c) {
169
+            return $this->getServer()->getUserMountCache();
170
+        });
171 171
 
172
-		$this->registerService('OCP\\Files\\IRootFolder', function($c) {
173
-			return $this->getServer()->getRootFolder();
174
-		});
172
+        $this->registerService('OCP\\Files\\IRootFolder', function($c) {
173
+            return $this->getServer()->getRootFolder();
174
+        });
175 175
 
176
-		$this->registerService('OCP\\Files\\Folder', function() {
177
-			return $this->getServer()->getUserFolder();
178
-		});
176
+        $this->registerService('OCP\\Files\\Folder', function() {
177
+            return $this->getServer()->getUserFolder();
178
+        });
179 179
 
180
-		$this->registerService('OCP\\Http\\Client\\IClientService', function($c) {
181
-			return $this->getServer()->getHTTPClientService();
182
-		});
180
+        $this->registerService('OCP\\Http\\Client\\IClientService', function($c) {
181
+            return $this->getServer()->getHTTPClientService();
182
+        });
183 183
 
184
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
185
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
186
-		});
184
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
185
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
186
+        });
187 187
 
188
-		$this->registerService('OCP\\IGroupManager', function($c) {
189
-			return $this->getServer()->getGroupManager();
190
-		});
188
+        $this->registerService('OCP\\IGroupManager', function($c) {
189
+            return $this->getServer()->getGroupManager();
190
+        });
191 191
 
192
-		$this->registerService('OCP\\Http\\Client\\IClientService', function() {
193
-			return $this->getServer()->getHTTPClientService();
194
-		});
192
+        $this->registerService('OCP\\Http\\Client\\IClientService', function() {
193
+            return $this->getServer()->getHTTPClientService();
194
+        });
195 195
 
196
-		$this->registerService('OCP\\IL10N', function($c) {
197
-			return $this->getServer()->getL10N($c->query('AppName'));
198
-		});
196
+        $this->registerService('OCP\\IL10N', function($c) {
197
+            return $this->getServer()->getL10N($c->query('AppName'));
198
+        });
199 199
 
200
-		$this->registerService('OCP\\L10N\\IFactory', function($c) {
201
-			return $this->getServer()->getL10NFactory();
202
-		});
200
+        $this->registerService('OCP\\L10N\\IFactory', function($c) {
201
+            return $this->getServer()->getL10NFactory();
202
+        });
203 203
 
204
-		$this->registerService('OCP\\ILogger', function($c) {
205
-			return $this->getServer()->getLogger();
206
-		});
204
+        $this->registerService('OCP\\ILogger', function($c) {
205
+            return $this->getServer()->getLogger();
206
+        });
207 207
 
208
-		$this->registerService('OCP\\BackgroundJob\\IJobList', function($c) {
209
-			return $this->getServer()->getJobList();
210
-		});
208
+        $this->registerService('OCP\\BackgroundJob\\IJobList', function($c) {
209
+            return $this->getServer()->getJobList();
210
+        });
211 211
 
212
-		$this->registerAlias('OCP\\AppFramework\\Utility\\IControllerMethodReflector', 'OC\AppFramework\Utility\ControllerMethodReflector');
213
-		$this->registerAlias('ControllerMethodReflector', 'OCP\\AppFramework\\Utility\\IControllerMethodReflector');
212
+        $this->registerAlias('OCP\\AppFramework\\Utility\\IControllerMethodReflector', 'OC\AppFramework\Utility\ControllerMethodReflector');
213
+        $this->registerAlias('ControllerMethodReflector', 'OCP\\AppFramework\\Utility\\IControllerMethodReflector');
214 214
 
215
-		$this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
216
-			return $this->getServer()->getMimeTypeDetector();
217
-		});
215
+        $this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
216
+            return $this->getServer()->getMimeTypeDetector();
217
+        });
218 218
 
219
-		$this->registerService('OCP\\Mail\\IMailer', function() {
220
-			return $this->getServer()->getMailer();
221
-		});
219
+        $this->registerService('OCP\\Mail\\IMailer', function() {
220
+            return $this->getServer()->getMailer();
221
+        });
222 222
 
223
-		$this->registerService('OCP\\INavigationManager', function($c) {
224
-			return $this->getServer()->getNavigationManager();
225
-		});
223
+        $this->registerService('OCP\\INavigationManager', function($c) {
224
+            return $this->getServer()->getNavigationManager();
225
+        });
226 226
 
227
-		$this->registerService('OCP\\Notification\IManager', function($c) {
228
-			return $this->getServer()->getNotificationManager();
229
-		});
227
+        $this->registerService('OCP\\Notification\IManager', function($c) {
228
+            return $this->getServer()->getNotificationManager();
229
+        });
230 230
 
231
-		$this->registerService('OCP\\IPreview', function($c) {
232
-			return $this->getServer()->getPreviewManager();
233
-		});
231
+        $this->registerService('OCP\\IPreview', function($c) {
232
+            return $this->getServer()->getPreviewManager();
233
+        });
234 234
 
235
-		$this->registerService('OCP\\IRequest', function () {
236
-			return $this->getServer()->getRequest();
237
-		});
238
-		$this->registerAlias('Request', 'OCP\\IRequest');
235
+        $this->registerService('OCP\\IRequest', function () {
236
+            return $this->getServer()->getRequest();
237
+        });
238
+        $this->registerAlias('Request', 'OCP\\IRequest');
239 239
 
240
-		$this->registerService('OCP\\ITagManager', function($c) {
241
-			return $this->getServer()->getTagManager();
242
-		});
240
+        $this->registerService('OCP\\ITagManager', function($c) {
241
+            return $this->getServer()->getTagManager();
242
+        });
243 243
 
244
-		$this->registerService('OCP\\ITempManager', function($c) {
245
-			return $this->getServer()->getTempManager();
246
-		});
244
+        $this->registerService('OCP\\ITempManager', function($c) {
245
+            return $this->getServer()->getTempManager();
246
+        });
247 247
 
248
-		$this->registerAlias('OCP\\AppFramework\\Utility\\ITimeFactory', 'OC\AppFramework\Utility\TimeFactory');
249
-		$this->registerAlias('TimeFactory', 'OCP\\AppFramework\\Utility\\ITimeFactory');
248
+        $this->registerAlias('OCP\\AppFramework\\Utility\\ITimeFactory', 'OC\AppFramework\Utility\TimeFactory');
249
+        $this->registerAlias('TimeFactory', 'OCP\\AppFramework\\Utility\\ITimeFactory');
250 250
 
251 251
 
252
-		$this->registerService('OCP\\Route\\IRouter', function($c) {
253
-			return $this->getServer()->getRouter();
254
-		});
255
-
256
-		$this->registerService('OCP\\ISearch', function($c) {
257
-			return $this->getServer()->getSearch();
258
-		});
252
+        $this->registerService('OCP\\Route\\IRouter', function($c) {
253
+            return $this->getServer()->getRouter();
254
+        });
255
+
256
+        $this->registerService('OCP\\ISearch', function($c) {
257
+            return $this->getServer()->getSearch();
258
+        });
259 259
 
260
-		$this->registerService('OCP\\ISearch', function($c) {
261
-			return $this->getServer()->getSearch();
262
-		});
263
-
264
-		$this->registerService('OCP\\Security\\ICrypto', function($c) {
265
-			return $this->getServer()->getCrypto();
266
-		});
267
-
268
-		$this->registerService('OCP\\Security\\IHasher', function($c) {
269
-			return $this->getServer()->getHasher();
270
-		});
271
-
272
-		$this->registerService('OCP\\Security\\ICredentialsManager', function($c) {
273
-			return $this->getServer()->getCredentialsManager();
274
-		});
275
-
276
-		$this->registerService('OCP\\Security\\ISecureRandom', function($c) {
277
-			return $this->getServer()->getSecureRandom();
278
-		});
279
-
280
-		$this->registerService('OCP\\Share\\IManager', function($c) {
281
-			return $this->getServer()->getShareManager();
282
-		});
283
-
284
-		$this->registerService('OCP\\SystemTag\\ISystemTagManager', function() {
285
-			return $this->getServer()->getSystemTagManager();
286
-		});
287
-
288
-		$this->registerService('OCP\\SystemTag\\ISystemTagObjectMapper', function() {
289
-			return $this->getServer()->getSystemTagObjectMapper();
290
-		});
291
-
292
-		$this->registerService('OCP\\IURLGenerator', function($c) {
293
-			return $this->getServer()->getURLGenerator();
294
-		});
295
-
296
-		$this->registerService('OCP\\IUserManager', function($c) {
297
-			return $this->getServer()->getUserManager();
298
-		});
299
-
300
-		$this->registerService('OCP\\IUserSession', function($c) {
301
-			return $this->getServer()->getUserSession();
302
-		});
303
-		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
304
-
305
-		$this->registerService('OCP\\ISession', function($c) {
306
-			return $this->getServer()->getSession();
307
-		});
308
-
309
-		$this->registerService('OCP\\Security\\IContentSecurityPolicyManager', function($c) {
310
-			return $this->getServer()->getContentSecurityPolicyManager();
311
-		});
312
-
313
-		$this->registerService('ServerContainer', function ($c) {
314
-			return $this->getServer();
315
-		});
316
-		$this->registerAlias('OCP\\IServerContainer', 'ServerContainer');
317
-
318
-		$this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function ($c) {
319
-			return $this->getServer()->getEventDispatcher();
320
-		});
321
-
322
-		$this->registerService('OCP\WorkflowEngine\IManager', function ($c) {
323
-			return $c->query('OCA\WorkflowEngine\Manager');
324
-		});
325
-
326
-		$this->registerService('OCP\\AppFramework\\IAppContainer', function ($c) {
327
-			return $c;
328
-		});
329
-		$this->registerService(IMountManager::class, function () {
330
-			return $this->getServer()->getMountManager();
331
-		});
332
-
333
-		// commonly used attributes
334
-		$this->registerService('UserId', function ($c) {
335
-			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
336
-		});
337
-
338
-		$this->registerService('WebRoot', function ($c) {
339
-			return $c->query('ServerContainer')->getWebRoot();
340
-		});
341
-
342
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
343
-			return $this->getServer()->getEncryptionManager();
344
-		});
345
-
346
-		$this->registerService(IValidator::class, function($c) {
347
-			return $c->query(Validator::class);
348
-		});
349
-
350
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
351
-			return new \OC\Security\IdentityProof\Manager(
352
-				$this->getServer()->getAppDataDir('identityproof'),
353
-				$this->getServer()->getCrypto()
354
-			);
355
-		});
356
-
357
-
358
-		/**
359
-		 * App Framework APIs
360
-		 */
361
-		$this->registerService('API', function($c){
362
-			$c->query('OCP\\ILogger')->debug(
363
-				'Accessing the API class is deprecated! Use the appropriate ' .
364
-				'services instead!'
365
-			);
366
-			return new API($c['AppName']);
367
-		});
368
-
369
-		$this->registerService('Protocol', function($c){
370
-			/** @var \OC\Server $server */
371
-			$server = $c->query('ServerContainer');
372
-			$protocol = $server->getRequest()->getHttpProtocol();
373
-			return new Http($_SERVER, $protocol);
374
-		});
375
-
376
-		$this->registerService('Dispatcher', function($c) {
377
-			return new Dispatcher(
378
-				$c['Protocol'],
379
-				$c['MiddlewareDispatcher'],
380
-				$c['ControllerMethodReflector'],
381
-				$c['Request']
382
-			);
383
-		});
384
-
385
-		/**
386
-		 * App Framework default arguments
387
-		 */
388
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
389
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
390
-		$this->registerParameter('corsMaxAge', 1728000);
391
-
392
-		/**
393
-		 * Middleware
394
-		 */
395
-		$app = $this;
396
-		$this->registerService('SecurityMiddleware', function($c) use ($app){
397
-			/** @var \OC\Server $server */
398
-			$server = $app->getServer();
399
-
400
-			return new SecurityMiddleware(
401
-				$c['Request'],
402
-				$c['ControllerMethodReflector'],
403
-				$server->getNavigationManager(),
404
-				$server->getURLGenerator(),
405
-				$server->getLogger(),
406
-				$server->getSession(),
407
-				$c['AppName'],
408
-				$app->isLoggedIn(),
409
-				$app->isAdminUser(),
410
-				$server->getContentSecurityPolicyManager(),
411
-				$server->getCsrfTokenManager(),
412
-				$server->getContentSecurityPolicyNonceManager(),
413
-				$server->getBruteForceThrottler()
414
-			);
415
-
416
-		});
417
-
418
-		$this->registerService('CORSMiddleware', function($c) {
419
-			return new CORSMiddleware(
420
-				$c['Request'],
421
-				$c['ControllerMethodReflector'],
422
-				$c['OCP\IUserSession'],
423
-				$c->getServer()->getBruteForceThrottler()
424
-			);
425
-		});
426
-
427
-		$this->registerService('SessionMiddleware', function($c) use ($app) {
428
-			return new SessionMiddleware(
429
-				$c['Request'],
430
-				$c['ControllerMethodReflector'],
431
-				$app->getServer()->getSession()
432
-			);
433
-		});
434
-
435
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
436
-			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
437
-			$userSession = $app->getServer()->getUserSession();
438
-			$session = $app->getServer()->getSession();
439
-			$urlGenerator = $app->getServer()->getURLGenerator();
440
-			$reflector = $c['ControllerMethodReflector'];
441
-			$request = $app->getServer()->getRequest();
442
-			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
443
-		});
444
-
445
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
446
-			return new OCSMiddleware(
447
-				$c['Request']
448
-			);
449
-		});
450
-
451
-		$middleWares = &$this->middleWares;
452
-		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
453
-			$dispatcher = new MiddlewareDispatcher();
454
-			$dispatcher->registerMiddleware($c['CORSMiddleware']);
455
-			$dispatcher->registerMiddleware($c['OCSMiddleware']);
456
-			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
457
-			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
458
-
459
-			foreach($middleWares as $middleWare) {
460
-				$dispatcher->registerMiddleware($c[$middleWare]);
461
-			}
462
-
463
-			$dispatcher->registerMiddleware($c['SessionMiddleware']);
464
-			return $dispatcher;
465
-		});
466
-
467
-	}
468
-
469
-
470
-	/**
471
-	 * @deprecated implements only deprecated methods
472
-	 * @return IApi
473
-	 */
474
-	function getCoreApi()
475
-	{
476
-		return $this->query('API');
477
-	}
478
-
479
-	/**
480
-	 * @return \OCP\IServerContainer
481
-	 */
482
-	function getServer()
483
-	{
484
-		return OC::$server;
485
-	}
486
-
487
-	/**
488
-	 * @param string $middleWare
489
-	 * @return boolean|null
490
-	 */
491
-	function registerMiddleWare($middleWare) {
492
-		array_push($this->middleWares, $middleWare);
493
-	}
494
-
495
-	/**
496
-	 * used to return the appname of the set application
497
-	 * @return string the name of your application
498
-	 */
499
-	function getAppName() {
500
-		return $this->query('AppName');
501
-	}
502
-
503
-	/**
504
-	 * @deprecated use IUserSession->isLoggedIn()
505
-	 * @return boolean
506
-	 */
507
-	function isLoggedIn() {
508
-		return \OC_User::isLoggedIn();
509
-	}
510
-
511
-	/**
512
-	 * @deprecated use IGroupManager->isAdmin($userId)
513
-	 * @return boolean
514
-	 */
515
-	function isAdminUser() {
516
-		$uid = $this->getUserId();
517
-		return \OC_User::isAdminUser($uid);
518
-	}
519
-
520
-	private function getUserId() {
521
-		return $this->getServer()->getSession()->get('user_id');
522
-	}
523
-
524
-	/**
525
-	 * @deprecated use the ILogger instead
526
-	 * @param string $message
527
-	 * @param string $level
528
-	 * @return mixed
529
-	 */
530
-	function log($message, $level) {
531
-		switch($level){
532
-			case 'debug':
533
-				$level = \OCP\Util::DEBUG;
534
-				break;
535
-			case 'info':
536
-				$level = \OCP\Util::INFO;
537
-				break;
538
-			case 'warn':
539
-				$level = \OCP\Util::WARN;
540
-				break;
541
-			case 'fatal':
542
-				$level = \OCP\Util::FATAL;
543
-				break;
544
-			default:
545
-				$level = \OCP\Util::ERROR;
546
-				break;
547
-		}
548
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
549
-	}
550
-
551
-	/**
552
-	 * Register a capability
553
-	 *
554
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
555
-	 */
556
-	public function registerCapability($serviceName) {
557
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
558
-			return $this->query($serviceName);
559
-		});
560
-	}
561
-
562
-	public function query($name) {
563
-		return parent::query($name);
564
-	}
260
+        $this->registerService('OCP\\ISearch', function($c) {
261
+            return $this->getServer()->getSearch();
262
+        });
263
+
264
+        $this->registerService('OCP\\Security\\ICrypto', function($c) {
265
+            return $this->getServer()->getCrypto();
266
+        });
267
+
268
+        $this->registerService('OCP\\Security\\IHasher', function($c) {
269
+            return $this->getServer()->getHasher();
270
+        });
271
+
272
+        $this->registerService('OCP\\Security\\ICredentialsManager', function($c) {
273
+            return $this->getServer()->getCredentialsManager();
274
+        });
275
+
276
+        $this->registerService('OCP\\Security\\ISecureRandom', function($c) {
277
+            return $this->getServer()->getSecureRandom();
278
+        });
279
+
280
+        $this->registerService('OCP\\Share\\IManager', function($c) {
281
+            return $this->getServer()->getShareManager();
282
+        });
283
+
284
+        $this->registerService('OCP\\SystemTag\\ISystemTagManager', function() {
285
+            return $this->getServer()->getSystemTagManager();
286
+        });
287
+
288
+        $this->registerService('OCP\\SystemTag\\ISystemTagObjectMapper', function() {
289
+            return $this->getServer()->getSystemTagObjectMapper();
290
+        });
291
+
292
+        $this->registerService('OCP\\IURLGenerator', function($c) {
293
+            return $this->getServer()->getURLGenerator();
294
+        });
295
+
296
+        $this->registerService('OCP\\IUserManager', function($c) {
297
+            return $this->getServer()->getUserManager();
298
+        });
299
+
300
+        $this->registerService('OCP\\IUserSession', function($c) {
301
+            return $this->getServer()->getUserSession();
302
+        });
303
+        $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
304
+
305
+        $this->registerService('OCP\\ISession', function($c) {
306
+            return $this->getServer()->getSession();
307
+        });
308
+
309
+        $this->registerService('OCP\\Security\\IContentSecurityPolicyManager', function($c) {
310
+            return $this->getServer()->getContentSecurityPolicyManager();
311
+        });
312
+
313
+        $this->registerService('ServerContainer', function ($c) {
314
+            return $this->getServer();
315
+        });
316
+        $this->registerAlias('OCP\\IServerContainer', 'ServerContainer');
317
+
318
+        $this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function ($c) {
319
+            return $this->getServer()->getEventDispatcher();
320
+        });
321
+
322
+        $this->registerService('OCP\WorkflowEngine\IManager', function ($c) {
323
+            return $c->query('OCA\WorkflowEngine\Manager');
324
+        });
325
+
326
+        $this->registerService('OCP\\AppFramework\\IAppContainer', function ($c) {
327
+            return $c;
328
+        });
329
+        $this->registerService(IMountManager::class, function () {
330
+            return $this->getServer()->getMountManager();
331
+        });
332
+
333
+        // commonly used attributes
334
+        $this->registerService('UserId', function ($c) {
335
+            return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
336
+        });
337
+
338
+        $this->registerService('WebRoot', function ($c) {
339
+            return $c->query('ServerContainer')->getWebRoot();
340
+        });
341
+
342
+        $this->registerService('OCP\Encryption\IManager', function ($c) {
343
+            return $this->getServer()->getEncryptionManager();
344
+        });
345
+
346
+        $this->registerService(IValidator::class, function($c) {
347
+            return $c->query(Validator::class);
348
+        });
349
+
350
+        $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
351
+            return new \OC\Security\IdentityProof\Manager(
352
+                $this->getServer()->getAppDataDir('identityproof'),
353
+                $this->getServer()->getCrypto()
354
+            );
355
+        });
356
+
357
+
358
+        /**
359
+         * App Framework APIs
360
+         */
361
+        $this->registerService('API', function($c){
362
+            $c->query('OCP\\ILogger')->debug(
363
+                'Accessing the API class is deprecated! Use the appropriate ' .
364
+                'services instead!'
365
+            );
366
+            return new API($c['AppName']);
367
+        });
368
+
369
+        $this->registerService('Protocol', function($c){
370
+            /** @var \OC\Server $server */
371
+            $server = $c->query('ServerContainer');
372
+            $protocol = $server->getRequest()->getHttpProtocol();
373
+            return new Http($_SERVER, $protocol);
374
+        });
375
+
376
+        $this->registerService('Dispatcher', function($c) {
377
+            return new Dispatcher(
378
+                $c['Protocol'],
379
+                $c['MiddlewareDispatcher'],
380
+                $c['ControllerMethodReflector'],
381
+                $c['Request']
382
+            );
383
+        });
384
+
385
+        /**
386
+         * App Framework default arguments
387
+         */
388
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
389
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
390
+        $this->registerParameter('corsMaxAge', 1728000);
391
+
392
+        /**
393
+         * Middleware
394
+         */
395
+        $app = $this;
396
+        $this->registerService('SecurityMiddleware', function($c) use ($app){
397
+            /** @var \OC\Server $server */
398
+            $server = $app->getServer();
399
+
400
+            return new SecurityMiddleware(
401
+                $c['Request'],
402
+                $c['ControllerMethodReflector'],
403
+                $server->getNavigationManager(),
404
+                $server->getURLGenerator(),
405
+                $server->getLogger(),
406
+                $server->getSession(),
407
+                $c['AppName'],
408
+                $app->isLoggedIn(),
409
+                $app->isAdminUser(),
410
+                $server->getContentSecurityPolicyManager(),
411
+                $server->getCsrfTokenManager(),
412
+                $server->getContentSecurityPolicyNonceManager(),
413
+                $server->getBruteForceThrottler()
414
+            );
415
+
416
+        });
417
+
418
+        $this->registerService('CORSMiddleware', function($c) {
419
+            return new CORSMiddleware(
420
+                $c['Request'],
421
+                $c['ControllerMethodReflector'],
422
+                $c['OCP\IUserSession'],
423
+                $c->getServer()->getBruteForceThrottler()
424
+            );
425
+        });
426
+
427
+        $this->registerService('SessionMiddleware', function($c) use ($app) {
428
+            return new SessionMiddleware(
429
+                $c['Request'],
430
+                $c['ControllerMethodReflector'],
431
+                $app->getServer()->getSession()
432
+            );
433
+        });
434
+
435
+        $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
436
+            $twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
437
+            $userSession = $app->getServer()->getUserSession();
438
+            $session = $app->getServer()->getSession();
439
+            $urlGenerator = $app->getServer()->getURLGenerator();
440
+            $reflector = $c['ControllerMethodReflector'];
441
+            $request = $app->getServer()->getRequest();
442
+            return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
443
+        });
444
+
445
+        $this->registerService('OCSMiddleware', function (SimpleContainer $c) {
446
+            return new OCSMiddleware(
447
+                $c['Request']
448
+            );
449
+        });
450
+
451
+        $middleWares = &$this->middleWares;
452
+        $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
453
+            $dispatcher = new MiddlewareDispatcher();
454
+            $dispatcher->registerMiddleware($c['CORSMiddleware']);
455
+            $dispatcher->registerMiddleware($c['OCSMiddleware']);
456
+            $dispatcher->registerMiddleware($c['SecurityMiddleware']);
457
+            $dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
458
+
459
+            foreach($middleWares as $middleWare) {
460
+                $dispatcher->registerMiddleware($c[$middleWare]);
461
+            }
462
+
463
+            $dispatcher->registerMiddleware($c['SessionMiddleware']);
464
+            return $dispatcher;
465
+        });
466
+
467
+    }
468
+
469
+
470
+    /**
471
+     * @deprecated implements only deprecated methods
472
+     * @return IApi
473
+     */
474
+    function getCoreApi()
475
+    {
476
+        return $this->query('API');
477
+    }
478
+
479
+    /**
480
+     * @return \OCP\IServerContainer
481
+     */
482
+    function getServer()
483
+    {
484
+        return OC::$server;
485
+    }
486
+
487
+    /**
488
+     * @param string $middleWare
489
+     * @return boolean|null
490
+     */
491
+    function registerMiddleWare($middleWare) {
492
+        array_push($this->middleWares, $middleWare);
493
+    }
494
+
495
+    /**
496
+     * used to return the appname of the set application
497
+     * @return string the name of your application
498
+     */
499
+    function getAppName() {
500
+        return $this->query('AppName');
501
+    }
502
+
503
+    /**
504
+     * @deprecated use IUserSession->isLoggedIn()
505
+     * @return boolean
506
+     */
507
+    function isLoggedIn() {
508
+        return \OC_User::isLoggedIn();
509
+    }
510
+
511
+    /**
512
+     * @deprecated use IGroupManager->isAdmin($userId)
513
+     * @return boolean
514
+     */
515
+    function isAdminUser() {
516
+        $uid = $this->getUserId();
517
+        return \OC_User::isAdminUser($uid);
518
+    }
519
+
520
+    private function getUserId() {
521
+        return $this->getServer()->getSession()->get('user_id');
522
+    }
523
+
524
+    /**
525
+     * @deprecated use the ILogger instead
526
+     * @param string $message
527
+     * @param string $level
528
+     * @return mixed
529
+     */
530
+    function log($message, $level) {
531
+        switch($level){
532
+            case 'debug':
533
+                $level = \OCP\Util::DEBUG;
534
+                break;
535
+            case 'info':
536
+                $level = \OCP\Util::INFO;
537
+                break;
538
+            case 'warn':
539
+                $level = \OCP\Util::WARN;
540
+                break;
541
+            case 'fatal':
542
+                $level = \OCP\Util::FATAL;
543
+                break;
544
+            default:
545
+                $level = \OCP\Util::ERROR;
546
+                break;
547
+        }
548
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
549
+    }
550
+
551
+    /**
552
+     * Register a capability
553
+     *
554
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
555
+     */
556
+    public function registerCapability($serviceName) {
557
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
558
+            return $this->query($serviceName);
559
+        });
560
+    }
561
+
562
+    public function query($name) {
563
+        return parent::query($name);
564
+    }
565 565
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 	 * Put your class dependencies in here
66 66
 	 * @param string $appName the name of the app
67 67
 	 */
68
-	public function __construct($appName, $urlParams = array()){
68
+	public function __construct($appName, $urlParams = array()) {
69 69
 		parent::__construct();
70 70
 		$this['AppName'] = $appName;
71 71
 		$this['urlParams'] = $urlParams;
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 			return $this->getServer()->getAppManager();
91 91
 		});
92 92
 
93
-		$this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c){
93
+		$this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c) {
94 94
 			return new Output($this->getServer()->getWebRoot());
95 95
 		});
96 96
 
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
 			return $this->getServer()->getHTTPClientService();
182 182
 		});
183 183
 
184
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
184
+		$this->registerService(IAppData::class, function(SimpleContainer $c) {
185 185
 			return $this->getServer()->getAppDataDir($c->query('AppName'));
186 186
 		});
187 187
 
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
 			return $this->getServer()->getPreviewManager();
233 233
 		});
234 234
 
235
-		$this->registerService('OCP\\IRequest', function () {
235
+		$this->registerService('OCP\\IRequest', function() {
236 236
 			return $this->getServer()->getRequest();
237 237
 		});
238 238
 		$this->registerAlias('Request', 'OCP\\IRequest');
@@ -310,36 +310,36 @@  discard block
 block discarded – undo
310 310
 			return $this->getServer()->getContentSecurityPolicyManager();
311 311
 		});
312 312
 
313
-		$this->registerService('ServerContainer', function ($c) {
313
+		$this->registerService('ServerContainer', function($c) {
314 314
 			return $this->getServer();
315 315
 		});
316 316
 		$this->registerAlias('OCP\\IServerContainer', 'ServerContainer');
317 317
 
318
-		$this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function ($c) {
318
+		$this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function($c) {
319 319
 			return $this->getServer()->getEventDispatcher();
320 320
 		});
321 321
 
322
-		$this->registerService('OCP\WorkflowEngine\IManager', function ($c) {
322
+		$this->registerService('OCP\WorkflowEngine\IManager', function($c) {
323 323
 			return $c->query('OCA\WorkflowEngine\Manager');
324 324
 		});
325 325
 
326
-		$this->registerService('OCP\\AppFramework\\IAppContainer', function ($c) {
326
+		$this->registerService('OCP\\AppFramework\\IAppContainer', function($c) {
327 327
 			return $c;
328 328
 		});
329
-		$this->registerService(IMountManager::class, function () {
329
+		$this->registerService(IMountManager::class, function() {
330 330
 			return $this->getServer()->getMountManager();
331 331
 		});
332 332
 
333 333
 		// commonly used attributes
334
-		$this->registerService('UserId', function ($c) {
334
+		$this->registerService('UserId', function($c) {
335 335
 			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
336 336
 		});
337 337
 
338
-		$this->registerService('WebRoot', function ($c) {
338
+		$this->registerService('WebRoot', function($c) {
339 339
 			return $c->query('ServerContainer')->getWebRoot();
340 340
 		});
341 341
 
342
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
342
+		$this->registerService('OCP\Encryption\IManager', function($c) {
343 343
 			return $this->getServer()->getEncryptionManager();
344 344
 		});
345 345
 
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 			return $c->query(Validator::class);
348 348
 		});
349 349
 
350
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
350
+		$this->registerService(\OC\Security\IdentityProof\Manager::class, function($c) {
351 351
 			return new \OC\Security\IdentityProof\Manager(
352 352
 				$this->getServer()->getAppDataDir('identityproof'),
353 353
 				$this->getServer()->getCrypto()
@@ -358,15 +358,15 @@  discard block
 block discarded – undo
358 358
 		/**
359 359
 		 * App Framework APIs
360 360
 		 */
361
-		$this->registerService('API', function($c){
361
+		$this->registerService('API', function($c) {
362 362
 			$c->query('OCP\\ILogger')->debug(
363
-				'Accessing the API class is deprecated! Use the appropriate ' .
363
+				'Accessing the API class is deprecated! Use the appropriate '.
364 364
 				'services instead!'
365 365
 			);
366 366
 			return new API($c['AppName']);
367 367
 		});
368 368
 
369
-		$this->registerService('Protocol', function($c){
369
+		$this->registerService('Protocol', function($c) {
370 370
 			/** @var \OC\Server $server */
371 371
 			$server = $c->query('ServerContainer');
372 372
 			$protocol = $server->getRequest()->getHttpProtocol();
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
 			);
433 433
 		});
434 434
 
435
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
435
+		$this->registerService('TwoFactorMiddleware', function(SimpleContainer $c) use ($app) {
436 436
 			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
437 437
 			$userSession = $app->getServer()->getUserSession();
438 438
 			$session = $app->getServer()->getSession();
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
443 443
 		});
444 444
 
445
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
445
+		$this->registerService('OCSMiddleware', function(SimpleContainer $c) {
446 446
 			return new OCSMiddleware(
447 447
 				$c['Request']
448 448
 			);
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
 			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
457 457
 			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
458 458
 
459
-			foreach($middleWares as $middleWare) {
459
+			foreach ($middleWares as $middleWare) {
460 460
 				$dispatcher->registerMiddleware($c[$middleWare]);
461 461
 			}
462 462
 
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
 	 * @return mixed
529 529
 	 */
530 530
 	function log($message, $level) {
531
-		switch($level){
531
+		switch ($level) {
532 532
 			case 'debug':
533 533
 				$level = \OCP\Util::DEBUG;
534 534
 				break;
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   +1022 added lines, -1022 removed lines patch added patch discarded remove patch
@@ -48,1026 +48,1026 @@
 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
-		while($row = $result->fetch()) {
176
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
177
-			$uri = $row['uri'] . '_shared_by_' . $name;
178
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
179
-			if (!isset($addressBooks[$row['id']])) {
180
-				$addressBooks[$row['id']] = [
181
-					'id'  => $row['id'],
182
-					'uri' => $uri,
183
-					'principaluri' => $principalUriOriginal,
184
-					'{DAV:}displayname' => $displayName,
185
-					'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
186
-					'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
187
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
188
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
189
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
190
-				];
191
-			}
192
-		}
193
-		$result->closeCursor();
194
-
195
-		return array_values($addressBooks);
196
-	}
197
-
198
-	public function getUsersOwnAddressBooks($principalUri) {
199
-		$principalUriOriginal = $principalUri;
200
-		$principalUri = $this->convertPrincipal($principalUri, true);
201
-		$query = $this->db->getQueryBuilder();
202
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
203
-			  ->from('addressbooks')
204
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
205
-
206
-		$addressBooks = [];
207
-
208
-		$result = $query->execute();
209
-		while($row = $result->fetch()) {
210
-			$addressBooks[$row['id']] = [
211
-				'id'  => $row['id'],
212
-				'uri' => $row['uri'],
213
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
214
-				'{DAV:}displayname' => $row['displayname'],
215
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
216
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
217
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
218
-			];
219
-		}
220
-		$result->closeCursor();
221
-
222
-		return array_values($addressBooks);
223
-	}
224
-
225
-	private function getUserDisplayName($uid) {
226
-		if (!isset($this->userDisplayNames[$uid])) {
227
-			$user = $this->userManager->get($uid);
228
-
229
-			if ($user instanceof IUser) {
230
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
231
-			} else {
232
-				$this->userDisplayNames[$uid] = $uid;
233
-			}
234
-		}
235
-
236
-		return $this->userDisplayNames[$uid];
237
-	}
238
-
239
-	/**
240
-	 * @param int $addressBookId
241
-	 */
242
-	public function getAddressBookById($addressBookId) {
243
-		$query = $this->db->getQueryBuilder();
244
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
245
-			->from('addressbooks')
246
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
247
-			->execute();
248
-
249
-		$row = $result->fetch();
250
-		$result->closeCursor();
251
-		if ($row === false) {
252
-			return null;
253
-		}
254
-
255
-		return [
256
-			'id'  => $row['id'],
257
-			'uri' => $row['uri'],
258
-			'principaluri' => $row['principaluri'],
259
-			'{DAV:}displayname' => $row['displayname'],
260
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
261
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
262
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
263
-		];
264
-	}
265
-
266
-	/**
267
-	 * @param $addressBookUri
268
-	 * @return array|null
269
-	 */
270
-	public function getAddressBooksByUri($principal, $addressBookUri) {
271
-		$query = $this->db->getQueryBuilder();
272
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
273
-			->from('addressbooks')
274
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
275
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
276
-			->setMaxResults(1)
277
-			->execute();
278
-
279
-		$row = $result->fetch();
280
-		$result->closeCursor();
281
-		if ($row === false) {
282
-			return null;
283
-		}
284
-
285
-		return [
286
-				'id'  => $row['id'],
287
-				'uri' => $row['uri'],
288
-				'principaluri' => $row['principaluri'],
289
-				'{DAV:}displayname' => $row['displayname'],
290
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
291
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
292
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
293
-			];
294
-	}
295
-
296
-	/**
297
-	 * Updates properties for an address book.
298
-	 *
299
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
300
-	 * To do the actual updates, you must tell this object which properties
301
-	 * you're going to process with the handle() method.
302
-	 *
303
-	 * Calling the handle method is like telling the PropPatch object "I
304
-	 * promise I can handle updating this property".
305
-	 *
306
-	 * Read the PropPatch documentation for more info and examples.
307
-	 *
308
-	 * @param string $addressBookId
309
-	 * @param \Sabre\DAV\PropPatch $propPatch
310
-	 * @return void
311
-	 */
312
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
313
-		$supportedProperties = [
314
-			'{DAV:}displayname',
315
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
316
-		];
317
-
318
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
319
-
320
-			$updates = [];
321
-			foreach($mutations as $property=>$newValue) {
322
-
323
-				switch($property) {
324
-					case '{DAV:}displayname' :
325
-						$updates['displayname'] = $newValue;
326
-						break;
327
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
328
-						$updates['description'] = $newValue;
329
-						break;
330
-				}
331
-			}
332
-			$query = $this->db->getQueryBuilder();
333
-			$query->update('addressbooks');
334
-
335
-			foreach($updates as $key=>$value) {
336
-				$query->set($key, $query->createNamedParameter($value));
337
-			}
338
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
339
-			->execute();
340
-
341
-			$this->addChange($addressBookId, "", 2);
342
-
343
-			return true;
344
-
345
-		});
346
-	}
347
-
348
-	/**
349
-	 * Creates a new address book
350
-	 *
351
-	 * @param string $principalUri
352
-	 * @param string $url Just the 'basename' of the url.
353
-	 * @param array $properties
354
-	 * @return int
355
-	 * @throws BadRequest
356
-	 */
357
-	function createAddressBook($principalUri, $url, array $properties) {
358
-		$values = [
359
-			'displayname' => null,
360
-			'description' => null,
361
-			'principaluri' => $principalUri,
362
-			'uri' => $url,
363
-			'synctoken' => 1
364
-		];
365
-
366
-		foreach($properties as $property=>$newValue) {
367
-
368
-			switch($property) {
369
-				case '{DAV:}displayname' :
370
-					$values['displayname'] = $newValue;
371
-					break;
372
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
373
-					$values['description'] = $newValue;
374
-					break;
375
-				default :
376
-					throw new BadRequest('Unknown property: ' . $property);
377
-			}
378
-
379
-		}
380
-
381
-		// Fallback to make sure the displayname is set. Some clients may refuse
382
-		// to work with addressbooks not having a displayname.
383
-		if(is_null($values['displayname'])) {
384
-			$values['displayname'] = $url;
385
-		}
386
-
387
-		$query = $this->db->getQueryBuilder();
388
-		$query->insert('addressbooks')
389
-			->values([
390
-				'uri' => $query->createParameter('uri'),
391
-				'displayname' => $query->createParameter('displayname'),
392
-				'description' => $query->createParameter('description'),
393
-				'principaluri' => $query->createParameter('principaluri'),
394
-				'synctoken' => $query->createParameter('synctoken'),
395
-			])
396
-			->setParameters($values)
397
-			->execute();
398
-
399
-		return $query->getLastInsertId();
400
-	}
401
-
402
-	/**
403
-	 * Deletes an entire addressbook and all its contents
404
-	 *
405
-	 * @param mixed $addressBookId
406
-	 * @return void
407
-	 */
408
-	function deleteAddressBook($addressBookId) {
409
-		$query = $this->db->getQueryBuilder();
410
-		$query->delete('cards')
411
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
412
-			->setParameter('addressbookid', $addressBookId)
413
-			->execute();
414
-
415
-		$query->delete('addressbookchanges')
416
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
417
-			->setParameter('addressbookid', $addressBookId)
418
-			->execute();
419
-
420
-		$query->delete('addressbooks')
421
-			->where($query->expr()->eq('id', $query->createParameter('id')))
422
-			->setParameter('id', $addressBookId)
423
-			->execute();
424
-
425
-		$this->sharingBackend->deleteAllShares($addressBookId);
426
-
427
-		$query->delete($this->dbCardsPropertiesTable)
428
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
429
-			->execute();
430
-
431
-	}
432
-
433
-	/**
434
-	 * Returns all cards for a specific addressbook id.
435
-	 *
436
-	 * This method should return the following properties for each card:
437
-	 *   * carddata - raw vcard data
438
-	 *   * uri - Some unique url
439
-	 *   * lastmodified - A unix timestamp
440
-	 *
441
-	 * It's recommended to also return the following properties:
442
-	 *   * etag - A unique etag. This must change every time the card changes.
443
-	 *   * size - The size of the card in bytes.
444
-	 *
445
-	 * If these last two properties are provided, less time will be spent
446
-	 * calculating them. If they are specified, you can also ommit carddata.
447
-	 * This may speed up certain requests, especially with large cards.
448
-	 *
449
-	 * @param mixed $addressBookId
450
-	 * @return array
451
-	 */
452
-	function getCards($addressBookId) {
453
-		$query = $this->db->getQueryBuilder();
454
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
455
-			->from('cards')
456
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
457
-
458
-		$cards = [];
459
-
460
-		$result = $query->execute();
461
-		while($row = $result->fetch()) {
462
-			$row['etag'] = '"' . $row['etag'] . '"';
463
-			$row['carddata'] = $this->readBlob($row['carddata']);
464
-			$cards[] = $row;
465
-		}
466
-		$result->closeCursor();
467
-
468
-		return $cards;
469
-	}
470
-
471
-	/**
472
-	 * Returns a specific card.
473
-	 *
474
-	 * The same set of properties must be returned as with getCards. The only
475
-	 * exception is that 'carddata' is absolutely required.
476
-	 *
477
-	 * If the card does not exist, you must return false.
478
-	 *
479
-	 * @param mixed $addressBookId
480
-	 * @param string $cardUri
481
-	 * @return array
482
-	 */
483
-	function getCard($addressBookId, $cardUri) {
484
-		$query = $this->db->getQueryBuilder();
485
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
486
-			->from('cards')
487
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
488
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
489
-			->setMaxResults(1);
490
-
491
-		$result = $query->execute();
492
-		$row = $result->fetch();
493
-		if (!$row) {
494
-			return false;
495
-		}
496
-		$row['etag'] = '"' . $row['etag'] . '"';
497
-		$row['carddata'] = $this->readBlob($row['carddata']);
498
-
499
-		return $row;
500
-	}
501
-
502
-	/**
503
-	 * Returns a list of cards.
504
-	 *
505
-	 * This method should work identical to getCard, but instead return all the
506
-	 * cards in the list as an array.
507
-	 *
508
-	 * If the backend supports this, it may allow for some speed-ups.
509
-	 *
510
-	 * @param mixed $addressBookId
511
-	 * @param string[] $uris
512
-	 * @return array
513
-	 */
514
-	function getMultipleCards($addressBookId, array $uris) {
515
-		if (empty($uris)) {
516
-			return [];
517
-		}
518
-
519
-		$chunks = array_chunk($uris, 100);
520
-		$cards = [];
521
-
522
-		$query = $this->db->getQueryBuilder();
523
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
524
-			->from('cards')
525
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
526
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
527
-
528
-		foreach ($chunks as $uris) {
529
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
530
-			$result = $query->execute();
531
-
532
-			while ($row = $result->fetch()) {
533
-				$row['etag'] = '"' . $row['etag'] . '"';
534
-				$row['carddata'] = $this->readBlob($row['carddata']);
535
-				$cards[] = $row;
536
-			}
537
-			$result->closeCursor();
538
-		}
539
-		return $cards;
540
-	}
541
-
542
-	/**
543
-	 * Creates a new card.
544
-	 *
545
-	 * The addressbook id will be passed as the first argument. This is the
546
-	 * same id as it is returned from the getAddressBooksForUser method.
547
-	 *
548
-	 * The cardUri is a base uri, and doesn't include the full path. The
549
-	 * cardData argument is the vcard body, and is passed as a string.
550
-	 *
551
-	 * It is possible to return an ETag from this method. This ETag is for the
552
-	 * newly created resource, and must be enclosed with double quotes (that
553
-	 * is, the string itself must contain the double quotes).
554
-	 *
555
-	 * You should only return the ETag if you store the carddata as-is. If a
556
-	 * subsequent GET request on the same card does not have the same body,
557
-	 * byte-by-byte and you did return an ETag here, clients tend to get
558
-	 * confused.
559
-	 *
560
-	 * If you don't return an ETag, you can just return null.
561
-	 *
562
-	 * @param mixed $addressBookId
563
-	 * @param string $cardUri
564
-	 * @param string $cardData
565
-	 * @return string
566
-	 */
567
-	function createCard($addressBookId, $cardUri, $cardData) {
568
-		$etag = md5($cardData);
569
-
570
-		$query = $this->db->getQueryBuilder();
571
-		$query->insert('cards')
572
-			->values([
573
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
574
-				'uri' => $query->createNamedParameter($cardUri),
575
-				'lastmodified' => $query->createNamedParameter(time()),
576
-				'addressbookid' => $query->createNamedParameter($addressBookId),
577
-				'size' => $query->createNamedParameter(strlen($cardData)),
578
-				'etag' => $query->createNamedParameter($etag),
579
-			])
580
-			->execute();
581
-
582
-		$this->addChange($addressBookId, $cardUri, 1);
583
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
584
-
585
-		if (!is_null($this->dispatcher)) {
586
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
587
-				new GenericEvent(null, [
588
-					'addressBookId' => $addressBookId,
589
-					'cardUri' => $cardUri,
590
-					'cardData' => $cardData]));
591
-		}
592
-
593
-		return '"' . $etag . '"';
594
-	}
595
-
596
-	/**
597
-	 * Updates a card.
598
-	 *
599
-	 * The addressbook id will be passed as the first argument. This is the
600
-	 * same id as it is returned from the getAddressBooksForUser method.
601
-	 *
602
-	 * The cardUri is a base uri, and doesn't include the full path. The
603
-	 * cardData argument is the vcard body, and is passed as a string.
604
-	 *
605
-	 * It is possible to return an ETag from this method. This ETag should
606
-	 * match that of the updated resource, and must be enclosed with double
607
-	 * quotes (that is: the string itself must contain the actual quotes).
608
-	 *
609
-	 * You should only return the ETag if you store the carddata as-is. If a
610
-	 * subsequent GET request on the same card does not have the same body,
611
-	 * byte-by-byte and you did return an ETag here, clients tend to get
612
-	 * confused.
613
-	 *
614
-	 * If you don't return an ETag, you can just return null.
615
-	 *
616
-	 * @param mixed $addressBookId
617
-	 * @param string $cardUri
618
-	 * @param string $cardData
619
-	 * @return string
620
-	 */
621
-	function updateCard($addressBookId, $cardUri, $cardData) {
622
-
623
-		$etag = md5($cardData);
624
-		$query = $this->db->getQueryBuilder();
625
-		$query->update('cards')
626
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
627
-			->set('lastmodified', $query->createNamedParameter(time()))
628
-			->set('size', $query->createNamedParameter(strlen($cardData)))
629
-			->set('etag', $query->createNamedParameter($etag))
630
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
631
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
632
-			->execute();
633
-
634
-		$this->addChange($addressBookId, $cardUri, 2);
635
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
636
-
637
-		if (!is_null($this->dispatcher)) {
638
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
639
-				new GenericEvent(null, [
640
-					'addressBookId' => $addressBookId,
641
-					'cardUri' => $cardUri,
642
-					'cardData' => $cardData]));
643
-		}
644
-
645
-		return '"' . $etag . '"';
646
-	}
647
-
648
-	/**
649
-	 * Deletes a card
650
-	 *
651
-	 * @param mixed $addressBookId
652
-	 * @param string $cardUri
653
-	 * @return bool
654
-	 */
655
-	function deleteCard($addressBookId, $cardUri) {
656
-		try {
657
-			$cardId = $this->getCardId($addressBookId, $cardUri);
658
-		} catch (\InvalidArgumentException $e) {
659
-			$cardId = null;
660
-		}
661
-		$query = $this->db->getQueryBuilder();
662
-		$ret = $query->delete('cards')
663
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
664
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
665
-			->execute();
666
-
667
-		$this->addChange($addressBookId, $cardUri, 3);
668
-
669
-		if (!is_null($this->dispatcher)) {
670
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
671
-				new GenericEvent(null, [
672
-					'addressBookId' => $addressBookId,
673
-					'cardUri' => $cardUri]));
674
-		}
675
-
676
-		if ($ret === 1) {
677
-			if ($cardId !== null) {
678
-				$this->purgeProperties($addressBookId, $cardId);
679
-			}
680
-			return true;
681
-		}
682
-
683
-		return false;
684
-	}
685
-
686
-	/**
687
-	 * The getChanges method returns all the changes that have happened, since
688
-	 * the specified syncToken in the specified address book.
689
-	 *
690
-	 * This function should return an array, such as the following:
691
-	 *
692
-	 * [
693
-	 *   'syncToken' => 'The current synctoken',
694
-	 *   'added'   => [
695
-	 *      'new.txt',
696
-	 *   ],
697
-	 *   'modified'   => [
698
-	 *      'modified.txt',
699
-	 *   ],
700
-	 *   'deleted' => [
701
-	 *      'foo.php.bak',
702
-	 *      'old.txt'
703
-	 *   ]
704
-	 * ];
705
-	 *
706
-	 * The returned syncToken property should reflect the *current* syncToken
707
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
708
-	 * property. This is needed here too, to ensure the operation is atomic.
709
-	 *
710
-	 * If the $syncToken argument is specified as null, this is an initial
711
-	 * sync, and all members should be reported.
712
-	 *
713
-	 * The modified property is an array of nodenames that have changed since
714
-	 * the last token.
715
-	 *
716
-	 * The deleted property is an array with nodenames, that have been deleted
717
-	 * from collection.
718
-	 *
719
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
720
-	 * 1, you only have to report changes that happened only directly in
721
-	 * immediate descendants. If it's 2, it should also include changes from
722
-	 * the nodes below the child collections. (grandchildren)
723
-	 *
724
-	 * The $limit argument allows a client to specify how many results should
725
-	 * be returned at most. If the limit is not specified, it should be treated
726
-	 * as infinite.
727
-	 *
728
-	 * If the limit (infinite or not) is higher than you're willing to return,
729
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
730
-	 *
731
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
732
-	 * return null.
733
-	 *
734
-	 * The limit is 'suggestive'. You are free to ignore it.
735
-	 *
736
-	 * @param string $addressBookId
737
-	 * @param string $syncToken
738
-	 * @param int $syncLevel
739
-	 * @param int $limit
740
-	 * @return array
741
-	 */
742
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
743
-		// Current synctoken
744
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
745
-		$stmt->execute([ $addressBookId ]);
746
-		$currentToken = $stmt->fetchColumn(0);
747
-
748
-		if (is_null($currentToken)) return null;
749
-
750
-		$result = [
751
-			'syncToken' => $currentToken,
752
-			'added'     => [],
753
-			'modified'  => [],
754
-			'deleted'   => [],
755
-		];
756
-
757
-		if ($syncToken) {
758
-
759
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
760
-			if ($limit>0) {
761
-				$query .= " `LIMIT` " . (int)$limit;
762
-			}
763
-
764
-			// Fetching all changes
765
-			$stmt = $this->db->prepare($query);
766
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
767
-
768
-			$changes = [];
769
-
770
-			// This loop ensures that any duplicates are overwritten, only the
771
-			// last change on a node is relevant.
772
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
773
-
774
-				$changes[$row['uri']] = $row['operation'];
775
-
776
-			}
777
-
778
-			foreach($changes as $uri => $operation) {
779
-
780
-				switch($operation) {
781
-					case 1:
782
-						$result['added'][] = $uri;
783
-						break;
784
-					case 2:
785
-						$result['modified'][] = $uri;
786
-						break;
787
-					case 3:
788
-						$result['deleted'][] = $uri;
789
-						break;
790
-				}
791
-
792
-			}
793
-		} else {
794
-			// No synctoken supplied, this is the initial sync.
795
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
796
-			$stmt = $this->db->prepare($query);
797
-			$stmt->execute([$addressBookId]);
798
-
799
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
800
-		}
801
-		return $result;
802
-	}
803
-
804
-	/**
805
-	 * Adds a change record to the addressbookchanges table.
806
-	 *
807
-	 * @param mixed $addressBookId
808
-	 * @param string $objectUri
809
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
810
-	 * @return void
811
-	 */
812
-	protected function addChange($addressBookId, $objectUri, $operation) {
813
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
814
-		$stmt = $this->db->prepare($sql);
815
-		$stmt->execute([
816
-			$objectUri,
817
-			$addressBookId,
818
-			$operation,
819
-			$addressBookId
820
-		]);
821
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
822
-		$stmt->execute([
823
-			$addressBookId
824
-		]);
825
-	}
826
-
827
-	private function readBlob($cardData) {
828
-		if (is_resource($cardData)) {
829
-			return stream_get_contents($cardData);
830
-		}
831
-
832
-		return $cardData;
833
-	}
834
-
835
-	/**
836
-	 * @param IShareable $shareable
837
-	 * @param string[] $add
838
-	 * @param string[] $remove
839
-	 */
840
-	public function updateShares(IShareable $shareable, $add, $remove) {
841
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
842
-	}
843
-
844
-	/**
845
-	 * search contact
846
-	 *
847
-	 * @param int $addressBookId
848
-	 * @param string $pattern which should match within the $searchProperties
849
-	 * @param array $searchProperties defines the properties within the query pattern should match
850
-	 * @return array an array of contacts which are arrays of key-value-pairs
851
-	 */
852
-	public function search($addressBookId, $pattern, $searchProperties) {
853
-		$query = $this->db->getQueryBuilder();
854
-		$query2 = $this->db->getQueryBuilder();
855
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
856
-		foreach ($searchProperties as $property) {
857
-			$query2->orWhere(
858
-				$query2->expr()->andX(
859
-					$query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
860
-					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
861
-				)
862
-			);
863
-		}
864
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
865
-
866
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
867
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
868
-
869
-		$result = $query->execute();
870
-		$cards = $result->fetchAll();
871
-
872
-		$result->closeCursor();
873
-
874
-		return array_map(function($array) {
875
-			$array['carddata'] = $this->readBlob($array['carddata']);
876
-			return $array;
877
-		}, $cards);
878
-	}
879
-
880
-	/**
881
-	 * @param int $bookId
882
-	 * @param string $name
883
-	 * @return array
884
-	 */
885
-	public function collectCardProperties($bookId, $name) {
886
-		$query = $this->db->getQueryBuilder();
887
-		$result = $query->selectDistinct('value')
888
-			->from($this->dbCardsPropertiesTable)
889
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
890
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
891
-			->execute();
892
-
893
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
894
-		$result->closeCursor();
895
-
896
-		return $all;
897
-	}
898
-
899
-	/**
900
-	 * get URI from a given contact
901
-	 *
902
-	 * @param int $id
903
-	 * @return string
904
-	 */
905
-	public function getCardUri($id) {
906
-		$query = $this->db->getQueryBuilder();
907
-		$query->select('uri')->from($this->dbCardsTable)
908
-				->where($query->expr()->eq('id', $query->createParameter('id')))
909
-				->setParameter('id', $id);
910
-
911
-		$result = $query->execute();
912
-		$uri = $result->fetch();
913
-		$result->closeCursor();
914
-
915
-		if (!isset($uri['uri'])) {
916
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
917
-		}
918
-
919
-		return $uri['uri'];
920
-	}
921
-
922
-	/**
923
-	 * return contact with the given URI
924
-	 *
925
-	 * @param int $addressBookId
926
-	 * @param string $uri
927
-	 * @returns array
928
-	 */
929
-	public function getContact($addressBookId, $uri) {
930
-		$result = [];
931
-		$query = $this->db->getQueryBuilder();
932
-		$query->select('*')->from($this->dbCardsTable)
933
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
934
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
935
-		$queryResult = $query->execute();
936
-		$contact = $queryResult->fetch();
937
-		$queryResult->closeCursor();
938
-
939
-		if (is_array($contact)) {
940
-			$result = $contact;
941
-		}
942
-
943
-		return $result;
944
-	}
945
-
946
-	/**
947
-	 * Returns the list of people whom this address book is shared with.
948
-	 *
949
-	 * Every element in this array should have the following properties:
950
-	 *   * href - Often a mailto: address
951
-	 *   * commonName - Optional, for example a first + last name
952
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
953
-	 *   * readOnly - boolean
954
-	 *   * summary - Optional, a description for the share
955
-	 *
956
-	 * @return array
957
-	 */
958
-	public function getShares($addressBookId) {
959
-		return $this->sharingBackend->getShares($addressBookId);
960
-	}
961
-
962
-	/**
963
-	 * update properties table
964
-	 *
965
-	 * @param int $addressBookId
966
-	 * @param string $cardUri
967
-	 * @param string $vCardSerialized
968
-	 */
969
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
970
-		$cardId = $this->getCardId($addressBookId, $cardUri);
971
-		$vCard = $this->readCard($vCardSerialized);
972
-
973
-		$this->purgeProperties($addressBookId, $cardId);
974
-
975
-		$query = $this->db->getQueryBuilder();
976
-		$query->insert($this->dbCardsPropertiesTable)
977
-			->values(
978
-				[
979
-					'addressbookid' => $query->createNamedParameter($addressBookId),
980
-					'cardid' => $query->createNamedParameter($cardId),
981
-					'name' => $query->createParameter('name'),
982
-					'value' => $query->createParameter('value'),
983
-					'preferred' => $query->createParameter('preferred')
984
-				]
985
-			);
986
-
987
-		foreach ($vCard->children() as $property) {
988
-			if(!in_array($property->name, self::$indexProperties)) {
989
-				continue;
990
-			}
991
-			$preferred = 0;
992
-			foreach($property->parameters as $parameter) {
993
-				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
994
-					$preferred = 1;
995
-					break;
996
-				}
997
-			}
998
-			$query->setParameter('name', $property->name);
999
-			$query->setParameter('value', substr($property->getValue(), 0, 254));
1000
-			$query->setParameter('preferred', $preferred);
1001
-			$query->execute();
1002
-		}
1003
-	}
1004
-
1005
-	/**
1006
-	 * read vCard data into a vCard object
1007
-	 *
1008
-	 * @param string $cardData
1009
-	 * @return VCard
1010
-	 */
1011
-	protected function readCard($cardData) {
1012
-		return  Reader::read($cardData);
1013
-	}
1014
-
1015
-	/**
1016
-	 * delete all properties from a given card
1017
-	 *
1018
-	 * @param int $addressBookId
1019
-	 * @param int $cardId
1020
-	 */
1021
-	protected function purgeProperties($addressBookId, $cardId) {
1022
-		$query = $this->db->getQueryBuilder();
1023
-		$query->delete($this->dbCardsPropertiesTable)
1024
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1025
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1026
-		$query->execute();
1027
-	}
1028
-
1029
-	/**
1030
-	 * get ID from a given contact
1031
-	 *
1032
-	 * @param int $addressBookId
1033
-	 * @param string $uri
1034
-	 * @return int
1035
-	 */
1036
-	protected function getCardId($addressBookId, $uri) {
1037
-		$query = $this->db->getQueryBuilder();
1038
-		$query->select('id')->from($this->dbCardsTable)
1039
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1040
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1041
-
1042
-		$result = $query->execute();
1043
-		$cardIds = $result->fetch();
1044
-		$result->closeCursor();
1045
-
1046
-		if (!isset($cardIds['id'])) {
1047
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1048
-		}
1049
-
1050
-		return (int)$cardIds['id'];
1051
-	}
1052
-
1053
-	/**
1054
-	 * For shared address books the sharee is set in the ACL of the address book
1055
-	 * @param $addressBookId
1056
-	 * @param $acl
1057
-	 * @return array
1058
-	 */
1059
-	public function applyShareAcl($addressBookId, $acl) {
1060
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1061
-	}
1062
-
1063
-	private function convertPrincipal($principalUri, $toV2) {
1064
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1065
-			list(, $name) = URLUtil::splitPath($principalUri);
1066
-			if ($toV2 === true) {
1067
-				return "principals/users/$name";
1068
-			}
1069
-			return "principals/$name";
1070
-		}
1071
-		return $principalUri;
1072
-	}
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
+        while($row = $result->fetch()) {
176
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
177
+            $uri = $row['uri'] . '_shared_by_' . $name;
178
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
179
+            if (!isset($addressBooks[$row['id']])) {
180
+                $addressBooks[$row['id']] = [
181
+                    'id'  => $row['id'],
182
+                    'uri' => $uri,
183
+                    'principaluri' => $principalUriOriginal,
184
+                    '{DAV:}displayname' => $displayName,
185
+                    '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
186
+                    '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
187
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
188
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
189
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
190
+                ];
191
+            }
192
+        }
193
+        $result->closeCursor();
194
+
195
+        return array_values($addressBooks);
196
+    }
197
+
198
+    public function getUsersOwnAddressBooks($principalUri) {
199
+        $principalUriOriginal = $principalUri;
200
+        $principalUri = $this->convertPrincipal($principalUri, true);
201
+        $query = $this->db->getQueryBuilder();
202
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
203
+                ->from('addressbooks')
204
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
205
+
206
+        $addressBooks = [];
207
+
208
+        $result = $query->execute();
209
+        while($row = $result->fetch()) {
210
+            $addressBooks[$row['id']] = [
211
+                'id'  => $row['id'],
212
+                'uri' => $row['uri'],
213
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
214
+                '{DAV:}displayname' => $row['displayname'],
215
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
216
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
217
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
218
+            ];
219
+        }
220
+        $result->closeCursor();
221
+
222
+        return array_values($addressBooks);
223
+    }
224
+
225
+    private function getUserDisplayName($uid) {
226
+        if (!isset($this->userDisplayNames[$uid])) {
227
+            $user = $this->userManager->get($uid);
228
+
229
+            if ($user instanceof IUser) {
230
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
231
+            } else {
232
+                $this->userDisplayNames[$uid] = $uid;
233
+            }
234
+        }
235
+
236
+        return $this->userDisplayNames[$uid];
237
+    }
238
+
239
+    /**
240
+     * @param int $addressBookId
241
+     */
242
+    public function getAddressBookById($addressBookId) {
243
+        $query = $this->db->getQueryBuilder();
244
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
245
+            ->from('addressbooks')
246
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
247
+            ->execute();
248
+
249
+        $row = $result->fetch();
250
+        $result->closeCursor();
251
+        if ($row === false) {
252
+            return null;
253
+        }
254
+
255
+        return [
256
+            'id'  => $row['id'],
257
+            'uri' => $row['uri'],
258
+            'principaluri' => $row['principaluri'],
259
+            '{DAV:}displayname' => $row['displayname'],
260
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
261
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
262
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
263
+        ];
264
+    }
265
+
266
+    /**
267
+     * @param $addressBookUri
268
+     * @return array|null
269
+     */
270
+    public function getAddressBooksByUri($principal, $addressBookUri) {
271
+        $query = $this->db->getQueryBuilder();
272
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
273
+            ->from('addressbooks')
274
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
275
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
276
+            ->setMaxResults(1)
277
+            ->execute();
278
+
279
+        $row = $result->fetch();
280
+        $result->closeCursor();
281
+        if ($row === false) {
282
+            return null;
283
+        }
284
+
285
+        return [
286
+                'id'  => $row['id'],
287
+                'uri' => $row['uri'],
288
+                'principaluri' => $row['principaluri'],
289
+                '{DAV:}displayname' => $row['displayname'],
290
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
291
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
292
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
293
+            ];
294
+    }
295
+
296
+    /**
297
+     * Updates properties for an address book.
298
+     *
299
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
300
+     * To do the actual updates, you must tell this object which properties
301
+     * you're going to process with the handle() method.
302
+     *
303
+     * Calling the handle method is like telling the PropPatch object "I
304
+     * promise I can handle updating this property".
305
+     *
306
+     * Read the PropPatch documentation for more info and examples.
307
+     *
308
+     * @param string $addressBookId
309
+     * @param \Sabre\DAV\PropPatch $propPatch
310
+     * @return void
311
+     */
312
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
313
+        $supportedProperties = [
314
+            '{DAV:}displayname',
315
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
316
+        ];
317
+
318
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
319
+
320
+            $updates = [];
321
+            foreach($mutations as $property=>$newValue) {
322
+
323
+                switch($property) {
324
+                    case '{DAV:}displayname' :
325
+                        $updates['displayname'] = $newValue;
326
+                        break;
327
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
328
+                        $updates['description'] = $newValue;
329
+                        break;
330
+                }
331
+            }
332
+            $query = $this->db->getQueryBuilder();
333
+            $query->update('addressbooks');
334
+
335
+            foreach($updates as $key=>$value) {
336
+                $query->set($key, $query->createNamedParameter($value));
337
+            }
338
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
339
+            ->execute();
340
+
341
+            $this->addChange($addressBookId, "", 2);
342
+
343
+            return true;
344
+
345
+        });
346
+    }
347
+
348
+    /**
349
+     * Creates a new address book
350
+     *
351
+     * @param string $principalUri
352
+     * @param string $url Just the 'basename' of the url.
353
+     * @param array $properties
354
+     * @return int
355
+     * @throws BadRequest
356
+     */
357
+    function createAddressBook($principalUri, $url, array $properties) {
358
+        $values = [
359
+            'displayname' => null,
360
+            'description' => null,
361
+            'principaluri' => $principalUri,
362
+            'uri' => $url,
363
+            'synctoken' => 1
364
+        ];
365
+
366
+        foreach($properties as $property=>$newValue) {
367
+
368
+            switch($property) {
369
+                case '{DAV:}displayname' :
370
+                    $values['displayname'] = $newValue;
371
+                    break;
372
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
373
+                    $values['description'] = $newValue;
374
+                    break;
375
+                default :
376
+                    throw new BadRequest('Unknown property: ' . $property);
377
+            }
378
+
379
+        }
380
+
381
+        // Fallback to make sure the displayname is set. Some clients may refuse
382
+        // to work with addressbooks not having a displayname.
383
+        if(is_null($values['displayname'])) {
384
+            $values['displayname'] = $url;
385
+        }
386
+
387
+        $query = $this->db->getQueryBuilder();
388
+        $query->insert('addressbooks')
389
+            ->values([
390
+                'uri' => $query->createParameter('uri'),
391
+                'displayname' => $query->createParameter('displayname'),
392
+                'description' => $query->createParameter('description'),
393
+                'principaluri' => $query->createParameter('principaluri'),
394
+                'synctoken' => $query->createParameter('synctoken'),
395
+            ])
396
+            ->setParameters($values)
397
+            ->execute();
398
+
399
+        return $query->getLastInsertId();
400
+    }
401
+
402
+    /**
403
+     * Deletes an entire addressbook and all its contents
404
+     *
405
+     * @param mixed $addressBookId
406
+     * @return void
407
+     */
408
+    function deleteAddressBook($addressBookId) {
409
+        $query = $this->db->getQueryBuilder();
410
+        $query->delete('cards')
411
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
412
+            ->setParameter('addressbookid', $addressBookId)
413
+            ->execute();
414
+
415
+        $query->delete('addressbookchanges')
416
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
417
+            ->setParameter('addressbookid', $addressBookId)
418
+            ->execute();
419
+
420
+        $query->delete('addressbooks')
421
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
422
+            ->setParameter('id', $addressBookId)
423
+            ->execute();
424
+
425
+        $this->sharingBackend->deleteAllShares($addressBookId);
426
+
427
+        $query->delete($this->dbCardsPropertiesTable)
428
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
429
+            ->execute();
430
+
431
+    }
432
+
433
+    /**
434
+     * Returns all cards for a specific addressbook id.
435
+     *
436
+     * This method should return the following properties for each card:
437
+     *   * carddata - raw vcard data
438
+     *   * uri - Some unique url
439
+     *   * lastmodified - A unix timestamp
440
+     *
441
+     * It's recommended to also return the following properties:
442
+     *   * etag - A unique etag. This must change every time the card changes.
443
+     *   * size - The size of the card in bytes.
444
+     *
445
+     * If these last two properties are provided, less time will be spent
446
+     * calculating them. If they are specified, you can also ommit carddata.
447
+     * This may speed up certain requests, especially with large cards.
448
+     *
449
+     * @param mixed $addressBookId
450
+     * @return array
451
+     */
452
+    function getCards($addressBookId) {
453
+        $query = $this->db->getQueryBuilder();
454
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
455
+            ->from('cards')
456
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
457
+
458
+        $cards = [];
459
+
460
+        $result = $query->execute();
461
+        while($row = $result->fetch()) {
462
+            $row['etag'] = '"' . $row['etag'] . '"';
463
+            $row['carddata'] = $this->readBlob($row['carddata']);
464
+            $cards[] = $row;
465
+        }
466
+        $result->closeCursor();
467
+
468
+        return $cards;
469
+    }
470
+
471
+    /**
472
+     * Returns a specific card.
473
+     *
474
+     * The same set of properties must be returned as with getCards. The only
475
+     * exception is that 'carddata' is absolutely required.
476
+     *
477
+     * If the card does not exist, you must return false.
478
+     *
479
+     * @param mixed $addressBookId
480
+     * @param string $cardUri
481
+     * @return array
482
+     */
483
+    function getCard($addressBookId, $cardUri) {
484
+        $query = $this->db->getQueryBuilder();
485
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
486
+            ->from('cards')
487
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
488
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
489
+            ->setMaxResults(1);
490
+
491
+        $result = $query->execute();
492
+        $row = $result->fetch();
493
+        if (!$row) {
494
+            return false;
495
+        }
496
+        $row['etag'] = '"' . $row['etag'] . '"';
497
+        $row['carddata'] = $this->readBlob($row['carddata']);
498
+
499
+        return $row;
500
+    }
501
+
502
+    /**
503
+     * Returns a list of cards.
504
+     *
505
+     * This method should work identical to getCard, but instead return all the
506
+     * cards in the list as an array.
507
+     *
508
+     * If the backend supports this, it may allow for some speed-ups.
509
+     *
510
+     * @param mixed $addressBookId
511
+     * @param string[] $uris
512
+     * @return array
513
+     */
514
+    function getMultipleCards($addressBookId, array $uris) {
515
+        if (empty($uris)) {
516
+            return [];
517
+        }
518
+
519
+        $chunks = array_chunk($uris, 100);
520
+        $cards = [];
521
+
522
+        $query = $this->db->getQueryBuilder();
523
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
524
+            ->from('cards')
525
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
526
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
527
+
528
+        foreach ($chunks as $uris) {
529
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
530
+            $result = $query->execute();
531
+
532
+            while ($row = $result->fetch()) {
533
+                $row['etag'] = '"' . $row['etag'] . '"';
534
+                $row['carddata'] = $this->readBlob($row['carddata']);
535
+                $cards[] = $row;
536
+            }
537
+            $result->closeCursor();
538
+        }
539
+        return $cards;
540
+    }
541
+
542
+    /**
543
+     * Creates a new card.
544
+     *
545
+     * The addressbook id will be passed as the first argument. This is the
546
+     * same id as it is returned from the getAddressBooksForUser method.
547
+     *
548
+     * The cardUri is a base uri, and doesn't include the full path. The
549
+     * cardData argument is the vcard body, and is passed as a string.
550
+     *
551
+     * It is possible to return an ETag from this method. This ETag is for the
552
+     * newly created resource, and must be enclosed with double quotes (that
553
+     * is, the string itself must contain the double quotes).
554
+     *
555
+     * You should only return the ETag if you store the carddata as-is. If a
556
+     * subsequent GET request on the same card does not have the same body,
557
+     * byte-by-byte and you did return an ETag here, clients tend to get
558
+     * confused.
559
+     *
560
+     * If you don't return an ETag, you can just return null.
561
+     *
562
+     * @param mixed $addressBookId
563
+     * @param string $cardUri
564
+     * @param string $cardData
565
+     * @return string
566
+     */
567
+    function createCard($addressBookId, $cardUri, $cardData) {
568
+        $etag = md5($cardData);
569
+
570
+        $query = $this->db->getQueryBuilder();
571
+        $query->insert('cards')
572
+            ->values([
573
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
574
+                'uri' => $query->createNamedParameter($cardUri),
575
+                'lastmodified' => $query->createNamedParameter(time()),
576
+                'addressbookid' => $query->createNamedParameter($addressBookId),
577
+                'size' => $query->createNamedParameter(strlen($cardData)),
578
+                'etag' => $query->createNamedParameter($etag),
579
+            ])
580
+            ->execute();
581
+
582
+        $this->addChange($addressBookId, $cardUri, 1);
583
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
584
+
585
+        if (!is_null($this->dispatcher)) {
586
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
587
+                new GenericEvent(null, [
588
+                    'addressBookId' => $addressBookId,
589
+                    'cardUri' => $cardUri,
590
+                    'cardData' => $cardData]));
591
+        }
592
+
593
+        return '"' . $etag . '"';
594
+    }
595
+
596
+    /**
597
+     * Updates a card.
598
+     *
599
+     * The addressbook id will be passed as the first argument. This is the
600
+     * same id as it is returned from the getAddressBooksForUser method.
601
+     *
602
+     * The cardUri is a base uri, and doesn't include the full path. The
603
+     * cardData argument is the vcard body, and is passed as a string.
604
+     *
605
+     * It is possible to return an ETag from this method. This ETag should
606
+     * match that of the updated resource, and must be enclosed with double
607
+     * quotes (that is: the string itself must contain the actual quotes).
608
+     *
609
+     * You should only return the ETag if you store the carddata as-is. If a
610
+     * subsequent GET request on the same card does not have the same body,
611
+     * byte-by-byte and you did return an ETag here, clients tend to get
612
+     * confused.
613
+     *
614
+     * If you don't return an ETag, you can just return null.
615
+     *
616
+     * @param mixed $addressBookId
617
+     * @param string $cardUri
618
+     * @param string $cardData
619
+     * @return string
620
+     */
621
+    function updateCard($addressBookId, $cardUri, $cardData) {
622
+
623
+        $etag = md5($cardData);
624
+        $query = $this->db->getQueryBuilder();
625
+        $query->update('cards')
626
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
627
+            ->set('lastmodified', $query->createNamedParameter(time()))
628
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
629
+            ->set('etag', $query->createNamedParameter($etag))
630
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
631
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
632
+            ->execute();
633
+
634
+        $this->addChange($addressBookId, $cardUri, 2);
635
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
636
+
637
+        if (!is_null($this->dispatcher)) {
638
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
639
+                new GenericEvent(null, [
640
+                    'addressBookId' => $addressBookId,
641
+                    'cardUri' => $cardUri,
642
+                    'cardData' => $cardData]));
643
+        }
644
+
645
+        return '"' . $etag . '"';
646
+    }
647
+
648
+    /**
649
+     * Deletes a card
650
+     *
651
+     * @param mixed $addressBookId
652
+     * @param string $cardUri
653
+     * @return bool
654
+     */
655
+    function deleteCard($addressBookId, $cardUri) {
656
+        try {
657
+            $cardId = $this->getCardId($addressBookId, $cardUri);
658
+        } catch (\InvalidArgumentException $e) {
659
+            $cardId = null;
660
+        }
661
+        $query = $this->db->getQueryBuilder();
662
+        $ret = $query->delete('cards')
663
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
664
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
665
+            ->execute();
666
+
667
+        $this->addChange($addressBookId, $cardUri, 3);
668
+
669
+        if (!is_null($this->dispatcher)) {
670
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
671
+                new GenericEvent(null, [
672
+                    'addressBookId' => $addressBookId,
673
+                    'cardUri' => $cardUri]));
674
+        }
675
+
676
+        if ($ret === 1) {
677
+            if ($cardId !== null) {
678
+                $this->purgeProperties($addressBookId, $cardId);
679
+            }
680
+            return true;
681
+        }
682
+
683
+        return false;
684
+    }
685
+
686
+    /**
687
+     * The getChanges method returns all the changes that have happened, since
688
+     * the specified syncToken in the specified address book.
689
+     *
690
+     * This function should return an array, such as the following:
691
+     *
692
+     * [
693
+     *   'syncToken' => 'The current synctoken',
694
+     *   'added'   => [
695
+     *      'new.txt',
696
+     *   ],
697
+     *   'modified'   => [
698
+     *      'modified.txt',
699
+     *   ],
700
+     *   'deleted' => [
701
+     *      'foo.php.bak',
702
+     *      'old.txt'
703
+     *   ]
704
+     * ];
705
+     *
706
+     * The returned syncToken property should reflect the *current* syncToken
707
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
708
+     * property. This is needed here too, to ensure the operation is atomic.
709
+     *
710
+     * If the $syncToken argument is specified as null, this is an initial
711
+     * sync, and all members should be reported.
712
+     *
713
+     * The modified property is an array of nodenames that have changed since
714
+     * the last token.
715
+     *
716
+     * The deleted property is an array with nodenames, that have been deleted
717
+     * from collection.
718
+     *
719
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
720
+     * 1, you only have to report changes that happened only directly in
721
+     * immediate descendants. If it's 2, it should also include changes from
722
+     * the nodes below the child collections. (grandchildren)
723
+     *
724
+     * The $limit argument allows a client to specify how many results should
725
+     * be returned at most. If the limit is not specified, it should be treated
726
+     * as infinite.
727
+     *
728
+     * If the limit (infinite or not) is higher than you're willing to return,
729
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
730
+     *
731
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
732
+     * return null.
733
+     *
734
+     * The limit is 'suggestive'. You are free to ignore it.
735
+     *
736
+     * @param string $addressBookId
737
+     * @param string $syncToken
738
+     * @param int $syncLevel
739
+     * @param int $limit
740
+     * @return array
741
+     */
742
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
743
+        // Current synctoken
744
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
745
+        $stmt->execute([ $addressBookId ]);
746
+        $currentToken = $stmt->fetchColumn(0);
747
+
748
+        if (is_null($currentToken)) return null;
749
+
750
+        $result = [
751
+            'syncToken' => $currentToken,
752
+            'added'     => [],
753
+            'modified'  => [],
754
+            'deleted'   => [],
755
+        ];
756
+
757
+        if ($syncToken) {
758
+
759
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
760
+            if ($limit>0) {
761
+                $query .= " `LIMIT` " . (int)$limit;
762
+            }
763
+
764
+            // Fetching all changes
765
+            $stmt = $this->db->prepare($query);
766
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
767
+
768
+            $changes = [];
769
+
770
+            // This loop ensures that any duplicates are overwritten, only the
771
+            // last change on a node is relevant.
772
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
773
+
774
+                $changes[$row['uri']] = $row['operation'];
775
+
776
+            }
777
+
778
+            foreach($changes as $uri => $operation) {
779
+
780
+                switch($operation) {
781
+                    case 1:
782
+                        $result['added'][] = $uri;
783
+                        break;
784
+                    case 2:
785
+                        $result['modified'][] = $uri;
786
+                        break;
787
+                    case 3:
788
+                        $result['deleted'][] = $uri;
789
+                        break;
790
+                }
791
+
792
+            }
793
+        } else {
794
+            // No synctoken supplied, this is the initial sync.
795
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
796
+            $stmt = $this->db->prepare($query);
797
+            $stmt->execute([$addressBookId]);
798
+
799
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
800
+        }
801
+        return $result;
802
+    }
803
+
804
+    /**
805
+     * Adds a change record to the addressbookchanges table.
806
+     *
807
+     * @param mixed $addressBookId
808
+     * @param string $objectUri
809
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
810
+     * @return void
811
+     */
812
+    protected function addChange($addressBookId, $objectUri, $operation) {
813
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
814
+        $stmt = $this->db->prepare($sql);
815
+        $stmt->execute([
816
+            $objectUri,
817
+            $addressBookId,
818
+            $operation,
819
+            $addressBookId
820
+        ]);
821
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
822
+        $stmt->execute([
823
+            $addressBookId
824
+        ]);
825
+    }
826
+
827
+    private function readBlob($cardData) {
828
+        if (is_resource($cardData)) {
829
+            return stream_get_contents($cardData);
830
+        }
831
+
832
+        return $cardData;
833
+    }
834
+
835
+    /**
836
+     * @param IShareable $shareable
837
+     * @param string[] $add
838
+     * @param string[] $remove
839
+     */
840
+    public function updateShares(IShareable $shareable, $add, $remove) {
841
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
842
+    }
843
+
844
+    /**
845
+     * search contact
846
+     *
847
+     * @param int $addressBookId
848
+     * @param string $pattern which should match within the $searchProperties
849
+     * @param array $searchProperties defines the properties within the query pattern should match
850
+     * @return array an array of contacts which are arrays of key-value-pairs
851
+     */
852
+    public function search($addressBookId, $pattern, $searchProperties) {
853
+        $query = $this->db->getQueryBuilder();
854
+        $query2 = $this->db->getQueryBuilder();
855
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
856
+        foreach ($searchProperties as $property) {
857
+            $query2->orWhere(
858
+                $query2->expr()->andX(
859
+                    $query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
860
+                    $query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
861
+                )
862
+            );
863
+        }
864
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
865
+
866
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
867
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
868
+
869
+        $result = $query->execute();
870
+        $cards = $result->fetchAll();
871
+
872
+        $result->closeCursor();
873
+
874
+        return array_map(function($array) {
875
+            $array['carddata'] = $this->readBlob($array['carddata']);
876
+            return $array;
877
+        }, $cards);
878
+    }
879
+
880
+    /**
881
+     * @param int $bookId
882
+     * @param string $name
883
+     * @return array
884
+     */
885
+    public function collectCardProperties($bookId, $name) {
886
+        $query = $this->db->getQueryBuilder();
887
+        $result = $query->selectDistinct('value')
888
+            ->from($this->dbCardsPropertiesTable)
889
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
890
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
891
+            ->execute();
892
+
893
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
894
+        $result->closeCursor();
895
+
896
+        return $all;
897
+    }
898
+
899
+    /**
900
+     * get URI from a given contact
901
+     *
902
+     * @param int $id
903
+     * @return string
904
+     */
905
+    public function getCardUri($id) {
906
+        $query = $this->db->getQueryBuilder();
907
+        $query->select('uri')->from($this->dbCardsTable)
908
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
909
+                ->setParameter('id', $id);
910
+
911
+        $result = $query->execute();
912
+        $uri = $result->fetch();
913
+        $result->closeCursor();
914
+
915
+        if (!isset($uri['uri'])) {
916
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
917
+        }
918
+
919
+        return $uri['uri'];
920
+    }
921
+
922
+    /**
923
+     * return contact with the given URI
924
+     *
925
+     * @param int $addressBookId
926
+     * @param string $uri
927
+     * @returns array
928
+     */
929
+    public function getContact($addressBookId, $uri) {
930
+        $result = [];
931
+        $query = $this->db->getQueryBuilder();
932
+        $query->select('*')->from($this->dbCardsTable)
933
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
934
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
935
+        $queryResult = $query->execute();
936
+        $contact = $queryResult->fetch();
937
+        $queryResult->closeCursor();
938
+
939
+        if (is_array($contact)) {
940
+            $result = $contact;
941
+        }
942
+
943
+        return $result;
944
+    }
945
+
946
+    /**
947
+     * Returns the list of people whom this address book is shared with.
948
+     *
949
+     * Every element in this array should have the following properties:
950
+     *   * href - Often a mailto: address
951
+     *   * commonName - Optional, for example a first + last name
952
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
953
+     *   * readOnly - boolean
954
+     *   * summary - Optional, a description for the share
955
+     *
956
+     * @return array
957
+     */
958
+    public function getShares($addressBookId) {
959
+        return $this->sharingBackend->getShares($addressBookId);
960
+    }
961
+
962
+    /**
963
+     * update properties table
964
+     *
965
+     * @param int $addressBookId
966
+     * @param string $cardUri
967
+     * @param string $vCardSerialized
968
+     */
969
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
970
+        $cardId = $this->getCardId($addressBookId, $cardUri);
971
+        $vCard = $this->readCard($vCardSerialized);
972
+
973
+        $this->purgeProperties($addressBookId, $cardId);
974
+
975
+        $query = $this->db->getQueryBuilder();
976
+        $query->insert($this->dbCardsPropertiesTable)
977
+            ->values(
978
+                [
979
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
980
+                    'cardid' => $query->createNamedParameter($cardId),
981
+                    'name' => $query->createParameter('name'),
982
+                    'value' => $query->createParameter('value'),
983
+                    'preferred' => $query->createParameter('preferred')
984
+                ]
985
+            );
986
+
987
+        foreach ($vCard->children() as $property) {
988
+            if(!in_array($property->name, self::$indexProperties)) {
989
+                continue;
990
+            }
991
+            $preferred = 0;
992
+            foreach($property->parameters as $parameter) {
993
+                if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
994
+                    $preferred = 1;
995
+                    break;
996
+                }
997
+            }
998
+            $query->setParameter('name', $property->name);
999
+            $query->setParameter('value', substr($property->getValue(), 0, 254));
1000
+            $query->setParameter('preferred', $preferred);
1001
+            $query->execute();
1002
+        }
1003
+    }
1004
+
1005
+    /**
1006
+     * read vCard data into a vCard object
1007
+     *
1008
+     * @param string $cardData
1009
+     * @return VCard
1010
+     */
1011
+    protected function readCard($cardData) {
1012
+        return  Reader::read($cardData);
1013
+    }
1014
+
1015
+    /**
1016
+     * delete all properties from a given card
1017
+     *
1018
+     * @param int $addressBookId
1019
+     * @param int $cardId
1020
+     */
1021
+    protected function purgeProperties($addressBookId, $cardId) {
1022
+        $query = $this->db->getQueryBuilder();
1023
+        $query->delete($this->dbCardsPropertiesTable)
1024
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1025
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1026
+        $query->execute();
1027
+    }
1028
+
1029
+    /**
1030
+     * get ID from a given contact
1031
+     *
1032
+     * @param int $addressBookId
1033
+     * @param string $uri
1034
+     * @return int
1035
+     */
1036
+    protected function getCardId($addressBookId, $uri) {
1037
+        $query = $this->db->getQueryBuilder();
1038
+        $query->select('id')->from($this->dbCardsTable)
1039
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1040
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1041
+
1042
+        $result = $query->execute();
1043
+        $cardIds = $result->fetch();
1044
+        $result->closeCursor();
1045
+
1046
+        if (!isset($cardIds['id'])) {
1047
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1048
+        }
1049
+
1050
+        return (int)$cardIds['id'];
1051
+    }
1052
+
1053
+    /**
1054
+     * For shared address books the sharee is set in the ACL of the address book
1055
+     * @param $addressBookId
1056
+     * @param $acl
1057
+     * @return array
1058
+     */
1059
+    public function applyShareAcl($addressBookId, $acl) {
1060
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1061
+    }
1062
+
1063
+    private function convertPrincipal($principalUri, $toV2) {
1064
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1065
+            list(, $name) = URLUtil::splitPath($principalUri);
1066
+            if ($toV2 === true) {
1067
+                return "principals/users/$name";
1068
+            }
1069
+            return "principals/$name";
1070
+        }
1071
+        return $principalUri;
1072
+    }
1073 1073
 }
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,21 +172,21 @@  discard block
 block discarded – undo
172 172
 			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173 173
 			->execute();
174 174
 
175
-		while($row = $result->fetch()) {
175
+		while ($row = $result->fetch()) {
176 176
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
177
-			$uri = $row['uri'] . '_shared_by_' . $name;
178
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
177
+			$uri = $row['uri'].'_shared_by_'.$name;
178
+			$displayName = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
179 179
 			if (!isset($addressBooks[$row['id']])) {
180 180
 				$addressBooks[$row['id']] = [
181 181
 					'id'  => $row['id'],
182 182
 					'uri' => $uri,
183 183
 					'principaluri' => $principalUriOriginal,
184 184
 					'{DAV:}displayname' => $displayName,
185
-					'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
185
+					'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
186 186
 					'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
187
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
188
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
189
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
187
+					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
188
+					'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
189
+					'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
190 190
 				];
191 191
 			}
192 192
 		}
@@ -206,15 +206,15 @@  discard block
 block discarded – undo
206 206
 		$addressBooks = [];
207 207
 
208 208
 		$result = $query->execute();
209
-		while($row = $result->fetch()) {
209
+		while ($row = $result->fetch()) {
210 210
 			$addressBooks[$row['id']] = [
211 211
 				'id'  => $row['id'],
212 212
 				'uri' => $row['uri'],
213 213
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
214 214
 				'{DAV:}displayname' => $row['displayname'],
215
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
215
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
216 216
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
217
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
217
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
218 218
 			];
219 219
 		}
220 220
 		$result->closeCursor();
@@ -257,9 +257,9 @@  discard block
 block discarded – undo
257 257
 			'uri' => $row['uri'],
258 258
 			'principaluri' => $row['principaluri'],
259 259
 			'{DAV:}displayname' => $row['displayname'],
260
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
260
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
261 261
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
262
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
262
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
263 263
 		];
264 264
 	}
265 265
 
@@ -287,9 +287,9 @@  discard block
 block discarded – undo
287 287
 				'uri' => $row['uri'],
288 288
 				'principaluri' => $row['principaluri'],
289 289
 				'{DAV:}displayname' => $row['displayname'],
290
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
290
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
291 291
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
292
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
292
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
293 293
 			];
294 294
 	}
295 295
 
@@ -312,19 +312,19 @@  discard block
 block discarded – undo
312 312
 	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
313 313
 		$supportedProperties = [
314 314
 			'{DAV:}displayname',
315
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
315
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description',
316 316
 		];
317 317
 
318 318
 		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
319 319
 
320 320
 			$updates = [];
321
-			foreach($mutations as $property=>$newValue) {
321
+			foreach ($mutations as $property=>$newValue) {
322 322
 
323
-				switch($property) {
323
+				switch ($property) {
324 324
 					case '{DAV:}displayname' :
325 325
 						$updates['displayname'] = $newValue;
326 326
 						break;
327
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
327
+					case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
328 328
 						$updates['description'] = $newValue;
329 329
 						break;
330 330
 				}
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 			$query = $this->db->getQueryBuilder();
333 333
 			$query->update('addressbooks');
334 334
 
335
-			foreach($updates as $key=>$value) {
335
+			foreach ($updates as $key=>$value) {
336 336
 				$query->set($key, $query->createNamedParameter($value));
337 337
 			}
338 338
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
@@ -363,24 +363,24 @@  discard block
 block discarded – undo
363 363
 			'synctoken' => 1
364 364
 		];
365 365
 
366
-		foreach($properties as $property=>$newValue) {
366
+		foreach ($properties as $property=>$newValue) {
367 367
 
368
-			switch($property) {
368
+			switch ($property) {
369 369
 				case '{DAV:}displayname' :
370 370
 					$values['displayname'] = $newValue;
371 371
 					break;
372
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
372
+				case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
373 373
 					$values['description'] = $newValue;
374 374
 					break;
375 375
 				default :
376
-					throw new BadRequest('Unknown property: ' . $property);
376
+					throw new BadRequest('Unknown property: '.$property);
377 377
 			}
378 378
 
379 379
 		}
380 380
 
381 381
 		// Fallback to make sure the displayname is set. Some clients may refuse
382 382
 		// to work with addressbooks not having a displayname.
383
-		if(is_null($values['displayname'])) {
383
+		if (is_null($values['displayname'])) {
384 384
 			$values['displayname'] = $url;
385 385
 		}
386 386
 
@@ -458,8 +458,8 @@  discard block
 block discarded – undo
458 458
 		$cards = [];
459 459
 
460 460
 		$result = $query->execute();
461
-		while($row = $result->fetch()) {
462
-			$row['etag'] = '"' . $row['etag'] . '"';
461
+		while ($row = $result->fetch()) {
462
+			$row['etag'] = '"'.$row['etag'].'"';
463 463
 			$row['carddata'] = $this->readBlob($row['carddata']);
464 464
 			$cards[] = $row;
465 465
 		}
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 		if (!$row) {
494 494
 			return false;
495 495
 		}
496
-		$row['etag'] = '"' . $row['etag'] . '"';
496
+		$row['etag'] = '"'.$row['etag'].'"';
497 497
 		$row['carddata'] = $this->readBlob($row['carddata']);
498 498
 
499 499
 		return $row;
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
 			$result = $query->execute();
531 531
 
532 532
 			while ($row = $result->fetch()) {
533
-				$row['etag'] = '"' . $row['etag'] . '"';
533
+				$row['etag'] = '"'.$row['etag'].'"';
534 534
 				$row['carddata'] = $this->readBlob($row['carddata']);
535 535
 				$cards[] = $row;
536 536
 			}
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
 					'cardData' => $cardData]));
591 591
 		}
592 592
 
593
-		return '"' . $etag . '"';
593
+		return '"'.$etag.'"';
594 594
 	}
595 595
 
596 596
 	/**
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
 					'cardData' => $cardData]));
643 643
 		}
644 644
 
645
-		return '"' . $etag . '"';
645
+		return '"'.$etag.'"';
646 646
 	}
647 647
 
648 648
 	/**
@@ -742,7 +742,7 @@  discard block
 block discarded – undo
742 742
 	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
743 743
 		// Current synctoken
744 744
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
745
-		$stmt->execute([ $addressBookId ]);
745
+		$stmt->execute([$addressBookId]);
746 746
 		$currentToken = $stmt->fetchColumn(0);
747 747
 
748 748
 		if (is_null($currentToken)) return null;
@@ -757,8 +757,8 @@  discard block
 block discarded – undo
757 757
 		if ($syncToken) {
758 758
 
759 759
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
760
-			if ($limit>0) {
761
-				$query .= " `LIMIT` " . (int)$limit;
760
+			if ($limit > 0) {
761
+				$query .= " `LIMIT` ".(int) $limit;
762 762
 			}
763 763
 
764 764
 			// Fetching all changes
@@ -769,15 +769,15 @@  discard block
 block discarded – undo
769 769
 
770 770
 			// This loop ensures that any duplicates are overwritten, only the
771 771
 			// last change on a node is relevant.
772
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
772
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
773 773
 
774 774
 				$changes[$row['uri']] = $row['operation'];
775 775
 
776 776
 			}
777 777
 
778
-			foreach($changes as $uri => $operation) {
778
+			foreach ($changes as $uri => $operation) {
779 779
 
780
-				switch($operation) {
780
+				switch ($operation) {
781 781
 					case 1:
782 782
 						$result['added'][] = $uri;
783 783
 						break;
@@ -857,7 +857,7 @@  discard block
 block discarded – undo
857 857
 			$query2->orWhere(
858 858
 				$query2->expr()->andX(
859 859
 					$query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
860
-					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
860
+					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%'))
861 861
 				)
862 862
 			);
863 863
 		}
@@ -913,7 +913,7 @@  discard block
 block discarded – undo
913 913
 		$result->closeCursor();
914 914
 
915 915
 		if (!isset($uri['uri'])) {
916
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
916
+			throw new \InvalidArgumentException('Card does not exists: '.$id);
917 917
 		}
918 918
 
919 919
 		return $uri['uri'];
@@ -985,11 +985,11 @@  discard block
 block discarded – undo
985 985
 			);
986 986
 
987 987
 		foreach ($vCard->children() as $property) {
988
-			if(!in_array($property->name, self::$indexProperties)) {
988
+			if (!in_array($property->name, self::$indexProperties)) {
989 989
 				continue;
990 990
 			}
991 991
 			$preferred = 0;
992
-			foreach($property->parameters as $parameter) {
992
+			foreach ($property->parameters as $parameter) {
993 993
 				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
994 994
 					$preferred = 1;
995 995
 					break;
@@ -1044,10 +1044,10 @@  discard block
 block discarded – undo
1044 1044
 		$result->closeCursor();
1045 1045
 
1046 1046
 		if (!isset($cardIds['id'])) {
1047
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1047
+			throw new \InvalidArgumentException('Card does not exists: '.$uri);
1048 1048
 		}
1049 1049
 
1050
-		return (int)$cardIds['id'];
1050
+		return (int) $cardIds['id'];
1051 1051
 	}
1052 1052
 
1053 1053
 	/**
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.