Passed
Push — master ( fe7dcd...466ab7 )
by Angel Fernando Quiroz
08:26
created

EmbedRegistryPlugin::get_name()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\Course;
5
use Chamilo\CoreBundle\Entity\Session;
6
use Chamilo\PluginBundle\Entity\EmbedRegistry\Embed;
7
use Doctrine\ORM\Tools\SchemaTool;
8
9
/**
10
 * Class EmbedRegistryPlugin.
11
 */
12
class EmbedRegistryPlugin extends Plugin
13
{
14
    public const SETTING_ENABLED = 'tool_enabled';
15
    public const SETTING_TITLE = 'tool_title';
16
    public const SETTING_EXTERNAL_URL = 'external_url';
17
    public const TBL_EMBED = 'plugin_embed_registry_embed';
18
19
    /**
20
     * EmbedRegistryPlugin constructor.
21
     */
22
    protected function __construct()
23
    {
24
        $authors = [
25
            'Angel Fernando Quiroz Campos',
26
        ];
27
28
        parent::__construct(
29
            '1.0',
30
            implode(', ', $authors),
31
            [
32
                self::SETTING_ENABLED => 'boolean',
33
                self::SETTING_TITLE => 'text',
34
                self::SETTING_EXTERNAL_URL => 'text',
35
            ]
36
        );
37
    }
38
39
    /**
40
     * @return string
41
     */
42
    public function getToolTitle()
43
    {
44
        $title = $this->get(self::SETTING_TITLE);
45
46
        if (!empty($title)) {
47
            return $title;
48
        }
49
50
        return $this->get_title();
51
    }
52
53
    /**
54
     * @return EmbedRegistryPlugin|null
55
     */
56
    public static function create()
57
    {
58
        static $result = null;
59
60
        return $result ? $result : $result = new self();
61
    }
62
63
    /**
64
     * @throws \Doctrine\ORM\Tools\ToolsException
65
     *
66
     * @throws \Doctrine\DBAL\Exception
67
     */
68
    public function install()
69
    {
70
        $em = Database::getManager();
71
72
        if ($em->getConnection()->createSchemaManager()->tablesExist([self::TBL_EMBED])) {
73
            return;
74
        }
75
76
        $schemaTool = new SchemaTool($em);
77
        $schemaTool->createSchema(
78
            [
79
                $em->getClassMetadata(Embed::class),
80
            ]
81
        );
82
    }
83
84
    /**
85
     * @throws \Doctrine\DBAL\Exception
86
     */
87
    public function uninstall()
88
    {
89
        $em = Database::getManager();
90
91
        if (!$em->getConnection()->createSchemaManager()->tablesExist([self::TBL_EMBED])) {
92
            return;
93
        }
94
95
        $schemaTool = new SchemaTool($em);
96
        $schemaTool->dropSchema(
97
            [
98
                $em->getClassMetadata(Embed::class),
99
            ]
100
        );
101
    }
102
103
    /**
104
     * @return EmbedRegistryPlugin
105
     */
106
    public function performActionsAfterConfigure()
107
    {
108
        $em = Database::getManager();
109
110
        $this->deleteCourseToolLinks();
111
112
        if ('true' === $this->get(self::SETTING_ENABLED)) {
113
            $courses = $em->createQuery('SELECT c.id FROM ChamiloCoreBundle:Course c')->getResult();
114
115
            foreach ($courses as $course) {
116
                $this->createLinkToCourseTool($this->getToolTitle(), $course['id']);
117
            }
118
        }
119
120
        return $this;
121
    }
122
123
    /**
124
     * @param int $courseId
125
     */
126
    public function doWhenDeletingCourse($courseId)
127
    {
128
        Database::getManager()
129
            ->createQuery('DELETE FROM ChamiloPluginBundle:EmbedRegistry\Embed e WHERE e.course = :course')
130
            ->execute(['course' => (int) $courseId]);
131
    }
132
133
    /**
134
     * @param int $sessionId
135
     */
136
    public function doWhenDeletingSession($sessionId)
137
    {
138
        Database::getManager()
139
            ->createQuery('DELETE FROM ChamiloPluginBundle:EmbedRegistry\Embed e WHERE e.session = :session')
140
            ->execute(['session' => (int) $sessionId]);
141
    }
142
143
    /**
144
     * @throws \Doctrine\ORM\NonUniqueResultException
145
     *
146
     * @return Embed
147
     */
148
    public function getCurrentEmbed(Course $course, Session $session = null)
149
    {
150
        $embedRepo = Database::getManager()->getRepository('ChamiloPluginBundle:EmbedRegistry\Embed');
151
        $qb = $embedRepo->createQueryBuilder('e');
152
        $query = $qb
153
            ->where('e.displayStartDate <= :now')
154
            ->andWhere('e.displayEndDate >= :now')
155
            ->andWhere(
156
                $qb->expr()->eq('e.course', $course->getId())
157
            );
158
159
        $query->andWhere(
160
            $session
161
                ? $qb->expr()->eq('e.session', $session->getId())
162
                : $qb->expr()->isNull('e.session')
163
        );
164
165
        $query = $query
166
            ->orderBy('e.displayStartDate', 'DESC')
167
            ->setMaxResults(1)
168
            ->setParameters(['now' => api_get_utc_datetime(null, false, true)])
169
            ->getQuery();
170
171
        return $query->getOneOrNullResult();
172
    }
173
174
    /**
175
     * @return string
176
     */
177
    public function formatDisplayDate(Embed $embed)
178
    {
179
        $startDate = sprintf(
180
            '<time datetime="%s">%s</time>',
181
            $embed->getDisplayStartDate()->format(DateTime::W3C),
182
            api_convert_and_format_date($embed->getDisplayStartDate())
183
        );
184
        $endDate = sprintf(
185
            '<time datetime="%s">%s</time>',
186
            $embed->getDisplayEndDate()->format(DateTime::W3C),
187
            api_convert_and_format_date($embed->getDisplayEndDate())
188
        );
189
190
        return sprintf(get_lang('FromDateXToDateY'), $startDate, $endDate);
191
    }
192
193
    /**
194
     * @return string
195
     */
196
    public function getViewUrl(Embed $embed)
197
    {
198
        return api_get_path(WEB_PLUGIN_PATH).'EmbedRegistry/view.php?id='.$embed->getId().'&'.api_get_cidreq();
199
    }
200
201
    /**
202
     * @throws \Doctrine\ORM\Query\QueryException
203
     *
204
     * @return int
205
     */
206
    public function getMembersCount(Embed $embed)
207
    {
208
        $dql = 'SELECT COUNT(DISTINCT tea.accessUserId) FROM ChamiloCoreBundle:TrackEAccess tea
209
                WHERE
210
                    tea.accessTool = :tool AND
211
                    (tea.accessDate >= :start_date AND tea.accessDate <= :end_date) AND
212
                    tea.cId = :course';
213
214
        $params = [
215
            'tool' => 'plugin_'.$this->get_name(),
216
            'start_date' => $embed->getDisplayStartDate(),
217
            'end_date' => $embed->getDisplayEndDate(),
218
            'course' => $embed->getCourse(),
219
        ];
220
221
        if ($embed->getSession()) {
222
            $dql .= ' AND tea.accessSessionId = :session ';
223
224
            $params['session'] = $embed->getSession();
225
        }
226
227
        $count = Database::getManager()
228
            ->createQuery($dql)
229
            ->setParameters($params)
230
            ->getSingleScalarResult();
231
232
        return $count;
233
    }
234
235
    public function saveEventAccessTool()
236
    {
237
        $tableAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
238
        $params = [
239
            'access_user_id' => api_get_user_id(),
240
            'c_id' => api_get_course_int_id(),
241
            'access_tool' => 'plugin_'.$this->get_name(),
242
            'access_date' => api_get_utc_datetime(),
243
            'access_session_id' => api_get_session_id(),
244
            'user_ip' => api_get_real_ip(),
245
        ];
246
        Database::insert($tableAccess, $params);
247
    }
248
249
    private function deleteCourseToolLinks()
250
    {
251
        Database::getManager()
252
            ->createQuery('DELETE FROM ChamiloCourseBundle:CTool t WHERE t.category = :category AND t.link LIKE :link')
253
            ->execute(['category' => 'plugin', 'link' => 'EmbedRegistry/start.php%']);
254
    }
255
256
    public function get_name()
257
    {
258
        return 'EmbedRegistry';
259
    }
260
}
261