WhispeakAuthPlugin   F
last analyzed

Complexity

Total Complexity 68

Size/Duplication

Total Lines 786
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 68
eloc 281
dl 0
loc 786
rs 2.96
c 0
b 0
f 0

40 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A getAdminUrl() 0 5 1
A create() 0 5 2
A toolIsEnabled() 0 3 1
A uninstallHook() 0 7 1
A isQuizQuestionMarked() 0 9 3
A getQuizQuestionExtraField() 0 13 1
A installHook() 0 7 1
A getLpItemValue() 0 6 1
A getLpItemExtraField() 0 13 1
A questionRequireAuthentify() 0 23 5
A getAuthUidValue() 0 10 1
A protectTool() 0 7 2
A performActionsAfterConfigure() 0 11 2
A install() 0 5 1
A saveEnrollment() 0 20 2
A deleteEnrollment() 0 13 2
A getEnrollmentUrl() 0 3 1
A getMaxAttempts() 0 3 1
A isLpItemMarked() 0 9 3
A getQuizQuestionValue() 0 6 1
A checkUserIsEnrolled() 0 9 2
A uninstall() 0 5 1
A getAuthUidExtraField() 0 14 1
A addAttemptInLearningPath() 0 26 3
A addAttemptInQuiz() 0 26 3
A countSuccessAttemptsInQuiz() 0 12 1
A uninstallEntities() 0 14 2
A installExtraFields() 0 30 1
A quizQuestionAuthentify() 0 18 1
A countAllAttemptsInLearningPath() 0 12 1
A uninstallExtraFields() 0 35 4
A displayNotAllowedMessage() 0 7 2
A countSuccessAttemptsInLearningPath() 0 12 1
A installEntities() 0 14 2
A getApiUrl() 0 5 1
A addAuthenticationAttempt() 0 18 1
A isAllowedToSaveLpItem() 0 17 4
A countAllAttemptsInQuiz() 0 12 1
A isEnabled() 0 3 2

How to fix   Complexity   

Complex Class

Complex classes like WhispeakAuthPlugin often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WhispeakAuthPlugin, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\ExtraField;
5
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
6
use Chamilo\PluginBundle\Entity\WhispeakAuth\LogEvent;
7
use Chamilo\PluginBundle\Entity\WhispeakAuth\LogEventLp;
8
use Chamilo\PluginBundle\Entity\WhispeakAuth\LogEventQuiz;
9
use Chamilo\UserBundle\Entity\User;
10
use Doctrine\ORM\Tools\SchemaTool;
11
12
/**
13
 * Class WhispeakAuthPlugin.
14
 */
15
class WhispeakAuthPlugin extends Plugin implements HookPluginInterface
16
{
17
    public const SETTING_ENABLE = 'enable';
18
    public const SETTING_MAX_ATTEMPTS = 'max_attempts';
19
    public const SETTING_2FA = '2fa';
20
    public const SETTING_API_URL = 'api_url';
21
    public const SETTING_TOKEN = 'token';
22
23
    public const EXTRAFIELD_AUTH_UID = 'whispeak_auth_uid';
24
    public const EXTRAFIELD_LP_ITEM = 'whispeak_lp_item';
25
    public const EXTRAFIELD_QUIZ_QUESTION = 'whispeak_quiz_question';
26
27
    public const SESSION_FAILED_LOGINS = 'whispeak_failed_logins';
28
    public const SESSION_2FA_USER = 'whispeak_user_id';
29
    public const SESSION_LP_ITEM = 'whispeak_lp_item';
30
    public const SESSION_QUIZ_QUESTION = 'whispeak_quiz_question';
31
    public const SESSION_AUTH_PASSWORD = 'whispeak_auth_password';
32
    public const SESSION_SENTENCE_TEXT = 'whispeak_sentence_text';
33
34
    /**
35
     * StudentFollowUpPlugin constructor.
36
     */
37
    protected function __construct()
38
    {
39
        parent::__construct(
40
            '0.1',
41
            'Angel Fernando Quiroz',
42
            [
43
                self::SETTING_ENABLE => 'boolean',
44
                self::SETTING_API_URL => 'text',
45
                self::SETTING_TOKEN => 'text',
46
                self::SETTING_MAX_ATTEMPTS => 'text',
47
                self::SETTING_2FA => 'boolean',
48
            ]
49
        );
50
    }
51
52
    /**
53
     * Get the admin URL for the plugin if Plugin::isAdminPlugin is true.
54
     *
55
     * @return string
56
     */
57
    public function getAdminUrl()
58
    {
59
        $webPath = api_get_path(WEB_PLUGIN_PATH).$this->get_name();
60
61
        return "$webPath/admin.php";
62
    }
63
64
    /**
65
     * @return WhispeakAuthPlugin
66
     */
67
    public static function create()
68
    {
69
        static $result = null;
70
71
        return $result ? $result : $result = new self();
72
    }
73
74
    /**
75
     * @throws \Doctrine\ORM\Tools\ToolsException
76
     */
77
    public function install()
78
    {
79
        $this->installExtraFields();
80
        $this->installEntities();
81
        $this->installHook();
82
    }
83
84
    public function uninstall()
85
    {
86
        $this->uninstallHook();
87
        $this->uninstallExtraFields();
88
        $this->uninstallEntities();
89
    }
90
91
    /**
92
     * @return ExtraField
93
     */
94
    public static function getAuthUidExtraField()
95
    {
96
        $em = Database::getManager();
97
        $efRepo = $em->getRepository('ChamiloCoreBundle:ExtraField');
98
99
        /** @var ExtraField $extraField */
100
        $extraField = $efRepo->findOneBy(
101
            [
102
                'variable' => self::EXTRAFIELD_AUTH_UID,
103
                'extraFieldType' => ExtraField::USER_FIELD_TYPE,
104
            ]
105
        );
106
107
        return $extraField;
108
    }
109
110
    /**
111
     * @return ExtraField
112
     */
113
    public static function getLpItemExtraField()
114
    {
115
        $efRepo = Database::getManager()->getRepository('ChamiloCoreBundle:ExtraField');
116
117
        /** @var ExtraField $extraField */
118
        $extraField = $efRepo->findOneBy(
119
            [
120
                'variable' => self::EXTRAFIELD_LP_ITEM,
121
                'extraFieldType' => ExtraField::LP_ITEM_FIELD_TYPE,
122
            ]
123
        );
124
125
        return $extraField;
126
    }
127
128
    /**
129
     * @return ExtraField
130
     */
131
    public static function getQuizQuestionExtraField()
132
    {
133
        $efRepo = Database::getManager()->getRepository('ChamiloCoreBundle:ExtraField');
134
135
        /** @var ExtraField $extraField */
136
        $extraField = $efRepo->findOneBy(
137
            [
138
                'variable' => self::EXTRAFIELD_QUIZ_QUESTION,
139
                'extraFieldType' => ExtraField::QUESTION_FIELD_TYPE,
140
            ]
141
        );
142
143
        return $extraField;
144
    }
145
146
    /**
147
     * @param int $userId
148
     *
149
     * @return ExtraFieldValues
150
     */
151
    public static function getAuthUidValue($userId)
152
    {
153
        $extraField = self::getAuthUidExtraField();
154
        $em = Database::getManager();
155
        $efvRepo = $em->getRepository('ChamiloCoreBundle:ExtraFieldValues');
156
157
        /** @var ExtraFieldValues $value */
158
        $value = $efvRepo->findOneBy(['field' => $extraField, 'itemId' => $userId]);
159
160
        return $value;
161
    }
162
163
    /**
164
     * Get the whispeak_lp_item value for a LP item ID.
165
     *
166
     * @param int $lpItemId
167
     *
168
     * @return array|false
169
     */
170
    public static function getLpItemValue($lpItemId)
171
    {
172
        $efv = new ExtraFieldValue('lp_item');
173
        $value = $efv->get_values_by_handler_and_field_variable($lpItemId, self::EXTRAFIELD_LP_ITEM);
174
175
        return $value;
176
    }
177
178
    /**
179
     * @param int $lpItemId
180
     *
181
     * @return bool
182
     */
183
    public static function isLpItemMarked($lpItemId)
184
    {
185
        if (!self::create()->isEnabled()) {
186
            return false;
187
        }
188
189
        $value = self::getLpItemValue($lpItemId);
190
191
        return !empty($value) && !empty($value['value']);
192
    }
193
194
    /**
195
     * Get the whispeak_quiz_question value for a quiz question ID.
196
     *
197
     * @param int $questionId
198
     *
199
     * @return array|false
200
     */
201
    public static function getQuizQuestionValue($questionId)
202
    {
203
        $efv = new ExtraFieldValue('question');
204
        $value = $efv->get_values_by_handler_and_field_variable($questionId, self::EXTRAFIELD_QUIZ_QUESTION);
205
206
        return $value;
207
    }
208
209
    /**
210
     * @param int $questionId
211
     *
212
     * @return bool
213
     */
214
    public static function isQuizQuestionMarked($questionId)
215
    {
216
        if (!self::create()->isEnabled()) {
217
            return false;
218
        }
219
220
        $value = self::getQuizQuestionValue($questionId);
221
222
        return !empty($value) && !empty($value['value']);
223
    }
224
225
    /**
226
     * @param int $questionId
227
     *
228
     * @return bool
229
     */
230
    public static function questionRequireAuthentify($questionId)
231
    {
232
        $isMarked = self::isQuizQuestionMarked($questionId);
233
234
        if (!$isMarked) {
235
            return false;
236
        }
237
238
        $questionInfo = ChamiloSession::read(self::SESSION_QUIZ_QUESTION, []);
239
240
        if (empty($questionInfo)) {
241
            return true;
242
        }
243
244
        if ((int) $questionId !== $questionInfo['question']) {
245
            return true;
246
        }
247
248
        if (false === $questionInfo['passed']) {
249
            return true;
250
        }
251
252
        return false;
253
    }
254
255
    /**
256
     * @param int $userId
257
     *
258
     * @return bool
259
     */
260
    public static function checkUserIsEnrolled($userId)
261
    {
262
        $value = self::getAuthUidValue($userId);
263
264
        if (empty($value)) {
265
            return false;
266
        }
267
268
        return !empty($value->getValue());
269
    }
270
271
    /**
272
     * @return string
273
     */
274
    public static function getEnrollmentUrl()
275
    {
276
        return api_get_path(WEB_PLUGIN_PATH).'whispeakauth/enrollment.php';
277
    }
278
279
    /**
280
     * @param string $uid
281
     *
282
     * @throws \Doctrine\ORM\OptimisticLockException
283
     */
284
    public function saveEnrollment(User $user, $uid)
285
    {
286
        $em = Database::getManager();
287
        $extraFieldValue = self::getAuthUidValue($user->getId());
288
289
        if (empty($extraFieldValue)) {
290
            $extraField = self::getAuthUidExtraField();
291
            $now = new DateTime('now', new DateTimeZone('UTC'));
292
293
            $extraFieldValue = new ExtraFieldValues();
294
            $extraFieldValue
295
                ->setField($extraField)
296
                ->setItemId($user->getId())
297
                ->setUpdatedAt($now);
298
        }
299
300
        $extraFieldValue->setValue($uid);
301
302
        $em->persist($extraFieldValue);
303
        $em->flush();
304
    }
305
306
    /**
307
     * @return bool
308
     */
309
    public function toolIsEnabled()
310
    {
311
        return 'true' === $this->get(self::SETTING_ENABLE);
312
    }
313
314
    /**
315
     * Access not allowed when tool is not enabled.
316
     *
317
     * @param bool $printHeaders Optional. Print headers.
318
     */
319
    public function protectTool($printHeaders = true)
320
    {
321
        if ($this->toolIsEnabled()) {
322
            return;
323
        }
324
325
        api_not_allowed($printHeaders);
326
    }
327
328
    /**
329
     * Get the max_attemtps option.
330
     *
331
     * @return int
332
     */
333
    public function getMaxAttempts()
334
    {
335
        return (int) $this->get(self::SETTING_MAX_ATTEMPTS);
336
    }
337
338
    /**
339
     * Install hook when saving the plugin configuration.
340
     *
341
     * @return WhispeakAuthPlugin
342
     */
343
    public function performActionsAfterConfigure()
344
    {
345
        $observer = WhispeakConditionalLoginHook::create();
346
347
        if ('true' === $this->get(self::SETTING_2FA)) {
348
            HookConditionalLogin::create()->attach($observer);
349
        } else {
350
            HookConditionalLogin::create()->detach($observer);
351
        }
352
353
        return $this;
354
    }
355
356
    /**
357
     * This method will call the Hook management insertHook to add Hook observer from this plugin.
358
     */
359
    public function installHook()
360
    {
361
        $observer = WhispeakMyStudentsLpTrackingHook::create();
362
        HookMyStudentsLpTracking::create()->attach($observer);
363
364
        $observer = WhispeakMyStudentsQuizTrackingHook::create();
365
        HookMyStudentsQuizTracking::create()->attach($observer);
366
    }
367
368
    /**
369
     * This method will call the Hook management deleteHook to disable Hook observer from this plugin.
370
     */
371
    public function uninstallHook()
372
    {
373
        $observer = WhispeakConditionalLoginHook::create();
374
        HookConditionalLogin::create()->detach($observer);
375
376
        $observer = WhispeakMyStudentsLpTrackingHook::create();
377
        HookMyStudentsLpTracking::create()->detach($observer);
378
    }
379
380
    /**
381
     * @param int $userId
382
     *
383
     * @throws \Doctrine\ORM\OptimisticLockException
384
     *
385
     * @return bool
386
     */
387
    public static function deleteEnrollment($userId)
388
    {
389
        $extraFieldValue = self::getAuthUidValue($userId);
390
391
        if (empty($extraFieldValue)) {
392
            return false;
393
        }
394
395
        $em = Database::getManager();
396
        $em->remove($extraFieldValue);
397
        $em->flush();
398
399
        return true;
400
    }
401
402
    /**
403
     * Check if the WhispeakAuth plugin is installed and enabled.
404
     *
405
     * @param bool $checkEnabled Check if, additionnally to being installed, the plugin is enabled
406
     */
407
    public function isEnabled(bool $checkEnabled = false): bool
408
    {
409
        return parent::isEnabled() && 'true' === api_get_plugin_setting('whispeakauth', self::SETTING_ENABLE);
410
    }
411
412
    /**
413
     * @param int $lpItemId
414
     *
415
     * @return bool
416
     */
417
    public static function isAllowedToSaveLpItem($lpItemId)
418
    {
419
        if (!self::isLpItemMarked($lpItemId)) {
420
            return true;
421
        }
422
423
        $markedItem = ChamiloSession::read(self::SESSION_LP_ITEM, []);
424
425
        if (empty($markedItem)) {
426
            return true;
427
        }
428
429
        if ((int) $lpItemId !== (int) $markedItem['lp_item']) {
430
            return true;
431
        }
432
433
        return false;
434
    }
435
436
    /**
437
     * Display a error message.
438
     *
439
     * @param string|null $error Optional. The message text
440
     */
441
    public static function displayNotAllowedMessage($error = null)
442
    {
443
        $error = empty($error) ? get_lang('NotAllowed') : $error;
444
445
        echo Display::return_message($error, 'error', false);
446
447
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
448
    }
449
450
    /**
451
     * @param int $questionId
452
     *
453
     * @throws Exception
454
     *
455
     * @return string
456
     */
457
    public static function quizQuestionAuthentify($questionId, Exercise $exercise)
458
    {
459
        ChamiloSession::write(
460
            self::SESSION_QUIZ_QUESTION,
461
            [
462
                'quiz' => (int) $exercise->iid,
463
                'question' => (int) $questionId,
464
                'url_params' => $_SERVER['QUERY_STRING'],
465
                'passed' => false,
466
            ]
467
        );
468
469
        $template = new Template('', false, false, false, true, false, false);
470
        $template->assign('question', $questionId);
471
        $template->assign('exercise', $exercise->iid);
472
        $content = $template->fetch('whispeakauth/view/quiz_question.html.twig');
473
474
        echo $content;
475
    }
476
477
    /**
478
     * @param int $status
479
     * @param int $userId
480
     * @param int $lpItemId
481
     * @param int $lpId
482
     *
483
     * @throws \Doctrine\ORM\ORMException
484
     * @throws \Doctrine\ORM\OptimisticLockException
485
     * @throws \Doctrine\ORM\TransactionRequiredException
486
     *
487
     * @return LogEventLp|null
488
     */
489
    public function addAttemptInLearningPath($status, $userId, $lpItemId, $lpId)
490
    {
491
        $em = Database::getManager();
492
493
        $user = api_get_user_entity($userId);
494
        $lpItem = $em->find('ChamiloCourseBundle:CLpItem', $lpItemId);
495
        $lp = $em->find('ChamiloCourseBundle:CLp', $lpId);
496
497
        if (empty($lp) || empty($lpItem)) {
498
            return null;
499
        }
500
501
        $logEvent = new LogEventLp();
502
        $logEvent
503
            ->setLpItem($lpItem)
504
            ->setLp($lp)
505
            ->setUser($user)
506
            ->setDatetime(
507
                api_get_utc_datetime(null, false, true)
508
            )
509
            ->setActionStatus($status);
510
511
        $em->persist($logEvent);
512
        $em->flush();
513
514
        return $logEvent;
515
    }
516
517
    /**
518
     * @param int $status
519
     * @param int $userId
520
     * @param int $questionId
521
     * @param int $quizId
522
     *
523
     * @throws \Doctrine\ORM\ORMException
524
     * @throws \Doctrine\ORM\OptimisticLockException
525
     * @throws \Doctrine\ORM\TransactionRequiredException
526
     *
527
     * @return LogEventQuiz|null
528
     */
529
    public function addAttemptInQuiz($status, $userId, $questionId, $quizId)
530
    {
531
        $em = Database::getManager();
532
533
        $user = api_get_user_entity($userId);
534
        $question = $em->find('ChamiloCourseBundle:CQuizQuestion', $questionId);
535
        $quiz = $em->find('ChamiloCourseBundle:CQuiz', $quizId);
536
537
        if (empty($quiz) || empty($question)) {
538
            return null;
539
        }
540
541
        $logEvent = new LogEventQuiz();
542
        $logEvent
543
            ->setQuestion($question)
544
            ->setQuiz($quiz)
545
            ->setUser($user)
546
            ->setDatetime(
547
                api_get_utc_datetime(null, false, true)
548
            )
549
            ->setActionStatus($status);
550
551
        $em->persist($logEvent);
552
        $em->flush();
553
554
        return $logEvent;
555
    }
556
557
    /**
558
     * @param int $status
559
     * @param int $userId
560
     *
561
     * @throws \Doctrine\ORM\ORMException
562
     * @throws \Doctrine\ORM\OptimisticLockException
563
     * @throws \Doctrine\ORM\TransactionRequiredException
564
     *
565
     * @return LogEvent|null
566
     */
567
    public function addAuthenticationAttempt($status, $userId)
568
    {
569
        $em = Database::getManager();
570
571
        $user = api_get_user_entity($userId);
572
573
        $logEvent = new LogEvent();
574
        $logEvent
575
            ->setUser($user)
576
            ->setDatetime(
577
                api_get_utc_datetime(null, false, true)
578
            )
579
            ->setActionStatus($status);
580
581
        $em->persist($logEvent);
582
        $em->flush();
583
584
        return $logEvent;
585
    }
586
587
    /**
588
     * @param int $lpId
589
     * @param int $userId
590
     *
591
     * @throws \Doctrine\ORM\Query\QueryException
592
     *
593
     * @return string
594
     */
595
    public static function countAllAttemptsInLearningPath($lpId, $userId)
596
    {
597
        $query = Database::getManager()
598
            ->createQuery(
599
                'SELECT COUNT(log) AS c FROM ChamiloPluginBundle:WhispeakAuth\LogEventLp log
600
                WHERE log.lp = :lp AND log.user = :user'
601
            )
602
            ->setParameters(['lp' => $lpId, 'user' => $userId]);
603
604
        $totalCount = (int) $query->getSingleScalarResult();
605
606
        return $totalCount;
607
    }
608
609
    /**
610
     * @param int $lpId
611
     * @param int $userId
612
     *
613
     * @throws \Doctrine\ORM\Query\QueryException
614
     *
615
     * @return string
616
     */
617
    public static function countSuccessAttemptsInLearningPath($lpId, $userId)
618
    {
619
        $query = Database::getManager()
620
            ->createQuery(
621
                'SELECT COUNT(log) AS c FROM ChamiloPluginBundle:WhispeakAuth\LogEventLp log
622
                WHERE log.lp = :lp AND log.user = :user AND log.actionStatus = :status'
623
            )
624
            ->setParameters(['lp' => $lpId, 'user' => $userId, 'status' => LogEvent::STATUS_SUCCESS]);
625
626
        $totalCount = (int) $query->getSingleScalarResult();
627
628
        return $totalCount;
629
    }
630
631
    /**
632
     * @param int $quizId
633
     * @param int $userId
634
     *
635
     * @throws \Doctrine\ORM\Query\QueryException
636
     *
637
     * @return string
638
     */
639
    public static function countAllAttemptsInQuiz($quizId, $userId)
640
    {
641
        $query = Database::getManager()
642
            ->createQuery(
643
                'SELECT COUNT(log) AS c FROM ChamiloPluginBundle:WhispeakAuth\LogEventQuiz log
644
                WHERE log.quiz = :quiz AND log.user = :user'
645
            )
646
            ->setParameters(['quiz' => $quizId, 'user' => $userId]);
647
648
        $totalCount = (int) $query->getSingleScalarResult();
649
650
        return $totalCount;
651
    }
652
653
    /**
654
     * @param int $quizId
655
     * @param int $userId
656
     *
657
     * @throws \Doctrine\ORM\Query\QueryException
658
     *
659
     * @return string
660
     */
661
    public static function countSuccessAttemptsInQuiz($quizId, $userId)
662
    {
663
        $query = Database::getManager()
664
            ->createQuery(
665
                'SELECT COUNT(log) AS c FROM ChamiloPluginBundle:WhispeakAuth\LogEventQuiz log
666
                WHERE log.quiz = :quiz AND log.user = :user AND log.actionStatus = :status'
667
            )
668
            ->setParameters(['quiz' => $quizId, 'user' => $userId, 'status' => LogEvent::STATUS_SUCCESS]);
669
670
        $totalCount = (int) $query->getSingleScalarResult();
671
672
        return $totalCount;
673
    }
674
675
    /**
676
     * @return string
677
     */
678
    public function getApiUrl()
679
    {
680
        $url = $this->get(self::SETTING_API_URL);
681
682
        return trim($url, " \t\n\r \v/").'/';
683
    }
684
685
    /**
686
     * Install extra fields for user, learning path and quiz question.
687
     */
688
    private function installExtraFields()
689
    {
690
        UserManager::create_extra_field(
691
            self::EXTRAFIELD_AUTH_UID,
692
            \ExtraField::FIELD_TYPE_TEXT,
693
            $this->get_lang('Whispeak uid'),
694
            ''
695
        );
696
697
        LpItem::createExtraField(
698
            self::EXTRAFIELD_LP_ITEM,
699
            \ExtraField::FIELD_TYPE_CHECKBOX,
700
            $this->get_lang('MarkForSpeechAuthentication'),
701
            '0',
702
            true,
703
            true
704
        );
705
706
        $extraField = new \ExtraField('question');
707
        $params = [
708
            'variable' => self::EXTRAFIELD_QUIZ_QUESTION,
709
            'field_type' => \ExtraField::FIELD_TYPE_CHECKBOX,
710
            'display_text' => $this->get_lang('MarkForSpeechAuthentication'),
711
            'default_value' => '0',
712
            'changeable' => true,
713
            'visible_to_self' => true,
714
            'visible_to_others' => false,
715
        ];
716
717
        $extraField->save($params);
718
    }
719
720
    /**
721
     * Install the Doctrine's entities.
722
     *
723
     * @throws \Doctrine\ORM\Tools\ToolsException
724
     */
725
    private function installEntities()
726
    {
727
        $em = Database::getManager();
728
729
        if ($em->getConnection()->getSchemaManager()->tablesExist(['whispeak_log_event'])) {
730
            return;
731
        }
732
733
        $schemaTool = new SchemaTool($em);
734
        $schemaTool->createSchema(
735
            [
736
                $em->getClassMetadata(LogEvent::class),
737
                $em->getClassMetadata(LogEventLp::class),
738
                $em->getClassMetadata(LogEventQuiz::class),
739
            ]
740
        );
741
    }
742
743
    /**
744
     * Uninstall extra fields for user, learning path and quiz question.
745
     */
746
    private function uninstallExtraFields()
747
    {
748
        $em = Database::getManager();
749
750
        $authIdExtrafield = self::getAuthUidExtraField();
751
752
        if (!empty($authIdExtrafield)) {
753
            $em
754
                ->createQuery('DELETE FROM ChamiloCoreBundle:ExtraFieldValues efv WHERE efv.field = :field')
755
                ->execute(['field' => $authIdExtrafield]);
756
757
            $em->remove($authIdExtrafield);
758
            $em->flush();
759
        }
760
761
        $lpItemExtrafield = self::getLpItemExtraField();
762
763
        if (!empty($lpItemExtrafield)) {
764
            $em
765
                ->createQuery('DELETE FROM ChamiloCoreBundle:ExtraFieldValues efv WHERE efv.field = :field')
766
                ->execute(['field' => $lpItemExtrafield]);
767
768
            $em->remove($lpItemExtrafield);
769
            $em->flush();
770
        }
771
772
        $quizQuestionExtrafield = self::getQuizQuestionExtraField();
773
774
        if (!empty($quizQuestionExtrafield)) {
775
            $em
776
                ->createQuery('DELETE FROM ChamiloCoreBundle:ExtraFieldValues efv WHERE efv.field = :field')
777
                ->execute(['field' => $quizQuestionExtrafield]);
778
779
            $em->remove($quizQuestionExtrafield);
780
            $em->flush();
781
        }
782
    }
783
784
    /**
785
     * Uninstall the Doctrine's entities.
786
     */
787
    private function uninstallEntities()
788
    {
789
        $em = Database::getManager();
790
791
        if (!$em->getConnection()->getSchemaManager()->tablesExist(['whispeak_log_event'])) {
792
            return;
793
        }
794
795
        $schemaTool = new SchemaTool($em);
796
        $schemaTool->dropSchema(
797
            [
798
                $em->getClassMetadata(LogEvent::class),
799
                $em->getClassMetadata(LogEventLp::class),
800
                $em->getClassMetadata(LogEventQuiz::class),
801
            ]
802
        );
803
    }
804
}
805