Passed
Push — master ( 7ed11b...ecdfe9 )
by Christoph
14:07 queued 11s
created
apps/dav/lib/Command/SyncSystemAddressBook.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@
 block discarded – undo
54 54
 		$output->writeln('Syncing users ...');
55 55
 		$progress = new ProgressBar($output);
56 56
 		$progress->start();
57
-		$this->syncService->syncInstance(function () use ($progress) {
57
+		$this->syncService->syncInstance(function() use ($progress) {
58 58
 			$progress->advance();
59 59
 		});
60 60
 
Please login to merge, or discard this patch.
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -32,37 +32,37 @@
 block discarded – undo
32 32
 
33 33
 class SyncSystemAddressBook extends Command {
34 34
 
35
-	/** @var SyncService */
36
-	private $syncService;
35
+    /** @var SyncService */
36
+    private $syncService;
37 37
 
38
-	/**
39
-	 * @param SyncService $syncService
40
-	 */
41
-	public function __construct(SyncService $syncService) {
42
-		parent::__construct();
43
-		$this->syncService = $syncService;
44
-	}
38
+    /**
39
+     * @param SyncService $syncService
40
+     */
41
+    public function __construct(SyncService $syncService) {
42
+        parent::__construct();
43
+        $this->syncService = $syncService;
44
+    }
45 45
 
46
-	protected function configure() {
47
-		$this
48
-			->setName('dav:sync-system-addressbook')
49
-			->setDescription('Synchronizes users to the system addressbook');
50
-	}
46
+    protected function configure() {
47
+        $this
48
+            ->setName('dav:sync-system-addressbook')
49
+            ->setDescription('Synchronizes users to the system addressbook');
50
+    }
51 51
 
52
-	/**
53
-	 * @param InputInterface $input
54
-	 * @param OutputInterface $output
55
-	 */
56
-	protected function execute(InputInterface $input, OutputInterface $output): int {
57
-		$output->writeln('Syncing users ...');
58
-		$progress = new ProgressBar($output);
59
-		$progress->start();
60
-		$this->syncService->syncInstance(function () use ($progress) {
61
-			$progress->advance();
62
-		});
52
+    /**
53
+     * @param InputInterface $input
54
+     * @param OutputInterface $output
55
+     */
56
+    protected function execute(InputInterface $input, OutputInterface $output): int {
57
+        $output->writeln('Syncing users ...');
58
+        $progress = new ProgressBar($output);
59
+        $progress->start();
60
+        $this->syncService->syncInstance(function () use ($progress) {
61
+            $progress->advance();
62
+        });
63 63
 
64
-		$progress->finish();
65
-		$output->writeln('');
66
-		return 0;
67
-	}
64
+        $progress->finish();
65
+        $output->writeln('');
66
+        return 0;
67
+    }
68 68
 }
Please login to merge, or discard this patch.
apps/dav/lib/Avatars/AvatarHome.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@
 block discarded – undo
58 58
 	public function getChild($name) {
59 59
 		$elements = pathinfo($name);
60 60
 		$ext = isset($elements['extension']) ? $elements['extension'] : '';
61
-		$size = (int)(isset($elements['filename']) ? $elements['filename'] : '64');
61
+		$size = (int) (isset($elements['filename']) ? $elements['filename'] : '64');
62 62
 		if (!in_array($ext, ['jpeg', 'png'], true)) {
63 63
 			throw new MethodNotAllowed('File format not allowed');
64 64
 		}
Please login to merge, or discard this patch.
Indentation   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -33,87 +33,87 @@
 block discarded – undo
33 33
 
34 34
 class AvatarHome implements ICollection {
35 35
 
36
-	/** @var array */
37
-	private $principalInfo;
38
-	/** @var IAvatarManager */
39
-	private $avatarManager;
36
+    /** @var array */
37
+    private $principalInfo;
38
+    /** @var IAvatarManager */
39
+    private $avatarManager;
40 40
 
41
-	/**
42
-	 * AvatarHome constructor.
43
-	 *
44
-	 * @param array $principalInfo
45
-	 * @param IAvatarManager $avatarManager
46
-	 */
47
-	public function __construct($principalInfo, IAvatarManager $avatarManager) {
48
-		$this->principalInfo = $principalInfo;
49
-		$this->avatarManager = $avatarManager;
50
-	}
41
+    /**
42
+     * AvatarHome constructor.
43
+     *
44
+     * @param array $principalInfo
45
+     * @param IAvatarManager $avatarManager
46
+     */
47
+    public function __construct($principalInfo, IAvatarManager $avatarManager) {
48
+        $this->principalInfo = $principalInfo;
49
+        $this->avatarManager = $avatarManager;
50
+    }
51 51
 
52
-	public function createFile($name, $data = null) {
53
-		throw new Forbidden('Permission denied to create a file');
54
-	}
52
+    public function createFile($name, $data = null) {
53
+        throw new Forbidden('Permission denied to create a file');
54
+    }
55 55
 
56
-	public function createDirectory($name) {
57
-		throw new Forbidden('Permission denied to create a folder');
58
-	}
56
+    public function createDirectory($name) {
57
+        throw new Forbidden('Permission denied to create a folder');
58
+    }
59 59
 
60
-	public function getChild($name) {
61
-		$elements = pathinfo($name);
62
-		$ext = isset($elements['extension']) ? $elements['extension'] : '';
63
-		$size = (int)(isset($elements['filename']) ? $elements['filename'] : '64');
64
-		if (!in_array($ext, ['jpeg', 'png'], true)) {
65
-			throw new MethodNotAllowed('File format not allowed');
66
-		}
67
-		if ($size <= 0 || $size > 1024) {
68
-			throw new MethodNotAllowed('Invalid image size');
69
-		}
70
-		$avatar = $this->avatarManager->getAvatar($this->getName());
71
-		if (!$avatar->exists()) {
72
-			throw new NotFound();
73
-		}
74
-		return new AvatarNode($size, $ext, $avatar);
75
-	}
60
+    public function getChild($name) {
61
+        $elements = pathinfo($name);
62
+        $ext = isset($elements['extension']) ? $elements['extension'] : '';
63
+        $size = (int)(isset($elements['filename']) ? $elements['filename'] : '64');
64
+        if (!in_array($ext, ['jpeg', 'png'], true)) {
65
+            throw new MethodNotAllowed('File format not allowed');
66
+        }
67
+        if ($size <= 0 || $size > 1024) {
68
+            throw new MethodNotAllowed('Invalid image size');
69
+        }
70
+        $avatar = $this->avatarManager->getAvatar($this->getName());
71
+        if (!$avatar->exists()) {
72
+            throw new NotFound();
73
+        }
74
+        return new AvatarNode($size, $ext, $avatar);
75
+    }
76 76
 
77
-	public function getChildren() {
78
-		try {
79
-			return [
80
-				$this->getChild('96.jpeg')
81
-			];
82
-		} catch (NotFound $exception) {
83
-			return [];
84
-		}
85
-	}
77
+    public function getChildren() {
78
+        try {
79
+            return [
80
+                $this->getChild('96.jpeg')
81
+            ];
82
+        } catch (NotFound $exception) {
83
+            return [];
84
+        }
85
+    }
86 86
 
87
-	public function childExists($name) {
88
-		try {
89
-			$ret = $this->getChild($name);
90
-			return $ret !== null;
91
-		} catch (NotFound $ex) {
92
-			return false;
93
-		} catch (MethodNotAllowed $ex) {
94
-			return false;
95
-		}
96
-	}
87
+    public function childExists($name) {
88
+        try {
89
+            $ret = $this->getChild($name);
90
+            return $ret !== null;
91
+        } catch (NotFound $ex) {
92
+            return false;
93
+        } catch (MethodNotAllowed $ex) {
94
+            return false;
95
+        }
96
+    }
97 97
 
98
-	public function delete() {
99
-		throw new Forbidden('Permission denied to delete this folder');
100
-	}
98
+    public function delete() {
99
+        throw new Forbidden('Permission denied to delete this folder');
100
+    }
101 101
 
102
-	public function getName() {
103
-		list(,$name) = Uri\split($this->principalInfo['uri']);
104
-		return $name;
105
-	}
102
+    public function getName() {
103
+        list(,$name) = Uri\split($this->principalInfo['uri']);
104
+        return $name;
105
+    }
106 106
 
107
-	public function setName($name) {
108
-		throw new Forbidden('Permission denied to rename this folder');
109
-	}
107
+    public function setName($name) {
108
+        throw new Forbidden('Permission denied to rename this folder');
109
+    }
110 110
 
111
-	/**
112
-	 * Returns the last modification time, as a unix timestamp
113
-	 *
114
-	 * @return int|null
115
-	 */
116
-	public function getLastModified() {
117
-		return null;
118
-	}
111
+    /**
112
+     * Returns the last modification time, as a unix timestamp
113
+     *
114
+     * @return int|null
115
+     */
116
+    public function getLastModified() {
117
+        return null;
118
+    }
119 119
 }
Please login to merge, or discard this patch.
apps/dav/lib/Avatars/AvatarNode.php 2 patches
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -26,71 +26,71 @@
 block discarded – undo
26 26
 use Sabre\DAV\File;
27 27
 
28 28
 class AvatarNode extends File {
29
-	private $ext;
30
-	private $size;
31
-	private $avatar;
29
+    private $ext;
30
+    private $size;
31
+    private $avatar;
32 32
 
33
-	/**
34
-	 * AvatarNode constructor.
35
-	 *
36
-	 * @param integer $size
37
-	 * @param string $ext
38
-	 * @param IAvatar $avatar
39
-	 */
40
-	public function __construct($size, $ext, $avatar) {
41
-		$this->size = $size;
42
-		$this->ext = $ext;
43
-		$this->avatar = $avatar;
44
-	}
33
+    /**
34
+     * AvatarNode constructor.
35
+     *
36
+     * @param integer $size
37
+     * @param string $ext
38
+     * @param IAvatar $avatar
39
+     */
40
+    public function __construct($size, $ext, $avatar) {
41
+        $this->size = $size;
42
+        $this->ext = $ext;
43
+        $this->avatar = $avatar;
44
+    }
45 45
 
46
-	/**
47
-	 * Returns the name of the node.
48
-	 *
49
-	 * This is used to generate the url.
50
-	 *
51
-	 * @return string
52
-	 */
53
-	public function getName() {
54
-		return "$this->size.$this->ext";
55
-	}
46
+    /**
47
+     * Returns the name of the node.
48
+     *
49
+     * This is used to generate the url.
50
+     *
51
+     * @return string
52
+     */
53
+    public function getName() {
54
+        return "$this->size.$this->ext";
55
+    }
56 56
 
57
-	public function get() {
58
-		$image = $this->avatar->get($this->size);
59
-		$res = $image->resource();
57
+    public function get() {
58
+        $image = $this->avatar->get($this->size);
59
+        $res = $image->resource();
60 60
 
61
-		ob_start();
62
-		if ($this->ext === 'png') {
63
-			imagepng($res);
64
-		} else {
65
-			imagejpeg($res);
66
-		}
61
+        ob_start();
62
+        if ($this->ext === 'png') {
63
+            imagepng($res);
64
+        } else {
65
+            imagejpeg($res);
66
+        }
67 67
 
68
-		return ob_get_clean();
69
-	}
68
+        return ob_get_clean();
69
+    }
70 70
 
71
-	/**
72
-	 * Returns the mime-type for a file
73
-	 *
74
-	 * If null is returned, we'll assume application/octet-stream
75
-	 *
76
-	 * @return string|null
77
-	 */
78
-	public function getContentType() {
79
-		if ($this->ext === 'png') {
80
-			return 'image/png';
81
-		}
82
-		return 'image/jpeg';
83
-	}
71
+    /**
72
+     * Returns the mime-type for a file
73
+     *
74
+     * If null is returned, we'll assume application/octet-stream
75
+     *
76
+     * @return string|null
77
+     */
78
+    public function getContentType() {
79
+        if ($this->ext === 'png') {
80
+            return 'image/png';
81
+        }
82
+        return 'image/jpeg';
83
+    }
84 84
 
85
-	public function getETag() {
86
-		return $this->avatar->getFile($this->size)->getEtag();
87
-	}
85
+    public function getETag() {
86
+        return $this->avatar->getFile($this->size)->getEtag();
87
+    }
88 88
 
89
-	public function getLastModified() {
90
-		$timestamp = $this->avatar->getFile($this->size)->getMTime();
91
-		if (!empty($timestamp)) {
92
-			return (int)$timestamp;
93
-		}
94
-		return $timestamp;
95
-	}
89
+    public function getLastModified() {
90
+        $timestamp = $this->avatar->getFile($this->size)->getMTime();
91
+        if (!empty($timestamp)) {
92
+            return (int)$timestamp;
93
+        }
94
+        return $timestamp;
95
+    }
96 96
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -89,7 +89,7 @@
 block discarded – undo
89 89
 	public function getLastModified() {
90 90
 		$timestamp = $this->avatar->getFile($this->size)->getMTime();
91 91
 		if (!empty($timestamp)) {
92
-			return (int)$timestamp;
92
+			return (int) $timestamp;
93 93
 		}
94 94
 		return $timestamp;
95 95
 	}
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/Xml/Groups.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -39,7 +39,7 @@
 block discarded – undo
39 39
 
40 40
 	public function xmlSerialize(Writer $writer) {
41 41
 		foreach ($this->groups as $group) {
42
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
42
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}group', $group);
43 43
 		}
44 44
 	}
45 45
 }
Please login to merge, or discard this patch.
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -27,21 +27,21 @@
 block discarded – undo
27 27
 use Sabre\Xml\XmlSerializable;
28 28
 
29 29
 class Groups implements XmlSerializable {
30
-	public const NS_OWNCLOUD = 'http://owncloud.org/ns';
30
+    public const NS_OWNCLOUD = 'http://owncloud.org/ns';
31 31
 
32
-	/** @var string[] of TYPE:CHECKSUM */
33
-	private $groups;
32
+    /** @var string[] of TYPE:CHECKSUM */
33
+    private $groups;
34 34
 
35
-	/**
36
-	 * @param string $groups
37
-	 */
38
-	public function __construct($groups) {
39
-		$this->groups = $groups;
40
-	}
35
+    /**
36
+     * @param string $groups
37
+     */
38
+    public function __construct($groups) {
39
+        $this->groups = $groups;
40
+    }
41 41
 
42
-	public function xmlSerialize(Writer $writer) {
43
-		foreach ($this->groups as $group) {
44
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
45
-		}
46
-	}
42
+    public function xmlSerialize(Writer $writer) {
43
+        foreach ($this->groups as $group) {
44
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
45
+        }
46
+    }
47 47
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/SyncService.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 			if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
97 97
 				// remote server revoked access to the address book, remove it
98 98
 				$this->backend->deleteAddressBook($addressBookId);
99
-				$this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
99
+				$this->logger->info('Authorization failed, remove address book: '.$url, ['app' => 'dav']);
100 100
 				throw $ex;
101 101
 			}
102 102
 		}
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
 	 */
170 170
 	protected function getClient($url, $userName, $sharedSecret) {
171 171
 		$settings = [
172
-			'baseUri' => $url . '/',
172
+			'baseUri' => $url.'/',
173 173
 			'userName' => $userName,
174 174
 			'password' => $sharedSecret,
175 175
 		];
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
 		if (is_null($this->localSystemAddressBook)) {
307 307
 			$systemPrincipal = "principals/system/system";
308 308
 			$this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
309
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
309
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => 'System addressbook which holds all users of this instance'
310 310
 			]);
311 311
 		}
312 312
 
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
 
316 316
 	public function syncInstance(\Closure $progressCallback = null) {
317 317
 		$systemAddressBook = $this->getLocalSystemAddressBook();
318
-		$this->userManager->callForAllUsers(function ($user) use ($systemAddressBook, $progressCallback) {
318
+		$this->userManager->callForAllUsers(function($user) use ($systemAddressBook, $progressCallback) {
319 319
 			$this->updateUser($user);
320 320
 			if (!is_null($progressCallback)) {
321 321
 				$progressCallback();
Please login to merge, or discard this patch.
Indentation   +297 added lines, -297 removed lines patch added patch discarded remove patch
@@ -43,301 +43,301 @@
 block discarded – undo
43 43
 
44 44
 class SyncService {
45 45
 
46
-	/** @var CardDavBackend */
47
-	private $backend;
48
-
49
-	/** @var IUserManager */
50
-	private $userManager;
51
-
52
-	/** @var ILogger */
53
-	private $logger;
54
-
55
-	/** @var array */
56
-	private $localSystemAddressBook;
57
-
58
-	/** @var AccountManager */
59
-	private $accountManager;
60
-
61
-	/** @var string */
62
-	protected $certPath;
63
-
64
-	/**
65
-	 * SyncService constructor.
66
-	 *
67
-	 * @param CardDavBackend $backend
68
-	 * @param IUserManager $userManager
69
-	 * @param ILogger $logger
70
-	 * @param AccountManager $accountManager
71
-	 */
72
-	public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
73
-		$this->backend = $backend;
74
-		$this->userManager = $userManager;
75
-		$this->logger = $logger;
76
-		$this->accountManager = $accountManager;
77
-		$this->certPath = '';
78
-	}
79
-
80
-	/**
81
-	 * @param string $url
82
-	 * @param string $userName
83
-	 * @param string $addressBookUrl
84
-	 * @param string $sharedSecret
85
-	 * @param string $syncToken
86
-	 * @param int $targetBookId
87
-	 * @param string $targetPrincipal
88
-	 * @param array $targetProperties
89
-	 * @return string
90
-	 * @throws \Exception
91
-	 */
92
-	public function syncRemoteAddressBook($url, $userName, $addressBookUrl, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
93
-		// 1. create addressbook
94
-		$book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
95
-		$addressBookId = $book['id'];
96
-
97
-		// 2. query changes
98
-		try {
99
-			$response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
100
-		} catch (ClientHttpException $ex) {
101
-			if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
102
-				// remote server revoked access to the address book, remove it
103
-				$this->backend->deleteAddressBook($addressBookId);
104
-				$this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
105
-				throw $ex;
106
-			}
107
-		}
108
-
109
-		// 3. apply changes
110
-		// TODO: use multi-get for download
111
-		foreach ($response['response'] as $resource => $status) {
112
-			$cardUri = basename($resource);
113
-			if (isset($status[200])) {
114
-				$vCard = $this->download($url, $userName, $sharedSecret, $resource);
115
-				$existingCard = $this->backend->getCard($addressBookId, $cardUri);
116
-				if ($existingCard === false) {
117
-					$this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
118
-				} else {
119
-					$this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
120
-				}
121
-			} else {
122
-				$this->backend->deleteCard($addressBookId, $cardUri);
123
-			}
124
-		}
125
-
126
-		return $response['token'];
127
-	}
128
-
129
-	/**
130
-	 * @param string $principal
131
-	 * @param string $id
132
-	 * @param array $properties
133
-	 * @return array|null
134
-	 * @throws \Sabre\DAV\Exception\BadRequest
135
-	 */
136
-	public function ensureSystemAddressBookExists($principal, $id, $properties) {
137
-		$book = $this->backend->getAddressBooksByUri($principal, $id);
138
-		if (!is_null($book)) {
139
-			return $book;
140
-		}
141
-		$this->backend->createAddressBook($principal, $id, $properties);
142
-
143
-		return $this->backend->getAddressBooksByUri($principal, $id);
144
-	}
145
-
146
-	/**
147
-	 * Check if there is a valid certPath we should use
148
-	 *
149
-	 * @return string
150
-	 */
151
-	protected function getCertPath() {
152
-
153
-		// we already have a valid certPath
154
-		if ($this->certPath !== '') {
155
-			return $this->certPath;
156
-		}
157
-
158
-		/** @var ICertificateManager $certManager */
159
-		$certManager = \OC::$server->getCertificateManager(null);
160
-		$certPath = $certManager->getAbsoluteBundlePath();
161
-		if (file_exists($certPath)) {
162
-			$this->certPath = $certPath;
163
-		}
164
-
165
-		return $this->certPath;
166
-	}
167
-
168
-	/**
169
-	 * @param string $url
170
-	 * @param string $userName
171
-	 * @param string $addressBookUrl
172
-	 * @param string $sharedSecret
173
-	 * @return Client
174
-	 */
175
-	protected function getClient($url, $userName, $sharedSecret) {
176
-		$settings = [
177
-			'baseUri' => $url . '/',
178
-			'userName' => $userName,
179
-			'password' => $sharedSecret,
180
-		];
181
-		$client = new Client($settings);
182
-		$certPath = $this->getCertPath();
183
-		$client->setThrowExceptions(true);
184
-
185
-		if ($certPath !== '' && strpos($url, 'http://') !== 0) {
186
-			$client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
187
-		}
188
-
189
-		return $client;
190
-	}
191
-
192
-	/**
193
-	 * @param string $url
194
-	 * @param string $userName
195
-	 * @param string $addressBookUrl
196
-	 * @param string $sharedSecret
197
-	 * @param string $syncToken
198
-	 * @return array
199
-	 */
200
-	protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) {
201
-		$client = $this->getClient($url, $userName, $sharedSecret);
202
-
203
-		$body = $this->buildSyncCollectionRequestBody($syncToken);
204
-
205
-		$response = $client->request('REPORT', $addressBookUrl, $body, [
206
-			'Content-Type' => 'application/xml'
207
-		]);
208
-
209
-		return $this->parseMultiStatus($response['body']);
210
-	}
211
-
212
-	/**
213
-	 * @param string $url
214
-	 * @param string $userName
215
-	 * @param string $sharedSecret
216
-	 * @param string $resourcePath
217
-	 * @return array
218
-	 */
219
-	protected function download($url, $userName, $sharedSecret, $resourcePath) {
220
-		$client = $this->getClient($url, $userName, $sharedSecret);
221
-		return $client->request('GET', $resourcePath);
222
-	}
223
-
224
-	/**
225
-	 * @param string|null $syncToken
226
-	 * @return string
227
-	 */
228
-	private function buildSyncCollectionRequestBody($syncToken) {
229
-		$dom = new \DOMDocument('1.0', 'UTF-8');
230
-		$dom->formatOutput = true;
231
-		$root = $dom->createElementNS('DAV:', 'd:sync-collection');
232
-		$sync = $dom->createElement('d:sync-token', $syncToken);
233
-		$prop = $dom->createElement('d:prop');
234
-		$cont = $dom->createElement('d:getcontenttype');
235
-		$etag = $dom->createElement('d:getetag');
236
-
237
-		$prop->appendChild($cont);
238
-		$prop->appendChild($etag);
239
-		$root->appendChild($sync);
240
-		$root->appendChild($prop);
241
-		$dom->appendChild($root);
242
-		return $dom->saveXML();
243
-	}
244
-
245
-	/**
246
-	 * @param string $body
247
-	 * @return array
248
-	 * @throws \Sabre\Xml\ParseException
249
-	 */
250
-	private function parseMultiStatus($body) {
251
-		$xml = new Service();
252
-
253
-		/** @var MultiStatus $multiStatus */
254
-		$multiStatus = $xml->expect('{DAV:}multistatus', $body);
255
-
256
-		$result = [];
257
-		foreach ($multiStatus->getResponses() as $response) {
258
-			$result[$response->getHref()] = $response->getResponseProperties();
259
-		}
260
-
261
-		return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
262
-	}
263
-
264
-	/**
265
-	 * @param IUser $user
266
-	 */
267
-	public function updateUser(IUser $user) {
268
-		$systemAddressBook = $this->getLocalSystemAddressBook();
269
-		$addressBookId = $systemAddressBook['id'];
270
-		$converter = new Converter($this->accountManager);
271
-		$name = $user->getBackendClassName();
272
-		$userId = $user->getUID();
273
-
274
-		$cardId = "$name:$userId.vcf";
275
-		$card = $this->backend->getCard($addressBookId, $cardId);
276
-		if ($user->isEnabled()) {
277
-			if ($card === false) {
278
-				$vCard = $converter->createCardFromUser($user);
279
-				if ($vCard !== null) {
280
-					$this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
281
-				}
282
-			} else {
283
-				$vCard = $converter->createCardFromUser($user);
284
-				if (is_null($vCard)) {
285
-					$this->backend->deleteCard($addressBookId, $cardId);
286
-				} else {
287
-					$this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
288
-				}
289
-			}
290
-		} else {
291
-			$this->backend->deleteCard($addressBookId, $cardId);
292
-		}
293
-	}
294
-
295
-	/**
296
-	 * @param IUser|string $userOrCardId
297
-	 */
298
-	public function deleteUser($userOrCardId) {
299
-		$systemAddressBook = $this->getLocalSystemAddressBook();
300
-		if ($userOrCardId instanceof IUser) {
301
-			$name = $userOrCardId->getBackendClassName();
302
-			$userId = $userOrCardId->getUID();
303
-
304
-			$userOrCardId = "$name:$userId.vcf";
305
-		}
306
-		$this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
307
-	}
308
-
309
-	/**
310
-	 * @return array|null
311
-	 */
312
-	public function getLocalSystemAddressBook() {
313
-		if (is_null($this->localSystemAddressBook)) {
314
-			$systemPrincipal = "principals/system/system";
315
-			$this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
316
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
317
-			]);
318
-		}
319
-
320
-		return $this->localSystemAddressBook;
321
-	}
322
-
323
-	public function syncInstance(\Closure $progressCallback = null) {
324
-		$systemAddressBook = $this->getLocalSystemAddressBook();
325
-		$this->userManager->callForAllUsers(function ($user) use ($systemAddressBook, $progressCallback) {
326
-			$this->updateUser($user);
327
-			if (!is_null($progressCallback)) {
328
-				$progressCallback();
329
-			}
330
-		});
331
-
332
-		// remove no longer existing
333
-		$allCards = $this->backend->getCards($systemAddressBook['id']);
334
-		foreach ($allCards as $card) {
335
-			$vCard = Reader::read($card['carddata']);
336
-			$uid = $vCard->UID->getValue();
337
-			// load backend and see if user exists
338
-			if (!$this->userManager->userExists($uid)) {
339
-				$this->deleteUser($card['uri']);
340
-			}
341
-		}
342
-	}
46
+    /** @var CardDavBackend */
47
+    private $backend;
48
+
49
+    /** @var IUserManager */
50
+    private $userManager;
51
+
52
+    /** @var ILogger */
53
+    private $logger;
54
+
55
+    /** @var array */
56
+    private $localSystemAddressBook;
57
+
58
+    /** @var AccountManager */
59
+    private $accountManager;
60
+
61
+    /** @var string */
62
+    protected $certPath;
63
+
64
+    /**
65
+     * SyncService constructor.
66
+     *
67
+     * @param CardDavBackend $backend
68
+     * @param IUserManager $userManager
69
+     * @param ILogger $logger
70
+     * @param AccountManager $accountManager
71
+     */
72
+    public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
73
+        $this->backend = $backend;
74
+        $this->userManager = $userManager;
75
+        $this->logger = $logger;
76
+        $this->accountManager = $accountManager;
77
+        $this->certPath = '';
78
+    }
79
+
80
+    /**
81
+     * @param string $url
82
+     * @param string $userName
83
+     * @param string $addressBookUrl
84
+     * @param string $sharedSecret
85
+     * @param string $syncToken
86
+     * @param int $targetBookId
87
+     * @param string $targetPrincipal
88
+     * @param array $targetProperties
89
+     * @return string
90
+     * @throws \Exception
91
+     */
92
+    public function syncRemoteAddressBook($url, $userName, $addressBookUrl, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
93
+        // 1. create addressbook
94
+        $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
95
+        $addressBookId = $book['id'];
96
+
97
+        // 2. query changes
98
+        try {
99
+            $response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
100
+        } catch (ClientHttpException $ex) {
101
+            if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
102
+                // remote server revoked access to the address book, remove it
103
+                $this->backend->deleteAddressBook($addressBookId);
104
+                $this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
105
+                throw $ex;
106
+            }
107
+        }
108
+
109
+        // 3. apply changes
110
+        // TODO: use multi-get for download
111
+        foreach ($response['response'] as $resource => $status) {
112
+            $cardUri = basename($resource);
113
+            if (isset($status[200])) {
114
+                $vCard = $this->download($url, $userName, $sharedSecret, $resource);
115
+                $existingCard = $this->backend->getCard($addressBookId, $cardUri);
116
+                if ($existingCard === false) {
117
+                    $this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
118
+                } else {
119
+                    $this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
120
+                }
121
+            } else {
122
+                $this->backend->deleteCard($addressBookId, $cardUri);
123
+            }
124
+        }
125
+
126
+        return $response['token'];
127
+    }
128
+
129
+    /**
130
+     * @param string $principal
131
+     * @param string $id
132
+     * @param array $properties
133
+     * @return array|null
134
+     * @throws \Sabre\DAV\Exception\BadRequest
135
+     */
136
+    public function ensureSystemAddressBookExists($principal, $id, $properties) {
137
+        $book = $this->backend->getAddressBooksByUri($principal, $id);
138
+        if (!is_null($book)) {
139
+            return $book;
140
+        }
141
+        $this->backend->createAddressBook($principal, $id, $properties);
142
+
143
+        return $this->backend->getAddressBooksByUri($principal, $id);
144
+    }
145
+
146
+    /**
147
+     * Check if there is a valid certPath we should use
148
+     *
149
+     * @return string
150
+     */
151
+    protected function getCertPath() {
152
+
153
+        // we already have a valid certPath
154
+        if ($this->certPath !== '') {
155
+            return $this->certPath;
156
+        }
157
+
158
+        /** @var ICertificateManager $certManager */
159
+        $certManager = \OC::$server->getCertificateManager(null);
160
+        $certPath = $certManager->getAbsoluteBundlePath();
161
+        if (file_exists($certPath)) {
162
+            $this->certPath = $certPath;
163
+        }
164
+
165
+        return $this->certPath;
166
+    }
167
+
168
+    /**
169
+     * @param string $url
170
+     * @param string $userName
171
+     * @param string $addressBookUrl
172
+     * @param string $sharedSecret
173
+     * @return Client
174
+     */
175
+    protected function getClient($url, $userName, $sharedSecret) {
176
+        $settings = [
177
+            'baseUri' => $url . '/',
178
+            'userName' => $userName,
179
+            'password' => $sharedSecret,
180
+        ];
181
+        $client = new Client($settings);
182
+        $certPath = $this->getCertPath();
183
+        $client->setThrowExceptions(true);
184
+
185
+        if ($certPath !== '' && strpos($url, 'http://') !== 0) {
186
+            $client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
187
+        }
188
+
189
+        return $client;
190
+    }
191
+
192
+    /**
193
+     * @param string $url
194
+     * @param string $userName
195
+     * @param string $addressBookUrl
196
+     * @param string $sharedSecret
197
+     * @param string $syncToken
198
+     * @return array
199
+     */
200
+    protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) {
201
+        $client = $this->getClient($url, $userName, $sharedSecret);
202
+
203
+        $body = $this->buildSyncCollectionRequestBody($syncToken);
204
+
205
+        $response = $client->request('REPORT', $addressBookUrl, $body, [
206
+            'Content-Type' => 'application/xml'
207
+        ]);
208
+
209
+        return $this->parseMultiStatus($response['body']);
210
+    }
211
+
212
+    /**
213
+     * @param string $url
214
+     * @param string $userName
215
+     * @param string $sharedSecret
216
+     * @param string $resourcePath
217
+     * @return array
218
+     */
219
+    protected function download($url, $userName, $sharedSecret, $resourcePath) {
220
+        $client = $this->getClient($url, $userName, $sharedSecret);
221
+        return $client->request('GET', $resourcePath);
222
+    }
223
+
224
+    /**
225
+     * @param string|null $syncToken
226
+     * @return string
227
+     */
228
+    private function buildSyncCollectionRequestBody($syncToken) {
229
+        $dom = new \DOMDocument('1.0', 'UTF-8');
230
+        $dom->formatOutput = true;
231
+        $root = $dom->createElementNS('DAV:', 'd:sync-collection');
232
+        $sync = $dom->createElement('d:sync-token', $syncToken);
233
+        $prop = $dom->createElement('d:prop');
234
+        $cont = $dom->createElement('d:getcontenttype');
235
+        $etag = $dom->createElement('d:getetag');
236
+
237
+        $prop->appendChild($cont);
238
+        $prop->appendChild($etag);
239
+        $root->appendChild($sync);
240
+        $root->appendChild($prop);
241
+        $dom->appendChild($root);
242
+        return $dom->saveXML();
243
+    }
244
+
245
+    /**
246
+     * @param string $body
247
+     * @return array
248
+     * @throws \Sabre\Xml\ParseException
249
+     */
250
+    private function parseMultiStatus($body) {
251
+        $xml = new Service();
252
+
253
+        /** @var MultiStatus $multiStatus */
254
+        $multiStatus = $xml->expect('{DAV:}multistatus', $body);
255
+
256
+        $result = [];
257
+        foreach ($multiStatus->getResponses() as $response) {
258
+            $result[$response->getHref()] = $response->getResponseProperties();
259
+        }
260
+
261
+        return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
262
+    }
263
+
264
+    /**
265
+     * @param IUser $user
266
+     */
267
+    public function updateUser(IUser $user) {
268
+        $systemAddressBook = $this->getLocalSystemAddressBook();
269
+        $addressBookId = $systemAddressBook['id'];
270
+        $converter = new Converter($this->accountManager);
271
+        $name = $user->getBackendClassName();
272
+        $userId = $user->getUID();
273
+
274
+        $cardId = "$name:$userId.vcf";
275
+        $card = $this->backend->getCard($addressBookId, $cardId);
276
+        if ($user->isEnabled()) {
277
+            if ($card === false) {
278
+                $vCard = $converter->createCardFromUser($user);
279
+                if ($vCard !== null) {
280
+                    $this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
281
+                }
282
+            } else {
283
+                $vCard = $converter->createCardFromUser($user);
284
+                if (is_null($vCard)) {
285
+                    $this->backend->deleteCard($addressBookId, $cardId);
286
+                } else {
287
+                    $this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
288
+                }
289
+            }
290
+        } else {
291
+            $this->backend->deleteCard($addressBookId, $cardId);
292
+        }
293
+    }
294
+
295
+    /**
296
+     * @param IUser|string $userOrCardId
297
+     */
298
+    public function deleteUser($userOrCardId) {
299
+        $systemAddressBook = $this->getLocalSystemAddressBook();
300
+        if ($userOrCardId instanceof IUser) {
301
+            $name = $userOrCardId->getBackendClassName();
302
+            $userId = $userOrCardId->getUID();
303
+
304
+            $userOrCardId = "$name:$userId.vcf";
305
+        }
306
+        $this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
307
+    }
308
+
309
+    /**
310
+     * @return array|null
311
+     */
312
+    public function getLocalSystemAddressBook() {
313
+        if (is_null($this->localSystemAddressBook)) {
314
+            $systemPrincipal = "principals/system/system";
315
+            $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
316
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
317
+            ]);
318
+        }
319
+
320
+        return $this->localSystemAddressBook;
321
+    }
322
+
323
+    public function syncInstance(\Closure $progressCallback = null) {
324
+        $systemAddressBook = $this->getLocalSystemAddressBook();
325
+        $this->userManager->callForAllUsers(function ($user) use ($systemAddressBook, $progressCallback) {
326
+            $this->updateUser($user);
327
+            if (!is_null($progressCallback)) {
328
+                $progressCallback();
329
+            }
330
+        });
331
+
332
+        // remove no longer existing
333
+        $allCards = $this->backend->getCards($systemAddressBook['id']);
334
+        foreach ($allCards as $card) {
335
+            $vCard = Reader::read($card['carddata']);
336
+            $uid = $vCard->UID->getValue();
337
+            // load backend and see if user exists
338
+            if (!$this->userManager->userExists($uid)) {
339
+                $this->deleteUser($card['uri']);
340
+            }
341
+        }
342
+    }
343 343
 }
Please login to merge, or discard this patch.
apps/dav/lib/DAV/Sharing/IShareable.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -29,47 +29,47 @@
 block discarded – undo
29 29
  */
30 30
 interface IShareable extends INode {
31 31
 
32
-	/**
33
-	 * Updates the list of shares.
34
-	 *
35
-	 * The first array is a list of people that are to be added to the
36
-	 * resource.
37
-	 *
38
-	 * Every element in the add array has the following properties:
39
-	 *   * href - A url. Usually a mailto: address
40
-	 *   * commonName - Usually a first and last name, or false
41
-	 *   * summary - A description of the share, can also be false
42
-	 *   * readOnly - A boolean value
43
-	 *
44
-	 * Every element in the remove array is just the address string.
45
-	 *
46
-	 * @param array $add
47
-	 * @param array $remove
48
-	 * @return void
49
-	 */
50
-	public function updateShares(array $add, array $remove);
32
+    /**
33
+     * Updates the list of shares.
34
+     *
35
+     * The first array is a list of people that are to be added to the
36
+     * resource.
37
+     *
38
+     * Every element in the add array has the following properties:
39
+     *   * href - A url. Usually a mailto: address
40
+     *   * commonName - Usually a first and last name, or false
41
+     *   * summary - A description of the share, can also be false
42
+     *   * readOnly - A boolean value
43
+     *
44
+     * Every element in the remove array is just the address string.
45
+     *
46
+     * @param array $add
47
+     * @param array $remove
48
+     * @return void
49
+     */
50
+    public function updateShares(array $add, array $remove);
51 51
 
52
-	/**
53
-	 * Returns the list of people whom this resource is shared with.
54
-	 *
55
-	 * Every element in this array should have the following properties:
56
-	 *   * href - Often a mailto: address
57
-	 *   * commonName - Optional, for example a first + last name
58
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
59
-	 *   * readOnly - boolean
60
-	 *   * summary - Optional, a description for the share
61
-	 *
62
-	 * @return array
63
-	 */
64
-	public function getShares();
52
+    /**
53
+     * Returns the list of people whom this resource is shared with.
54
+     *
55
+     * Every element in this array should have the following properties:
56
+     *   * href - Often a mailto: address
57
+     *   * commonName - Optional, for example a first + last name
58
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
59
+     *   * readOnly - boolean
60
+     *   * summary - Optional, a description for the share
61
+     *
62
+     * @return array
63
+     */
64
+    public function getShares();
65 65
 
66
-	/**
67
-	 * @return int
68
-	 */
69
-	public function getResourceId();
66
+    /**
67
+     * @return int
68
+     */
69
+    public function getResourceId();
70 70
 
71
-	/**
72
-	 * @return string
73
-	 */
74
-	public function getOwner();
71
+    /**
72
+     * @return string
73
+     */
74
+    public function getOwner();
75 75
 }
Please login to merge, or discard this patch.
apps/dav/lib/DAV/Sharing/Xml/Invite.php 2 patches
Indentation   +106 added lines, -106 removed lines patch added patch discarded remove patch
@@ -41,120 +41,120 @@
 block discarded – undo
41 41
  */
42 42
 class Invite implements XmlSerializable {
43 43
 
44
-	/**
45
-	 * The list of users a calendar has been shared to.
46
-	 *
47
-	 * @var array
48
-	 */
49
-	protected $users;
44
+    /**
45
+     * The list of users a calendar has been shared to.
46
+     *
47
+     * @var array
48
+     */
49
+    protected $users;
50 50
 
51
-	/**
52
-	 * The organizer contains information about the person who shared the
53
-	 * object.
54
-	 *
55
-	 * @var array|null
56
-	 */
57
-	protected $organizer;
51
+    /**
52
+     * The organizer contains information about the person who shared the
53
+     * object.
54
+     *
55
+     * @var array|null
56
+     */
57
+    protected $organizer;
58 58
 
59
-	/**
60
-	 * Creates the property.
61
-	 *
62
-	 * Users is an array. Each element of the array has the following
63
-	 * properties:
64
-	 *
65
-	 *   * href - Often a mailto: address
66
-	 *   * commonName - Optional, for example a first and lastname for a user.
67
-	 *   * status - One of the SharingPlugin::STATUS_* constants.
68
-	 *   * readOnly - true or false
69
-	 *   * summary - Optional, description of the share
70
-	 *
71
-	 * The organizer key is optional to specify. It's only useful when a
72
-	 * 'sharee' requests the sharing information.
73
-	 *
74
-	 * The organizer may have the following properties:
75
-	 *   * href - Often a mailto: address.
76
-	 *   * commonName - Optional human-readable name.
77
-	 *   * firstName - Optional first name.
78
-	 *   * lastName - Optional last name.
79
-	 *
80
-	 * If you wonder why these two structures are so different, I guess a
81
-	 * valid answer is that the current spec is still a draft.
82
-	 *
83
-	 * @param array $users
84
-	 */
85
-	public function __construct(array $users, array $organizer = null) {
86
-		$this->users = $users;
87
-		$this->organizer = $organizer;
88
-	}
59
+    /**
60
+     * Creates the property.
61
+     *
62
+     * Users is an array. Each element of the array has the following
63
+     * properties:
64
+     *
65
+     *   * href - Often a mailto: address
66
+     *   * commonName - Optional, for example a first and lastname for a user.
67
+     *   * status - One of the SharingPlugin::STATUS_* constants.
68
+     *   * readOnly - true or false
69
+     *   * summary - Optional, description of the share
70
+     *
71
+     * The organizer key is optional to specify. It's only useful when a
72
+     * 'sharee' requests the sharing information.
73
+     *
74
+     * The organizer may have the following properties:
75
+     *   * href - Often a mailto: address.
76
+     *   * commonName - Optional human-readable name.
77
+     *   * firstName - Optional first name.
78
+     *   * lastName - Optional last name.
79
+     *
80
+     * If you wonder why these two structures are so different, I guess a
81
+     * valid answer is that the current spec is still a draft.
82
+     *
83
+     * @param array $users
84
+     */
85
+    public function __construct(array $users, array $organizer = null) {
86
+        $this->users = $users;
87
+        $this->organizer = $organizer;
88
+    }
89 89
 
90
-	/**
91
-	 * Returns the list of users, as it was passed to the constructor.
92
-	 *
93
-	 * @return array
94
-	 */
95
-	public function getValue() {
96
-		return $this->users;
97
-	}
90
+    /**
91
+     * Returns the list of users, as it was passed to the constructor.
92
+     *
93
+     * @return array
94
+     */
95
+    public function getValue() {
96
+        return $this->users;
97
+    }
98 98
 
99
-	/**
100
-	 * The xmlSerialize metod is called during xml writing.
101
-	 *
102
-	 * Use the $writer argument to write its own xml serialization.
103
-	 *
104
-	 * An important note: do _not_ create a parent element. Any element
105
-	 * implementing XmlSerializble should only ever write what's considered
106
-	 * its 'inner xml'.
107
-	 *
108
-	 * The parent of the current element is responsible for writing a
109
-	 * containing element.
110
-	 *
111
-	 * This allows serializers to be re-used for different element names.
112
-	 *
113
-	 * If you are opening new elements, you must also close them again.
114
-	 *
115
-	 * @param Writer $writer
116
-	 * @return void
117
-	 */
118
-	public function xmlSerialize(Writer $writer) {
119
-		$cs = '{' . Plugin::NS_OWNCLOUD . '}';
99
+    /**
100
+     * The xmlSerialize metod is called during xml writing.
101
+     *
102
+     * Use the $writer argument to write its own xml serialization.
103
+     *
104
+     * An important note: do _not_ create a parent element. Any element
105
+     * implementing XmlSerializble should only ever write what's considered
106
+     * its 'inner xml'.
107
+     *
108
+     * The parent of the current element is responsible for writing a
109
+     * containing element.
110
+     *
111
+     * This allows serializers to be re-used for different element names.
112
+     *
113
+     * If you are opening new elements, you must also close them again.
114
+     *
115
+     * @param Writer $writer
116
+     * @return void
117
+     */
118
+    public function xmlSerialize(Writer $writer) {
119
+        $cs = '{' . Plugin::NS_OWNCLOUD . '}';
120 120
 
121
-		if (!is_null($this->organizer)) {
122
-			$writer->startElement($cs . 'organizer');
123
-			$writer->writeElement('{DAV:}href', $this->organizer['href']);
121
+        if (!is_null($this->organizer)) {
122
+            $writer->startElement($cs . 'organizer');
123
+            $writer->writeElement('{DAV:}href', $this->organizer['href']);
124 124
 
125
-			if (isset($this->organizer['commonName']) && $this->organizer['commonName']) {
126
-				$writer->writeElement($cs . 'common-name', $this->organizer['commonName']);
127
-			}
128
-			if (isset($this->organizer['firstName']) && $this->organizer['firstName']) {
129
-				$writer->writeElement($cs . 'first-name', $this->organizer['firstName']);
130
-			}
131
-			if (isset($this->organizer['lastName']) && $this->organizer['lastName']) {
132
-				$writer->writeElement($cs . 'last-name', $this->organizer['lastName']);
133
-			}
134
-			$writer->endElement(); // organizer
135
-		}
125
+            if (isset($this->organizer['commonName']) && $this->organizer['commonName']) {
126
+                $writer->writeElement($cs . 'common-name', $this->organizer['commonName']);
127
+            }
128
+            if (isset($this->organizer['firstName']) && $this->organizer['firstName']) {
129
+                $writer->writeElement($cs . 'first-name', $this->organizer['firstName']);
130
+            }
131
+            if (isset($this->organizer['lastName']) && $this->organizer['lastName']) {
132
+                $writer->writeElement($cs . 'last-name', $this->organizer['lastName']);
133
+            }
134
+            $writer->endElement(); // organizer
135
+        }
136 136
 
137
-		foreach ($this->users as $user) {
138
-			$writer->startElement($cs . 'user');
139
-			$writer->writeElement('{DAV:}href', $user['href']);
140
-			if (isset($user['commonName']) && $user['commonName']) {
141
-				$writer->writeElement($cs . 'common-name', $user['commonName']);
142
-			}
143
-			$writer->writeElement($cs . 'invite-accepted');
137
+        foreach ($this->users as $user) {
138
+            $writer->startElement($cs . 'user');
139
+            $writer->writeElement('{DAV:}href', $user['href']);
140
+            if (isset($user['commonName']) && $user['commonName']) {
141
+                $writer->writeElement($cs . 'common-name', $user['commonName']);
142
+            }
143
+            $writer->writeElement($cs . 'invite-accepted');
144 144
 
145
-			$writer->startElement($cs . 'access');
146
-			if ($user['readOnly']) {
147
-				$writer->writeElement($cs . 'read');
148
-			} else {
149
-				$writer->writeElement($cs . 'read-write');
150
-			}
151
-			$writer->endElement(); // access
145
+            $writer->startElement($cs . 'access');
146
+            if ($user['readOnly']) {
147
+                $writer->writeElement($cs . 'read');
148
+            } else {
149
+                $writer->writeElement($cs . 'read-write');
150
+            }
151
+            $writer->endElement(); // access
152 152
 
153
-			if (isset($user['summary']) && $user['summary']) {
154
-				$writer->writeElement($cs . 'summary', $user['summary']);
155
-			}
153
+            if (isset($user['summary']) && $user['summary']) {
154
+                $writer->writeElement($cs . 'summary', $user['summary']);
155
+            }
156 156
 
157
-			$writer->endElement(); //user
158
-		}
159
-	}
157
+            $writer->endElement(); //user
158
+        }
159
+    }
160 160
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -116,42 +116,42 @@
 block discarded – undo
116 116
 	 * @return void
117 117
 	 */
118 118
 	public function xmlSerialize(Writer $writer) {
119
-		$cs = '{' . Plugin::NS_OWNCLOUD . '}';
119
+		$cs = '{'.Plugin::NS_OWNCLOUD.'}';
120 120
 
121 121
 		if (!is_null($this->organizer)) {
122
-			$writer->startElement($cs . 'organizer');
122
+			$writer->startElement($cs.'organizer');
123 123
 			$writer->writeElement('{DAV:}href', $this->organizer['href']);
124 124
 
125 125
 			if (isset($this->organizer['commonName']) && $this->organizer['commonName']) {
126
-				$writer->writeElement($cs . 'common-name', $this->organizer['commonName']);
126
+				$writer->writeElement($cs.'common-name', $this->organizer['commonName']);
127 127
 			}
128 128
 			if (isset($this->organizer['firstName']) && $this->organizer['firstName']) {
129
-				$writer->writeElement($cs . 'first-name', $this->organizer['firstName']);
129
+				$writer->writeElement($cs.'first-name', $this->organizer['firstName']);
130 130
 			}
131 131
 			if (isset($this->organizer['lastName']) && $this->organizer['lastName']) {
132
-				$writer->writeElement($cs . 'last-name', $this->organizer['lastName']);
132
+				$writer->writeElement($cs.'last-name', $this->organizer['lastName']);
133 133
 			}
134 134
 			$writer->endElement(); // organizer
135 135
 		}
136 136
 
137 137
 		foreach ($this->users as $user) {
138
-			$writer->startElement($cs . 'user');
138
+			$writer->startElement($cs.'user');
139 139
 			$writer->writeElement('{DAV:}href', $user['href']);
140 140
 			if (isset($user['commonName']) && $user['commonName']) {
141
-				$writer->writeElement($cs . 'common-name', $user['commonName']);
141
+				$writer->writeElement($cs.'common-name', $user['commonName']);
142 142
 			}
143
-			$writer->writeElement($cs . 'invite-accepted');
143
+			$writer->writeElement($cs.'invite-accepted');
144 144
 
145
-			$writer->startElement($cs . 'access');
145
+			$writer->startElement($cs.'access');
146 146
 			if ($user['readOnly']) {
147
-				$writer->writeElement($cs . 'read');
147
+				$writer->writeElement($cs.'read');
148 148
 			} else {
149
-				$writer->writeElement($cs . 'read-write');
149
+				$writer->writeElement($cs.'read-write');
150 150
 			}
151 151
 			$writer->endElement(); // access
152 152
 
153 153
 			if (isset($user['summary']) && $user['summary']) {
154
-				$writer->writeElement($cs . 'summary', $user['summary']);
154
+				$writer->writeElement($cs.'summary', $user['summary']);
155 155
 			}
156 156
 
157 157
 			$writer->endElement(); //user
Please login to merge, or discard this patch.
apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php 2 patches
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -26,54 +26,54 @@
 block discarded – undo
26 26
 use Sabre\Xml\XmlDeserializable;
27 27
 
28 28
 class ShareRequest implements XmlDeserializable {
29
-	public $set = [];
29
+    public $set = [];
30 30
 
31
-	public $remove = [];
31
+    public $remove = [];
32 32
 
33
-	/**
34
-	 * Constructor
35
-	 *
36
-	 * @param array $set
37
-	 * @param array $remove
38
-	 */
39
-	public function __construct(array $set, array $remove) {
40
-		$this->set = $set;
41
-		$this->remove = $remove;
42
-	}
33
+    /**
34
+     * Constructor
35
+     *
36
+     * @param array $set
37
+     * @param array $remove
38
+     */
39
+    public function __construct(array $set, array $remove) {
40
+        $this->set = $set;
41
+        $this->remove = $remove;
42
+    }
43 43
 
44
-	public static function xmlDeserialize(Reader $reader) {
45
-		$elements = $reader->parseInnerTree([
46
-			'{' . Plugin::NS_OWNCLOUD. '}set' => 'Sabre\\Xml\\Element\\KeyValue',
47
-			'{' . Plugin::NS_OWNCLOUD . '}remove' => 'Sabre\\Xml\\Element\\KeyValue',
48
-		]);
44
+    public static function xmlDeserialize(Reader $reader) {
45
+        $elements = $reader->parseInnerTree([
46
+            '{' . Plugin::NS_OWNCLOUD. '}set' => 'Sabre\\Xml\\Element\\KeyValue',
47
+            '{' . Plugin::NS_OWNCLOUD . '}remove' => 'Sabre\\Xml\\Element\\KeyValue',
48
+        ]);
49 49
 
50
-		$set = [];
51
-		$remove = [];
50
+        $set = [];
51
+        $remove = [];
52 52
 
53
-		foreach ($elements as $elem) {
54
-			switch ($elem['name']) {
53
+        foreach ($elements as $elem) {
54
+            switch ($elem['name']) {
55 55
 
56
-				case '{' . Plugin::NS_OWNCLOUD . '}set':
57
-					$sharee = $elem['value'];
56
+                case '{' . Plugin::NS_OWNCLOUD . '}set':
57
+                    $sharee = $elem['value'];
58 58
 
59
-					$sumElem = '{' . Plugin::NS_OWNCLOUD . '}summary';
60
-					$commonName = '{' . Plugin::NS_OWNCLOUD . '}common-name';
59
+                    $sumElem = '{' . Plugin::NS_OWNCLOUD . '}summary';
60
+                    $commonName = '{' . Plugin::NS_OWNCLOUD . '}common-name';
61 61
 
62
-					$set[] = [
63
-						'href' => $sharee['{DAV:}href'],
64
-						'commonName' => isset($sharee[$commonName]) ? $sharee[$commonName] : null,
65
-						'summary' => isset($sharee[$sumElem]) ? $sharee[$sumElem] : null,
66
-						'readOnly' => !array_key_exists('{' . Plugin::NS_OWNCLOUD . '}read-write', $sharee),
67
-					];
68
-					break;
62
+                    $set[] = [
63
+                        'href' => $sharee['{DAV:}href'],
64
+                        'commonName' => isset($sharee[$commonName]) ? $sharee[$commonName] : null,
65
+                        'summary' => isset($sharee[$sumElem]) ? $sharee[$sumElem] : null,
66
+                        'readOnly' => !array_key_exists('{' . Plugin::NS_OWNCLOUD . '}read-write', $sharee),
67
+                    ];
68
+                    break;
69 69
 
70
-				case '{' . Plugin::NS_OWNCLOUD . '}remove':
71
-					$remove[] = $elem['value']['{DAV:}href'];
72
-					break;
70
+                case '{' . Plugin::NS_OWNCLOUD . '}remove':
71
+                    $remove[] = $elem['value']['{DAV:}href'];
72
+                    break;
73 73
 
74
-			}
75
-		}
74
+            }
75
+        }
76 76
 
77
-		return new self($set, $remove);
78
-	}
77
+        return new self($set, $remove);
78
+    }
79 79
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -43,8 +43,8 @@  discard block
 block discarded – undo
43 43
 
44 44
 	public static function xmlDeserialize(Reader $reader) {
45 45
 		$elements = $reader->parseInnerTree([
46
-			'{' . Plugin::NS_OWNCLOUD. '}set' => 'Sabre\\Xml\\Element\\KeyValue',
47
-			'{' . Plugin::NS_OWNCLOUD . '}remove' => 'Sabre\\Xml\\Element\\KeyValue',
46
+			'{'.Plugin::NS_OWNCLOUD.'}set' => 'Sabre\\Xml\\Element\\KeyValue',
47
+			'{'.Plugin::NS_OWNCLOUD.'}remove' => 'Sabre\\Xml\\Element\\KeyValue',
48 48
 		]);
49 49
 
50 50
 		$set = [];
@@ -53,21 +53,21 @@  discard block
 block discarded – undo
53 53
 		foreach ($elements as $elem) {
54 54
 			switch ($elem['name']) {
55 55
 
56
-				case '{' . Plugin::NS_OWNCLOUD . '}set':
56
+				case '{'.Plugin::NS_OWNCLOUD.'}set':
57 57
 					$sharee = $elem['value'];
58 58
 
59
-					$sumElem = '{' . Plugin::NS_OWNCLOUD . '}summary';
60
-					$commonName = '{' . Plugin::NS_OWNCLOUD . '}common-name';
59
+					$sumElem = '{'.Plugin::NS_OWNCLOUD.'}summary';
60
+					$commonName = '{'.Plugin::NS_OWNCLOUD.'}common-name';
61 61
 
62 62
 					$set[] = [
63 63
 						'href' => $sharee['{DAV:}href'],
64 64
 						'commonName' => isset($sharee[$commonName]) ? $sharee[$commonName] : null,
65 65
 						'summary' => isset($sharee[$sumElem]) ? $sharee[$sumElem] : null,
66
-						'readOnly' => !array_key_exists('{' . Plugin::NS_OWNCLOUD . '}read-write', $sharee),
66
+						'readOnly' => !array_key_exists('{'.Plugin::NS_OWNCLOUD.'}read-write', $sharee),
67 67
 					];
68 68
 					break;
69 69
 
70
-				case '{' . Plugin::NS_OWNCLOUD . '}remove':
70
+				case '{'.Plugin::NS_OWNCLOUD.'}remove':
71 71
 					$remove[] = $elem['value']['{DAV:}href'];
72 72
 					break;
73 73
 
Please login to merge, or discard this patch.
apps/dav/lib/DAV/Sharing/Backend.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -191,13 +191,13 @@  discard block
 block discarded – undo
191 191
 		foreach ($shares as $share) {
192 192
 			$acl[] = [
193 193
 				'privilege' => '{DAV:}read',
194
-				'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
194
+				'principal' => $share['{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}principal'],
195 195
 				'protected' => true,
196 196
 			];
197 197
 			if (!$share['readOnly']) {
198 198
 				$acl[] = [
199 199
 					'privilege' => '{DAV:}write',
200
-					'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
200
+					'principal' => $share['{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}principal'],
201 201
 					'protected' => true,
202 202
 				];
203 203
 			} elseif ($this->resourceType === 'calendar') {
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 				// so users can change the visibility.
206 206
 				$acl[] = [
207 207
 					'privilege' => '{DAV:}write-properties',
208
-					'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
208
+					'principal' => $share['{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}principal'],
209 209
 					'protected' => true,
210 210
 				];
211 211
 			}
Please login to merge, or discard this patch.
Indentation   +209 added lines, -209 removed lines patch added patch discarded remove patch
@@ -35,213 +35,213 @@
 block discarded – undo
35 35
 
36 36
 class Backend {
37 37
 
38
-	/** @var IDBConnection */
39
-	private $db;
40
-	/** @var IUserManager */
41
-	private $userManager;
42
-	/** @var IGroupManager */
43
-	private $groupManager;
44
-	/** @var Principal */
45
-	private $principalBackend;
46
-	/** @var string */
47
-	private $resourceType;
48
-
49
-	public const ACCESS_OWNER = 1;
50
-	public const ACCESS_READ_WRITE = 2;
51
-	public const ACCESS_READ = 3;
52
-
53
-	/**
54
-	 * @param IDBConnection $db
55
-	 * @param IUserManager $userManager
56
-	 * @param IGroupManager $groupManager
57
-	 * @param Principal $principalBackend
58
-	 * @param string $resourceType
59
-	 */
60
-	public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, Principal $principalBackend, $resourceType) {
61
-		$this->db = $db;
62
-		$this->userManager = $userManager;
63
-		$this->groupManager = $groupManager;
64
-		$this->principalBackend = $principalBackend;
65
-		$this->resourceType = $resourceType;
66
-	}
67
-
68
-	/**
69
-	 * @param IShareable $shareable
70
-	 * @param string[] $add
71
-	 * @param string[] $remove
72
-	 */
73
-	public function updateShares(IShareable $shareable, array $add, array $remove) {
74
-		foreach ($add as $element) {
75
-			$principal = $this->principalBackend->findByUri($element['href'], '');
76
-			if ($principal !== '') {
77
-				$this->shareWith($shareable, $element);
78
-			}
79
-		}
80
-		foreach ($remove as $element) {
81
-			$principal = $this->principalBackend->findByUri($element, '');
82
-			if ($principal !== '') {
83
-				$this->unshare($shareable, $element);
84
-			}
85
-		}
86
-	}
87
-
88
-	/**
89
-	 * @param IShareable $shareable
90
-	 * @param string $element
91
-	 */
92
-	private function shareWith($shareable, $element) {
93
-		$user = $element['href'];
94
-		$parts = explode(':', $user, 2);
95
-		if ($parts[0] !== 'principal') {
96
-			return;
97
-		}
98
-
99
-		// don't share with owner
100
-		if ($shareable->getOwner() === $parts[1]) {
101
-			return;
102
-		}
103
-
104
-		$principal = explode('/', $parts[1], 3);
105
-		if (count($principal) !== 3 || $principal[0] !== 'principals' || !in_array($principal[1], ['users', 'groups', 'circles'], true)) {
106
-			// Invalid principal
107
-			return;
108
-		}
109
-
110
-		if (($principal[1] === 'users' && !$this->userManager->userExists($principal[2])) ||
111
-			($principal[1] === 'groups' && !$this->groupManager->groupExists($principal[2]))) {
112
-			// User or group does not exist
113
-			return;
114
-		}
115
-
116
-		// remove the share if it already exists
117
-		$this->unshare($shareable, $element['href']);
118
-		$access = self::ACCESS_READ;
119
-		if (isset($element['readOnly'])) {
120
-			$access = $element['readOnly'] ? self::ACCESS_READ : self::ACCESS_READ_WRITE;
121
-		}
122
-
123
-		$query = $this->db->getQueryBuilder();
124
-		$query->insert('dav_shares')
125
-			->values([
126
-				'principaluri' => $query->createNamedParameter($parts[1]),
127
-				'type' => $query->createNamedParameter($this->resourceType),
128
-				'access' => $query->createNamedParameter($access),
129
-				'resourceid' => $query->createNamedParameter($shareable->getResourceId())
130
-			]);
131
-		$query->execute();
132
-	}
133
-
134
-	/**
135
-	 * @param $resourceId
136
-	 */
137
-	public function deleteAllShares($resourceId) {
138
-		$query = $this->db->getQueryBuilder();
139
-		$query->delete('dav_shares')
140
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
141
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
142
-			->execute();
143
-	}
144
-
145
-	public function deleteAllSharesByUser($principaluri) {
146
-		$query = $this->db->getQueryBuilder();
147
-		$query->delete('dav_shares')
148
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principaluri)))
149
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
150
-			->execute();
151
-	}
152
-
153
-	/**
154
-	 * @param IShareable $shareable
155
-	 * @param string $element
156
-	 */
157
-	private function unshare($shareable, $element) {
158
-		$parts = explode(':', $element, 2);
159
-		if ($parts[0] !== 'principal') {
160
-			return;
161
-		}
162
-
163
-		// don't share with owner
164
-		if ($shareable->getOwner() === $parts[1]) {
165
-			return;
166
-		}
167
-
168
-		$query = $this->db->getQueryBuilder();
169
-		$query->delete('dav_shares')
170
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($shareable->getResourceId())))
171
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
172
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($parts[1])))
173
-		;
174
-		$query->execute();
175
-	}
176
-
177
-	/**
178
-	 * Returns the list of people whom this resource is shared with.
179
-	 *
180
-	 * Every element in this array should have the following properties:
181
-	 *   * href - Often a mailto: address
182
-	 *   * commonName - Optional, for example a first + last name
183
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
184
-	 *   * readOnly - boolean
185
-	 *   * summary - Optional, a description for the share
186
-	 *
187
-	 * @param int $resourceId
188
-	 * @return array
189
-	 */
190
-	public function getShares($resourceId) {
191
-		$query = $this->db->getQueryBuilder();
192
-		$result = $query->select(['principaluri', 'access'])
193
-			->from('dav_shares')
194
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
195
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
196
-			->execute();
197
-
198
-		$shares = [];
199
-		while ($row = $result->fetch()) {
200
-			$p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
201
-			$shares[] = [
202
-				'href' => "principal:${row['principaluri']}",
203
-				'commonName' => isset($p['{DAV:}displayname']) ? $p['{DAV:}displayname'] : '',
204
-				'status' => 1,
205
-				'readOnly' => (int) $row['access'] === self::ACCESS_READ,
206
-				'{http://owncloud.org/ns}principal' => $row['principaluri'],
207
-				'{http://owncloud.org/ns}group-share' => is_null($p)
208
-			];
209
-		}
210
-
211
-		return $shares;
212
-	}
213
-
214
-	/**
215
-	 * For shared resources the sharee is set in the ACL of the resource
216
-	 *
217
-	 * @param int $resourceId
218
-	 * @param array $acl
219
-	 * @return array
220
-	 */
221
-	public function applyShareAcl($resourceId, $acl) {
222
-		$shares = $this->getShares($resourceId);
223
-		foreach ($shares as $share) {
224
-			$acl[] = [
225
-				'privilege' => '{DAV:}read',
226
-				'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
227
-				'protected' => true,
228
-			];
229
-			if (!$share['readOnly']) {
230
-				$acl[] = [
231
-					'privilege' => '{DAV:}write',
232
-					'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
233
-					'protected' => true,
234
-				];
235
-			} elseif ($this->resourceType === 'calendar') {
236
-				// Allow changing the properties of read only calendars,
237
-				// so users can change the visibility.
238
-				$acl[] = [
239
-					'privilege' => '{DAV:}write-properties',
240
-					'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
241
-					'protected' => true,
242
-				];
243
-			}
244
-		}
245
-		return $acl;
246
-	}
38
+    /** @var IDBConnection */
39
+    private $db;
40
+    /** @var IUserManager */
41
+    private $userManager;
42
+    /** @var IGroupManager */
43
+    private $groupManager;
44
+    /** @var Principal */
45
+    private $principalBackend;
46
+    /** @var string */
47
+    private $resourceType;
48
+
49
+    public const ACCESS_OWNER = 1;
50
+    public const ACCESS_READ_WRITE = 2;
51
+    public const ACCESS_READ = 3;
52
+
53
+    /**
54
+     * @param IDBConnection $db
55
+     * @param IUserManager $userManager
56
+     * @param IGroupManager $groupManager
57
+     * @param Principal $principalBackend
58
+     * @param string $resourceType
59
+     */
60
+    public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, Principal $principalBackend, $resourceType) {
61
+        $this->db = $db;
62
+        $this->userManager = $userManager;
63
+        $this->groupManager = $groupManager;
64
+        $this->principalBackend = $principalBackend;
65
+        $this->resourceType = $resourceType;
66
+    }
67
+
68
+    /**
69
+     * @param IShareable $shareable
70
+     * @param string[] $add
71
+     * @param string[] $remove
72
+     */
73
+    public function updateShares(IShareable $shareable, array $add, array $remove) {
74
+        foreach ($add as $element) {
75
+            $principal = $this->principalBackend->findByUri($element['href'], '');
76
+            if ($principal !== '') {
77
+                $this->shareWith($shareable, $element);
78
+            }
79
+        }
80
+        foreach ($remove as $element) {
81
+            $principal = $this->principalBackend->findByUri($element, '');
82
+            if ($principal !== '') {
83
+                $this->unshare($shareable, $element);
84
+            }
85
+        }
86
+    }
87
+
88
+    /**
89
+     * @param IShareable $shareable
90
+     * @param string $element
91
+     */
92
+    private function shareWith($shareable, $element) {
93
+        $user = $element['href'];
94
+        $parts = explode(':', $user, 2);
95
+        if ($parts[0] !== 'principal') {
96
+            return;
97
+        }
98
+
99
+        // don't share with owner
100
+        if ($shareable->getOwner() === $parts[1]) {
101
+            return;
102
+        }
103
+
104
+        $principal = explode('/', $parts[1], 3);
105
+        if (count($principal) !== 3 || $principal[0] !== 'principals' || !in_array($principal[1], ['users', 'groups', 'circles'], true)) {
106
+            // Invalid principal
107
+            return;
108
+        }
109
+
110
+        if (($principal[1] === 'users' && !$this->userManager->userExists($principal[2])) ||
111
+            ($principal[1] === 'groups' && !$this->groupManager->groupExists($principal[2]))) {
112
+            // User or group does not exist
113
+            return;
114
+        }
115
+
116
+        // remove the share if it already exists
117
+        $this->unshare($shareable, $element['href']);
118
+        $access = self::ACCESS_READ;
119
+        if (isset($element['readOnly'])) {
120
+            $access = $element['readOnly'] ? self::ACCESS_READ : self::ACCESS_READ_WRITE;
121
+        }
122
+
123
+        $query = $this->db->getQueryBuilder();
124
+        $query->insert('dav_shares')
125
+            ->values([
126
+                'principaluri' => $query->createNamedParameter($parts[1]),
127
+                'type' => $query->createNamedParameter($this->resourceType),
128
+                'access' => $query->createNamedParameter($access),
129
+                'resourceid' => $query->createNamedParameter($shareable->getResourceId())
130
+            ]);
131
+        $query->execute();
132
+    }
133
+
134
+    /**
135
+     * @param $resourceId
136
+     */
137
+    public function deleteAllShares($resourceId) {
138
+        $query = $this->db->getQueryBuilder();
139
+        $query->delete('dav_shares')
140
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
141
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
142
+            ->execute();
143
+    }
144
+
145
+    public function deleteAllSharesByUser($principaluri) {
146
+        $query = $this->db->getQueryBuilder();
147
+        $query->delete('dav_shares')
148
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principaluri)))
149
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
150
+            ->execute();
151
+    }
152
+
153
+    /**
154
+     * @param IShareable $shareable
155
+     * @param string $element
156
+     */
157
+    private function unshare($shareable, $element) {
158
+        $parts = explode(':', $element, 2);
159
+        if ($parts[0] !== 'principal') {
160
+            return;
161
+        }
162
+
163
+        // don't share with owner
164
+        if ($shareable->getOwner() === $parts[1]) {
165
+            return;
166
+        }
167
+
168
+        $query = $this->db->getQueryBuilder();
169
+        $query->delete('dav_shares')
170
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($shareable->getResourceId())))
171
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
172
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($parts[1])))
173
+        ;
174
+        $query->execute();
175
+    }
176
+
177
+    /**
178
+     * Returns the list of people whom this resource is shared with.
179
+     *
180
+     * Every element in this array should have the following properties:
181
+     *   * href - Often a mailto: address
182
+     *   * commonName - Optional, for example a first + last name
183
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
184
+     *   * readOnly - boolean
185
+     *   * summary - Optional, a description for the share
186
+     *
187
+     * @param int $resourceId
188
+     * @return array
189
+     */
190
+    public function getShares($resourceId) {
191
+        $query = $this->db->getQueryBuilder();
192
+        $result = $query->select(['principaluri', 'access'])
193
+            ->from('dav_shares')
194
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
195
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
196
+            ->execute();
197
+
198
+        $shares = [];
199
+        while ($row = $result->fetch()) {
200
+            $p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
201
+            $shares[] = [
202
+                'href' => "principal:${row['principaluri']}",
203
+                'commonName' => isset($p['{DAV:}displayname']) ? $p['{DAV:}displayname'] : '',
204
+                'status' => 1,
205
+                'readOnly' => (int) $row['access'] === self::ACCESS_READ,
206
+                '{http://owncloud.org/ns}principal' => $row['principaluri'],
207
+                '{http://owncloud.org/ns}group-share' => is_null($p)
208
+            ];
209
+        }
210
+
211
+        return $shares;
212
+    }
213
+
214
+    /**
215
+     * For shared resources the sharee is set in the ACL of the resource
216
+     *
217
+     * @param int $resourceId
218
+     * @param array $acl
219
+     * @return array
220
+     */
221
+    public function applyShareAcl($resourceId, $acl) {
222
+        $shares = $this->getShares($resourceId);
223
+        foreach ($shares as $share) {
224
+            $acl[] = [
225
+                'privilege' => '{DAV:}read',
226
+                'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
227
+                'protected' => true,
228
+            ];
229
+            if (!$share['readOnly']) {
230
+                $acl[] = [
231
+                    'privilege' => '{DAV:}write',
232
+                    'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
233
+                    'protected' => true,
234
+                ];
235
+            } elseif ($this->resourceType === 'calendar') {
236
+                // Allow changing the properties of read only calendars,
237
+                // so users can change the visibility.
238
+                $acl[] = [
239
+                    'privilege' => '{DAV:}write-properties',
240
+                    'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
241
+                    'protected' => true,
242
+                ];
243
+            }
244
+        }
245
+        return $acl;
246
+    }
247 247
 }
Please login to merge, or discard this patch.