Test Setup Failed
Push — master ( ec638a...cb9435 )
by Julito
51:10
created

Blog::displayMiniMonthCalendar()   F

Complexity

Conditions 33
Paths > 20000

Size

Total Lines 163
Code Lines 104

Duplication

Lines 9
Ratio 5.52 %

Importance

Changes 0
Metric Value
cc 33
eloc 104
nc 159744
nop 3
dl 9
loc 163
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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