NotebookManager   A
last analyzed

Complexity

Total Complexity 29

Size/Duplication

Total Lines 309
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 29
eloc 151
c 0
b 0
f 0
dl 0
loc 309
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A javascript_notebook() 0 6 1
B save_note() 0 42 7
A get_note_information() 0 25 3
A delete_note() 0 34 3
A update_note() 0 42 3
C display_notes() 0 86 11
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 * This class provides methods for the notebook management.
8
 * Include/require it in your code to use its features.
9
 *
10
 * @author Carlos Vargas <[email protected]>, move code of main/notebook up here
11
 */
12
class NotebookManager
13
{
14
    /**
15
     * Constructor.
16
     */
17
    public function __construct()
18
    {
19
    }
20
21
    /**
22
     * a little bit of javascript to display a prettier warning when deleting a note.
23
     *
24
     * @return string
25
     *
26
     * @author Patrick Cool <[email protected]>, Ghent University, Belgium
27
     *
28
     * @version januari 2009, dokeos 1.8.6
29
     */
30
    public static function javascript_notebook()
31
    {
32
        return "<script>
33
				function confirmation (name)
34
				{
35
					if (confirm(\" ".get_lang("NoteConfirmDelete")." \"+ name + \" ?\"))
36
						{return true;}
37
					else
38
						{return false;}
39
				}
40
				</script>";
41
    }
42
43
    /**
44
     * This functions stores the note in the database.
45
     *
46
     * @param array $values
47
     * @param int   $userId    Optional. The user ID
48
     * @param int   $courseId  Optional. The course ID
49
     * @param int   $sessionId Optional. The session ID
50
     *
51
     * @return bool
52
     *
53
     * @author Christian Fasanando <[email protected]>
54
     * @author Patrick Cool <[email protected]>, Ghent University, Belgium
55
     *
56
     * @version januari 2009, dokeos 1.8.6
57
     */
58
    public static function save_note($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_course_table(TABLE_NOTEBOOK);
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
            'notebook_id' => 0,
74
            'c_id' => $courseId,
75
            'user_id' => $userId,
76
            'course' => $courseCode,
77
            'session_id' => $sessionId,
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
            $sql = "UPDATE $table SET notebook_id = $id WHERE iid = $id";
88
            Database::query($sql);
89
90
            //insert into item_property
91
            api_item_property_update(
92
                $courseInfo,
93
                TOOL_NOTEBOOK,
94
                $id,
95
                'NotebookAdded',
96
                $userId
97
            );
98
99
            return $id;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $id also could return the type integer which is incompatible with the documented return type boolean.
Loading history...
100
        }
101
    }
102
103
    /**
104
     * @param int $notebook_id
105
     *
106
     * @return array
107
     */
108
    public static function get_note_information($notebook_id)
109
    {
110
        if (empty($notebook_id)) {
111
            return [];
112
        }
113
114
        // Database table definition
115
        $table = Database::get_course_table(TABLE_NOTEBOOK);
116
        $course_id = api_get_course_int_id();
117
        $notebook_id = (int) $notebook_id;
118
119
        $sql = "SELECT
120
                user_id,
121
                notebook_id 		AS notebook_id,
122
                title				AS note_title,
123
                description 		AS note_comment,
124
                session_id			AS session_id
125
                FROM $table
126
                WHERE c_id = $course_id AND notebook_id = '".$notebook_id."' ";
127
        $result = Database::query($sql);
128
        if (Database::num_rows($result) != 1) {
129
            return [];
130
        }
131
132
        return Database::fetch_array($result);
133
    }
134
135
    /**
136
     * This functions updates the note in the database.
137
     *
138
     * @param array $values
139
     *
140
     * @author Christian Fasanando <[email protected]>
141
     * @author Patrick Cool <[email protected]>, Ghent University, Belgium
142
     *
143
     * @return bool
144
     *
145
     * @version januari 2009, dokeos 1.8.6
146
     */
147
    public static function update_note($values)
148
    {
149
        if (!is_array($values) || empty($values['note_title'])) {
150
            return false;
151
        }
152
153
        // Database table definition
154
        $table = Database::get_course_table(TABLE_NOTEBOOK);
155
156
        $course_id = api_get_course_int_id();
157
        $sessionId = api_get_session_id();
158
159
        $params = [
160
            'user_id' => api_get_user_id(),
161
            'course' => api_get_course_id(),
162
            'session_id' => $sessionId,
163
            'title' => $values['note_title'],
164
            'description' => $values['note_comment'],
165
            'update_date' => api_get_utc_datetime(),
166
        ];
167
168
        Database::update(
169
            $table,
170
            $params,
171
            [
172
                'c_id = ? AND notebook_id = ?' => [
173
                    $course_id,
174
                    $values['notebook_id'],
175
                ],
176
            ]
177
        );
178
179
        // update item_property (update)
180
        api_item_property_update(
181
            api_get_course_info(),
182
            TOOL_NOTEBOOK,
183
            $values['notebook_id'],
184
            'NotebookUpdated',
185
            api_get_user_id()
186
        );
187
188
        return true;
189
    }
190
191
    /**
192
     * @param int $notebook_id
193
     *
194
     * @return bool
195
     */
196
    public static function delete_note($notebook_id)
197
    {
198
        $notebook_id = (int) $notebook_id;
199
200
        if (empty($notebook_id)) {
201
            return false;
202
        }
203
204
        // Database table definition
205
        $table = Database::get_course_table(TABLE_NOTEBOOK);
206
        $course_id = api_get_course_int_id();
207
208
        $sql = "DELETE FROM $table
209
                WHERE
210
                    c_id = $course_id AND
211
                    notebook_id='".$notebook_id."' AND
212
                    user_id = '".api_get_user_id()."'";
213
        $result = Database::query($sql);
214
        $affected_rows = Database::affected_rows($result);
215
216
        if ($affected_rows != 1) {
217
            return false;
218
        }
219
220
        // Update item_property (delete)
221
        api_item_property_update(
222
            api_get_course_info(),
223
            TOOL_NOTEBOOK,
224
            $notebook_id,
225
            'delete',
226
            api_get_user_id()
227
        );
228
229
        return true;
230
    }
231
232
    /**
233
     * Display notes.
234
     */
235
    public static function display_notes()
236
    {
237
        $cidReq = api_get_cidreq();
238
        $sessionId = api_get_session_id();
239
        $_user = api_get_user_info();
240
        if (!isset($_GET['direction'])) {
241
            $sort_direction = 'ASC';
242
            $link_sort_direction = 'DESC';
243
        } elseif ($_GET['direction'] == 'ASC') {
244
            $sort_direction = 'ASC';
245
            $link_sort_direction = 'DESC';
246
        } else {
247
            $sort_direction = 'DESC';
248
            $link_sort_direction = 'ASC';
249
        }
250
251
        // action links
252
        echo '<div class="actions">';
253
        if (!api_is_anonymous()) {
254
            if ($sessionId == 0 || api_is_allowed_to_session_edit(false, true)) {
255
                echo '<a href="index.php?'.$cidReq.'&action=addnote">'.
256
                    Display::return_icon('new_note.png', get_lang('NoteAddNew'), '', '32').'</a>';
257
            }
258
        }
259
260
        echo '<a href="index.php?'.$cidReq.'&action=changeview&view=creation_date&direction='.$link_sort_direction.'">'.
261
            Display::return_icon('notes_order_by_date_new.png', get_lang('OrderByCreationDate'), '', '32').'</a>';
262
        echo '<a href="index.php?'.$cidReq.'&action=changeview&view=update_date&direction='.$link_sort_direction.'">'.
263
            Display::return_icon('notes_order_by_date_mod.png', get_lang('OrderByModificationDate'), '', '32').'</a>';
264
        echo '<a href="index.php?'.$cidReq.'&action=changeview&view=title&direction='.$link_sort_direction.'">'.
265
            Display::return_icon('notes_order_by_title.png', get_lang('OrderByTitle'), '', '32').'</a>';
266
        echo '</div>';
267
268
        $notebookView = Session::read('notebook_view');
269
        if (empty($notebookView)) {
270
            $notebookView = 'creation_date';
271
        }
272
273
        if (!in_array($notebookView, ['creation_date', 'update_date', 'title'])) {
274
            Session::write('notebook_view', 'creation_date');
275
        }
276
277
        // Database table definition
278
        $table = Database::get_course_table(TABLE_NOTEBOOK);
279
        $order_by = " ORDER BY `$notebookView` $sort_direction ";
280
281
        // Condition for the session
282
        $condition_session = api_get_session_condition($sessionId);
283
284
        $cond_extra = $notebookView === 'update_date' ? " AND update_date <> ''" : ' ';
285
        $course_id = api_get_course_int_id();
286
287
        $sql = "SELECT * FROM $table
288
                WHERE
289
                    c_id = $course_id AND
290
                    user_id = '".api_get_user_id()."'
291
                    $condition_session
292
                    $cond_extra $order_by
293
                ";
294
        $result = Database::query($sql);
295
        $iconEdit = Display::return_icon('edit.png', get_lang('Edit'));
296
        $iconDelete = Display::return_icon('delete.png', get_lang('Delete'));
297
        while ($row = Database::fetch_array($result)) {
298
            // Validation when belongs to a session
299
            $session_img = api_get_session_image($row['session_id'], $_user['status']);
300
            $updateValue = '';
301
            if ($row['update_date'] != $row['creation_date']) {
302
                $updateValue = ', '.get_lang('UpdateDate').': '.Display::dateToStringAgoAndLongDate($row['update_date']);
303
            }
304
305
            $actions = Display::url(
306
                $iconEdit,
307
                api_get_self().'?action=editnote&notebook_id='.$row['notebook_id'].'&'.$cidReq
308
            );
309
            $actions .= Display::url(
310
                $iconDelete,
311
                api_get_self().'?action=deletenote&notebook_id='.$row['notebook_id'].'&'.$cidReq,
312
                ['onclick' => 'return confirmation(\''.$row['title'].'\');']
313
            );
314
315
            echo Display::panel(
316
                Security::remove_XSS($row['description']),
317
                Security::remove_XSS($row['title']).$session_img.
318
                ' <div class="pull-right">'.$actions.'</div>',
319
                get_lang('CreationDate').': '.Display::dateToStringAgoAndLongDate($row['creation_date']).
320
                $updateValue
321
            );
322
        }
323
    }
324
}
325