EmbedRegistryPlugin::getMembersCount()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 14
nc 2
nop 1
dl 0
loc 27
rs 9.7998
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
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...
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
    public function install()
67
    {
68
        $em = Database::getManager();
69
70
        if ($em->getConnection()->getSchemaManager()->tablesExist([self::TBL_EMBED])) {
71
            return;
72
        }
73
74
        $schemaTool = new SchemaTool($em);
75
        $schemaTool->createSchema(
76
            [
77
                $em->getClassMetadata(Embed::class),
78
            ]
79
        );
80
    }
81
82
    public function uninstall()
83
    {
84
        $em = Database::getManager();
85
86
        if (!$em->getConnection()->getSchemaManager()->tablesExist([self::TBL_EMBED])) {
87
            return;
88
        }
89
90
        $schemaTool = new SchemaTool($em);
91
        $schemaTool->dropSchema(
92
            [
93
                $em->getClassMetadata(Embed::class),
94
            ]
95
        );
96
    }
97
98
    /**
99
     * @return EmbedRegistryPlugin
100
     */
101
    public function performActionsAfterConfigure()
102
    {
103
        $em = Database::getManager();
104
105
        $this->deleteCourseToolLinks();
106
107
        if ('true' === $this->get(self::SETTING_ENABLED)) {
108
            $courses = $em->createQuery('SELECT c.id FROM ChamiloCoreBundle:Course c')->getResult();
109
110
            foreach ($courses as $course) {
111
                $this->createLinkToCourseTool($this->getToolTitle(), $course['id']);
112
            }
113
        }
114
115
        return $this;
116
    }
117
118
    /**
119
     * @param int $courseId
120
     */
121
    public function doWhenDeletingCourse($courseId)
122
    {
123
        Database::getManager()
124
            ->createQuery('DELETE FROM ChamiloPluginBundle:EmbedRegistry\Embed e WHERE e.course = :course')
125
            ->execute(['course' => (int) $courseId]);
126
    }
127
128
    /**
129
     * @param int $sessionId
130
     */
131
    public function doWhenDeletingSession($sessionId)
132
    {
133
        Database::getManager()
134
            ->createQuery('DELETE FROM ChamiloPluginBundle:EmbedRegistry\Embed e WHERE e.session = :session')
135
            ->execute(['session' => (int) $sessionId]);
136
    }
137
138
    /**
139
     * @throws \Doctrine\ORM\NonUniqueResultException
140
     *
141
     * @return Embed
142
     */
143
    public function getCurrentEmbed(Course $course, Session $session = null)
144
    {
145
        $embedRepo = Database::getManager()->getRepository('ChamiloPluginBundle:EmbedRegistry\Embed');
146
        $qb = $embedRepo->createQueryBuilder('e');
147
        $query = $qb
148
            ->where('e.displayStartDate <= :now')
149
            ->andWhere('e.displayEndDate >= :now')
150
            ->andWhere(
151
                $qb->expr()->eq('e.course', $course->getId())
152
            );
153
154
        $query->andWhere(
155
            $session
156
                ? $qb->expr()->eq('e.session', $session->getId())
157
                : $qb->expr()->isNull('e.session')
158
        );
159
160
        $query = $query
161
            ->orderBy('e.displayStartDate', 'DESC')
162
            ->setMaxResults(1)
163
            ->setParameters(['now' => api_get_utc_datetime(null, false, true)])
164
            ->getQuery();
165
166
        return $query->getOneOrNullResult();
167
    }
168
169
    /**
170
     * @return string
171
     */
172
    public function formatDisplayDate(Embed $embed)
173
    {
174
        $startDate = sprintf(
175
            '<time datetime="%s">%s</time>',
176
            $embed->getDisplayStartDate()->format(DateTime::W3C),
177
            api_convert_and_format_date($embed->getDisplayStartDate())
178
        );
179
        $endDate = sprintf(
180
            '<time datetime="%s">%s</time>',
181
            $embed->getDisplayEndDate()->format(DateTime::W3C),
182
            api_convert_and_format_date($embed->getDisplayEndDate())
183
        );
184
185
        return sprintf(get_lang('FromDateXToDateY'), $startDate, $endDate);
186
    }
187
188
    /**
189
     * @return string
190
     */
191
    public function getViewUrl(Embed $embed)
192
    {
193
        return api_get_path(WEB_PLUGIN_PATH).'embedregistry/view.php?id='.$embed->getId().'&'.api_get_cidreq();
194
    }
195
196
    /**
197
     * @throws \Doctrine\ORM\Query\QueryException
198
     *
199
     * @return int
200
     */
201
    public function getMembersCount(Embed $embed)
202
    {
203
        $dql = 'SELECT COUNT(DISTINCT tea.accessUserId) FROM ChamiloCoreBundle:TrackEAccess tea
204
                WHERE
205
                    tea.accessTool = :tool AND
206
                    (tea.accessDate >= :start_date AND tea.accessDate <= :end_date) AND
207
                    tea.cId = :course';
208
209
        $params = [
210
            'tool' => 'plugin_'.$this->get_name(),
211
            'start_date' => $embed->getDisplayStartDate(),
212
            'end_date' => $embed->getDisplayEndDate(),
213
            'course' => $embed->getCourse(),
214
        ];
215
216
        if ($embed->getSession()) {
217
            $dql .= ' AND tea.accessSessionId = :session ';
218
219
            $params['session'] = $embed->getSession();
220
        }
221
222
        $count = Database::getManager()
223
            ->createQuery($dql)
224
            ->setParameters($params)
225
            ->getSingleScalarResult();
226
227
        return $count;
228
    }
229
230
    public function saveEventAccessTool()
231
    {
232
        $tableAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
233
        $params = [
234
            'access_user_id' => api_get_user_id(),
235
            'c_id' => api_get_course_int_id(),
236
            'access_tool' => 'plugin_'.$this->get_name(),
237
            'access_date' => api_get_utc_datetime(),
238
            'access_session_id' => api_get_session_id(),
239
            'user_ip' => api_get_real_ip(),
240
        ];
241
        Database::insert($tableAccess, $params);
242
    }
243
244
    private function deleteCourseToolLinks()
245
    {
246
        Database::getManager()
247
            ->createQuery('DELETE FROM ChamiloCourseBundle:CTool t WHERE t.category = :category AND t.link LIKE :link')
248
            ->execute(['category' => 'plugin', 'link' => 'embedregistry/start.php%']);
249
    }
250
}
251