Completed
Push — master ( 80b21c...5129a7 )
by Joas
29:44 queued 15s
created
apps/federation/lib/DbHandler.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
 			return $query->getLastInsertId();
81 81
 		}
82 82
 
83
-		$message = 'Internal failure, Could not add trusted server: ' . $url;
83
+		$message = 'Internal failure, Could not add trusted server: '.$url;
84 84
 		$message_t = $this->IL10N->t('Could not add server');
85 85
 		throw new HintException($message, $message_t);
86 86
 		return -1;
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 		$qResult->closeCursor();
115 115
 
116 116
 		if (empty($result)) {
117
-			throw new \Exception('No Server found with ID: ' . $id);
117
+			throw new \Exception('No Server found with ID: '.$id);
118 118
 		}
119 119
 
120 120
 		return $result[0];
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 		$statement->closeCursor();
184 184
 
185 185
 		if (!isset($result['token'])) {
186
-			throw new \Exception('No token found for: ' . $url);
186
+			throw new \Exception('No token found for: '.$url);
187 187
 		}
188 188
 
189 189
 		return $result['token'];
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 		$statement = $query->executeQuery();
217 217
 		$result = $statement->fetch();
218 218
 		$statement->closeCursor();
219
-		return (string)$result['shared_secret'];
219
+		return (string) $result['shared_secret'];
220 220
 	}
221 221
 
222 222
 	/**
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 		$statement = $query->executeQuery();
248 248
 		$result = $statement->fetch();
249 249
 		$statement->closeCursor();
250
-		return (int)$result['status'];
250
+		return (int) $result['status'];
251 251
 	}
252 252
 
253 253
 	/**
Please login to merge, or discard this patch.
Indentation   +240 added lines, -240 removed lines patch added patch discarded remove patch
@@ -25,244 +25,244 @@
 block discarded – undo
25 25
  * @package OCA\Federation
26 26
  */
27 27
 class DbHandler {
28
-	private string $dbTable = 'trusted_servers';
29
-
30
-	public function __construct(
31
-		private IDBConnection $connection,
32
-		private IL10N $IL10N,
33
-	) {
34
-	}
35
-
36
-	/**
37
-	 * Add server to the list of trusted servers
38
-	 *
39
-	 * @throws HintException
40
-	 */
41
-	public function addServer(string $url): int {
42
-		$hash = $this->hash($url);
43
-		$url = rtrim($url, '/');
44
-		$query = $this->connection->getQueryBuilder();
45
-		$query->insert($this->dbTable)
46
-			->values([
47
-				'url' => $query->createParameter('url'),
48
-				'url_hash' => $query->createParameter('url_hash'),
49
-			])
50
-			->setParameter('url', $url)
51
-			->setParameter('url_hash', $hash);
52
-
53
-		$result = $query->executeStatement();
54
-
55
-		if ($result) {
56
-			return $query->getLastInsertId();
57
-		}
58
-
59
-		$message = 'Internal failure, Could not add trusted server: ' . $url;
60
-		$message_t = $this->IL10N->t('Could not add server');
61
-		throw new HintException($message, $message_t);
62
-		return -1;
63
-	}
64
-
65
-	/**
66
-	 * Remove server from the list of trusted servers
67
-	 */
68
-	public function removeServer(int $id): void {
69
-		$query = $this->connection->getQueryBuilder();
70
-		$query->delete($this->dbTable)
71
-			->where($query->expr()->eq('id', $query->createParameter('id')))
72
-			->setParameter('id', $id);
73
-		$query->executeStatement();
74
-	}
75
-
76
-	/**
77
-	 * Get trusted server with given ID
78
-	 *
79
-	 * @return array{id: int, url: string, url_hash: string, token: ?string, shared_secret: ?string, status: int, sync_token: ?string}
80
-	 * @throws \Exception
81
-	 */
82
-	public function getServerById(int $id): array {
83
-		$query = $this->connection->getQueryBuilder();
84
-		$query->select('*')->from($this->dbTable)
85
-			->where($query->expr()->eq('id', $query->createParameter('id')))
86
-			->setParameter('id', $id, IQueryBuilder::PARAM_INT);
87
-
88
-		$qResult = $query->executeQuery();
89
-		$result = $qResult->fetchAll();
90
-		$qResult->closeCursor();
91
-
92
-		if (empty($result)) {
93
-			throw new \Exception('No Server found with ID: ' . $id);
94
-		}
95
-
96
-		return $result[0];
97
-	}
98
-
99
-	/**
100
-	 * Get all trusted servers
101
-	 *
102
-	 * @return list<array{id: int, url: string, url_hash: string, shared_secret: ?string, status: int, sync_token: ?string}>
103
-	 * @throws DBException
104
-	 */
105
-	public function getAllServer(): array {
106
-		$query = $this->connection->getQueryBuilder();
107
-		$query->select(['url', 'url_hash', 'id', 'status', 'shared_secret', 'sync_token'])
108
-			->from($this->dbTable);
109
-		$statement = $query->executeQuery();
110
-		$result = $statement->fetchAll();
111
-		$statement->closeCursor();
112
-		return $result;
113
-	}
114
-
115
-	/**
116
-	 * Check if server already exists in the database table
117
-	 */
118
-	public function serverExists(string $url): bool {
119
-		$hash = $this->hash($url);
120
-		$query = $this->connection->getQueryBuilder();
121
-		$query->select('url')
122
-			->from($this->dbTable)
123
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
124
-			->setParameter('url_hash', $hash);
125
-		$statement = $query->executeQuery();
126
-		$result = $statement->fetchAll();
127
-		$statement->closeCursor();
128
-
129
-		return !empty($result);
130
-	}
131
-
132
-	/**
133
-	 * Write token to database. Token is used to exchange the secret
134
-	 */
135
-	public function addToken(string $url, string $token): void {
136
-		$hash = $this->hash($url);
137
-		$query = $this->connection->getQueryBuilder();
138
-		$query->update($this->dbTable)
139
-			->set('token', $query->createParameter('token'))
140
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
141
-			->setParameter('url_hash', $hash)
142
-			->setParameter('token', $token);
143
-		$query->executeStatement();
144
-	}
145
-
146
-	/**
147
-	 * Get token stored in database
148
-	 * @throws \Exception
149
-	 */
150
-	public function getToken(string $url): string {
151
-		$hash = $this->hash($url);
152
-		$query = $this->connection->getQueryBuilder();
153
-		$query->select('token')->from($this->dbTable)
154
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
155
-			->setParameter('url_hash', $hash);
156
-
157
-		$statement = $query->executeQuery();
158
-		$result = $statement->fetch();
159
-		$statement->closeCursor();
160
-
161
-		if (!isset($result['token'])) {
162
-			throw new \Exception('No token found for: ' . $url);
163
-		}
164
-
165
-		return $result['token'];
166
-	}
167
-
168
-	/**
169
-	 * Add shared Secret to database
170
-	 */
171
-	public function addSharedSecret(string $url, string $sharedSecret): void {
172
-		$hash = $this->hash($url);
173
-		$query = $this->connection->getQueryBuilder();
174
-		$query->update($this->dbTable)
175
-			->set('shared_secret', $query->createParameter('sharedSecret'))
176
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
177
-			->setParameter('url_hash', $hash)
178
-			->setParameter('sharedSecret', $sharedSecret);
179
-		$query->executeStatement();
180
-	}
181
-
182
-	/**
183
-	 * Get shared secret from database
184
-	 */
185
-	public function getSharedSecret(string $url): string {
186
-		$hash = $this->hash($url);
187
-		$query = $this->connection->getQueryBuilder();
188
-		$query->select('shared_secret')->from($this->dbTable)
189
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
190
-			->setParameter('url_hash', $hash);
191
-
192
-		$statement = $query->executeQuery();
193
-		$result = $statement->fetch();
194
-		$statement->closeCursor();
195
-		return (string)$result['shared_secret'];
196
-	}
197
-
198
-	/**
199
-	 * Set server status
200
-	 */
201
-	public function setServerStatus(string $url, int $status, ?string $token = null): void {
202
-		$hash = $this->hash($url);
203
-		$query = $this->connection->getQueryBuilder();
204
-		$query->update($this->dbTable)
205
-			->set('status', $query->createNamedParameter($status))
206
-			->where($query->expr()->eq('url_hash', $query->createNamedParameter($hash)));
207
-		if (!is_null($token)) {
208
-			$query->set('sync_token', $query->createNamedParameter($token));
209
-		}
210
-		$query->executeStatement();
211
-	}
212
-
213
-	/**
214
-	 * Get server status
215
-	 */
216
-	public function getServerStatus(string $url): int {
217
-		$hash = $this->hash($url);
218
-		$query = $this->connection->getQueryBuilder();
219
-		$query->select('status')->from($this->dbTable)
220
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
221
-			->setParameter('url_hash', $hash);
222
-
223
-		$statement = $query->executeQuery();
224
-		$result = $statement->fetch();
225
-		$statement->closeCursor();
226
-		return (int)$result['status'];
227
-	}
228
-
229
-	/**
230
-	 * Create hash from URL
231
-	 */
232
-	protected function hash(string $url): string {
233
-		$normalized = $this->normalizeUrl($url);
234
-		return sha1($normalized);
235
-	}
236
-
237
-	/**
238
-	 * Normalize URL, used to create the sha1 hash
239
-	 */
240
-	protected function normalizeUrl(string $url): string {
241
-		$normalized = $url;
242
-
243
-		if (strpos($url, 'https://') === 0) {
244
-			$normalized = substr($url, strlen('https://'));
245
-		} elseif (strpos($url, 'http://') === 0) {
246
-			$normalized = substr($url, strlen('http://'));
247
-		}
248
-
249
-		$normalized = Filesystem::normalizePath($normalized);
250
-		$normalized = trim($normalized, '/');
251
-
252
-		return $normalized;
253
-	}
254
-
255
-	public function auth(string $username, string $password): bool {
256
-		if ($username !== 'system') {
257
-			return false;
258
-		}
259
-		$query = $this->connection->getQueryBuilder();
260
-		$query->select('url')->from($this->dbTable)
261
-			->where($query->expr()->eq('shared_secret', $query->createNamedParameter($password)));
262
-
263
-		$statement = $query->executeQuery();
264
-		$result = $statement->fetch();
265
-		$statement->closeCursor();
266
-		return !empty($result);
267
-	}
28
+    private string $dbTable = 'trusted_servers';
29
+
30
+    public function __construct(
31
+        private IDBConnection $connection,
32
+        private IL10N $IL10N,
33
+    ) {
34
+    }
35
+
36
+    /**
37
+     * Add server to the list of trusted servers
38
+     *
39
+     * @throws HintException
40
+     */
41
+    public function addServer(string $url): int {
42
+        $hash = $this->hash($url);
43
+        $url = rtrim($url, '/');
44
+        $query = $this->connection->getQueryBuilder();
45
+        $query->insert($this->dbTable)
46
+            ->values([
47
+                'url' => $query->createParameter('url'),
48
+                'url_hash' => $query->createParameter('url_hash'),
49
+            ])
50
+            ->setParameter('url', $url)
51
+            ->setParameter('url_hash', $hash);
52
+
53
+        $result = $query->executeStatement();
54
+
55
+        if ($result) {
56
+            return $query->getLastInsertId();
57
+        }
58
+
59
+        $message = 'Internal failure, Could not add trusted server: ' . $url;
60
+        $message_t = $this->IL10N->t('Could not add server');
61
+        throw new HintException($message, $message_t);
62
+        return -1;
63
+    }
64
+
65
+    /**
66
+     * Remove server from the list of trusted servers
67
+     */
68
+    public function removeServer(int $id): void {
69
+        $query = $this->connection->getQueryBuilder();
70
+        $query->delete($this->dbTable)
71
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
72
+            ->setParameter('id', $id);
73
+        $query->executeStatement();
74
+    }
75
+
76
+    /**
77
+     * Get trusted server with given ID
78
+     *
79
+     * @return array{id: int, url: string, url_hash: string, token: ?string, shared_secret: ?string, status: int, sync_token: ?string}
80
+     * @throws \Exception
81
+     */
82
+    public function getServerById(int $id): array {
83
+        $query = $this->connection->getQueryBuilder();
84
+        $query->select('*')->from($this->dbTable)
85
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
86
+            ->setParameter('id', $id, IQueryBuilder::PARAM_INT);
87
+
88
+        $qResult = $query->executeQuery();
89
+        $result = $qResult->fetchAll();
90
+        $qResult->closeCursor();
91
+
92
+        if (empty($result)) {
93
+            throw new \Exception('No Server found with ID: ' . $id);
94
+        }
95
+
96
+        return $result[0];
97
+    }
98
+
99
+    /**
100
+     * Get all trusted servers
101
+     *
102
+     * @return list<array{id: int, url: string, url_hash: string, shared_secret: ?string, status: int, sync_token: ?string}>
103
+     * @throws DBException
104
+     */
105
+    public function getAllServer(): array {
106
+        $query = $this->connection->getQueryBuilder();
107
+        $query->select(['url', 'url_hash', 'id', 'status', 'shared_secret', 'sync_token'])
108
+            ->from($this->dbTable);
109
+        $statement = $query->executeQuery();
110
+        $result = $statement->fetchAll();
111
+        $statement->closeCursor();
112
+        return $result;
113
+    }
114
+
115
+    /**
116
+     * Check if server already exists in the database table
117
+     */
118
+    public function serverExists(string $url): bool {
119
+        $hash = $this->hash($url);
120
+        $query = $this->connection->getQueryBuilder();
121
+        $query->select('url')
122
+            ->from($this->dbTable)
123
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
124
+            ->setParameter('url_hash', $hash);
125
+        $statement = $query->executeQuery();
126
+        $result = $statement->fetchAll();
127
+        $statement->closeCursor();
128
+
129
+        return !empty($result);
130
+    }
131
+
132
+    /**
133
+     * Write token to database. Token is used to exchange the secret
134
+     */
135
+    public function addToken(string $url, string $token): void {
136
+        $hash = $this->hash($url);
137
+        $query = $this->connection->getQueryBuilder();
138
+        $query->update($this->dbTable)
139
+            ->set('token', $query->createParameter('token'))
140
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
141
+            ->setParameter('url_hash', $hash)
142
+            ->setParameter('token', $token);
143
+        $query->executeStatement();
144
+    }
145
+
146
+    /**
147
+     * Get token stored in database
148
+     * @throws \Exception
149
+     */
150
+    public function getToken(string $url): string {
151
+        $hash = $this->hash($url);
152
+        $query = $this->connection->getQueryBuilder();
153
+        $query->select('token')->from($this->dbTable)
154
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
155
+            ->setParameter('url_hash', $hash);
156
+
157
+        $statement = $query->executeQuery();
158
+        $result = $statement->fetch();
159
+        $statement->closeCursor();
160
+
161
+        if (!isset($result['token'])) {
162
+            throw new \Exception('No token found for: ' . $url);
163
+        }
164
+
165
+        return $result['token'];
166
+    }
167
+
168
+    /**
169
+     * Add shared Secret to database
170
+     */
171
+    public function addSharedSecret(string $url, string $sharedSecret): void {
172
+        $hash = $this->hash($url);
173
+        $query = $this->connection->getQueryBuilder();
174
+        $query->update($this->dbTable)
175
+            ->set('shared_secret', $query->createParameter('sharedSecret'))
176
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
177
+            ->setParameter('url_hash', $hash)
178
+            ->setParameter('sharedSecret', $sharedSecret);
179
+        $query->executeStatement();
180
+    }
181
+
182
+    /**
183
+     * Get shared secret from database
184
+     */
185
+    public function getSharedSecret(string $url): string {
186
+        $hash = $this->hash($url);
187
+        $query = $this->connection->getQueryBuilder();
188
+        $query->select('shared_secret')->from($this->dbTable)
189
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
190
+            ->setParameter('url_hash', $hash);
191
+
192
+        $statement = $query->executeQuery();
193
+        $result = $statement->fetch();
194
+        $statement->closeCursor();
195
+        return (string)$result['shared_secret'];
196
+    }
197
+
198
+    /**
199
+     * Set server status
200
+     */
201
+    public function setServerStatus(string $url, int $status, ?string $token = null): void {
202
+        $hash = $this->hash($url);
203
+        $query = $this->connection->getQueryBuilder();
204
+        $query->update($this->dbTable)
205
+            ->set('status', $query->createNamedParameter($status))
206
+            ->where($query->expr()->eq('url_hash', $query->createNamedParameter($hash)));
207
+        if (!is_null($token)) {
208
+            $query->set('sync_token', $query->createNamedParameter($token));
209
+        }
210
+        $query->executeStatement();
211
+    }
212
+
213
+    /**
214
+     * Get server status
215
+     */
216
+    public function getServerStatus(string $url): int {
217
+        $hash = $this->hash($url);
218
+        $query = $this->connection->getQueryBuilder();
219
+        $query->select('status')->from($this->dbTable)
220
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
221
+            ->setParameter('url_hash', $hash);
222
+
223
+        $statement = $query->executeQuery();
224
+        $result = $statement->fetch();
225
+        $statement->closeCursor();
226
+        return (int)$result['status'];
227
+    }
228
+
229
+    /**
230
+     * Create hash from URL
231
+     */
232
+    protected function hash(string $url): string {
233
+        $normalized = $this->normalizeUrl($url);
234
+        return sha1($normalized);
235
+    }
236
+
237
+    /**
238
+     * Normalize URL, used to create the sha1 hash
239
+     */
240
+    protected function normalizeUrl(string $url): string {
241
+        $normalized = $url;
242
+
243
+        if (strpos($url, 'https://') === 0) {
244
+            $normalized = substr($url, strlen('https://'));
245
+        } elseif (strpos($url, 'http://') === 0) {
246
+            $normalized = substr($url, strlen('http://'));
247
+        }
248
+
249
+        $normalized = Filesystem::normalizePath($normalized);
250
+        $normalized = trim($normalized, '/');
251
+
252
+        return $normalized;
253
+    }
254
+
255
+    public function auth(string $username, string $password): bool {
256
+        if ($username !== 'system') {
257
+            return false;
258
+        }
259
+        $query = $this->connection->getQueryBuilder();
260
+        $query->select('url')->from($this->dbTable)
261
+            ->where($query->expr()->eq('shared_secret', $query->createNamedParameter($password)));
262
+
263
+        $statement = $query->executeQuery();
264
+        $result = $statement->fetch();
265
+        $statement->closeCursor();
266
+        return !empty($result);
267
+    }
268 268
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/ExpireSharesJob.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -87,13 +87,13 @@
 block discarded – undo
87 87
 
88 88
 		$shares = $qb->executeQuery();
89 89
 		while ($share = $shares->fetch()) {
90
-			if ((int)$share['share_type'] === IShare::TYPE_LINK) {
90
+			if ((int) $share['share_type'] === IShare::TYPE_LINK) {
91 91
 				$id = 'ocinternal';
92
-			} elseif ((int)$share['share_type'] === IShare::TYPE_EMAIL) {
92
+			} elseif ((int) $share['share_type'] === IShare::TYPE_EMAIL) {
93 93
 				$id = 'ocMailShare';
94 94
 			}
95 95
 
96
-			$id .= ':' . $share['id'];
96
+			$id .= ':'.$share['id'];
97 97
 
98 98
 			try {
99 99
 				$share = $this->shareManager->getShareById($id);
Please login to merge, or discard this patch.
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -19,60 +19,60 @@
 block discarded – undo
19 19
  */
20 20
 class ExpireSharesJob extends TimedJob {
21 21
 
22
-	public function __construct(
23
-		ITimeFactory $time,
24
-		private IManager $shareManager,
25
-		private IDBConnection $db,
26
-	) {
27
-		parent::__construct($time);
22
+    public function __construct(
23
+        ITimeFactory $time,
24
+        private IManager $shareManager,
25
+        private IDBConnection $db,
26
+    ) {
27
+        parent::__construct($time);
28 28
 
29
-		// Run once a day
30
-		$this->setInterval(24 * 60 * 60);
31
-		$this->setTimeSensitivity(self::TIME_INSENSITIVE);
32
-	}
29
+        // Run once a day
30
+        $this->setInterval(24 * 60 * 60);
31
+        $this->setTimeSensitivity(self::TIME_INSENSITIVE);
32
+    }
33 33
 
34 34
 
35
-	/**
36
-	 * Makes the background job do its work
37
-	 *
38
-	 * @param array $argument unused argument
39
-	 */
40
-	public function run($argument) {
41
-		//Current time
42
-		$now = new \DateTime();
43
-		$now = $now->format('Y-m-d H:i:s');
35
+    /**
36
+     * Makes the background job do its work
37
+     *
38
+     * @param array $argument unused argument
39
+     */
40
+    public function run($argument) {
41
+        //Current time
42
+        $now = new \DateTime();
43
+        $now = $now->format('Y-m-d H:i:s');
44 44
 
45
-		/*
45
+        /*
46 46
 		 * Expire file link shares only (for now)
47 47
 		 */
48
-		$qb = $this->db->getQueryBuilder();
49
-		$qb->select('id', 'share_type')
50
-			->from('share')
51
-			->where(
52
-				$qb->expr()->andX(
53
-					$qb->expr()->in('share_type', $qb->createNamedParameter([IShare::TYPE_LINK, IShare::TYPE_EMAIL], IQueryBuilder::PARAM_INT_ARRAY)),
54
-					$qb->expr()->lte('expiration', $qb->expr()->literal($now)),
55
-					$qb->expr()->in('item_type', $qb->createNamedParameter(['file', 'folder'], IQueryBuilder::PARAM_STR_ARRAY))
56
-				)
57
-			);
48
+        $qb = $this->db->getQueryBuilder();
49
+        $qb->select('id', 'share_type')
50
+            ->from('share')
51
+            ->where(
52
+                $qb->expr()->andX(
53
+                    $qb->expr()->in('share_type', $qb->createNamedParameter([IShare::TYPE_LINK, IShare::TYPE_EMAIL], IQueryBuilder::PARAM_INT_ARRAY)),
54
+                    $qb->expr()->lte('expiration', $qb->expr()->literal($now)),
55
+                    $qb->expr()->in('item_type', $qb->createNamedParameter(['file', 'folder'], IQueryBuilder::PARAM_STR_ARRAY))
56
+                )
57
+            );
58 58
 
59
-		$shares = $qb->executeQuery();
60
-		while ($share = $shares->fetch()) {
61
-			if ((int)$share['share_type'] === IShare::TYPE_LINK) {
62
-				$id = 'ocinternal';
63
-			} elseif ((int)$share['share_type'] === IShare::TYPE_EMAIL) {
64
-				$id = 'ocMailShare';
65
-			}
59
+        $shares = $qb->executeQuery();
60
+        while ($share = $shares->fetch()) {
61
+            if ((int)$share['share_type'] === IShare::TYPE_LINK) {
62
+                $id = 'ocinternal';
63
+            } elseif ((int)$share['share_type'] === IShare::TYPE_EMAIL) {
64
+                $id = 'ocMailShare';
65
+            }
66 66
 
67
-			$id .= ':' . $share['id'];
67
+            $id .= ':' . $share['id'];
68 68
 
69
-			try {
70
-				$share = $this->shareManager->getShareById($id);
71
-				$this->shareManager->deleteShare($share);
72
-			} catch (ShareNotFound $e) {
73
-				// Normally the share gets automatically expired on fetching it
74
-			}
75
-		}
76
-		$shares->closeCursor();
77
-	}
69
+            try {
70
+                $share = $this->shareManager->getShareById($id);
71
+                $this->shareManager->deleteShare($share);
72
+            } catch (ShareNotFound $e) {
73
+                // Normally the share gets automatically expired on fetching it
74
+            }
75
+        }
76
+        $shares->closeCursor();
77
+    }
78 78
 }
Please login to merge, or discard this patch.
apps/files/templates/list.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
 	<?php if (isset($_['dirToken'])):?>
16 16
 	<input type="hidden" id="publicUploadRequestToken" name="requesttoken" value="<?php p($_['requesttoken']) ?>" />
17 17
 	<input type="hidden" id="dirToken" name="dirToken" value="<?php p($_['dirToken']) ?>" />
18
-	<?php endif;?>
18
+	<?php endif; ?>
19 19
 	<input type="hidden" class="max_human_file_size"
20 20
 		   value="(max <?php isset($_['uploadMaxHumanFilesize']) ? p($_['uploadMaxHumanFilesize']) : ''; ?>)">
21 21
 </div>
@@ -75,6 +75,6 @@  discard block
 block discarded – undo
75 75
 </div>
76 76
 <div id="uploadsize-message" title="<?php p($l->t('Upload too large'))?>">
77 77
 	<p>
78
-	<?php p($l->t('The files you are trying to upload exceed the maximum size for file uploads on this server.'));?>
78
+	<?php p($l->t('The files you are trying to upload exceed the maximum size for file uploads on this server.')); ?>
79 79
 	</p>
80 80
 </div>
Please login to merge, or discard this patch.
apps/dav/templates/schedule-response-success.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -5,5 +5,5 @@
 block discarded – undo
5 5
 ?>
6 6
 <div class="guest-box">
7 7
 	<div class="icon icon-checkmark"></div>
8
-	<p class="message"><?php p($l->t('Your attendance was updated successfully.'));?></p>
8
+	<p class="message"><?php p($l->t('Your attendance was updated successfully.')); ?></p>
9 9
 </div>
Please login to merge, or discard this patch.
apps/dav/templates/schedule-response-error.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -6,8 +6,8 @@
 block discarded – undo
6 6
 ?>
7 7
 <div class="guest-box">
8 8
 	<div class="notecard error">
9
-		<p><?php p($l->t('There was an error updating your attendance status.'));?></p>
10
-		<p><?php p($l->t('Please contact the organizer directly.'));?></p>
9
+		<p><?php p($l->t('There was an error updating your attendance status.')); ?></p>
10
+		<p><?php p($l->t('Please contact the organizer directly.')); ?></p>
11 11
 		<?php if (isset($_['organizer'])): ?>
12 12
 			<p><a href="<?php p($_['organizer']) ?>"><?php p(substr($_['organizer'], 7)) ?></a></p>
13 13
 		<?php endif; ?>
Please login to merge, or discard this patch.
apps/dav/lib/Migration/Version1024Date20211221144219.php 1 patch
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -17,42 +17,42 @@
 block discarded – undo
17 17
  */
18 18
 class Version1024Date20211221144219 extends SimpleMigrationStep {
19 19
 
20
-	/**
21
-	 * @param IOutput $output
22
-	 * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
23
-	 * @param array $options
24
-	 */
25
-	public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
26
-	}
27
-
28
-	/**
29
-	 * @param IOutput $output
30
-	 * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
31
-	 * @param array $options
32
-	 * @return null|ISchemaWrapper
33
-	 * @throws SchemaException
34
-	 */
35
-	public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
36
-		/** @var ISchemaWrapper $schema */
37
-		$schema = $schemaClosure();
38
-		$propertiesTable = $schema->getTable('properties');
39
-
40
-		if ($propertiesTable->hasColumn('valuetype')) {
41
-			return null;
42
-		}
43
-		$propertiesTable->addColumn('valuetype', Types::SMALLINT, [
44
-			'notnull' => false,
45
-			'default' => CustomPropertiesBackend::PROPERTY_TYPE_STRING
46
-		]);
47
-
48
-		return $schema;
49
-	}
50
-
51
-	/**
52
-	 * @param IOutput $output
53
-	 * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
54
-	 * @param array $options
55
-	 */
56
-	public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
57
-	}
20
+    /**
21
+     * @param IOutput $output
22
+     * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
23
+     * @param array $options
24
+     */
25
+    public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
26
+    }
27
+
28
+    /**
29
+     * @param IOutput $output
30
+     * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
31
+     * @param array $options
32
+     * @return null|ISchemaWrapper
33
+     * @throws SchemaException
34
+     */
35
+    public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
36
+        /** @var ISchemaWrapper $schema */
37
+        $schema = $schemaClosure();
38
+        $propertiesTable = $schema->getTable('properties');
39
+
40
+        if ($propertiesTable->hasColumn('valuetype')) {
41
+            return null;
42
+        }
43
+        $propertiesTable->addColumn('valuetype', Types::SMALLINT, [
44
+            'notnull' => false,
45
+            'default' => CustomPropertiesBackend::PROPERTY_TYPE_STRING
46
+        ]);
47
+
48
+        return $schema;
49
+    }
50
+
51
+    /**
52
+     * @param IOutput $output
53
+     * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
54
+     * @param array $options
55
+     */
56
+    public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
57
+    }
58 58
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/PublicCalendar.php 1 patch
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -28,63 +28,63 @@
 block discarded – undo
28 28
 
29 29
 class PublicCalendar extends Calendar {
30 30
 
31
-	/**
32
-	 * @param string $name
33
-	 * @throws NotFound
34
-	 * @return PublicCalendarObject
35
-	 */
36
-	public function getChild($name) {
37
-		$obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
31
+    /**
32
+     * @param string $name
33
+     * @throws NotFound
34
+     * @return PublicCalendarObject
35
+     */
36
+    public function getChild($name) {
37
+        $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
38 38
 
39
-		if (!$obj) {
40
-			throw new NotFound('Calendar object not found');
41
-		}
42
-		if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
43
-			throw new NotFound('Calendar object not found');
44
-		}
45
-		$obj['acl'] = $this->getChildACL();
39
+        if (!$obj) {
40
+            throw new NotFound('Calendar object not found');
41
+        }
42
+        if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
43
+            throw new NotFound('Calendar object not found');
44
+        }
45
+        $obj['acl'] = $this->getChildACL();
46 46
 
47
-		return new PublicCalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
48
-	}
47
+        return new PublicCalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
48
+    }
49 49
 
50
-	/**
51
-	 * @return PublicCalendarObject[]
52
-	 */
53
-	public function getChildren() {
54
-		$objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']);
55
-		$children = [];
56
-		foreach ($objs as $obj) {
57
-			if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
58
-				continue;
59
-			}
60
-			$obj['acl'] = $this->getChildACL();
61
-			$children[] = new PublicCalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
62
-		}
63
-		return $children;
64
-	}
50
+    /**
51
+     * @return PublicCalendarObject[]
52
+     */
53
+    public function getChildren() {
54
+        $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']);
55
+        $children = [];
56
+        foreach ($objs as $obj) {
57
+            if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
58
+                continue;
59
+            }
60
+            $obj['acl'] = $this->getChildACL();
61
+            $children[] = new PublicCalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
62
+        }
63
+        return $children;
64
+    }
65 65
 
66
-	/**
67
-	 * @param string[] $paths
68
-	 * @return PublicCalendarObject[]
69
-	 */
70
-	public function getMultipleChildren(array $paths) {
71
-		$objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths);
72
-		$children = [];
73
-		foreach ($objs as $obj) {
74
-			if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
75
-				continue;
76
-			}
77
-			$obj['acl'] = $this->getChildACL();
78
-			$children[] = new PublicCalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
79
-		}
80
-		return $children;
81
-	}
66
+    /**
67
+     * @param string[] $paths
68
+     * @return PublicCalendarObject[]
69
+     */
70
+    public function getMultipleChildren(array $paths) {
71
+        $objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths);
72
+        $children = [];
73
+        foreach ($objs as $obj) {
74
+            if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
75
+                continue;
76
+            }
77
+            $obj['acl'] = $this->getChildACL();
78
+            $children[] = new PublicCalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
79
+        }
80
+        return $children;
81
+    }
82 82
 
83
-	/**
84
-	 * public calendars are always shared
85
-	 * @return bool
86
-	 */
87
-	public function isShared() {
88
-		return true;
89
-	}
83
+    /**
84
+     * public calendars are always shared
85
+     * @return bool
86
+     */
87
+    public function isShared() {
88
+        return true;
89
+    }
90 90
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Reminder/Notifier.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -263,10 +263,10 @@  discard block
 block discarded – undo
263 263
 			]);
264 264
 
265 265
 			return $localeStart
266
-				. ' (' . $startTimezone . ') '
266
+				. ' ('.$startTimezone.') '
267 267
 				. ' - '
268 268
 				. $localeEnd
269
-				. ' (' . $endTimezone . ')';
269
+				. ' ('.$endTimezone.')';
270 270
 		}
271 271
 
272 272
 		// Show only the time if the day is the same
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 		return $localeStart
281 281
 			. ' - '
282 282
 			. $localeEnd
283
-			. ' (' . $startTimezone . ')';
283
+			. ' ('.$startTimezone.')';
284 284
 	}
285 285
 
286 286
 	/**
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
 	 * @return string
299 299
 	 */
300 300
 	private function getWeekDayName(DateTime $dt):string {
301
-		return (string)$this->l10n->l('weekdayName', $dt, ['width' => 'abbreviated']);
301
+		return (string) $this->l10n->l('weekdayName', $dt, ['width' => 'abbreviated']);
302 302
 	}
303 303
 
304 304
 	/**
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
 	 * @return string
307 307
 	 */
308 308
 	private function getDateString(DateTime $dt):string {
309
-		return (string)$this->l10n->l('date', $dt, ['width' => 'medium']);
309
+		return (string) $this->l10n->l('date', $dt, ['width' => 'medium']);
310 310
 	}
311 311
 
312 312
 	/**
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 	 * @return string
315 315
 	 */
316 316
 	private function getDateTimeString(DateTime $dt):string {
317
-		return (string)$this->l10n->l('datetime', $dt, ['width' => 'medium|short']);
317
+		return (string) $this->l10n->l('datetime', $dt, ['width' => 'medium|short']);
318 318
 	}
319 319
 
320 320
 	/**
@@ -322,6 +322,6 @@  discard block
 block discarded – undo
322 322
 	 * @return string
323 323
 	 */
324 324
 	private function getTimeString(DateTime $dt):string {
325
-		return (string)$this->l10n->l('time', $dt, ['width' => 'short']);
325
+		return (string) $this->l10n->l('time', $dt, ['width' => 'short']);
326 326
 	}
327 327
 }
Please login to merge, or discard this patch.
Indentation   +282 added lines, -282 removed lines patch added patch discarded remove patch
@@ -26,286 +26,286 @@
 block discarded – undo
26 26
  */
27 27
 class Notifier implements INotifier {
28 28
 
29
-	/** @var IL10N */
30
-	private $l10n;
31
-
32
-	/**
33
-	 * Notifier constructor.
34
-	 *
35
-	 * @param IFactory $l10nFactory
36
-	 * @param IURLGenerator $urlGenerator
37
-	 * @param ITimeFactory $timeFactory
38
-	 */
39
-	public function __construct(
40
-		private IFactory $l10nFactory,
41
-		private IURLGenerator $urlGenerator,
42
-		private ITimeFactory $timeFactory,
43
-	) {
44
-	}
45
-
46
-	/**
47
-	 * Identifier of the notifier, only use [a-z0-9_]
48
-	 *
49
-	 * @return string
50
-	 * @since 17.0.0
51
-	 */
52
-	public function getID():string {
53
-		return Application::APP_ID;
54
-	}
55
-
56
-	/**
57
-	 * Human readable name describing the notifier
58
-	 *
59
-	 * @return string
60
-	 * @since 17.0.0
61
-	 */
62
-	public function getName():string {
63
-		return $this->l10nFactory->get('dav')->t('Calendar');
64
-	}
65
-
66
-	/**
67
-	 * Prepare sending the notification
68
-	 *
69
-	 * @param INotification $notification
70
-	 * @param string $languageCode The code of the language that should be used to prepare the notification
71
-	 * @return INotification
72
-	 * @throws UnknownNotificationException
73
-	 */
74
-	public function prepare(INotification $notification,
75
-		string $languageCode):INotification {
76
-		if ($notification->getApp() !== Application::APP_ID) {
77
-			throw new UnknownNotificationException('Notification not from this app');
78
-		}
79
-
80
-		// Read the language from the notification
81
-		$this->l10n = $this->l10nFactory->get('dav', $languageCode);
82
-
83
-		// Handle notifier subjects
84
-		switch ($notification->getSubject()) {
85
-			case 'calendar_reminder':
86
-				return $this->prepareReminderNotification($notification);
87
-
88
-			default:
89
-				throw new UnknownNotificationException('Unknown subject');
90
-
91
-		}
92
-	}
93
-
94
-	/**
95
-	 * @param INotification $notification
96
-	 * @return INotification
97
-	 */
98
-	private function prepareReminderNotification(INotification $notification):INotification {
99
-		$imagePath = $this->urlGenerator->imagePath('core', 'places/calendar.svg');
100
-		$iconUrl = $this->urlGenerator->getAbsoluteURL($imagePath);
101
-		$notification->setIcon($iconUrl);
102
-
103
-		$this->prepareNotificationSubject($notification);
104
-		$this->prepareNotificationMessage($notification);
105
-
106
-		return $notification;
107
-	}
108
-
109
-	/**
110
-	 * Sets the notification subject based on the parameters set in PushProvider
111
-	 *
112
-	 * @param INotification $notification
113
-	 */
114
-	private function prepareNotificationSubject(INotification $notification): void {
115
-		$parameters = $notification->getSubjectParameters();
116
-
117
-		$startTime = \DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['start_atom']);
118
-		$now = $this->timeFactory->getDateTime();
119
-		$title = $this->getTitleFromParameters($parameters);
120
-
121
-		$diff = $startTime->diff($now);
122
-		if ($diff === false) {
123
-			return;
124
-		}
125
-
126
-		$components = [];
127
-		if ($diff->y) {
128
-			$components[] = $this->l10n->n('%n year', '%n years', $diff->y);
129
-		}
130
-		if ($diff->m) {
131
-			$components[] = $this->l10n->n('%n month', '%n months', $diff->m);
132
-		}
133
-		if ($diff->d) {
134
-			$components[] = $this->l10n->n('%n day', '%n days', $diff->d);
135
-		}
136
-		if ($diff->h) {
137
-			$components[] = $this->l10n->n('%n hour', '%n hours', $diff->h);
138
-		}
139
-		if ($diff->i) {
140
-			$components[] = $this->l10n->n('%n minute', '%n minutes', $diff->i);
141
-		}
142
-
143
-		if (count($components) > 0 && !$this->hasPhpDatetimeDiffBug()) {
144
-			// Limiting to the first three components to prevent
145
-			// the string from getting too long
146
-			$firstThreeComponents = array_slice($components, 0, 2);
147
-			$diffLabel = implode(', ', $firstThreeComponents);
148
-
149
-			if ($diff->invert) {
150
-				$title = $this->l10n->t('%s (in %s)', [$title, $diffLabel]);
151
-			} else {
152
-				$title = $this->l10n->t('%s (%s ago)', [$title, $diffLabel]);
153
-			}
154
-		}
155
-
156
-		$notification->setParsedSubject($title);
157
-	}
158
-
159
-	/**
160
-	 * @see https://github.com/nextcloud/server/issues/41615
161
-	 * @see https://github.com/php/php-src/issues/9699
162
-	 */
163
-	private function hasPhpDatetimeDiffBug(): bool {
164
-		$d1 = DateTime::createFromFormat(\DateTimeInterface::ATOM, '2023-11-22T11:52:00+01:00');
165
-		$d2 = new DateTime('2023-11-22T10:52:03', new \DateTimeZone('UTC'));
166
-
167
-		// The difference is 3 seconds, not -1year+11months+…
168
-		return $d1->diff($d2)->y < 0;
169
-	}
170
-
171
-	/**
172
-	 * Sets the notification message based on the parameters set in PushProvider
173
-	 *
174
-	 * @param INotification $notification
175
-	 */
176
-	private function prepareNotificationMessage(INotification $notification): void {
177
-		$parameters = $notification->getMessageParameters();
178
-
179
-		$description = [
180
-			$this->l10n->t('Calendar: %s', $parameters['calendar_displayname']),
181
-			$this->l10n->t('Date: %s', $this->generateDateString($parameters)),
182
-		];
183
-		if ($parameters['description']) {
184
-			$description[] = $this->l10n->t('Description: %s', $parameters['description']);
185
-		}
186
-		if ($parameters['location']) {
187
-			$description[] = $this->l10n->t('Where: %s', $parameters['location']);
188
-		}
189
-
190
-		$message = implode("\r\n", $description);
191
-		$notification->setParsedMessage($message);
192
-	}
193
-
194
-	/**
195
-	 * @param array $parameters
196
-	 * @return string
197
-	 */
198
-	private function getTitleFromParameters(array $parameters):string {
199
-		return $parameters['title'] ?? $this->l10n->t('Untitled event');
200
-	}
201
-
202
-	/**
203
-	 * @param array $parameters
204
-	 * @return string
205
-	 * @throws \Exception
206
-	 */
207
-	private function generateDateString(array $parameters):string {
208
-		$startDateTime = DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['start_atom']);
209
-		$endDateTime = DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['end_atom']);
210
-
211
-		// If the event has already ended, dismiss the notification
212
-		if ($endDateTime < $this->timeFactory->getDateTime()) {
213
-			throw new AlreadyProcessedException();
214
-		}
215
-
216
-		$isAllDay = $parameters['all_day'];
217
-		$diff = $startDateTime->diff($endDateTime);
218
-
219
-		if ($isAllDay) {
220
-			// One day event
221
-			if ($diff->days === 1) {
222
-				return $this->getDateString($startDateTime);
223
-			}
224
-
225
-			return implode(' - ', [
226
-				$this->getDateString($startDateTime),
227
-				$this->getDateString($endDateTime),
228
-			]);
229
-		}
230
-
231
-		$startTimezone = $endTimezone = null;
232
-		if (!$parameters['start_is_floating']) {
233
-			$startTimezone = $parameters['start_timezone'];
234
-			$endTimezone = $parameters['end_timezone'];
235
-		}
236
-
237
-		$localeStart = implode(', ', [
238
-			$this->getWeekDayName($startDateTime),
239
-			$this->getDateTimeString($startDateTime)
240
-		]);
241
-
242
-		// always show full date with timezone if timezones are different
243
-		if ($startTimezone !== $endTimezone) {
244
-			$localeEnd = implode(', ', [
245
-				$this->getWeekDayName($endDateTime),
246
-				$this->getDateTimeString($endDateTime)
247
-			]);
248
-
249
-			return $localeStart
250
-				. ' (' . $startTimezone . ') '
251
-				. ' - '
252
-				. $localeEnd
253
-				. ' (' . $endTimezone . ')';
254
-		}
255
-
256
-		// Show only the time if the day is the same
257
-		$localeEnd = $this->isDayEqual($startDateTime, $endDateTime)
258
-			? $this->getTimeString($endDateTime)
259
-			: implode(', ', [
260
-				$this->getWeekDayName($endDateTime),
261
-				$this->getDateTimeString($endDateTime)
262
-			]);
263
-
264
-		return $localeStart
265
-			. ' - '
266
-			. $localeEnd
267
-			. ' (' . $startTimezone . ')';
268
-	}
269
-
270
-	/**
271
-	 * @param DateTime $dtStart
272
-	 * @param DateTime $dtEnd
273
-	 * @return bool
274
-	 */
275
-	private function isDayEqual(DateTime $dtStart,
276
-		DateTime $dtEnd):bool {
277
-		return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
278
-	}
279
-
280
-	/**
281
-	 * @param DateTime $dt
282
-	 * @return string
283
-	 */
284
-	private function getWeekDayName(DateTime $dt):string {
285
-		return (string)$this->l10n->l('weekdayName', $dt, ['width' => 'abbreviated']);
286
-	}
287
-
288
-	/**
289
-	 * @param DateTime $dt
290
-	 * @return string
291
-	 */
292
-	private function getDateString(DateTime $dt):string {
293
-		return (string)$this->l10n->l('date', $dt, ['width' => 'medium']);
294
-	}
295
-
296
-	/**
297
-	 * @param DateTime $dt
298
-	 * @return string
299
-	 */
300
-	private function getDateTimeString(DateTime $dt):string {
301
-		return (string)$this->l10n->l('datetime', $dt, ['width' => 'medium|short']);
302
-	}
303
-
304
-	/**
305
-	 * @param DateTime $dt
306
-	 * @return string
307
-	 */
308
-	private function getTimeString(DateTime $dt):string {
309
-		return (string)$this->l10n->l('time', $dt, ['width' => 'short']);
310
-	}
29
+    /** @var IL10N */
30
+    private $l10n;
31
+
32
+    /**
33
+     * Notifier constructor.
34
+     *
35
+     * @param IFactory $l10nFactory
36
+     * @param IURLGenerator $urlGenerator
37
+     * @param ITimeFactory $timeFactory
38
+     */
39
+    public function __construct(
40
+        private IFactory $l10nFactory,
41
+        private IURLGenerator $urlGenerator,
42
+        private ITimeFactory $timeFactory,
43
+    ) {
44
+    }
45
+
46
+    /**
47
+     * Identifier of the notifier, only use [a-z0-9_]
48
+     *
49
+     * @return string
50
+     * @since 17.0.0
51
+     */
52
+    public function getID():string {
53
+        return Application::APP_ID;
54
+    }
55
+
56
+    /**
57
+     * Human readable name describing the notifier
58
+     *
59
+     * @return string
60
+     * @since 17.0.0
61
+     */
62
+    public function getName():string {
63
+        return $this->l10nFactory->get('dav')->t('Calendar');
64
+    }
65
+
66
+    /**
67
+     * Prepare sending the notification
68
+     *
69
+     * @param INotification $notification
70
+     * @param string $languageCode The code of the language that should be used to prepare the notification
71
+     * @return INotification
72
+     * @throws UnknownNotificationException
73
+     */
74
+    public function prepare(INotification $notification,
75
+        string $languageCode):INotification {
76
+        if ($notification->getApp() !== Application::APP_ID) {
77
+            throw new UnknownNotificationException('Notification not from this app');
78
+        }
79
+
80
+        // Read the language from the notification
81
+        $this->l10n = $this->l10nFactory->get('dav', $languageCode);
82
+
83
+        // Handle notifier subjects
84
+        switch ($notification->getSubject()) {
85
+            case 'calendar_reminder':
86
+                return $this->prepareReminderNotification($notification);
87
+
88
+            default:
89
+                throw new UnknownNotificationException('Unknown subject');
90
+
91
+        }
92
+    }
93
+
94
+    /**
95
+     * @param INotification $notification
96
+     * @return INotification
97
+     */
98
+    private function prepareReminderNotification(INotification $notification):INotification {
99
+        $imagePath = $this->urlGenerator->imagePath('core', 'places/calendar.svg');
100
+        $iconUrl = $this->urlGenerator->getAbsoluteURL($imagePath);
101
+        $notification->setIcon($iconUrl);
102
+
103
+        $this->prepareNotificationSubject($notification);
104
+        $this->prepareNotificationMessage($notification);
105
+
106
+        return $notification;
107
+    }
108
+
109
+    /**
110
+     * Sets the notification subject based on the parameters set in PushProvider
111
+     *
112
+     * @param INotification $notification
113
+     */
114
+    private function prepareNotificationSubject(INotification $notification): void {
115
+        $parameters = $notification->getSubjectParameters();
116
+
117
+        $startTime = \DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['start_atom']);
118
+        $now = $this->timeFactory->getDateTime();
119
+        $title = $this->getTitleFromParameters($parameters);
120
+
121
+        $diff = $startTime->diff($now);
122
+        if ($diff === false) {
123
+            return;
124
+        }
125
+
126
+        $components = [];
127
+        if ($diff->y) {
128
+            $components[] = $this->l10n->n('%n year', '%n years', $diff->y);
129
+        }
130
+        if ($diff->m) {
131
+            $components[] = $this->l10n->n('%n month', '%n months', $diff->m);
132
+        }
133
+        if ($diff->d) {
134
+            $components[] = $this->l10n->n('%n day', '%n days', $diff->d);
135
+        }
136
+        if ($diff->h) {
137
+            $components[] = $this->l10n->n('%n hour', '%n hours', $diff->h);
138
+        }
139
+        if ($diff->i) {
140
+            $components[] = $this->l10n->n('%n minute', '%n minutes', $diff->i);
141
+        }
142
+
143
+        if (count($components) > 0 && !$this->hasPhpDatetimeDiffBug()) {
144
+            // Limiting to the first three components to prevent
145
+            // the string from getting too long
146
+            $firstThreeComponents = array_slice($components, 0, 2);
147
+            $diffLabel = implode(', ', $firstThreeComponents);
148
+
149
+            if ($diff->invert) {
150
+                $title = $this->l10n->t('%s (in %s)', [$title, $diffLabel]);
151
+            } else {
152
+                $title = $this->l10n->t('%s (%s ago)', [$title, $diffLabel]);
153
+            }
154
+        }
155
+
156
+        $notification->setParsedSubject($title);
157
+    }
158
+
159
+    /**
160
+     * @see https://github.com/nextcloud/server/issues/41615
161
+     * @see https://github.com/php/php-src/issues/9699
162
+     */
163
+    private function hasPhpDatetimeDiffBug(): bool {
164
+        $d1 = DateTime::createFromFormat(\DateTimeInterface::ATOM, '2023-11-22T11:52:00+01:00');
165
+        $d2 = new DateTime('2023-11-22T10:52:03', new \DateTimeZone('UTC'));
166
+
167
+        // The difference is 3 seconds, not -1year+11months+…
168
+        return $d1->diff($d2)->y < 0;
169
+    }
170
+
171
+    /**
172
+     * Sets the notification message based on the parameters set in PushProvider
173
+     *
174
+     * @param INotification $notification
175
+     */
176
+    private function prepareNotificationMessage(INotification $notification): void {
177
+        $parameters = $notification->getMessageParameters();
178
+
179
+        $description = [
180
+            $this->l10n->t('Calendar: %s', $parameters['calendar_displayname']),
181
+            $this->l10n->t('Date: %s', $this->generateDateString($parameters)),
182
+        ];
183
+        if ($parameters['description']) {
184
+            $description[] = $this->l10n->t('Description: %s', $parameters['description']);
185
+        }
186
+        if ($parameters['location']) {
187
+            $description[] = $this->l10n->t('Where: %s', $parameters['location']);
188
+        }
189
+
190
+        $message = implode("\r\n", $description);
191
+        $notification->setParsedMessage($message);
192
+    }
193
+
194
+    /**
195
+     * @param array $parameters
196
+     * @return string
197
+     */
198
+    private function getTitleFromParameters(array $parameters):string {
199
+        return $parameters['title'] ?? $this->l10n->t('Untitled event');
200
+    }
201
+
202
+    /**
203
+     * @param array $parameters
204
+     * @return string
205
+     * @throws \Exception
206
+     */
207
+    private function generateDateString(array $parameters):string {
208
+        $startDateTime = DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['start_atom']);
209
+        $endDateTime = DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['end_atom']);
210
+
211
+        // If the event has already ended, dismiss the notification
212
+        if ($endDateTime < $this->timeFactory->getDateTime()) {
213
+            throw new AlreadyProcessedException();
214
+        }
215
+
216
+        $isAllDay = $parameters['all_day'];
217
+        $diff = $startDateTime->diff($endDateTime);
218
+
219
+        if ($isAllDay) {
220
+            // One day event
221
+            if ($diff->days === 1) {
222
+                return $this->getDateString($startDateTime);
223
+            }
224
+
225
+            return implode(' - ', [
226
+                $this->getDateString($startDateTime),
227
+                $this->getDateString($endDateTime),
228
+            ]);
229
+        }
230
+
231
+        $startTimezone = $endTimezone = null;
232
+        if (!$parameters['start_is_floating']) {
233
+            $startTimezone = $parameters['start_timezone'];
234
+            $endTimezone = $parameters['end_timezone'];
235
+        }
236
+
237
+        $localeStart = implode(', ', [
238
+            $this->getWeekDayName($startDateTime),
239
+            $this->getDateTimeString($startDateTime)
240
+        ]);
241
+
242
+        // always show full date with timezone if timezones are different
243
+        if ($startTimezone !== $endTimezone) {
244
+            $localeEnd = implode(', ', [
245
+                $this->getWeekDayName($endDateTime),
246
+                $this->getDateTimeString($endDateTime)
247
+            ]);
248
+
249
+            return $localeStart
250
+                . ' (' . $startTimezone . ') '
251
+                . ' - '
252
+                . $localeEnd
253
+                . ' (' . $endTimezone . ')';
254
+        }
255
+
256
+        // Show only the time if the day is the same
257
+        $localeEnd = $this->isDayEqual($startDateTime, $endDateTime)
258
+            ? $this->getTimeString($endDateTime)
259
+            : implode(', ', [
260
+                $this->getWeekDayName($endDateTime),
261
+                $this->getDateTimeString($endDateTime)
262
+            ]);
263
+
264
+        return $localeStart
265
+            . ' - '
266
+            . $localeEnd
267
+            . ' (' . $startTimezone . ')';
268
+    }
269
+
270
+    /**
271
+     * @param DateTime $dtStart
272
+     * @param DateTime $dtEnd
273
+     * @return bool
274
+     */
275
+    private function isDayEqual(DateTime $dtStart,
276
+        DateTime $dtEnd):bool {
277
+        return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
278
+    }
279
+
280
+    /**
281
+     * @param DateTime $dt
282
+     * @return string
283
+     */
284
+    private function getWeekDayName(DateTime $dt):string {
285
+        return (string)$this->l10n->l('weekdayName', $dt, ['width' => 'abbreviated']);
286
+    }
287
+
288
+    /**
289
+     * @param DateTime $dt
290
+     * @return string
291
+     */
292
+    private function getDateString(DateTime $dt):string {
293
+        return (string)$this->l10n->l('date', $dt, ['width' => 'medium']);
294
+    }
295
+
296
+    /**
297
+     * @param DateTime $dt
298
+     * @return string
299
+     */
300
+    private function getDateTimeString(DateTime $dt):string {
301
+        return (string)$this->l10n->l('datetime', $dt, ['width' => 'medium|short']);
302
+    }
303
+
304
+    /**
305
+     * @param DateTime $dt
306
+     * @return string
307
+     */
308
+    private function getTimeString(DateTime $dt):string {
309
+        return (string)$this->l10n->l('time', $dt, ['width' => 'short']);
310
+    }
311 311
 }
Please login to merge, or discard this patch.
apps/dav/lib/Listener/ActivityUpdaterListener.php 2 patches
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 				);
71 71
 			} catch (Throwable $e) {
72 72
 				// Any error with activities shouldn't abort the calendar creation, so we just log it
73
-				$this->logger->error('Error generating activities for a new calendar: ' . $e->getMessage(), [
73
+				$this->logger->error('Error generating activities for a new calendar: '.$e->getMessage(), [
74 74
 					'exception' => $e,
75 75
 				]);
76 76
 			}
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 				);
88 88
 			} catch (Throwable $e) {
89 89
 				// Any error with activities shouldn't abort the calendar update, so we just log it
90
-				$this->logger->error('Error generating activities for changed calendar: ' . $e->getMessage(), [
90
+				$this->logger->error('Error generating activities for changed calendar: '.$e->getMessage(), [
91 91
 					'exception' => $e,
92 92
 				]);
93 93
 			}
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 				);
104 104
 			} catch (Throwable $e) {
105 105
 				// Any error with activities shouldn't abort the calendar update, so we just log it
106
-				$this->logger->error('Error generating activities for changed calendar: ' . $e->getMessage(), [
106
+				$this->logger->error('Error generating activities for changed calendar: '.$e->getMessage(), [
107 107
 					'exception' => $e,
108 108
 				]);
109 109
 			}
@@ -119,13 +119,13 @@  discard block
 block discarded – undo
119 119
 				);
120 120
 			} catch (Throwable $e) {
121 121
 				// Any error with activities shouldn't abort the calendar update, so we just log it
122
-				$this->logger->error('Error generating activities for changed calendar: ' . $e->getMessage(), [
122
+				$this->logger->error('Error generating activities for changed calendar: '.$e->getMessage(), [
123 123
 					'exception' => $e,
124 124
 				]);
125 125
 			}
126 126
 		} elseif ($event instanceof CalendarDeletedEvent) {
127 127
 			try {
128
-				$deletedProp = '{' . Plugin::NS_NEXTCLOUD . '}deleted-at';
128
+				$deletedProp = '{'.Plugin::NS_NEXTCLOUD.'}deleted-at';
129 129
 				if (isset($event->getCalendarData()[$deletedProp])) {
130 130
 					$this->logger->debug(
131 131
 						sprintf('Calendar %d was already in trashbin, skipping deletion activity', $event->getCalendarId())
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 				}
143 143
 			} catch (Throwable $e) {
144 144
 				// Any error with activities shouldn't abort the calendar deletion, so we just log it
145
-				$this->logger->error('Error generating activities for a deleted calendar: ' . $e->getMessage(), [
145
+				$this->logger->error('Error generating activities for a deleted calendar: '.$e->getMessage(), [
146 146
 					'exception' => $e,
147 147
 				]);
148 148
 			}
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 				);
161 161
 			} catch (Throwable $e) {
162 162
 				// Any error with activities shouldn't abort the calendar object creation, so we just log it
163
-				$this->logger->error('Error generating activity for a new calendar object: ' . $e->getMessage(), [
163
+				$this->logger->error('Error generating activity for a new calendar object: '.$e->getMessage(), [
164 164
 					'exception' => $e,
165 165
 				]);
166 166
 			}
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 				);
179 179
 			} catch (Throwable $e) {
180 180
 				// Any error with activities shouldn't abort the calendar deletion, so we just log it
181
-				$this->logger->error('Error generating activity for a deleted calendar object: ' . $e->getMessage(), [
181
+				$this->logger->error('Error generating activity for a deleted calendar object: '.$e->getMessage(), [
182 182
 					'exception' => $e,
183 183
 				]);
184 184
 			}
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 				);
198 198
 			} catch (Throwable $e) {
199 199
 				// Any error with activities shouldn't abort the calendar deletion, so we just log it
200
-				$this->logger->error('Error generating activity for a deleted calendar object: ' . $e->getMessage(), [
200
+				$this->logger->error('Error generating activity for a deleted calendar object: '.$e->getMessage(), [
201 201
 					'exception' => $e,
202 202
 				]);
203 203
 			}
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
 				);
216 216
 			} catch (Throwable $e) {
217 217
 				// Any error with activities shouldn't abort the calendar object creation, so we just log it
218
-				$this->logger->error('Error generating activity for a new calendar object: ' . $e->getMessage(), [
218
+				$this->logger->error('Error generating activity for a new calendar object: '.$e->getMessage(), [
219 219
 					'exception' => $e,
220 220
 				]);
221 221
 			}
@@ -233,13 +233,13 @@  discard block
 block discarded – undo
233 233
 				);
234 234
 			} catch (Throwable $e) {
235 235
 				// Any error with activities shouldn't abort the calendar object restoration, so we just log it
236
-				$this->logger->error('Error generating activity for a restored calendar object: ' . $e->getMessage(), [
236
+				$this->logger->error('Error generating activity for a restored calendar object: '.$e->getMessage(), [
237 237
 					'exception' => $e,
238 238
 				]);
239 239
 			}
240 240
 		} elseif ($event instanceof CalendarObjectDeletedEvent) {
241 241
 			try {
242
-				$deletedProp = '{' . Plugin::NS_NEXTCLOUD . '}deleted-at';
242
+				$deletedProp = '{'.Plugin::NS_NEXTCLOUD.'}deleted-at';
243 243
 				if (isset($event->getObjectData()[$deletedProp])) {
244 244
 					$this->logger->debug(
245 245
 						sprintf('Calendar object in calendar %d was already in trashbin, skipping deletion activity', $event->getCalendarId())
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 				}
259 259
 			} catch (Throwable $e) {
260 260
 				// Any error with activities shouldn't abort the calendar deletion, so we just log it
261
-				$this->logger->error('Error generating activity for a deleted calendar object: ' . $e->getMessage(), [
261
+				$this->logger->error('Error generating activity for a deleted calendar object: '.$e->getMessage(), [
262 262
 					'exception' => $e,
263 263
 				]);
264 264
 			}
Please login to merge, or discard this patch.
Indentation   +212 added lines, -212 removed lines patch added patch discarded remove patch
@@ -30,216 +30,216 @@
 block discarded – undo
30 30
 /** @template-implements IEventListener<CalendarCreatedEvent|CalendarUpdatedEvent|CalendarMovedToTrashEvent|CalendarRestoredEvent|CalendarDeletedEvent|CalendarObjectCreatedEvent|CalendarObjectUpdatedEvent|CalendarObjectMovedEvent|CalendarObjectMovedToTrashEvent|CalendarObjectRestoredEvent|CalendarObjectDeletedEvent> */
31 31
 class ActivityUpdaterListener implements IEventListener {
32 32
 
33
-	public function __construct(
34
-		private ActivityBackend $activityBackend,
35
-		private LoggerInterface $logger,
36
-	) {
37
-	}
38
-
39
-	public function handle(Event $event): void {
40
-		if ($event instanceof CalendarCreatedEvent) {
41
-			try {
42
-				$this->activityBackend->onCalendarAdd(
43
-					$event->getCalendarData()
44
-				);
45
-
46
-				$this->logger->debug(
47
-					sprintf('Activity generated for new calendar %d', $event->getCalendarId())
48
-				);
49
-			} catch (Throwable $e) {
50
-				// Any error with activities shouldn't abort the calendar creation, so we just log it
51
-				$this->logger->error('Error generating activities for a new calendar: ' . $e->getMessage(), [
52
-					'exception' => $e,
53
-				]);
54
-			}
55
-		} elseif ($event instanceof CalendarUpdatedEvent) {
56
-			try {
57
-				$this->activityBackend->onCalendarUpdate(
58
-					$event->getCalendarData(),
59
-					$event->getShares(),
60
-					$event->getMutations()
61
-				);
62
-
63
-				$this->logger->debug(
64
-					sprintf('Activity generated for changed calendar %d', $event->getCalendarId())
65
-				);
66
-			} catch (Throwable $e) {
67
-				// Any error with activities shouldn't abort the calendar update, so we just log it
68
-				$this->logger->error('Error generating activities for changed calendar: ' . $e->getMessage(), [
69
-					'exception' => $e,
70
-				]);
71
-			}
72
-		} elseif ($event instanceof CalendarMovedToTrashEvent) {
73
-			try {
74
-				$this->activityBackend->onCalendarMovedToTrash(
75
-					$event->getCalendarData(),
76
-					$event->getShares()
77
-				);
78
-
79
-				$this->logger->debug(
80
-					sprintf('Activity generated for changed calendar %d', $event->getCalendarId())
81
-				);
82
-			} catch (Throwable $e) {
83
-				// Any error with activities shouldn't abort the calendar update, so we just log it
84
-				$this->logger->error('Error generating activities for changed calendar: ' . $e->getMessage(), [
85
-					'exception' => $e,
86
-				]);
87
-			}
88
-		} elseif ($event instanceof CalendarRestoredEvent) {
89
-			try {
90
-				$this->activityBackend->onCalendarRestored(
91
-					$event->getCalendarData(),
92
-					$event->getShares()
93
-				);
94
-
95
-				$this->logger->debug(
96
-					sprintf('Activity generated for changed calendar %d', $event->getCalendarId())
97
-				);
98
-			} catch (Throwable $e) {
99
-				// Any error with activities shouldn't abort the calendar update, so we just log it
100
-				$this->logger->error('Error generating activities for changed calendar: ' . $e->getMessage(), [
101
-					'exception' => $e,
102
-				]);
103
-			}
104
-		} elseif ($event instanceof CalendarDeletedEvent) {
105
-			try {
106
-				$deletedProp = '{' . Plugin::NS_NEXTCLOUD . '}deleted-at';
107
-				if (isset($event->getCalendarData()[$deletedProp])) {
108
-					$this->logger->debug(
109
-						sprintf('Calendar %d was already in trashbin, skipping deletion activity', $event->getCalendarId())
110
-					);
111
-				} else {
112
-					$this->activityBackend->onCalendarDelete(
113
-						$event->getCalendarData(),
114
-						$event->getShares()
115
-					);
116
-
117
-					$this->logger->debug(
118
-						sprintf('Activity generated for deleted calendar %d', $event->getCalendarId())
119
-					);
120
-				}
121
-			} catch (Throwable $e) {
122
-				// Any error with activities shouldn't abort the calendar deletion, so we just log it
123
-				$this->logger->error('Error generating activities for a deleted calendar: ' . $e->getMessage(), [
124
-					'exception' => $e,
125
-				]);
126
-			}
127
-		} elseif ($event instanceof CalendarObjectCreatedEvent) {
128
-			try {
129
-				$this->activityBackend->onTouchCalendarObject(
130
-					\OCA\DAV\CalDAV\Activity\Provider\Event::SUBJECT_OBJECT_ADD,
131
-					$event->getCalendarData(),
132
-					$event->getShares(),
133
-					$event->getObjectData()
134
-				);
135
-
136
-				$this->logger->debug(
137
-					sprintf('Activity generated for new calendar object in calendar %d', $event->getCalendarId())
138
-				);
139
-			} catch (Throwable $e) {
140
-				// Any error with activities shouldn't abort the calendar object creation, so we just log it
141
-				$this->logger->error('Error generating activity for a new calendar object: ' . $e->getMessage(), [
142
-					'exception' => $e,
143
-				]);
144
-			}
145
-		} elseif ($event instanceof CalendarObjectUpdatedEvent) {
146
-			try {
147
-				$this->activityBackend->onTouchCalendarObject(
148
-					\OCA\DAV\CalDAV\Activity\Provider\Event::SUBJECT_OBJECT_UPDATE,
149
-					$event->getCalendarData(),
150
-					$event->getShares(),
151
-					$event->getObjectData()
152
-				);
153
-
154
-				$this->logger->debug(
155
-					sprintf('Activity generated for updated calendar object in calendar %d', $event->getCalendarId())
156
-				);
157
-			} catch (Throwable $e) {
158
-				// Any error with activities shouldn't abort the calendar deletion, so we just log it
159
-				$this->logger->error('Error generating activity for a deleted calendar object: ' . $e->getMessage(), [
160
-					'exception' => $e,
161
-				]);
162
-			}
163
-		} elseif ($event instanceof CalendarObjectMovedEvent) {
164
-			try {
165
-				$this->activityBackend->onMovedCalendarObject(
166
-					$event->getSourceCalendarData(),
167
-					$event->getTargetCalendarData(),
168
-					$event->getSourceShares(),
169
-					$event->getTargetShares(),
170
-					$event->getObjectData()
171
-				);
172
-
173
-				$this->logger->debug(
174
-					sprintf('Activity generated for moved calendar object from calendar %d to calendar %d', $event->getSourceCalendarId(), $event->getTargetCalendarId())
175
-				);
176
-			} catch (Throwable $e) {
177
-				// Any error with activities shouldn't abort the calendar deletion, so we just log it
178
-				$this->logger->error('Error generating activity for a deleted calendar object: ' . $e->getMessage(), [
179
-					'exception' => $e,
180
-				]);
181
-			}
182
-		} elseif ($event instanceof CalendarObjectMovedToTrashEvent) {
183
-			try {
184
-				$this->activityBackend->onTouchCalendarObject(
185
-					\OCA\DAV\CalDAV\Activity\Provider\Event::SUBJECT_OBJECT_MOVE_TO_TRASH,
186
-					$event->getCalendarData(),
187
-					$event->getShares(),
188
-					$event->getObjectData()
189
-				);
190
-
191
-				$this->logger->debug(
192
-					sprintf('Activity generated for a calendar object of calendar %d that is moved to trash', $event->getCalendarId())
193
-				);
194
-			} catch (Throwable $e) {
195
-				// Any error with activities shouldn't abort the calendar object creation, so we just log it
196
-				$this->logger->error('Error generating activity for a new calendar object: ' . $e->getMessage(), [
197
-					'exception' => $e,
198
-				]);
199
-			}
200
-		} elseif ($event instanceof CalendarObjectRestoredEvent) {
201
-			try {
202
-				$this->activityBackend->onTouchCalendarObject(
203
-					\OCA\DAV\CalDAV\Activity\Provider\Event::SUBJECT_OBJECT_RESTORE,
204
-					$event->getCalendarData(),
205
-					$event->getShares(),
206
-					$event->getObjectData()
207
-				);
208
-
209
-				$this->logger->debug(
210
-					sprintf('Activity generated for a restore calendar object of calendar %d', $event->getCalendarId())
211
-				);
212
-			} catch (Throwable $e) {
213
-				// Any error with activities shouldn't abort the calendar object restoration, so we just log it
214
-				$this->logger->error('Error generating activity for a restored calendar object: ' . $e->getMessage(), [
215
-					'exception' => $e,
216
-				]);
217
-			}
218
-		} elseif ($event instanceof CalendarObjectDeletedEvent) {
219
-			try {
220
-				$deletedProp = '{' . Plugin::NS_NEXTCLOUD . '}deleted-at';
221
-				if (isset($event->getObjectData()[$deletedProp])) {
222
-					$this->logger->debug(
223
-						sprintf('Calendar object in calendar %d was already in trashbin, skipping deletion activity', $event->getCalendarId())
224
-					);
225
-				} else {
226
-					$this->activityBackend->onTouchCalendarObject(
227
-						\OCA\DAV\CalDAV\Activity\Provider\Event::SUBJECT_OBJECT_DELETE,
228
-						$event->getCalendarData(),
229
-						$event->getShares(),
230
-						$event->getObjectData()
231
-					);
232
-
233
-					$this->logger->debug(
234
-						sprintf('Activity generated for deleted calendar object in calendar %d', $event->getCalendarId())
235
-					);
236
-				}
237
-			} catch (Throwable $e) {
238
-				// Any error with activities shouldn't abort the calendar deletion, so we just log it
239
-				$this->logger->error('Error generating activity for a deleted calendar object: ' . $e->getMessage(), [
240
-					'exception' => $e,
241
-				]);
242
-			}
243
-		}
244
-	}
33
+    public function __construct(
34
+        private ActivityBackend $activityBackend,
35
+        private LoggerInterface $logger,
36
+    ) {
37
+    }
38
+
39
+    public function handle(Event $event): void {
40
+        if ($event instanceof CalendarCreatedEvent) {
41
+            try {
42
+                $this->activityBackend->onCalendarAdd(
43
+                    $event->getCalendarData()
44
+                );
45
+
46
+                $this->logger->debug(
47
+                    sprintf('Activity generated for new calendar %d', $event->getCalendarId())
48
+                );
49
+            } catch (Throwable $e) {
50
+                // Any error with activities shouldn't abort the calendar creation, so we just log it
51
+                $this->logger->error('Error generating activities for a new calendar: ' . $e->getMessage(), [
52
+                    'exception' => $e,
53
+                ]);
54
+            }
55
+        } elseif ($event instanceof CalendarUpdatedEvent) {
56
+            try {
57
+                $this->activityBackend->onCalendarUpdate(
58
+                    $event->getCalendarData(),
59
+                    $event->getShares(),
60
+                    $event->getMutations()
61
+                );
62
+
63
+                $this->logger->debug(
64
+                    sprintf('Activity generated for changed calendar %d', $event->getCalendarId())
65
+                );
66
+            } catch (Throwable $e) {
67
+                // Any error with activities shouldn't abort the calendar update, so we just log it
68
+                $this->logger->error('Error generating activities for changed calendar: ' . $e->getMessage(), [
69
+                    'exception' => $e,
70
+                ]);
71
+            }
72
+        } elseif ($event instanceof CalendarMovedToTrashEvent) {
73
+            try {
74
+                $this->activityBackend->onCalendarMovedToTrash(
75
+                    $event->getCalendarData(),
76
+                    $event->getShares()
77
+                );
78
+
79
+                $this->logger->debug(
80
+                    sprintf('Activity generated for changed calendar %d', $event->getCalendarId())
81
+                );
82
+            } catch (Throwable $e) {
83
+                // Any error with activities shouldn't abort the calendar update, so we just log it
84
+                $this->logger->error('Error generating activities for changed calendar: ' . $e->getMessage(), [
85
+                    'exception' => $e,
86
+                ]);
87
+            }
88
+        } elseif ($event instanceof CalendarRestoredEvent) {
89
+            try {
90
+                $this->activityBackend->onCalendarRestored(
91
+                    $event->getCalendarData(),
92
+                    $event->getShares()
93
+                );
94
+
95
+                $this->logger->debug(
96
+                    sprintf('Activity generated for changed calendar %d', $event->getCalendarId())
97
+                );
98
+            } catch (Throwable $e) {
99
+                // Any error with activities shouldn't abort the calendar update, so we just log it
100
+                $this->logger->error('Error generating activities for changed calendar: ' . $e->getMessage(), [
101
+                    'exception' => $e,
102
+                ]);
103
+            }
104
+        } elseif ($event instanceof CalendarDeletedEvent) {
105
+            try {
106
+                $deletedProp = '{' . Plugin::NS_NEXTCLOUD . '}deleted-at';
107
+                if (isset($event->getCalendarData()[$deletedProp])) {
108
+                    $this->logger->debug(
109
+                        sprintf('Calendar %d was already in trashbin, skipping deletion activity', $event->getCalendarId())
110
+                    );
111
+                } else {
112
+                    $this->activityBackend->onCalendarDelete(
113
+                        $event->getCalendarData(),
114
+                        $event->getShares()
115
+                    );
116
+
117
+                    $this->logger->debug(
118
+                        sprintf('Activity generated for deleted calendar %d', $event->getCalendarId())
119
+                    );
120
+                }
121
+            } catch (Throwable $e) {
122
+                // Any error with activities shouldn't abort the calendar deletion, so we just log it
123
+                $this->logger->error('Error generating activities for a deleted calendar: ' . $e->getMessage(), [
124
+                    'exception' => $e,
125
+                ]);
126
+            }
127
+        } elseif ($event instanceof CalendarObjectCreatedEvent) {
128
+            try {
129
+                $this->activityBackend->onTouchCalendarObject(
130
+                    \OCA\DAV\CalDAV\Activity\Provider\Event::SUBJECT_OBJECT_ADD,
131
+                    $event->getCalendarData(),
132
+                    $event->getShares(),
133
+                    $event->getObjectData()
134
+                );
135
+
136
+                $this->logger->debug(
137
+                    sprintf('Activity generated for new calendar object in calendar %d', $event->getCalendarId())
138
+                );
139
+            } catch (Throwable $e) {
140
+                // Any error with activities shouldn't abort the calendar object creation, so we just log it
141
+                $this->logger->error('Error generating activity for a new calendar object: ' . $e->getMessage(), [
142
+                    'exception' => $e,
143
+                ]);
144
+            }
145
+        } elseif ($event instanceof CalendarObjectUpdatedEvent) {
146
+            try {
147
+                $this->activityBackend->onTouchCalendarObject(
148
+                    \OCA\DAV\CalDAV\Activity\Provider\Event::SUBJECT_OBJECT_UPDATE,
149
+                    $event->getCalendarData(),
150
+                    $event->getShares(),
151
+                    $event->getObjectData()
152
+                );
153
+
154
+                $this->logger->debug(
155
+                    sprintf('Activity generated for updated calendar object in calendar %d', $event->getCalendarId())
156
+                );
157
+            } catch (Throwable $e) {
158
+                // Any error with activities shouldn't abort the calendar deletion, so we just log it
159
+                $this->logger->error('Error generating activity for a deleted calendar object: ' . $e->getMessage(), [
160
+                    'exception' => $e,
161
+                ]);
162
+            }
163
+        } elseif ($event instanceof CalendarObjectMovedEvent) {
164
+            try {
165
+                $this->activityBackend->onMovedCalendarObject(
166
+                    $event->getSourceCalendarData(),
167
+                    $event->getTargetCalendarData(),
168
+                    $event->getSourceShares(),
169
+                    $event->getTargetShares(),
170
+                    $event->getObjectData()
171
+                );
172
+
173
+                $this->logger->debug(
174
+                    sprintf('Activity generated for moved calendar object from calendar %d to calendar %d', $event->getSourceCalendarId(), $event->getTargetCalendarId())
175
+                );
176
+            } catch (Throwable $e) {
177
+                // Any error with activities shouldn't abort the calendar deletion, so we just log it
178
+                $this->logger->error('Error generating activity for a deleted calendar object: ' . $e->getMessage(), [
179
+                    'exception' => $e,
180
+                ]);
181
+            }
182
+        } elseif ($event instanceof CalendarObjectMovedToTrashEvent) {
183
+            try {
184
+                $this->activityBackend->onTouchCalendarObject(
185
+                    \OCA\DAV\CalDAV\Activity\Provider\Event::SUBJECT_OBJECT_MOVE_TO_TRASH,
186
+                    $event->getCalendarData(),
187
+                    $event->getShares(),
188
+                    $event->getObjectData()
189
+                );
190
+
191
+                $this->logger->debug(
192
+                    sprintf('Activity generated for a calendar object of calendar %d that is moved to trash', $event->getCalendarId())
193
+                );
194
+            } catch (Throwable $e) {
195
+                // Any error with activities shouldn't abort the calendar object creation, so we just log it
196
+                $this->logger->error('Error generating activity for a new calendar object: ' . $e->getMessage(), [
197
+                    'exception' => $e,
198
+                ]);
199
+            }
200
+        } elseif ($event instanceof CalendarObjectRestoredEvent) {
201
+            try {
202
+                $this->activityBackend->onTouchCalendarObject(
203
+                    \OCA\DAV\CalDAV\Activity\Provider\Event::SUBJECT_OBJECT_RESTORE,
204
+                    $event->getCalendarData(),
205
+                    $event->getShares(),
206
+                    $event->getObjectData()
207
+                );
208
+
209
+                $this->logger->debug(
210
+                    sprintf('Activity generated for a restore calendar object of calendar %d', $event->getCalendarId())
211
+                );
212
+            } catch (Throwable $e) {
213
+                // Any error with activities shouldn't abort the calendar object restoration, so we just log it
214
+                $this->logger->error('Error generating activity for a restored calendar object: ' . $e->getMessage(), [
215
+                    'exception' => $e,
216
+                ]);
217
+            }
218
+        } elseif ($event instanceof CalendarObjectDeletedEvent) {
219
+            try {
220
+                $deletedProp = '{' . Plugin::NS_NEXTCLOUD . '}deleted-at';
221
+                if (isset($event->getObjectData()[$deletedProp])) {
222
+                    $this->logger->debug(
223
+                        sprintf('Calendar object in calendar %d was already in trashbin, skipping deletion activity', $event->getCalendarId())
224
+                    );
225
+                } else {
226
+                    $this->activityBackend->onTouchCalendarObject(
227
+                        \OCA\DAV\CalDAV\Activity\Provider\Event::SUBJECT_OBJECT_DELETE,
228
+                        $event->getCalendarData(),
229
+                        $event->getShares(),
230
+                        $event->getObjectData()
231
+                    );
232
+
233
+                    $this->logger->debug(
234
+                        sprintf('Activity generated for deleted calendar object in calendar %d', $event->getCalendarId())
235
+                    );
236
+                }
237
+            } catch (Throwable $e) {
238
+                // Any error with activities shouldn't abort the calendar deletion, so we just log it
239
+                $this->logger->error('Error generating activity for a deleted calendar object: ' . $e->getMessage(), [
240
+                    'exception' => $e,
241
+                ]);
242
+            }
243
+        }
244
+    }
245 245
 }
Please login to merge, or discard this patch.