8cea9da1b79b13f3be35984003d68f18393ae4b7
[GitHub/WoltLab/WCF.git] /
1 <?php
2 declare(strict_types=1);
3 namespace wcf\system\package\plugin;
4 use wcf\data\object\type\ObjectTypeCache;
5 use wcf\data\user\notification\event\UserNotificationEvent;
6 use wcf\data\user\notification\event\UserNotificationEventEditor;
7 use wcf\data\user\notification\event\UserNotificationEventList;
8 use wcf\system\devtools\pip\IDevtoolsPipEntryList;
9 use wcf\system\devtools\pip\IGuiPackageInstallationPlugin;
10 use wcf\system\devtools\pip\TXmlGuiPackageInstallationPlugin;
11 use wcf\system\exception\SystemException;
12 use wcf\system\form\builder\container\FormContainer;
13 use wcf\system\form\builder\field\OptionFormField;
14 use wcf\system\form\builder\field\UserGroupOptionFormField;
15 use wcf\system\form\builder\field\validation\FormFieldValidationError;
16 use wcf\system\form\builder\field\validation\FormFieldValidator;
17 use wcf\system\form\builder\field\BooleanFormField;
18 use wcf\system\form\builder\field\ClassNameFormField;
19 use wcf\system\form\builder\field\ItemListFormField;
20 use wcf\system\form\builder\field\SingleSelectionFormField;
21 use wcf\system\form\builder\field\TextFormField;
22 use wcf\system\form\builder\IFormDocument;
23 use wcf\system\user\notification\event\IUserNotificationEvent;
24 use wcf\system\WCF;
25 use wcf\util\StringUtil;
26
27 /**
28 * Installs, updates and deletes user notification events.
29 *
30 * @author Matthias Schmidt, Marcel Werk
31 * @copyright 2001-2018 WoltLab GmbH
32 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
33 * @package WoltLabSuite\Core\System\Package\Plugin
34 */
35 class UserNotificationEventPackageInstallationPlugin extends AbstractXMLPackageInstallationPlugin implements IGuiPackageInstallationPlugin {
36 use TXmlGuiPackageInstallationPlugin;
37
38 /**
39 * @inheritDoc
40 */
41 public $className = UserNotificationEventEditor::class;
42
43 /**
44 * @inheritDoc
45 */
46 public $tableName = 'user_notification_event';
47
48 /**
49 * @inheritDoc
50 */
51 public $tagName = 'event';
52
53 /**
54 * preset event ids
55 * @var integer[]
56 */
57 protected $presetEventIDs = [];
58
59 /**
60 * @inheritDoc
61 */
62 protected function handleDelete(array $items) {
63 $sql = "DELETE FROM wcf".WCF_N."_".$this->tableName."
64 WHERE packageID = ?
65 AND objectTypeID = ?
66 AND eventName = ?";
67 $statement = WCF::getDB()->prepareStatement($sql);
68 foreach ($items as $item) {
69 $statement->execute([
70 $this->installation->getPackageID(),
71 $this->getObjectTypeID($item['elements']['objecttype']),
72 $item['elements']['name']
73 ]);
74 }
75 }
76
77 /**
78 * @inheritDoc
79 */
80 protected function prepareImport(array $data) {
81 $presetMailNotificationType = 'none';
82 if (isset($data['elements']['presetmailnotificationtype']) && ($data['elements']['presetmailnotificationtype'] == 'instant' || $data['elements']['presetmailnotificationtype'] == 'daily')) {
83 $presetMailNotificationType = $data['elements']['presetmailnotificationtype'];
84 }
85
86 return [
87 'eventName' => $data['elements']['name'],
88 'className' => $data['elements']['classname'],
89 'objectTypeID' => $this->getObjectTypeID($data['elements']['objecttype']),
90 'permissions' => isset($data['elements']['permissions']) ? StringUtil::normalizeCsv($data['elements']['permissions']) : '',
91 'options' => isset($data['elements']['options']) ? StringUtil::normalizeCsv($data['elements']['options']) : '',
92 'preset' => !empty($data['elements']['preset']) ? 1 : 0,
93 'presetMailNotificationType' => $presetMailNotificationType
94 ];
95 }
96
97 /**
98 * @inheritDoc
99 */
100 protected function import(array $row, array $data) {
101 /** @var UserNotificationEvent $event */
102 $event = parent::import($row, $data);
103
104 if (empty($row) && $data['preset']) {
105 $this->presetEventIDs[$event->eventID] = $data['presetMailNotificationType'];
106 }
107
108 return $event;
109 }
110
111 /**
112 * @inheritDoc
113 */
114 protected function cleanup() {
115 if (empty($this->presetEventIDs)) return;
116
117 $sql = "INSERT IGNORE INTO wcf".WCF_N."_user_notification_event_to_user
118 (userID, eventID, mailNotificationType)
119 SELECT userID, ?, ?
120 FROM wcf".WCF_N."_user";
121 $statement = WCF::getDB()->prepareStatement($sql);
122 WCF::getDB()->beginTransaction();
123 foreach ($this->presetEventIDs as $eventID => $mailNotificationType) {
124 $statement->execute([$eventID, $mailNotificationType]);
125 }
126 WCF::getDB()->commitTransaction();
127 }
128
129 /**
130 * @inheritDoc
131 */
132 protected function findExistingItem(array $data) {
133 $sql = "SELECT *
134 FROM wcf".WCF_N."_".$this->tableName."
135 WHERE objectTypeID = ?
136 AND eventName = ?";
137 $parameters = [
138 $data['objectTypeID'],
139 $data['eventName']
140 ];
141
142 return [
143 'sql' => $sql,
144 'parameters' => $parameters
145 ];
146 }
147
148 /**
149 * Gets the id of given object type id.
150 *
151 * @param string $objectType
152 * @return integer
153 * @throws SystemException
154 */
155 protected function getObjectTypeID($objectType) {
156 // get object type id
157 $sql = "SELECT object_type.objectTypeID
158 FROM wcf".WCF_N."_object_type object_type
159 WHERE object_type.objectType = ?
160 AND object_type.definitionID IN (
161 SELECT definitionID
162 FROM wcf".WCF_N."_object_type_definition
163 WHERE definitionName = 'com.woltlab.wcf.notification.objectType'
164 )";
165 $statement = WCF::getDB()->prepareStatement($sql, 1);
166 $statement->execute([$objectType]);
167 $row = $statement->fetchArray();
168 if (empty($row['objectTypeID'])) throw new SystemException("unknown notification object type '".$objectType."' given");
169 return $row['objectTypeID'];
170 }
171
172 /**
173 * @inheritDoc
174 * @since 3.1
175 */
176 public static function getSyncDependencies() {
177 return ['objectType'];
178 }
179
180 /**
181 * @inheritDoc
182 * @since 3.2
183 */
184 public function addFormFields(IFormDocument $form) {
185 /** @var FormContainer $dataContainer */
186 $dataContainer = $form->getNodeById('data');
187
188 $dataContainer->appendChildren([
189 TextFormField::create('name')
190 ->label('wcf.acp.pip.userNotificationEvent.name')
191 ->description('wcf.acp.pip.userNotificationEvent.name.description')
192 ->required()
193 ->addValidator(new FormFieldValidator('format', function(TextFormField $formField) {
194 if (!preg_match('~^[a-z][A-z]+$~', $formField->getValue())) {
195 $formField->addValidationError(
196 new FormFieldValidationError(
197 'format',
198 'wcf.acp.pip.userNotificationEvent.name.error.format'
199 )
200 );
201 }
202 })),
203
204 SingleSelectionFormField::create('objectType')
205 ->objectProperty('objecttype')
206 ->label('wcf.acp.pip.userNotificationEvent.objectType')
207 ->description('wcf.acp.pip.userNotificationEvent.objectType.description')
208 ->required()
209 ->options(function(): array {
210 $options = [];
211 foreach (ObjectTypeCache::getInstance()->getObjectTypes('com.woltlab.wcf.notification.objectType') as $objectType) {
212 $options[$objectType->objectType] = $objectType->objectType;
213 }
214
215 asort($options);
216
217 return $options;
218 })
219 // validate the uniqueness of the `name` field after knowing that the selected object type is valid
220 ->addValidator(new FormFieldValidator('nameUniqueness', function(SingleSelectionFormField $formField) {
221 /** @var TextFormField $nameField */
222 $nameField = $formField->getDocument()->getNodeById('name');
223
224 if ($formField->getDocument()->getFormMode() === IFormDocument::FORM_MODE_CREATE || $this->editedEntry->getAttribute('name') !== $nameField->getSaveValue()) {
225 $eventList = new UserNotificationEventList();
226 $eventList->getConditionBuilder()->add('user_notification_event.eventName = ?', [$nameField->getSaveValue()]);
227 $eventList->getConditionBuilder()->add(
228 'user_notification_event.objectTypeID = ?',
229 [ObjectTypeCache::getInstance()->getObjectTypeByName('com.woltlab.wcf.notification.objectType', $formField->getSaveValue())->objectTypeID]
230 );
231
232 if ($eventList->countObjects() > 0) {
233 $nameField->addValidationError(
234 new FormFieldValidationError(
235 'notUnique',
236 'wcf.acp.pip.userNotificationEvent.name.error.notUnique'
237 )
238 );
239 }
240 }
241 })),
242
243 ClassNameFormField::create()
244 ->objectProperty('classname')
245 ->required()
246 ->implementedInterface(IUserNotificationEvent::class),
247
248 BooleanFormField::create('preset')
249 ->label('wcf.acp.pip.userNotificationEvent.preset')
250 ->description('wcf.acp.pip.userNotificationEvent.preset.description'),
251
252 OptionFormField::create()
253 ->description('wcf.acp.pip.userNotificationEvent.options.description')
254 ->packageIDs(array_merge(
255 [$this->installation->getPackage()->packageID],
256 array_keys($this->installation->getPackage()->getAllRequiredPackages())
257 )),
258
259 UserGroupOptionFormField::create()
260 ->description('wcf.acp.pip.userNotificationEvent.permissions.description')
261 ->packageIDs(array_merge(
262 [$this->installation->getPackage()->packageID],
263 array_keys($this->installation->getPackage()->getAllRequiredPackages())
264 )),
265
266 SingleSelectionFormField::create('presetMailNotificationType')
267 ->objectProperty('presetmailnotificationtype')
268 ->label('wcf.acp.pip.userNotificationEvent.presetMailNotificationType')
269 ->description('wcf.acp.pip.userNotificationEvent.presetMailNotificationType.description')
270 ->nullable()
271 ->options([
272 '' => 'wcf.user.notification.mailNotificationType.none',
273 'daily' => 'wcf.user.notification.mailNotificationType.daily',
274 'instant' => 'wcf.user.notification.mailNotificationType.instant'
275 ])
276 ]);
277 }
278
279 /**
280 * @inheritDoc
281 * @since 3.2
282 */
283 protected function getElementData(\DOMElement $element, bool $saveData = false): array {
284 $data = [
285 'className' => $element->getElementsByTagName('classname')->item(0)->nodeValue,
286 'objectTypeID' => $this->getObjectTypeID($element->getElementsByTagName('objecttype')->item(0)->nodeValue),
287 'eventName' => $element->getElementsByTagName('name')->item(0)->nodeValue,
288 'packageID' => $this->installation->getPackage()->packageID,
289 'preset' => 0
290 ];
291
292 $options = $element->getElementsByTagName('options')->item(0);
293 if ($options) {
294 $data['options'] = StringUtil::normalizeCsv($options->nodeValue);
295 }
296
297 $permissions = $element->getElementsByTagName('permissions')->item(0);
298 if ($permissions) {
299 $data['permissions'] = StringUtil::normalizeCsv($permissions->nodeValue);
300 }
301
302 // the presence of a `preset` element is treated as `<preset>1</preset>
303 if ($element->getElementsByTagName('preset')->length === 1) {
304 $data['preset'] = 1;
305 }
306
307 $presetMailNotificationType = $element->getElementsByTagName('presetmailnotificationtype')->item(0);
308 if ($presetMailNotificationType && in_array($presetMailNotificationType->nodeValue, ['instant', 'daily'])) {
309 $data['presetMailNotificationType'] = $presetMailNotificationType->nodeValue;
310 }
311
312 return $data;
313 }
314
315 /**
316 * @inheritDoc
317 * @since 3.2
318 */
319 public function getElementIdentifier(\DOMElement $element): string {
320 return sha1(
321 $element->getElementsByTagName('name')->item(0)->nodeValue . '/' .
322 $element->getElementsByTagName('objecttype')->item(0)->nodeValue
323 );
324 }
325
326 /**
327 * @inheritDoc
328 * @since 3.2
329 */
330 protected function setEntryListKeys(IDevtoolsPipEntryList $entryList) {
331 $entryList->setKeys([
332 'name' => 'wcf.acp.pip.userNotificationEvent.name',
333 'className' => 'wcf.acp.pip.userNotificationEvent.className'
334 ]);
335 }
336
337 /**
338 * @inheritDoc
339 * @since 3.2
340 */
341 protected function sortDocument(\DOMDocument $document) {
342 $this->sortImportDelete($document);
343
344 $compareFunction = function(\DOMElement $element1, \DOMElement $element2) {
345 $objectType1 = $element1->getElementsByTagName('objecttype')->item(0)->nodeValue;
346 $objectType2 = $element2->getElementsByTagName('objecttype')->item(0)->nodeValue;
347
348 if ($objectType1 !== $objectType2) {
349 return strcmp($objectType1, $objectType2);
350 }
351
352 return strcmp(
353 $element1->getElementsByTagName('name')->item(0)->nodeValue,
354 $element2->getElementsByTagName('name')->item(0)->nodeValue
355 );
356 };
357
358 $this->sortChildNodes($document->getElementsByTagName('import'), $compareFunction);
359 $this->sortChildNodes($document->getElementsByTagName('delete'), $compareFunction);
360 }
361
362 /**
363 * @inheritDoc
364 * @since 3.2
365 */
366 protected function writeEntry(\DOMDocument $document, IFormDocument $form): \DOMElement {
367 $data = $form->getData()['data'];
368
369 $event = $document->createElement($this->tagName);
370
371 foreach (['name', 'objecttype', 'classname'] as $element) {
372 $event->appendChild(
373 $document->createElement(
374 $element,
375 (string)$data[$element]
376 )
377 );
378 }
379
380 foreach (['options', 'permissions', 'preset', 'presetmailnotificationtype'] as $optionalElement) {
381 if (!empty($data[$optionalElement])) {
382 $event->appendChild(
383 $document->createElement(
384 $optionalElement,
385 (string)$data[$optionalElement]
386 )
387 );
388 }
389 }
390
391 $document->getElementsByTagName('import')->item(0)->appendChild($event);
392
393 return $event;
394 }
395 }