Completed
Push — master ( a6bd78...0ffec3 )
by Julito
13:34
created

NotebookTeacher::saveNote()   C

Complexity

Conditions 7
Paths 3

Size

Total Lines 30
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 23
nc 3
nop 4
dl 0
loc 30
rs 6.7272
c 1
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
require_once __DIR__.'/../config.php';
7
8
/**
9
 * This class provides methods for the notebook management.
10
 * Include/require it in your code to use its features.
11
 *
12
 * @author Carlos Vargas <[email protected]>, move code of main/notebook up here
13
 * @author Jose Angel Ruiz <[email protected]>, adaptation for the plugin
14
 *
15
 * @package chamilo.library
16
 */
17
class NotebookTeacher
18
{
19
    /**
20
     * Constructor.
21
     */
22
    public function __construct()
23
    {
24
    }
25
26
    /**
27
     * a little bit of javascript to display a prettier warning when deleting a note.
28
     *
29
     * @author Patrick Cool <[email protected]>, Ghent University, Belgium
30
     *
31
     * @version januari 2009, dokeos 1.8.6
32
     *
33
     * @return string
34
     */
35
    public static function javascriptNotebook()
36
    {
37
        return "<script>
38
				function confirmation (name)
39
				{
40
					if (confirm(\" ".get_lang("NoteConfirmDelete")." \"+ name + \" ?\"))
41
						{return true;}
42
					else
43
						{return false;}
44
				}
45
				</script>";
46
    }
47
48
    /**
49
     * This functions stores the note in the database.
50
     *
51
     * @param array $values
52
     * @param int   $userId    Optional. The user ID
53
     * @param int   $courseId  Optional. The course ID
54
     * @param int   $sessionId Optional. The session ID
55
     *
56
     * @return bool
57
     */
58
    public static function saveNote($values, $userId = 0, $courseId = 0, $sessionId = 0)
59
    {
60
        if (!is_array($values) || empty($values['note_title'])) {
61
            return false;
62
        }
63
64
        // Database table definition
65
        $table = Database::get_main_table(NotebookTeacherPlugin::TABLE_NOTEBOOKTEACHER);
66
        $userId = $userId ?: api_get_user_id();
67
        $courseId = $courseId ?: api_get_course_int_id();
68
        $courseInfo = api_get_course_info_by_id($courseId);
69
        $courseCode = $courseInfo['code'];
70
        $sessionId = $sessionId ?: api_get_session_id();
71
        $now = api_get_utc_datetime();
72
        $params = [
73
            'c_id' => $courseId,
74
            'session_id' => $sessionId,
75
            'user_id' => $userId,
76
            'student_id' => intval($values['student_id']),
77
            'course' => $courseCode,
78
            'title' => $values['note_title'],
79
            'description' => $values['note_comment'],
80
            'creation_date' => $now,
81
            'update_date' => $now,
82
            'status' => 0,
83
        ];
84
        $id = Database::insert($table, $params);
85
86
        if ($id > 0) {
87
            return $id;
88
        }
89
    }
90
91
    /**
92
     * @param int $notebookId
93
     *
94
     * @return array|mixed
95
     */
96
    public static function getNoteInformation($notebookId)
97
    {
98
        if (empty($notebookId)) {
99
            return [];
100
        }
101
102
        // Database table definition
103
        $tableNotebook = Database::get_main_table(NotebookTeacherPlugin::TABLE_NOTEBOOKTEACHER);
104
        $courseId = api_get_course_int_id();
105
106
        $sql = "SELECT
107
                id AS notebook_id,
108
                title AS note_title,
109
                description AS note_comment,
110
                session_id AS session_id,
111
                student_id AS student_id
112
               FROM $tableNotebook
113
               WHERE c_id = $courseId AND id = '".intval($notebookId)."' ";
114
        $result = Database::query($sql);
115
        if (Database::num_rows($result) != 1) {
116
            return [];
117
        }
118
119
        return Database::fetch_array($result);
120
    }
121
122
    /**
123
     * This functions updates the note in the database.
124
     *
125
     * @param array $values
126
     *
127
     * @return bool
128
     */
129
    public static function updateNote($values)
130
    {
131
        if (!is_array($values) or empty($values['note_title'])) {
132
            return false;
133
        }
134
        // Database table definition
135
        $table = Database::get_main_table(NotebookTeacherPlugin::TABLE_NOTEBOOKTEACHER);
136
137
        $courseId = api_get_course_int_id();
138
        $sessionId = api_get_session_id();
139
140
        $params = [
141
            'user_id' => api_get_user_id(),
142
            'student_id' => intval($values['student_id']),
143
            'course' => api_get_course_id(),
144
            'session_id' => $sessionId,
145
            'title' => $values['note_title'],
146
            'description' => $values['note_comment'],
147
            'update_date' => api_get_utc_datetime(),
148
        ];
149
150
        Database::update(
151
            $table,
152
            $params,
153
            [
154
                'c_id = ? AND id = ?' => [
155
                    $courseId,
156
                    $values['notebook_id'],
157
                ],
158
            ]
159
        );
160
161
        return true;
162
    }
163
164
    /**
165
     * @param int $notebookId
166
     *
167
     * @return bool
168
     */
169
    public static function deleteNote($notebookId)
170
    {
171
        if (empty($notebookId) || $notebookId != strval(intval($notebookId))) {
172
            return false;
173
        }
174
175
        // Database table definition
176
        $tableNotebook = Database::get_main_table(NotebookTeacherPlugin::TABLE_NOTEBOOKTEACHER);
177
178
        $courseId = api_get_course_int_id();
179
180
        $sql = "DELETE FROM $tableNotebook
181
                WHERE
182
                    c_id = $courseId AND
183
                    id = '".intval($notebookId)."' AND
184
                    user_id = '".api_get_user_id()."'";
185
        $result = Database::query($sql);
186
187
        if (Database::affected_rows($result) != 1) {
188
            return false;
189
        }
190
191
        return true;
192
    }
193
194
    /**
195
     * Display notes.
196
     */
197
    public static function displayNotes()
198
    {
199
        $plugin = NotebookTeacherPlugin::create();
200
        $userInfo = api_get_user_info();
201
        if (!isset($_GET['direction'])) {
202
            $sortDirection = 'ASC';
203
            $linkSortDirection = 'DESC';
204
        } elseif ($_GET['direction'] == 'ASC') {
205
            $sortDirection = 'ASC';
206
            $linkSortDirection = 'DESC';
207
        } else {
208
            $sortDirection = 'DESC';
209
            $linkSortDirection = 'ASC';
210
        }
211
212
        $studentId = isset($_GET['student_id']) ? $_GET['student_id'] : null;
213
        $sessionId = api_get_session_id();
214
        $courseCode = api_get_course_id();
215
        $active = isset($_GET['active']) ? $_GET['active'] : null;
216
        $status = STUDENT;
217
        $courseInfo = api_get_course_info();
218
        $courseId = $courseInfo['real_id'];
219
        $currentAccessUrlId = api_get_current_access_url_id();
220
        $sortByfirstName = api_sort_by_first_name();
221
        $type = isset($_REQUEST['type']) ? intval($_REQUEST['type']) : STUDENT;
222
223
        if (!empty($sessionId)) {
224
            $tableSessionCourseUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
225
            $tableUsers = Database::get_main_table(TABLE_MAIN_USER);
226
            $isWesternNameOrder = api_is_western_name_order();
227
            $sql = "SELECT DISTINCT
228
                        user.user_id, ".($isWesternNameOrder
229
                                ? "user.firstname, user.lastname"
230
                                : "user.lastname, user.firstname")."
231
                    FROM $tableSessionCourseUser as session_course_user,
232
            $tableUsers as user ";
233
            if (api_is_multiple_url_enabled()) {
234
                $sql .= ' , '.Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER).' au ';
235
            }
236
            $sql .= " WHERE c_id = '$courseId' AND session_course_user.user_id = user.user_id ";
237
            $sql .= ' AND session_id = '.$sessionId;
238
239
            if (api_is_multiple_url_enabled()) {
240
                $sql .= " AND user.user_id = au.user_id AND access_url_id =  $currentAccessUrlId  ";
241
            }
242
243
            // only users no coaches/teachers
244
            if ($type == COURSEMANAGER) {
245
                $sql .= " AND session_course_user.status = 2 ";
246
            } else {
247
                $sql .= " AND session_course_user.status = 0 ";
248
            }
249
            $sql .= $sortByfirstName
250
                ? ' ORDER BY user.firstname, user.lastname'
251
                : ' ORDER BY user.lastname, user.firstname';
252
253
            $rs = Database::query($sql);
254
255
            $courseUsersList = [];
256
            while ($row = Database::fetch_assoc($rs)) {
257
                $courseUsersList[$row['user_id']] = $row;
258
            }
259
        } else {
260
            $courseUsersList = CourseManager::get_user_list_from_course_code(
261
                $courseCode,
262
                0,
263
                null,
264
                null,
265
                $status,
266
                null,
267
                false,
268
                false,
269
                null,
270
                null,
271
                null,
272
                $active
273
            );
274
        }
275
276
        $form = new FormValidator('search_student');
277
278
        // Status
279
        $students = [];
280
        $students[] = $plugin->get_lang('AllStudent');
281
        foreach ($courseUsersList as $key => $userItem) {
282
            $students[$key] = $userItem['firstname'].' '.$userItem['lastname'];
283
        }
284
285
        $form->addElement(
286
            'select',
287
            'student_filter',
288
            $plugin->get_lang('StudentFilter'),
289
            $students,
290
            [
291
                'id' => 'student_filter',
292
                'onchange' => 'javascript: filter_student();',
293
            ]
294
        );
295
        $user_data = ['student_filter' => $studentId];
296
        $form->setDefaults($user_data);
297
298
        $selectStudent = $form->returnForm();
299
300
        // action links
301
        echo '<div class="actions">';
302
        if (!api_is_drh()) {
303
            if (!api_is_anonymous()) {
304
                if (api_get_session_id() == 0) {
305
                    echo '<a href="index.php?'.api_get_cidreq().'&action=addnote">'.
306
                        Display::return_icon(
307
                            'new_note.png',
308
                            get_lang('NoteAddNew'),
309
                            '',
310
                            '32'
311
                        ).'</a>';
312
                } elseif (api_is_allowed_to_session_edit(false, true)) {
313
                    echo '<a href="index.php?'.api_get_cidreq().'&action=addnote">'.
314
                        Display::return_icon('new_note.png', get_lang('NoteAddNew'), '', '32').'</a>';
315
                }
316
            } else {
317
                echo '<a href="javascript:void(0)">'.
318
                    Display::return_icon('new_note.png', get_lang('NoteAddNew'), '', '32').'</a>';
319
            }
320
        }
321
322
        echo '<a href="index.php?'.
323
                api_get_cidreq().
324
                '&action=changeview&view=creation_date&direction='.$linkSortDirection.'&student_id='.$studentId.'">'.
325
            Display::return_icon('notes_order_by_date_new.png', get_lang('OrderByCreationDate'), '', '32').'</a>';
326
        echo '<a href="index.php?'.
327
                api_get_cidreq().
328
                '&action=changeview&view=update_date&direction='.$linkSortDirection.'&student_id='.$studentId.'">'.
329
            Display::return_icon('notes_order_by_date_mod.png', get_lang('OrderByModificationDate'), '', '32').'</a>';
330
        echo '<a href="index.php?'.
331
                api_get_cidreq().
332
                '&action=changeview&view=title&direction='.$linkSortDirection.'&student_id='.$studentId.'">'.
333
            Display::return_icon('notes_order_by_title.png', get_lang('OrderByTitle'), '', '32').'</a>';
334
335
        echo '</div>';
336
        echo '<div class="row">'.$selectStudent.'</div>';
337
338
        $view = Session::read('notebook_view');
339
        if (!isset($view) ||
340
            !in_array($view, ['creation_date', 'update_date', 'title'])
341
        ) {
342
            Session::write('notebook_view', 'creation_date');
343
        }
344
345
        $view = Session::read('notebook_view');
346
347
        // Database table definition
348
        $tableNotebook = Database::get_main_table(NotebookTeacherPlugin::TABLE_NOTEBOOKTEACHER);
349
        if ($view == 'creation_date' || $view == 'update_date') {
350
            $orderBy = " ORDER BY $view $sortDirection ";
351
        } else {
352
            $orderBy = " ORDER BY $view $sortDirection ";
353
        }
354
355
        //condition for the session
356
        $session_id = api_get_session_id();
357
        $conditionSession = api_get_session_condition($session_id);
358
359
        $condExtra = $view == 'update_date' ? " AND update_date <> ''" : " ";
360
        $courseId = api_get_course_int_id();
361
362
        if ($studentId > 0) {
363
            // Only one student
364
            $conditionStudent = " AND student_id = $studentId";
365
366
            $sql = "SELECT * FROM $tableNotebook
367
                    WHERE
368
                    c_id = $courseId
369
                    $conditionSession
370
                    $conditionStudent
371
                    $condExtra $orderBy
372
                    ";
373
            $first = true;
374
            $result = Database::query($sql);
375
            if (Database::num_rows($result) > 0) {
376
                while ($row = Database::fetch_array($result)) {
377
                    if ($first) {
378
                        $studentText = '';
379
                        if ($row['student_id'] > 0) {
380
                            $studentInfo = api_get_user_info($row['student_id']);
381
                            $studentText = $studentInfo['complete_name'];
382
                        }
383
                        echo Display::page_subheader($studentText);
384
                        $first = false;
385
                    }
386
                    // Validation when belongs to a session
387
                    $sessionImg = api_get_session_image($row['session_id'], $userInfo['status']);
388
                    $updateValue = '';
389
                    if ($row['update_date'] != $row['creation_date']) {
390
                        $updateValue = ', '.get_lang('UpdateDate').': '.
391
                                        Display::dateToStringAgoAndLongDate($row['update_date']);
392
                    }
393
                    $userInfo = api_get_user_info($row['user_id']);
394
                    $author = ', '.get_lang('Teacher').': '.$userInfo['complete_name'];
395
                    $actions = '';
396
                    if (intval($row['user_id']) == api_get_user_id()) {
397
                        $actions = '<a href="'.
398
                                api_get_self().'?'.
399
                                api_get_cidreq().'action=editnote&notebook_id='.$row['id'].'">'.
400
                                Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL).'</a>';
401
                        $actions .= '<a href="'.
402
                                api_get_self().
403
                                '?action=deletenote&notebook_id='.$row['id'].
404
                                '" onclick="return confirmation(\''.$row['title'].'\');">'.
405
                                Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
406
                    }
407
                    echo Display::panel(
408
                        $row['description'],
409
                        $row['title'].$sessionImg.' <div class="pull-right">'.$actions.'</div>',
410
                        get_lang('CreationDate').': '.
411
                        Display::dateToStringAgoAndLongDate($row['creation_date']).$updateValue.$author
412
                    );
413
                }
414
            } else {
415
                echo Display::return_message($plugin->get_lang('NoNotebookUser'), 'warning');
416
            }
417
        } else {
418
            // All students
419
            foreach ($courseUsersList as $key => $userItem) {
420
                $studentId = $key;
421
                $studentText = $userItem['firstname'].' '.$userItem['lastname'];
422
                $conditionStudent = " AND student_id = $studentId";
423
424
                $sql = "SELECT * FROM $tableNotebook
425
                        WHERE
426
                        c_id = $courseId
427
                        $conditionSession
428
                        $conditionStudent
429
                        $condExtra $orderBy
430
                ";
431
432
                $result = Database::query($sql);
433
                if (Database::num_rows($result) > 0) {
434
                    echo Display::page_subheader($studentText);
435
                    while ($row = Database::fetch_array($result)) {
436
                        // Validation when belongs to a session
437
                        $sessionImg = api_get_session_image($row['session_id'], $userInfo['status']);
438
                        $updateValue = '';
439
440
                        if ($row['update_date'] != $row['creation_date']) {
441
                            $updateValue = ', '.get_lang('UpdateDate').': '.
442
                            Display::dateToStringAgoAndLongDate($row['update_date']);
443
                        }
444
445
                        $userInfo = api_get_user_info($row['user_id']);
446
                        $author = ', '.get_lang('Teacher').': '.$userInfo['complete_name'];
447
448
                        if (intval($row['user_id']) == api_get_user_id()) {
449
                            $actions = '<a href="'.api_get_self().
450
                                '?action=editnote&notebook_id='.$row['id'].'&'.api_get_cidreq().'">'.
451
                                    Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL).'</a>';
452
                            $actions .= '<a href="'.api_get_self().
453
                                    '?action=deletenote&notebook_id='.$row['id'].
454
                                    '" onclick="return confirmation(\''.$row['title'].'\');">'.
455
                                    Display::return_icon(
456
                                        'delete.png',
457
                                        get_lang('Delete'),
458
                                        '',
459
                                        ICON_SIZE_SMALL
460
                                    ).'</a>';
461
                        } else {
462
                            $actions = '';
463
                        }
464
465
                        echo Display::panel(
466
                            $row['description'],
467
                            $row['title'].$sessionImg.' <div class="pull-right">'.$actions.'</div>',
468
                            get_lang('CreationDate').': '.
469
                            Display::dateToStringAgoAndLongDate($row['creation_date']).$updateValue.$author
470
                        );
471
                    }
472
                }
473
            }
474
475
            $conditionStudent = " AND student_id = 0";
476
477
            $sql = "SELECT * FROM $tableNotebook
478
                    WHERE
479
                    c_id = $courseId
480
                    $conditionSession
481
                    $conditionStudent
482
                    $condExtra $orderBy
483
            ";
484
485
            $result = Database::query($sql);
486
            if (Database::num_rows($result) > 0) {
487
                echo Display::page_subheader($plugin->get_lang('NotebookNoStudentAssigned'));
488
                while ($row = Database::fetch_array($result)) {
489
                    // Validation when belongs to a session
490
                    $sessionImg = api_get_session_image($row['session_id'], $userInfo['status']);
491
                    $updateValue = '';
492
493
                    if ($row['update_date'] != $row['creation_date']) {
494
                        $updateValue = ', '.get_lang('UpdateDate').': '.
495
                        Display::dateToStringAgoAndLongDate($row['update_date']);
496
                    }
497
498
                    $userInfo = api_get_user_info($row['user_id']);
499
                    $author = ', '.get_lang('Teacher').': '.$userInfo['complete_name'];
500
                    $actions = '';
501
                    if (intval($row['user_id']) == api_get_user_id()) {
502
                        $actions = '<a href="'.api_get_self().
503
                                '?action=editnote&notebook_id='.$row['id'].'&'.api_get_cidreq().'">'.
504
                                Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL).'</a>';
505
                        $actions .= '<a href="'.api_get_self().
506
                                '?action=deletenote&notebook_id='.$row['id'].
507
                                '" onclick="return confirmation(\''.$row['title'].'\');">'.
508
                                Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
509
                    }
510
                    echo Display::panel(
511
                        $row['description'],
512
                        $row['title'].$sessionImg.' <div class="pull-right">'.$actions.'</div>',
513
                        get_lang('CreationDate').': '.
514
                        Display::dateToStringAgoAndLongDate($row['creation_date']).$updateValue.$author
515
                    );
516
                }
517
            }
518
        }
519
    }
520
}
521