Issues (2091)

plugin/StudentFollowUp/StudentFollowUpPlugin.php (1 issue)

Severity
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
6
use Symfony\Component\Filesystem\Filesystem;
7
8
/**
9
 * Class StudentFollowUpPlugin.
10
 */
11
class StudentFollowUpPlugin extends Plugin
12
{
13
    public $hasEntity = true;
14
15
    /**
16
     * StudentFollowUpPlugin constructor.
17
     */
18
    protected function __construct()
19
    {
20
        parent::__construct(
21
            '0.1',
22
            'Julio Montoya',
23
            [
24
            ]
25
        );
26
    }
27
28
    /**
29
     * @return StudentFollowUpPlugin
30
     */
31
    public static function create()
32
    {
33
        static $result = null;
34
35
        return $result ?: $result = new self();
36
    }
37
38
    /**
39
     * @throws \Doctrine\DBAL\Exception
40
     */
41
    public function install()
42
    {
43
        $pluginEntityPath = $this->getEntityPath();
44
        if (!is_dir($pluginEntityPath)) {
45
            if (!is_writable(dirname($pluginEntityPath))) {
46
                $message = get_lang('Can\'t create the directory. Please contact your system administrator.').': '.$pluginEntityPath;
47
                Display::addFlash(Display::return_message($message, 'error'));
48
49
                return false;
50
            }
51
            mkdir($pluginEntityPath, api_get_permissions_for_new_directories());
52
        }
53
54
        $fs = new Filesystem();
55
        $fs->mirror(__DIR__.'/Entity/', $pluginEntityPath, null, ['override']);
56
        $schema = Database::getManager()->getConnection()->createSchemaManager();
57
58
        if (false === $schema->tablesExist('sfu_post')) {
59
            $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;";
60
            Database::query($sql);
61
            $sql = 'ALTER TABLE sfu_post ADD CONSTRAINT FK_35F9473C9C859CC3 FOREIGN KEY (insert_user_id) REFERENCES user (id);';
62
            Database::query($sql);
63
            $sql = 'ALTER TABLE sfu_post ADD CONSTRAINT FK_35F9473CA76ED395 FOREIGN KEY (user_id) REFERENCES user (id);';
64
            Database::query($sql);
65
            $sql = 'ALTER TABLE sfu_post ADD CONSTRAINT FK_35F9473C727ACA70 FOREIGN KEY (parent_id) REFERENCES sfu_post (id) ON DELETE SET NULL;';
66
            Database::query($sql);
67
        }
68
    }
69
70
    public function uninstall()
71
    {
72
        $pluginEntityPath = $this->getEntityPath();
73
        $fs = new Filesystem();
74
        if ($fs->exists($pluginEntityPath)) {
75
            $fs->remove($pluginEntityPath);
76
        }
77
        $table = Database::get_main_table('sfu_post');
78
        $sql = "DROP TABLE IF EXISTS $table";
79
        Database::query($sql);
80
    }
81
82
    /**
83
     * @return string
84
     */
85
    public function getEntityPath()
86
    {
87
        return api_get_path(SYS_PATH).'src/Chamilo/PluginBundle/Entity/'.$this->get_name();
88
    }
89
90
    /**
91
     * @param int $studentId
92
     * @param int $currentUserId
93
     *
94
     * @return array
95
     */
96
    public static function getPermissions($studentId, $currentUserId)
97
    {
98
        $installed = AppPlugin::getInstance()->isInstalled('studentfollowup');
99
        if (false === $installed) {
100
            return [
101
                'is_allow' => false,
102
                'show_private' => false,
103
            ];
104
        }
105
106
        if ($studentId === $currentUserId) {
107
            $isAllow = true;
108
            $showPrivate = true;
109
        } else {
110
            $isDrh = api_is_drh();
111
            $isCareTaker = false;
112
            $isDrhRelatedViaPost = false;
113
            $isCourseCoach = false;
114
            $isDrhRelatedToSession = false;
115
116
            // Only admins and DRH that follow the user
117
            $isAdmin = api_is_platform_admin();
118
119
            // Check if user is care taker
120
            if ($isDrh) {
121
                $criteria = [
122
                    'user' => $studentId,
123
                    'insertUser' => $currentUserId,
124
                ];
125
                $repo = Database::getManager()->getRepository('ChamiloPluginBundle:StudentFollowUp\CarePost');
126
                $post = $repo->findOneBy($criteria);
127
                if ($post) {
128
                    $isDrhRelatedViaPost = true;
129
                }
130
            }
131
132
            // Check if course session coach
133
            $sessions = SessionManager::get_sessions_by_user($studentId, false, true);
134
            if (!empty($sessions)) {
135
                foreach ($sessions as $session) {
136
                    $sessionId = $session['session_id'];
137
                    $sessionDrhInfo = SessionManager::getSessionFollowedByDrh(
138
                        $currentUserId,
139
                        $sessionId
140
                    );
141
                    if (!empty($sessionDrhInfo)) {
142
                        $isDrhRelatedToSession = true;
143
144
                        break;
145
                    }
146
                    foreach ($session['courses'] as $course) {
147
                        $coachList = SessionManager::getCoachesByCourseSession(
148
                            $sessionId,
149
                            $course['real_id']
150
                        );
151
                        if (!empty($coachList) && in_array($currentUserId, $coachList)) {
152
                            $isCourseCoach = true;
153
154
                            break 2;
155
                        }
156
                    }
157
                }
158
            }
159
160
            $isCareTaker = $isDrhRelatedViaPost && $isDrhRelatedToSession;
161
162
            $isAllow = $isAdmin || $isCareTaker || $isDrhRelatedToSession || $isCourseCoach;
163
            $showPrivate = $isAdmin || $isCareTaker;
164
        }
165
166
        return [
167
            'is_allow' => $isAllow,
168
            'show_private' => $showPrivate,
169
        ];
170
    }
171
172
    /**
173
     * @param string $status
174
     * @param int    $currentUserId
175
     * @param int    $sessionId
176
     * @param int    $start
177
     * @param int    $limit
178
     *
179
     * @return array
180
     */
181
    public static function getUsers($status, $currentUserId, $sessionId, $start, $limit)
182
    {
183
        $sessions = [];
184
        $courses = [];
185
        $sessionsFull = [];
186
187
        switch ($status) {
188
            case COURSEMANAGER:
189
                $sessionsFull = SessionManager::getSessionsCoachedByUser($currentUserId);
190
                $sessions = array_column($sessionsFull, 'id');
191
                if (!empty($sessionId)) {
192
                    $sessions = [$sessionId];
193
                }
194
                // Get session courses where I'm coach
195
                $courseList = SessionManager::getCoursesListByCourseCoach($currentUserId);
196
                $courses = [];
197
                /** @var SessionRelCourseRelUser $courseItem */
198
                foreach ($courseList as $courseItem) {
199
                    $courses[] = $courseItem->getCourse()->getId();
200
                }
201
202
                break;
203
            case DRH:
204
                $sessionsFull = SessionManager::get_sessions_followed_by_drh($currentUserId);
205
                $sessions = array_column($sessionsFull, 'id');
206
207
                if (!empty($sessionId)) {
208
                    $sessions = [$sessionId];
209
                }
210
                $courses = [];
211
                foreach ($sessions as $sessionId) {
0 ignored issues
show
$sessionId is overwriting one of the parameters of this function.
Loading history...
212
                    $sessionDrhInfo = SessionManager::getSessionFollowedByDrh(
213
                        $currentUserId,
214
                        $sessionId
215
                    );
216
                    if ($sessionDrhInfo && isset($sessionDrhInfo['course_list'])) {
217
                        $courses = array_merge($courses, array_column($sessionDrhInfo['course_list'], 'id'));
218
                    }
219
                }
220
221
                break;
222
        }
223
224
        $userList = SessionManager::getUsersByCourseAndSessionList(
225
            $sessions,
226
            $courses,
227
            $start,
228
            $limit
229
        );
230
231
        return [
232
            'users' => $userList,
233
            'sessions' => $sessionsFull,
234
        ];
235
    }
236
237
    /**
238
     * @return int
239
     */
240
    public static function getPageSize()
241
    {
242
        return 20;
243
    }
244
245
    /**
246
     * @param int $userId
247
     */
248
    public function doWhenDeletingUser($userId)
249
    {
250
        $userId = (int) $userId;
251
252
        Database::query("DELETE FROM sfu_post WHERE user_id = $userId");
253
        Database::query("DELETE FROM sfu_post WHERE insert_user_id = $userId");
254
    }
255
}
256