Completed
Push — master ( 887318...038ae3 )
by Lukas
21:37
created

Provider::getSubjectParameters()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
nc 2
nop 1
dl 0
loc 13
rs 9.4285
c 1
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016 Joas Schilling <[email protected]>
4
 *
5
 * @license GNU AGPL version 3 or any later version
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as
9
 * published by the Free Software Foundation, either version 3 of the
10
 * License, or (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 *
20
 */
21
22
namespace OCA\Comments\Activity;
23
24
use OCP\Activity\IEvent;
25
use OCP\Activity\IManager;
26
use OCP\Activity\IProvider;
27
use OCP\Comments\ICommentsManager;
28
use OCP\Comments\NotFoundException;
29
use OCP\IL10N;
30
use OCP\IURLGenerator;
31
use OCP\IUser;
32
use OCP\IUserManager;
33
use OCP\L10N\IFactory;
34
35
class Provider implements IProvider {
36
37
	/** @var IFactory */
38
	protected $languageFactory;
39
40
	/** @var IL10N */
41
	protected $l;
42
43
	/** @var IURLGenerator */
44
	protected $url;
45
46
	/** @var ICommentsManager */
47
	protected $commentsManager;
48
49
	/** @var IUserManager */
50
	protected $userManager;
51
52
	/** @var IManager */
53
	protected $activityManager;
54
55
	/** @var string[] */
56
	protected $displayNames = [];
57
58
	/**
59
	 * @param IFactory $languageFactory
60
	 * @param IURLGenerator $url
61
	 * @param ICommentsManager $commentsManager
62
	 * @param IUserManager $userManager
63
	 * @param IManager $activityManager
64
	 */
65
	public function __construct(IFactory $languageFactory, IURLGenerator $url, ICommentsManager $commentsManager, IUserManager $userManager, IManager $activityManager) {
66
		$this->languageFactory = $languageFactory;
67
		$this->url = $url;
68
		$this->commentsManager = $commentsManager;
69
		$this->userManager = $userManager;
70
		$this->activityManager = $activityManager;
71
	}
72
73
	/**
74
	 * @param string $language
75
	 * @param IEvent $event
76
	 * @param IEvent|null $previousEvent
77
	 * @return IEvent
78
	 * @throws \InvalidArgumentException
79
	 * @since 11.0.0
80
	 */
81
	public function parse($language, IEvent $event, IEvent $previousEvent = null) {
82
		if ($event->getApp() !== 'comments') {
83
			throw new \InvalidArgumentException();
84
		}
85
86
		$this->l = $this->languageFactory->get('comments', $language);
87
88
		if ($event->getSubject() === 'add_comment_subject') {
89
			$this->parseMessage($event);
90
			if ($this->activityManager->getRequirePNG()) {
91
				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/comment.png')));
92
			} else {
93
				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/comment.svg')));
94
			}
95
96
			if ($this->activityManager->isFormattingFilteredObject()) {
97
				try {
98
					return $this->parseShortVersion($event);
99
				} catch (\InvalidArgumentException $e) {
100
					// Ignore and simply use the long version...
101
				}
102
			}
103
104
			return $this->parseLongVersion($event);
105
		} else {
106
			throw new \InvalidArgumentException();
107
		}
108
	}
109
110
	/**
111
	 * @param IEvent $event
112
	 * @return IEvent
113
	 * @throws \InvalidArgumentException
114
	 */
115
	protected function parseShortVersion(IEvent $event) {
116
		$subjectParameters = $event->getSubjectParameters();
117
118
		if ($event->getSubject() === 'add_comment_subject') {
119
			if ($subjectParameters['actor'] === $this->activityManager->getCurrentUserId()) {
120
				$event->setParsedSubject($this->l->t('You commented'))
121
					->setRichSubject($this->l->t('You commented'), []);
122
			} else {
123
				$author = $this->generateUserParameter($subjectParameters['actor']);
124
				$event->setParsedSubject($this->l->t('%1$s commented', [$author['name']]))
125
					->setRichSubject($this->l->t('{author} commented'), [
126
						'author' => $author,
127
					]);
128
			}
129
		} else {
130
			throw new \InvalidArgumentException();
131
		}
132
133
		return $event;
134
	}
135
136
	/**
137
	 * @param IEvent $event
138
	 * @return IEvent
139
	 * @throws \InvalidArgumentException
140
	 */
141
	protected function parseLongVersion(IEvent $event) {
142
		$subjectParameters = $event->getSubjectParameters();
143
144
		if ($event->getSubject() === 'add_comment_subject') {
145
			if ($subjectParameters['actor'] === $this->activityManager->getCurrentUserId()) {
146
				$event->setParsedSubject($this->l->t('You commented on %1$s', [
147
						$subjectParameters['filePath'],
148
					]))
149
					->setRichSubject($this->l->t('You commented on {file}'), [
150
						'file' => $this->generateFileParameter($subjectParameters['fileId'], $subjectParameters['filePath']),
151
					]);
152
			} else {
153
				$author = $this->generateUserParameter($subjectParameters['actor']);
154
				$event->setParsedSubject($this->l->t('%1$s commented on %2$s', [
155
						$author['name'],
156
						$subjectParameters['filePath'],
157
					]))
158
					->setRichSubject($this->l->t('{author} commented on {file}'), [
159
						'author' => $author,
160
						'file' => $this->generateFileParameter($subjectParameters['fileId'], $subjectParameters['filePath']),
161
					]);
162
			}
163
		} else {
164
			throw new \InvalidArgumentException();
165
		}
166
167
		return $event;
168
	}
169
170
	protected function getSubjectParameters(IEvent $event) {
171
		$subjectParameters = $event->getSubjectParameters();
172
		if (isset($subjectParameters['fileId'])) {
173
			return $subjectParameters;
174
		}
175
176
		// Fix subjects from 12.0.3 and older
177
		return [
178
			'actor' => $subjectParameters[0],
179
			'fileId' => (int) $event->getObjectId(),
180
			'filePath' => trim($subjectParameters[1], '/'),
181
		];
182
	}
183
184
	/**
185
	 * @param IEvent $event
186
	 */
187
	protected function parseMessage(IEvent $event) {
188
		$messageParameters = $event->getMessageParameters();
189
		if (empty($messageParameters)) {
190
			// Email
191
			return;
192
		}
193
194
		$commentId = isset($messageParameters['commentId']) ? $messageParameters['commentId'] : $messageParameters[0];
195
196
		try {
197
			$comment = $this->commentsManager->get((string) $commentId);
198
			$message = $comment->getMessage();
199
			$message = str_replace("\n", '<br />', str_replace(['<', '>'], ['&lt;', '&gt;'], $message));
200
201
			$mentionCount = 1;
202
			$mentions = [];
203
			foreach ($comment->getMentions() as $mention) {
204
				if ($mention['type'] !== 'user') {
205
					continue;
206
				}
207
208
				$message = preg_replace(
209
					'/(^|\s)(' . '@' . $mention['id'] . ')(\b)/',
210
					//'${1}' . $this->regexSafeUser($mention['id'], $displayName) . '${3}',
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
211
					'${1}' . '{mention' . $mentionCount . '}' . '${3}',
212
					$message
213
				);
214
				$mentions['mention' . $mentionCount] = $this->generateUserParameter($mention['id']);
215
				$mentionCount++;
216
			}
217
218
			$event->setParsedMessage($comment->getMessage())
219
				->setRichMessage($message, $mentions);
220
		} catch (NotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
221
		}
222
	}
223
224
	/**
225
	 * @param int $id
226
	 * @param string $path
227
	 * @return array
228
	 */
229 View Code Duplication
	protected function generateFileParameter($id, $path) {
230
		return [
231
			'type' => 'file',
232
			'id' => $id,
233
			'name' => basename($path),
234
			'path' => $path,
235
			'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $id]),
236
		];
237
	}
238
239
	/**
240
	 * @param string $uid
241
	 * @return array
242
	 */
243 View Code Duplication
	protected function generateUserParameter($uid) {
244
		if (!isset($this->displayNames[$uid])) {
245
			$this->displayNames[$uid] = $this->getDisplayName($uid);
246
		}
247
248
		return [
249
			'type' => 'user',
250
			'id' => $uid,
251
			'name' => $this->displayNames[$uid],
252
		];
253
	}
254
255
	/**
256
	 * @param string $uid
257
	 * @return string
258
	 */
259 View Code Duplication
	protected function getDisplayName($uid) {
260
		$user = $this->userManager->get($uid);
261
		if ($user instanceof IUser) {
262
			return $user->getDisplayName();
263
		} else {
264
			return $uid;
265
		}
266
	}
267
}
268