Completed
Push — master ( 8b2aa0...562606 )
by Julito
09:06
created

StudentFollowUpPlugin   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 237
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 120
dl 0
loc 237
rs 9.44
c 1
b 0
f 0
wmc 37

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getEntityPath() 0 3 1
A __construct() 0 7 1
A install() 0 26 4
A create() 0 5 2
A uninstall() 0 10 2
A getPageSize() 0 3 1
A doWhenDeletingUser() 0 6 1
B getUsers() 0 51 9
D getPermissions() 0 71 16
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
5
use Symfony\Component\Filesystem\Filesystem;
6
7
/**
8
 * Class StudentFollowUpPlugin.
9
 */
10
class StudentFollowUpPlugin extends Plugin
11
{
12
    public $hasEntity = true;
13
14
    /**
15
     * StudentFollowUpPlugin constructor.
16
     */
17
    protected function __construct()
18
    {
19
        parent::__construct(
20
            '0.1',
21
            'Julio Montoya',
22
            [
23
                'tool_enable' => 'boolean',
24
            ]
25
        );
26
    }
27
28
    /**
29
     * @return StudentFollowUpPlugin
30
     */
31
    public static function create()
32
    {
33
        static $result = null;
34
35
        return $result ? $result : $result = new self();
36
    }
37
38
    public function install()
39
    {
40
        $pluginEntityPath = $this->getEntityPath();
41
        if (!is_dir($pluginEntityPath)) {
42
            if (!is_writable(dirname($pluginEntityPath))) {
43
                $message = get_lang('ErrorCreatingDir').': '.$pluginEntityPath;
44
                Display::addFlash(Display::return_message($message, 'error'));
45
46
                return false;
47
            }
48
            mkdir($pluginEntityPath, api_get_permissions_for_new_directories());
49
        }
50
51
        $fs = new Filesystem();
52
        $fs->mirror(__DIR__.'/Entity/', $pluginEntityPath, null, ['override']);
53
        $schema = Database::getManager()->getConnection()->getSchemaManager();
54
55
        if ($schema->tablesExist('sfu_post') === false) {
56
            $sql = "CREATE TABLE IF NOT EXISTS sfu_post (id INT AUTO_INCREMENT NOT NULL, insert_user_id INT NOT NULL, user_id INT NOT NULL, parent_id INT DEFAULT NULL, title VARCHAR(255) NOT NULL, content LONGTEXT DEFAULT NULL, external_care_id VARCHAR(255) DEFAULT NULL, created_at DATETIME DEFAULT NULL, updated_at DATETIME DEFAULT NULL, private TINYINT(1) NOT NULL, external_source TINYINT(1) NOT NULL, tags LONGTEXT NOT NULL COMMENT '(DC2Type:array)', attachment VARCHAR(255) NOT NULL, lft INT DEFAULT NULL, rgt INT DEFAULT NULL, lvl INT DEFAULT NULL, root INT DEFAULT NULL, INDEX IDX_35F9473C9C859CC3 (insert_user_id), INDEX IDX_35F9473CA76ED395 (user_id), INDEX IDX_35F9473C727ACA70 (parent_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;";
57
            Database::query($sql);
58
            $sql = "ALTER TABLE sfu_post ADD CONSTRAINT FK_35F9473C9C859CC3 FOREIGN KEY (insert_user_id) REFERENCES user (id);";
59
            Database::query($sql);
60
            $sql = "ALTER TABLE sfu_post ADD CONSTRAINT FK_35F9473CA76ED395 FOREIGN KEY (user_id) REFERENCES user (id);";
61
            Database::query($sql);
62
            $sql = "ALTER TABLE sfu_post ADD CONSTRAINT FK_35F9473C727ACA70 FOREIGN KEY (parent_id) REFERENCES sfu_post (id) ON DELETE SET NULL;";
63
            Database::query($sql);
64
        }
65
    }
66
67
    public function uninstall()
68
    {
69
        $pluginEntityPath = $this->getEntityPath();
70
        $fs = new Filesystem();
71
        if ($fs->exists($pluginEntityPath)) {
72
            $fs->remove($pluginEntityPath);
73
        }
74
        $table = Database::get_main_table('sfu_post');
75
        $sql = "DROP TABLE IF EXISTS $table";
76
        Database::query($sql);
77
    }
78
79
    /**
80
     * @return string
81
     */
82
    public function getEntityPath()
83
    {
84
        return api_get_path(SYS_PATH).'src/Chamilo/PluginBundle/Entity/'.$this->getCamelCaseName();
85
    }
86
87
    /**
88
     * @param int $studentId
89
     * @param int $currentUserId
90
     *
91
     * @return array
92
     */
93
    public static function getPermissions($studentId, $currentUserId)
94
    {
95
        $installed = AppPlugin::getInstance()->isInstalled('studentfollowup');
96
        if ($installed === false) {
97
            return [
98
                'is_allow' => false,
99
                'show_private' => false,
100
            ];
101
        }
102
103
        if ($studentId === $currentUserId) {
104
            $isAllow = true;
105
            $showPrivate = true;
106
        } else {
107
            $isDrh = api_is_drh();
108
            $isCareTaker = false;
109
            $isDrhRelatedViaPost = false;
110
            $isCourseCoach = false;
111
            $isDrhRelatedToSession = false;
112
113
            // Only admins and DRH that follow the user
114
            $isAdmin = api_is_platform_admin();
115
116
            // Check if user is care taker
117
            if ($isDrh) {
118
                $criteria = [
119
                    'user' => $studentId,
120
                    'insertUser' => $currentUserId,
121
                ];
122
                $repo = Database::getManager()->getRepository('ChamiloPluginBundle:StudentFollowUp\CarePost');
123
                $post = $repo->findOneBy($criteria);
124
                if ($post) {
125
                    $isDrhRelatedViaPost = true;
126
                }
127
            }
128
129
            // Check if course session coach
130
            $sessions = SessionManager::get_sessions_by_user($studentId, false, true);
131
            if (!empty($sessions)) {
132
                foreach ($sessions as $session) {
133
                    $sessionId = $session['session_id'];
134
                    $sessionDrhInfo = SessionManager::getSessionFollowedByDrh(
135
                        $currentUserId,
136
                        $sessionId
137
                    );
138
                    if (!empty($sessionDrhInfo)) {
139
                        $isDrhRelatedToSession = true;
140
                        break;
141
                    }
142
                    foreach ($session['courses'] as $course) {
143
                        $coachList = SessionManager::getCoachesByCourseSession(
144
                            $sessionId,
145
                            $course['real_id']
146
                        );
147
                        if (!empty($coachList) && in_array($currentUserId, $coachList)) {
148
                            $isCourseCoach = true;
149
                            break 2;
150
                        }
151
                    }
152
                }
153
            }
154
155
            $isCareTaker = $isDrhRelatedViaPost && $isDrhRelatedToSession;
156
157
            $isAllow = $isAdmin || $isCareTaker || $isDrhRelatedToSession || $isCourseCoach;
158
            $showPrivate = $isAdmin || $isCareTaker;
159
        }
160
161
        return [
162
            'is_allow' => $isAllow,
163
            'show_private' => $showPrivate,
164
        ];
165
    }
166
167
    /**
168
     * @param string $status
169
     * @param int    $currentUserId
170
     * @param int    $sessionId
171
     * @param int    $start
172
     * @param int    $limit
173
     *
174
     * @return array
175
     */
176
    public static function getUsers($status, $currentUserId, $sessionId, $start, $limit)
177
    {
178
        $sessions = [];
179
        $courses = [];
180
        $sessionsFull = [];
181
182
        switch ($status) {
183
            case COURSEMANAGER:
184
                $sessionsFull = SessionManager::getSessionsCoachedByUser($currentUserId);
185
                $sessions = array_column($sessionsFull, 'id');
186
                if (!empty($sessionId)) {
187
                    $sessions = [$sessionId];
188
                }
189
                // Get session courses where I'm coach
190
                $courseList = SessionManager::getCoursesListByCourseCoach($currentUserId);
191
                $courses = [];
192
                /** @var SessionRelCourseRelUser $courseItem */
193
                foreach ($courseList as $courseItem) {
194
                    $courses[] = $courseItem->getCourse()->getId();
195
                }
196
                break;
197
            case DRH:
198
                $sessionsFull = SessionManager::get_sessions_followed_by_drh($currentUserId);
199
                $sessions = array_column($sessionsFull, 'id');
200
201
                if (!empty($sessionId)) {
202
                    $sessions = [$sessionId];
203
                }
204
                $courses = [];
205
                foreach ($sessions as $sessionId) {
0 ignored issues
show
introduced by
$sessionId is overwriting one of the parameters of this function.
Loading history...
206
                    $sessionDrhInfo = SessionManager::getSessionFollowedByDrh(
207
                        $currentUserId,
208
                        $sessionId
209
                    );
210
                    if ($sessionDrhInfo && isset($sessionDrhInfo['course_list'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sessionDrhInfo of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
211
                        $courses = array_merge($courses, array_column($sessionDrhInfo['course_list'], 'id'));
212
                    }
213
                }
214
                break;
215
        }
216
217
        $userList = SessionManager::getUsersByCourseAndSessionList(
218
            $sessions,
219
            $courses,
220
            $start,
221
            $limit
222
        );
223
224
        return [
225
            'users' => $userList,
226
            'sessions' => $sessionsFull,
227
        ];
228
    }
229
230
    /**
231
     * @return int
232
     */
233
    public static function getPageSize()
234
    {
235
        return 20;
236
    }
237
238
    /**
239
     * @param int $userId
240
     */
241
    public function doWhenDeletingUser($userId)
242
    {
243
        $userId = (int) $userId;
244
245
        Database::query("DELETE FROM sfu_post WHERE user_id = $userId");
246
        Database::query("DELETE FROM sfu_post WHERE insert_user_id = $userId");
247
    }
248
}
249