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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
<?php

namespace Mautic\CoreBundle\Model;

use Mautic\CoreBundle\Helper\InputHelper;
use Mautic\UserBundle\Entity\User;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Contracts\EventDispatcher\Event;

/**
 * @template T of object
 *
 * @extends AbstractCommonModel<T>
 */
class FormModel extends AbstractCommonModel
{
    /**
     * Lock an entity to prevent multiple people from editing.
     *
     * @param object $entity
     */
    public function lockEntity($entity): void
    {
        // lock the row if applicable
        if (method_exists($entity, 'setCheckedOut') && method_exists($entity, 'getId') && $entity->getId()) {
            if ($this->userHelper->getUser()->getId()) {
                $entity->setCheckedOut(new \DateTime());
                $entity->setCheckedOutBy($this->userHelper->getUser());
                $this->em->persist($entity);
                $this->em->flush();
            }
        }
    }

    /**
     * Check to see if the entity is locked.
     *
     * @param object $entity
     */
    public function isLocked($entity): bool
    {
        if (method_exists($entity, 'getCheckedOut')) {
            $checkedOut = $entity->getCheckedOut();
            if (!empty($checkedOut) && $checkedOut instanceof \DateTime) {
                $checkedOutBy = $entity->getCheckedOutBy();
                $maxLockTime  = $this->coreParametersHelper->get('max_entity_lock_time', 0);

                if (0 != $maxLockTime && is_numeric($maxLockTime)) {
                    $lockValidityDate = clone $checkedOut;
                    $lockValidityDate->add(new \DateInterval('PT'.$maxLockTime.'S'));
                } else {
                    $lockValidityDate = false;
                }

                // is lock expired ?
                if (false !== $lockValidityDate && (new \DateTime()) > $lockValidityDate) {
                    return false;
                }

                // is it checked out by the current user?
                if (!empty($checkedOutBy) && ($checkedOutBy !== $this->userHelper->getUser()->getId())) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Unlock an entity that prevents multiple people from editing.
     *
     * @param object $entity
     * @param        $extra  Can be used by model to determine what to unlock
     */
    public function unlockEntity($entity, $extra = null): void
    {
        // unlock the row if applicable
        if (method_exists($entity, 'setCheckedOut') && method_exists($entity, 'getId') && $entity->getId()) {
            // flush any potential changes
            $this->em->refresh($entity);

            $entity->setCheckedOut(null);
            $entity->setCheckedOutBy(null);

            $this->em->persist($entity);
            $this->em->flush();
        }
    }

    /**
     * Create/edit entity.
     *
     * @param object $entity
     * @param bool   $unlock
     *
     * @phpstan-param T $entity
     */
    public function saveEntity($entity, $unlock = true): void
    {
        $isNew = $this->isNewEntity($entity);

        // set some defaults
        $this->setTimestamps($entity, $isNew, $unlock);

        $event = $this->dispatchEvent('pre_save', $entity, $isNew);
        $this->getRepository()->saveEntity($entity);
        $this->dispatchEvent('post_save', $entity, $isNew, $event);
    }

    /**
     * Create/edit entity then detach to preserve RAM.
     *
     * @param bool $unlock
     */
    public function saveAndDetachEntity($entity, $unlock = true): void
    {
        $this->saveEntity($entity, $unlock);

        $this->em->detach($entity);
    }

    /**
     * Save an array of entities.
     *
     * @param iterable<T> $entities
     * @param bool        $unlock
     */
    public function saveEntities($entities, $unlock = true): void
    {
        // iterate over the results so the events are dispatched on each delete
        $batchSize = 20;
        $i         = 0;
        foreach ($entities as $entity) {
            $isNew = $this->isNewEntity($entity);

            // set some defaults
            $this->setTimestamps($entity, $isNew, $unlock);

            $event = $this->dispatchEvent('pre_save', $entity, $isNew);
            $this->getRepository()->saveEntity($entity, false);
            if (0 === ++$i % $batchSize) {
                $this->em->flush();
            }
        }

        $this->em->flush();

        // Dispatch post events after everything has been flushed
        foreach ($entities as $entity) {
            $this->dispatchEvent('post_save', $entity, $isNew, $event);
        }
    }

    /**
     * Determines if an entity is new or not.
     *
     * @param mixed $entity
     *
     * @return bool
     */
    public function isNewEntity($entity)
    {
        if (method_exists($entity, 'isNew')) {
            return $entity->isNew();
        }

        if (method_exists($entity, 'getId')) {
            $isNew = ($entity->getId()) ? false : true;
        } else {
            $isNew = \Doctrine\ORM\UnitOfWork::STATE_NEW === $this->em->getUnitOfWork()->getEntityState($entity);
        }

        return $isNew;
    }

    /**
     * Toggles entity publish status.
     *
     * @param object $entity
     *
     * @return bool Force browser refresh
     */
    public function togglePublishStatus($entity): bool
    {
        if (method_exists($entity, 'setIsPublished')) {
            $status = $entity->getPublishStatus();

            switch ($status) {
                case 'unpublished':
                    $entity->setIsPublished(true);
                    break;
                case 'published':
                case 'expired':
                case 'pending':
                    $this->dispatchEvent('pre_unpublish', $entity);
                    $entity->setIsPublished(false);
                    break;
            }

            // set timestamp changes
            $this->setTimestamps($entity, false, false);
        } elseif (method_exists($entity, 'setIsEnabled')) {
            $enabled    = $entity->getIsEnabled();
            $newSetting = ($enabled) ? false : true;
            $entity->setIsEnabled($newSetting);
        }

        // hit up event listeners
        $event = $this->dispatchEvent('pre_save', $entity);
        $this->getRepository()->saveEntity($entity);
        $this->dispatchEvent('post_save', $entity, false, $event);

        return false;
    }

    /**
     * Set timestamps and user ids.
     *
     * @param object $entity
     * @param bool   $isNew
     * @param bool   $unlock
     */
    public function setTimestamps(&$entity, $isNew, $unlock = true): void
    {
        if ($isNew) {
            if (method_exists($entity, 'setDateAdded') && !$entity->getDateAdded()) {
                $entity->setDateAdded(new \DateTime());
            }

            if ($this->userHelper->getUser() instanceof User) {
                if (method_exists($entity, 'setCreatedBy') && !$entity->getCreatedBy()) {
                    $entity->setCreatedBy($this->userHelper->getUser());
                } elseif (method_exists($entity, 'setCreatedByUser') && !$entity->getCreatedByUser()) {
                    $entity->setCreatedByUser($this->userHelper->getUser()->getName());
                }
            }
        } else {
            if (method_exists($entity, 'setDateModified')) {
                $setDateModified = true;
                if (method_exists($entity, 'getChanges')) {
                    $changes = $entity->getChanges();
                    if (empty($changes)) {
                        $setDateModified = false;
                    }
                    if (is_array($changes) && 1 === count($changes) && isset($changes['dateLastActive'])) {
                        $setDateModified = false;
                    }
                }
                if ($setDateModified) {
                    $dateModified = (defined('MAUTIC_DATE_MODIFIED_OVERRIDE')) ? \DateTime::createFromFormat('U', MAUTIC_DATE_MODIFIED_OVERRIDE)
                        : new \DateTime();
                    $entity->setDateModified($dateModified);
                }
            }

            if ($this->userHelper->getUser() instanceof User) {
                if (method_exists($entity, 'setModifiedBy')) {
                    $entity->setModifiedBy($this->userHelper->getUser());
                } elseif (method_exists($entity, 'setModifiedByUser')) {
                    $entity->setModifiedByUser($this->userHelper->getUser()->getName());
                }
            }
        }

        // unlock the row if applicable
        if ($unlock && method_exists($entity, 'setCheckedOut')) {
            $entity->setCheckedOut(null);
            $entity->setCheckedOutBy(null);
        }
    }

    /**
     * Delete an entity.
     *
     * @param object $entity
     */
    public function deleteEntity($entity): void
    {
        // take note of ID before doctrine wipes it out
        $id    = $entity->getId();
        $event = $this->dispatchEvent('pre_delete', $entity);
        $this->getRepository()->deleteEntity($entity);

        // set the id for use in events
        $entity->deletedId = $id;
        $this->dispatchEvent('post_delete', $entity, false, $event);
    }

    /**
     * Delete an array of entities.
     *
     * @param mixed[] $ids
     *
     * @return mixed[]
     */
    public function deleteEntities($ids): array
    {
        $entities = [];
        // iterate over the results so the events are dispatched on each delete
        $batchSize = 20;
        foreach ($ids as $k => $id) {
            $entity        = $this->getEntity($id);
            $entities[$id] = $entity;
            if (null !== $entity) {
                $event = $this->dispatchEvent('pre_delete', $entity);
                $this->getRepository()->deleteEntity($entity, false);
                // set the id for use in events
                $entity->deletedId = $id;
                $this->dispatchEvent('post_delete', $entity, false, $event);
            }
            if (0 === (($k + 1) % $batchSize)) {
                $this->em->flush();
            }
        }
        $this->em->flush();

        // retrieving the entities while here so may as well return them so they can be used if needed
        return $entities;
    }

    /**
     * Creates the appropriate form per the model.
     *
     * @param object      $entity
     * @param string|null $action
     * @param array       $options
     *
     * @return \Symfony\Component\Form\FormInterface<mixed>
     *
     * @throws NotFoundHttpException
     */
    public function createForm($entity, FormFactoryInterface $formFactory, $action = null, $options = []): FormInterface
    {
        throw new NotFoundHttpException('Object does not support edits.');
    }

    /**
     * Dispatches events for child classes.
     *
     * @param string $action
     * @param object $entity
     * @param bool   $isNew
     */
    protected function dispatchEvent($action, &$entity, $isNew = false, Event $event = null): ?Event
    {
        // ...

        return $event;
    }

    /**
     * Set default subject for user contact form.
     *
     * @param string $subject
     * @param object $entity
     */
    public function getUserContactSubject($subject, $entity): string
    {
        $msg = match ($subject) {
            'locked' => 'mautic.user.user.contact.locked',
            default  => 'mautic.user.user.contact.regarding',
        };

        $nameGetter = $this->getNameGetter();

        return $this->translator->trans($msg, [
            '%entityName%' => $entity->$nameGetter(),
            '%entityId%'   => $entity->getId(),
        ]);
    }

    /**
     * Returns the function used to name the entity.
     */
    public function getNameGetter(): string
    {
        return 'getName';
    }

    /**
     * Cleans a string to be used as an alias. The returned string will be alphanumeric or underscore, less than 25 characters
     * and if it is a reserved SQL keyword, it will be prefixed with f_.
     *
     * @param string   $prefix            Used when the alias is a reserved keyword by the database platform
     * @param int      $maxLength         Maximum number of characters used; 0 to disable
     * @param string   $spaceCharacter    Character to replace spaces with
     * @param string[] $allowedCharacters Allowed characters in alias
     *
     * @throws \Doctrine\DBAL\Exception
     */
    public function cleanAlias(
        string $alias,
        string $prefix = '',
        int $maxLength = 0,
        string $spaceCharacter = '_',
        array $allowedCharacters = []
    ): string {
        // Transliterate to latin characters
        $alias = InputHelper::transliterate(trim($alias));

        // Some labels are quite long if a question so cut this short
        $alias = strtolower(InputHelper::alphanum($alias, false, $spaceCharacter, $allowedCharacters));

        // Ensure we have something
        if (empty($alias)) {
            $alias = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 5);
        }

        // Trim if applicable
        if ($maxLength) {
            $alias = substr($alias, 0, $maxLength);
        }

        if (str_ends_with($alias, '_')) {
            $alias = substr($alias, 0, -1);
        }

        // Check that alias is SQL safe since it will be used for the column name
        $databasePlatform = $this->em->getConnection()->getDatabasePlatform();
        $reservedWords    = $databasePlatform->getReservedKeywordsList();

        if ($reservedWords->isKeyword($alias) || is_numeric($alias)) {
            $alias = $prefix.$alias;
        }

        return $alias;
    }

    /**
     * Catch the exception in production and log the error.
     * Throw the exception in the dev mode only.
     */
    protected function flushAndCatch()
    {
        try {
            $this->em->flush();
        } catch (\Exception $ex) {
            if (MAUTIC_ENV === 'dev') {
                throw $ex;
            }

            $this->logger->error(
                $ex->getMessage(),
                ['exception' => $ex]
            );
        }
    }
}