Passed
Push — 1.11.x ( 08587c...c85e98 )
by Yannick
10:54
created

H5pImportPlugin::getViewUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\PluginBundle\Entity\H5pImport\H5pImport;
5
use Chamilo\PluginBundle\Entity\H5pImport\H5pImportLibrary;
6
use Chamilo\PluginBundle\Entity\H5pImport\H5pImportResults;
7
use Doctrine\ORM\Tools\SchemaTool;
8
use Doctrine\ORM\Tools\ToolsException;
9
use Symfony\Component\Filesystem\Filesystem;
10
11
/**
12
 * Define the H5pImportPlugin class as an extension of Plugin
13
 * install/uninstall the plugin.
14
 */
15
class H5pImportPlugin extends Plugin
16
{
17
    public const TBL_H5P_IMPORT = 'plugin_h5p_import';
18
    public const TBL_H5P_IMPORT_LIBRARY = 'plugin_h5p_import_library';
19
    public const TBL_H5P_IMPORT_RESULTS = 'plugin_h5p_import_results';
20
21
    protected function __construct()
22
    {
23
        $settings = [
24
            'tool_enable' => 'boolean',
25
            'frame' => 'boolean',
26
            'embed' => 'boolean',
27
            'copyright' => 'boolean',
28
            'icon' => 'boolean',
29
        ];
30
31
        parent::__construct(
32
            '0.1',
33
            'Borja Sanchez',
34
            $settings
35
        );
36
    }
37
38
    public static function create(): ?H5pImportPlugin
39
    {
40
        static $result = null;
41
42
        return $result ? $result : $result = new self();
43
    }
44
45
    /**
46
     * Updates and returns the total duration in the view of an H5P learning path item in a course.
47
     *
48
     * @param int $lpItemId The ID of the learning path item
49
     * @param int $userId   The user ID
50
     *
51
     * @return int The updated total duration in the learning path item view
52
     */
53
    public static function fixTotalTimeInLpItemView(
54
        int $lpItemId,
55
        int $userId
56
    ): int {
57
        $lpItemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
58
59
        $sql = "SELECT iid, score
60
            FROM $lpItemViewTable
61
            WHERE
62
                iid = $lpItemId
63
            ORDER BY view_count DESC
64
            LIMIT 1";
65
        $responseItemView = Database::query($sql);
66
        $lpItemView = Database::fetch_array($responseItemView);
67
68
        // Get the total execution duration of the user in the learning path item view
69
        $sql = 'SELECT SUM(total_time) AS exe_duration
70
            FROM plugin_h5p_import_results
71
            WHERE
72
                user_id = '.$userId.' AND
73
                c_lp_item_view_id = '.$lpItemView['iid'].
74
            ' ORDER BY total_time DESC';
75
        $sumScoreResult = Database::query($sql);
76
        $durationRow = Database::fetch_array($sumScoreResult, 'ASSOC');
77
78
        if (!empty($durationRow['exe_duration'])) {
79
            // Update the total duration in the learning path item view
80
            $sqlUpdate = 'UPDATE '.$lpItemViewTable.'
81
                SET total_time = '.$durationRow['exe_duration'].'
82
                WHERE iid = '.$lpItemView['iid'];
83
            Database::query($sqlUpdate);
84
85
            return (int) $durationRow['exe_duration'];
86
        } else {
87
            // Update c_lp_item_view status
88
            $sqlUpdate = 'UPDATE '.$lpItemViewTable.'
89
                SET status = "not attempted",
90
                total_time = 0
91
                WHERE iid = '.$lpItemView['iid'];
92
            Database::query($sqlUpdate);
93
94
            return 0;
95
        }
96
    }
97
98
    public function getToolTitle(): string
99
    {
100
        $title = $this->get_lang('plugin_title');
101
102
        if (!empty($title)) {
103
            return $title;
104
        }
105
106
        return $this->get_title();
107
    }
108
109
    /**
110
     * @throws ToolsException
111
     */
112
    public function install()
113
    {
114
        $em = Database::getManager();
115
        if ($em->getConnection()
116
            ->getSchemaManager()
117
            ->tablesExist(
118
                [
119
                    self::TBL_H5P_IMPORT,
120
                    self::TBL_H5P_IMPORT_LIBRARY,
121
                    self::TBL_H5P_IMPORT_RESULTS,
122
                ]
123
            )
124
        ) {
125
            return;
126
        }
127
128
        $schemaTool = new SchemaTool($em);
129
        $schemaTool->createSchema(
130
            [
131
                $em->getClassMetadata(H5pImport::class),
132
                $em->getClassMetadata(H5pImportLibrary::class),
133
                $em->getClassMetadata(H5pImportResults::class),
134
            ]
135
        );
136
        $this->addCourseTools();
137
    }
138
139
    public function addCourseTool(int $courseId)
140
    {
141
        // The $link param is set to "../plugin" as a hack to link correctly to the plugin URL in course tool.
142
        // Otherwise, the link en the course tool will link to "/main/" URL.
143
        $this->createLinkToCourseTool(
144
            $this->get_lang('plugin_title'),
145
            $courseId,
146
            'plugin_h5p_import.png',
147
            '../plugin/h5pimport/start.php',
148
            0,
149
            'authoring'
150
        );
151
    }
152
153
    public function uninstall()
154
    {
155
        $em = Database::getManager();
156
157
        if (!$em->getConnection()
158
            ->getSchemaManager()
159
            ->tablesExist(
160
                [
161
                    self::TBL_H5P_IMPORT,
162
                    self::TBL_H5P_IMPORT_LIBRARY,
163
                    self::TBL_H5P_IMPORT_RESULTS,
164
                ]
165
            )
166
        ) {
167
            return;
168
        }
169
170
        $schemaTool = new SchemaTool($em);
171
        $schemaTool->dropSchema(
172
            [
173
                $em->getClassMetadata(H5pImport::class),
174
                $em->getClassMetadata(H5pImportLibrary::class),
175
                $em->getClassMetadata(H5pImportResults::class),
176
            ]
177
        );
178
        $this->deleteCourseToolLinks();
179
        $this->removeH5pDirectories();
180
    }
181
182
    /**
183
     * Perform actions after configuring the H5P import plugin.
184
     *
185
     * @return H5pImportPlugin The H5P import plugin instance.
186
     */
187
    public function performActionsAfterConfigure(): H5pImportPlugin
188
    {
189
        $this->deleteCourseToolLinks();
190
191
        if ('true' === $this->get('tool_enable')) {
192
            $this->addCourseTools();
193
        }
194
195
        return $this;
196
    }
197
198
    /**
199
     * Get the view URL for an H5P import.
200
     *
201
     * @param H5pImport $h5pImport The H5P import object.
202
     *
203
     * @return string The view URL for the H5P import.
204
     */
205
    public function getViewUrl(H5pImport $h5pImport): string
206
    {
207
        return api_get_path(WEB_PLUGIN_PATH).'h5pimport/view.php?id='.$h5pImport->getIid().'&'.api_get_cidreq();
208
    }
209
210
    /**
211
     * Generates the LP resource block for H5P imports.
212
     *
213
     * @param int $lpId The LP ID.
214
     *
215
     * @return string The HTML for the LP resource block.
216
     */
217
    public function getLpResourceBlock(int $lpId): string
218
    {
219
        $cidReq = api_get_cidreq(true, true, 'lp');
220
        $webPath = api_get_path(WEB_PLUGIN_PATH).'h5pimport/';
221
        $course = api_get_course_entity();
222
        $session = api_get_session_entity();
223
224
        $tools = Database::getManager()
225
            ->getRepository(H5pImport::class)
226
            ->findBy(['course' => $course, 'session' => $session]);
227
228
        $importIcon = Display::return_icon('plugin_h5p_import_upload.png');
229
        $moveIcon = Display::url(
230
            Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY),
231
            '#',
232
            ['class' => 'moved']
233
        );
234
235
        $return = '<ul class="lp_resource">';
236
        $return .= '<li class="lp_resource_element">';
237
        $return .= $importIcon;
238
        $return .= Display::url(
239
            get_lang('Import'),
240
            $webPath."start.php?action=add&$cidReq&".http_build_query(['lp_id' => $lpId])
241
        );
242
        $return .= '</li>';
243
244
        /** @var H5pImport $tool */
245
        foreach ($tools as $tool) {
246
            $toolAnchor = Display::url(
247
                Security::remove_XSS($tool->getName()),
248
                api_get_self()."?$cidReq&"
249
                .http_build_query(
250
                    ['action' => 'add_item', 'type' => TOOL_H5P, 'file' => $tool->getIid(), 'lp_id' => $lpId]
251
                ),
252
                ['class' => 'moved']
253
            );
254
255
            $return .= Display::tag(
256
                'li',
257
                $moveIcon.$importIcon.$toolAnchor,
258
                [
259
                    'class' => 'lp_resource_element',
260
                    'data_id' => $tool->getIid(),
261
                    'data_type' => TOOL_H5P,
262
                    'title' => $tool->getName(),
263
                ]
264
            );
265
        }
266
267
        $return .= '</ul>';
268
269
        return $return;
270
    }
271
272
    /**
273
     * Add course tools for all courses.
274
     */
275
    private function addCourseTools(): void
276
    {
277
        $courses = Database::getManager()
278
            ->createQuery('SELECT c.id FROM ChamiloCoreBundle:Course c')
279
            ->getResult();
280
281
        foreach ($courses as $course) {
282
            $this->addCourseTool($course['id']);
283
        }
284
    }
285
286
    private function deleteCourseToolLinks()
287
    {
288
        Database::getManager()
289
            ->createQuery('DELETE FROM ChamiloCourseBundle:CTool t WHERE t.category = :category AND t.link LIKE :link')
290
            ->execute(['category' => 'authoring', 'link' => '../plugin/h5pimport/start.php%']);
291
    }
292
293
    /**
294
     * Removes H5P directories for all courses.
295
     */
296
    private function removeH5pDirectories(): void
297
    {
298
        $fs = new Filesystem();
299
        $table = Database::get_main_table(TABLE_MAIN_COURSE);
300
        $sql = "SELECT id FROM $table ORDER BY id";
301
        $res = Database::query($sql);
302
        while ($row = Database::fetch_assoc($res)) {
303
            $courseInfo = api_get_course_info_by_id($row['id']);
304
            $fs->remove($courseInfo['course_sys_path'].'/h5p');
305
        }
306
    }
307
}
308