Passed
Push — 1.11.x ( cf7018...7ebf39 )
by Angel Fernando Quiroz
10:11
created

ImsLtiPlugin::doWhenDeletingCourse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 12
rs 10
1
<?php
2
3
/* For license terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\Course;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Course. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use Chamilo\CoreBundle\Entity\Session;
7
use Chamilo\CourseBundle\Entity\CTool;
8
use Chamilo\PluginBundle\Entity\ImsLti\ImsLtiTool;
9
use Chamilo\PluginBundle\Entity\ImsLti\Platform;
10
use Chamilo\UserBundle\Entity\User;
11
use Doctrine\DBAL\DBALException;
12
use Symfony\Component\Filesystem\Filesystem;
13
14
/**
15
 * Description of MsiLti.
16
 *
17
 * @author Angel Fernando Quiroz Campos <[email protected]>
18
 */
19
class ImsLtiPlugin extends Plugin
20
{
21
    const TABLE_TOOL = 'plugin_ims_lti_tool';
22
    const TABLE_PLATFORM = 'plugin_ims_lti_platform';
23
24
    public $isAdminPlugin = true;
25
26
    protected function __construct()
27
    {
28
        $version = '1.8.0';
29
        $author = 'Angel Fernando Quiroz Campos';
30
31
        $message = Display::return_message($this->get_lang('GenerateKeyPairInfo'));
32
        $settings = [
33
            $message => 'html',
34
            'enabled' => 'boolean',
35
        ];
36
37
        parent::__construct($version, $author, $settings);
38
39
        $this->setCourseSettings();
40
    }
41
42
    /**
43
     * Get the class instance.
44
     *
45
     * @staticvar MsiLtiPlugin $result
46
     *
47
     * @return ImsLtiPlugin
48
     */
49
    public static function create()
50
    {
51
        static $result = null;
52
53
        return $result ?: $result = new self();
54
    }
55
56
    /**
57
     * Get the plugin directory name.
58
     */
59
    public function get_name()
60
    {
61
        return 'ims_lti';
62
    }
63
64
    /**
65
     * Install the plugin. Setup the database.
66
     */
67
    public function install()
68
    {
69
        $pluginEntityPath = $this->getEntityPath();
70
71
        if (!is_dir($pluginEntityPath)) {
72
            if (!is_writable(dirname($pluginEntityPath))) {
73
                $message = get_lang('ErrorCreatingDir').': '.$pluginEntityPath;
74
                Display::addFlash(Display::return_message($message, 'error'));
75
76
                return false;
77
            }
78
79
            mkdir($pluginEntityPath, api_get_permissions_for_new_directories());
80
        }
81
82
        $fs = new Filesystem();
83
        $fs->mirror(__DIR__.'/Entity/', $pluginEntityPath, null, ['override']);
84
85
        $this->createPluginTables();
86
    }
87
88
    /**
89
     * Save configuration for plugin.
90
     *
91
     * Generate a new key pair for platform when enabling plugin.
92
     *
93
     * @throws \Doctrine\ORM\OptimisticLockException
94
     *
95
     * @return $this|Plugin
96
     */
97
    public function performActionsAfterConfigure()
98
    {
99
        $em = Database::getManager();
100
101
        /** @var Platform $platform */
102
        $platform = $em
103
            ->getRepository('ChamiloPluginBundle:ImsLti\Platform')
104
            ->findOneBy([]);
105
106
        if ($this->get('enabled') === 'true') {
107
            if (!$platform) {
0 ignored issues
show
introduced by
$platform is of type Chamilo\PluginBundle\Entity\ImsLti\Platform, thus it always evaluated to true.
Loading history...
108
                $platform = new Platform();
109
            }
110
111
            $keyPair = self::generatePlatformKeys();
112
113
            $platform->setKid($keyPair['kid']);
114
            $platform->publicKey = $keyPair['public'];
115
            $platform->setPrivateKey($keyPair['private']);
116
117
            $em->persist($platform);
118
        } else {
119
            if ($platform) {
0 ignored issues
show
introduced by
$platform is of type Chamilo\PluginBundle\Entity\ImsLti\Platform, thus it always evaluated to true.
Loading history...
120
                $em->remove($platform);
121
            }
122
        }
123
124
        $em->flush();
125
126
        return $this;
127
    }
128
129
    /**
130
     * Unistall plugin. Clear the database.
131
     */
132
    public function uninstall()
133
    {
134
        $pluginEntityPath = $this->getEntityPath();
135
        $fs = new Filesystem();
136
137
        if ($fs->exists($pluginEntityPath)) {
138
            $fs->remove($pluginEntityPath);
139
        }
140
141
        try {
142
            $this->dropPluginTables();
143
            $this->removeTools();
144
        } catch (DBALException $e) {
145
            error_log('Error while uninstalling IMS/LTI plugin: '.$e->getMessage());
146
        }
147
    }
148
149
    /**
150
     * @return CTool
151
     */
152
    public function findCourseToolByLink(Course $course, ImsLtiTool $ltiTool)
153
    {
154
        $em = Database::getManager();
155
        $toolRepo = $em->getRepository('ChamiloCourseBundle:CTool');
156
157
        /** @var CTool $cTool */
158
        $cTool = $toolRepo->findOneBy(
159
            [
160
                'cId' => $course,
161
                'link' => self::generateToolLink($ltiTool),
162
            ]
163
        );
164
165
        return $cTool;
166
    }
167
168
    /**
169
     * @throws \Doctrine\ORM\OptimisticLockException
170
     */
171
    public function updateCourseTool(CTool $courseTool, ImsLtiTool $ltiTool)
172
    {
173
        $em = Database::getManager();
174
175
        $courseTool->setName($ltiTool->getName());
176
177
        if ('iframe' !== $ltiTool->getDocumentTarget()) {
178
            $courseTool->setTarget('_blank');
179
        } else {
180
            $courseTool->setTarget('_self');
181
        }
182
183
        $em->persist($courseTool);
184
        $em->flush();
185
    }
186
187
    /**
188
     * Add the course tool.
189
     *
190
     * @param bool $isVisible
191
     *
192
     * @throws \Doctrine\ORM\OptimisticLockException
193
     */
194
    public function addCourseTool(Course $course, ImsLtiTool $ltiTool, $isVisible = true)
195
    {
196
        $cTool = $this->createLinkToCourseTool(
197
            $ltiTool->getName(),
198
            $course->getId(),
199
            null,
200
            self::generateToolLink($ltiTool)
201
        );
202
        $cTool
203
            ->setTarget(
204
                $ltiTool->getDocumentTarget() === 'iframe' ? '_self' : '_blank'
205
            )
206
            ->setVisibility($isVisible);
207
208
        $em = Database::getManager();
209
        $em->persist($cTool);
210
        $em->flush();
211
    }
212
213
    /**
214
     * Add the course session tool.
215
     *
216
     * @param bool $isVisible
217
     *
218
     * @throws \Doctrine\ORM\OptimisticLockException
219
     */
220
    public function addCourseSessionTool(Course $course, Session $session, ImsLtiTool $ltiTool, $isVisible = true)
221
    {
222
        $cTool = $this->createLinkToCourseTool(
223
            $ltiTool->getName(),
224
            $course->getId(),
225
            null,
226
            self::generateToolLink($ltiTool),
227
            $session->getId()
228
        );
229
        $cTool
230
            ->setTarget(
231
                $ltiTool->getDocumentTarget() === 'iframe' ? '_self' : '_blank'
232
            )
233
            ->setVisibility($isVisible);
234
235
        $em = Database::getManager();
236
        $em->persist($cTool);
237
        $em->flush();
238
    }
239
240
    /**
241
     * @return string
242
     */
243
    public function getEntityPath()
244
    {
245
        return api_get_path(SYS_PATH).'src/Chamilo/PluginBundle/Entity/'.$this->getCamelCaseName();
246
    }
247
248
    public static function isInstructor()
249
    {
250
        api_is_allowed_to_edit(false, true);
251
    }
252
253
    /**
254
     * @return array
255
     */
256
    public static function getRoles(User $user)
257
    {
258
        $roles = ['http://purl.imsglobal.org/vocab/lis/v2/system/person#User'];
259
260
        if (DRH === $user->getStatus()) {
261
            $roles[] = 'http://purl.imsglobal.org/vocab/lis/v2/membership#Mentor';
262
            $roles[] = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Mentor';
263
264
            return $roles;
265
        }
266
267
        if (!api_is_allowed_to_edit(false, true)) {
268
            $roles[] = 'http://purl.imsglobal.org/vocab/lis/v2/membership#Learner';
269
            $roles[] = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Student';
270
271
            if ($user->getStatus() === INVITEE) {
272
                $roles[] = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Guest';
273
            }
274
275
            return $roles;
276
        }
277
278
        $roles[] = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Instructor';
279
        $roles[] = 'http://purl.imsglobal.org/vocab/lis/v2/membership#Instructor';
280
281
        if (api_is_platform_admin_by_id($user->getId())) {
282
            $roles[] = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Administrator';
283
            $roles[] = 'http://purl.imsglobal.org/vocab/lis/v2/system/person#SysAdmin';
284
            $roles[] = 'http://purl.imsglobal.org/vocab/lis/v2/system/person#Administrator';
285
        }
286
287
        return $roles;
288
    }
289
290
    /**
291
     * @return string
292
     */
293
    public static function getUserRoles(User $user)
294
    {
295
        if (DRH === $user->getStatus()) {
296
            return 'urn:lti:role:ims/lis/Mentor';
297
        }
298
299
        if ($user->getStatus() === INVITEE) {
300
            return 'Learner,urn:lti:role:ims/lis/Learner/GuestLearner';
301
        }
302
303
        if (!api_is_allowed_to_edit(false, true)) {
304
            return 'Learner';
305
        }
306
307
        $roles = ['Instructor'];
308
309
        if (api_is_platform_admin_by_id($user->getId())) {
310
            $roles[] = 'urn:lti:role:ims/lis/Administrator';
311
        }
312
313
        return implode(',', $roles);
314
    }
315
316
    /**
317
     * @param int $userId
318
     *
319
     * @return string
320
     */
321
    public static function generateToolUserId($userId)
322
    {
323
        $siteName = api_get_setting('siteName');
324
        $institution = api_get_setting('Institution');
325
        $toolUserId = "$siteName - $institution - $userId";
326
        $toolUserId = api_replace_dangerous_char($toolUserId);
327
328
        return $toolUserId;
329
    }
330
331
    /**
332
     * @return string
333
     */
334
    public static function getLaunchUserIdClaim(ImsLtiTool $tool, User $user)
335
    {
336
        if (null !== $tool->getParent()) {
337
            $tool = $tool->getParent();
338
        }
339
340
        $replacement = $tool->getReplacementForUserId();
341
342
        if (empty($replacement)) {
343
            if ($tool->getVersion() === ImsLti::V_1P1) {
344
                return self::generateToolUserId($user->getId());
345
            }
346
347
            return (string) $user->getId();
348
        }
349
350
        $replaced = str_replace(
351
            ['$User.id', '$User.username'],
352
            [$user->getId(), $user->getUsername()],
353
            $replacement
354
        );
355
356
        return $replaced;
357
    }
358
359
    /**
360
     * @return string
361
     */
362
    public static function getRoleScopeMentor(User $currentUser, ImsLtiTool $tool)
363
    {
364
        $scope = self::getRoleScopeMentorAsArray($currentUser, $tool, true);
365
366
        return implode(',', $scope);
367
    }
368
369
    /**
370
     * Tool User IDs which the user DRH can access as a mentor.
371
     *
372
     * @param bool $generateIdForTool. Optional. Set TRUE for LTI 1.x.
373
     *
374
     * @return array
375
     */
376
    public static function getRoleScopeMentorAsArray(User $user, ImsLtiTool $tool, $generateIdForTool = false)
377
    {
378
        if (DRH !== $user->getStatus()) {
379
            return [];
380
        }
381
382
        $followedUsers = UserManager::get_users_followed_by_drh($user->getId(), 0, true);
383
        $scope = [];
384
        /** @var array $userInfo */
385
        foreach ($followedUsers as $userInfo) {
386
            if ($generateIdForTool) {
387
                $followedUser = api_get_user_entity($userInfo['user_id']);
388
389
                $scope[] = self::getLaunchUserIdClaim($tool, $followedUser);
390
            } else {
391
                $scope[] = (string) $userInfo['user_id'];
392
            }
393
        }
394
395
        return $scope;
396
    }
397
398
    /**
399
     * @throws \Doctrine\ORM\OptimisticLockException
400
     */
401
    public function saveItemAsLtiLink(array $contentItem, ImsLtiTool $baseLtiTool, Course $course)
402
    {
403
        $em = Database::getManager();
404
        $ltiToolRepo = $em->getRepository('ChamiloPluginBundle:ImsLti\ImsLtiTool');
405
406
        $url = empty($contentItem['url']) ? $baseLtiTool->getLaunchUrl() : $contentItem['url'];
407
408
        /** @var ImsLtiTool $newLtiTool */
409
        $newLtiTool = $ltiToolRepo->findOneBy(['launchUrl' => $url, 'parent' => $baseLtiTool, 'course' => $course]);
410
411
        if (null === $newLtiTool) {
412
            $newLtiTool = new ImsLtiTool();
413
            $newLtiTool
414
                ->setLaunchUrl($url)
415
                ->setParent(
416
                    $baseLtiTool
417
                )
418
                ->setPrivacy(
419
                    $baseLtiTool->isSharingName(),
420
                    $baseLtiTool->isSharingEmail(),
421
                    $baseLtiTool->isSharingPicture()
422
                )
423
                ->setCourse($course);
424
        }
425
426
        $newLtiTool
427
            ->setName(
428
                !empty($contentItem['title']) ? $contentItem['title'] : $baseLtiTool->getName()
429
            )
430
            ->setDescription(
431
                !empty($contentItem['text']) ? $contentItem['text'] : null
432
            );
433
434
        if (!empty($contentItem['custom'])) {
435
            $newLtiTool
436
                ->setCustomParams(
437
                    $newLtiTool->encodeCustomParams($contentItem['custom'])
438
                );
439
        }
440
441
        $em->persist($newLtiTool);
442
        $em->flush();
443
444
        $courseTool = $this->findCourseToolByLink($course, $newLtiTool);
445
446
        if ($courseTool) {
0 ignored issues
show
introduced by
$courseTool is of type Chamilo\CourseBundle\Entity\CTool, thus it always evaluated to true.
Loading history...
447
            $this->updateCourseTool($courseTool, $newLtiTool);
448
449
            return;
450
        }
451
452
        $this->addCourseTool($course, $newLtiTool);
453
    }
454
455
    /**
456
     * @return ImsLtiServiceResponse|null
457
     */
458
    public function processServiceRequest()
459
    {
460
        $xml = $this->getRequestXmlElement();
461
462
        if (empty($xml)) {
463
            return null;
464
        }
465
466
        $request = ImsLtiServiceRequestFactory::create($xml);
467
468
        return $request->process();
469
    }
470
471
    /**
472
     * @param int $toolId
473
     *
474
     * @return bool
475
     */
476
    public static function existsToolInCourse($toolId, Course $course)
477
    {
478
        $em = Database::getManager();
479
        $toolRepo = $em->getRepository('ChamiloPluginBundle:ImsLti\ImsLtiTool');
480
481
        /** @var ImsLtiTool $tool */
482
        $tool = $toolRepo->findOneBy(['id' => $toolId, 'course' => $course]);
483
484
        return !empty($tool);
485
    }
486
487
    /**
488
     * @param string $configUrl
489
     *
490
     * @throws Exception
491
     *
492
     * @return string
493
     */
494
    public function getLaunchUrlFromCartridge($configUrl)
495
    {
496
        $options = [
497
            CURLOPT_CUSTOMREQUEST => 'GET',
498
            CURLOPT_POST => false,
499
            CURLOPT_RETURNTRANSFER => true,
500
            CURLOPT_HEADER => false,
501
            CURLOPT_FOLLOWLOCATION => true,
502
            CURLOPT_ENCODING => '',
503
            CURLOPT_SSL_VERIFYPEER => false,
504
        ];
505
506
        $ch = curl_init($configUrl);
507
        curl_setopt_array($ch, $options);
508
        $content = curl_exec($ch);
509
        $errno = curl_errno($ch);
510
        curl_close($ch);
511
512
        if ($errno !== 0) {
513
            throw new Exception($this->get_lang('NoAccessToUrl'));
514
        }
515
516
        $xml = new SimpleXMLElement($content);
517
        $result = $xml->xpath('blti:launch_url');
518
519
        if (empty($result)) {
520
            throw new Exception($this->get_lang('LaunchUrlNotFound'));
521
        }
522
523
        $launchUrl = $result[0];
524
525
        return (string) $launchUrl;
526
    }
527
528
    public function trimParams(array &$params)
529
    {
530
        foreach ($params as $key => $value) {
531
            $newValue = preg_replace('/\s+/', ' ', $value);
532
            $params[$key] = trim($newValue);
533
        }
534
    }
535
536
    /**
537
     * @return array
538
     */
539
    public function removeUrlParamsFromLaunchParams(ImsLtiTool $tool, array &$params)
540
    {
541
        $urlQuery = parse_url($tool->getLaunchUrl(), PHP_URL_QUERY);
542
543
        if (empty($urlQuery)) {
544
            return $params;
545
        }
546
547
        $queryParams = [];
548
        parse_str($urlQuery, $queryParams);
549
        $queryKeys = array_keys($queryParams);
550
551
        foreach ($queryKeys as $key) {
552
            if (isset($params[$key])) {
553
                unset($params[$key]);
554
            }
555
        }
556
    }
557
558
    /**
559
     * Avoid conflict with foreign key when deleting a course.
560
     *
561
     * @param int $courseId
562
     */
563
    public function doWhenDeletingCourse($courseId)
564
    {
565
        $em = Database::getManager();
566
        $q = $em
567
            ->createQuery(
568
                'DELETE FROM ChamiloPluginBundle:ImsLti\ImsLtiTool tool
569
                    WHERE tool.course = :c_id and tool.parent IS NOT NULL'
570
            );
571
        $q->execute(['c_id' => (int) $courseId]);
572
573
        $em->createQuery('DELETE FROM ChamiloPluginBundle:ImsLti\ImsLtiTool tool WHERE tool.course = :c_id')
574
            ->execute(['c_id' => (int) $courseId]);
575
    }
576
577
    /**
578
     * @return string
579
     */
580
    public static function getIssuerUrl()
581
    {
582
        $webPath = api_get_path(WEB_PATH);
583
584
        return trim($webPath, " /");
585
    }
586
587
    public static function getCoursesForParentTool(ImsLtiTool $tool)
588
    {
589
        $coursesId = [];
590
        if (!$tool->getParent()) {
591
            $coursesId = $tool->getChildren()->map(function (ImsLtiTool $tool) {
592
                return $tool->getCourse();
593
            });
594
        }
595
596
        return $coursesId;
597
    }
598
599
    /**
600
     * @return string
601
     */
602
    protected function getConfigExtraText()
603
    {
604
        $text = $this->get_lang('ImsLtiDescription');
605
        $text .= sprintf(
606
            $this->get_lang('ManageToolButton'),
607
            api_get_path(WEB_PLUGIN_PATH).'ims_lti/admin.php'
608
        );
609
610
        return $text;
611
    }
612
613
    /**
614
     * Creates the plugin tables on database.
615
     *
616
     * @throws DBALException
617
     *
618
     * @return bool
619
     */
620
    private function createPluginTables()
621
    {
622
        $entityManager = Database::getManager();
623
        $connection = $entityManager->getConnection();
624
625
        if ($connection->getSchemaManager()->tablesExist(self::TABLE_TOOL)) {
626
            return true;
627
        }
628
629
        $queries = [
630
            "CREATE TABLE plugin_ims_lti_tool (
631
                    id INT AUTO_INCREMENT NOT NULL,
632
                    c_id INT DEFAULT NULL,
633
                    gradebook_eval_id INT DEFAULT NULL,
634
                    parent_id INT DEFAULT NULL,
635
                    name VARCHAR(255) NOT NULL,
636
                    description LONGTEXT DEFAULT NULL,
637
                    launch_url VARCHAR(255) NOT NULL,
638
                    consumer_key VARCHAR(255) DEFAULT NULL,
639
                    shared_secret VARCHAR(255) DEFAULT NULL,
640
                    custom_params LONGTEXT DEFAULT NULL,
641
                    active_deep_linking TINYINT(1) DEFAULT '0' NOT NULL,
642
                    privacy LONGTEXT DEFAULT NULL,
643
                    client_id VARCHAR(255) DEFAULT NULL,
644
                    public_key LONGTEXT DEFAULT NULL,
645
                    login_url VARCHAR(255) DEFAULT NULL,
646
                    redirect_url VARCHAR(255) DEFAULT NULL,
647
                    advantage_services LONGTEXT DEFAULT NULL COMMENT '(DC2Type:json)',
648
                    version VARCHAR(255) DEFAULT 'lti1p1' NOT NULL,
649
                    launch_presentation LONGTEXT NOT NULL COMMENT '(DC2Type:json)',
650
                    replacement_params LONGTEXT NOT NULL COMMENT '(DC2Type:json)',
651
                    session_id INT DEFAULT NULL,
652
                    INDEX IDX_C5E47F7C91D79BD3 (c_id),
653
                    INDEX IDX_C5E47F7C82F80D8B (gradebook_eval_id),
654
                    INDEX IDX_C5E47F7C727ACA70 (parent_id),
655
                    INDEX IDX_C5E47F7C613FECDF (session_id),
656
                    PRIMARY KEY(id)
657
                ) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB",
658
            "CREATE TABLE plugin_ims_lti_platform (
659
                    id INT AUTO_INCREMENT NOT NULL,
660
                    kid VARCHAR(255) NOT NULL,
661
                    public_key LONGTEXT NOT NULL,
662
                    private_key LONGTEXT NOT NULL,
663
                    PRIMARY KEY(id)
664
                ) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB",
665
            "CREATE TABLE plugin_ims_lti_token (
666
                    id INT AUTO_INCREMENT NOT NULL,
667
                    tool_id INT DEFAULT NULL,
668
                    scope LONGTEXT NOT NULL COMMENT '(DC2Type:json)',
669
                    hash VARCHAR(255) NOT NULL,
670
                    created_at INT NOT NULL,
671
                    expires_at INT NOT NULL,
672
                    INDEX IDX_F7B5692F8F7B22CC (tool_id),
673
                    PRIMARY KEY(id)
674
                ) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB",
675
            "ALTER TABLE plugin_ims_lti_tool
676
                ADD CONSTRAINT FK_C5E47F7C91D79BD3 FOREIGN KEY (c_id) REFERENCES course (id)",
677
            "ALTER TABLE plugin_ims_lti_tool
678
                ADD CONSTRAINT FK_C5E47F7C82F80D8B FOREIGN KEY (gradebook_eval_id)
679
                REFERENCES gradebook_evaluation (id) ON DELETE SET NULL",
680
            "ALTER TABLE plugin_ims_lti_tool
681
                ADD CONSTRAINT FK_C5E47F7C727ACA70 FOREIGN KEY (parent_id)
682
                REFERENCES plugin_ims_lti_tool (id) ON DELETE CASCADE",
683
            "ALTER TABLE plugin_ims_lti_token
684
                ADD CONSTRAINT FK_F7B5692F8F7B22CC FOREIGN KEY (tool_id)
685
                REFERENCES plugin_ims_lti_tool (id) ON DELETE CASCADE",
686
            "CREATE TABLE plugin_ims_lti_lineitem (
687
                    id INT AUTO_INCREMENT NOT NULL,
688
                    tool_id INT NOT NULL,
689
                    evaluation INT NOT NULL,
690
                    resource_id VARCHAR(255) DEFAULT NULL,
691
                    tag VARCHAR(255) DEFAULT NULL,
692
                    start_date DATETIME DEFAULT NULL,
693
                    end_date DATETIME DEFAULT NULL,
694
                    INDEX IDX_BA81BBF08F7B22CC (tool_id),
695
                    UNIQUE INDEX UNIQ_BA81BBF01323A575 (evaluation),
696
                    PRIMARY KEY(id)
697
                ) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB",
698
            "ALTER TABLE plugin_ims_lti_lineitem ADD CONSTRAINT FK_BA81BBF08F7B22CC FOREIGN KEY (tool_id)
699
                REFERENCES plugin_ims_lti_tool (id) ON DELETE CASCADE",
700
            "ALTER TABLE plugin_ims_lti_lineitem ADD CONSTRAINT FK_BA81BBF01323A575 FOREIGN KEY (evaluation)
701
                REFERENCES gradebook_evaluation (id) ON DELETE CASCADE ",
702
            "ALTER TABLE plugin_ims_lti_tool ADD CONSTRAINT FK_C5E47F7C613FECDF FOREIGN KEY (session_id)
703
                REFERENCES session (id)",
704
        ];
705
706
        foreach ($queries as $query) {
707
            Database::query($query);
708
        }
709
710
        return true;
711
    }
712
713
    /**
714
     * Drops the plugin tables on database.
715
     *
716
     * @return bool
717
     */
718
    private function dropPluginTables()
719
    {
720
        Database::query("DROP TABLE IF EXISTS plugin_ims_lti_lineitem");
721
        Database::query("DROP TABLE IF EXISTS plugin_ims_lti_token");
722
        Database::query("DROP TABLE IF EXISTS plugin_ims_lti_platform");
723
        Database::query("DROP TABLE IF EXISTS plugin_ims_lti_tool");
724
725
        return true;
726
    }
727
728
    private function removeTools()
729
    {
730
        $sql = "DELETE FROM c_tool WHERE link LIKE 'ims_lti/start.php%' AND category = 'plugin'";
731
        Database::query($sql);
732
    }
733
734
    /**
735
     * Set the course settings.
736
     */
737
    private function setCourseSettings()
738
    {
739
        $button = Display::toolbarButton(
740
            $this->get_lang('ConfigureExternalTool'),
741
            api_get_path(WEB_PLUGIN_PATH).'ims_lti/configure.php?'.api_get_cidreq(),
742
            'cog',
743
            'primary'
744
        );
745
746
        // This setting won't be saved in the database.
747
        $this->course_settings = [
748
            [
749
                'name' => $this->get_lang('ImsLtiDescription').$button.'<hr>',
750
                'type' => 'html',
751
            ],
752
        ];
753
    }
754
755
    /**
756
     * @return string
757
     */
758
    private static function generateToolLink(ImsLtiTool $tool)
759
    {
760
        return 'ims_lti/start.php?id='.$tool->getId();
761
    }
762
763
    /**
764
     * @return SimpleXMLElement|null
765
     */
766
    private function getRequestXmlElement()
767
    {
768
        $request = file_get_contents("php://input");
769
770
        if (empty($request)) {
771
            return null;
772
        }
773
774
        return new SimpleXMLElement($request);
775
    }
776
777
    /**
778
     * Generate a key pair and key id for the platform.
779
     *
780
     * Rerturn a associative array like ['kid' => '...', 'private' => '...', 'public' => '...'].
781
     *
782
     * @return array
783
     */
784
    private static function generatePlatformKeys()
785
    {
786
        // Create the private and public key
787
        $res = openssl_pkey_new(
788
            [
789
                'digest_alg' => 'sha256',
790
                'private_key_bits' => 2048,
791
                'private_key_type' => OPENSSL_KEYTYPE_RSA,
792
            ]
793
        );
794
795
        // Extract the private key from $res to $privateKey
796
        $privateKey = '';
797
        openssl_pkey_export($res, $privateKey);
798
799
        // Extract the public key from $res to $publicKey
800
        $publicKey = openssl_pkey_get_details($res);
801
802
        return [
803
            'kid' => bin2hex(openssl_random_pseudo_bytes(10)),
804
            'private' => $privateKey,
805
            'public' => $publicKey["key"],
806
        ];
807
    }
808
}
809