Passed
Push — 1.11.x ( bce6cd...c146d9 )
by Angel Fernando Quiroz
12:25
created

main/inc/lib/blog.lib.php (2 issues)

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * Class Blog.
7
 *
8
 * Contains several functions dealing with displaying 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 Security::remove_XSS(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 Security::remove_XSS(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('FirstPostText'),
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) {
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,
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) {
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);
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('UplUnableToSaveFileFilteredExtension'), '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('UplNoFileUploaded'), '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);
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('UplUnableToSaveFileFilteredExtension'), '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 ($articleDelete == 'on') {
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 ($articleEdit == 'on') {
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 ($commentsDelete == 'on') {
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
        $cidReq = api_get_cidreq();
876
877
        if ($_user['user_id']) {
878
            $sql = "SELECT task_rel_user.*, task.title, blog.blog_name
879
                    FROM $tbl_blogs_tasks_rel_user task_rel_user
880
                    INNER JOIN $tbl_blogs_tasks task
881
                    ON task_rel_user.task_id = task.task_id
882
                    INNER JOIN $tbl_blogs blog
883
                    ON task_rel_user.blog_id = blog.blog_id
884
                    AND blog.blog_id = $blog_id
885
                    WHERE
886
                        task.c_id = $course_id AND
887
                        blog.c_id = $course_id AND
888
                        task_rel_user.c_id = $course_id AND
889
                        task_rel_user.user_id = ".$_user['user_id']."
890
                    ORDER BY target_date ASC";
891
            $result = Database::query($sql);
892
            $url = api_get_path(WEB_CODE_PATH).'blog/blog.php?'.$cidReq.'&action=execute_task';
893
            if (Database::num_rows($result) > 0) {
894
                $html .= '<ul>';
895
                while ($mytask = Database::fetch_array($result)) {
896
                    $html .= '<li>
897
                            <a
898
                            href="'.$url.'&blog_id='.$mytask['blog_id'].'&task_id='.intval($mytask['task_id']).'"
899
                            title="[Blog: '.stripslashes($mytask['blog_name']).'] '.
900
                        get_lang('ExecuteThisTask').'">'.
901
                        stripslashes($mytask['title']).'</a></li>';
902
                }
903
                $html .= '<ul>';
904
            } else {
905
                $html .= get_lang('NoTasks');
906
            }
907
        } else {
908
            $html .= get_lang('NoTasks');
909
        }
910
911
        return $html;
912
    }
913
914
    /**
915
     * Changes the visibility of a blog.
916
     *
917
     * @author Toon Keppens
918
     *
919
     * @param int $blog_id
920
     */
921
    public static function changeBlogVisibility($blog_id)
922
    {
923
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
924
        $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
925
        $course_id = api_get_course_int_id();
926
927
        // Get blog properties
928
        $sql = "SELECT blog_name, visibility FROM $tbl_blogs
929
                WHERE c_id = $course_id AND blog_id='".(int) $blog_id."'";
930
        $result = Database::query($sql);
931
        $blog = Database::fetch_array($result);
932
        $visibility = $blog['visibility'];
933
        $title = $blog['blog_name'];
934
935
        if ($visibility == 1) {
936
            // Change visibility state, remove from course home.
937
            $sql = "UPDATE $tbl_blogs SET visibility = '0'
938
                    WHERE c_id = $course_id AND blog_id ='".(int) $blog_id."' LIMIT 1";
939
            Database::query($sql);
940
941
            $sql = "DELETE FROM $tbl_tool
942
                    WHERE c_id = $course_id AND name = '".Database::escape_string($title)."'
943
                    LIMIT 1";
944
            Database::query($sql);
945
        } else {
946
            // Change visibility state, add to course home.
947
            $sql = "UPDATE $tbl_blogs SET visibility = '1'
948
                    WHERE c_id = $course_id AND blog_id ='".(int) $blog_id."' LIMIT 1";
949
            Database::query($sql);
950
951
            $sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, target)
952
                    VALUES ($course_id, '".Database::escape_string($title)."', 'blog/blog.php?blog_id=".(int) $blog_id."', 'blog.gif', '1', '0', 'pastillegris.gif', '0', '_self')";
953
            Database::query($sql);
954
            $id = Database::insert_id();
955
956
            if ($id) {
957
                $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $id";
958
                Database::query($sql);
959
            }
960
        }
961
    }
962
963
    /**
964
     * Display the search results.
965
     *
966
     * @param int    $blog_id
967
     * @param string $query_string
968
     *
969
     * @return string|array
970
     */
971
    public static function getSearchResults($blog_id, $query_string)
972
    {
973
        $query_string_parts = explode(' ', $query_string);
974
        $query_string = [];
975
        foreach ($query_string_parts as $query_part) {
976
            $query_part = Database::escape_string($query_part);
977
            $query_string[] = " full_text LIKE '%".$query_part."%' OR title LIKE '%".$query_part."%' ";
978
        }
979
        $query_string = '('.implode('OR', $query_string).')';
980
981
        // Display the posts
982
        return self::getPosts($blog_id, $query_string);
983
    }
984
985
    /**
986
     * Shows the posts of a blog.
987
     *
988
     * @author Toon Keppens
989
     *
990
     * @param int    $blog_id
991
     * @param string $filter
992
     * @param int    $max_number_of_posts
993
     *
994
     * @return string|array
995
     */
996
    public static function getPosts($blog_id, $filter = '1=1', $max_number_of_posts = 20)
997
    {
998
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
999
        $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
1000
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1001
1002
        $course_id = api_get_course_int_id();
1003
        $blog_id = intval($blog_id);
1004
        $max_number_of_posts = intval($max_number_of_posts);
1005
        // Get posts and authors
1006
        $sql = "SELECT post.*, user.lastname, user.firstname, user.username
1007
                FROM $tbl_blogs_posts post
1008
                INNER JOIN $tbl_users user
1009
                ON post.author_id = user.user_id
1010
                WHERE
1011
                    post.blog_id = $blog_id AND
1012
                    post.c_id = $course_id AND
1013
                    $filter
1014
                ORDER BY post_id DESC
1015
                LIMIT 0, $max_number_of_posts";
1016
        $result = Database::query($sql);
1017
1018
        // Display
1019
        if (Database::num_rows($result) > 0) {
1020
            $limit = 200;
1021
            $listArticle = [];
1022
            while ($blog_post = Database::fetch_array($result)) {
1023
                // Get number of comments
1024
                $sql = "SELECT COUNT(1) as number_of_comments
1025
                        FROM $tbl_blogs_comments
1026
                        WHERE
1027
                            c_id = $course_id AND
1028
                            blog_id = $blog_id AND
1029
                            post_id = ".$blog_post['post_id'];
1030
                $tmp = Database::query($sql);
1031
                $blog_post_comments = Database::fetch_array($tmp);
1032
1033
                $fileArray = self::getBlogAttachments($blog_id, $blog_post['post_id'], 0);
1034
                $scoreRanking = self::displayRating(
1035
                    'post',
1036
                    $blog_id,
1037
                    $blog_post['post_id']
1038
                );
1039
1040
                // Prepare data
1041
                $article = [
1042
                    'id_blog' => $blog_post['blog_id'],
1043
                    'c_id' => $blog_post['c_id'],
1044
                    'id_post' => $blog_post['post_id'],
1045
                    'id_autor' => $blog_post['author_id'],
1046
                    'autor' => $blog_post['firstname'].' '.$blog_post['lastname'],
1047
                    'username' => $blog_post['username'],
1048
                    'title' => Security::remove_XSS($blog_post['title']),
1049
                    'extract' => self::getPostExtract($blog_post['full_text'], BLOG_MAX_PREVIEW_CHARS),
1050
                    'content' => Security::remove_XSS($blog_post['full_text']),
1051
                    'post_date' => Display::dateToStringAgoAndLongDate($blog_post['date_creation']),
1052
                    'n_comments' => $blog_post_comments['number_of_comments'],
1053
                    'files' => $fileArray,
1054
                    'score_ranking' => $scoreRanking,
1055
                ];
1056
1057
                $listArticle[] = $article;
1058
            }
1059
1060
            return $listArticle;
1061
        } else {
1062
            if ($filter == '1=1') {
1063
                return get_lang('NoArticles');
1064
            } else {
1065
                return get_lang('NoArticleMatches');
1066
            }
1067
        }
1068
    }
1069
1070
    /**
1071
     * Display posts from a certain date.
1072
     *
1073
     * @param int    $blog_id
1074
     * @param string $query_string
1075
     *
1076
     * @return string|array
1077
     */
1078
    public static function getDailyResults($blog_id, $query_string)
1079
    {
1080
        $date = explode('-', $query_string);
1081
        $query_string = '
1082
            DAYOFMONTH(date_creation) ='.intval($date[2]).' AND
1083
            MONTH(date_creation) ='.intval($date[1]).' AND
1084
            YEAR(date_creation) ='.intval($date[0]);
1085
        $list = self::getPosts($blog_id, $query_string);
1086
1087
        return $list;
1088
    }
1089
1090
    /**
1091
     * Displays a post and his comments.
1092
     *
1093
     * @param int $blog_id
1094
     * @param int $post_id
1095
     *
1096
     * @return array
1097
     */
1098
    public static function getSinglePost($blog_id, $post_id)
1099
    {
1100
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
1101
        $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
1102
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1103
        $listComments = null;
1104
        global $charset;
1105
1106
        $course_id = api_get_course_int_id();
1107
        $blog_id = intval($blog_id);
1108
        $post_id = intval($post_id);
1109
1110
        // Get posts and author
1111
        $sql = "SELECT post.*, user.lastname, user.firstname, user.username
1112
                FROM $tbl_blogs_posts post
1113
                    INNER JOIN $tbl_users user
1114
                    ON post.author_id = user.user_id
1115
                WHERE
1116
                    post.c_id = $course_id AND
1117
                    post.blog_id = $blog_id AND
1118
                    post.post_id = $post_id
1119
                ORDER BY post_id DESC";
1120
        $result = Database::query($sql);
1121
        $blog_post = Database::fetch_array($result);
1122
1123
        // Get number of comments
1124
        $sql = "SELECT COUNT(1) as number_of_comments
1125
                FROM $tbl_blogs_comments
1126
                WHERE c_id = $course_id AND blog_id = $blog_id AND post_id = $post_id";
1127
        $result = Database::query($sql);
1128
        $blog_post_comments = Database::fetch_array($result);
1129
        $blogActions = null;
1130
1131
        $task_id = (isset($_GET['task_id']) && is_numeric($_GET['task_id'])) ? intval($_GET['task_id']) : 0;
1132
1133
        // Display comments if there are any
1134
        if ($blog_post_comments['number_of_comments'] > 0) {
1135
            $listComments = self::getThreadedComments(0, 0, $blog_id, $post_id, $task_id);
1136
        }
1137
        // Display comment form
1138
        if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_add')) {
1139
            $formComments = self::displayCommentCreateForm($blog_id, $post_id, $blog_post['title'], false);
1140
        }
1141
        // Prepare data
1142
        $fileArray = self::getBlogAttachments($blog_id, $post_id);
1143
1144
        $post_text = make_clickable(stripslashes($blog_post['full_text']));
1145
        $post_text = stripslashes($post_text);
1146
1147
        $blogUrl = api_get_path(WEB_CODE_PATH).'blog/blog.php?blog_id='.$blog_id.
1148
            '&post_id='.$post_id.'&article_id='.$blog_post['post_id'].'&task_id='.$task_id.'&'.api_get_cidreq();
1149
1150
        if (api_is_allowed('BLOG_'.$blog_id, 'article_edit', $task_id)) {
1151
            $blogActions .= '<a
1152
                class="btn btn-default"
1153
                href="'.$blogUrl.'&action=edit_post"
1154
                title="'.get_lang('EditThisPost').'">';
1155
            $blogActions .= Display::return_icon('edit.png', get_lang('Edit'), null, ICON_SIZE_TINY);
1156
            $blogActions .= '</a>';
1157
        }
1158
1159
        if (api_is_allowed('BLOG_'.$blog_id, 'article_delete', $task_id)) {
1160
            $blogActions .= '<a
1161
                class="btn btn-default"
1162
                href="'.$blogUrl.'&action=view_post&do=delete_article"
1163
                title="'.get_lang(
1164
                    'DeleteThisArticle'
1165
                ).'" onclick="javascript:if(!confirm(\''.addslashes(
1166
                    api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)
1167
                ).'\')) return false;">';
1168
            $blogActions .= Display::return_icon(
1169
                'delete.png',
1170
                get_lang('Delete'),
1171
                null,
1172
                ICON_SIZE_TINY
1173
            );
1174
            $blogActions .= '</a>';
1175
        }
1176
        $scoreRanking = self::displayRating('post', $blog_id, $post_id);
1177
        $article = [
1178
            'id_blog' => $blog_post['blog_id'],
1179
            'c_id' => $blog_post['c_id'],
1180
            'id_post' => $blog_post['post_id'],
1181
            'id_author' => $blog_post['author_id'],
1182
            'author' => $blog_post['firstname'].' '.$blog_post['lastname'],
1183
            'username' => $blog_post['username'],
1184
            'title' => Security::remove_XSS($blog_post['title']),
1185
            'extract' => api_get_short_text_from_html(
1186
                Security::remove_XSS($blog_post['full_text']),
1187
                400
1188
            ),
1189
            'content' => $post_text,
1190
            'post_date' => Display::dateToStringAgoAndLongDate($blog_post['date_creation']),
1191
            'n_comments' => $blog_post_comments['number_of_comments'],
1192
            'files' => $fileArray,
1193
            'id_task' => $task_id,
1194
            'comments' => $listComments,
1195
            'form_html' => $formComments,
1196
            'actions' => $blogActions,
1197
            'score_ranking' => (int) $scoreRanking,
1198
            'frm_rating' => api_is_allowed('BLOG_'.$blog_id, 'article_rate')
1199
                ? self::displayRatingCreateForm('post', $blog_id, $post_id)
1200
                : null,
1201
        ];
1202
1203
        return $article;
1204
    }
1205
1206
    /**
1207
     * This functions gets all replies to a post, threaded.
1208
     *
1209
     * @param int $current
1210
     * @param int $current_level
1211
     * @param int $blog_id
1212
     * @param int $post_id
1213
     * @param int $task_id
1214
     *
1215
     * @return array
1216
     */
1217
    public static function getThreadedComments(
1218
        $current,
1219
        $current_level,
1220
        $blog_id,
1221
        $post_id,
1222
        $task_id = 0
1223
    ) {
1224
        $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
1225
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1226
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1227
        $charset = api_get_system_encoding();
1228
        $course_id = api_get_course_int_id();
1229
        $blog_id = intval($blog_id);
1230
        $post_id = intval($post_id);
1231
        $task_id = intval($task_id);
1232
        $listComments = [];
1233
        // Select top level comments
1234
        $next_level = $current_level + 1;
1235
        $sql = "SELECT comments.*, user.lastname, user.firstname, user.username, task.color
1236
                FROM $tbl_blogs_comments comments
1237
                INNER JOIN $tbl_users user
1238
                ON comments.author_id = user.user_id
1239
                LEFT JOIN $tbl_blogs_tasks task
1240
                ON comments.task_id = task.task_id AND task.c_id = $course_id
1241
                WHERE
1242
                    comments.c_id = $course_id AND
1243
                    parent_comment_id = $current AND
1244
                    comments.blog_id = $blog_id AND
1245
                    comments.post_id = $post_id";
1246
1247
        $result = Database::query($sql);
1248
        $html = null;
1249
        $cidReq = api_get_cidreq();
1250
        while ($comment = Database::fetch_array($result)) {
1251
            $commentActions = null;
1252
            $ratingSelect = null;
1253
            $comment_text = make_clickable(stripslashes($comment['comment']));
1254
            $comment_text = Security::remove_XSS($comment_text);
1255
            $commentActions .= Display::toolbarButton(
1256
                get_lang('ReplyToThisComment'),
1257
                '#',
1258
                'reply',
1259
                'default',
1260
                ['data-id' => $comment['iid'], 'role' => 'button', 'class' => 'btn-reply-to'],
1261
                false
1262
            );
1263
1264
            if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_delete', $task_id)) {
1265
                $commentActions .= ' <a
1266
                class="btn btn-default"
1267
                href="blog.php?'.$cidReq.'&action=view_post&blog_id='.$blog_id.'&post_id='.$post_id.'&do=delete_comment&comment_id='.$comment['comment_id'].'&task_id='.$task_id.'"
1268
                title="'.get_lang(
1269
                        'DeleteThisComment'
1270
                    ).'" onclick="javascript:if(!confirm(\''.addslashes(
1271
                        api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)
1272
                    ).'\')) return false;">';
1273
                $commentActions .= Display::returnFontAwesomeIcon('trash');
1274
                $commentActions .= '</a>';
1275
            }
1276
            if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_rate')) {
1277
                $ratingSelect = self::displayRatingCreateForm(
1278
                    'comment',
1279
                    $blog_id,
1280
                    $post_id,
1281
                    $comment['comment_id']
1282
                );
1283
            }
1284
1285
            $scoreRanking = self::displayRating(
1286
                'comment',
1287
                $blog_id,
1288
                $comment['comment_id']
1289
            );
1290
1291
            // Files
1292
            $fileArray = self::getBlogAttachments(
1293
                $blog_id,
1294
                $post_id,
1295
                $comment['comment_id']
1296
            );
1297
            $userInfo = api_get_user_info($comment['author_id']);
1298
            $comments = [
1299
                'iid' => $comment['iid'],
1300
                'id_comment' => $comment['comment_id'],
1301
                'id_curso' => $comment['c_id'],
1302
                'title' => Security::remove_XSS($comment['title']),
1303
                'content' => $comment_text,
1304
                'id_author' => $comment['author_id'],
1305
                'comment_date' => Display::dateToStringAgoAndLongDate($comment['date_creation']),
1306
                'id_blog' => $comment['blog_id'],
1307
                'id_post' => $comment['post_id'],
1308
                'id_task' => $comment['task_id'],
1309
                'id_parent' => $comment['parent_comment_id'],
1310
                'user_info' => $userInfo,
1311
                'color' => $comment['color'],
1312
                'files' => $fileArray,
1313
                'actions' => $commentActions,
1314
                'form_ranking' => $ratingSelect,
1315
                'score_ranking' => $scoreRanking,
1316
                'comments' => self::getThreadedComments(
1317
                    $comment['iid'],
1318
                    $next_level,
1319
                    $blog_id,
1320
                    $post_id
1321
                ),
1322
            ];
1323
1324
            $listComments[] = $comments;
1325
        }
1326
1327
        return $listComments;
1328
    }
1329
1330
    /**
1331
     * Shows the rating form if not already rated by that user.
1332
     *
1333
     * @author Toon Keppens
1334
     *
1335
     * @param string $type
1336
     * @param int    $blog_id
1337
     * @param int    $post_id
1338
     * @param int    $comment_id
1339
     *
1340
     * @return string
1341
     */
1342
    public static function displayRatingCreateForm($type, $blog_id, $post_id, $comment_id = null)
1343
    {
1344
        $_user = api_get_user_info();
1345
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
1346
        $course_id = api_get_course_int_id();
1347
        $blog_id = intval($blog_id);
1348
        $post_id = intval($post_id);
1349
        $comment_id = isset($comment_id) ? intval($comment_id) : null;
1350
        $type = Database::escape_string($type);
1351
        $html = null;
1352
1353
        if ($type === 'post') {
1354
            // Check if the user has already rated this post
1355
            $sql = "SELECT rating_id FROM $tbl_blogs_rating
1356
                    WHERE c_id = $course_id AND
1357
                    blog_id = $blog_id
1358
                    AND item_id = $post_id
1359
                    AND rating_type = '$type'
1360
                    AND user_id = ".$_user['user_id'];
1361
            $result = Database::query($sql);
1362
            // Add rating
1363
            $url = api_get_path(WEB_CODE_PATH).'blog/blog.php?'.api_get_cidreq();
1364
            if (Database::num_rows($result) == 0) {
1365
                $html .= '<form
1366
                    class="form-horizontal"
1367
                    method="get"
1368
                    action="'.$url.'"
1369
                    id="frm_rating_'.$type.'_'.$post_id.'"
1370
                    name="frm_rating_'.$type.'_'.$post_id.'">';
1371
                $html .= '<div class="form-group">';
1372
                $html .= '<label class="col-sm-3 control-label">'.get_lang('RateThis').'</label>';
1373
                $html .= '<div class="col-sm-9">';
1374
                $html .= '<select
1375
                    class="selectpicker"
1376
                    name="rating"
1377
                    onchange="document.forms[\'frm_rating_'.$type.'_'.$post_id.'\'].submit()">
1378
                        <option value="">-</option>
1379
                        <option value="1">1</option>
1380
                        <option value="2">2</option>
1381
                        <option value="3">3</option>
1382
                        <option value="4">4</option>
1383
                        <option value="5">5</option>
1384
                        <option value="6">6</option>
1385
                        <option value="7">7</option>
1386
                        <option value="8">8</option>
1387
                        <option value="9">9</option>
1388
                        <option value="10">10</option>
1389
                    </select>
1390
                    <input type="hidden" name="action" value="view_post" />
1391
                    <input type="hidden" name="type" value="'.$type.'" />
1392
                    <input type="hidden" name="do" value="rate" />
1393
                    <input type="hidden" name="blog_id" value="'.$blog_id.'" />
1394
                    <input type="hidden" name="post_id" value="'.$post_id.'" />';
1395
                $html .= '</div>';
1396
                $html .= '</div>';
1397
                $html .= '</form>';
1398
1399
                return $html;
1400
            } else {
1401
                return '';
1402
            }
1403
        }
1404
1405
        if ($type = 'comment') {
1406
            // Check if the user has already rated this comment
1407
            $sql = "SELECT rating_id FROM $tbl_blogs_rating
1408
                    WHERE c_id = $course_id AND blog_id = $blog_id
1409
                    AND item_id = $comment_id
1410
                    AND rating_type = '$type'
1411
                    AND user_id = ".$_user['user_id'];
1412
            $result = Database::query($sql);
1413
            $url = api_get_path(WEB_CODE_PATH).'blog/blog.php?'.api_get_cidreq();
1414
            if (Database::num_rows($result) == 0) {
1415
                $html .= '<form
1416
                    class="form-horizontal"
1417
                    method="get"
1418
                    action="'.$url.'"
1419
                    id="frm_rating_'.$type.'_'.$comment_id.'" name="frm_rating_'.$type.'_'.$comment_id.'">';
1420
                $html .= '<div class="form-group">';
1421
                $html .= '<label class="col-sm-3 control-label">'.get_lang('RateThis').'</label>';
1422
                $html .= '<div class="col-sm-9">';
1423
                $html .= '<select
1424
                        class="selectpicker"
1425
                        name="rating"
1426
                        onchange="document.forms[\'frm_rating_'.$type.'_'.$comment_id.'\'].submit()">';
1427
                $html .= '<option value="">-</option>
1428
                            <option value="1">1</option>
1429
                            <option value="2">2</option>
1430
                            <option value="3">3</option>
1431
                            <option value="4">4</option>
1432
                            <option value="5">5</option>
1433
                            <option value="6">6</option>
1434
                            <option value="7">7</option>
1435
                            <option value="8">8</option>
1436
                            <option value="9">9</option>
1437
                            <option value="10">10</option>
1438
                         </select>
1439
                         <input type="hidden" name="action" value="view_post" />
1440
                        <input type="hidden" name="type" value="'.$type.'" />
1441
                        <input type="hidden" name="do" value="rate" />
1442
                        <input type="hidden" name="blog_id" value="'.$blog_id.'" />
1443
                        <input type="hidden" name="post_id" value="'.$post_id.'" />
1444
                        <input type="hidden" name="comment_id" value="'.$comment_id.'" />';
1445
                $html .= '</div>';
1446
                $html .= '</div>';
1447
                $html .= '</form>';
1448
1449
                return $html;
1450
            } else {
1451
                return '';
1452
            }
1453
        }
1454
    }
1455
1456
    /**
1457
     * Shows the rating of user.
1458
     *
1459
     * @param string $type
1460
     * @param int    $blog_id
1461
     * @param int    $item_id
1462
     *
1463
     * @return float
1464
     */
1465
    public static function displayRating($type, $blog_id, $item_id)
1466
    {
1467
        $table = Database::get_course_table(TABLE_BLOGS_RATING);
1468
        $course_id = api_get_course_int_id();
1469
        $blog_id = intval($blog_id);
1470
        $item_id = intval($item_id);
1471
        $type = Database::escape_string($type);
1472
1473
        // Calculate rating
1474
        $sql = "SELECT AVG(rating) as rating FROM $table
1475
                WHERE
1476
                    c_id = $course_id AND
1477
                    blog_id = $blog_id AND
1478
                    item_id = $item_id AND
1479
                    rating_type = '$type'";
1480
        $result = Database::query($sql);
1481
        $result = Database::fetch_array($result);
1482
1483
        return round($result['rating'], 2);
1484
    }
1485
1486
    /**
1487
     * Displays the form to create a new post.
1488
     *
1489
     * @author Toon Keppens
1490
     *
1491
     * @param int $blog_id
1492
     * @param int $post_id
1493
     *
1494
     * @return string HTML form
1495
     */
1496
    public static function displayCommentCreateForm($blog_id, $post_id)
1497
    {
1498
        $taskId = !empty($_GET['task_id']) ? intval($_GET['task_id']) : 0;
1499
        $blog_id = intval($blog_id);
1500
        $post_id = intval($post_id);
1501
1502
        $form = new FormValidator(
1503
            'add_post',
1504
            'post',
1505
            api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
1506
                'action' => 'view_post',
1507
                'blog_id' => $blog_id,
1508
                'post_id' => $post_id,
1509
                'task_id' => $taskId,
1510
            ]),
1511
            null,
1512
            ['enctype' => 'multipart/form-data']
1513
        );
1514
1515
        $header = $taskId ? get_lang('ExecuteThisTask') : get_lang('AddNewComment');
1516
        $form->addHeader($header);
1517
        $form->addText('title', get_lang('Title'));
1518
1519
        $config = [];
1520
        if (!api_is_allowed_to_edit()) {
1521
            $config['ToolbarSet'] = 'ProjectComment';
1522
        } else {
1523
            $config['ToolbarSet'] = 'ProjectCommentStudent';
1524
        }
1525
        $form->addHtmlEditor(
1526
            'comment',
1527
            get_lang('Comment'),
1528
            false,
1529
            false,
1530
            $config
1531
        );
1532
        $form->addFile('user_upload', get_lang('AddAnAttachment'));
1533
        $form->addTextarea('post_file_comment', get_lang('FileComment'));
1534
        $form->addHidden('action', null);
1535
        $form->addHidden('comment_parent_id', 0);
1536
        $form->addHidden('task_id', $taskId);
1537
        $form->addButton('save', get_lang('Save'));
1538
1539
        if ($form->validate()) {
1540
            $values = $form->exportValues();
1541
1542
            self::createComment(
1543
                $values['title'],
1544
                $values['comment'],
1545
                $values['post_file_comment'],
1546
                $blog_id,
1547
                $post_id,
1548
                $values['comment_parent_id'],
1549
                $taskId
1550
            );
1551
1552
            Display::addFlash(
1553
                Display::return_message(get_lang('CommentAdded'), 'success')
1554
            );
1555
1556
            header(
1557
                'Location: '
1558
                .api_get_self()
1559
                .'?'
1560
                .api_get_cidreq()
1561
                .'&'
1562
                .http_build_query([
1563
                    'blog_id' => $blog_id,
1564
                    'post_id' => $post_id,
1565
                    'action' => 'view_post',
1566
                    'task_id' => $taskId,
1567
                ])
1568
            );
1569
            exit;
1570
        }
1571
1572
        return $form->returnForm();
1573
    }
1574
1575
    /**
1576
     * Adds rating to a certain post or comment.
1577
     *
1578
     * @author Toon Keppens
1579
     *
1580
     * @param string $type
1581
     * @param int    $blog_id
1582
     * @param int    $item_id
1583
     * @param int    $rating
1584
     *
1585
     * @return bool success
1586
     */
1587
    public static function addRating($type, $blog_id, $item_id, $rating)
1588
    {
1589
        $_user = api_get_user_info();
1590
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
1591
        $course_id = api_get_course_int_id();
1592
        $blog_id = intval($blog_id);
1593
        $item_id = intval($item_id);
1594
        $type = Database::escape_string($type);
1595
        $rating = Database::escape_string($rating);
1596
1597
        // Check if the user has already rated this post/comment
1598
        $sql = "SELECT rating_id FROM $tbl_blogs_rating
1599
                WHERE
1600
                    c_id = $course_id AND
1601
                    blog_id = $blog_id AND
1602
                    item_id = $item_id AND
1603
                    rating_type = '$type' AND
1604
                    user_id = ".$_user['user_id'];
1605
        $result = Database::query($sql);
1606
1607
        // Add rating
1608
        if (Database::num_rows($result) == 0) {
1609
            $sql = "INSERT INTO $tbl_blogs_rating (c_id, blog_id, rating_type, item_id, user_id, rating )
1610
                    VALUES ($course_id, $blog_id, '$type', $item_id, ".$_user['user_id'].", '$rating')";
1611
            Database::query($sql);
1612
1613
            $id = Database::insert_id();
1614
            if ($id) {
1615
                $sql = "UPDATE $tbl_blogs_rating SET rating_id = iid WHERE iid = $id";
1616
                Database::query($sql);
1617
            }
1618
1619
            return true;
1620
        } else {
1621
            return false;
1622
        }
1623
    }
1624
1625
    /**
1626
     * Displays the form to create a new post.
1627
     *
1628
     * @author Toon Keppens
1629
     *
1630
     * @param int $blog_id
1631
     *
1632
     * @return string
1633
     */
1634
    public static function displayPostCreateForm($blog_id)
1635
    {
1636
        $blog_id = intval($blog_id);
1637
        if (!api_is_allowed('BLOG_'.$blog_id, 'article_add')) {
1638
            api_not_allowed();
1639
        }
1640
1641
        $form = new FormValidator(
1642
            'add_post',
1643
            'post',
1644
            api_get_path(WEB_CODE_PATH)."blog/blog.php?action=new_post&blog_id=".$blog_id."&".api_get_cidreq(),
1645
            null,
1646
            ['enctype' => 'multipart/form-data']
1647
        );
1648
        $form->addHidden('post_title_edited', 'false');
1649
        $form->addHeader(get_lang('NewPost'));
1650
        $form->addText('title', get_lang('Title'));
1651
        $config = [];
1652
        $config['ToolbarSet'] = !api_is_allowed_to_edit() ? 'ProjectStudent' : 'Project';
1653
        $form->addHtmlEditor('full_text', get_lang('Content'), false, false, $config);
1654
        $form->addFile('user_upload', get_lang('AddAnAttachment'));
1655
        $form->addTextarea('post_file_comment', get_lang('FileComment'));
1656
        $form->addHidden('new_post_submit', 'true');
1657
        $form->addButton('save', get_lang('Save'));
1658
1659
        if ($form->validate()) {
1660
            $values = $form->exportValues();
1661
1662
            $postId = self::createPost(
1663
                $values['title'],
1664
                $values['full_text'],
1665
                $values['post_file_comment'],
1666
                $blog_id
1667
            );
1668
1669
            if ($postId) {
1670
                Display::addFlash(
1671
                    Display::return_message(get_lang('BlogAdded'), 'success')
1672
                );
1673
1674
                header('Location: '.api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
1675
                    'action' => 'view_post',
1676
                    'blog_id' => $blog_id,
1677
                    'post_id' => $postId,
1678
                ]));
1679
                exit;
1680
            }
1681
        }
1682
1683
        return $form->returnForm();
1684
    }
1685
1686
    /**
1687
     * Displays the form to edit a post.
1688
     *
1689
     * @author Toon Keppens
1690
     *
1691
     * @param int $blog_id
1692
     * @param int $post_id
1693
     *
1694
     * @return string
1695
     */
1696
    public static function displayPostEditForm($blog_id, $post_id)
1697
    {
1698
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
1699
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1700
1701
        $course_id = api_get_course_int_id();
1702
        $blog_id = intval($blog_id);
1703
        $post_id = intval($post_id);
1704
1705
        // Get posts and author
1706
        $sql = "SELECT post.*, user.lastname, user.firstname
1707
                FROM $tbl_blogs_posts post
1708
                INNER JOIN $tbl_users user ON post.author_id = user.user_id
1709
                WHERE
1710
                post.c_id 			= $course_id AND
1711
                post.blog_id 		= $blog_id
1712
                AND post.post_id	= $post_id
1713
                ORDER BY post_id DESC";
1714
        $result = Database::query($sql);
1715
        $blog_post = Database::fetch_array($result);
1716
1717
        $form = new FormValidator(
1718
            'edit_post',
1719
            'post',
1720
            api_get_path(WEB_CODE_PATH).
1721
            'blog/blog.php?action=edit_post&post_id='.intval($_GET['post_id']).'&blog_id='.intval($blog_id).
1722
            '&article_id='.intval($_GET['article_id']).'&task_id='.intval($_GET['task_id']).'&'.api_get_cidreq()
1723
        );
1724
1725
        $form->addHeader(get_lang('EditPost'));
1726
        $form->addText('title', get_lang('Title'));
1727
1728
        if (!api_is_allowed_to_edit()) {
1729
            $config['ToolbarSet'] = 'ProjectStudent';
1730
        } else {
1731
            $config['ToolbarSet'] = 'Project';
1732
        }
1733
        $form->addHtmlEditor('full_text', get_lang('Content'), false, false, $config);
1734
1735
        $form->addHidden('action', '');
1736
        $form->addHidden('edit_post_submit', 'true');
1737
        $form->addHidden('post_id', intval($_GET['post_id']));
1738
        $form->addButton('save', get_lang('Save'));
1739
        $form->setDefaults($blog_post);
1740
1741
        return $form->returnForm();
1742
    }
1743
1744
    /**
1745
     * Displays a list of tasks in this blog.
1746
     *
1747
     * @author Toon Keppens
1748
     *
1749
     * @param int $blog_id
1750
     *
1751
     * @return string
1752
     */
1753
    public static function displayTasksList($blog_id)
1754
    {
1755
        global $charset;
1756
        $course_id = api_get_course_int_id();
1757
        $blog_id = intval($blog_id);
1758
        $html = '';
1759
        if (api_is_allowed('BLOG_'.$blog_id, 'article_add')) {
1760
            $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1761
            $counter = 0;
1762
            global $color2;
1763
1764
            $html .= '<div class="actions">';
1765
            $html .= '<a href="'.api_get_self().'?action=manage_tasks&blog_id='.$blog_id.'&do=add&'.api_get_cidreq().'">';
1766
            $html .= Display::return_icon('blog_newtasks.gif', get_lang('AddTasks'));
1767
            $html .= get_lang('AddTasks').'</a> ';
1768
            $html .= '<a href="'.api_get_self().'?action=manage_tasks&blog_id='.$blog_id.'&do=assign&'.api_get_cidreq().'">';
1769
            $html .= Display::return_icon('blog_task.gif', get_lang('AssignTasks'));
1770
            $html .= get_lang('AssignTasks').'</a>';
1771
            $html .= Display::url(
1772
                Display::return_icon('blog_admin_users.png', get_lang('RightsManager')),
1773
                api_get_self().'?'.http_build_query([
1774
                    'action' => 'manage_rights',
1775
                    'blog_id' => $blog_id,
1776
                ]),
1777
                ['title' => get_lang('ManageRights')]
1778
            );
1779
1780
            $html .= '</div>';
1781
1782
            $html .= '<span class="blogpost_title">'.get_lang('TaskList').'</span><br />';
1783
            $html .= "<table class=\"table table-hover table-striped data_table\">";
1784
            $html .= "<tr bgcolor=\"$color2\" align=\"center\" valign=\"top\">"
1785
                ."<th width='240'><b>".get_lang('Title')."</b></th>"
1786
                ."<th><b>".get_lang('Description')."</b></th>"
1787
                ."<th><b>".get_lang('Color')."</b></th>"
1788
                ."<th width='50'><b>".get_lang('Modify')."</b></th></tr>";
1789
1790
            $sql = " SELECT
1791
                        blog_id,
1792
                        task_id,
1793
                        blog_id,
1794
                        title,
1795
                        description,
1796
                        color,
1797
                        system_task
1798
                    FROM $tbl_blogs_tasks
1799
                    WHERE c_id = $course_id AND blog_id = $blog_id
1800
                    ORDER BY system_task, title";
1801
            $result = Database::query($sql);
1802
1803
            while ($task = Database::fetch_array($result)) {
1804
                $counter++;
1805
                $css_class = (($counter % 2) == 0) ? "row_odd" : "row_even";
1806
                $delete_icon = $task['system_task'] == '1' ? "delete_na.png" : "delete.png";
1807
                $delete_title = $task['system_task'] == '1' ? get_lang('DeleteSystemTask') : get_lang('DeleteTask');
1808
                $delete_link = $task['system_task'] == '1' ? '#' : api_get_self().'?action=manage_tasks&blog_id='.$task['blog_id'].'&do=delete&task_id='.$task['task_id'].'&'.api_get_cidreq();
1809
                $delete_confirm = ($task['system_task'] == '1') ? '' : 'onclick="javascript:if(!confirm(\''.addslashes(
1810
                        api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)
1811
                    ).'\')) return false;"';
1812
1813
                $html .= '<tr class="'.$css_class.'" valign="top">';
1814
                $html .= '<td width="240">'.Security::remove_XSS($task['title']).'</td>';
1815
                $html .= '<td>'.Security::remove_XSS($task['description']).'</td>';
1816
                $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>';
1817
                $html .= '<td width="50">';
1818
                $html .= '<a href="'.api_get_self().'?action=manage_tasks&blog_id='.$task['blog_id'].'&do=edit&task_id='.$task['task_id'].'&'.api_get_cidreq().'">';
1819
                $html .= Display::return_icon('edit.png', get_lang('EditTask'));
1820
                $html .= "</a>";
1821
                $html .= '<a href="'.$delete_link.'"';
1822
                $html .= $delete_confirm;
1823
                $html .= '>';
1824
                $html .= Display::return_icon($delete_icon, $delete_title);
1825
                $html .= "</a>";
1826
                $html .= '</td>';
1827
                $html .= '</tr>';
1828
            }
1829
            $html .= "</table>";
1830
        }
1831
1832
        return $html;
1833
    }
1834
1835
    /**
1836
     * Displays a list of tasks assigned to a user in this blog.
1837
     *
1838
     * @author Toon Keppens
1839
     *
1840
     * @param int $blog_id
1841
     *
1842
     * @return string
1843
     */
1844
    public static function displayAssignedTasksList($blog_id)
1845
    {
1846
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1847
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1848
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
1849
        $counter = 0;
1850
        global $charset, $color2;
1851
1852
        $return = '<span class="blogpost_title">'.get_lang('AssignedTasks').'</span><br />';
1853
        $return .= "<table class=\"table table-hover table-striped data_table\">";
1854
        $return .= "<tr bgcolor=\"$color2\" align=\"center\" valign=\"top\">"
1855
            ."<th width='240'><b>".get_lang('Member')."</b></th>"
1856
            ."<th><b>".get_lang('Task')."</b></th>"
1857
            ."<th><b>".get_lang('Description')."</b></th>"
1858
            ."<th><b>".get_lang('TargetDate')."</b></th>"
1859
            ."<th width='50'><b>".get_lang('Modify')."</b></th>"
1860
            ."</tr>";
1861
1862
        $course_id = api_get_course_int_id();
1863
        $blog_id = intval($blog_id);
1864
1865
        $sql = "SELECT task_rel_user.*, task.title, user.firstname, user.lastname, user.username, task.description, task.system_task, task.blog_id, task.task_id
1866
                FROM $tbl_blogs_tasks_rel_user task_rel_user
1867
                INNER JOIN $tbl_blogs_tasks task
1868
                ON task_rel_user.task_id = task.task_id
1869
                INNER JOIN $tbl_users user
1870
                ON task_rel_user.user_id = user.user_id
1871
                WHERE
1872
                    task_rel_user.c_id = $course_id AND
1873
                    task.c_id = $course_id AND
1874
                    task_rel_user.blog_id = $blog_id
1875
                ORDER BY target_date ASC";
1876
        $result = Database::query($sql);
1877
1878
        while ($assignment = Database::fetch_array($result)) {
1879
            $counter++;
1880
            $css_class = (($counter % 2) == 0) ? "row_odd" : "row_even";
1881
            $delete_icon = ($assignment['system_task'] == '1') ? "delete_na.png" : "delete.png";
1882
            $delete_title = ($assignment['system_task'] == '1') ? get_lang('DeleteSystemTask') : get_lang('DeleteTask');
1883
            $username = api_htmlentities(sprintf(get_lang('LoginX'), $assignment['username']), ENT_QUOTES);
1884
1885
            $return .= '<tr class="'.$css_class.'" valign="top">';
1886
            $return .= '<td width="240">'.Display::tag(
1887
                'span',
1888
                api_get_person_name($assignment['firstname'], $assignment['lastname']),
1889
                ['title' => $username]
1890
            ).'</td>';
1891
            $return .= '<td>'.Security::remove_XSS($assignment['title']).'</td>';
1892
            $return .= '<td>'.Security::remove_XSS($assignment['description']).'</td>';
1893
            $return .= '<td>'.$assignment['target_date'].'</td>';
1894
            $return .= '<td width="50">';
1895
            $return .= '<a
1896
                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().'">';
1897
            $return .= Display::return_icon('edit.png', get_lang('EditTask'));
1898
            $return .= "</a>";
1899
            $return .= '<a
1900
                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().'" ';
1901
            $return .= 'onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)).'\')) return false;"';
1902
            $return .= Display::return_icon($delete_icon, $delete_title);
1903
            $return .= "</a>";
1904
            $return .= '</td>';
1905
            $return .= '</tr>';
1906
        }
1907
        $return .= "</table>";
1908
1909
        return $return;
1910
    }
1911
1912
    /**
1913
     * Displays new task form.
1914
     *
1915
     * @todo use FormValidator
1916
     *
1917
     * @author Toon Keppens
1918
     *
1919
     * @param int $blog_id
1920
     *
1921
     * @return string HTML form
1922
     */
1923
    public static function displayTaskCreateForm($blog_id)
1924
    {
1925
        $blog_id = intval($blog_id);
1926
1927
        $colors = [
1928
            'FFFFFF',
1929
            'FFFF99',
1930
            'FFCC99',
1931
            'FF9933',
1932
            'FF6699',
1933
            'CCFF99',
1934
            'CC9966',
1935
            '66FF00',
1936
            '9966FF',
1937
            'CF3F3F',
1938
            '990033',
1939
            '669933',
1940
            '0033FF',
1941
            '003366',
1942
            '000000',
1943
        ];
1944
1945
        $url = api_get_path(WEB_CODE_PATH).'blog/blog.php?'.api_get_cidreq().'&action=manage_tasks';
1946
        $return = '<form name="add_task" method="post" action="'.$url.'&blog_id='.$blog_id.'">';
1947
        $return .= '<legend>'.get_lang('AddTask').'</legend>';
1948
        $return .= '	<div class="control-group">
1949
                    <label class="control-label">
1950
                        <span class="form_required">*</span>'.get_lang('Title').'
1951
                    </label>
1952
                    <div class="controls">
1953
                        <input name="task_name" type="text" size="70" />
1954
                    </div>
1955
                </div>';
1956
1957
        // task comment
1958
        $return .= '	<div class="control-group">
1959
                    <label class="control-label">
1960
                        '.get_lang('Description').'
1961
                    </label>
1962
                    <div class="controls">
1963
                        <textarea name="task_description" cols="45"></textarea>
1964
                    </div>
1965
                </div>';
1966
1967
        // task management
1968
        $return .= '	<div class="control-group">
1969
                    <label class="control-label">
1970
                        '.get_lang('TaskManager').'
1971
                    </label>
1972
                    <div class="controls">';
1973
        $return .= '<table class="table table-hover table-striped data_table" cellspacing="0" style="border-collapse:collapse; width:446px;">';
1974
        $return .= '<tr>';
1975
        $return .= '<th colspan="2" style="width:223px;">'.get_lang('ArticleManager').'</th>';
1976
        $return .= '<th width:223px;>'.get_lang('CommentManager').'</th>';
1977
        $return .= '</tr>';
1978
        $return .= '<tr>';
1979
        $return .= '<th style="width:111px;"><label for="articleDelete">'.get_lang('Delete').'</label></th>';
1980
        $return .= '<th style="width:112px;"><label for="articleEdit">'.get_lang('Edit').'</label></th>';
1981
        $return .= '<th style="width:223px;"><label for="commentsDelete">'.get_lang('Delete').'</label></th>';
1982
        $return .= '</tr>';
1983
        $return .= '<tr>';
1984
        $return .= '<td style="text-align:center;"><input id="articleDelete" name="chkArticleDelete" type="checkbox" /></td>';
1985
        $return .= '<td style="text-align:center;"><input id="articleEdit" name="chkArticleEdit" type="checkbox" /></td>';
1986
        $return .= '<td style="border:1px dotted #808080; text-align:center;"><input id="commentsDelete" name="chkCommentsDelete" type="checkbox" /></td>';
1987
        $return .= '</tr>';
1988
        $return .= '</table>';
1989
        $return .= '		</div>
1990
                </div>';
1991
1992
        // task color
1993
        $return .= '	<div class="control-group">
1994
                    <label class="control-label">
1995
                        '.get_lang('Color').'
1996
                    </label>
1997
                    <div class="controls">';
1998
        $return .= '<select name="task_color" id="color" style="width: 150px; background-color: #eeeeee" onchange="document.getElementById(\'color\').style.backgroundColor=\'#\'+document.getElementById(\'color\').value" onkeypress="document.getElementById(\'color\').style.backgroundColor=\'#\'+document.getElementById(\'color\').value">';
1999
        foreach ($colors as $color) {
2000
            $style = 'style="background-color: #'.$color.'"';
2001
            $return .= '<option value="'.$color.'" '.$style.'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
2002
        }
2003
        $return .= '</select>';
2004
        $return .= '		</div>
2005
                </div>';
2006
2007
        // submit
2008
        $return .= '	<div class="control-group">
2009
                    <div class="controls">
2010
                            <input type="hidden" name="action" value="" />
2011
                            <input type="hidden" name="new_task_submit" value="true" />
2012
                        <button class="save" type="submit" name="Submit">'.get_lang('Save').'</button>
2013
                    </div>
2014
                </div>';
2015
        $return .= '</form>';
2016
2017
        $return .= '<div style="clear:both; margin-bottom: 10px;"></div>';
2018
2019
        return $return;
2020
    }
2021
2022
    /**
2023
     * Displays edit task form.
2024
     *
2025
     * @author Toon Keppens
2026
     *
2027
     * @param int $blog_id
2028
     * @param int $task_id
2029
     *
2030
     * @return string
2031
     */
2032
    public static function displayTaskEditForm($blog_id, $task_id)
2033
    {
2034
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
2035
        $course_id = api_get_course_int_id();
2036
        $blog_id = intval($blog_id);
2037
        $task_id = intval($task_id);
2038
2039
        $colors = [
2040
            'FFFFFF',
2041
            'FFFF99',
2042
            'FFCC99',
2043
            'FF9933',
2044
            'FF6699',
2045
            'CCFF99',
2046
            'CC9966',
2047
            '66FF00',
2048
            '9966FF',
2049
            'CF3F3F',
2050
            '990033',
2051
            '669933',
2052
            '0033FF',
2053
            '003366',
2054
            '000000',
2055
        ];
2056
2057
        $sql = "SELECT blog_id, task_id, title, description, color FROM $tbl_blogs_tasks
2058
                WHERE c_id = $course_id AND task_id = $task_id";
2059
        $result = Database::query($sql);
2060
        $task = Database::fetch_array($result);
2061
2062
        $url = api_get_path(WEB_CODE_PATH).'blog/blog.php?'.api_get_cidreq().'&action=manage_tasks';
2063
        $return = '<form name="edit_task" method="post" action="'.$url.'&blog_id='.$blog_id.'">
2064
                    <legend>'.get_lang('EditTask').'</legend>
2065
                    <table width="100%" border="0" cellspacing="2">
2066
                        <tr>
2067
                       <td align="right">'.get_lang('Title').':&nbsp;&nbsp;</td>
2068
                       <td>
2069
                        <input name="task_name" type="text" size="70" value="'.Security::remove_XSS($task['title']).'" />
2070
                        </td>
2071
                        </tr>
2072
                        <tr>
2073
                       <td align="right">'.get_lang('Description').':&nbsp;&nbsp;</td>
2074
                       <td>
2075
                        <textarea name="task_description" cols="45">'.
2076
                            Security::remove_XSS($task['description']).'
2077
                        </textarea>
2078
                        </td>
2079
                        </tr>';
2080
2081
        /* edit by Kevin Van Den Haute ([email protected]) */
2082
        $tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
2083
2084
        $sql = "SELECT id, action FROM $tbl_tasks_permissions
2085
                WHERE c_id = $course_id AND task_id = $task_id";
2086
        $result = Database::query($sql);
2087
2088
        $arrPermissions = [];
2089
2090
        while ($row = Database::fetch_array($result)) {
2091
            $arrPermissions[] = $row['action'];
2092
        }
2093
2094
        $return .= '<tr>';
2095
        $return .= '<td style="text-align:right; vertical-align:top;">'.get_lang('TaskManager').':&nbsp;&nbsp;</td>';
2096
        $return .= '<td>';
2097
        $return .= '<table  class="table table-hover table-striped data_table" cellspacing="0" style="border-collapse:collapse; width:446px;">';
2098
        $return .= '<tr>';
2099
        $return .= '<th colspan="2" style="width:223px;">'.get_lang('ArticleManager').'</th>';
2100
        $return .= '<th width:223px;>'.get_lang('CommentManager').'</th>';
2101
        $return .= '</tr>';
2102
        $return .= '<tr>';
2103
        $return .= '<th style="width:111px;"><label for="articleDelete">'.get_lang('Delete').'</label></th>';
2104
        $return .= '<th style="width:112px;"><label for="articleEdit">'.get_lang('Edit').'</label></th>';
2105
        $return .= '<th style="width:223px;"><label for="commentsDelete">'.get_lang('Delete').'</label></th>';
2106
        $return .= '</tr>';
2107
        $return .= '<tr>';
2108
        $return .= '<td style="text-align:center;"><input '.((in_array(
2109
                'article_delete',
2110
                $arrPermissions
2111
            )) ? 'checked ' : '').'id="articleDelete" name="chkArticleDelete" type="checkbox" /></td>';
2112
        $return .= '<td style="text-align:center;"><input '.((in_array(
2113
                'article_edit',
2114
                $arrPermissions
2115
            )) ? 'checked ' : '').'id="articleEdit" name="chkArticleEdit" type="checkbox" /></td>';
2116
        $return .= '<td style="text-align:center;"><input '.((in_array(
2117
                'article_comments_delete',
2118
                $arrPermissions
2119
            )) ? 'checked ' : '').'id="commentsDelete" name="chkCommentsDelete" type="checkbox" /></td>';
2120
        $return .= '</tr>';
2121
        $return .= '</table>';
2122
        $return .= '</td>';
2123
        $return .= '</tr>';
2124
        /* end of edit */
2125
2126
        $return .= '<tr>
2127
                       <td align="right">'.get_lang('Color').':&nbsp;&nbsp;</td>
2128
                       <td>
2129
                        <select name="task_color" id="color" style="width: 150px; background-color: #'.$task['color'].'" onchange="document.getElementById(\'color\').style.backgroundColor=\'#\'+document.getElementById(\'color\').value" onkeypress="document.getElementById(\'color\').style.backgroundColor=\'#\'+document.getElementById(\'color\').value">';
2130
        foreach ($colors as $color) {
2131
            $selected = ($color == $task['color']) ? ' selected' : '';
2132
            $style = 'style="background-color: #'.$color.'"';
2133
            $return .= '<option value="'.$color.'" '.$style.' '.$selected.' >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
2134
        }
2135
        $return .= '</select>
2136
                          </td>
2137
                        </tr>
2138
                        <tr>
2139
                            <td align="right">&nbsp;</td>
2140
                            <td><br /><input type="hidden" name="action" value="" />
2141
                            <input type="hidden" name="edit_task_submit" value="true" />
2142
                            <input type="hidden" name="task_id" value="'.$task['task_id'].'" />
2143
                            <input type="hidden" name="blog_id" value="'.$task['blog_id'].'" />
2144
                            <button class="save" type="submit" name="Submit">'.get_lang('Save').'</button></td>
2145
                        </tr>
2146
                    </table>
2147
                </form>';
2148
2149
        return $return;
2150
    }
2151
2152
    /**
2153
     * Displays assign task form.
2154
     *
2155
     * @author Toon Keppens
2156
     */
2157
    public static function displayTaskAssignmentForm($blog_id)
2158
    {
2159
        $form = self::getTaskAssignmentForm($blog_id);
2160
        $form->addHidden('assign_task_submit', 'true');
2161
2162
        return $form->returnForm()
2163
            .PHP_EOL
2164
            .'<div style="clear: both; margin-bottom:10px;"></div>';
2165
    }
2166
2167
    /**
2168
     * Returns an HTML form to assign a task.
2169
     *
2170
     * @param $blog_id
2171
     *
2172
     * @return FormValidator
2173
     */
2174
    public static function getTaskAssignmentForm($blog_id)
2175
    {
2176
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2177
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
2178
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
2179
        $course_id = api_get_course_int_id();
2180
        $blog_id = intval($blog_id);
2181
2182
        // Get users in this blog / make select list of it
2183
        $sql = "SELECT user.user_id, user.firstname, user.lastname, user.username
2184
                FROM $tbl_users user
2185
                INNER JOIN $tbl_blogs_rel_user blogs_rel_user
2186
                ON user.user_id = blogs_rel_user.user_id
2187
                WHERE blogs_rel_user.c_id = $course_id AND blogs_rel_user.blog_id = $blog_id";
2188
        $result = Database::query($sql);
2189
2190
        $options = [];
2191
        while ($user = Database::fetch_array($result)) {
2192
            $options[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']);
2193
        }
2194
2195
        // Get tasks in this blog / make select list of it
2196
        $sql = "SELECT
2197
                    blog_id,
2198
                    task_id,
2199
                    blog_id,
2200
                    title,
2201
                    description,
2202
                    color,
2203
                    system_task
2204
                FROM $tbl_blogs_tasks
2205
                WHERE c_id = $course_id AND blog_id = $blog_id
2206
                ORDER BY system_task, title";
2207
        $result = Database::query($sql);
2208
2209
        $taskOptions = [];
2210
        while ($task = Database::fetch_array($result)) {
2211
            $taskOptions[$task['task_id']] = stripslashes($task['title']);
2212
        }
2213
2214
        $form = new FormValidator(
2215
            'assign_task',
2216
            'post',
2217
            api_get_path(WEB_CODE_PATH).
2218
            'blog/blog.php?action=manage_tasks&blog_id='.$blog_id.'&'.api_get_cidreq()
2219
        );
2220
2221
        $form->addHeader(get_lang('AssignTask'));
2222
        $form->addSelect('task_user_id', get_lang('SelectUser'), $options);
2223
        $form->addSelect('task_task_id', get_lang('SelectTask'), $taskOptions);
2224
        $form->addDatePicker('task_day', get_lang('SelectTargetDate'));
2225
2226
        $form->addHidden('action', '');
2227
        $form->addButtonSave(get_lang('Ok'));
2228
2229
        return $form;
2230
    }
2231
2232
    /**
2233
     * Displays assign task form.
2234
     *
2235
     * @author Toon Keppens
2236
     *
2237
     * @param int $blog_id
2238
     * @param int $task_id
2239
     * @param int $user_id
2240
     *
2241
     * @return string HTML form
2242
     */
2243
    public static function displayAssignedTaskEditForm($blog_id, $task_id, $user_id)
2244
    {
2245
        $table = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2246
2247
        $course_id = api_get_course_int_id();
2248
        $blog_id = intval($blog_id);
2249
        $task_id = intval($task_id);
2250
        $user_id = intval($user_id);
2251
2252
        // Get assign date;
2253
        $sql = "
2254
            SELECT target_date
2255
            FROM $table
2256
            WHERE c_id = $course_id AND
2257
                  blog_id = $blog_id AND
2258
                  user_id = $user_id AND
2259
                  task_id = $task_id";
2260
        $result = Database::query($sql);
2261
        $row = Database::fetch_assoc($result);
2262
2263
        $date = $row['target_date'];
2264
2265
        $defaults = [
2266
            'task_user_id' => $user_id,
2267
            'task_task_id' => $task_id,
2268
            'task_day' => $date,
2269
        ];
2270
        $form = self::getTaskAssignmentForm($blog_id);
2271
        $form->addHidden('old_task_id', $task_id);
2272
        $form->addHidden('old_user_id', $user_id);
2273
        $form->addHidden('old_target_date', $date);
2274
        $form->addHidden('assign_task_edit_submit', 'true');
2275
        $form->setDefaults($defaults);
2276
2277
        return $form->returnForm();
2278
    }
2279
2280
    /**
2281
     * Assigns a task to a user in a blog.
2282
     *
2283
     * @param int    $blog_id
2284
     * @param int    $user_id
2285
     * @param int    $task_id
2286
     * @param string $target_date date
2287
     */
2288
    public static function assignTask($blog_id, $user_id, $task_id, $target_date)
2289
    {
2290
        $table = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2291
        $course_id = api_get_course_int_id();
2292
        $blog_id = intval($blog_id);
2293
        $user_id = intval($user_id);
2294
        $task_id = intval($task_id);
2295
        $target_date = Database::escape_string($target_date);
2296
2297
        $sql = "
2298
            SELECT COUNT(*) as 'number'
2299
            FROM $table
2300
            WHERE c_id = $course_id
2301
            AND blog_id = $blog_id
2302
            AND	user_id = $user_id
2303
            AND	task_id = $task_id";
2304
2305
        $result = Database::query($sql);
2306
        $row = Database::fetch_assoc($result);
2307
2308
        if ($row['number'] == 0) {
2309
            $sql = "
2310
                INSERT INTO ".$table." (
2311
                    c_id,
2312
                    blog_id,
2313
                    user_id,
2314
                    task_id,
2315
                    target_date
2316
                ) VALUES (
2317
                    $course_id,
2318
                    $blog_id,
2319
                    $user_id,
2320
                    $task_id,
2321
                    '$target_date'
2322
                )";
2323
2324
            Database::query($sql);
2325
        }
2326
    }
2327
2328
    /**
2329
     * Edit an assigned task.
2330
     *
2331
     * @param $blog_id
2332
     * @param $user_id
2333
     * @param $task_id
2334
     * @param $target_date
2335
     * @param $old_user_id
2336
     * @param $old_task_id
2337
     * @param $old_target_date
2338
     */
2339
    public static function updateAssignedTask(
2340
        $blog_id,
2341
        $user_id,
2342
        $task_id,
2343
        $target_date,
2344
        $old_user_id,
2345
        $old_task_id,
2346
        $old_target_date
2347
    ) {
2348
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2349
2350
        $course_id = api_get_course_int_id();
2351
        $blog_id = intval($blog_id);
2352
        $user_id = intval($user_id);
2353
        $task_id = intval($task_id);
2354
        $target_date = Database::escape_string($target_date);
2355
        $old_user_id = intval($old_user_id);
2356
        $old_task_id = intval($old_task_id);
2357
        $old_target_date = Database::escape_string($old_target_date);
2358
2359
        $sql = "SELECT COUNT(*) as 'number'
2360
                FROM $tbl_blogs_tasks_rel_user
2361
                WHERE
2362
                    c_id = $course_id AND
2363
                    blog_id = $blog_id AND
2364
                    user_id = $user_id AND
2365
                    task_id = $task_id";
2366
2367
        $result = Database::query($sql);
2368
        $row = Database::fetch_assoc($result);
2369
2370
        if ($row['number'] == 0 ||
2371
            ($row['number'] != 0 && $task_id == $old_task_id && $user_id == $old_user_id)
2372
        ) {
2373
            $sql = "UPDATE $tbl_blogs_tasks_rel_user
2374
                SET
2375
                    user_id = $user_id,
2376
                    task_id = $task_id,
2377
                    target_date = '$target_date'
2378
                WHERE
2379
                    c_id = $course_id AND
2380
                    blog_id = $blog_id AND
2381
                    user_id = $old_user_id AND
2382
                    task_id = $old_task_id AND
2383
                    target_date = '$old_target_date'
2384
            ";
2385
            Database::query($sql);
2386
        }
2387
    }
2388
2389
    /**
2390
     * Displays a list with posts a user can select to execute his task.
2391
     *
2392
     * @param int $blog_id
2393
     * @param int $task_id
2394
     *
2395
     * @return string
2396
     */
2397
    public static function displayPostSelectionForTask($blog_id, $task_id)
2398
    {
2399
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
2400
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
2401
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2402
        $course_id = api_get_course_int_id();
2403
        $blog_id = intval($blog_id);
2404
        $task_id = intval($task_id);
2405
2406
        $sql = "SELECT title, description FROM $tbl_blogs_tasks
2407
                WHERE task_id = $task_id
2408
                AND c_id = $course_id";
2409
        $result = Database::query($sql);
2410
        $row = Database::fetch_assoc($result);
2411
2412
        // Get posts and authors
2413
        $sql = "SELECT post.*, user.lastname, user.firstname, user.username
2414
                FROM $tbl_blogs_posts post
2415
                INNER JOIN $tbl_users user ON post.author_id = user.user_id
2416
                WHERE post.blog_id = $blog_id AND post.c_id = $course_id
2417
                ORDER BY post_id DESC
2418
                LIMIT 0, 100";
2419
        $result = Database::query($sql);
2420
2421
        // Display
2422
        $return = '<span class="blogpost_title">'.
2423
                    get_lang('SelectTaskArticle').' "'.Security::remove_XSS($row['title']).'"</span>';
2424
        $return .= '<span style="font-style: italic;"">'.Security::remove_XSS($row['description']).'</span><br><br>';
2425
2426
        if (Database::num_rows($result) == 0) {
2427
            $return .= get_lang('NoArticles');
2428
2429
            return $return;
2430
        }
2431
        $url = api_get_path(WEB_CODE_PATH).'blog/blog.php?'.api_get_cidreq().'&action=execute_task';
2432
        while ($blog_post = Database::fetch_array($result)) {
2433
            $username = api_htmlentities(sprintf(get_lang('LoginX'), $blog_post['username']), ENT_QUOTES);
2434
            $return .= '<a href="'.$url.'&blog_id='.$blog_id.'&task_id='.$task_id.'&post_id='.$blog_post['post_id'].'#add_comment">'.
2435
                Security::remove_XSS($blog_post['title']).'</a>, '.
2436
                get_lang('WrittenBy').' '.stripslashes(
2437
                    Display::tag(
2438
                        'span',
2439
                        api_get_person_name($blog_post['firstname'], $blog_post['lastname']),
2440
                        ['title' => $username]
2441
                    )
2442
                ).'<br />';
2443
        }
2444
2445
        return $return;
2446
    }
2447
2448
    /**
2449
     * Unsubscribe a user from a given blog.
2450
     *
2451
     * @author Toon Keppens
2452
     *
2453
     * @param int $blog_id
2454
     * @param int $user_id
2455
     */
2456
    public static function unsubscribeUser($blog_id, $user_id)
2457
    {
2458
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
2459
        $tbl_user_permissions = Database::get_course_table(TABLE_PERMISSION_USER);
2460
        $blog_id = intval($blog_id);
2461
        $user_id = intval($user_id);
2462
2463
        // Unsubscribe the user
2464
        $sql = "DELETE FROM $tbl_blogs_rel_user
2465
                WHERE blog_id = $blog_id AND user_id = $user_id";
2466
        Database::query($sql);
2467
2468
        // Remove this user's permissions.
2469
        $sql = "DELETE FROM $tbl_user_permissions
2470
                WHERE user_id = $user_id";
2471
        Database::query($sql);
2472
    }
2473
2474
    /**
2475
     * Displays the form to register users in a blog (in a course)
2476
     * The listed users are users subscribed in the course.
2477
     *
2478
     * @author Toon Keppens
2479
     *
2480
     * @param int $blog_id
2481
     *
2482
     * @return string html Form with sortable table with users to subcribe in a blog, in a course
2483
     */
2484
    public static function displayUserSubscriptionForm($blog_id)
2485
    {
2486
        $_course = api_get_course_info();
2487
        $is_western_name_order = api_is_western_name_order();
2488
        $session_id = api_get_session_id();
2489
        $course_id = $_course['real_id'];
2490
        $blog_id = intval($blog_id);
2491
2492
        $currentCourse = $_course['code'];
2493
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2494
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
2495
        $html = null;
2496
2497
        $html .= '<legend>'.get_lang('SubscribeMembers').'</legend>';
2498
2499
        // Get blog members' id.
2500
        $sql = "SELECT user.user_id FROM $tbl_users user
2501
                INNER JOIN $tbl_blogs_rel_user blogs_rel_user
2502
                ON user.user_id = blogs_rel_user.user_id
2503
                WHERE blogs_rel_user.c_id = $course_id AND blogs_rel_user.blog_id = $blog_id";
2504
        $result = Database::query($sql);
2505
2506
        $blog_member_ids = [];
2507
        while ($user = Database::fetch_array($result)) {
2508
            $blog_member_ids[] = $user['user_id'];
2509
        }
2510
2511
        // Set table headers
2512
        $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...
2513
        if ($is_western_name_order) {
2514
            $column_header[] = [get_lang('FirstName'), true, ''];
2515
            $column_header[] = [get_lang('LastName'), true, ''];
2516
        } else {
2517
            $column_header[] = [get_lang('LastName'), true, ''];
2518
            $column_header[] = [get_lang('FirstName'), true, ''];
2519
        }
2520
        $column_header[] = [get_lang('Email'), false, ''];
2521
        $column_header[] = [get_lang('Register'), false, ''];
2522
2523
        $student_list = CourseManager:: get_student_list_from_course_code(
2524
            $currentCourse,
2525
            false,
2526
            $session_id
2527
        );
2528
        $user_data = [];
2529
2530
        // Add users that are not in this blog to the list.
2531
        foreach ($student_list as $key => $user) {
2532
            if (isset($user['id_user'])) {
2533
                $user['user_id'] = $user['id_user'];
2534
            }
2535
            if (!in_array($user['user_id'], $blog_member_ids)) {
2536
                $a_infosUser = api_get_user_info($user['user_id']);
2537
                $row = [];
2538
                $row[] = '<input type="checkbox" name="user[]" value="'.$a_infosUser['user_id'].'" '.((isset($_GET['selectall']) && $_GET['selectall'] == "subscribe") ? ' checked="checked" ' : '').'/>';
2539
                $username = api_htmlentities(sprintf(get_lang('LoginX'), $a_infosUser["username"]), ENT_QUOTES);
2540
                if ($is_western_name_order) {
2541
                    $row[] = $a_infosUser["firstname"];
2542
                    $row[] = Display::tag(
2543
                        'span',
2544
                        $a_infosUser["lastname"],
2545
                        ['title' => $username]
2546
                    );
2547
                } else {
2548
                    $row[] = Display::tag(
2549
                        'span',
2550
                        $a_infosUser["lastname"],
2551
                        ['title' => $username]
2552
                    );
2553
                    $row[] = $a_infosUser["firstname"];
2554
                }
2555
                $row[] = Display::icon_mailto_link($a_infosUser['email']);
2556
2557
                // Link to register users
2558
                if ($a_infosUser['user_id'] != api_get_user_id()) {
2559
                    $row[] = Display::url(
2560
                        get_lang('Register'),
2561
                        api_get_self()."?action=manage_members&blog_id=$blog_id&register=yes&user_id=".$a_infosUser["user_id"].'&'.api_get_cidreq(),
2562
                        ['class' => 'btn btn-primary']
2563
                    );
2564
                } else {
2565
                    $row[] = '';
2566
                }
2567
                $user_data[] = $row;
2568
            }
2569
        }
2570
2571
        // Display
2572
        $query_vars['action'] = 'manage_members';
2573
        $query_vars['blog_id'] = $blog_id;
2574
        $html .= '<form
2575
                class="form-inline"
2576
                method="post"
2577
                action="blog.php?action=manage_members&blog_id='.$blog_id.'&'.api_get_cidreq().'">';
2578
        $html .= Display::return_sortable_table($column_header, $user_data, null, null, $query_vars);
2579
2580
        $link = isset($_GET['action']) ? 'action='.Security::remove_XSS($_GET['action']).'&' : '';
2581
        $link .= "blog_id=$blog_id&".api_get_cidreq();
2582
2583
        $html .= '<a
2584
                class="btn btn-default" href="blog.php?'.$link.'selectall=subscribe">'.
2585
            get_lang('SelectAll').'</a> - ';
2586
        $html .= '<a class="btn btn-default" href="blog.php?'.$link.'">'.get_lang('UnSelectAll').'</a> ';
2587
        $html .= '<div class="form-group">';
2588
        $html .= '<label>';
2589
        $html .= get_lang('WithSelected').' : ';
2590
        $html .= '</label>';
2591
        $html .= '<select class="selectpicker" name="action">';
2592
        $html .= '<option value="select_subscribe">'.get_lang('Register').'</option>';
2593
        $html .= '</select>';
2594
        $html .= '<input type="hidden" name="register" value="true" />';
2595
        $html .= '<button class="btn btn-default" type="submit">'.get_lang('Ok').'</button>';
2596
        $html .= '</div>';
2597
        $html .= '</form>';
2598
2599
        return $html;
2600
    }
2601
2602
    /**
2603
     * Displays the form to register users in a blog (in a course)
2604
     * The listed users are users subcribed in the course.
2605
     *
2606
     * @author Toon Keppens
2607
     *
2608
     * @param int $blog_id
2609
     *
2610
     * @return false|null form with sortable table with users to unsubcribe from a blog
2611
     */
2612
    public static function displayUserUnsubscriptionForm($blog_id)
2613
    {
2614
        $_user = api_get_user_info();
2615
        $is_western_name_order = api_is_western_name_order();
2616
        $html = null;
2617
2618
        // Init
2619
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2620
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
2621
        $blog_id = intval($blog_id);
2622
2623
        $html .= '<legend>'.get_lang('UnsubscribeMembers').'</legend>';
2624
2625
        //table column titles
2626
        $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...
2627
        if ($is_western_name_order) {
2628
            $column_header[] = [get_lang('FirstName'), true, ''];
2629
            $column_header[] = [get_lang('LastName'), true, ''];
2630
        } else {
2631
            $column_header[] = [get_lang('LastName'), true, ''];
2632
            $column_header[] = [get_lang('FirstName'), true, ''];
2633
        }
2634
        $column_header[] = [get_lang('Email'), false, ''];
2635
        $column_header[] = [get_lang('TaskManager'), true, ''];
2636
        $column_header[] = [get_lang('UnRegister'), false, ''];
2637
2638
        $course_id = api_get_course_int_id();
2639
2640
        $sql = "SELECT user.user_id, user.lastname, user.firstname, user.email, user.username
2641
                FROM $tbl_users user
2642
                INNER JOIN $tbl_blogs_rel_user blogs_rel_user
2643
                ON user.user_id = blogs_rel_user.user_id
2644
                WHERE blogs_rel_user.c_id = $course_id AND  blogs_rel_user.blog_id = $blog_id";
2645
2646
        if (!($sql_result = Database::query($sql))) {
2647
            return false;
2648
        }
2649
2650
        $user_data = [];
2651
        while ($myrow = Database::fetch_array($sql_result)) {
2652
            $row = [];
2653
            $row[] = '<input
2654
                type="checkbox"
2655
                name="user[]"
2656
                value="'.$myrow['user_id'].'" '.((isset($_GET['selectall']) && $_GET['selectall'] == "unsubscribe") ? ' checked="checked" ' : '').'/>';
2657
            $username = api_htmlentities(sprintf(get_lang('LoginX'), $myrow["username"]), ENT_QUOTES);
2658
            if ($is_western_name_order) {
2659
                $row[] = $myrow["firstname"];
2660
                $row[] = Display::tag(
2661
                    'span',
2662
                    $myrow["lastname"],
2663
                    ['title' => $username]
2664
                );
2665
            } else {
2666
                $row[] = Display::tag(
2667
                    'span',
2668
                    $myrow["lastname"],
2669
                    ['title' => $username]
2670
                );
2671
                $row[] = $myrow["firstname"];
2672
            }
2673
            $row[] = Display::icon_mailto_link($myrow["email"]);
2674
2675
            $sql = "SELECT bt.title task
2676
                    FROM ".Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER)." btu
2677
                    INNER JOIN ".Database::get_course_table(TABLE_BLOGS_TASKS)." bt
2678
                    ON btu.task_id = bt.task_id
2679
                    WHERE 	btu.c_id 	= $course_id  AND
2680
                            bt.c_id 	= $course_id  AND
2681
                            btu.blog_id = $blog_id AND
2682
                            btu.user_id = ".$myrow['user_id'];
2683
            $sql_res = Database::query($sql);
2684
            $task = '';
2685
            while ($r = Database::fetch_array($sql_res)) {
2686
                $task .= stripslashes($r['task']).', ';
2687
            }
2688
            $task = (api_strlen(trim($task)) != 0) ? api_substr($task, 0, api_strlen($task) - 2) : get_lang('Reader');
2689
            $row[] = $task;
2690
            //Link to register users
2691
2692
            if ($myrow["user_id"] != $_user['user_id']) {
2693
                $row[] = Display::url(
2694
                    get_lang('UnRegister'),
2695
                    api_get_self()."?action=manage_members&blog_id=$blog_id&unregister=yes&user_id=".$myrow['user_id'].'&'.api_get_cidreq(),
2696
                    ['class' => 'btn btn-primary']
2697
                );
2698
            } else {
2699
                $row[] = '';
2700
            }
2701
            $user_data[] = $row;
2702
        }
2703
2704
        $query_vars['action'] = 'manage_members';
2705
        $query_vars['blog_id'] = $blog_id;
2706
        $html .= '<form
2707
            class="form-inline"
2708
            method="post"
2709
            action="blog.php?action=manage_members&blog_id='.$blog_id.'&'.api_get_cidreq().'">';
2710
        $html .= Display::return_sortable_table($column_header, $user_data, null, null, $query_vars);
2711
2712
        $link = isset($_GET['action']) ? 'action='.Security::remove_XSS($_GET['action']).'&' : '';
2713
        $link .= "blog_id=$blog_id&".api_get_cidreq();
2714
2715
        $html .= '<a class="btn btn-default" href="blog.php?'.$link.'selectall=unsubscribe">'.get_lang('SelectAll').'</a> - ';
2716
        $html .= '<a class="btn btn-default" href="blog.php?'.$link.'">'.get_lang('UnSelectAll').'</a> ';
2717
        $html .= '<div class="form-group">';
2718
        $html .= '<label>';
2719
        $html .= get_lang('WithSelected').' : ';
2720
        $html .= '</label>';
2721
        $html .= '<select name="action" class="selectpicker">';
2722
        $html .= '<option value="select_unsubscribe">'.get_lang('UnRegister').'</option>';
2723
        $html .= '</select>';
2724
        $html .= '<input type="hidden" name="unregister" value="true" />';
2725
        $html .= '<button class="btn btn-default" type="submit">'.get_lang('Ok').'</button>';
2726
        $html .= '</div>';
2727
        $html .= '</form>';
2728
2729
        return $html;
2730
    }
2731
2732
    /**
2733
     * Displays a matrix with selectboxes. On the left: users, on top: possible rights.
2734
     * The blog admin can thus select what a certain user can do in the current blog.
2735
     *
2736
     * @param int $blog_id
2737
     *
2738
     * @return string
2739
     */
2740
    public static function displayUserRightsForm($blog_id)
2741
    {
2742
        ob_start();
2743
        echo '<legend>'.get_lang('RightsManager').'</legend>';
2744
        echo '<br />';
2745
2746
        // Integration of patricks permissions system.
2747
        require_once api_get_path(SYS_CODE_PATH).'permissions/blog_permissions.inc.php';
2748
        $content = ob_get_contents();
2749
        ob_get_clean();
2750
2751
        return $content;
2752
    }
2753
2754
    /**
2755
     * show the calender of the given month.
2756
     *
2757
     * @author Patrick Cool
2758
     * @author Toon Keppens
2759
     *
2760
     * @param int $month   The integer value of the month we are viewing
2761
     * @param int $year    The 4-digit year indication e.g. 2005
2762
     * @param int $blog_id
2763
     *
2764
     * @return string html code
2765
     */
2766
    public static function displayMiniMonthCalendar($month, $year, $blog_id)
2767
    {
2768
        $_user = api_get_user_info();
2769
        global $DaysShort;
2770
        global $MonthsLong;
2771
        $html = null;
2772
2773
        $posts = [];
2774
        $tasks = [];
2775
2776
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2777
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
2778
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
2779
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2780
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
2781
2782
        $course_id = api_get_course_int_id();
2783
        $blog_id = intval($blog_id);
2784
        $month = intval($month);
2785
        $year = intval($year);
2786
2787
        //Handle leap year
2788
        $numberofdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
2789
2790
        if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 != 0)) {
2791
            $numberofdays[2] = 29;
2792
        }
2793
2794
        //Get the first day of the month
2795
        $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
2796
        $monthName = $MonthsLong[$month - 1];
2797
        $url = api_get_path(WEB_CODE_PATH).'blog/blog.php?'.api_get_cidreq();
2798
        //Start the week on monday
2799
        $startdayofweek = $dayone['wday'] != 0 ? ($dayone['wday'] - 1) : 6;
2800
        $blogId = isset($_GET['blog_id']) ? intval($_GET['blog_id']) : null;
2801
        $filter = isset($_GET['filter']) ? Security::remove_XSS($_GET['filter']) : null;
2802
        $backwardsURL = $url."&blog_id=".$blogId."&filter=".$filter."&month=".($month == 1 ? 12 : $month - 1)."&year=".($month == 1 ? $year - 1 : $year);
2803
        $forewardsURL = $url."&blog_id=".$blogId."&filter=".$filter."&month=".($month == 12 ? 1 : $month + 1)."&year=".($month == 12 ? $year + 1 : $year);
2804
2805
        // Get posts for this month
2806
        $sql = "SELECT post.*, DAYOFMONTH(date_creation) as post_day, user.lastname, user.firstname
2807
                FROM $tbl_blogs_posts post
2808
                INNER JOIN $tbl_users user
2809
                ON post.author_id = user.user_id
2810
                WHERE
2811
                    post.c_id = $course_id AND
2812
                    post.blog_id = $blog_id AND
2813
                    MONTH(date_creation) = '$month' AND
2814
                    YEAR(date_creation) = '$year'
2815
                ORDER BY date_creation";
2816
        $result = Database::query($sql);
2817
        // We will create an array of days on which there are posts.
2818
        if (Database::num_rows($result) > 0) {
2819
            while ($blog_post = Database::fetch_array($result)) {
2820
                // If the day of this post is not yet in the array, add it.
2821
                if (!in_array($blog_post['post_day'], $posts)) {
2822
                    $posts[] = $blog_post['post_day'];
2823
                }
2824
            }
2825
        }
2826
2827
        // Get tasks for this month
2828
        if ($_user['user_id']) {
2829
            $sql = "SELECT
2830
                        task_rel_user.*,
2831
                        DAYOFMONTH(target_date) as task_day,
2832
                        task.title,
2833
                        blog.blog_name
2834
                    FROM $tbl_blogs_tasks_rel_user task_rel_user
2835
                    INNER JOIN $tbl_blogs_tasks task
2836
                    ON task_rel_user.task_id = task.task_id
2837
                    INNER JOIN $tbl_blogs blog
2838
                    ON task_rel_user.blog_id = blog.blog_id
2839
                    WHERE
2840
                        task_rel_user.c_id = $course_id AND
2841
                        task.c_id = $course_id AND
2842
                        blog.c_id = $course_id AND
2843
                        task_rel_user.user_id = ".$_user['user_id']." AND
2844
                        MONTH(target_date) = '$month' AND
2845
                        YEAR(target_date) = '$year'
2846
                    ORDER BY target_date ASC";
2847
            $result = Database::query($sql);
2848
            if (Database::num_rows($result) > 0) {
2849
                while ($mytask = Database::fetch_array($result)) {
2850
                    $tasks[$mytask['task_day']][$mytask['task_id']]['task_id'] = $mytask['task_id'];
2851
                    $tasks[$mytask['task_day']][$mytask['task_id']]['title'] = $mytask['title'];
2852
                    $tasks[$mytask['task_day']][$mytask['task_id']]['blog_id'] = $mytask['blog_id'];
2853
                    $tasks[$mytask['task_day']][$mytask['task_id']]['blog_name'] = $mytask['blog_name'];
2854
                    $tasks[$mytask['task_day']][$mytask['task_id']]['day'] = $mytask['task_day'];
2855
                }
2856
            }
2857
        }
2858
2859
        $html .= '<table id="smallcalendar" class="table table-responsive">
2860
                <tr id="title">
2861
                <th width="10%"><a href="'.$backwardsURL.'">&laquo;</a></th>
2862
                <th align="center" width="80%" colspan="5" class="month">'.$monthName.' '.$year.'</th>
2863
                <th width="10%" align="right"><a href="'.$forewardsURL.'">&raquo;</a></th></tr>';
2864
2865
        $html .= '<tr>';
2866
        for ($ii = 1; $ii < 8; $ii++) {
2867
            $html .= '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
2868
        }
2869
        $html .= '</tr>';
2870
        $curday = -1;
2871
        $today = getdate();
2872
2873
        while ($curday <= $numberofdays[$month]) {
2874
            $html .= '<tr>';
2875
            for ($ii = 0; $ii < 7; $ii++) {
2876
                if (($curday == -1) && ($ii == $startdayofweek)) {
2877
                    $curday = 1;
2878
                }
2879
2880
                if (($curday > 0) && ($curday <= $numberofdays[$month])) {
2881
                    $bgcolor = $ii < 5 ? $class = "class=\"days_week\"" : $class = "class=\"days_weekend\"";
2882
                    $dayheader = "$curday";
2883
2884
                    if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
2885
                        $dayheader = "$curday";
2886
                        $class = "class=\"days_today\"";
2887
                    }
2888
2889
                    $html .= '<td '.$class.'>';
2890
                    // If there are posts on this day, create a filter link.
2891
                    if (in_array($curday, $posts)) {
2892
                        $html .= '<a
2893
                        href="'.$url.'&blog_id='.$blog_id.'&filter='.$year.'-'.$month.'-'.$curday.'&month='.$month.'&year='.$year.'"
2894
                        title="'.get_lang('ViewPostsOfThisDay').'">'.$curday.'</a>';
2895
                    } else {
2896
                        $html .= $dayheader;
2897
                    }
2898
2899
                    if (count($tasks) > 0) {
2900
                        if (isset($tasks[$curday]) && is_array($tasks[$curday])) {
2901
                            // Add tasks to calendar
2902
                            foreach ($tasks[$curday] as $task) {
2903
                                $html .= '<a
2904
                                    href="blog.php?action=execute_task&blog_id='.$task['blog_id'].'&task_id='.stripslashes($task['task_id']).'" title="'.$task['title'].' : '.get_lang('InBlog').' : '.$task['blog_name'].' - '.get_lang('ExecuteThisTask').'">';
2905
                                $html .= Display::return_icon('blog_task.gif', get_lang('ExecuteThisTask'));
2906
                                $html .= '</a>';
2907
                            }
2908
                        }
2909
                    }
2910
2911
                    $html .= '</td>';
2912
                    $curday++;
2913
                } else {
2914
                    $html .= '<td>&nbsp;</td>';
2915
                }
2916
            }
2917
            $html .= '</tr>';
2918
        }
2919
        $html .= '</table>';
2920
2921
        return $html;
2922
    }
2923
2924
    /**
2925
     * Blog admin | Display the form to add a new blog.
2926
     */
2927
    public static function displayBlogCreateForm()
2928
    {
2929
        $form = new FormValidator(
2930
            'add_blog',
2931
            'post',
2932
            'blog_admin.php?action=add&'.api_get_cidreq()
2933
        );
2934
        $form->addElement('header', get_lang('AddBlog'));
2935
        $form->addElement('text', 'blog_name', get_lang('Title'));
2936
        $form->addElement('textarea', 'blog_subtitle', get_lang('SubTitle'));
2937
        $form->addElement('hidden', 'new_blog_submit', 'true');
2938
        $form->addButtonSave(get_lang('SaveProject'));
2939
2940
        $defaults = [
2941
            'blog_name' => isset($_POST['blog_name']) ? Security::remove_XSS($_POST['blog_name']) : null,
2942
            'blog_subtitle' => isset($_POST['blog_subtitle']) ? Security::remove_XSS($_POST['blog_subtitle']) : null,
2943
        ];
2944
        $form->setDefaults($defaults);
2945
        $form->display();
2946
    }
2947
2948
    /**
2949
     * Blog admin | Display the form to edit a blog.
2950
     *
2951
     * @param int $blog_id
2952
     */
2953
    public static function displayBlogEditForm($blog_id)
2954
    {
2955
        $course_id = api_get_course_int_id();
2956
        $blog_id = intval($blog_id);
2957
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
2958
2959
        $sql = "SELECT blog_id, blog_name, blog_subtitle
2960
                FROM $tbl_blogs
2961
                WHERE c_id = $course_id AND blog_id = $blog_id";
2962
        $result = Database::query($sql);
2963
        $blog = Database::fetch_array($result);
2964
2965
        // the form contained errors but we do not want to lose the changes the user already did
2966
        if ($_POST) {
2967
            $blog['blog_name'] = Security::remove_XSS($_POST['blog_name']);
2968
            $blog['blog_subtitle'] = Security::remove_XSS($_POST['blog_subtitle']);
2969
        }
2970
2971
        $form = new FormValidator(
2972
            'edit_blog',
2973
            'post',
2974
            'blog_admin.php?action=edit&blog_id='.intval($_GET['blog_id'])
2975
        );
2976
        $form->addElement('header', get_lang('EditBlog'));
2977
        $form->addElement('text', 'blog_name', get_lang('Title'));
2978
        $form->addElement('textarea', 'blog_subtitle', get_lang('SubTitle'));
2979
        $form->addElement('hidden', 'edit_blog_submit', 'true');
2980
        $form->addElement('hidden', 'blog_id', $blog['blog_id']);
2981
        $form->addButtonSave(get_lang('Save'));
2982
2983
        $defaults = [];
2984
        $defaults['blog_name'] = $blog['blog_name'];
2985
        $defaults['blog_subtitle'] = $blog['blog_subtitle'];
2986
        $form->setDefaults($defaults);
2987
        $form->display();
2988
    }
2989
2990
    /**
2991
     * Blog admin | Returns table with blogs in this course.
2992
     */
2993
    public static function displayBlogsList()
2994
    {
2995
        global $charset;
2996
        $_user = api_get_user_info();
2997
        $course_id = api_get_course_int_id();
2998
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
2999
3000
        //condition for the session
3001
        $session_id = api_get_session_id();
3002
3003
        $sql = "SELECT blog_name, blog_subtitle, visibility, blog_id, session_id
3004
                FROM $tbl_blogs WHERE c_id = $course_id
3005
                ORDER BY date_creation DESC";
3006
        $result = Database::query($sql);
3007
        $list_info = [];
3008
        if (Database::num_rows($result)) {
3009
            while ($row_project = Database::fetch_row($result)) {
3010
                $list_info[] = $row_project;
3011
            }
3012
        }
3013
3014
        $list_content_blog = [];
3015
        $list_body_blog = [];
3016
3017
        if (is_array($list_info)) {
3018
            foreach ($list_info as $key => $info_log) {
3019
                // Validation when belongs to a session
3020
                $session_img = api_get_session_image($info_log[4], $_user['status']);
3021
3022
                $url_start_blog = 'blog.php'."?"."blog_id=".$info_log[3]."&".api_get_cidreq();
3023
                $title = Security::remove_XSS($info_log[0]);
3024
                $image = Display::return_icon('blog.png', $title);
3025
                $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;
3026
3027
                $list_body_blog[] = $list_name;
3028
                $list_body_blog[] = Security::remove_XSS($info_log[1]);
3029
3030
                $visibility_icon = ($info_log[2] == 0) ? 'invisible' : 'visible';
3031
                $visibility_info = ($info_log[2] == 0) ? 'Visible' : 'Invisible';
3032
3033
                $my_image = '<a href="'.api_get_self().'?action=visibility&blog_id='.$info_log[3].'">';
3034
                $my_image .= Display::return_icon($visibility_icon.'.png', get_lang($visibility_info));
3035
                $my_image .= "</a>";
3036
3037
                $my_image .= '<a href="'.api_get_self().'?action=edit&blog_id='.$info_log[3].'">';
3038
                $my_image .= Display::return_icon('edit.png', get_lang('EditBlog'));
3039
                $my_image .= "</a>";
3040
3041
                $my_image .= '<a href="'.api_get_self().'?action=delete&blog_id='.$info_log[3].'" ';
3042
                $my_image .= 'onclick="javascript:if(!confirm(\''.addslashes(
3043
                        api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)
3044
                    ).'\')) return false;" >';
3045
                $my_image .= Display::return_icon('delete.png', get_lang('DeleteBlog'));
3046
                $my_image .= "</a>";
3047
3048
                $list_body_blog[] = $my_image;
3049
                $list_content_blog[] = $list_body_blog;
3050
                $list_body_blog = [];
3051
            }
3052
3053
            $table = new SortableTableFromArrayConfig(
3054
                $list_content_blog,
3055
                1,
3056
                20,
3057
                'project'
3058
            );
3059
            $table->set_header(0, get_lang('Title'));
3060
            $table->set_header(1, get_lang('SubTitle'));
3061
            $table->set_header(2, get_lang('Modify'));
3062
            $table->display();
3063
        }
3064
    }
3065
3066
    /**
3067
     * Show a list with all the attachments according the parameter's.
3068
     *
3069
     * @param int $blog_id    the blog's id
3070
     * @param int $post_id    the post's id
3071
     * @param int $comment_id the comment's id
3072
     *
3073
     * @return array with the post info according the parameters
3074
     *
3075
     * @author Julio Montoya
3076
     *
3077
     * @version avril 2008, dokeos 1.8.5
3078
     */
3079
    public static function getBlogAttachments($blog_id, $post_id = 0, $comment_id = 0)
3080
    {
3081
        $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
3082
3083
        $blog_id = intval($blog_id);
3084
        $comment_id = intval($comment_id);
3085
        $post_id = intval($post_id);
3086
        $row = [];
3087
        $where = '';
3088
        if (!empty($post_id) && is_numeric($post_id)) {
3089
            $where .= " AND post_id = $post_id ";
3090
        }
3091
3092
        if (!empty($comment_id) && is_numeric($comment_id)) {
3093
            if (!empty($post_id)) {
3094
                $where .= ' AND ';
3095
            }
3096
            $where .= " comment_id = $comment_id ";
3097
        }
3098
3099
        $course_id = api_get_course_int_id();
3100
3101
        $sql = "SELECT path, filename, comment
3102
                FROM $blog_table_attachment
3103
	            WHERE c_id = $course_id AND blog_id = $blog_id
3104
	            $where";
3105
3106
        $result = Database::query($sql);
3107
        if (Database::num_rows($result) != 0) {
3108
            $row = Database::fetch_array($result);
3109
        }
3110
3111
        return $row;
3112
    }
3113
3114
    /**
3115
     * Delete the all the attachments according the parameters.
3116
     *
3117
     * @param int $blog_id
3118
     * @param int $post_id    post's id
3119
     * @param int $comment_id the comment's id
3120
     *
3121
     * @author Julio Montoya
3122
     *
3123
     * @version avril 2008, dokeos 1.8.5
3124
     */
3125
    public static function deleteAllBlogAttachments(
3126
        $blog_id,
3127
        $post_id = 0,
3128
        $comment_id = 0
3129
    ) {
3130
        $_course = api_get_course_info();
3131
        $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
3132
        $blog_id = intval($blog_id);
3133
        $comment_id = intval($comment_id);
3134
        $post_id = intval($post_id);
3135
3136
        $course_id = api_get_course_int_id();
3137
        $where = null;
3138
3139
        // delete files in DB
3140
        if (!empty($post_id) && is_numeric($post_id)) {
3141
            $where .= " AND post_id = $post_id ";
3142
        }
3143
3144
        if (!empty($comment_id) && is_numeric($comment_id)) {
3145
            if (!empty($post_id)) {
3146
                $where .= ' AND ';
3147
            }
3148
            $where .= " comment_id = $comment_id ";
3149
        }
3150
3151
        // delete all files in directory
3152
        $courseDir = $_course['path'].'/upload/blog';
3153
        $sys_course_path = api_get_path(SYS_COURSE_PATH);
3154
        $updir = $sys_course_path.$courseDir;
3155
3156
        $sql = "SELECT path FROM $blog_table_attachment
3157
	        WHERE c_id = $course_id AND blog_id = $blog_id $where";
3158
        $result = Database::query($sql);
3159
3160
        while ($row = Database::fetch_row($result)) {
3161
            $file = $updir.'/'.$row[0];
3162
            if (Security::check_abs_path($file, $updir)) {
3163
                @unlink($file);
3164
            }
3165
        }
3166
        $sql = "DELETE FROM $blog_table_attachment
3167
	        WHERE c_id = $course_id AND  blog_id = $blog_id $where";
3168
        Database::query($sql);
3169
    }
3170
3171
    /**
3172
     * Gets all the post from a given user id.
3173
     *
3174
     * @param int    $courseId
3175
     * @param int    $userId
3176
     * @param string $courseCode
3177
     *
3178
     * @return string
3179
     */
3180
    public static function getBlogPostFromUser($courseId, $userId, $courseCode)
3181
    {
3182
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
3183
        $tbl_blog_post = Database::get_course_table(TABLE_BLOGS_POSTS);
3184
        $courseId = intval($courseId);
3185
        $userId = intval($userId);
3186
3187
        $sql = "SELECT DISTINCT blog.blog_id, post_id, title, full_text, post.date_creation
3188
                FROM $tbl_blogs blog
3189
                INNER JOIN $tbl_blog_post post
3190
                ON (blog.blog_id = post.blog_id AND blog.c_id = post.c_id)
3191
                WHERE
3192
                    blog.c_id = $courseId AND
3193
                    post.c_id = $courseId AND
3194
                    author_id =  $userId AND
3195
                    visibility = 1
3196
                ORDER BY post.date_creation DESC ";
3197
        $result = Database::query($sql);
3198
        $return_data = '';
3199
3200
        if (Database::num_rows($result) != 0) {
3201
            while ($row = Database::fetch_array($result)) {
3202
                $return_data .= '<div class="clear"></div><br />';
3203
                $return_data .= '<div class="actions" style="margin-left:5px;margin-right:5px;">'.
3204
                    Display::return_icon(
3205
                        'blog_article.png',
3206
                        get_lang('BlogPosts')
3207
                    ).' '.
3208
                    $row['title'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
3209
                    <div style="float:right;margin-top:-18px">
3210
                    <a href="../blog/blog.php?blog_id='.$row['blog_id'].'&gidReq=&cidReq='.$courseCode.' " >'.
3211
                    get_lang('SeeBlog').'</a></div></div>';
3212
                $return_data .= '<br / >';
3213
                $return_data .= $row['full_text'];
3214
                $return_data .= '<br /><br />';
3215
            }
3216
        }
3217
3218
        return $return_data;
3219
    }
3220
3221
    /**
3222
     * Gets all the post comments from a given user id.
3223
     *
3224
     * @param int    $courseId
3225
     * @param int    $userId
3226
     * @param string $courseCode
3227
     *
3228
     * @return string
3229
     */
3230
    public static function getBlogCommentsFromUser($courseId, $userId, $courseCode)
3231
    {
3232
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
3233
        $tbl_blog_comment = Database::get_course_table(TABLE_BLOGS_COMMENTS);
3234
3235
        $userId = intval($userId);
3236
        $courseId = intval($courseId);
3237
3238
        $sql = "SELECT DISTINCT blog.blog_id, comment_id, title, comment, comment.date_creation
3239
                FROM $tbl_blogs blog
3240
                INNER JOIN  $tbl_blog_comment comment
3241
                ON (blog.blog_id = comment.blog_id AND blog.c_id = comment.c_id)
3242
                WHERE 	blog.c_id = $courseId AND
3243
                        comment.c_id = $courseId AND
3244
                        author_id = $userId AND
3245
                        visibility = 1
3246
                ORDER BY blog_name";
3247
        $result = Database::query($sql);
3248
        $return_data = '';
3249
        if (Database::num_rows($result) != 0) {
3250
            while ($row = Database::fetch_array($result)) {
3251
                $return_data .= '<div class="clear"></div><br />';
3252
                $return_data .= '<div class="actions" style="margin-left:5px;margin-right:5px;">'.
3253
                    $row['title'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
3254
                        <div style="float:right;margin-top:-18px">
3255
                        <a href="../blog/blog.php?blog_id='.$row['blog_id'].'&gidReq=&cidReq='.Security::remove_XSS($courseCode).' " >'.
3256
                    get_lang('SeeBlog').'</a></div></div>';
3257
                $return_data .= '<br / >';
3258
                $return_data .= $row['comment'];
3259
                $return_data .= '<br />';
3260
            }
3261
        }
3262
3263
        return $return_data;
3264
    }
3265
3266
    /**
3267
     * Filter the post $fullText to get a extract of $length characters.
3268
     *
3269
     * @param string $fullText
3270
     * @param int    $length
3271
     *
3272
     * @return string|null
3273
     */
3274
    private static function getPostExtract($fullText, $length = BLOG_MAX_PREVIEW_CHARS)
3275
    {
3276
        $parts = explode(BLOG_PAGE_BREAK, $fullText);
3277
3278
        if (count($parts) > 1) {
3279
            return $parts[0];
3280
        }
3281
3282
        // Remove any HTML from the string
3283
        $text = strip_tags($fullText);
3284
        $text = api_html_entity_decode($text);
3285
        // Replace end of lines with spaces
3286
        $text = preg_replace('/\s+/', ' ', $text);
3287
        // Count whitespaces to add to the cut() call below
3288
        $countBlanks = substr_count($text, ' ');
3289
        // Get a version of the string without spaces for comparison purposes
3290
        $textWithoutBlanks = str_replace(' ', '', $text);
3291
        // utf8_decode replaces non-ISO chars by '?' which avoids counting
3292
        // multi-byte characters as more than one character
3293
        $stringLength = strlen(utf8_decode($textWithoutBlanks));
3294
3295
        if ($stringLength <= $length) {
3296
            return null;
3297
        }
3298
3299
        // Cut the string to the BLOG_MAX_PREVIEX_CHARS limit, adding
3300
        // whitespaces
3301
        $extract = cut($text, $length + $countBlanks);
3302
3303
        // Return an HTML string for printing
3304
        return api_htmlentities($extract);
3305
    }
3306
}
3307