Completed
Push — master ( 4fc9f8...d0e06e )
by Julito
12:04
created

Blog::deleteTask()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 2
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class Blog.
6
 *
7
 * Contains several functions dealing with displaying,
8
 * editing,... of a blog
9
 *
10
 * @author Toon Keppens <[email protected]>
11
 * @author Julio Montoya - Cleaning code
12
 */
13
class Blog
14
{
15
    /**
16
     * Get the title of a blog.
17
     *
18
     * @author Toon Keppens
19
     *
20
     * @param int $blog_id The internal ID of the blog
21
     *
22
     * @return string Blog Title
23
     */
24
    public static function getBlogTitle($blog_id)
25
    {
26
        $course_id = api_get_course_int_id();
27
28
        if (is_numeric($blog_id)) {
29
            $table = Database::get_course_table(TABLE_BLOGS);
30
31
            $sql = "SELECT blog_name
32
                    FROM $table
33
                    WHERE c_id = $course_id AND blog_id = ".intval($blog_id);
34
35
            $result = Database::query($sql);
36
            $blog = Database::fetch_array($result);
37
38
            return stripslashes($blog['blog_name']);
39
        }
40
    }
41
42
    /**
43
     * Get the description of a blog.
44
     *
45
     * @author Toon Keppens
46
     *
47
     * @param int $blog_id The internal ID of the blog
48
     *
49
     * @return string Blog description
50
     */
51
    public static function getBlogSubtitle($blog_id)
52
    {
53
        $table = Database::get_course_table(TABLE_BLOGS);
54
        $course_id = api_get_course_int_id();
55
        $sql = "SELECT blog_subtitle FROM $table
56
                WHERE c_id = $course_id AND blog_id ='".intval($blog_id)."'";
57
        $result = Database::query($sql);
58
        $blog = Database::fetch_array($result);
59
60
        return stripslashes($blog['blog_subtitle']);
61
    }
62
63
    /**
64
     * Get the users of a blog.
65
     *
66
     * @author Toon Keppens
67
     *
68
     * @param int $blog_id The ID of the blog
69
     *
70
     * @return array Returns an array with [userid]=>[username]
71
     */
72
    public static function getBlogUsers($blog_id)
73
    {
74
        // Database table definitions
75
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
76
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
77
78
        $course_id = api_get_course_int_id();
79
80
        // Get blog members
81
        $sql = "SELECT user.user_id, user.firstname, user.lastname
82
                FROM  $tbl_blogs_rel_user blogs_rel_user
83
                INNER JOIN $tbl_users user
84
                ON (blogs_rel_user.user_id = user.user_id)
85
                WHERE
86
                    blogs_rel_user.c_id = $course_id AND
87
                    blogs_rel_user.blog_id = '".(int) $blog_id."'";
88
        $result = Database::query($sql);
89
        $blog_members = [];
90
        while ($user = Database::fetch_array($result)) {
91
            $blog_members[$user['user_id']] = api_get_person_name(
92
                $user['firstname'],
93
                $user['lastname']
94
            );
95
        }
96
97
        return $blog_members;
98
    }
99
100
    /**
101
     * Creates a new blog in the given course.
102
     *
103
     * @author Toon Keppens
104
     *
105
     * @param string $title    The title of the new blog
106
     * @param string $subtitle The description (or subtitle) of the new blog
107
     */
108
    public static function addBlog($title, $subtitle)
109
    {
110
        $_user = api_get_user_info();
111
        $course_id = api_get_course_int_id();
112
113
        $current_date = api_get_utc_datetime();
114
        $session_id = api_get_session_id();
115
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
116
        $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
117
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
118
119
        //verified if exist blog
120
        $sql = "SELECT COUNT(*) as count FROM $tbl_blogs
121
                WHERE
122
                    c_id = $course_id AND
123
                    blog_name = '".Database::escape_string($title)."' AND
124
                    blog_subtitle = '".Database::escape_string($subtitle)."'  ";
125
        $res = Database::query($sql);
126
        $info_count = Database::result($res, 0, 0);
127
128
        if (0 == $info_count) {
129
            // Create the blog
130
            $params = [
131
                'blog_id' => 0,
132
                'c_id' => $course_id,
133
                'blog_name' => $title,
134
                'blog_subtitle' => $subtitle,
135
                'date_creation' => $current_date,
136
                'visibility' => 1,
137
                'session_id' => $session_id,
138
            ];
139
            $this_blog_id = Database::insert($tbl_blogs, $params);
140
141
            if ($this_blog_id > 0) {
142
                $sql = "UPDATE $tbl_blogs SET blog_id = iid WHERE iid = $this_blog_id";
143
                Database::query($sql);
144
145
                // insert into item_property
146
                api_item_property_update(
147
                    api_get_course_info(),
148
                    TOOL_BLOGS,
149
                    $this_blog_id,
150
                    'BlogAdded',
151
                    api_get_user_id()
152
                );
153
            }
154
155
            // Make first post. :)
156
            $params = [
157
                'post_id' => 0,
158
                'c_id' => $course_id,
159
                'title' => get_lang("Welcome !"),
160
                'full_text' => get_lang('This is the first task in the project. Everybody subscribed to this project is able to participate'),
161
                'date_creation' => $current_date,
162
                'blog_id' => $this_blog_id,
163
                'author_id' => $_user['user_id'],
164
            ];
165
            $postId = Database::insert($tbl_blogs_posts, $params);
166
            if ($postId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $postId of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
167
                $sql = "UPDATE $tbl_blogs_posts SET post_id = iid WHERE iid = $postId";
168
                Database::query($sql);
169
            }
170
171
            // Put it on course homepage
172
            $params = [
173
                'c_id' => $course_id,
174
                'name' => $title,
175
                'link' => 'blog/blog.php?blog_id='.$this_blog_id,
0 ignored issues
show
Bug introduced by
Are you sure $this_blog_id of type false|integer can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

175
                'link' => 'blog/blog.php?blog_id='./** @scrutinizer ignore-type */ $this_blog_id,
Loading history...
176
                'image' => 'blog.gif',
177
                'visibility' => '1',
178
                'admin' => '0',
179
                'address' => 'pastillegris.gif',
180
                'added_tool' => 0,
181
                'session_id' => $session_id,
182
                'target' => '',
183
            ];
184
            $toolId = Database::insert($tbl_tool, $params);
185
            if ($toolId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $toolId of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
186
                $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $toolId";
187
                Database::query($sql);
188
            }
189
190
            // Subscribe the teacher to this blog
191
            self::subscribeUser($this_blog_id, $_user['user_id']);
192
        }
193
    }
194
195
    /**
196
     * Subscribes a user to a given blog.
197
     *
198
     * @author Toon Keppens
199
     *
200
     * @param int $blog_id The internal blog ID
201
     * @param int $user_id The internal user ID (of the user to be subscribed)
202
     */
203
    public static function subscribeUser($blog_id, $user_id)
204
    {
205
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
206
        $tbl_user_permissions = Database::get_course_table(TABLE_PERMISSION_USER);
207
208
        $course_id = api_get_course_int_id();
209
        $blog_id = intval($blog_id);
210
        $user_id = intval($user_id);
211
212
        // Subscribe the user
213
        $sql = "INSERT INTO $tbl_blogs_rel_user (c_id, blog_id, user_id )
214
                VALUES ($course_id, $blog_id, $user_id)";
215
        Database::query($sql);
216
217
        // Give this user basic rights
218
        $sql = "INSERT INTO $tbl_user_permissions (c_id, user_id, tool, action)
219
                VALUES ($course_id, $user_id, 'BLOG_$blog_id', 'article_add')";
220
        Database::query($sql);
221
222
        $id = Database::insert_id();
223
        if ($id) {
224
            $sql = "UPDATE $tbl_user_permissions SET id = iid WHERE iid = $id";
225
            Database::query($sql);
226
        }
227
228
        $sql = "INSERT INTO $tbl_user_permissions (c_id, user_id, tool, action)
229
                VALUES ($course_id, $user_id,'BLOG_$blog_id', 'article_comments_add')";
230
        Database::query($sql);
231
232
        $id = Database::insert_id();
233
        if ($id) {
234
            $sql = "UPDATE $tbl_user_permissions SET id = iid WHERE iid = $id";
235
            Database::query($sql);
236
        }
237
    }
238
239
    /**
240
     * Update title and subtitle of a blog in the given course.
241
     *
242
     * @author Toon Keppens
243
     *
244
     * @param int    $blog_id  The internal ID of the blog
245
     * @param string $title    The title to be set
246
     * @param string $subtitle The subtitle (or description) to be set
247
     */
248
    public static function editBlog($blog_id, $title, $subtitle = '')
249
    {
250
        // Table definitions
251
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
252
        $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
253
254
        $course_id = api_get_course_int_id();
255
        $blog_id = intval($blog_id);
256
        $title = Database::escape_string($title);
257
        $subtitle = Database::escape_string($subtitle);
258
259
        // Update the blog
260
        $sql = "UPDATE $tbl_blogs SET
261
                blog_name = '$title',
262
                blog_subtitle = '$subtitle'
263
                WHERE
264
                    c_id = $course_id AND
265
                    blog_id = $blog_id
266
                LIMIT 1";
267
        Database::query($sql);
268
269
        //update item_property (update)
270
        api_item_property_update(
271
            api_get_course_info(),
272
            TOOL_BLOGS,
273
            $blog_id,
274
            'BlogUpdated',
275
            api_get_user_id()
276
        );
277
278
        // Update course homepage link
279
        $sql = "UPDATE $tbl_tool SET
280
                name = '$title'
281
                WHERE c_id = $course_id AND link = 'blog/blog.php?blog_id=$blog_id' 
282
                LIMIT 1";
283
        Database::query($sql);
284
    }
285
286
    /**
287
     * Deletes a blog and it's posts from the course database.
288
     *
289
     * @author Toon Keppens
290
     *
291
     * @param int $blog_id The internal blog ID
292
     */
293
    public static function deleteBlog($blog_id)
294
    {
295
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
296
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
297
        $tbl_blogs_comment = Database::get_course_table(TABLE_BLOGS_COMMENTS);
298
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
299
        $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
300
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
301
302
        $course_id = api_get_course_int_id();
303
        $blog_id = intval($blog_id);
304
305
        // Delete posts from DB and the attachments
306
        self::deleteAllBlogAttachments($blog_id);
307
308
        //Delete comments
309
        $sql = "DELETE FROM $tbl_blogs_comment WHERE c_id = $course_id AND blog_id = $blog_id";
310
        Database::query($sql);
311
312
        // Delete posts
313
        $sql = "DELETE FROM $tbl_blogs_posts WHERE c_id = $course_id AND blog_id = $blog_id";
314
        Database::query($sql);
315
316
        // Delete tasks
317
        $sql = "DELETE FROM $tbl_blogs_tasks WHERE c_id = $course_id AND blog_id = $blog_id";
318
        Database::query($sql);
319
320
        // Delete ratings
321
        $sql = "DELETE FROM $tbl_blogs_rating WHERE c_id = $course_id AND blog_id = $blog_id";
322
        Database::query($sql);
323
324
        // Delete blog
325
        $sql = "DELETE FROM $tbl_blogs WHERE c_id = $course_id AND blog_id = $blog_id";
326
        Database::query($sql);
327
328
        // Delete from course homepage
329
        $sql = "DELETE FROM $tbl_tool WHERE c_id = $course_id AND link = 'blog/blog.php?blog_id=".$blog_id."'";
330
        Database::query($sql);
331
332
        //update item_property (delete)
333
        api_item_property_update(
334
            api_get_course_info(),
335
            TOOL_BLOGS,
336
            $blog_id,
337
            'delete',
338
            api_get_user_id()
339
        );
340
    }
341
342
    /**
343
     * Creates a new post in a given blog.
344
     *
345
     * @author Toon Keppens
346
     *
347
     * @param string $title        The title of the new post
348
     * @param string $full_text    The full text of the new post
349
     * @param string $file_comment The text of the comment (if any)
350
     * @param int    $blog_id      The internal blog ID
351
     *
352
     * @return int
353
     */
354
    public static function createPost($title, $full_text, $file_comment, $blog_id)
355
    {
356
        $_user = api_get_user_info();
357
        $_course = api_get_course_info();
358
        $course_id = $_course['real_id'];
359
        $blog_id = intval($blog_id);
360
361
        $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
362
        $upload_ok = true;
363
        $has_attachment = false;
364
        $current_date = api_get_utc_datetime();
365
366
        if (!empty($_FILES['user_upload']['name'])) {
367
            $upload_ok = process_uploaded_file($_FILES['user_upload']);
368
            $has_attachment = true;
369
        }
370
371
        if ($upload_ok) {
372
            // Table Definitions
373
            $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
374
            $title = Database::escape_string($title);
375
            $full_text = Database::escape_string($full_text);
376
377
            // Create the post
378
            $sql = "INSERT INTO $tbl_blogs_posts (c_id, title, full_text, date_creation, blog_id, author_id )
379
                    VALUES ($course_id, '$title', '$full_text', '$current_date', '$blog_id', ".$_user['user_id'].")";
380
381
            Database::query($sql);
382
            $last_post_id = Database::insert_id();
383
384
            if ($last_post_id) {
385
                $sql = "UPDATE $tbl_blogs_posts SET post_id = iid WHERE iid = $last_post_id";
386
                Database::query($sql);
387
            }
388
389
            if ($has_attachment) {
390
                $courseDir = $_course['path'].'/upload/blog';
391
                $sys_course_path = api_get_path(SYS_COURSE_PATH);
0 ignored issues
show
Bug introduced by
The constant SYS_COURSE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
392
                $updir = $sys_course_path.$courseDir;
393
394
                // Try to add an extension to the file if it hasn't one
395
                $new_file_name = add_ext_on_mime(
396
                    stripslashes($_FILES['user_upload']['name']),
397
                    $_FILES['user_upload']['type']
398
                );
399
400
                // user's file name
401
                $file_name = $_FILES['user_upload']['name'];
402
403
                if (!filter_extension($new_file_name)) {
404
                    echo Display::return_message(get_lang('File upload failed: this file extension or file type is prohibited'), 'error');
405
                } else {
406
                    $new_file_name = uniqid('');
407
                    $new_path = $updir.'/'.$new_file_name;
408
                    $result = @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path);
409
                    $comment = Database::escape_string($file_comment);
410
                    $file_name = Database::escape_string($file_name);
411
                    $size = intval($_FILES['user_upload']['size']);
412
413
                    // Storing the attachments if any
414
                    if ($result) {
415
                        $sql = "INSERT INTO $blog_table_attachment (c_id, filename,comment, path, post_id,size, blog_id,comment_id)
416
                            VALUES ($course_id, '$file_name', '$comment', '$new_file_name', $last_post_id, $size, $blog_id, 0)";
417
                        Database::query($sql);
418
                        $id = Database::insert_id();
419
                        if ($id) {
420
                            $sql = "UPDATE $blog_table_attachment SET id = iid WHERE iid = $id";
421
                            Database::query($sql);
422
                        }
423
                    }
424
                }
425
            }
426
427
            return $last_post_id;
428
        } else {
429
            echo Display::return_message(get_lang('No file was uploaded.'), 'error');
430
431
            return 0;
432
        }
433
    }
434
435
    /**
436
     * Edits a post in a given blog.
437
     *
438
     * @author Toon Keppens
439
     *
440
     * @param int    $post_id   The internal ID of the post to edit
441
     * @param string $title     The title
442
     * @param string $full_text The full post text
443
     * @param int    $blog_id   The internal ID of the blog in which the post is located
444
     */
445
    public static function editPost($post_id, $title, $full_text, $blog_id)
446
    {
447
        $table = Database::get_course_table(TABLE_BLOGS_POSTS);
448
        $course_id = api_get_course_int_id();
449
        $title = Database::escape_string($title);
450
        $full_text = Database::escape_string($full_text);
451
        $post_id = intval($post_id);
452
        $blog_id = intval($blog_id);
453
454
        // Create the post
455
        $sql = "UPDATE $table SET
456
                title = '$title',
457
                full_text = '$full_text'
458
                WHERE c_id = $course_id AND post_id = $post_id AND blog_id = $blog_id
459
                LIMIT 1";
460
        Database::query($sql);
461
    }
462
463
    /**
464
     * Deletes an article and its comments.
465
     *
466
     * @author Toon Keppens
467
     *
468
     * @param int $blog_id The internal blog ID
469
     * @param int $post_id The internal post ID
470
     */
471
    public static function deletePost($blog_id, $post_id)
472
    {
473
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
474
        $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
475
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
476
        $blog_id = intval($blog_id);
477
        $post_id = intval($post_id);
478
479
        $course_id = api_get_course_int_id();
480
481
        // Delete ratings on this comment
482
        $sql = "DELETE FROM $tbl_blogs_rating
483
                WHERE c_id = $course_id AND blog_id = $blog_id AND item_id = $post_id AND rating_type = 'post'";
484
        Database::query($sql);
485
486
        // Delete the post
487
        $sql = "DELETE FROM $tbl_blogs_posts
488
                WHERE c_id = $course_id AND post_id = $post_id";
489
        Database::query($sql);
490
491
        // Delete the comments
492
        $sql = "DELETE FROM $tbl_blogs_comments
493
                WHERE c_id = $course_id AND post_id = $post_id AND blog_id = $blog_id";
494
        Database::query($sql);
495
496
        // Delete posts and attachments
497
        self::deleteAllBlogAttachments($blog_id, $post_id);
498
    }
499
500
    /**
501
     * Creates a comment on a post in a given blog.
502
     *
503
     * @author Toon Keppens
504
     *
505
     * @param string $title        The comment title
506
     * @param string $full_text    The full text of the comment
507
     * @param string $file_comment A comment on a file, if any was uploaded
508
     * @param int    $blog_id      The internal blog ID
509
     * @param int    $post_id      The internal post ID
510
     * @param int    $parent_id    The internal parent post ID
511
     * @param int    $task_id      The internal task ID (if any)
512
     */
513
    public static function createComment(
514
        $title,
515
        $full_text,
516
        $file_comment,
517
        $blog_id,
518
        $post_id,
519
        $parent_id,
520
        $task_id = null
521
    ) {
522
        $_user = api_get_user_info();
523
        $_course = api_get_course_info();
524
        $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
525
526
        $upload_ok = true;
527
        $has_attachment = false;
528
        $current_date = api_get_utc_datetime();
529
        $course_id = api_get_course_int_id();
530
531
        if (!empty($_FILES['user_upload']['name'])) {
532
            $upload_ok = process_uploaded_file($_FILES['user_upload']);
533
            $has_attachment = true;
534
        }
535
536
        if ($upload_ok) {
537
            // Table Definition
538
            $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
539
            $title = Database::escape_string($title);
540
            $full_text = Database::escape_string($full_text);
541
            $blog_id = intval($blog_id);
542
            $post_id = intval($post_id);
543
            $parent_id = intval($parent_id);
544
            $task_id = !empty($task_id) ? intval($task_id) : 'null';
545
546
            // Create the comment
547
            $sql = "INSERT INTO $tbl_blogs_comments (c_id, title, comment, author_id, date_creation, blog_id, post_id, parent_comment_id, task_id )
548
                    VALUES ($course_id, '$title', '$full_text', ".$_user['user_id'].", '$current_date', $blog_id, $post_id, $parent_id, '$task_id')";
549
            Database::query($sql);
550
551
            // Empty post values, or they are shown on the page again
552
            $last_id = Database::insert_id();
553
554
            if ($last_id) {
555
                $sql = "UPDATE $tbl_blogs_comments SET comment_id = iid WHERE iid = $last_id";
556
                Database::query($sql);
557
558
                if ($has_attachment) {
559
                    $courseDir = $_course['path'].'/upload/blog';
560
                    $sys_course_path = api_get_path(SYS_COURSE_PATH);
0 ignored issues
show
Bug introduced by
The constant SYS_COURSE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
561
                    $updir = $sys_course_path.$courseDir;
562
563
                    // Try to add an extension to the file if it hasn't one
564
                    $new_file_name = add_ext_on_mime(
565
                        stripslashes($_FILES['user_upload']['name']),
566
                        $_FILES['user_upload']['type']
567
                    );
568
569
                    // user's file name
570
                    $file_name = Database::escape_string($_FILES['user_upload']['name']);
571
572
                    if (!filter_extension($new_file_name)) {
573
                        echo Display::return_message(get_lang('File upload failed: this file extension or file type is prohibited'), 'error');
574
                    } else {
575
                        $new_file_name = uniqid('');
576
                        $new_path = $updir.'/'.$new_file_name;
577
                        $result = @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path);
578
                        $comment = Database::escape_string($file_comment);
579
                        $size = intval($_FILES['user_upload']['size']);
580
581
                        // Storing the attachments if any
582
                        if ($result) {
583
                            $sql = "INSERT INTO $blog_table_attachment (c_id, filename,comment, path, post_id,size,blog_id,comment_id)
584
                                VALUES ($course_id, '$file_name', '$comment', '$new_file_name', $post_id, $size, $blog_id, $last_id)";
585
                            Database::query($sql);
586
587
                            $id = Database::insert_id();
588
589
                            if ($id) {
590
                                $sql = "UPDATE $blog_table_attachment SET id = iid WHERE iid = $id";
591
                                Database::query($sql);
592
                            }
593
                        }
594
                    }
595
                }
596
            }
597
        }
598
    }
599
600
    /**
601
     * Deletes a comment from a blogpost.
602
     *
603
     * @author Toon Keppens
604
     *
605
     * @param int $blog_id    The internal blog ID
606
     * @param int $post_id    The internal post ID
607
     * @param int $comment_id The internal comment ID
608
     */
609
    public static function deleteComment($blog_id, $post_id, $comment_id)
610
    {
611
        $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
612
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
613
        $blog_id = intval($blog_id);
614
        $post_id = intval($post_id);
615
        $comment_id = intval($comment_id);
616
        $course_id = api_get_course_int_id();
617
618
        self::deleteAllBlogAttachments($blog_id, $post_id, $comment_id);
619
620
        // Delete ratings on this comment
621
        $sql = "DELETE FROM $tbl_blogs_rating
622
                WHERE
623
                    c_id = $course_id AND
624
                    blog_id = $blog_id AND
625
                    item_id = $comment_id AND
626
                    rating_type = 'comment'";
627
        Database::query($sql);
628
629
        // select comments that have the selected comment as their parent
630
        $sql = "SELECT comment_id FROM $tbl_blogs_comments
631
                WHERE c_id = $course_id AND parent_comment_id = $comment_id";
632
        $result = Database::query($sql);
633
634
        // Delete them recursively
635
        while ($comment = Database::fetch_array($result)) {
636
            self::deleteComment($blog_id, $post_id, $comment['comment_id']);
637
        }
638
639
        // Finally, delete the selected comment to
640
        $sql = "DELETE FROM $tbl_blogs_comments
641
                WHERE c_id = $course_id AND comment_id = $comment_id";
642
        Database::query($sql);
643
    }
644
645
    /**
646
     * Creates a new task in a blog.
647
     *
648
     * @author Toon Keppens
649
     *
650
     * @param int    $blog_id
651
     * @param string $title
652
     * @param string $description
653
     * @param string $articleDelete  Set to 'on' to register as 'article_delete' in tasks_permissions
654
     * @param string $articleEdit    Set to 'on' to register as 'article_edit' in tasks_permissions
655
     * @param string $commentsDelete Set to 'on' to register as 'article_comments_delete' in tasks permissions
656
     * @param string $color
657
     */
658
    public static function addTask(
659
        $blog_id,
660
        $title,
661
        $description,
662
        $articleDelete,
663
        $articleEdit,
664
        $commentsDelete,
665
        $color
666
    ) {
667
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
668
        $tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
669
670
        $course_id = api_get_course_int_id();
671
        $blog_id = intval($blog_id);
672
        $title = Database::escape_string($title);
673
        $description = Database::escape_string($description);
674
        $color = Database::escape_string($color);
675
676
        // Create the task
677
        $sql = "INSERT INTO $tbl_blogs_tasks (c_id, blog_id, title, description, color, system_task)
678
                VALUES ($course_id , $blog_id, '$title', '$description', '$color', '0');";
679
        Database::query($sql);
680
681
        $task_id = Database::insert_id();
682
683
        if ($task_id) {
684
            $sql = "UPDATE $tbl_blogs_tasks SET task_id = iid WHERE iid = $task_id";
685
            Database::query($sql);
686
        }
687
688
        $tool = 'BLOG_'.$blog_id;
689
690
        if ('on' == $articleDelete) {
691
            $sql = "INSERT INTO $tbl_tasks_permissions ( c_id,  task_id, tool, action)
692
                    VALUES ($course_id, $task_id, '$tool', 'article_delete')";
693
            Database::query($sql);
694
695
            $id = Database::insert_id();
696
697
            if ($id) {
698
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
699
                Database::query($sql);
700
            }
701
        }
702
703
        if ('on' == $articleEdit) {
704
            $sql = "
705
                INSERT INTO $tbl_tasks_permissions (c_id, task_id, tool, action ) 
706
                VALUES ($course_id, $task_id, '$tool', 'article_edit')";
707
            Database::query($sql);
708
            $id = Database::insert_id();
709
710
            if ($id) {
711
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
712
                Database::query($sql);
713
            }
714
        }
715
716
        if ('on' == $commentsDelete) {
717
            $sql = "
718
                INSERT INTO $tbl_tasks_permissions (c_id, task_id, tool, action )
719
                VALUES ($course_id, $task_id, '$tool', 'article_comments_delete')";
720
            Database::query($sql);
721
            $id = Database::insert_id();
722
723
            if ($id) {
724
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
725
                Database::query($sql);
726
            }
727
        }
728
    }
729
730
    /**
731
     * Edit a task in a blog.
732
     *
733
     * @author Toon Keppens
734
     *
735
     * @param int    $blog_id        The internal blog ID
736
     * @param int    $task_id        The internal task ID
737
     * @param string $title          The task title
738
     * @param string $description    The task description
739
     * @param string $articleDelete  Set to 'on' to register as 'article_delete' in tasks_permissions
740
     * @param string $articleEdit    Set to 'on' to register as 'article_edit' in tasks_permissions
741
     * @param string $commentsDelete Set to 'on' to register as 'article_comments_delete' in tasks permissions
742
     * @param string $color          The color code
743
     */
744
    public static function editTask(
745
        $blog_id,
746
        $task_id,
747
        $title,
748
        $description,
749
        $articleDelete,
750
        $articleEdit,
751
        $commentsDelete,
752
        $color
753
    ) {
754
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
755
        $tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
756
757
        $course_id = api_get_course_int_id();
758
        $blog_id = intval($blog_id);
759
        $task_id = intval($task_id);
760
        $title = Database::escape_string($title);
761
        $description = Database::escape_string($description);
762
        $color = Database::escape_string($color);
763
764
        // Create the task
765
        $sql = "UPDATE $tbl_blogs_tasks SET
766
                    title = '$title',
767
                    description = '$description',
768
                    color = '$color'
769
                WHERE c_id = $course_id AND task_id = task_id LIMIT 1";
770
        Database::query($sql);
771
772
        $tool = 'BLOG_'.$blog_id;
773
        $sql = "DELETE FROM $tbl_tasks_permissions
774
                WHERE c_id = $course_id AND task_id = $task_id";
775
        Database::query($sql);
776
777
        if ('on' == $articleDelete) {
778
            $sql = "INSERT INTO $tbl_tasks_permissions ( c_id, task_id, tool, action)
779
                    VALUES ($course_id, $task_id, '$tool', 'article_delete')";
780
            Database::query($sql);
781
            $id = Database::insert_id();
782
783
            if ($id) {
784
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
785
                Database::query($sql);
786
            }
787
        }
788
789
        if ('on' == $articleEdit) {
790
            $sql = "INSERT INTO $tbl_tasks_permissions (c_id, task_id, tool, action) 
791
                    VALUES ($course_id, $task_id, '$tool', 'article_edit')";
792
            Database::query($sql);
793
            $id = Database::insert_id();
794
795
            if ($id) {
796
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
797
                Database::query($sql);
798
            }
799
        }
800
801
        if ('on' == $commentsDelete) {
802
            $sql = "INSERT INTO $tbl_tasks_permissions (c_id, task_id, tool, action)
803
                    VALUES ($course_id, $task_id, '$tool', 'article_comments_delete')";
804
            Database::query($sql);
805
            $id = Database::insert_id();
806
807
            if ($id) {
808
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
809
                Database::query($sql);
810
            }
811
        }
812
    }
813
814
    /**
815
     * Deletes a task from a blog.
816
     *
817
     * @param int $blog_id
818
     * @param int $task_id
819
     */
820
    public static function deleteTask($blog_id, $task_id)
821
    {
822
        $table = Database::get_course_table(TABLE_BLOGS_TASKS);
823
        $course_id = api_get_course_int_id();
824
        $blog_id = intval($blog_id);
825
        $task_id = intval($task_id);
826
827
        // Delete posts
828
        $sql = "DELETE FROM $table
829
                WHERE c_id = $course_id AND blog_id = $blog_id AND task_id = $task_id";
830
        Database::query($sql);
831
    }
832
833
    /**
834
     * Deletes an assigned task from a blog.
835
     *
836
     * @param int $blog_id
837
     * @param int $task_id
838
     * @param int $user_id
839
     */
840
    public static function deleteAssignedTask($blog_id, $task_id, $user_id)
841
    {
842
        $table = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
843
        $course_id = api_get_course_int_id();
844
        $blog_id = intval($blog_id);
845
        $task_id = intval($task_id);
846
        $user_id = intval($user_id);
847
848
        // Delete posts
849
        $sql = "DELETE FROM $table
850
                WHERE
851
                    c_id = $course_id AND
852
                    blog_id = $blog_id AND
853
                    task_id = $task_id AND
854
                    user_id = $user_id";
855
        Database::query($sql);
856
    }
857
858
    /**
859
     * Get personal task list.
860
     *
861
     * @author Toon Keppens
862
     *
863
     * @return string Returns an unsorted list (<ul></ul>) with the users' tasks
864
     */
865
    public static function getPersonalTasksList()
866
    {
867
        $_user = api_get_user_info();
868
        $html = null;
869
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
870
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
871
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
872
873
        $course_id = api_get_course_int_id();
874
        $blog_id = intval($_GET['blog_id']);
875
876
        if ($_user['user_id']) {
877
            $sql = "SELECT task_rel_user.*, task.title, blog.blog_name
878
                    FROM $tbl_blogs_tasks_rel_user task_rel_user
879
                    INNER JOIN $tbl_blogs_tasks task
880
                    ON task_rel_user.task_id = task.task_id
881
                    INNER JOIN $tbl_blogs blog
882
                    ON task_rel_user.blog_id = blog.blog_id
883
                    AND blog.blog_id = $blog_id
884
                    WHERE
885
                        task.c_id = $course_id AND
886
                        blog.c_id = $course_id AND
887
                        task_rel_user.c_id = $course_id AND
888
                        task_rel_user.user_id = ".$_user['user_id']."
889
                    ORDER BY target_date ASC";
890
891
            $result = Database::query($sql);
892
893
            if (Database::num_rows($result) > 0) {
894
                $html .= '<ul>';
895
                while ($mytask = Database::fetch_array($result)) {
896
                    $html .= '<li>
897
                            <a href="blog.php?action=execute_task&blog_id='.$mytask['blog_id'].'&task_id='.intval($mytask['task_id']).'" title="[Blog: '.stripslashes($mytask['blog_name']).'] '.get_lang('A task for me').'">'.
898
                        stripslashes($mytask['title']).'</a></li>';
899
                }
900
                $html .= '<ul>';
901
            } else {
902
                $html .= get_lang('No tasks');
903
            }
904
        } else {
905
            $html .= get_lang('No tasks');
906
        }
907
908
        return $html;
909
    }
910
911
    /**
912
     * Changes the visibility of a blog.
913
     *
914
     * @author Toon Keppens
915
     *
916
     * @param int $blog_id
917
     */
918
    public static function changeBlogVisibility($blog_id)
919
    {
920
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
921
        $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
922
        $course_id = api_get_course_int_id();
923
924
        // Get blog properties
925
        $sql = "SELECT blog_name, visibility FROM $tbl_blogs
926
                WHERE c_id = $course_id AND blog_id='".(int) $blog_id."'";
927
        $result = Database::query($sql);
928
        $blog = Database::fetch_array($result);
929
        $visibility = $blog['visibility'];
930
        $title = $blog['blog_name'];
931
932
        if (1 == $visibility) {
933
            // Change visibility state, remove from course home.
934
            $sql = "UPDATE $tbl_blogs SET visibility = '0'
935
                    WHERE c_id = $course_id AND blog_id ='".(int) $blog_id."' LIMIT 1";
936
            Database::query($sql);
937
938
            $sql = "DELETE FROM $tbl_tool
939
                    WHERE c_id = $course_id AND name = '".Database::escape_string($title)."' 
940
                    LIMIT 1";
941
            Database::query($sql);
942
        } else {
943
            // Change visibility state, add to course home.
944
            $sql = "UPDATE $tbl_blogs SET visibility = '1'
945
                    WHERE c_id = $course_id AND blog_id ='".(int) $blog_id."' LIMIT 1";
946
            Database::query($sql);
947
948
            $sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, target)
949
                    VALUES ($course_id, '".Database::escape_string($title)."', 'blog/blog.php?blog_id=".(int) $blog_id."', 'blog.gif', '1', '0', 'pastillegris.gif', '0', '_self')";
950
            Database::query($sql);
951
            $id = Database::insert_id();
952
953
            if ($id) {
954
                $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $id";
955
                Database::query($sql);
956
            }
957
        }
958
    }
959
960
    /**
961
     * Display the search results.
962
     *
963
     * @param int    $blog_id
964
     * @param string $query_string
965
     *
966
     * @return string|array
967
     */
968
    public static function getSearchResults($blog_id, $query_string)
969
    {
970
        $query_string_parts = explode(' ', $query_string);
971
        $query_string = [];
972
        foreach ($query_string_parts as $query_part) {
973
            $query_part = Database::escape_string($query_part);
974
            $query_string[] = " full_text LIKE '%".$query_part."%' OR title LIKE '%".$query_part."%' ";
975
        }
976
        $query_string = '('.implode('OR', $query_string).')';
977
978
        // Display the posts
979
        return self::getPosts($blog_id, $query_string);
980
    }
981
982
    /**
983
     * Shows the posts of a blog.
984
     *
985
     * @author Toon Keppens
986
     *
987
     * @param int    $blog_id
988
     * @param string $filter
989
     * @param int    $max_number_of_posts
990
     *
991
     * @return string|array
992
     */
993
    public static function getPosts($blog_id, $filter = '1=1', $max_number_of_posts = 20)
994
    {
995
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
996
        $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
997
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
998
999
        $course_id = api_get_course_int_id();
1000
        $blog_id = intval($blog_id);
1001
        $max_number_of_posts = intval($max_number_of_posts);
1002
        // Get posts and authors
1003
        $sql = "SELECT post.*, user.lastname, user.firstname, user.username
1004
                FROM $tbl_blogs_posts post
1005
                INNER JOIN $tbl_users user
1006
                ON post.author_id = user.user_id
1007
                WHERE 	
1008
                    post.blog_id = $blog_id AND
1009
                    post.c_id = $course_id AND
1010
                    $filter
1011
                ORDER BY post_id DESC 
1012
                LIMIT 0, $max_number_of_posts";
1013
        $result = Database::query($sql);
1014
1015
        // Display
1016
        if (Database::num_rows($result) > 0) {
1017
            $limit = 200;
1018
            $listArticle = [];
1019
            while ($blog_post = Database::fetch_array($result)) {
1020
                // Get number of comments
1021
                $sql = "SELECT COUNT(1) as number_of_comments
1022
                        FROM $tbl_blogs_comments
1023
                        WHERE
1024
                            c_id = $course_id AND
1025
                            blog_id = $blog_id AND
1026
                            post_id = ".$blog_post['post_id'];
1027
                $tmp = Database::query($sql);
1028
                $blog_post_comments = Database::fetch_array($tmp);
1029
1030
                $fileArray = self::getBlogAttachments($blog_id, $blog_post['post_id'], 0);
1031
                $scoreRanking = self::displayRating(
1032
                    'post',
1033
                    $blog_id,
1034
                    $blog_post['post_id']
1035
                );
1036
1037
                // Prepare data
1038
                $article = [
1039
                    'id_blog' => $blog_post['blog_id'],
1040
                    'c_id' => $blog_post['c_id'],
1041
                    'id_post' => $blog_post['post_id'],
1042
                    'id_autor' => $blog_post['author_id'],
1043
                    'autor' => $blog_post['firstname'].' '.$blog_post['lastname'],
1044
                    'username' => $blog_post['username'],
1045
                    'title' => stripslashes($blog_post['title']),
1046
                    'extract' => self::getPostExtract($blog_post['full_text'], BLOG_MAX_PREVIEW_CHARS),
1047
                    'content' => stripslashes($blog_post['full_text']),
1048
                    'post_date' => Display::dateToStringAgoAndLongDate($blog_post['date_creation']),
1049
                    'n_comments' => $blog_post_comments['number_of_comments'],
1050
                    'files' => $fileArray,
1051
                    'score_ranking' => $scoreRanking,
1052
                ];
1053
1054
                $listArticle[] = $article;
1055
            }
1056
1057
            return $listArticle;
1058
        } else {
1059
            if ('1=1' == $filter) {
1060
                return get_lang('There are no tasks in this project. If you are the manager of this project, click on  link New task to write an task.');
1061
            } else {
1062
                return get_lang('No tasks have been found. Check the word spelling or try another search.');
1063
            }
1064
        }
1065
    }
1066
1067
    /**
1068
     * Display posts from a certain date.
1069
     *
1070
     * @param int    $blog_id
1071
     * @param string $query_string
1072
     *
1073
     * @return string|array
1074
     */
1075
    public static function getDailyResults($blog_id, $query_string)
1076
    {
1077
        $date = explode('-', $query_string);
1078
        $query_string = ' 
1079
            DAYOFMONTH(date_creation) ='.intval($date[2]).' AND 
1080
            MONTH(date_creation) ='.intval($date[1]).' AND 
1081
            YEAR(date_creation) ='.intval($date[0]);
1082
        $list = self::getPosts($blog_id, $query_string);
1083
1084
        return $list;
1085
    }
1086
1087
    /**
1088
     * Displays a post and his comments.
1089
     *
1090
     * @param int $blog_id
1091
     * @param int $post_id
1092
     *
1093
     * @return array
1094
     */
1095
    public static function getSinglePost($blog_id, $post_id)
1096
    {
1097
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
1098
        $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
1099
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1100
        $listComments = null;
1101
        global $charset;
1102
1103
        $course_id = api_get_course_int_id();
1104
        $blog_id = intval($blog_id);
1105
        $post_id = intval($post_id);
1106
1107
        // Get posts and author
1108
        $sql = "SELECT post.*, user.lastname, user.firstname, user.username
1109
                FROM $tbl_blogs_posts post
1110
                    INNER JOIN $tbl_users user
1111
                    ON post.author_id = user.user_id
1112
                WHERE
1113
                    post.c_id = $course_id AND
1114
                    post.blog_id = $blog_id AND
1115
                    post.post_id = $post_id
1116
                ORDER BY post_id DESC";
1117
        $result = Database::query($sql);
1118
        $blog_post = Database::fetch_array($result);
1119
1120
        // Get number of comments
1121
        $sql = "SELECT COUNT(1) as number_of_comments
1122
                FROM $tbl_blogs_comments
1123
                WHERE c_id = $course_id AND blog_id = $blog_id AND post_id = $post_id";
1124
        $result = Database::query($sql);
1125
        $blog_post_comments = Database::fetch_array($result);
1126
        $blogActions = null;
1127
1128
        $task_id = (isset($_GET['task_id']) && is_numeric($_GET['task_id'])) ? intval($_GET['task_id']) : 0;
1129
1130
        // Display comments if there are any
1131
        if ($blog_post_comments['number_of_comments'] > 0) {
1132
            $listComments = self::getThreadedComments(0, 0, $blog_id, $post_id, $task_id);
1133
        }
1134
        // Display comment form
1135
        if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_add')) {
1136
            $formComments = self::displayCommentCreateForm($blog_id, $post_id, $blog_post['title'], false);
1137
        }
1138
        // Prepare data
1139
        $fileArray = self::getBlogAttachments($blog_id, $post_id);
1140
1141
        $post_text = make_clickable(stripslashes($blog_post['full_text']));
1142
        $post_text = stripslashes($post_text);
1143
1144
        if (api_is_allowed('BLOG_'.$blog_id, 'article_edit', $task_id)) {
1145
            $blogActions .= '<a class="btn btn-default" href="blog.php?action=edit_post&blog_id='.$blog_id.'&post_id='.$post_id.'&article_id='.$blog_post['post_id'].'&task_id='.$task_id.'" title="'.get_lang('Edit this task').'">';
1146
            $blogActions .= Display::return_icon('edit.png', get_lang('Edit'), null, ICON_SIZE_TINY);
1147
            $blogActions .= '</a>';
1148
        }
1149
1150
        if (api_is_allowed('BLOG_'.$blog_id, 'article_delete', $task_id)) {
1151
            $blogActions .= '<a class="btn btn-default" href="blog.php?action=view_post&blog_id='.$blog_id.'&post_id='.$post_id.'&do=delete_article&article_id='.$blog_post['post_id'].'&task_id='.$task_id.'" title="'.get_lang(
1152
                    'DeleteThisArticle'
1153
                ).'" onclick="javascript:if(!confirm(\''.addslashes(
1154
                    api_htmlentities(get_lang("Please confirm your choice"), ENT_QUOTES, $charset)
1155
                ).'\')) return false;">';
1156
            $blogActions .= Display::return_icon(
1157
                'delete.png',
1158
                get_lang('Delete'),
1159
                null,
1160
                ICON_SIZE_TINY
1161
            );
1162
            $blogActions .= '</a>';
1163
        }
1164
        $scoreRanking = self::displayRating('post', $blog_id, $post_id);
1165
        $article = [
1166
            'id_blog' => $blog_post['blog_id'],
1167
            'c_id' => $blog_post['c_id'],
1168
            'id_post' => $blog_post['post_id'],
1169
            'id_author' => $blog_post['author_id'],
1170
            'author' => $blog_post['firstname'].' '.$blog_post['lastname'],
1171
            'username' => $blog_post['username'],
1172
            'title' => stripslashes($blog_post['title']),
1173
            'extract' => api_get_short_text_from_html(
1174
                stripslashes($blog_post['full_text']),
1175
                400
1176
            ),
1177
            'content' => $post_text,
1178
            'post_date' => Display::dateToStringAgoAndLongDate($blog_post['date_creation']),
1179
            'n_comments' => $blog_post_comments['number_of_comments'],
1180
            'files' => $fileArray,
1181
            'id_task' => $task_id,
1182
            'comments' => $listComments,
1183
            'form_html' => $formComments,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $formComments does not seem to be defined for all execution paths leading up to this point.
Loading history...
1184
            'actions' => $blogActions,
1185
            'score_ranking' => (int) $scoreRanking,
1186
            'frm_rating' => api_is_allowed('BLOG_'.$blog_id, 'article_rate')
1187
                ? self::displayRatingCreateForm('post', $blog_id, $post_id)
1188
                : null,
1189
        ];
1190
1191
        return $article;
1192
    }
1193
1194
    /**
1195
     * This functions gets all replies to a post, threaded.
1196
     *
1197
     * @param int $current
1198
     * @param int $current_level
1199
     * @param int $blog_id
1200
     * @param int $post_id
1201
     * @param int $task_id
1202
     *
1203
     * @return array
1204
     */
1205
    public static function getThreadedComments(
1206
        $current = 0,
1207
        $current_level = 0,
1208
        $blog_id,
1209
        $post_id,
1210
        $task_id = 0
1211
    ) {
1212
        $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
1213
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1214
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1215
        $charset = api_get_system_encoding();
1216
1217
        $course_id = api_get_course_int_id();
1218
        $blog_id = intval($blog_id);
1219
        $post_id = intval($post_id);
1220
        $task_id = intval($task_id);
1221
1222
        $listComments = [];
1223
        // Select top level comments
1224
        $next_level = $current_level + 1;
1225
        $sql = "SELECT comments.*, user.lastname, user.firstname, user.username, task.color
1226
                FROM $tbl_blogs_comments comments
1227
                INNER JOIN $tbl_users user
1228
                ON comments.author_id = user.user_id
1229
                LEFT JOIN $tbl_blogs_tasks task
1230
                ON comments.task_id = task.task_id AND task.c_id = $course_id
1231
                WHERE
1232
                    comments.c_id = $course_id AND
1233
                    parent_comment_id = $current AND
1234
                    comments.blog_id = $blog_id AND
1235
                    comments.post_id = $post_id";
1236
1237
        $result = Database::query($sql);
1238
        $html = null;
1239
        while ($comment = Database::fetch_array($result)) {
1240
            $commentActions = null;
1241
            $ratingSelect = null;
1242
            $comment_text = make_clickable(stripslashes($comment['comment']));
1243
            $comment_text = stripslashes($comment_text);
1244
1245
            $commentActions .= Display::toolbarButton(
1246
                get_lang('Reply to this comment'),
1247
                '#',
1248
                'reply',
1249
                'default',
1250
                ['data-id' => $comment['iid'], 'role' => 'button', 'class' => 'btn-reply-to'],
1251
                false
1252
            );
1253
1254
            if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_delete', $task_id)) {
1255
                $commentActions .= ' <a class="btn btn-default" href="blog.php?action=view_post&blog_id='.$blog_id.'&post_id='.$post_id.'&do=delete_comment&comment_id='.$comment['comment_id'].'&task_id='.$task_id.'" title="'.get_lang(
1256
                        'DeleteThisComment'
1257
                    ).'" onclick="javascript:if(!confirm(\''.addslashes(
1258
                        api_htmlentities(get_lang("Please confirm your choice"), ENT_QUOTES, $charset)
1259
                    ).'\')) return false;">';
1260
                $commentActions .= Display::returnFontAwesomeIcon('trash');
1261
                $commentActions .= '</a>';
1262
            }
1263
            if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_rate')) {
1264
                $ratingSelect = self::displayRatingCreateForm(
1265
                    'comment',
1266
                    $blog_id,
1267
                    $post_id,
1268
                    $comment['comment_id']
1269
                );
1270
            }
1271
1272
            $scoreRanking = self::displayRating(
1273
                'comment',
1274
                $blog_id,
1275
                $comment['comment_id']
1276
            );
1277
1278
            // Files
1279
            $fileArray = self::getBlogAttachments(
1280
                $blog_id,
1281
                $post_id,
1282
                $comment['comment_id']
1283
            );
1284
            $userInfo = api_get_user_info($comment['author_id']);
1285
            $comments = [
1286
                'iid' => $comment['iid'],
1287
                'id_comment' => $comment['comment_id'],
1288
                'id_curso' => $comment['c_id'],
1289
                'title' => $comment['title'],
1290
                'content' => $comment_text,
1291
                'id_author' => $comment['author_id'],
1292
                'comment_date' => Display::dateToStringAgoAndLongDate($comment['date_creation']),
1293
                'id_blog' => $comment['blog_id'],
1294
                'id_post' => $comment['post_id'],
1295
                'id_task' => $comment['task_id'],
1296
                'id_parent' => $comment['parent_comment_id'],
1297
                'user_info' => $userInfo,
1298
                'color' => $comment['color'],
1299
                'files' => $fileArray,
1300
                'actions' => $commentActions,
1301
                'form_ranking' => $ratingSelect,
1302
                'score_ranking' => $scoreRanking,
1303
                'comments' => self::getThreadedComments(
1304
                    $comment['iid'],
1305
                    $next_level,
1306
                    $blog_id,
1307
                    $post_id
1308
                ),
1309
            ];
1310
1311
            $listComments[] = $comments;
1312
        }
1313
1314
        return $listComments;
1315
    }
1316
1317
    /**
1318
     * Shows the rating form if not already rated by that user.
1319
     *
1320
     * @author Toon Keppens
1321
     *
1322
     * @param string $type
1323
     * @param int    $blog_id
1324
     * @param int    $post_id
1325
     * @param int    $comment_id
1326
     *
1327
     * @return string
1328
     */
1329
    public static function displayRatingCreateForm($type, $blog_id, $post_id, $comment_id = null)
1330
    {
1331
        $_user = api_get_user_info();
1332
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
1333
        $course_id = api_get_course_int_id();
1334
        $blog_id = intval($blog_id);
1335
        $post_id = intval($post_id);
1336
        $comment_id = isset($comment_id) ? intval($comment_id) : null;
1337
        $type = Database::escape_string($type);
1338
        $html = null;
1339
1340
        if ('post' == $type) {
1341
            // Check if the user has already rated this post
1342
            $sql = "SELECT rating_id FROM $tbl_blogs_rating
1343
                    WHERE c_id = $course_id AND
1344
                    blog_id = $blog_id
1345
                    AND item_id = $post_id
1346
                    AND rating_type = '$type'
1347
                    AND user_id = ".$_user['user_id'];
1348
            $result = Database::query($sql);
1349
            // Add rating
1350
            if (0 == Database::num_rows($result)) {
1351
                $html .= '<form class="form-horizontal" method="get" action="blog.php" id="frm_rating_'.$type.'_'.$post_id.'" name="frm_rating_'.$type.'_'.$post_id.'">';
1352
                $html .= '<div class="form-group">';
1353
                $html .= '<label class="col-sm-3 control-label">'.get_lang('Rate this task').'</label>';
1354
                $html .= '<div class="col-sm-9">';
1355
                $html .= '<select class="selectpicker" name="rating" onchange="document.forms[\'frm_rating_'.$type.'_'.$post_id.'\'].submit()"><option value="">-</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option></select><input type="hidden" name="action" value="view_post" /><input type="hidden" name="type" value="'.$type.'" /><input type="hidden" name="do" value="rate" /><input type="hidden" name="blog_id" value="'.$blog_id.'" /><input type="hidden" name="post_id" value="'.$post_id.'" />';
1356
                $html .= '</div>';
1357
                $html .= '</div>';
1358
                $html .= '</form>';
1359
1360
                return $html;
1361
            } else {
1362
                return '';
1363
            }
1364
        }
1365
1366
        if ($type = 'comment') {
1367
            // Check if the user has already rated this comment
1368
            $sql = "SELECT rating_id FROM $tbl_blogs_rating
1369
                    WHERE c_id = $course_id AND blog_id = $blog_id
1370
                    AND item_id = $comment_id
1371
                    AND rating_type = '$type'
1372
                    AND user_id = ".$_user['user_id'];
1373
            $result = Database::query($sql);
1374
            if (0 == Database::num_rows($result)) {
1375
                $html .= '<form class="form-horizontal" method="get" action="blog.php" id="frm_rating_'.$type.'_'.$comment_id.'" name="frm_rating_'.$type.'_'.$comment_id.'">';
1376
                $html .= '<div class="form-group">';
1377
                $html .= '<label class="col-sm-3 control-label">'.get_lang('Rate this task').'</label>';
1378
                $html .= '<div class="col-sm-9">';
1379
                $html .= '<select  class="selectpicker" name="rating" onchange="document.forms[\'frm_rating_'.$type.'_'.$comment_id.'\'].submit()">';
1380
                $html .= '<option value="">-</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option>
1381
                         </select>
1382
                         <input type="hidden" name="action" value="view_post" />
1383
                        <input type="hidden" name="type" value="'.$type.'" />
1384
                        <input type="hidden" name="do" value="rate" />
1385
                        <input type="hidden" name="blog_id" value="'.$blog_id.'" />
1386
                        <input type="hidden" name="post_id" value="'.$post_id.'" />
1387
                        <input type="hidden" name="comment_id" value="'.$comment_id.'" />';
1388
                $html .= '</div>';
1389
                $html .= '</div>';
1390
                $html .= '</form>';
1391
1392
                return $html;
1393
            } else {
1394
                return '';
1395
            }
1396
        }
1397
    }
1398
1399
    /**
1400
     * Shows the rating of user.
1401
     *
1402
     * @param string $type
1403
     * @param int    $blog_id
1404
     * @param int    $item_id
1405
     *
1406
     * @return float
1407
     */
1408
    public static function displayRating($type, $blog_id, $item_id)
1409
    {
1410
        $table = Database::get_course_table(TABLE_BLOGS_RATING);
1411
        $course_id = api_get_course_int_id();
1412
        $blog_id = intval($blog_id);
1413
        $item_id = intval($item_id);
1414
        $type = Database::escape_string($type);
1415
1416
        // Calculate rating
1417
        $sql = "SELECT AVG(rating) as rating FROM $table
1418
                WHERE
1419
                    c_id = $course_id AND
1420
                    blog_id = $blog_id AND
1421
                    item_id = $item_id AND
1422
                    rating_type = '$type'";
1423
        $result = Database::query($sql);
1424
        $result = Database::fetch_array($result);
1425
1426
        return round($result['rating'], 2);
1427
    }
1428
1429
    /**
1430
     * Displays the form to create a new post.
1431
     *
1432
     * @author Toon Keppens
1433
     *
1434
     * @param int $blog_id
1435
     * @param int $post_id
1436
     *
1437
     * @return string HTML form
1438
     */
1439
    public static function displayCommentCreateForm($blog_id, $post_id)
1440
    {
1441
        $taskId = !empty($_GET['task_id']) ? intval($_GET['task_id']) : 0;
1442
        $blog_id = intval($blog_id);
1443
        $post_id = intval($post_id);
1444
1445
        $form = new FormValidator(
1446
            'add_post',
1447
            'post',
1448
            api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
1449
                'action' => 'view_post',
1450
                'blog_id' => $blog_id,
1451
                'post_id' => $post_id,
1452
                'task_id' => $taskId,
1453
            ]),
1454
            null,
1455
            ['enctype' => 'multipart/form-data']
1456
        );
1457
1458
        $header = $taskId ? get_lang('A task for me') : get_lang('Add a new comment');
1459
        $form->addHeader($header);
1460
        $form->addText('title', get_lang('Title'));
1461
1462
        $config = [];
1463
        if (!api_is_allowed_to_edit()) {
1464
            $config['ToolbarSet'] = 'ProjectComment';
1465
        } else {
1466
            $config['ToolbarSet'] = 'ProjectCommentStudent';
1467
        }
1468
        $form->addHtmlEditor(
1469
            'comment',
1470
            get_lang('Comment'),
1471
            false,
1472
            false,
1473
            $config
1474
        );
1475
        $form->addFile('user_upload', get_lang('Add attachment'));
1476
        $form->addTextarea('post_file_comment', get_lang('File comment'));
1477
        $form->addHidden('action', null);
1478
        $form->addHidden('comment_parent_id', 0);
1479
        $form->addHidden('task_id', $taskId);
1480
        $form->addButton('save', get_lang('Save'));
1481
1482
        if ($form->validate()) {
1483
            $values = $form->exportValues();
1484
1485
            self::createComment(
1486
                $values['title'],
1487
                $values['comment'],
1488
                $values['post_file_comment'],
1489
                $blog_id,
1490
                $post_id,
1491
                $values['comment_parent_id'],
1492
                $taskId
1493
            );
1494
1495
            Display::addFlash(
1496
                Display::return_message(get_lang('You comment has been added'), 'success')
1497
            );
1498
1499
            header(
1500
                'Location: '
1501
                .api_get_self()
1502
                .'?'
1503
                .api_get_cidreq()
1504
                .'&'
1505
                .http_build_query([
1506
                    'blog_id' => $blog_id,
1507
                    'post_id' => $post_id,
1508
                    'action' => 'view_post',
1509
                    'task_id' => $taskId,
1510
                ])
1511
            );
1512
            exit;
1513
        }
1514
1515
        return $form->returnForm();
1516
    }
1517
1518
    /**
1519
     * Adds rating to a certain post or comment.
1520
     *
1521
     * @author Toon Keppens
1522
     *
1523
     * @param string $type
1524
     * @param int    $blog_id
1525
     * @param int    $item_id
1526
     * @param int    $rating
1527
     *
1528
     * @return bool success
1529
     */
1530
    public static function addRating($type, $blog_id, $item_id, $rating)
1531
    {
1532
        $_user = api_get_user_info();
1533
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
1534
        $course_id = api_get_course_int_id();
1535
        $blog_id = intval($blog_id);
1536
        $item_id = intval($item_id);
1537
        $type = Database::escape_string($type);
1538
        $rating = Database::escape_string($rating);
1539
1540
        // Check if the user has already rated this post/comment
1541
        $sql = "SELECT rating_id FROM $tbl_blogs_rating
1542
                WHERE
1543
                    c_id = $course_id AND
1544
                    blog_id = $blog_id AND
1545
                    item_id = $item_id AND
1546
                    rating_type = '$type' AND
1547
                    user_id = ".$_user['user_id'];
1548
        $result = Database::query($sql);
1549
1550
        // Add rating
1551
        if (0 == Database::num_rows($result)) {
1552
            $sql = "INSERT INTO $tbl_blogs_rating (c_id, blog_id, rating_type, item_id, user_id, rating )
1553
                    VALUES ($course_id, $blog_id, '$type', $item_id, ".$_user['user_id'].", '$rating')";
1554
            Database::query($sql);
1555
1556
            $id = Database::insert_id();
1557
            if ($id) {
1558
                $sql = "UPDATE $tbl_blogs_rating SET rating_id = iid WHERE iid = $id";
1559
                Database::query($sql);
1560
            }
1561
1562
            return true;
1563
        } else {
1564
            return false;
1565
        }
1566
    }
1567
1568
    /**
1569
     * Displays the form to create a new post.
1570
     *
1571
     * @author Toon Keppens
1572
     *
1573
     * @param int $blog_id
1574
     *
1575
     * @return string
1576
     */
1577
    public static function displayPostCreateForm($blog_id)
1578
    {
1579
        $blog_id = intval($blog_id);
1580
        if (!api_is_allowed('BLOG_'.$blog_id, 'article_add')) {
1581
            api_not_allowed();
1582
        }
1583
1584
        $form = new FormValidator(
1585
            'add_post',
1586
            'post',
1587
            api_get_path(WEB_CODE_PATH)."blog/blog.php?action=new_post&blog_id=".$blog_id."&".api_get_cidreq(),
1588
            null,
1589
            ['enctype' => 'multipart/form-data']
1590
        );
1591
        $form->addHidden('post_title_edited', 'false');
1592
        $form->addHeader(get_lang('New task'));
1593
        $form->addText('title', get_lang('Title'));
1594
        $config = [];
1595
        $config['ToolbarSet'] = !api_is_allowed_to_edit() ? 'ProjectStudent' : 'Project';
1596
        $form->addHtmlEditor('full_text', get_lang('Content'), false, false, $config);
1597
        $form->addFile('user_upload', get_lang('Add attachment'));
1598
        $form->addTextarea('post_file_comment', get_lang('File comment'));
1599
        $form->addHidden('new_post_submit', 'true');
1600
        $form->addButton('save', get_lang('Save'));
1601
1602
        if ($form->validate()) {
1603
            $values = $form->exportValues();
1604
1605
            $postId = self::createPost(
1606
                $values['title'],
1607
                $values['full_text'],
1608
                $values['post_file_comment'],
1609
                $blog_id
1610
            );
1611
1612
            if ($postId) {
1613
                Display::addFlash(
1614
                    Display::return_message(get_lang('The article has been added.'), 'success')
1615
                );
1616
1617
                header('Location: '.api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
1618
                    'action' => 'view_post',
1619
                    'blog_id' => $blog_id,
1620
                    'post_id' => $postId,
1621
                ]));
1622
                exit;
1623
            }
1624
        }
1625
1626
        return $form->returnForm();
1627
    }
1628
1629
    /**
1630
     * Displays the form to edit a post.
1631
     *
1632
     * @author Toon Keppens
1633
     *
1634
     * @param int $blog_id
1635
     * @param int $post_id
1636
     *
1637
     * @return string
1638
     */
1639
    public static function displayPostEditForm($blog_id, $post_id)
1640
    {
1641
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
1642
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1643
1644
        $course_id = api_get_course_int_id();
1645
        $blog_id = intval($blog_id);
1646
        $post_id = intval($post_id);
1647
1648
        // Get posts and author
1649
        $sql = "SELECT post.*, user.lastname, user.firstname
1650
                FROM $tbl_blogs_posts post
1651
                INNER JOIN $tbl_users user ON post.author_id = user.user_id
1652
                WHERE
1653
                post.c_id 			= $course_id AND
1654
                post.blog_id 		= $blog_id
1655
                AND post.post_id	= $post_id
1656
                ORDER BY post_id DESC";
1657
        $result = Database::query($sql);
1658
        $blog_post = Database::fetch_array($result);
1659
1660
        // Form
1661
        $form = new FormValidator(
1662
            'edit_post',
1663
            'post',
1664
            api_get_path(WEB_CODE_PATH).'blog/blog.php?action=edit_post&post_id='.intval($_GET['post_id']).'&blog_id='.intval($blog_id).'&article_id='.intval($_GET['article_id']).'&task_id='.intval($_GET['task_id'])
1665
        );
1666
1667
        $form->addHeader(get_lang('Edit a post'));
1668
        $form->addText('title', get_lang('Title'));
1669
1670
        if (!api_is_allowed_to_edit()) {
1671
            $config['ToolbarSet'] = 'ProjectStudent';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$config was never initialized. Although not strictly required by PHP, it is generally a good practice to add $config = array(); before regardless.
Loading history...
1672
        } else {
1673
            $config['ToolbarSet'] = 'Project';
1674
        }
1675
        $form->addHtmlEditor('full_text', get_lang('Content'), false, false, $config);
1676
1677
        $form->addHidden('action', '');
1678
        $form->addHidden('edit_post_submit', 'true');
1679
        $form->addHidden('post_id', intval($_GET['post_id']));
1680
        $form->addButton('save', get_lang('Save'));
1681
        $form->setDefaults($blog_post);
1682
1683
        return $form->returnForm();
1684
    }
1685
1686
    /**
1687
     * Displays a list of tasks in this blog.
1688
     *
1689
     * @author Toon Keppens
1690
     *
1691
     * @param int $blog_id
1692
     *
1693
     * @return string
1694
     */
1695
    public static function displayTasksList($blog_id)
1696
    {
1697
        global $charset;
1698
        $course_id = api_get_course_int_id();
1699
        $blog_id = intval($blog_id);
1700
        $html = '';
1701
        if (api_is_allowed('BLOG_'.$blog_id, 'article_add')) {
1702
            $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1703
            $counter = 0;
1704
            global $color2;
1705
1706
            $html .= '<div class="actions">';
1707
            $html .= '<a href="'.api_get_self().'?action=manage_tasks&blog_id='.$blog_id.'&do=add&'.api_get_cidreq().'">';
1708
            $html .= Display::return_icon('blog_newtasks.gif', get_lang('Add a new role'));
1709
            $html .= get_lang('Add a new role').'</a> ';
1710
            $html .= '<a href="'.api_get_self().'?action=manage_tasks&blog_id='.$blog_id.'&do=assign&'.api_get_cidreq().'">';
1711
            $html .= Display::return_icon('blog_task.gif', get_lang('Assign roles'));
1712
            $html .= get_lang('Assign roles').'</a>';
1713
            $html .= Display::url(
1714
                Display::return_icon('blog_admin_users.png', get_lang('Users rights management')),
1715
                api_get_self().'?'.http_build_query([
1716
                    'action' => 'manage_rights',
1717
                    'blog_id' => $blog_id,
1718
                ]),
1719
                ['title' => get_lang('Manage roles and rights of user in this project')]
1720
            );
1721
1722
            $html .= '</div>';
1723
1724
            $html .= '<span class="blogpost_title">'.get_lang('Roles in this project').'</span><br />';
1725
            $html .= "<table class=\"data_table\">";
1726
            $html .= "<tr bgcolor=\"$color2\" align=\"center\" valign=\"top\">"
1727
                ."<th width='240'><b>".get_lang('Title')."</b></th>"
1728
                ."<th><b>".get_lang('Description')."</b></th>"
1729
                ."<th><b>".get_lang('Colour')."</b></th>"
1730
                ."<th width='50'><b>".get_lang('Edit')."</b></th></tr>";
1731
1732
            $sql = " SELECT
1733
                        blog_id,
1734
                        task_id,
1735
                        blog_id,
1736
                        title,
1737
                        description,
1738
                        color,
1739
                        system_task
1740
                    FROM $tbl_blogs_tasks
1741
                    WHERE c_id = $course_id AND blog_id = $blog_id
1742
                    ORDER BY system_task, title";
1743
            $result = Database::query($sql);
1744
1745
            while ($task = Database::fetch_array($result)) {
1746
                $counter++;
1747
                $css_class = (0 == ($counter % 2)) ? "row_odd" : "row_even";
1748
                $delete_icon = '1' == $task['system_task'] ? "delete_na.png" : "delete.png";
1749
                $delete_title = '1' == $task['system_task'] ? get_lang('This is a preset task. You can\'t delete a preset task.') : get_lang('Delete this task');
1750
                $delete_link = '1' == $task['system_task'] ? '#' : api_get_self().'?action=manage_tasks&blog_id='.$task['blog_id'].'&do=delete&task_id='.$task['task_id'].'&'.api_get_cidreq();
1751
                $delete_confirm = ('1' == $task['system_task']) ? '' : 'onclick="javascript:if(!confirm(\''.addslashes(
1752
                        api_htmlentities(get_lang("Please confirm your choice"), ENT_QUOTES, $charset)
1753
                    ).'\')) return false;"';
1754
1755
                $html .= '<tr class="'.$css_class.'" valign="top">';
1756
                $html .= '<td width="240">'.Security::remove_XSS($task['title']).'</td>';
1757
                $html .= '<td>'.Security::remove_XSS($task['description']).'</td>';
1758
                $html .= '<td><span style="background-color: #'.$task['color'].'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></td>';
1759
                $html .= '<td width="50">';
1760
                $html .= '<a href="'.api_get_self().'?action=manage_tasks&blog_id='.$task['blog_id'].'&do=edit&task_id='.$task['task_id'].'&'.api_get_cidreq().'">';
1761
                $html .= Display::return_icon('edit.png', get_lang('Edit this task'));
1762
                $html .= "</a>";
1763
                $html .= '<a href="'.$delete_link.'"';
1764
                $html .= $delete_confirm;
1765
                $html .= '>';
1766
                $html .= Display::return_icon($delete_icon, $delete_title);
1767
                $html .= "</a>";
1768
                $html .= '</td>';
1769
                $html .= '</tr>';
1770
            }
1771
            $html .= "</table>";
1772
        }
1773
1774
        return $html;
1775
    }
1776
1777
    /**
1778
     * Displays a list of tasks assigned to a user in this blog.
1779
     *
1780
     * @author Toon Keppens
1781
     *
1782
     * @param int $blog_id
1783
     *
1784
     * @return string
1785
     */
1786
    public static function displayAssignedTasksList($blog_id)
1787
    {
1788
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1789
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1790
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
1791
        $counter = 0;
1792
        global $charset, $color2;
1793
1794
        $return = '<span class="blogpost_title">'.get_lang('Assigned tasks').'</span><br />';
1795
        $return .= "<table class=\"data_table\">";
1796
        $return .= "<tr bgcolor=\"$color2\" align=\"center\" valign=\"top\">"
1797
            ."<th width='240'><b>".get_lang('Member')."</b></th>"
1798
            ."<th><b>".get_lang('Task')."</b></th>"
1799
            ."<th><b>".get_lang('Description')."</b></th>"
1800
            ."<th><b>".get_lang('Date')."</b></th>"
1801
            ."<th width='50'><b>".get_lang('Edit')."</b></th>"
1802
            ."</tr>";
1803
1804
        $course_id = api_get_course_int_id();
1805
        $blog_id = intval($blog_id);
1806
1807
        $sql = "SELECT task_rel_user.*, task.title, user.firstname, user.lastname, user.username, task.description, task.system_task, task.blog_id, task.task_id
1808
                FROM $tbl_blogs_tasks_rel_user task_rel_user
1809
                INNER JOIN $tbl_blogs_tasks task
1810
                ON task_rel_user.task_id = task.task_id
1811
                INNER JOIN $tbl_users user
1812
                ON task_rel_user.user_id = user.user_id
1813
                WHERE
1814
                    task_rel_user.c_id = $course_id AND
1815
                    task.c_id = $course_id AND
1816
                    task_rel_user.blog_id = $blog_id
1817
                ORDER BY target_date ASC";
1818
        $result = Database::query($sql);
1819
1820
        while ($assignment = Database::fetch_array($result)) {
1821
            $counter++;
1822
            $css_class = (0 == ($counter % 2)) ? "row_odd" : "row_even";
1823
            $delete_icon = ('1' == $assignment['system_task']) ? "delete_na.png" : "delete.png";
1824
            $delete_title = ('1' == $assignment['system_task']) ? get_lang('This is a preset task. You can\'t delete a preset task.') : get_lang('Delete this task');
1825
            $delete_link = ('1' == $assignment['system_task']) ? '#' : api_get_self().'?action=manage_tasks&blog_id='.$assignment['blog_id'].'&do=delete&task_id='.$assignment['task_id'].'&'.api_get_cidreq();
1826
            $delete_confirm = ('1' == $assignment['system_task']) ? '' : 'onclick="javascript:if(!confirm(\''.addslashes(
1827
                    api_htmlentities(get_lang("Please confirm your choice"), ENT_QUOTES, $charset)
1828
                ).'\')) return false;"';
1829
1830
            $username = api_htmlentities(sprintf(get_lang('Login: %s'), $assignment['username']), ENT_QUOTES);
1831
1832
            $return .= '<tr class="'.$css_class.'" valign="top">';
1833
            $return .= '<td width="240">'.Display::tag(
1834
                'span',
1835
                api_get_person_name($assignment['firstname'], $assignment['lastname']),
1836
                ['title' => $username]
1837
            ).'</td>';
1838
            $return .= '<td>'.stripslashes($assignment['title']).'</td>';
1839
            $return .= '<td>'.stripslashes($assignment['description']).'</td>';
1840
            $return .= '<td>'.$assignment['target_date'].'</td>';
1841
            $return .= '<td width="50">';
1842
            $return .= '<a href="'.api_get_self().'?action=manage_tasks&blog_id='.$assignment['blog_id'].'&do=edit_assignment&task_id='.$assignment['task_id'].'&user_id='.$assignment['user_id'].'&'.api_get_cidreq().'">';
1843
            $return .= Display::return_icon('edit.png', get_lang('Edit this task'));
1844
            $return .= "</a>";
1845
            $return .= '<a href="'.api_get_self().'?action=manage_tasks&blog_id='.$assignment['blog_id'].'&do=delete_assignment&task_id='.$assignment['task_id'].'&user_id='.$assignment['user_id'].'&'.api_get_cidreq().'" ';
1846
            $return .= 'onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("Please confirm your choice"), ENT_QUOTES, $charset)).'\')) return false;"';
1847
            $return .= Display::return_icon($delete_icon, $delete_title);
1848
            $return .= "</a>";
1849
            $return .= '</td>';
1850
            $return .= '</tr>';
1851
        }
1852
        $return .= "</table>";
1853
1854
        return $return;
1855
    }
1856
1857
    /**
1858
     * Displays new task form.
1859
     *
1860
     * @todo use FormValidator
1861
     *
1862
     * @author Toon Keppens
1863
     *
1864
     * @param int $blog_id
1865
     *
1866
     * @return string HTML form
1867
     */
1868
    public static function displayTaskCreateForm($blog_id)
1869
    {
1870
        $blog_id = intval($blog_id);
1871
        // Init
1872
        $colors = [
1873
            'FFFFFF',
1874
            'FFFF99',
1875
            'FFCC99',
1876
            'FF9933',
1877
            'FF6699',
1878
            'CCFF99',
1879
            'CC9966',
1880
            '66FF00',
1881
            '9966FF',
1882
            'CF3F3F',
1883
            '990033',
1884
            '669933',
1885
            '0033FF',
1886
            '003366',
1887
            '000000',
1888
        ];
1889
1890
        // form
1891
        $return = '<form name="add_task" method="post" action="blog.php?action=manage_tasks&blog_id='.$blog_id.'">';
1892
1893
        // form title
1894
        $return .= '<legend>'.get_lang('Add a new role').'</legend>';
1895
1896
        // task title
1897
        $return .= '	<div class="control-group">
1898
                    <label class="control-label">
1899
                        <span class="form_required">*</span>'.get_lang('Title').'
1900
                    </label>
1901
                    <div class="controls">
1902
                        <input name="task_name" type="text" size="70" />
1903
                    </div>
1904
                </div>';
1905
1906
        // task comment
1907
        $return .= '	<div class="control-group">
1908
                    <label class="control-label">
1909
                        '.get_lang('Description').'
1910
                    </label>
1911
                    <div class="controls">
1912
                        <textarea name="task_description" cols="45"></textarea>
1913
                    </div>
1914
                </div>';
1915
1916
        // task management
1917
        $return .= '	<div class="control-group">
1918
                    <label class="control-label">
1919
                        '.get_lang('Roles management').'
1920
                    </label>
1921
                    <div class="controls">';
1922
        $return .= '<table class="data_table" cellspacing="0" style="border-collapse:collapse; width:446px;">';
1923
        $return .= '<tr>';
1924
        $return .= '<th colspan="2" style="width:223px;">'.get_lang('Tasks manager').'</th>';
1925
        $return .= '<th width:223px;>'.get_lang('Comment manager').'</th>';
1926
        $return .= '</tr>';
1927
        $return .= '<tr>';
1928
        $return .= '<th style="width:111px;"><label for="articleDelete">'.get_lang('Delete').'</label></th>';
1929
        $return .= '<th style="width:112px;"><label for="articleEdit">'.get_lang('Edit').'</label></th>';
1930
        $return .= '<th style="width:223px;"><label for="commentsDelete">'.get_lang('Delete').'</label></th>';
1931
        $return .= '</tr>';
1932
        $return .= '<tr>';
1933
        $return .= '<td style="text-align:center;"><input id="articleDelete" name="chkArticleDelete" type="checkbox" /></td>';
1934
        $return .= '<td style="text-align:center;"><input id="articleEdit" name="chkArticleEdit" type="checkbox" /></td>';
1935
        $return .= '<td style="border:1px dotted #808080; text-align:center;"><input id="commentsDelete" name="chkCommentsDelete" type="checkbox" /></td>';
1936
        $return .= '</tr>';
1937
        $return .= '</table>';
1938
        $return .= '		</div>
1939
                </div>';
1940
1941
        // task color
1942
        $return .= '	<div class="control-group">
1943
                    <label class="control-label">
1944
                        '.get_lang('Colour').'
1945
                    </label>
1946
                    <div class="controls">';
1947
        $return .= '<select name="task_color" id="color" style="width: 150px; background-color: #eeeeee" onchange="document.getElementById(\'color\').style.backgroundColour=\'#\'+document.getElementById(\'color\').value" onkeypress="document.getElementById(\'color\').style.backgroundColour=\'#\'+document.getElementById(\'color\').value">';
1948
        foreach ($colors as $color) {
1949
            $style = 'style="background-color: #'.$color.'"';
1950
            $return .= '<option value="'.$color.'" '.$style.'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
1951
        }
1952
        $return .= '</select>';
1953
        $return .= '		</div>
1954
                </div>';
1955
1956
        // submit
1957
        $return .= '	<div class="control-group">
1958
                    <div class="controls">
1959
                            <input type="hidden" name="action" value="" />
1960
                            <input type="hidden" name="new_task_submit" value="true" />
1961
                        <button class="save" type="submit" name="Submit">'.get_lang('Save').'</button>
1962
                    </div>
1963
                </div>';
1964
        $return .= '</form>';
1965
1966
        $return .= '<div style="clear:both; margin-bottom: 10px;"></div>';
1967
1968
        return $return;
1969
    }
1970
1971
    /**
1972
     * Displays edit task form.
1973
     *
1974
     * @author Toon Keppens
1975
     *
1976
     * @param int $blog_id
1977
     * @param int $task_id
1978
     *
1979
     * @return string
1980
     */
1981
    public static function displayTaskEditForm($blog_id, $task_id)
1982
    {
1983
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1984
        $course_id = api_get_course_int_id();
1985
        $blog_id = intval($blog_id);
1986
        $task_id = intval($task_id);
1987
1988
        $colors = [
1989
            'FFFFFF',
1990
            'FFFF99',
1991
            'FFCC99',
1992
            'FF9933',
1993
            'FF6699',
1994
            'CCFF99',
1995
            'CC9966',
1996
            '66FF00',
1997
            '9966FF',
1998
            'CF3F3F',
1999
            '990033',
2000
            '669933',
2001
            '0033FF',
2002
            '003366',
2003
            '000000',
2004
        ];
2005
2006
        $sql = "SELECT blog_id, task_id, title, description, color FROM $tbl_blogs_tasks 
2007
                WHERE c_id = $course_id AND task_id = $task_id";
2008
        $result = Database::query($sql);
2009
        $task = Database::fetch_array($result);
2010
2011
        // Display
2012
        $return = '<form name="edit_task" method="post" action="blog.php?action=manage_tasks&blog_id='.$blog_id.'">
2013
                    <legend>'.get_lang('Edit this task').'</legend>
2014
                    <table width="100%" border="0" cellspacing="2">
2015
                        <tr>
2016
                       <td align="right">'.get_lang('Title').':&nbsp;&nbsp;</td>
2017
                       <td><input name="task_name" type="text" size="70" value="'.Security::remove_XSS($task['title']).'" /></td>
2018
                        </tr>
2019
                        <tr>
2020
                       <td align="right">'.get_lang('Description').':&nbsp;&nbsp;</td>
2021
                       <td><textarea name="task_description" cols="45">'.Security::remove_XSS($task['description']).'</textarea></td>
2022
                        </tr>';
2023
2024
        /* edit by Kevin Van Den Haute ([email protected]) */
2025
        $tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
2026
2027
        $sql = "SELECT id, action FROM $tbl_tasks_permissions
2028
                WHERE c_id = $course_id AND task_id = $task_id";
2029
        $result = Database::query($sql);
2030
2031
        $arrPermissions = [];
2032
2033
        while ($row = Database::fetch_array($result)) {
2034
            $arrPermissions[] = $row['action'];
2035
        }
2036
2037
        $return .= '<tr>';
2038
        $return .= '<td style="text-align:right; vertical-align:top;">'.get_lang('Roles management').':&nbsp;&nbsp;</td>';
2039
        $return .= '<td>';
2040
        $return .= '<table  class="data_table" cellspacing="0" style="border-collapse:collapse; width:446px;">';
2041
        $return .= '<tr>';
2042
        $return .= '<th colspan="2" style="width:223px;">'.get_lang('Tasks manager').'</th>';
2043
        $return .= '<th width:223px;>'.get_lang('Comment manager').'</th>';
2044
        $return .= '</tr>';
2045
        $return .= '<tr>';
2046
        $return .= '<th style="width:111px;"><label for="articleDelete">'.get_lang('Delete').'</label></th>';
2047
        $return .= '<th style="width:112px;"><label for="articleEdit">'.get_lang('Edit').'</label></th>';
2048
        $return .= '<th style="width:223px;"><label for="commentsDelete">'.get_lang('Delete').'</label></th>';
2049
        $return .= '</tr>';
2050
        $return .= '<tr>';
2051
        $return .= '<td style="text-align:center;"><input '.((in_array(
2052
                'article_delete',
2053
                $arrPermissions
2054
            )) ? 'checked ' : '').'id="articleDelete" name="chkArticleDelete" type="checkbox" /></td>';
2055
        $return .= '<td style="text-align:center;"><input '.((in_array(
2056
                'article_edit',
2057
                $arrPermissions
2058
            )) ? 'checked ' : '').'id="articleEdit" name="chkArticleEdit" type="checkbox" /></td>';
2059
        $return .= '<td style="text-align:center;"><input '.((in_array(
2060
                'article_comments_delete',
2061
                $arrPermissions
2062
            )) ? 'checked ' : '').'id="commentsDelete" name="chkCommentsDelete" type="checkbox" /></td>';
2063
        $return .= '</tr>';
2064
        $return .= '</table>';
2065
        $return .= '</td>';
2066
        $return .= '</tr>';
2067
        /* end of edit */
2068
2069
        $return .= '<tr>
2070
                       <td align="right">'.get_lang('Colour').':&nbsp;&nbsp;</td>
2071
                       <td>
2072
                        <select name="task_color" id="color" style="width: 150px; background-color: #'.$task['color'].'" onchange="document.getElementById(\'color\').style.backgroundColour=\'#\'+document.getElementById(\'color\').value" onkeypress="document.getElementById(\'color\').style.backgroundColour=\'#\'+document.getElementById(\'color\').value">';
2073
        foreach ($colors as $color) {
2074
            $selected = ($color == $task['color']) ? ' selected' : '';
2075
            $style = 'style="background-color: #'.$color.'"';
2076
            $return .= '<option value="'.$color.'" '.$style.' '.$selected.' >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
2077
        }
2078
        $return .= '</select>
2079
                          </td>
2080
                        </tr>
2081
                        <tr>
2082
                            <td align="right">&nbsp;</td>
2083
                            <td><br /><input type="hidden" name="action" value="" />
2084
                            <input type="hidden" name="edit_task_submit" value="true" />
2085
                            <input type="hidden" name="task_id" value="'.$task['task_id'].'" />
2086
                            <input type="hidden" name="blog_id" value="'.$task['blog_id'].'" />
2087
                            <button class="save" type="submit" name="Submit">'.get_lang('Save').'</button></td>
2088
                        </tr>
2089
                    </table>
2090
                </form>';
2091
2092
        return $return;
2093
    }
2094
2095
    /**
2096
     * Displays assign task form.
2097
     *
2098
     * @author Toon Keppens
2099
     */
2100
    public static function displayTaskAssignmentForm($blog_id)
2101
    {
2102
        $form = self::getTaskAssignmentForm($blog_id);
2103
        $form->addHidden('assign_task_submit', 'true');
2104
2105
        return $form->returnForm()
2106
            .PHP_EOL
2107
            .'<div style="clear: both; margin-bottom:10px;"></div>';
2108
    }
2109
2110
    /**
2111
     * Returns an HTML form to assign a task.
2112
     *
2113
     * @param $blog_id
2114
     *
2115
     * @return FormValidator
2116
     */
2117
    public static function getTaskAssignmentForm($blog_id)
2118
    {
2119
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2120
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
2121
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
2122
        $course_id = api_get_course_int_id();
2123
        $blog_id = intval($blog_id);
2124
2125
        // Get users in this blog / make select list of it
2126
        $sql = "SELECT user.user_id, user.firstname, user.lastname, user.username
2127
                FROM $tbl_users user
2128
                INNER JOIN $tbl_blogs_rel_user blogs_rel_user
2129
                ON user.user_id = blogs_rel_user.user_id
2130
                WHERE blogs_rel_user.c_id = $course_id AND blogs_rel_user.blog_id = $blog_id";
2131
        $result = Database::query($sql);
2132
2133
        $options = [];
2134
        while ($user = Database::fetch_array($result)) {
2135
            $options[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']);
2136
        }
2137
2138
        // Get tasks in this blog / make select list of it
2139
        $sql = "SELECT
2140
                    blog_id,
2141
                    task_id,
2142
                    blog_id,
2143
                    title,
2144
                    description,
2145
                    color,
2146
                    system_task
2147
                FROM $tbl_blogs_tasks
2148
                WHERE c_id = $course_id AND blog_id = $blog_id
2149
                ORDER BY system_task, title";
2150
        $result = Database::query($sql);
2151
2152
        $taskOptions = [];
2153
        while ($task = Database::fetch_array($result)) {
2154
            $taskOptions[$task['task_id']] = stripslashes($task['title']);
2155
        }
2156
2157
        $form = new FormValidator(
2158
            'assign_task',
2159
            'post',
2160
            api_get_path(
2161
                WEB_CODE_PATH
2162
            ).'blog/blog.php?action=manage_tasks&blog_id='.$blog_id
2163
        );
2164
2165
        $form->addHeader(get_lang('Assign a role'));
2166
        $form->addSelect('task_user_id', get_lang('User'), $options);
2167
        $form->addSelect('task_task_id', get_lang('Task'), $taskOptions);
2168
        $form->addDatePicker('task_day', get_lang('SelectDate'));
2169
2170
        $form->addHidden('action', '');
2171
        $form->addButtonSave(get_lang('Validate'));
2172
2173
        return $form;
2174
    }
2175
2176
    /**
2177
     * Displays assign task form.
2178
     *
2179
     * @author Toon Keppens
2180
     *
2181
     * @param int $blog_id
2182
     * @param int $task_id
2183
     * @param int $user_id
2184
     *
2185
     * @return string HTML form
2186
     */
2187
    public static function displayAssignedTaskEditForm($blog_id, $task_id, $user_id)
2188
    {
2189
        $table = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2190
2191
        $course_id = api_get_course_int_id();
2192
        $blog_id = intval($blog_id);
2193
        $task_id = intval($task_id);
2194
        $user_id = intval($user_id);
2195
2196
        // Get assign date;
2197
        $sql = "
2198
            SELECT target_date
2199
            FROM $table
2200
            WHERE c_id = $course_id AND
2201
                  blog_id = $blog_id AND
2202
                  user_id = $user_id AND
2203
                  task_id = $task_id";
2204
        $result = Database::query($sql);
2205
        $row = Database::fetch_assoc($result);
2206
2207
        $date = $row['target_date'];
2208
2209
        $defaults = [
2210
            'task_user_id' => $user_id,
2211
            'task_task_id' => $task_id,
2212
            'task_day' => $date,
2213
        ];
2214
        $form = self::getTaskAssignmentForm($blog_id);
2215
        $form->addHidden('old_task_id', $task_id);
2216
        $form->addHidden('old_user_id', $user_id);
2217
        $form->addHidden('old_target_date', $date);
2218
        $form->addHidden('assign_task_edit_submit', 'true');
2219
        $form->setDefaults($defaults);
2220
2221
        return $form->returnForm();
2222
    }
2223
2224
    /**
2225
     * Assigns a task to a user in a blog.
2226
     *
2227
     * @param int    $blog_id
2228
     * @param int    $user_id
2229
     * @param int    $task_id
2230
     * @param string $target_date date
2231
     */
2232
    public static function assignTask($blog_id, $user_id, $task_id, $target_date)
2233
    {
2234
        $table = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2235
        $course_id = api_get_course_int_id();
2236
        $blog_id = intval($blog_id);
2237
        $user_id = intval($user_id);
2238
        $task_id = intval($task_id);
2239
        $target_date = Database::escape_string($target_date);
2240
2241
        $sql = "
2242
            SELECT COUNT(*) as 'number'
2243
            FROM $table
2244
            WHERE c_id = $course_id 
2245
            AND blog_id = $blog_id 
2246
            AND	user_id = $user_id 
2247
            AND	task_id = $task_id";
2248
2249
        $result = Database::query($sql);
2250
        $row = Database::fetch_assoc($result);
2251
2252
        if (0 == $row['number']) {
2253
            $sql = "
2254
                INSERT INTO ".$table." (
2255
                    c_id,
2256
                    blog_id,
2257
                    user_id,
2258
                    task_id,
2259
                    target_date
2260
                ) VALUES (
2261
                    $course_id,
2262
                    $blog_id,
2263
                    $user_id,
2264
                    $task_id,
2265
                    '$target_date'
2266
                )";
2267
2268
            Database::query($sql);
2269
        }
2270
    }
2271
2272
    /**
2273
     * Edit an assigned task.
2274
     *
2275
     * @param $blog_id
2276
     * @param $user_id
2277
     * @param $task_id
2278
     * @param $target_date
2279
     * @param $old_user_id
2280
     * @param $old_task_id
2281
     * @param $old_target_date
2282
     */
2283
    public static function updateAssignedTask(
2284
        $blog_id,
2285
        $user_id,
2286
        $task_id,
2287
        $target_date,
2288
        $old_user_id,
2289
        $old_task_id,
2290
        $old_target_date
2291
    ) {
2292
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2293
2294
        $course_id = api_get_course_int_id();
2295
        $blog_id = intval($blog_id);
2296
        $user_id = intval($user_id);
2297
        $task_id = intval($task_id);
2298
        $target_date = Database::escape_string($target_date);
2299
        $old_user_id = intval($old_user_id);
2300
        $old_task_id = intval($old_task_id);
2301
        $old_target_date = Database::escape_string($old_target_date);
2302
2303
        $sql = "SELECT COUNT(*) as 'number'
2304
                FROM $tbl_blogs_tasks_rel_user
2305
                WHERE
2306
                    c_id = $course_id AND
2307
                    blog_id = $blog_id AND
2308
                    user_id = $user_id AND
2309
                    task_id = $task_id";
2310
2311
        $result = Database::query($sql);
2312
        $row = Database::fetch_assoc($result);
2313
2314
        if (0 == $row['number'] ||
2315
            (0 != $row['number'] && $task_id == $old_task_id && $user_id == $old_user_id)
2316
        ) {
2317
            $sql = "UPDATE $tbl_blogs_tasks_rel_user
2318
                SET
2319
                    user_id = $user_id,
2320
                    task_id = $task_id,
2321
                    target_date = '$target_date'
2322
                WHERE
2323
                    c_id = $course_id AND
2324
                    blog_id = $blog_id AND
2325
                    user_id = $old_user_id AND
2326
                    task_id = $old_task_id AND
2327
                    target_date = '$old_target_date'
2328
            ";
2329
            Database::query($sql);
2330
        }
2331
    }
2332
2333
    /**
2334
     * Displays a list with posts a user can select to execute his task.
2335
     *
2336
     * @param int $blog_id
2337
     * @param int $task_id
2338
     *
2339
     * @return string
2340
     */
2341
    public static function displayPostSelectionForTask($blog_id, $task_id)
2342
    {
2343
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
2344
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
2345
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2346
        $course_id = api_get_course_int_id();
2347
        $blog_id = intval($blog_id);
2348
        $task_id = intval($task_id);
2349
2350
        $sql = "SELECT title, description FROM $tbl_blogs_tasks
2351
                WHERE task_id = $task_id
2352
                AND c_id = $course_id";
2353
        $result = Database::query($sql);
2354
        $row = Database::fetch_assoc($result);
2355
        // Get posts and authors
2356
        $sql = "SELECT post.*, user.lastname, user.firstname, user.username
2357
                FROM $tbl_blogs_posts post
2358
                INNER JOIN $tbl_users user ON post.author_id = user.user_id
2359
                WHERE post.blog_id = $blog_id AND post.c_id = $course_id
2360
                ORDER BY post_id DESC
2361
                LIMIT 0, 100";
2362
        $result = Database::query($sql);
2363
2364
        // Display
2365
        $return = '<span class="blogpost_title">'.get_lang('TaskArticle').' "'.stripslashes($row['title']).'"</span>';
2366
        $return .= '<span style="font-style: italic;"">'.stripslashes($row['description']).'</span><br><br>';
2367
2368
        if (0 == Database::num_rows($result)) {
2369
            $return .= get_lang('There are no tasks in this project. If you are the manager of this project, click on  link New task to write an task.');
2370
2371
            return $return;
2372
        }
2373
2374
        while ($blog_post = Database::fetch_array($result)) {
2375
            $username = api_htmlentities(sprintf(get_lang('Login: %s'), $blog_post['username']), ENT_QUOTES);
2376
            $return .= '<a href="blog.php?action=execute_task&blog_id='.$blog_id.'&task_id='.$task_id.'&post_id='.$blog_post['post_id'].'#add_comment">'.stripslashes(
2377
                    $blog_post['title']
2378
                ).'</a>, '.get_lang('Written by').' '.stripslashes(
2379
                    Display::tag(
2380
                        'span',
2381
                        api_get_person_name($blog_post['firstname'], $blog_post['lastname']),
2382
                        ['title' => $username]
2383
                    )
2384
                ).'<br />';
2385
        }
2386
2387
        return $return;
2388
    }
2389
2390
    /**
2391
     * Unsubscribe a user from a given blog.
2392
     *
2393
     * @author Toon Keppens
2394
     *
2395
     * @param int $blog_id
2396
     * @param int $user_id
2397
     */
2398
    public static function unsubscribeUser($blog_id, $user_id)
2399
    {
2400
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
2401
        $tbl_user_permissions = Database::get_course_table(TABLE_PERMISSION_USER);
2402
        $blog_id = intval($blog_id);
2403
        $user_id = intval($user_id);
2404
2405
        // Unsubscribe the user
2406
        $sql = "DELETE FROM $tbl_blogs_rel_user
2407
                WHERE blog_id = $blog_id AND user_id = $user_id";
2408
        Database::query($sql);
2409
2410
        // Remove this user's permissions.
2411
        $sql = "DELETE FROM $tbl_user_permissions
2412
                WHERE user_id = $user_id";
2413
        Database::query($sql);
2414
    }
2415
2416
    /**
2417
     * Displays the form to register users in a blog (in a course)
2418
     * The listed users are users subscribed in the course.
2419
     *
2420
     * @author Toon Keppens
2421
     *
2422
     * @param int $blog_id
2423
     *
2424
     * @return string html Form with sortable table with users to subcribe in a blog, in a course
2425
     */
2426
    public static function displayUserSubscriptionForm($blog_id)
2427
    {
2428
        $_course = api_get_course_info();
2429
        $is_western_name_order = api_is_western_name_order();
2430
        $session_id = api_get_session_id();
2431
        $course_id = $_course['real_id'];
2432
        $blog_id = intval($blog_id);
2433
2434
        $currentCourse = $_course['code'];
2435
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2436
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
2437
        $html = null;
2438
2439
        $html .= '<legend>'.get_lang('Subscribe users').'</legend>';
2440
2441
        $properties['width'] = '100%';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$properties was never initialized. Although not strictly required by PHP, it is generally a good practice to add $properties = array(); before regardless.
Loading history...
2442
2443
        // Get blog members' id.
2444
        $sql = "SELECT user.user_id FROM $tbl_users user
2445
                INNER JOIN $tbl_blogs_rel_user blogs_rel_user
2446
                ON user.user_id = blogs_rel_user.user_id
2447
                WHERE blogs_rel_user.c_id = $course_id AND blogs_rel_user.blog_id = $blog_id";
2448
        $result = Database::query($sql);
2449
2450
        $blog_member_ids = [];
2451
        while ($user = Database::fetch_array($result)) {
2452
            $blog_member_ids[] = $user['user_id'];
2453
        }
2454
2455
        // Set table headers
2456
        $column_header[] = ['', false, ''];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$column_header was never initialized. Although not strictly required by PHP, it is generally a good practice to add $column_header = array(); before regardless.
Loading history...
2457
        if ($is_western_name_order) {
2458
            $column_header[] = [get_lang('First name'), true, ''];
2459
            $column_header[] = [get_lang('Last name'), true, ''];
2460
        } else {
2461
            $column_header[] = [get_lang('Last name'), true, ''];
2462
            $column_header[] = [get_lang('First name'), true, ''];
2463
        }
2464
        $column_header[] = [get_lang('e-mail'), false, ''];
2465
        $column_header[] = [get_lang('Register'), false, ''];
2466
2467
        $student_list = CourseManager:: get_student_list_from_course_code(
2468
            $currentCourse,
2469
            false,
2470
            $session_id
2471
        );
2472
        $user_data = [];
2473
2474
        // Add users that are not in this blog to the list.
2475
        foreach ($student_list as $key => $user) {
2476
            if (isset($user['id_user'])) {
2477
                $user['user_id'] = $user['id_user'];
2478
            }
2479
            if (!in_array($user['user_id'], $blog_member_ids)) {
2480
                $a_infosUser = api_get_user_info($user['user_id']);
2481
                $row = [];
2482
                $row[] = '<input type="checkbox" name="user[]" value="'.$a_infosUser['user_id'].'" '.((isset($_GET['selectall']) && "subscribe" == $_GET['selectall']) ? ' checked="checked" ' : '').'/>';
2483
                $username = api_htmlentities(sprintf(get_lang('Login: %s'), $a_infosUser["username"]), ENT_QUOTES);
2484
                if ($is_western_name_order) {
2485
                    $row[] = $a_infosUser["firstname"];
2486
                    $row[] = Display::tag(
2487
                        'span',
2488
                        $a_infosUser["lastname"],
2489
                        ['title' => $username]
2490
                    );
2491
                } else {
2492
                    $row[] = Display::tag(
2493
                        'span',
2494
                        $a_infosUser["lastname"],
2495
                        ['title' => $username]
2496
                    );
2497
                    $row[] = $a_infosUser["firstname"];
2498
                }
2499
                $row[] = Display::icon_mailto_link($a_infosUser['email']);
2500
2501
                // Link to register users
2502
                if ($a_infosUser['user_id'] != api_get_user_id()) {
2503
                    $row[] = Display::url(
2504
                        get_lang('Register'),
2505
                        api_get_self()."?action=manage_members&blog_id=$blog_id&register=yes&user_id=".$a_infosUser["user_id"].'&'.api_get_cidreq(),
2506
                        ['class' => 'btn btn-primary']
2507
                    );
2508
                } else {
2509
                    $row[] = '';
2510
                }
2511
                $user_data[] = $row;
2512
            }
2513
        }
2514
2515
        // Display
2516
        $query_vars['action'] = 'manage_members';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$query_vars was never initialized. Although not strictly required by PHP, it is generally a good practice to add $query_vars = array(); before regardless.
Loading history...
2517
        $query_vars['blog_id'] = $blog_id;
2518
        $html .= '<form class="form-inline" method="post" action="blog.php?action=manage_members&blog_id='.$blog_id.'&'.api_get_cidreq().'">';
2519
        $html .= Display::return_sortable_table($column_header, $user_data, null, null, $query_vars);
2520
2521
        $link = isset($_GET['action']) ? 'action='.Security::remove_XSS($_GET['action']).'&' : '';
2522
        $link .= "blog_id=$blog_id&".api_get_cidreq();
2523
2524
        $html .= '<a class="btn btn-default" href="blog.php?'.$link.'selectall=subscribe">'.get_lang('Select all').'</a> - ';
2525
        $html .= '<a class="btn btn-default" href="blog.php?'.$link.'">'.get_lang('UnSelect all').'</a> ';
2526
        $html .= '<div class="form-group">';
2527
        $html .= '<label>';
2528
        $html .= get_lang('With selected').' : ';
2529
        $html .= '</label>';
2530
        $html .= '<select class="selectpicker" name="action">';
2531
        $html .= '<option value="select_subscribe">'.get_lang('Register').'</option>';
2532
        $html .= '</select>';
2533
        $html .= '<input type="hidden" name="register" value="true" />';
2534
        $html .= '<button class="btn btn-default" type="submit">'.get_lang('Validate').'</button>';
2535
        $html .= '</div>';
2536
        $html .= '</form>';
2537
2538
        return $html;
2539
    }
2540
2541
    /**
2542
     * Displays the form to register users in a blog (in a course)
2543
     * The listed users are users subcribed in the course.
2544
     *
2545
     * @author Toon Keppens
2546
     *
2547
     * @param int $blog_id
2548
     *
2549
     * @return false|null form with sortable table with users to unsubcribe from a blog
2550
     */
2551
    public static function displayUserUnsubscriptionForm($blog_id)
2552
    {
2553
        $_user = api_get_user_info();
2554
        $is_western_name_order = api_is_western_name_order();
2555
        $html = null;
2556
2557
        // Init
2558
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2559
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
2560
        $blog_id = intval($blog_id);
2561
2562
        $html .= '<legend>'.get_lang('Unsubscribe users').'</legend>';
2563
2564
        $properties["width"] = "100%";
0 ignored issues
show
Comprehensibility Best Practice introduced by
$properties was never initialized. Although not strictly required by PHP, it is generally a good practice to add $properties = array(); before regardless.
Loading history...
2565
        //table column titles
2566
        $column_header[] = ['', false, ''];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$column_header was never initialized. Although not strictly required by PHP, it is generally a good practice to add $column_header = array(); before regardless.
Loading history...
2567
        if ($is_western_name_order) {
2568
            $column_header[] = [get_lang('First name'), true, ''];
2569
            $column_header[] = [get_lang('Last name'), true, ''];
2570
        } else {
2571
            $column_header[] = [get_lang('Last name'), true, ''];
2572
            $column_header[] = [get_lang('First name'), true, ''];
2573
        }
2574
        $column_header[] = [get_lang('e-mail'), false, ''];
2575
        $column_header[] = [get_lang('Roles management'), true, ''];
2576
        $column_header[] = [get_lang('Unregister'), false, ''];
2577
2578
        $course_id = api_get_course_int_id();
2579
2580
        $sql = "SELECT user.user_id, user.lastname, user.firstname, user.email, user.username
2581
                FROM $tbl_users user 
2582
                INNER JOIN $tbl_blogs_rel_user blogs_rel_user
2583
                ON user.user_id = blogs_rel_user.user_id
2584
                WHERE blogs_rel_user.c_id = $course_id AND  blogs_rel_user.blog_id = $blog_id";
2585
2586
        if (!($sql_result = Database::query($sql))) {
2587
            return false;
2588
        }
2589
2590
        $user_data = [];
2591
        while ($myrow = Database::fetch_array($sql_result)) {
2592
            $row = [];
2593
            $row[] = '<input type="checkbox" name="user[]" value="'.$myrow['user_id'].'" '.((isset($_GET['selectall']) && "unsubscribe" == $_GET['selectall']) ? ' checked="checked" ' : '').'/>';
2594
            $username = api_htmlentities(sprintf(get_lang('Login: %s'), $myrow["username"]), ENT_QUOTES);
2595
            if ($is_western_name_order) {
2596
                $row[] = $myrow["firstname"];
2597
                $row[] = Display::tag(
2598
                    'span',
2599
                    $myrow["lastname"],
2600
                    ['title' => $username]
2601
                );
2602
            } else {
2603
                $row[] = Display::tag(
2604
                    'span',
2605
                    $myrow["lastname"],
2606
                    ['title' => $username]
2607
                );
2608
                $row[] = $myrow["firstname"];
2609
            }
2610
            $row[] = Display::icon_mailto_link($myrow["email"]);
2611
2612
            $sql = "SELECT bt.title task
2613
                    FROM ".Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER)." btu
2614
                    INNER JOIN ".Database::get_course_table(TABLE_BLOGS_TASKS)." bt
2615
                    ON btu.task_id = bt.task_id
2616
                    WHERE 	btu.c_id 	= $course_id  AND
2617
                            bt.c_id 	= $course_id  AND
2618
                            btu.blog_id = $blog_id AND
2619
                            btu.user_id = ".$myrow['user_id'];
2620
            $sql_res = Database::query($sql);
2621
2622
            $task = '';
2623
2624
            while ($r = Database::fetch_array($sql_res)) {
2625
                $task .= stripslashes($r['task']).', ';
2626
            }
2627
            //echo $task;
2628
            $task = (0 != api_strlen(trim($task))) ? api_substr($task, 0, api_strlen($task) - 2) : get_lang('Reader');
2629
            $row[] = $task;
2630
            //Link to register users
2631
2632
            if ($myrow["user_id"] != $_user['user_id']) {
2633
                $row[] = Display::url(
2634
                    get_lang('Unregister'),
2635
                    api_get_self()."?action=manage_members&blog_id=$blog_id&unregister=yes&user_id=".$myrow['user_id'].'&'.api_get_cidreq(),
2636
                    ['class' => 'btn btn-primary']
2637
                );
2638
            } else {
2639
                $row[] = '';
2640
            }
2641
            $user_data[] = $row;
2642
        }
2643
2644
        $query_vars['action'] = 'manage_members';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$query_vars was never initialized. Although not strictly required by PHP, it is generally a good practice to add $query_vars = array(); before regardless.
Loading history...
2645
        $query_vars['blog_id'] = $blog_id;
2646
        $html .= '<form class="form-inline" method="post" action="blog.php?action=manage_members&blog_id='.$blog_id.'&'.api_get_cidreq().'">';
2647
        $html .= Display::return_sortable_table($column_header, $user_data, null, null, $query_vars);
2648
2649
        $link = isset($_GET['action']) ? 'action='.Security::remove_XSS($_GET['action']).'&' : '';
2650
        $link .= "blog_id=$blog_id&".api_get_cidreq();
2651
2652
        $html .= '<a class="btn btn-default" href="blog.php?'.$link.'selectall=unsubscribe">'.get_lang('Select all').'</a> - ';
2653
        $html .= '<a class="btn btn-default" href="blog.php?'.$link.'">'.get_lang('UnSelect all').'</a> ';
2654
        $html .= '<div class="form-group">';
2655
        $html .= '<label>';
2656
        $html .= get_lang('With selected').' : ';
2657
        $html .= '</label>';
2658
        $html .= '<select name="action" class="selectpicker">';
2659
        $html .= '<option value="select_unsubscribe">'.get_lang('Unregister').'</option>';
2660
        $html .= '</select>';
2661
        $html .= '<input type="hidden" name="unregister" value="true" />';
2662
        $html .= '<button class="btn btn-default" type="submit">'.get_lang('Validate').'</button>';
2663
        $html .= '</div>';
2664
        $html .= '</form>';
2665
2666
        return $html;
2667
    }
2668
2669
    /**
2670
     * Displays a matrix with selectboxes. On the left: users, on top: possible rights.
2671
     * The blog admin can thus select what a certain user can do in the current blog.
2672
     *
2673
     * @param int $blog_id
2674
     *
2675
     * @return string
2676
     */
2677
    public static function displayUserRightsForm($blog_id)
2678
    {
2679
        ob_start();
2680
        echo '<legend>'.get_lang('Users rights management').'</legend>';
2681
        echo '<br />';
2682
2683
        // Integration of patricks permissions system.
2684
        require_once api_get_path(SYS_CODE_PATH).'permissions/blog_permissions.inc.php';
2685
        $content = ob_get_contents();
2686
        ob_get_clean();
2687
2688
        return $content;
2689
    }
2690
2691
    /**
2692
     * show the calender of the given month.
2693
     *
2694
     * @author Patrick Cool
2695
     * @author Toon Keppens
2696
     *
2697
     * @param int $month   The integer value of the month we are viewing
2698
     * @param int $year    The 4-digit year indication e.g. 2005
2699
     * @param int $blog_id
2700
     *
2701
     * @return string html code
2702
     */
2703
    public static function displayMiniMonthCalendar($month, $year, $blog_id)
2704
    {
2705
        // Init
2706
        $_user = api_get_user_info();
2707
        global $DaysShort;
2708
        global $MonthsLong;
2709
        $html = null;
2710
2711
        $posts = [];
2712
        $tasks = [];
2713
2714
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2715
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
2716
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
2717
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2718
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
2719
2720
        $course_id = api_get_course_int_id();
2721
        $blog_id = intval($blog_id);
2722
        $month = intval($month);
2723
        $year = intval($year);
2724
2725
        //Handle leap year
2726
        $numberofdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
2727
2728
        if ((0 == $year % 400) or (0 == $year % 4 and 0 != $year % 100)) {
2729
            $numberofdays[2] = 29;
2730
        }
2731
2732
        //Get the first day of the month
2733
        $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
2734
        $monthName = $MonthsLong[$month - 1];
2735
2736
        //Start the week on monday
2737
        $startdayofweek = 0 != $dayone['wday'] ? ($dayone['wday'] - 1) : 6;
2738
        $blogId = isset($_GET['blog_id']) ? intval($_GET['blog_id']) : null;
2739
        $filter = isset($_GET['filter']) ? Security::remove_XSS($_GET['filter']) : null;
2740
        $backwardsURL = api_get_self(
2741
            )."?blog_id=".$blogId."&filter=".$filter."&month=".(1 == $month ? 12 : $month - 1)."&year=".(1 == $month ? $year - 1 : $year);
2742
        $forewardsURL = api_get_self(
2743
            )."?blog_id=".$blogId."&filter=".$filter."&month=".(12 == $month ? 1 : $month + 1)."&year=".(12 == $month ? $year + 1 : $year);
2744
2745
        // Get posts for this month
2746
        $sql = "SELECT post.*, DAYOFMONTH(date_creation) as post_day, user.lastname, user.firstname
2747
                FROM $tbl_blogs_posts post
2748
                INNER JOIN $tbl_users user
2749
                ON post.author_id = user.user_id
2750
                WHERE
2751
                    post.c_id = $course_id AND
2752
                    post.blog_id = $blog_id AND
2753
                    MONTH(date_creation) = '$month' AND
2754
                    YEAR(date_creation) = '$year'
2755
                ORDER BY date_creation";
2756
        $result = Database::query($sql);
2757
2758
        // We will create an array of days on which there are posts.
2759
        if (Database::num_rows($result) > 0) {
2760
            while ($blog_post = Database::fetch_array($result)) {
2761
                // If the day of this post is not yet in the array, add it.
2762
                if (!in_array($blog_post['post_day'], $posts)) {
2763
                    $posts[] = $blog_post['post_day'];
2764
                }
2765
            }
2766
        }
2767
2768
        // Get tasks for this month
2769
        if ($_user['user_id']) {
2770
            $sql = "SELECT 
2771
                        task_rel_user.*,  
2772
                        DAYOFMONTH(target_date) as task_day, 
2773
                        task.title, 
2774
                        blog.blog_name
2775
                    FROM $tbl_blogs_tasks_rel_user task_rel_user
2776
                    INNER JOIN $tbl_blogs_tasks task 
2777
                    ON task_rel_user.task_id = task.task_id
2778
                    INNER JOIN $tbl_blogs blog 
2779
                    ON task_rel_user.blog_id = blog.blog_id
2780
                    WHERE
2781
                        task_rel_user.c_id = $course_id AND
2782
                        task.c_id = $course_id AND
2783
                        blog.c_id = $course_id AND
2784
                        task_rel_user.user_id = ".$_user['user_id']." AND
2785
                        MONTH(target_date) = '$month' AND
2786
                        YEAR(target_date) = '$year'
2787
                    ORDER BY target_date ASC";
2788
            $result = Database::query($sql);
2789
2790
            if (Database::num_rows($result) > 0) {
2791
                while ($mytask = Database::fetch_array($result)) {
2792
                    $tasks[$mytask['task_day']][$mytask['task_id']]['task_id'] = $mytask['task_id'];
2793
                    $tasks[$mytask['task_day']][$mytask['task_id']]['title'] = $mytask['title'];
2794
                    $tasks[$mytask['task_day']][$mytask['task_id']]['blog_id'] = $mytask['blog_id'];
2795
                    $tasks[$mytask['task_day']][$mytask['task_id']]['blog_name'] = $mytask['blog_name'];
2796
                    $tasks[$mytask['task_day']][$mytask['task_id']]['day'] = $mytask['task_day'];
2797
                }
2798
            }
2799
        }
2800
2801
        $html .= '<table id="smallcalendar" class="table table-responsive">
2802
                <tr id="title">
2803
                <th width="10%"><a href="'.$backwardsURL.'">&laquo;</a></th>
2804
                <th align="center" width="80%" colspan="5" class="month">'.$monthName.' '.$year.'</th>
2805
                <th width="10%" align="right"><a href="'.$forewardsURL.'">&raquo;</a></th></tr>';
2806
2807
        $html .= '<tr>';
2808
2809
        for ($ii = 1; $ii < 8; $ii++) {
2810
            $html .= '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
2811
        }
2812
2813
        $html .= '</tr>';
2814
2815
        $curday = -1;
2816
        $today = getdate();
2817
2818
        while ($curday <= $numberofdays[$month]) {
2819
            $html .= '<tr>';
2820
            for ($ii = 0; $ii < 7; $ii++) {
2821
                if ((-1 == $curday) && ($ii == $startdayofweek)) {
2822
                    $curday = 1;
2823
                }
2824
2825
                if (($curday > 0) && ($curday <= $numberofdays[$month])) {
2826
                    $bgcolor = $ii < 5 ? $class = "class=\"days_week\"" : $class = "class=\"days_weekend\"";
2827
                    $dayheader = "$curday";
2828
2829
                    if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
2830
                        $dayheader = "$curday";
2831
                        $class = "class=\"days_today\"";
2832
                    }
2833
2834
                    $html .= '<td '.$class.'>';
2835
2836
                    // If there are posts on this day, create a filter link.
2837
                    if (in_array($curday, $posts)) {
2838
                        $html .= '<a href="blog.php?blog_id='.$blog_id.'&filter='.$year.'-'.$month.'-'.$curday.'&month='.$month.'&year='.$year.'" title="'.get_lang(
2839
                                'ViewPostsOfThisDay'
2840
                            ).'">'.$curday.'</a>';
2841
                    } else {
2842
                        $html .= $dayheader;
2843
                    }
2844
2845
                    if (count($tasks) > 0) {
2846
                        if (isset($tasks[$curday]) && is_array($tasks[$curday])) {
2847
                            // Add tasks to calendar
2848
                            foreach ($tasks[$curday] as $task) {
2849
                                $html .= '<a href="blog.php?action=execute_task&blog_id='.$task['blog_id'].'&task_id='.stripslashes($task['task_id']).'" title="'.$task['title'].' : '.get_lang('in the project').' : '.$task['blog_name'].' - '.get_lang('A task for me').'">';
2850
                                $html .= Display::return_icon('blog_task.gif', get_lang('A task for me'));
2851
                                $html .= '</a>';
2852
                            }
2853
                        }
2854
                    }
2855
2856
                    $html .= '</td>';
2857
                    $curday++;
2858
                } else {
2859
                    $html .= '<td>&nbsp;</td>';
2860
                }
2861
            }
2862
            $html .= '</tr>';
2863
        }
2864
        $html .= '</table>';
2865
2866
        return $html;
2867
    }
2868
2869
    /**
2870
     * Blog admin | Display the form to add a new blog.
2871
     */
2872
    public static function displayBlogCreateForm()
2873
    {
2874
        $form = new FormValidator(
2875
            'add_blog',
2876
            'post',
2877
            'blog_admin.php?action=add'
2878
        );
2879
        $form->addElement('header', get_lang('Create a new project'));
2880
        $form->addText('blog_name', get_lang('Title'));
2881
        $form->addHtmlEditor(
2882
            'blog_subtitle',
2883
            get_lang('Sub-title'),
2884
            false,
2885
            false,
2886
            [
2887
                'ToolbarSet' => 'Profile',
2888
                'Width' => '100%',
2889
                'Height' => '130',
2890
            ]
2891
        );
2892
        $form->addElement('hidden', 'new_blog_submit', 'true');
2893
        $form->addButtonSave(get_lang('Save blog'));
2894
2895
        $defaults = [
2896
            'blog_name' => isset($_POST['blog_name']) ? Security::remove_XSS($_POST['blog_name']) : null,
2897
            'blog_subtitle' => isset($_POST['blog_subtitle']) ? Security::remove_XSS($_POST['blog_subtitle']) : null,
2898
        ];
2899
        $form->setDefaults($defaults);
2900
        $form->display();
2901
    }
2902
2903
    /**
2904
     * Blog admin | Display the form to edit a blog.
2905
     *
2906
     * @param int $blog_id
2907
     */
2908
    public static function displayBlogEditForm($blog_id)
2909
    {
2910
        $course_id = api_get_course_int_id();
2911
        $blog_id = intval($blog_id);
2912
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
2913
2914
        $sql = "SELECT blog_id, blog_name, blog_subtitle
2915
                FROM $tbl_blogs
2916
                WHERE c_id = $course_id AND blog_id = $blog_id";
2917
        $result = Database::query($sql);
2918
        $blog = Database::fetch_array($result);
2919
2920
        // the form contained errors but we do not want to lose the changes the user already did
2921
        if ($_POST) {
2922
            $blog['blog_name'] = Security::remove_XSS($_POST['blog_name']);
2923
            $blog['blog_subtitle'] = Security::remove_XSS($_POST['blog_subtitle']);
2924
        }
2925
2926
        $form = new FormValidator(
2927
            'edit_blog',
2928
            'post',
2929
            'blog_admin.php?action=edit&blog_id='.intval($_GET['blog_id'])
2930
        );
2931
        $form->addElement('header', get_lang('Edit a project'));
2932
        $form->addElement('text', 'blog_name', get_lang('Title'));
2933
        $form->addElement('textarea', 'blog_subtitle', get_lang('Sub-title'));
2934
        $form->addElement('hidden', 'edit_blog_submit', 'true');
2935
        $form->addElement('hidden', 'blog_id', $blog['blog_id']);
2936
        $form->addButtonSave(get_lang('Save'));
2937
2938
        $defaults = [];
2939
        $defaults['blog_name'] = $blog['blog_name'];
2940
        $defaults['blog_subtitle'] = $blog['blog_subtitle'];
2941
        $form->setDefaults($defaults);
2942
        $form->display();
2943
    }
2944
2945
    /**
2946
     * Blog admin | Returns table with blogs in this course.
2947
     */
2948
    public static function displayBlogsList()
2949
    {
2950
        global $charset;
2951
        $_user = api_get_user_info();
2952
        $course_id = api_get_course_int_id();
2953
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
2954
2955
        //condition for the session
2956
        $session_id = api_get_session_id();
2957
2958
        $sql = "SELECT blog_name, blog_subtitle, visibility, blog_id, session_id
2959
                FROM $tbl_blogs WHERE c_id = $course_id
2960
                ORDER BY date_creation DESC";
2961
        $result = Database::query($sql);
2962
        $list_info = [];
2963
        if (Database::num_rows($result)) {
2964
            while ($row_project = Database::fetch_row($result)) {
2965
                $list_info[] = $row_project;
2966
            }
2967
        }
2968
2969
        $list_content_blog = [];
2970
        $list_body_blog = [];
2971
2972
        if (is_array($list_info)) {
2973
            foreach ($list_info as $key => $info_log) {
2974
                // Validation when belongs to a session
2975
                $session_img = api_get_session_image($info_log[4], $_user['status']);
2976
2977
                $url_start_blog = 'blog.php'."?"."blog_id=".$info_log[3]."&".api_get_cidreq();
2978
                $title = $info_log[0];
2979
                $image = Display::return_icon('blog.png', $title);
2980
                $list_name = '<div style="float: left; width: 35px; height: 22px;"><a href="'.$url_start_blog.'">'.$image.'</a></div><a href="'.$url_start_blog.'">'.$title.'</a>'.$session_img;
2981
2982
                $list_body_blog[] = $list_name;
2983
                $list_body_blog[] = $info_log[1];
2984
2985
                $visibility_icon = (0 == $info_log[2]) ? 'invisible' : 'visible';
2986
                $visibility_info = (0 == $info_log[2]) ? 'Visible' : 'Invisible';
2987
2988
                $my_image = '<a href="'.api_get_self().'?action=visibility&blog_id='.$info_log[3].'">';
2989
                $my_image .= Display::return_icon($visibility_icon.'.png', get_lang($visibility_info));
2990
                $my_image .= "</a>";
2991
2992
                $my_image .= '<a href="'.api_get_self().'?action=edit&blog_id='.$info_log[3].'">';
2993
                $my_image .= Display::return_icon('edit.png', get_lang('Edit a project'));
2994
                $my_image .= "</a>";
2995
2996
                $my_image .= '<a href="'.api_get_self().'?action=delete&blog_id='.$info_log[3].'" ';
2997
                $my_image .= 'onclick="javascript:if(!confirm(\''.addslashes(
2998
                        api_htmlentities(get_lang("Please confirm your choice"), ENT_QUOTES, $charset)
2999
                    ).'\')) return false;" >';
3000
                $my_image .= Display::return_icon('delete.png', get_lang('Delete this project'));
3001
                $my_image .= "</a>";
3002
3003
                $list_body_blog[] = $my_image;
3004
                $list_content_blog[] = $list_body_blog;
3005
                $list_body_blog = [];
3006
            }
3007
3008
            $table = new SortableTableFromArrayConfig(
3009
                $list_content_blog,
3010
                1,
3011
                20,
3012
                'project'
3013
            );
3014
            $table->set_header(0, get_lang('Title'));
3015
            $table->set_header(1, get_lang('Sub-title'));
3016
            $table->set_header(2, get_lang('Edit'));
3017
            $table->display();
3018
        }
3019
    }
3020
3021
    /**
3022
     * Show a list with all the attachments according the parameter's.
3023
     *
3024
     * @param int $blog_id    the blog's id
3025
     * @param int $post_id    the post's id
3026
     * @param int $comment_id the comment's id
3027
     *
3028
     * @return array with the post info according the parameters
3029
     *
3030
     * @author Julio Montoya
3031
     *
3032
     * @version avril 2008, dokeos 1.8.5
3033
     */
3034
    public static function getBlogAttachments($blog_id, $post_id = 0, $comment_id = 0)
3035
    {
3036
        $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
3037
3038
        $blog_id = intval($blog_id);
3039
        $comment_id = intval($comment_id);
3040
        $post_id = intval($post_id);
3041
        $row = [];
3042
        $where = '';
3043
        if (!empty($post_id) && is_numeric($post_id)) {
3044
            $where .= " AND post_id = $post_id ";
3045
        }
3046
3047
        if (!empty($comment_id) && is_numeric($comment_id)) {
3048
            if (!empty($post_id)) {
3049
                $where .= ' AND ';
3050
            }
3051
            $where .= " comment_id = $comment_id ";
3052
        }
3053
3054
        $course_id = api_get_course_int_id();
3055
3056
        $sql = "SELECT path, filename, comment 
3057
                FROM $blog_table_attachment
3058
	            WHERE c_id = $course_id AND blog_id = $blog_id  
3059
	            $where";
3060
3061
        $result = Database::query($sql);
3062
        if (0 != Database::num_rows($result)) {
3063
            $row = Database::fetch_array($result);
3064
        }
3065
3066
        return $row;
3067
    }
3068
3069
    /**
3070
     * Delete the all the attachments according the parameters.
3071
     *
3072
     * @param int $blog_id
3073
     * @param int $post_id    post's id
3074
     * @param int $comment_id the comment's id
3075
     *
3076
     * @author Julio Montoya
3077
     *
3078
     * @version avril 2008, dokeos 1.8.5
3079
     */
3080
    public static function deleteAllBlogAttachments(
3081
        $blog_id,
3082
        $post_id = 0,
3083
        $comment_id = 0
3084
    ) {
3085
        $_course = api_get_course_info();
3086
        $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
3087
        $blog_id = intval($blog_id);
3088
        $comment_id = intval($comment_id);
3089
        $post_id = intval($post_id);
3090
3091
        $course_id = api_get_course_int_id();
3092
        $where = null;
3093
3094
        // delete files in DB
3095
        if (!empty($post_id) && is_numeric($post_id)) {
3096
            $where .= " AND post_id = $post_id ";
3097
        }
3098
3099
        if (!empty($comment_id) && is_numeric($comment_id)) {
3100
            if (!empty($post_id)) {
3101
                $where .= ' AND ';
3102
            }
3103
            $where .= " comment_id = $comment_id ";
3104
        }
3105
3106
        // delete all files in directory
3107
        $courseDir = $_course['path'].'/upload/blog';
3108
        $sys_course_path = api_get_path(SYS_COURSE_PATH);
0 ignored issues
show
Bug introduced by
The constant SYS_COURSE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
3109
        $updir = $sys_course_path.$courseDir;
3110
3111
        $sql = "SELECT path FROM $blog_table_attachment
3112
	        WHERE c_id = $course_id AND blog_id = $blog_id $where";
3113
        $result = Database::query($sql);
3114
3115
        while ($row = Database::fetch_row($result)) {
3116
            $file = $updir.'/'.$row[0];
3117
            if (Security::check_abs_path($file, $updir)) {
3118
                @unlink($file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

3118
                /** @scrutinizer ignore-unhandled */ @unlink($file);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
3119
            }
3120
        }
3121
        $sql = "DELETE FROM $blog_table_attachment
3122
	        WHERE c_id = $course_id AND  blog_id = $blog_id $where";
3123
        Database::query($sql);
3124
    }
3125
3126
    /**
3127
     * Gets all the post from a given user id.
3128
     *
3129
     * @param int    $courseId
3130
     * @param int    $userId
3131
     * @param string $courseCode
3132
     *
3133
     * @return string
3134
     */
3135
    public static function getBlogPostFromUser($courseId, $userId, $courseCode)
3136
    {
3137
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
3138
        $tbl_blog_post = Database::get_course_table(TABLE_BLOGS_POSTS);
3139
        $courseId = intval($courseId);
3140
        $userId = intval($userId);
3141
3142
        $sql = "SELECT DISTINCT blog.blog_id, post_id, title, full_text, post.date_creation
3143
                FROM $tbl_blogs blog
3144
                INNER JOIN $tbl_blog_post post
3145
                ON (blog.blog_id = post.blog_id AND blog.c_id = post.c_id)
3146
                WHERE
3147
                    blog.c_id = $courseId AND
3148
                    post.c_id = $courseId AND
3149
                    author_id =  $userId AND 
3150
                    visibility = 1
3151
                ORDER BY post.date_creation DESC ";
3152
        $result = Database::query($sql);
3153
        $return_data = '';
3154
3155
        if (0 != Database::num_rows($result)) {
3156
            while ($row = Database::fetch_array($result)) {
3157
                $return_data .= '<div class="clear"></div><br />';
3158
                $return_data .= '<div class="actions" style="margin-left:5px;margin-right:5px;">'.
3159
                    Display::return_icon(
3160
                        'blog_article.png',
3161
                        get_lang('Blog Posts')
3162
                    ).' '.
3163
                    $row['title'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="float:right;margin-top:-18px"><a href="../blog/blog.php?blog_id='.$row['blog_id'].'&gidReq=&cidReq='.$courseCode.' " >'.
3164
                    get_lang('See blog').'</a></div></div>';
3165
                $return_data .= '<br / >';
3166
                $return_data .= $row['full_text'];
3167
                $return_data .= '<br /><br />';
3168
            }
3169
        }
3170
3171
        return $return_data;
3172
    }
3173
3174
    /**
3175
     * Gets all the post comments from a given user id.
3176
     *
3177
     * @param int    $courseId
3178
     * @param int    $userId
3179
     * @param string $courseCode
3180
     *
3181
     * @return string
3182
     */
3183
    public static function getBlogCommentsFromUser($courseId, $userId, $courseCode)
3184
    {
3185
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
3186
        $tbl_blog_comment = Database::get_course_table(TABLE_BLOGS_COMMENTS);
3187
3188
        $userId = intval($userId);
3189
        $courseId = intval($courseId);
3190
3191
        $sql = "SELECT DISTINCT blog.blog_id, comment_id, title, comment, comment.date_creation
3192
                FROM $tbl_blogs blog 
3193
                INNER JOIN  $tbl_blog_comment comment
3194
                ON (blog.blog_id = comment.blog_id AND blog.c_id = comment.c_id)
3195
                WHERE 	blog.c_id = $courseId AND
3196
                        comment.c_id = $courseId AND
3197
                        author_id = $userId AND
3198
                        visibility = 1
3199
                ORDER BY blog_name";
3200
        $result = Database::query($sql);
3201
        $return_data = '';
3202
        if (0 != Database::num_rows($result)) {
3203
            while ($row = Database::fetch_array($result)) {
3204
                $return_data .= '<div class="clear"></div><br />';
3205
                $return_data .= '<div class="actions" style="margin-left:5px;margin-right:5px;">'.
3206
                    $row['title'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="float:right;margin-top:-18px"><a href="../blog/blog.php?blog_id='.$row['blog_id'].'&gidReq=&cidReq='.Security::remove_XSS($courseCode).' " >'.
3207
                    get_lang('See blog').'</a></div></div>';
3208
                $return_data .= '<br / >';
3209
                $return_data .= $row['comment'];
3210
                $return_data .= '<br />';
3211
            }
3212
        }
3213
3214
        return $return_data;
3215
    }
3216
3217
    /**
3218
     * Filter the post $fullText to get a extract of $length characters.
3219
     *
3220
     * @param string $fullText
3221
     * @param int    $length
3222
     *
3223
     * @return string|null
3224
     */
3225
    private static function getPostExtract($fullText, $length = BLOG_MAX_PREVIEW_CHARS)
3226
    {
3227
        $parts = explode(BLOG_PAGE_BREAK, $fullText);
3228
3229
        if (count($parts) > 1) {
3230
            return $parts[0];
3231
        }
3232
3233
        // Remove any HTML from the string
3234
        $text = strip_tags($fullText);
3235
        $text = api_html_entity_decode($text);
3236
        // Replace end of lines with spaces
3237
        $text = preg_replace('/\s+/', ' ', $text);
3238
        // Count whitespaces to add to the cut() call below
3239
        $countBlanks = substr_count($text, ' ');
3240
        // Get a version of the string without spaces for comparison purposes
3241
        $textWithoutBlanks = str_replace(' ', '', $text);
3242
        // utf8_decode replaces non-ISO chars by '?' which avoids counting
3243
        // multi-byte characters as more than one character
3244
        $stringLength = strlen(utf8_decode($textWithoutBlanks));
3245
3246
        if ($stringLength <= $length) {
3247
            return null;
3248
        }
3249
3250
        // Cut the string to the BLOG_MAX_PREVIEX_CHARS limit, adding
3251
        // whitespaces
3252
        $extract = cut($text, $length + $countBlanks);
3253
3254
        // Return an HTML string for printing
3255
        return api_htmlentities($extract);
3256
    }
3257
}
3258