Completed
Push — 1.10.x ( a9323e...dc10cd )
by Angel Fernando Quiroz
124:05 queued 70:15
created

Blog::displayUserSubscriptionForm()   F

Complexity

Conditions 11
Paths 280

Size

Total Lines 103
Code Lines 76

Duplication

Lines 19
Ratio 18.45 %

Importance

Changes 0
Metric Value
cc 11
eloc 76
nc 280
nop 1
dl 19
loc 103
rs 3.8181
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
     *
19
     * @param int $blog_id
20
     *
21
     * @return String Blog Title
22
     */
23 View Code Duplication
    public static function getBlogTitle($blog_id)
24
    {
25
        $course_id = api_get_course_int_id();
26
27
        if (is_numeric($blog_id)) {
28
            $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
29
30
            $sql = "SELECT blog_name
31
                    FROM ".$tbl_blogs."
32
                    WHERE c_id = $course_id AND blog_id = ".intval($blog_id);
33
34
            $result = Database::query($sql);
35
            $blog = Database::fetch_array($result);
36
37
            return stripslashes($blog['blog_name']);
38
        }
39
    }
40
41
    /**
42
     * Get the description of a blog
43
     * @author Toon Keppens
44
     *
45
     * @param Integer $blog_id
46
     *
47
     * @return String Blog description
48
     */
49 View Code Duplication
    public static function getBlogSubtitle($blog_id)
50
    {
51
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
52
        $course_id = api_get_course_int_id();
53
        $sql = "SELECT blog_subtitle FROM $tbl_blogs
54
                WHERE c_id = $course_id AND blog_id ='".intval($blog_id)."'";
55
        $result = Database::query($sql);
56
        $blog = Database::fetch_array($result);
57
58
        return stripslashes($blog['blog_subtitle']);
59
    }
60
61
    /**
62
     * Get the users of a blog
63
     * @author Toon Keppens
64
     * @param int $blog_id The ID of the blog
65
     * @return array Returns an array with [userid]=>[username]
66
     */
67
    public static function getBlogUsers($blog_id)
68
    {
69
        // Database table definitions
70
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
71
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
72
73
        $course_id = api_get_course_int_id();
74
75
        // Get blog members
76
        $sql = "SELECT user.user_id, user.firstname, user.lastname
77
                FROM  $tbl_blogs_rel_user blogs_rel_user
78
                INNER JOIN $tbl_users user
79
                ON (blogs_rel_user.user_id = user.user_id)
80
                WHERE
81
                    blogs_rel_user.c_id = $course_id AND
82
                    blogs_rel_user.blog_id = '".(int) $blog_id."'";
83
        $result = Database::query($sql);
84
        $blog_members = array();
85 View Code Duplication
        while ($user = Database::fetch_array($result)) {
86
            $blog_members[$user['user_id']] = api_get_person_name(
87
                $user['firstname'],
88
                $user['lastname']
89
            );
90
        }
91
92
		return $blog_members;
93
	}
94
95
    /**
96
     * Creates a new blog in the given course
97
     * @author Toon Keppens
98
     * @param string $title The title of the new blog
99
     * @param string $subtitle The description (or subtitle) of the new blog
100
     * @return void
101
     */
102
    public static function addBlog($title, $subtitle)
103
    {
104
        $_user = api_get_user_info();
105
        $course_id = api_get_course_int_id();
106
107
        $current_date = api_get_utc_datetime();
108
        $session_id = api_get_session_id();
109
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
110
        $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
111
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
112
113
		//verified if exist blog
114
		$sql = 'SELECT COUNT(*) as count FROM '.$tbl_blogs.'
115
			  	WHERE
116
			  	    c_id = '.$course_id.' AND
117
			  	    blog_name="'.Database::escape_string($title).'" AND
118
			  	    blog_subtitle="'.Database::escape_string($subtitle).'"';
119
        $res = Database::query($sql);
120
        $info_count = Database::result($res, 0, 0);
121
122
        if ($info_count == 0) {
123
			// Create the blog
124
            $params = [
125
				'blog_id' => 0,
126
                'c_id' => $course_id,
127
                'blog_name' => $title,
128
                'blog_subtitle' => $subtitle,
129
                'date_creation' => $current_date,
130
                'visibility' => 1,
131
                'session_id' => $session_id,
132
            ];
133
			$this_blog_id = Database::insert($tbl_blogs, $params);
134
135 View Code Duplication
			if ($this_blog_id > 0) {
136
                $sql = "UPDATE $tbl_blogs SET blog_id = iid WHERE iid = $this_blog_id";
137
                Database::query($sql);
138
139
				// insert into item_property
140
                api_item_property_update(
141
                    api_get_course_info(),
142
                    TOOL_BLOGS,
143
                    $this_blog_id,
144
                    'BlogAdded',
145
                    api_get_user_id()
146
                );
147
			}
148
149
			// Make first post. :)
150
            $params = [
151
				'post_id' => 0,
152
                'c_id' => $course_id,
153
                'title' => get_lang("Welcome"),
154
                'full_text' => get_lang('FirstPostText'),
155
                'date_creation' => $current_date,
156
                'blog_id' => $this_blog_id,
157
                'author_id' => $_user['user_id'],
158
            ];
159
            $postId = Database::insert($tbl_blogs_posts, $params);
160
            if ($postId) {
161
                $sql = "UPDATE $tbl_blogs_posts SET post_id = iid WHERE iid = $postId";
162
                Database::query($sql);
163
            }
164
165
            // Put it on course homepage
166
            $sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, session_id, target)
167
                    VALUES ($course_id, '".Database::escape_string(
168
                    $title
169
                )."','blog/blog.php?blog_id=".(int) $this_blog_id."','blog.gif','1','0','pastillegris.gif',0,'$session_id', '')";
170
            Database::query($sql);
171
172
            $toolId = Database::insert_id();
173
            if ($toolId) {
174
                $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $toolId";
175
                Database::query($sql);
176
            }
177
178
            // Subscribe the teacher to this blog
179
            Blog::subscribeUser($this_blog_id, $_user['user_id']);
180
        }
181
    }
182
183
    /**
184
     * Subscribes a user to a given blog
185
     * @author Toon Keppens
186
     *
187
     * @param Integer $blog_id
188
     * @param Integer $user_id
189
     */
190
    public static function subscribeUser($blog_id, $user_id)
191
    {
192
        // Init
193
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
194
        $tbl_user_permissions = Database::get_course_table(TABLE_PERMISSION_USER);
195
196
        $course_id = api_get_course_int_id();
197
198
        // Subscribe the user
199
        $sql = "INSERT INTO $tbl_blogs_rel_user (c_id, blog_id, user_id )
200
                VALUES ($course_id, '".(int) $blog_id."', '".(int) $user_id."');";
201
        Database::query($sql);
202
203
        // Give this user basic rights
204
        $sql = "INSERT INTO $tbl_user_permissions (c_id, user_id,tool,action)
205
                VALUES ($course_id, '".(int) $user_id."','BLOG_".(int) $blog_id."','article_add')";
206
        Database::query($sql);
207
208
        $id = Database::insert_id();
209
        if ($id) {
210
            $sql = "UPDATE $tbl_user_permissions SET id = iid WHERE iid = $id";
211
            Database::query($sql);
212
        }
213
214
        $sql = "INSERT INTO $tbl_user_permissions (c_id, user_id,tool,action)
215
                VALUES ($course_id, '".(int) $user_id."','BLOG_".(int) $blog_id."','article_comments_add')";
216
        Database::query($sql);
217
218
        $id = Database::insert_id();
219
        if ($id) {
220
            $sql = "UPDATE $tbl_user_permissions SET id = iid WHERE iid = $id";
221
            Database::query($sql);
222
        }
223
    }
224
225
    /**
226
     * Update title and subtitle of a blog in the given course
227
     * @author Toon Keppens
228
     * @param string $title
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
238
        // Update the blog
239
        $sql = "UPDATE $tbl_blogs SET
240
                blog_name = '".Database::escape_string($title)."',
241
                blog_subtitle = '".Database::escape_string($subtitle)."'
242
                WHERE
243
                    c_id = $course_id AND
244
                    blog_id ='".Database::escape_string((int) $blog_id)."'
245
                LIMIT 1";
246
		Database::query($sql);
247
248
		//update item_property (update)
249
        api_item_property_update(
250
            api_get_course_info(),
251
            TOOL_BLOGS,
252
            intval($blog_id),
253
            'BlogUpdated',
254
            api_get_user_id()
255
        );
256
257
        // Update course homepage link
258
        $sql = "UPDATE $tbl_tool SET
259
                name = '".Database::escape_string($title)."'
260
                WHERE c_id = $course_id AND link = 'blog/blog.php?blog_id=".(int) $blog_id."' 
261
                LIMIT 1";
262
        Database::query($sql);
263
    }
264
265
    /**
266
     * Deletes a blog and it's posts from the course database
267
     * @author Toon Keppens
268
     * @param Integer $blog_id The internal blog ID
269
     * @return void
270
     */
271
    public static function deleteBlog($blog_id)
272
    {
273
        // Init
274
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
275
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
276
        $tbl_blogs_comment = Database::get_course_table(TABLE_BLOGS_COMMENTS);
277
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
278
        $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
279
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
280
281
        $course_id = api_get_course_int_id();
282
        $blog_id = intval($blog_id);
283
284
        // Delete posts from DB and the attachments
285
        self::deleteAllBlogAttachments($blog_id);
286
287
		//Delete comments
288
		$sql = "DELETE FROM $tbl_blogs_comment WHERE c_id = $course_id AND blog_id ='".$blog_id."'";
289
   		Database::query($sql);
290
291
		// Delete posts
292
   		$sql = "DELETE FROM $tbl_blogs_posts WHERE c_id = $course_id AND blog_id ='".$blog_id."'";
293
   		Database::query($sql);
294
295
		// Delete tasks
296
		$sql = "DELETE FROM $tbl_blogs_tasks WHERE c_id = $course_id AND blog_id ='".$blog_id."'";
297
		Database::query($sql);
298
299
		// Delete ratings
300
		$sql = "DELETE FROM $tbl_blogs_rating WHERE c_id = $course_id AND blog_id ='".$blog_id."'";
301
		Database::query($sql);
302
303
        // Delete blog
304
        $sql = "DELETE FROM $tbl_blogs WHERE c_id = $course_id AND blog_id ='".$blog_id."'";
305
        Database::query($sql);
306
307
		// Delete from course homepage
308
		$sql = "DELETE FROM $tbl_tool WHERE c_id = $course_id AND link = 'blog/blog.php?blog_id=".$blog_id."'";
309
		Database::query($sql);
310
311
		//update item_property (delete)
312
        api_item_property_update(
313
            api_get_course_info(),
314
            TOOL_BLOGS,
315
            $blog_id,
316
            'delete',
317
            api_get_user_id()
318
        );
319
    }
320
321
    /**
322
     * Creates a new post in a given blog
323
     * @author Toon Keppens
324
     * @param String $title
325
     * @param String $full_text
326
     * @param Integer $blog_id
327
     */
328
    public static function createPost($title, $full_text, $file_comment, $blog_id)
329
    {
330
        $_user = api_get_user_info();
331
        $_course = api_get_course_info();
332
        $course_id = $_course['real_id'];
333
334
        $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
335
        $upload_ok = true;
336
        $has_attachment = false;
337
        $current_date = api_get_utc_datetime();
338
339 View Code Duplication
        if (!empty($_FILES['user_upload']['name'])) {
340
            $upload_ok = process_uploaded_file($_FILES['user_upload']);
341
            $has_attachment = true;
342
        }
343
344
		if ($upload_ok) {
345
			// Table Definitions
346
			$tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
347
348
            // Create the post
349
            $sql = "INSERT INTO $tbl_blogs_posts (c_id, title, full_text, date_creation, blog_id, author_id )
350
                    VALUES ($course_id, '".Database::escape_string($title)."', '".Database::escape_string(
351
                    $full_text
352
                )."','".$current_date."', '".(int) $blog_id."', '".(int) $_user['user_id']."');";
353
354
			Database::query($sql);
355
			$last_post_id = Database::insert_id();
356
357
            if ($last_post_id) {
358
                $sql = "UPDATE $tbl_blogs_posts SET post_id = iid WHERE iid = $last_post_id";
359
                Database::query($sql);
360
            }
361
362 View Code Duplication
            if ($has_attachment) {
363
                $courseDir = $_course['path'].'/upload/blog';
364
                $sys_course_path = api_get_path(SYS_COURSE_PATH);
365
                $updir = $sys_course_path.$courseDir;
366
367
                // Try to add an extension to the file if it hasn't one
368
                $new_file_name = add_ext_on_mime(
369
                    stripslashes($_FILES['user_upload']['name']),
370
                    $_FILES['user_upload']['type']
371
                );
372
373
                // user's file name
374
                $file_name = $_FILES['user_upload']['name'];
375
376
                if (!filter_extension($new_file_name)) {
377
                    Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
378
                } else {
379
                    $new_file_name = uniqid('');
380
                    $new_path = $updir.'/'.$new_file_name;
381
                    $result = @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path);
382
                    $comment = Database::escape_string($file_comment);
383
384
                    // Storing the attachments if any
385
                    if ($result) {
386
                        $sql = 'INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size, blog_id,comment_id) '.
387
                            "VALUES ($course_id, '".Database::escape_string(
388
                                $file_name
389
                            )."', '".$comment."', '".Database::escape_string(
390
                                $new_file_name
391
                            )."' , '".$last_post_id."', '".intval(
392
                                $_FILES['user_upload']['size']
393
                            )."',  '".$blog_id."', '0' )";
394
                        Database::query($sql);
395
                        $id = Database::insert_id();
396
                        if ($id) {
397
                            $sql = "UPDATE $blog_table_attachment SET id = iid WHERE iid = $id";
398
                            Database::query($sql);
399
                        }
400
                    }
401
                }
402
            }
403
404
            return $last_post_id;
405
        } else {
406
            Display::display_error_message(get_lang('UplNoFileUploaded'));
407
        }
408
    }
409
410
    /**
411
     * Edits a post in a given blog
412
     * @author Toon Keppens
413
     * @param int $post_id The internal ID of the post to edit
414
     * @param string $title The title
415
     * @param string $full_text The full post text
416
     * @param int $blog_id The internal ID of the blog in which the post is located
417
     */
418 View Code Duplication
    public static function editPost($post_id, $title, $full_text, $blog_id)
419
    {
420
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
421
        $course_id = api_get_course_int_id();
422
423
        // Create the post
424
        $sql = "UPDATE $tbl_blogs_posts SET
425
                title = '".Database::escape_string($title)."',
426
                full_text = '".Database::escape_string($full_text)."'
427
                WHERE c_id = $course_id AND post_id ='".(int) $post_id."' AND blog_id ='".(int) $blog_id."'
428
                LIMIT 1 ";
429
        Database::query($sql);
430
    }
431
432
    /**
433
     * Deletes an article and its comments
434
     * @author Toon Keppens
435
     * @param int $blog_id The internal blog ID
436
     * @param int $post_id The internal post ID
437
     */
438
    public static function deletePost($blog_id, $post_id)
439
    {
440
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
441
        $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
442
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
443
        $blog_id = intval($blog_id);
444
        $post_id = intval($post_id);
445
446
        $course_id = api_get_course_int_id();
447
448
        // Delete ratings on this comment
449
        $sql = "DELETE FROM $tbl_blogs_rating
450
                WHERE c_id = $course_id AND blog_id = '".(int) $blog_id."' AND item_id = '".(int) $post_id."' AND rating_type = 'post'";
451
        Database::query($sql);
452
453
        // Delete the post
454
        $sql = "DELETE FROM $tbl_blogs_posts
455
                WHERE c_id = $course_id AND post_id = '".(int) $post_id."'";
456
        Database::query($sql);
457
458
        // Delete the comments
459
        $sql = "DELETE FROM $tbl_blogs_comments
460
                WHERE c_id = $course_id AND post_id = '".(int) $post_id."' AND blog_id = '".(int) $blog_id."'";
461
        Database::query($sql);
462
463
        // Delete posts and attachments
464
        self::deleteAllBlogAttachments($blog_id, $post_id);
465
    }
466
467
    /**
468
     * Creates a comment on a post in a given blog
469
     * @author Toon Keppens
470
     * @param String $title
471
     * @param String $full_text
472
     * @param Integer $blog_id
473
     * @param Integer $post_id
474
     * @param Integer $parent_id
475
     */
476
    public static function createComment(
477
        $title,
478
        $full_text,
479
        $file_comment,
480
        $blog_id,
481
        $post_id,
482
        $parent_id,
483
        $task_id = 'NULL'
484
    ) {
485
        $_user = api_get_user_info();
486
        $_course = api_get_course_info();
487
        $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
488
489
        $upload_ok = true;
490
        $has_attachment = false;
491
        $current_date = api_get_utc_datetime();
492
        $course_id = api_get_course_int_id();
493
494 View Code Duplication
        if (!empty($_FILES['user_upload']['name'])) {
495
            $upload_ok = process_uploaded_file($_FILES['user_upload']);
496
            $has_attachment = true;
497
        }
498
499
		if ($upload_ok) {
500
			// Table Definition
501
			$tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
502
503
            // Create the comment
504
            $sql = "INSERT INTO $tbl_blogs_comments (c_id, title, comment, author_id, date_creation, blog_id, post_id, parent_comment_id, task_id )
505
                    VALUES ($course_id, '".Database::escape_string($title)."', '".Database::escape_string(
506
                    $full_text
507
                )."', '".(int) $_user['user_id']."','".$current_date."', '".(int) $blog_id."', '".(int) $post_id."', '".(int) $parent_id."', '".(int) $task_id."')";
508
            Database::query($sql);
509
510
			// Empty post values, or they are shown on the page again
511
			$last_id = Database::insert_id();
512
513
            if ($last_id) {
514
                $sql = "UPDATE $tbl_blogs_comments SET comment_id = iid WHERE iid = $last_id";
515
                Database::query($sql);
516
            }
517
518 View Code Duplication
            if ($has_attachment) {
519
                $courseDir = $_course['path'].'/upload/blog';
520
                $sys_course_path = api_get_path(SYS_COURSE_PATH);
521
                $updir = $sys_course_path.$courseDir;
522
523
                // Try to add an extension to the file if it hasn't one
524
                $new_file_name = add_ext_on_mime(
525
                    stripslashes($_FILES['user_upload']['name']),
526
                    $_FILES['user_upload']['type']
527
                );
528
529
                // user's file name
530
                $file_name = $_FILES['user_upload']['name'];
531
532
                if (!filter_extension($new_file_name)) {
533
                    Display:: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
534
                } else {
535
                    $new_file_name = uniqid('');
536
                    $new_path = $updir.'/'.$new_file_name;
537
                    $result = @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path);
538
                    $comment = Database::escape_string($file_comment);
539
540
                    // Storing the attachments if any
541
                    if ($result) {
542
                        $sql = 'INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size,blog_id,comment_id) '.
543
                            "VALUES ($course_id, '".Database::escape_string(
544
                                $file_name
545
                            )."', '".$comment."', '".Database::escape_string(
546
                                $new_file_name
547
                            )."' , '".$post_id."', '".$_FILES['user_upload']['size']."',  '".$blog_id."', '".$last_id."'  )";
548
                        Database::query($sql);
549
550
                        $id = Database::insert_id();
551
552
                        if ($id) {
553
                            $sql = "UPDATE $blog_table_attachment SET id = iid WHERE iid = $id";
554
                            Database::query($sql);
555
                        }
556
					}
557
				}
558
			}
559
		}
560
	}
561
562
    /**
563
     * Deletes a comment from a blogpost
564
     * @author Toon Keppens
565
     * @param int $blog_id The internal blog ID
566
     * @param int $post_id The internal post ID
567
     * @param int $comment_id The internal comment ID
568
     */
569
    public static function deleteComment($blog_id, $post_id, $comment_id)
570
    {
571
        $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
572
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
573
        $blog_id = intval($blog_id);
574
        $post_id = intval($post_id);
575
        $comment_id = intval($comment_id);
576
        $course_id = api_get_course_int_id();
577
578
        self::deleteAllBlogAttachments($blog_id, $post_id, $comment_id);
579
580
        // Delete ratings on this comment
581
        $sql = "DELETE FROM $tbl_blogs_rating
582
                WHERE
583
                    c_id = $course_id AND
584
                    blog_id = $blog_id AND
585
                    item_id = $comment_id AND
586
                    rating_type = 'comment'";
587
        Database::query($sql);
588
589
        // select comments that have the selected comment as their parent
590
        $sql = "SELECT comment_id FROM $tbl_blogs_comments
591
                WHERE c_id = $course_id AND parent_comment_id = $comment_id";
592
        $result = Database::query($sql);
593
594
        // Delete them recursively
595
        while ($comment = Database::fetch_array($result)) {
596
            Blog::deleteComment($blog_id, $post_id, $comment['comment_id']);
597
        }
598
599
        // Finally, delete the selected comment to
600
        $sql = "DELETE FROM $tbl_blogs_comments
601
                WHERE c_id = $course_id AND comment_id = $comment_id";
602
        Database::query($sql);
603
    }
604
605
    /**
606
     * Creates a new task in a blog
607
     * @author Toon Keppens
608
     * @param Integer $blog_id
609
     * @param String $title
610
     * @param String $description
611
     * @param String $color
612
     */
613
    public static function addTask(
614
        $blog_id,
615
        $title,
616
        $description,
617
        $articleDelete,
618
        $articleEdit,
619
        $commentsDelete,
620
        $color
621
    ) {
622
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
623
        $tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
624
625
		$course_id = api_get_course_int_id();
626
627
        // Create the task
628
        $sql = "INSERT INTO $tbl_blogs_tasks (c_id, blog_id, title, description, color, system_task)
629
                VALUES ($course_id , '".(int) $blog_id."', '".Database::escape_string(
630
                $title
631
            )."', '".Database::escape_string($description)."', '".Database::escape_string($color)."', '0');";
632
        Database::query($sql);
633
634
		$task_id = Database::insert_id();
635
636
        if ($task_id) {
637
            $sql = "UPDATE $tbl_blogs_tasks SET task_id = iid WHERE iid = $task_id";
638
            Database::query($sql);
639
        }
640
641
        $tool = 'BLOG_'.$blog_id;
642
643 View Code Duplication
        if ($articleDelete == 'on') {
644
            $sql = " INSERT INTO ".$tbl_tasks_permissions." ( c_id,  task_id, tool, action) VALUES (
645
                    '".(int) $course_id."',
646
                    '".(int) $task_id."',
647
                    '".Database::escape_string($tool)."',
648
                    'article_delete'
649
                )";
650
            Database::query($sql);
651
652
            $id = Database::insert_id();
653
654
            if ($id) {
655
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
656
                Database::query($sql);
657
            }
658
        }
659
660 View Code Duplication
        if ($articleEdit == 'on') {
661
            $sql = "
662
                INSERT INTO ".$tbl_tasks_permissions." (c_id, task_id, tool, action ) VALUES (
663
                    '".(int) $course_id."',
664
                    '".(int) $task_id."',
665
                    '".Database::escape_string($tool)."',
666
                    'article_edit'
667
                )";
668
            Database::query($sql);
669
            $id = Database::insert_id();
670
671
            if ($id) {
672
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
673
                Database::query($sql);
674
            }
675
		}
676
677 View Code Duplication
        if ($commentsDelete == 'on') {
678
            $sql = "
679
                INSERT INTO ".$tbl_tasks_permissions." (c_id, task_id, tool, action ) VALUES (
680
                    '".(int) $course_id."',
681
                    '".(int) $task_id."',
682
                    '".Database::escape_string($tool)."',
683
                    'article_comments_delete'
684
                )";
685
            Database::query($sql);
686
            $id = Database::insert_id();
687
688
            if ($id) {
689
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
690
                Database::query($sql);
691
            }
692
        }
693
    }
694
695
    /**
696
     * Edit a task in a blog
697
     * @author Toon Keppens
698
     * @param int $blog_id The internal blog ID
699
     * @param int $task_id The internal task ID
700
     * @param string $title The task title
701
     * @param string $description The task description
702
     * @param string $articleDelete Set to 'on' to register as 'article_delete' in tasks_permissions
703
     * @param string $articleEdit Set to 'on' to register as 'article_edit' in tasks_permissions
704
     * @param string $commentsDelete Set to 'on' to register as 'article_comments_delete' in tasks permissions
705
     * @param string $color The color code
706
     */
707
    public static function editTask(
708
        $blog_id,
709
        $task_id,
710
        $title,
711
        $description,
712
        $articleDelete,
713
        $articleEdit,
714
        $commentsDelete,
715
        $color
716
    ) {
717
		$tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
718
		$tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
719
720
        $course_id = api_get_course_int_id();
721
722
        // Create the task
723
        $sql = "UPDATE $tbl_blogs_tasks SET
724
                    title = '".Database::escape_string($title)."',
725
                    description = '".Database::escape_string($description)."',
726
                    color = '".Database::escape_string($color)."'
727
                WHERE c_id = $course_id AND task_id ='".(int) $task_id."' LIMIT 1";
728
        Database::query($sql);
729
730
        $tool = 'BLOG_'.$blog_id;
731
732
        $sql = "DELETE FROM ".$tbl_tasks_permissions."
733
                WHERE c_id = $course_id AND task_id = '".(int) $task_id."'";
734
        Database::query($sql);
735
736 View Code Duplication
        if ($articleDelete == 'on') {
737
            $sql = "INSERT INTO ".$tbl_tasks_permissions." ( c_id, task_id, tool, action) VALUES (
738
                    '".(int) $course_id."',
739
                    '".(int) $task_id."',
740
                    '".Database::escape_string($tool)."',
741
                    'article_delete'
742
                )";
743
            Database::query($sql);
744
            $id = Database::insert_id();
745
746
            if ($id) {
747
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
748
                Database::query($sql);
749
            }
750
		}
751
752 View Code Duplication
        if ($articleEdit == 'on') {
753
            $sql = "INSERT INTO ".$tbl_tasks_permissions." (c_id, task_id, tool, action) VALUES (
754
                    '".(int) $course_id."',
755
                    '".(int) $task_id."',
756
                    '".Database::escape_string($tool)."',
757
                    'article_edit'
758
                )";
759
            Database::query($sql);
760
            $id = Database::insert_id();
761
762
            if ($id) {
763
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
764
                Database::query($sql);
765
            }
766
		}
767
768 View Code Duplication
        if ($commentsDelete == 'on') {
769
            $sql = " INSERT INTO ".$tbl_tasks_permissions." (c_id, task_id, tool, action) VALUES (
770
                    '".(int) $course_id."',
771
                    '".(int) $task_id."',
772
                    '".Database::escape_string($tool)."',
773
                    'article_comments_delete'
774
                )";
775
            Database::query($sql);
776
            $id = Database::insert_id();
777
778
            if ($id) {
779
                $sql = "UPDATE $tbl_tasks_permissions SET id = iid WHERE iid = $id";
780
                Database::query($sql);
781
            }
782
        }
783
    }
784
785
    /**
786
     * Deletes a task from a blog
787
     * @param int $blog_id
788
     * @param int $task_id
789
     * @return void
790
     */
791
    public static function deleteTask($blog_id, $task_id)
792
    {
793
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
794
        $course_id = api_get_course_int_id();
795
        $blog_id = intval($blog_id);
796
        $task_id = intval($task_id);
797
798
        // Delete posts
799
        $sql = "DELETE FROM $tbl_blogs_tasks
800
                WHERE c_id = $course_id AND blog_id = '".(int) $blog_id."' AND task_id = '".(int) $task_id."'";
801
        Database::query($sql);
802
    }
803
804
    /**
805
     * Deletes an assigned task from a blog
806
     * @param int $blog_id
807
     * @param int $task_id
808
     * @param int $user_id
809
     * @return void
810
     */
811 View Code Duplication
    public static function deleteAssignedTask($blog_id, $task_id, $user_id)
812
    {
813
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
814
        $course_id = api_get_course_int_id();
815
816
        // Delete posts
817
        $sql = "DELETE FROM $tbl_blogs_tasks_rel_user
818
                WHERE
819
                    c_id = $course_id AND
820
                    blog_id = '".(int) $blog_id."' AND
821
                    task_id = '".(int) $task_id."' AND
822
                    user_id = '".(int) $user_id."'";
823
        Database::query($sql);
824
    }
825
826
    /**
827
     * Get personal task list
828
     * @author Toon Keppens
829
     * @return Returns an unsorted list (<ul></ul>) with the users' tasks
830
     */
831
    public static function getPersonalTasksList()
832
    {
833
        $_user = api_get_user_info();
834
        $html = null;
835
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
836
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
837
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
838
839
		$course_id = api_get_course_int_id();
840
841
		if ($_user['user_id']) {
842
			$sql = "SELECT task_rel_user.*, task.title, blog.blog_name
843
                    FROM $tbl_blogs_tasks_rel_user task_rel_user
844
                    INNER JOIN $tbl_blogs_tasks task
845
                    ON task_rel_user.task_id = task.task_id
846
                    INNER JOIN $tbl_blogs blog
847
                    ON task_rel_user.blog_id = blog.blog_id
848
                    AND blog.blog_id = ".intval($_GET['blog_id'])."
849
                    WHERE
850
                        task.c_id = $course_id AND
851
                        blog.c_id = $course_id AND
852
                        task_rel_user.c_id = $course_id AND
853
                        task_rel_user.user_id = ".(int) $_user['user_id']."
854
                    ORDER BY target_date ASC";
855
856
            $result = Database::query($sql);
857
858
            if (Database::num_rows($result) > 0) {
859
                $html .= '<ul>';
860
                while ($mytask = Database::fetch_array($result)) {
861
                    $html .= '<li><a href="blog.php?action=execute_task&blog_id='.$mytask['blog_id'].'&task_id='.stripslashes(
862
                            $mytask['task_id']
863
                        ).'" title="[Blog: '.stripslashes($mytask['blog_name']).'] '.get_lang(
864
                            'ExecuteThisTask'
865
                        ).'">'.stripslashes($mytask['title']).'</a></li>';
866
                }
867
                $html .= '<ul>';
868
            } else {
869
                $html .= get_lang('NoTasks');
870
            }
871
        } else {
872
            $html .= get_lang('NoTasks');
873
        }
874
875
        return $html;
876
    }
877
878
    /**
879
     * Changes the visibility of a blog
880
     * @author Toon Keppens
881
     * @param Integer $blog_id
882
     */
883
    public static function changeBlogVisibility($blog_id)
884
    {
885
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
886
        $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
887
        $course_id = api_get_course_int_id();
888
889
        // Get blog properties
890
        $sql = "SELECT blog_name, visibility FROM $tbl_blogs
891
                WHERE c_id = $course_id AND blog_id='".(int) $blog_id."'";
892
        $result = Database::query($sql);
893
        $blog = Database::fetch_array($result);
894
        $visibility = $blog['visibility'];
895
        $title = $blog['blog_name'];
896
897
        if ($visibility == 1) {
898
            // Change visibility state, remove from course home.
899
            $sql = "UPDATE $tbl_blogs SET visibility = '0'
900
                    WHERE c_id = $course_id AND blog_id ='".(int) $blog_id."' LIMIT 1";
901
            Database::query($sql);
902
903
            $sql = "DELETE FROM $tbl_tool
904
                    WHERE c_id = $course_id AND name = '".Database::escape_string($title)."' LIMIT 1";
905
            Database::query($sql);
906
        } else {
907
            // Change visibility state, add to course home.
908
            $sql = "UPDATE $tbl_blogs SET visibility = '1'
909
                    WHERE c_id = $course_id AND blog_id ='".(int) $blog_id."' LIMIT 1";
910
            Database::query($sql);
911
912
            $sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, target )
913
                    VALUES ($course_id, '".Database::escape_string(
914
                    $title
915
                )."', 'blog/blog.php?blog_id=".(int) $blog_id."', 'blog.gif', '1', '0', 'pastillegris.gif', '0', '_self')";
916
            Database::query($sql);
917
            $id = Database::insert_id();
918
919
            if ($id) {
920
                $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $id";
921
                Database::query($sql);
922
            }
923
		}
924
	}
925
926
    /**
927
     * Display the search results
928
     * @param Integer $blog_id
929
     * @param String $query_string
930
     */
931
    public static function getSearchResults($blog_id, $query_string)
932
    {
933
        // Init
934
        $query_string = Database::escape_string($query_string);
935
        $query_string_parts = explode(' ', $query_string);
936
        $query_string = array();
937
        foreach ($query_string_parts as $query_part) {
938
            $query_string[] = " full_text LIKE '%".$query_part."%' OR title LIKE '%".$query_part."%' ";
939
        }
940
        $query_string = '('.implode('OR', $query_string).')';
941
942
        // Display the posts
943
        //echo '<span class="blogpost_title">' . get_lang('SearchResults') . '</span>';
944
        return Blog::getPosts($blog_id, $query_string);
945
    }
946
947
    /**
948
     * Shows the posts of a blog
949
     * @author Toon Keppens
950
     *
951
     * @param Integer $blog_id
952
     */
953
    public static function getPosts($blog_id, $filter = '1=1', $max_number_of_posts = 20)
954
    {
955
		// Init
956
		$tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
957
		$tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
958
		$tbl_users = Database::get_main_table(TABLE_MAIN_USER);
959
960
		$course_id = api_get_course_int_id();
961
962
		// Get posts and authors
963
		$sql = "SELECT post.*, user.lastname, user.firstname, user.username
964
		        FROM $tbl_blogs_posts post
965
                INNER JOIN $tbl_users user
966
                ON post.author_id = user.user_id
967
                WHERE 	post.blog_id = '".(int) $blog_id."' AND
968
                        post.c_id = $course_id AND
969
                        $filter
970
                ORDER BY post_id DESC LIMIT 0,".(int) $max_number_of_posts;
971
        $result = Database::query($sql);
972
973
        // Display
974
        if (Database::num_rows($result) > 0) {
975
            $limit = 200;
976
977
            while ($blog_post = Database::fetch_array($result)) {
978
                // Get number of comments
979
                $sql = "SELECT COUNT(1) as number_of_comments
980
                        FROM $tbl_blogs_comments
981
                        WHERE
982
                            c_id = $course_id AND
983
                            blog_id = '".(int) $blog_id."' AND
984
                            post_id = '".(int) $blog_post['post_id']."'";
985
                $tmp = Database::query($sql);
986
                $blog_post_comments = Database::fetch_array($tmp);
987
988
                $fileArray = self::getBlogAttachments($blog_id, $blog_post['post_id'], 0);
989
                $scoreRanking = Blog::displayRating('post',$blog_id,$blog_post['post_id']);
990
                // Prepare data
991
                $article = [
992
                    'id_blog' => $blog_post['blog_id'],
993
                    'c_id' => $blog_post['c_id'],
994
                    'id_post' => $blog_post['post_id'],
995
                    'id_autor' => $blog_post['author_id'],
996
                    'autor' => $blog_post['firstname'].' '.$blog_post['lastname'],
997
                    'username' => $blog_post['username'],
998
                    'title' => stripslashes($blog_post['title']),
999
                    'extract' => self::getPostExtract($blog_post['full_text'], BLOG_MAX_PREVIEW_CHARS),
1000
                    'content' => stripslashes($blog_post['full_text']),
1001
                    'post_date' => api_convert_and_format_date($blog_post['date_creation']),
1002
                    'n_comments' => $blog_post_comments['number_of_comments'],
1003
                    'files' => $fileArray,
1004
                    'score_ranking' => $scoreRanking
1005
1006
                ];
1007
1008
                $listArticle[] = $article;
1009
1010
            }
1011
1012
            return $listArticle;
1013
1014
        } else {
1015
            if ($filter == '1=1') {
1016
                return get_lang('NoArticles');
1017
            } else {
1018
                return get_lang('NoArticleMatches');
1019
            }
1020
        }
1021
    }
1022
1023
    /**
1024
     * Display posts from a certain date
1025
     *
1026
     * @param Integer $blog_id
1027
     * @param String $query_string
1028
     */
1029
    public static function getDailyResults($blog_id, $query_string)
1030
    {
1031
        //$date_output = $query_string;
1032
        $date = explode('-', $query_string);
1033
        $query_string = ' DAYOFMONTH(date_creation) ='.intval($date[2]).' AND MONTH(date_creation) ='.intval(
1034
                $date[1]
1035
            ).' 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 = Blog::getPosts($blog_id, $query_string);
1041
1042
        return $list;
1043
    }
1044
1045
    /**
1046
     * Displays a post and his comments
1047
     *
1048
     * @param Integer $blog_id
1049
     * @param Integer $post_id
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
1058
		global $charset, $dateFormatLong;
1059
1060
		$course_id = api_get_course_int_id();
1061
1062
		// Get posts and author
1063
		$sql = "SELECT post.*, user.lastname, user.firstname, user.username
1064
		        FROM $tbl_blogs_posts post
1065
					INNER JOIN $tbl_users user
1066
					ON post.author_id = user.user_id
1067
                WHERE
1068
                    post.c_id = $course_id AND
1069
                    post.blog_id = '".(int) $blog_id."' AND
1070
                    post.post_id = '".(int) $post_id."'
1071
                ORDER BY post_id DESC";
1072
        $result = Database::query($sql);
1073
        $blog_post = Database::fetch_array($result);
1074
1075
        // Get number of comments
1076
        $sql = "SELECT COUNT(1) as number_of_comments
1077
                FROM $tbl_blogs_comments
1078
                WHERE c_id = $course_id AND blog_id = '".(int) $blog_id."' AND post_id = '".(int) $post_id."'";
1079
        $result = Database::query($sql);
1080
        $blog_post_comments = Database::fetch_array($result);
1081
        $blogActions = null;
1082
1083
        $task_id = (isset($_GET['task_id']) && is_numeric($_GET['task_id'])) ? intval($_GET['task_id']) : 0;
1084
1085
        // Display comments if there are any
1086
        if ($blog_post_comments['number_of_comments'] > 0) {
1087
            $listComments = Blog::getThreadedComments(0, 0, $blog_id, $post_id, $task_id);
1088
        }
1089
        // Display comment form
1090
        if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_add')) {
1091
            $formComments = Blog::displayCommentCreateForm($blog_id, $post_id, $blog_post['title'], false);
1092
        }
1093
        // Prepare data
1094
        $fileArray = self::getBlogAttachments($blog_id, $post_id);
1095
1096
        $post_text = make_clickable(stripslashes($blog_post['full_text']));
1097
        $post_text = stripslashes($post_text);
1098
1099
        if (api_is_allowed('BLOG_'.$blog_id, 'article_edit', $task_id)) {
1100
            $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').'">';
1101
            $blogActions .= Display::return_icon('edit.png', get_lang('Edit'), null, ICON_SIZE_TINY);
1102
            $blogActions .= '</a>';
1103
        }
1104
1105
        if (api_is_allowed('BLOG_'.$blog_id, 'article_delete', $task_id)) {
1106
            $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(
1107
                    'DeleteThisArticle'
1108
                ).'" onclick="javascript:if(!confirm(\''.addslashes(
1109
                    api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)
1110
                ).'\')) return false;">';
1111
            $blogActions .= Display::return_icon('delete.png', get_lang('Delete'), null, ICON_SIZE_TINY);
1112
            $blogActions .= '</a>';
1113
        }
1114
        $scoreRanking = Blog::displayRating('post',$blog_id,$post_id);
1115
        $article = [
1116
            'id_blog' => $blog_post['blog_id'],
1117
            'c_id' => $blog_post['c_id'],
1118
            'id_post' => $blog_post['post_id'],
1119
            'id_author' => $blog_post['author_id'],
1120
            'author' => $blog_post['firstname'].' '.$blog_post['lastname'],
1121
            'username' => $blog_post['username'],
1122
            'title' => stripslashes($blog_post['title']),
1123
            'extract' => api_get_short_text_from_html(stripslashes($blog_post['full_text']), 400),
1124
            'content' => $post_text,
1125
            'post_date' => api_convert_and_format_date($blog_post['date_creation']),
1126
            'n_comments' => $blog_post_comments['number_of_comments'],
1127
            'files' => $fileArray,
1128
            'id_task' => $task_id,
1129
            'comments' => $listComments,
1130
            'form_html' => $formComments,
1131
            'actions' => $blogActions,
1132
            'score_ranking' => (int)$scoreRanking,
1133
            'frm_rating' => api_is_allowed('BLOG_'.$blog_id, 'article_rate')
1134
                ? Blog::displayRatingCreateForm('post', $blog_id, $post_id)
1135
                : null
1136
        ];
1137
1138
        return $article;
1139
1140
    }
1141
1142
    /**
1143
     * This functions gets all replys to a post, threaded.
1144
     *
1145
     * @param Integer $current
1146
     * @param Integer $current_level
1147
     * @param Integer $blog_id
1148
     * @param Integer $post_id
1149
     */
1150
    public static function getThreadedComments($current = 0, $current_level = 0, $blog_id, $post_id, $task_id = 0)
1151
    {
1152
        $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
1153
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1154
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1155
        $charset = api_get_system_encoding();
1156
1157
        $course_id = api_get_course_int_id();
1158
        $listComments = [];
1159
        // Select top level comments
1160
        $next_level = $current_level + 1;
1161
        $sql = "SELECT comments.*, user.lastname, user.firstname, user.username, task.color
1162
                FROM $tbl_blogs_comments comments
1163
                INNER JOIN $tbl_users user
1164
                ON comments.author_id = user.user_id
1165
                LEFT JOIN $tbl_blogs_tasks task
1166
                ON comments.task_id = task.task_id AND task.c_id = $course_id
1167
                WHERE
1168
                    comments.c_id = $course_id AND
1169
                    parent_comment_id = $current AND
1170
                    comments.blog_id = '".(int) $blog_id."' AND
1171
                    comments.post_id = '".(int) $post_id."'";
1172
1173
        $result = Database::query($sql);
1174
        $html = null;
1175
        while ($comment = Database::fetch_array($result)) {
1176
            $commentActions = null;
1177
            $ratingSelect = null;
1178
            $comment_text = make_clickable(stripslashes($comment['comment']));
1179
            $comment_text = stripslashes($comment_text);
1180
            $infoUser = UserManager::getUserPicture($comment['author_id']);
1181
1182
            $commentActions .= Display::toolbarButton(
1183
                get_lang('ReplyToThisComment'),
1184
                '#',
1185
                'reply',
1186
                'default',
1187
                ['data-id' => $comment['iid'], 'role' => 'button', 'class' => 'btn-reply-to'],
1188
                false
1189
            );
1190
1191
            if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_delete', $task_id)) {
1192
                $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(
1193
                        'DeleteThisComment'
1194
                    ).'" onclick="javascript:if(!confirm(\''.addslashes(
1195
                        api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)
1196
                    ).'\')) return false;">';
1197
                $commentActions .= Display::returnFontAwesomeIcon('trash');
1198
                $commentActions .= '</a>';
1199
            }
1200
            if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_rate')) {
1201
                $ratingSelect = Blog::displayRatingCreateForm('comment', $blog_id, $post_id, $comment['comment_id']);
1202
            }
1203
1204
            $scoreRanking = self::displayRating('comment', $blog_id, $comment['comment_id']);
1205
1206
            //Files
1207
            $fileArray = self::getBlogAttachments($blog_id, $post_id, $comment['comment_id']);
1208
1209
            $comments = [
1210
                'iid' => $comment['iid'],
1211
                'id_comment' => $comment['comment_id'],
1212
                'id_curso' => $comment['c_id'],
1213
                'title' => $comment['title'],
1214
                'content' => $comment_text,
1215
                'id_author' => $comment['author_id'],
1216
                'comment_date' => api_convert_and_format_date($comment['date_creation']),
1217
                'id_blog' => $comment['blog_id'],
1218
                'id_post' => $comment['post_id'],
1219
                'id_task' => $comment['task_id'],
1220
                'id_parent' => $comment['parent_comment_id'],
1221
                'name_author' => api_get_person_name($comment['firstname'], $comment['lastname']),
1222
                'info_user' => $infoUser,
1223
                'username' => $comment['username'],
1224
                'color' => $comment['color'],
1225
                'files' => $fileArray,
1226
                'actions' => $commentActions,
1227
                'form_ranking' => $ratingSelect,
1228
                'score_ranking' => $scoreRanking,
1229
                'comments' => self::getThreadedComments($comment['iid'], $next_level, $blog_id, $post_id)
1230
            ];
1231
1232
            $listComments[] = $comments;
1233
        }
1234
1235
        return $listComments;
1236
    }
1237
1238
    /**
1239
     * Shows the rating form if not already rated by that user
1240
     * @author Toon Keppens
1241
     *
1242
     * @param String $type
1243
     * @param Integer $blog_id
1244
     * @param integer $post_id
1245
     */
1246
    public static function displayRatingCreateForm($type, $blog_id, $post_id, $comment_id = null)
1247
    {
1248
        $_user = api_get_user_info();
1249
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
1250
        $course_id = api_get_course_int_id();
1251
        $html = null;
1252
1253 View Code Duplication
        if ($type == 'post') {
1254
            // Check if the user has already rated this post
1255
            $sql = "SELECT rating_id FROM $tbl_blogs_rating
1256
                    WHERE c_id = $course_id AND
1257
                    blog_id = '".(int) $blog_id."'
1258
                    AND item_id = '".(int) $post_id."'
1259
                    AND rating_type = '".Database::escape_string($type)."'
1260
                    AND user_id = '".(int) $_user['user_id']."'";
1261
            $result = Database::query($sql);
1262
            // Add rating
1263
            if (Database::num_rows($result) == 0) {
1264
                $html .= '<form class="form-horizontal" method="get" action="blog.php" id="frm_rating_'.$type.'_'.$post_id.'" name="frm_rating_'.$type.'_'.$post_id.'">';
1265
                $html .= '<div class="form-group">';
1266
                $html .= '<label class="col-sm-3 control-label">'.get_lang('RateThis').'</label>';
1267
                $html .= '<div class="col-sm-9">';
1268
                $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.'" />';
1269
                $html .= '</div>';
1270
                $html .= '</div>';
1271
                $html .= '</form>';
1272
1273
                return $html;
1274
            } else {
1275
                return '';
1276
            }
1277
        }
1278
1279 View Code Duplication
        if ($type = 'comment') {
1280
            // Check if the user has already rated this comment
1281
            $sql = "SELECT rating_id FROM $tbl_blogs_rating
1282
                    WHERE c_id = $course_id AND blog_id = '".(int) $blog_id."'
1283
                    AND item_id = '".(int) $comment_id."'
1284
                    AND rating_type = '".Database::escape_string($type)."'
1285
                    AND user_id = '".(int) $_user['user_id']."' ";
1286
            $result = Database::query($sql);
1287
            if (Database::num_rows($result) == 0) {
1288
                $html .= '<form class="form-horizontal" method="get" action="blog.php" id="frm_rating_'.$type.'_'.$comment_id.'" name="frm_rating_'.$type.'_'.$comment_id.'">';
1289
                $html .= '<div class="form-group">';
1290
                $html .= '<label class="col-sm-3 control-label">'.get_lang('RateThis').'</label>';
1291
                $html .= '<div class="col-sm-9">';
1292
                $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.'" />';
1293
                $html .= '</div>';
1294
                $html .= '</div>';
1295
                $html .= '</form>';
1296
1297
                return $html;
1298
            } else {
1299
                return '';
1300
            }
1301
        }
1302
    }
1303
1304
    /**
1305
     * Shows the rating of user
1306
     * @param String $type
1307
     * @param Integer $blog_id
1308
     * @param Integer $item_id
1309
     * @return array
1310
     */
1311 View Code Duplication
    public static function displayRating($type, $blog_id, $item_id)
1312
    {
1313
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
1314
        $course_id = api_get_course_int_id();
1315
1316
        // Calculate rating
1317
        $sql = "SELECT AVG(rating) as rating FROM $tbl_blogs_rating
1318
                WHERE
1319
                    c_id = $course_id AND
1320
                    blog_id = '".(int) $blog_id."' AND
1321
                    item_id = '".(int) $item_id."' AND
1322
                    rating_type = '".Database::escape_string($type)."' ";
1323
        $result = Database::query($sql);
1324
        $result = Database::fetch_array($result);
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1325
1326
        return round($result['rating'], 2);
1327
    }
1328
1329
    /**
1330
     * Displays the form to create a new post
1331
     * @author Toon Keppens
1332
     *
1333
     * @param Integer $blog_id
1334
     * @param Integer $post_id
1335
     */
1336
    public static function displayCommentCreateForm($blog_id, $post_id)
1337
    {
1338
        $taskId = !empty($_GET['task_id']) ? (int) $_GET['task_id'] : 0;
1339
1340
        $form = new FormValidator(
1341
            'add_post',
1342
            'post',
1343
            api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
1344
                'action' => 'view_post',
1345
                'blog_id' => (int) $blog_id,
1346
                'post_id' => (int) $post_id,
1347
                'task_id' => (int) $taskId
1348
            ]),
1349
            null,
1350
            array('enctype' => 'multipart/form-data')
1351
        );
1352
1353
        $header = $taskId ? get_lang('ExecuteThisTask') : get_lang('AddNewComment');
1354
        $form->addHeader($header);
1355
        $form->addText('title', get_lang('Title'));
1356
1357
        $config = array();
1358
        if (!api_is_allowed_to_edit()) {
1359
            $config['ToolbarSet'] = 'ProjectComment';
1360
        } else {
1361
            $config['ToolbarSet'] = 'ProjectCommentStudent';
1362
        }
1363
        $form->addHtmlEditor('comment', get_lang('Comment'), false, false, $config);
1364
        $form->addFile('user_upload', get_lang('AddAnAttachment'));
1365
        $form->addTextarea('post_file_comment', get_lang('FileComment'));
1366
        $form->addHidden('action', null);
1367
        $form->addHidden('comment_parent_id', 0);
1368
        $form->addHidden('task_id', $taskId);
1369
        $form->addButton('save', get_lang('Save'));
1370
1371
        if ($form->validate()) {
1372
            $values = $form->exportValues();
1373
1374
            Blog::createComment(
1375
                $values['title'],
1376
                $values['comment'],
1377
                $values['post_file_comment'],
1378
                $blog_id,
1379
                $post_id,
1380
                $values['comment_parent_id'],
1381
                $taskId
1382
            );
1383
1384
            Display::addFlash(
1385
                Display::return_message(get_lang('CommentAdded'), 'success')
1386
            );
1387
1388
            header(
1389
                'Location: '
1390
                .api_get_self()
1391
                .'?'
1392
                .api_get_cidreq()
1393
                .'&'
1394
                .http_build_query([
1395
                    'blog_id' => $blog_id,
1396
                    'post_id' => $post_id,
1397
                    'action' => 'view_post',
1398
                    'task_id' => $taskId
1399
                ])
1400
            );
1401
            exit;
1402
        }
1403
1404
        return $form->returnForm();
1405
    }
1406
1407
    /**
1408
     * Adds rating to a certain post or comment
1409
     * @author Toon Keppens
1410
     *
1411
     * @param String $type
1412
     * @param Integer $blog_id
1413
     * @param Integer $item_id
1414
     * @param Integer $rating
1415
     *
1416
     * @return Boolean success
1417
     */
1418
    public static function addRating($type, $blog_id, $item_id, $rating)
1419
    {
1420
        $_user = api_get_user_info();
1421
1422
        // Init
1423
        $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
1424
        $course_id = api_get_course_int_id();
1425
1426
        // Check if the user has already rated this post/comment
1427
        $sql = "SELECT rating_id FROM $tbl_blogs_rating
1428
                WHERE
1429
                    c_id = $course_id AND
1430
                    blog_id = '".(int) $blog_id."' AND
1431
                    item_id = '".(int) $item_id."' AND
1432
                    rating_type = '".Database::escape_string($type)."' AND
1433
                    user_id = '".(int) $_user['user_id']."'";
1434
        $result = Database::query($sql);
1435
1436
        // Add rating
1437
        if (Database::num_rows($result) == 0) {
1438
            $sql = "INSERT INTO $tbl_blogs_rating (c_id, blog_id, rating_type, item_id, user_id, rating )
1439
                    VALUES ($course_id, '".(int) $blog_id."', '".Database::escape_string(
1440
                    $type
1441
                )."', '".(int) $item_id."', '".(int) $_user['user_id']."', '".Database::escape_string($rating)."')";
1442
            Database::query($sql);
1443
1444
            $id = Database::insert_id();
1445
            if ($id) {
1446
                $sql = "UPDATE $tbl_blogs_rating SET rating_id = iid WHERE iid = $id";
1447
                Database::query($sql);
1448
            }
1449
1450
            return true;
1451
        } else {
1452
            return false;
1453
        }
1454
    }
1455
1456
    /**
1457
     * Displays the form to create a new post
1458
     * @author Toon Keppens
1459
     *
1460
     * @param Integer $blog_id
1461
     */
1462
    public static function displayPostCreateForm($blog_id)
1463
    {
1464
        $blog_id = intval($blog_id);
1465
        if (!api_is_allowed('BLOG_'.$blog_id, 'article_add')) {
1466
            api_not_allowed();
1467
        }
1468
1469
        $form = new FormValidator(
1470
            'add_post',
1471
            'post',
1472
            api_get_path(WEB_CODE_PATH)."blog/blog.php?action=new_post&blog_id=".$blog_id."&".api_get_cidreq(),
1473
            null,
1474
            array('enctype' => 'multipart/form-data')
1475
        );
1476
        $form->addHidden('post_title_edited', 'false');
1477
        $form->addHeader(get_lang('NewPost'));
1478
        $form->addText('title', get_lang('Title'));
1479
        $config = array();
1480
        $config['ToolbarSet'] = !api_is_allowed_to_edit() ? 'ProjectStudent' : 'Project';
1481
        $form->addHtmlEditor('full_text', get_lang('Content'), false, false, $config);
1482
        $form->addFile('user_upload', get_lang('AddAnAttachment'));
1483
        $form->addTextarea('post_file_comment', get_lang('FileComment'));
1484
        $form->addHidden('new_post_submit', 'true');
1485
        $form->addButton('save', get_lang('Save'));
1486
1487
        if ($form->validate()) {
1488
            $values = $form->exportValues();
1489
1490
            $postId = Blog::createPost(
1491
                $values['title'],
1492
                $values['full_text'],
1493
                $values['post_file_comment'],
1494
                $blog_id
1495
            );
1496
1497
            if ($postId) {
1498
                Display::addFlash(
1499
                    Display::return_message(get_lang('BlogAdded'), 'success')
1500
                );
1501
1502
                header('Location: '.api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
1503
                    'action' => 'view_post',
1504
                    'blog_id' => $blog_id,
1505
                    'post_id' => $postId,
1506
                ]));
1507
                exit;
1508
            }
1509
        }
1510
1511
        return $form->returnForm();
1512
    }
1513
1514
    /**
1515
     * Displays the form to edit a post
1516
     * @author Toon Keppens
1517
     *
1518
     * @param Integer $blog_id
1519
     */
1520
    public static function displayPostEditForm($blog_id, $post_id)
1521
    {
1522
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
1523
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1524
1525
        $course_id = api_get_course_int_id();
1526
1527
        // Get posts and author
1528
        $sql = "SELECT post.*, user.lastname, user.firstname
1529
                FROM $tbl_blogs_posts post
1530
                INNER JOIN $tbl_users user ON post.author_id = user.user_id
1531
                WHERE
1532
                post.c_id 			= $course_id AND
1533
                post.blog_id 		= '".(int) $blog_id."'
1534
                AND post.post_id	= '".(int) $post_id."'
1535
                ORDER BY post_id DESC";
1536
        $result = Database::query($sql);
1537
        $blog_post = Database::fetch_array($result);
1538
1539
        // Form
1540
        $form = new FormValidator(
1541
            'edit_post',
1542
            'post',
1543
            api_get_path(WEB_CODE_PATH).'blog/blog.php?action=edit_post&post_id='.intval(
1544
                $_GET['post_id']
1545
            ).'&blog_id='.intval($blog_id).'&article_id='.intval($_GET['article_id']).'&task_id='.intval(
1546
                $_GET['task_id']
1547
            )
1548
        );
1549
1550
		$form->addHeader(get_lang('EditPost'));
1551
		$form->addText('title', get_lang('Title'));
1552
1553
		if (!api_is_allowed_to_edit()) {
1554
			$config['ToolbarSet'] = 'ProjectStudent';
1555
		} else {
1556
			$config['ToolbarSet'] = 'Project';
1557
		}
1558
		$form->addHtmlEditor('full_text', get_lang('Content'), false, false, $config);
1559
1560
        $form->addHidden('action', '');
1561
        $form->addHidden('edit_post_submit', 'true');
1562
        $form->addHidden('post_id', intval($_GET['post_id']));
1563
        $form->addButton('save', get_lang('Save'));
1564
        $form->setDefaults($blog_post);
1565
1566
        return $form->return_form();
0 ignored issues
show
Deprecated Code introduced by
The method FormValidator::return_form() has been deprecated with message: use returnForm()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1567
    }
1568
1569
    /**
1570
     * Displays a list of tasks in this blog
1571
     * @author Toon Keppens
1572
     *
1573
     * @param int $blog_id
1574
     * @return string
1575
     */
1576
    public static function displayTasksList($blog_id)
1577
    {
1578
		global $charset;
1579
        $course_id = api_get_course_int_id();
1580
        $html = '';
1581
        if (api_is_allowed('BLOG_'.$blog_id, 'article_add')) {
1582
            $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1583
            $counter = 0;
1584
            global $color2;
1585
1586
            $html .= '<div class="actions">';
1587
            $html .= '<a href="'.api_get_self().'?action=manage_tasks&blog_id='.$blog_id.'&do=add">';
1588
            $html .= Display::return_icon('blog_newtasks.gif', get_lang('AddTasks'));
1589
            $html .= get_lang('AddTasks').'</a> ';
1590
            $html .= '<a href="'.api_get_self().'?action=manage_tasks&blog_id='.$blog_id.'&do=assign">';
1591
            $html .= Display::return_icon('blog_task.gif', get_lang('AssignTasks'));
1592
            $html .= get_lang('AssignTasks').'</a>';
1593
            $html .= Display::url(
1594
                Display::return_icon('blog_admin_users.png', get_lang('RightsManager')),
1595
                api_get_self().'?'.http_build_query([
1596
                    'action' => 'manage_rights',
1597
                    'blog_id' => $blog_id
1598
                ]),
1599
                ['title' => get_lang('ManageRights')]
1600
            );
1601
1602
            $html .= '</div>';
1603
1604
            $html .= '<span class="blogpost_title">'.get_lang('TaskList').'</span><br />';
1605
            $html .= "<table class=\"data_table\">";
1606
            $html .= "<tr bgcolor=\"$color2\" align=\"center\" valign=\"top\">"
1607
                ."<th width='240'><b>".get_lang('Title')."</b></th>"
1608
                ."<th><b>".get_lang('Description')."</b></th>"
1609
                ."<th><b>".get_lang('Color')."</b></th>"
1610
                ."<th width='50'><b>".get_lang('Modify')."</b></th></tr>";
1611
1612
1613
			$sql = " SELECT
1614
                        blog_id,
1615
                        task_id,
1616
                        blog_id,
1617
                        title,
1618
                        description,
1619
                        color,
1620
                        system_task
1621
                    FROM ".$tbl_blogs_tasks."
1622
                    WHERE c_id = $course_id AND blog_id = ".(int) $blog_id."
1623
                    ORDER BY system_task, title";
1624
			$result = Database::query($sql);
1625
1626
            while ($task = Database::fetch_array($result)) {
1627
                $counter++;
1628
                $css_class = (($counter % 2) == 0) ? "row_odd" : "row_even";
1629
                $delete_icon = ($task['system_task'] == '1') ? "delete_na.png" : "delete.png";
1630
                $delete_title = ($task['system_task'] == '1') ? get_lang('DeleteSystemTask') : get_lang('DeleteTask');
1631
                $delete_link = ($task['system_task'] == '1') ? '#' : api_get_self(
1632
                    ).'?action=manage_tasks&blog_id='.$task['blog_id'].'&do=delete&task_id='.$task['task_id'];
1633
                $delete_confirm = ($task['system_task'] == '1') ? '' : 'onclick="javascript:if(!confirm(\''.addslashes(
1634
                        api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)
1635
                    ).'\')) return false;"';
1636
1637
                $html .= '<tr class="'.$css_class.'" valign="top">';
1638
                $html .= '<td width="240">'.Security::remove_XSS($task['title']).'</td>';
1639
                $html .= '<td>'.Security::remove_XSS($task['description']).'</td>';
1640
                $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>';
1641
                $html .= '<td width="50">';
1642
                $html .= '<a href="'.api_get_self(
1643
                    ).'?action=manage_tasks&blog_id='.$task['blog_id'].'&do=edit&task_id='.$task['task_id'].'">';
1644
                $html .= Display::return_icon('edit.png', get_lang('EditTask'));
1645
                $html .= "</a>";
1646
                $html .= '<a href="'.$delete_link.'"';
1647
                $html .= $delete_confirm;
1648
                $html .= '>';
1649
                $html .= Display::return_icon($delete_icon, $delete_title);
1650
                $html .= "</a>";
1651
                $html .= '</td>';
1652
                $html .= '</tr>';
1653
            }
1654
            $html .= "</table>";
1655
        }
1656
1657
        return $html;
1658
    }
1659
1660
    /**
1661
     * Displays a list of tasks assigned to a user in this blog
1662
     * @author Toon Keppens
1663
     *
1664
     * @param Integer $blog_id
1665
     */
1666
    public static function displayAssignedTasksList($blog_id)
1667
    {
1668
        // Init
1669
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1670
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1671
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
1672
        $counter = 0;
1673
        global $charset, $color2;
1674
1675
        $return = '<span class="blogpost_title">'.get_lang('AssignedTasks').'</span><br />';
1676
        $return .= "<table class=\"data_table\">";
1677
        $return .= "<tr bgcolor=\"$color2\" align=\"center\" valign=\"top\">"
1678
            ."<th width='240'><b>".get_lang('Member')."</b></th>"
1679
            ."<th><b>".get_lang('Task')."</b></th>"
1680
            ."<th><b>".get_lang('Description')."</b></th>"
1681
            ."<th><b>".get_lang('TargetDate')."</b></th>"
1682
            ."<th width='50'><b>".get_lang('Modify')."</b></th>"
1683
            ."</tr>";
1684
1685
        $course_id = api_get_course_int_id();
1686
1687
        $sql = "SELECT task_rel_user.*, task.title, user.firstname, user.lastname, user.username, task.description, task.system_task, task.blog_id, task.task_id
1688
                FROM $tbl_blogs_tasks_rel_user task_rel_user
1689
                INNER JOIN $tbl_blogs_tasks task ON task_rel_user.task_id = task.task_id
1690
                INNER JOIN $tbl_users user ON task_rel_user.user_id = user.user_id
1691
                WHERE
1692
                    task_rel_user.c_id = $course_id AND
1693
                    task.c_id = $course_id AND
1694
                    task_rel_user.blog_id = '".(int) $blog_id."'
1695
                ORDER BY target_date ASC";
1696
        $result = Database::query($sql);
1697
1698
        while ($assignment = Database::fetch_array($result)) {
1699
            $counter++;
1700
            $css_class = (($counter % 2) == 0) ? "row_odd" : "row_even";
1701
            $delete_icon = ($assignment['system_task'] == '1') ? "delete_na.png" : "delete.png";
1702
            $delete_title = ($assignment['system_task'] == '1') ? get_lang('DeleteSystemTask') : get_lang('DeleteTask');
1703
            $delete_link = ($assignment['system_task'] == '1') ? '#' : api_get_self(
1704
                ).'?action=manage_tasks&blog_id='.$assignment['blog_id'].'&do=delete&task_id='.$assignment['task_id'];
1705
            $delete_confirm = ($assignment['system_task'] == '1') ? '' : 'onclick="javascript:if(!confirm(\''.addslashes(
1706
                    api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)
1707
                ).'\')) return false;"';
1708
1709
            $username = api_htmlentities(sprintf(get_lang('LoginX'), $assignment['username']), ENT_QUOTES);
1710
1711
            $return .='<tr class="'.$css_class.'" valign="top">';
1712
            $return .='<td width="240">'.Display::tag(
1713
                    'span',
1714
                    api_get_person_name($assignment['firstname'], $assignment['lastname']),
1715
                    array('title' => $username)
1716
                ).'</td>';
1717
            $return .= '<td>'.stripslashes($assignment['title']).'</td>';
1718
            $return .= '<td>'.stripslashes($assignment['description']).'</td>';
1719
            $return .= '<td>'.$assignment['target_date'].'</td>';
1720
            $return .= '<td width="50">';
1721
            $return .= '<a href="'.api_get_self(
1722
                ).'?action=manage_tasks&blog_id='.$assignment['blog_id'].'&do=edit_assignment&task_id='.$assignment['task_id'].'&user_id='.$assignment['user_id'].'">';
1723
            $return .= Display::return_icon('edit.png', get_lang('EditTask'));
1724
            $return .= "</a>";
1725
            $return .= '<a href="'.api_get_self(
1726
                ).'?action=manage_tasks&blog_id='.$assignment['blog_id'].'&do=delete_assignment&task_id='.$assignment['task_id'].'&user_id='.$assignment['user_id'].'" ';
1727
            $return .= 'onclick="javascript:if(!confirm(\''.addslashes(
1728
                    api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)
1729
                ).'\')) return false;"';
1730
            $return .= Display::return_icon($delete_icon, $delete_title);
1731
            $return .= "</a>";
1732
            $return .= '</td>';
1733
            $return .= '</tr>';
1734
        }
1735
        $return .= "</table>";
1736
1737
        return $return;
1738
    }
1739
1740
    /**
1741
     * Displays new task form
1742
     * @author Toon Keppens
1743
     *
1744
     */
1745
    public static function displayTaskCreateForm($blog_id)
1746
    {
1747
        // Init
1748
        $colors = array(
1749
            'FFFFFF',
1750
            'FFFF99',
1751
            'FFCC99',
1752
            'FF9933',
1753
            'FF6699',
1754
            'CCFF99',
1755
            'CC9966',
1756
            '66FF00',
1757
            '9966FF',
1758
            'CF3F3F',
1759
            '990033',
1760
            '669933',
1761
            '0033FF',
1762
            '003366',
1763
            '000000',
1764
        );
1765
1766
        // form
1767
        $return = '<form name="add_task" method="post" action="blog.php?action=manage_tasks&blog_id='.$blog_id.'">';
1768
1769
        // form title
1770
        $return .= '<legend>'.get_lang('AddTask').'</legend>';
1771
1772
        // task title
1773
        $return .= '	<div class="control-group">
1774
                    <label class="control-label">
1775
                        <span class="form_required">*</span>'.get_lang('Title').'
1776
                    </label>
1777
                    <div class="controls">
1778
                        <input name="task_name" type="text" size="70" />
1779
                    </div>
1780
                </div>';
1781
1782
        // task comment
1783
        $return .= '	<div class="control-group">
1784
                    <label class="control-label">
1785
                        '.get_lang('Description').'
1786
                    </label>
1787
                    <div class="controls">
1788
                        <textarea name="task_description" cols="45"></textarea>
1789
                    </div>
1790
                </div>';
1791
1792
        // task management
1793
        $return .= '	<div class="control-group">
1794
                    <label class="control-label">
1795
                        '.get_lang('TaskManager').'
1796
                    </label>
1797
                    <div class="controls">';
1798
        $return .= '<table class="data_table" cellspacing="0" style="border-collapse:collapse; width:446px;">';
1799
        $return .= '<tr>';
1800
        $return .= '<th colspan="2" style="width:223px;">'.get_lang('ArticleManager').'</th>';
1801
        $return .= '<th width:223px;>'.get_lang('CommentManager').'</th>';
1802
        $return .= '</tr>';
1803
        $return .= '<tr>';
1804
        $return .= '<th style="width:111px;"><label for="articleDelete">'.get_lang('Delete').'</label></th>';
1805
        $return .= '<th style="width:112px;"><label for="articleEdit">'.get_lang('Edit').'</label></th>';
1806
        $return .= '<th style="width:223px;"><label for="commentsDelete">'.get_lang('Delete').'</label></th>';
1807
        $return .= '</tr>';
1808
        $return .= '<tr>';
1809
        $return .= '<td style="text-align:center;"><input id="articleDelete" name="chkArticleDelete" type="checkbox" /></td>';
1810
        $return .= '<td style="text-align:center;"><input id="articleEdit" name="chkArticleEdit" type="checkbox" /></td>';
1811
        $return .= '<td style="border:1px dotted #808080; text-align:center;"><input id="commentsDelete" name="chkCommentsDelete" type="checkbox" /></td>';
1812
        $return .= '</tr>';
1813
        $return .= '</table>';
1814
        $return .= '		</div>
1815
                </div>';
1816
1817
1818
        // task color
1819
        $return .= '	<div class="control-group">
1820
                    <label class="control-label">
1821
                        '.get_lang('Color').'
1822
                    </label>
1823
                    <div class="controls">';
1824
        $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">';
1825
        foreach ($colors as $color) {
1826
            $style = 'style="background-color: #'.$color.'"';
1827
            $return .= '<option value="'.$color.'" '.$style.'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
1828
        }
1829
        $return .= '</select>';
1830
        $return .= '		</div>
1831
                </div>';
1832
1833
        // submit
1834
        $return .= '	<div class="control-group">
1835
                    <div class="controls">
1836
                            <input type="hidden" name="action" value="" />
1837
                            <input type="hidden" name="new_task_submit" value="true" />
1838
                        <button class="save" type="submit" name="Submit">'.get_lang('Save').'</button>
1839
                    </div>
1840
                </div>';
1841
        $return .= '</form>';
1842
1843
        $return .= '<div style="clear:both; margin-bottom: 10px;"></div>';
1844
1845
        return $return;
1846
    }
1847
1848
    /**
1849
     * Displays edit task form
1850
     * @author Toon Keppens
1851
     *
1852
     */
1853
    public static function displayTaskEditForm($blog_id, $task_id)
1854
    {
1855
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1856
        $course_id = api_get_course_int_id();
1857
1858
        $colors = array(
1859
            'FFFFFF',
1860
            'FFFF99',
1861
            'FFCC99',
1862
            'FF9933',
1863
            'FF6699',
1864
            'CCFF99',
1865
            'CC9966',
1866
            '66FF00',
1867
            '9966FF',
1868
            'CF3F3F',
1869
            '990033',
1870
            '669933',
1871
            '0033FF',
1872
            '003366',
1873
            '000000',
1874
        );
1875
1876
        $sql = "SELECT blog_id, task_id, title, description, color FROM $tbl_blogs_tasks WHERE c_id = $course_id AND task_id = '".(int) $task_id."'";
1877
        $result = Database::query($sql);
1878
        $task = Database::fetch_array($result);
1879
1880
        // Display
1881
        $return = '<form name="edit_task" method="post" action="blog.php?action=manage_tasks&blog_id='.$blog_id.'">
1882
                    <legend>'.get_lang('EditTask').'</legend>
1883
                    <table width="100%" border="0" cellspacing="2">
1884
                        <tr>
1885
                       <td align="right">'.get_lang('Title').':&nbsp;&nbsp;</td>
1886
                       <td><input name="task_name" type="text" size="70" value="'.Security::remove_XSS($task['title']).'" /></td>
1887
                        </tr>
1888
                        <tr>
1889
                       <td align="right">'.get_lang('Description').':&nbsp;&nbsp;</td>
1890
                       <td><textarea name="task_description" cols="45">'.Security::remove_XSS($task['description']).'</textarea></td>
1891
                        </tr>';
1892
1893
        /* edit by Kevin Van Den Haute ([email protected]) */
1894
        $tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
1895
1896
        $sql = " SELECT id, action FROM ".$tbl_tasks_permissions."
1897
                                 WHERE c_id = $course_id AND task_id = '".(int) $task_id."'";
1898
        $result = Database::query($sql);
1899
1900
        $arrPermissions = array();
1901
1902
        while ($row = Database::fetch_array($result)) {
1903
            $arrPermissions[] = $row['action'];
1904
        }
1905
1906
        $return .= '<tr>';
1907
        $return .= '<td style="text-align:right; vertical-align:top;">'.get_lang('TaskManager').':&nbsp;&nbsp;</td>';
1908
        $return .= '<td>';
1909
        $return .= '<table  class="data_table" cellspacing="0" style="border-collapse:collapse; width:446px;">';
1910
        $return .= '<tr>';
1911
        $return .= '<th colspan="2" style="width:223px;">'.get_lang('ArticleManager').'</th>';
1912
        $return .= '<th width:223px;>'.get_lang('CommentManager').'</th>';
1913
        $return .= '</tr>';
1914
        $return .= '<tr>';
1915
        $return .= '<th style="width:111px;"><label for="articleDelete">'.get_lang('Delete').'</label></th>';
1916
        $return .= '<th style="width:112px;"><label for="articleEdit">'.get_lang('Edit').'</label></th>';
1917
        $return .= '<th style="width:223px;"><label for="commentsDelete">'.get_lang('Delete').'</label></th>';
1918
        $return .= '</tr>';
1919
        $return .= '<tr>';
1920
        $return .= '<td style="text-align:center;"><input '.((in_array(
1921
                'article_delete',
1922
                $arrPermissions
1923
            )) ? 'checked ' : '').'id="articleDelete" name="chkArticleDelete" type="checkbox" /></td>';
1924
        $return .= '<td style="text-align:center;"><input '.((in_array(
1925
                'article_edit',
1926
                $arrPermissions
1927
            )) ? 'checked ' : '').'id="articleEdit" name="chkArticleEdit" type="checkbox" /></td>';
1928
        $return .= '<td style="text-align:center;"><input '.((in_array(
1929
                'article_comments_delete',
1930
                $arrPermissions
1931
            )) ? 'checked ' : '').'id="commentsDelete" name="chkCommentsDelete" type="checkbox" /></td>';
1932
        $return .= '</tr>';
1933
        $return .= '</table>';
1934
        $return .= '</td>';
1935
        $return .= '</tr>';
1936
        /* end of edit */
1937
1938
        $return .= '<tr>
1939
                       <td align="right">'.get_lang('Color').':&nbsp;&nbsp;</td>
1940
                       <td>
1941
                        <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">';
1942
        foreach ($colors as $color) {
1943
            $selected = ($color == $task['color']) ? ' selected' : '';
1944
            $style = 'style="background-color: #'.$color.'"';
1945
            $return .= '<option value="'.$color.'" '.$style.' '.$selected.' >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>';
1946
        }
1947
        $return .= '			   </select>
1948
                          </td>
1949
                        </tr>
1950
                        <tr>
1951
                            <td align="right">&nbsp;</td>
1952
                            <td><br /><input type="hidden" name="action" value="" />
1953
                            <input type="hidden" name="edit_task_submit" value="true" />
1954
                            <input type="hidden" name="task_id" value="'.$task['task_id'].'" />
1955
                            <input type="hidden" name="blog_id" value="'.$task['blog_id'].'" />
1956
                            <button class="save" type="submit" name="Submit">'.get_lang('Save').'</button></td>
1957
                        </tr>
1958
                    </table>
1959
                </form>';
1960
1961
        return $return;
1962
    }
1963
1964
    /**
1965
     * Displays assign task form
1966
     * @author Toon Keppens
1967
     *
1968
     */
1969
    public static function displayTaskAssignmentForm($blog_id)
1970
    {
1971
        $form = self::getTaskAssignmentForm($blog_id);
1972
        $form->addHidden('assign_task_submit', 'true');
1973
1974
        return $form->returnForm()
1975
            . PHP_EOL
1976
            . '<div style="clear: both; margin-bottom:10px;"></div>';
1977
    }
1978
1979
    /**
1980
     * @param $blog_id
1981
     * @return FormValidator
1982
     */
1983
    public static function getTaskAssignmentForm($blog_id)
1984
    {
1985
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
1986
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
1987
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
1988
        $course_id = api_get_course_int_id();
1989
1990
        // Get users in this blog / make select list of it
1991
        $sql = "SELECT user.user_id, user.firstname, user.lastname, user.username
1992
                FROM $tbl_users user
1993
                INNER JOIN $tbl_blogs_rel_user blogs_rel_user
1994
                ON user.user_id = blogs_rel_user.user_id
1995
                WHERE blogs_rel_user.c_id = $course_id AND blogs_rel_user.blog_id = '".(int) $blog_id."'";
1996
        $result = Database::query($sql);
1997
1998
        $options = array();
1999 View Code Duplication
        while ($user = Database::fetch_array($result)) {
2000
            $options[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']);
2001
        }
2002
2003
        // Get tasks in this blog / make select list of it
2004
        $sql = "
2005
            SELECT
2006
                blog_id,
2007
                task_id,
2008
                blog_id,
2009
                title,
2010
                description,
2011
                color,
2012
                system_task
2013
            FROM $tbl_blogs_tasks
2014
            WHERE c_id = $course_id AND blog_id = ".(int) $blog_id."
2015
            ORDER BY system_task, title";
2016
        $result = Database::query($sql);
2017
2018
        $taskOptions = array();
2019
        while ($task = Database::fetch_array($result)) {
2020
            $taskOptions[$task['task_id']] = stripslashes($task['title']);
2021
        }
2022
2023
        $form = new FormValidator(
2024
            'assign_task',
2025
            'post',
2026
            api_get_path(
2027
                WEB_CODE_PATH
2028
            ).'blog/blog.php?action=manage_tasks&blog_id='.$blog_id
2029
        );
2030
2031
        $form->addHeader(get_lang('AssignTask'));
2032
        $form->addSelect('task_user_id', get_lang('SelectUser'), $options);
2033
        $form->addSelect('task_task_id', get_lang('SelectTask'), $taskOptions);
2034
        $form->addDatePicker('task_day', get_lang('SelectTargetDate'));
2035
2036
        $form->addHidden('action', '');
2037
        $form->addButtonSave(get_lang('Ok'));
2038
2039
		return $form;
2040
	}
2041
2042
	/**
2043
     * Displays assign task form
2044
     * @author Toon Keppens
2045
     *
2046
     */
2047
    public static function displayAssignedTaskEditForm($blog_id, $task_id, $user_id)
2048
    {
2049
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2050
2051
        $course_id = api_get_course_int_id();
2052
2053
        // Get assignd date;
2054
        $sql = "
2055
            SELECT target_date
2056
            FROM $tbl_blogs_tasks_rel_user
2057
            WHERE c_id = $course_id AND
2058
                  blog_id = '".(int) $blog_id."' AND
2059
                  user_id = '".(int) $user_id."' AND
2060
                  task_id = '".(int) $task_id."'";
2061
        $result = Database::query($sql);
2062
        $row = Database::fetch_assoc($result);
2063
2064
        $date = $row['target_date'];
2065
2066
        $defaults = [
2067
            'task_user_id' => $user_id,
2068
            'task_task_id' => $task_id,
2069
            'task_day' => $date,
2070
        ];
2071
        $form = self::getTaskAssignmentForm($blog_id);
2072
        $form->addHidden('old_task_id', $task_id);
2073
        $form->addHidden('old_user_id', $user_id);
2074
        $form->addHidden('old_target_date', $date);
2075
        $form->addHidden('assign_task_edit_submit', 'true');
2076
        $form->setDefaults($defaults);
2077
2078
        return $form->returnForm();
2079
    }
2080
2081
    /**
2082
     * Assigns a task to a user in a blog
2083
     * @param int $blog_id
2084
     * @param int $user_id
2085
     * @param int $task_id
2086
     * @param string $target_date date
2087
     * @return void
2088
     */
2089
    public static function assignTask($blog_id, $user_id, $task_id, $target_date)
2090
    {
2091
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2092
        $course_id = api_get_course_int_id();
2093
        $blog_id = intval($blog_id);
2094
        $user_id = intval($user_id);
2095
        $task_id = intval($task_id);
2096
        $target_date = Database::escape_string($target_date);
2097
2098
        $sql = "
2099
            SELECT COUNT(*) as 'number'
2100
            FROM ".$tbl_blogs_tasks_rel_user."
2101
            WHERE c_id = $course_id AND
2102
            blog_id = ".(int) $blog_id."
2103
            AND	user_id = ".(int) $user_id."
2104
            AND	task_id = ".(int) $task_id."
2105
        ";
2106
2107
        $result = Database::query($sql);
2108
        $row = Database::fetch_assoc($result);
2109
2110
        if ($row['number'] == 0) {
2111
            $sql = "
2112
                INSERT INTO ".$tbl_blogs_tasks_rel_user." (
2113
                    c_id,
2114
                    blog_id,
2115
                    user_id,
2116
                    task_id,
2117
                    target_date
2118
                ) VALUES (
2119
                    '".(int) $course_id."',
2120
                    '".(int) $blog_id."',
2121
                    '".(int) $user_id."',
2122
                    '".(int) $task_id."',
2123
                    '".Database::escape_string($target_date)."'
2124
                )";
2125
2126
			Database::query($sql);
2127
		}
2128
	}
2129
2130
    /**
2131
     * @param $blog_id
2132
     * @param $user_id
2133
     * @param $task_id
2134
     * @param $target_date
2135
     * @param $old_user_id
2136
     * @param $old_task_id
2137
     * @param $old_target_date
2138
     */
2139
    public static function updateAssignedTask(
2140
        $blog_id,
2141
        $user_id,
2142
        $task_id,
2143
        $target_date,
2144
        $old_user_id,
2145
        $old_task_id,
2146
        $old_target_date
2147
    ) {
2148
		$tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2149
2150
		$course_id = api_get_course_int_id();
2151
2152
        $sql = "SELECT COUNT(*) as 'number'
2153
                FROM ".$tbl_blogs_tasks_rel_user."
2154
                WHERE
2155
                    c_id = $course_id AND
2156
                    blog_id = ".(int) $blog_id." AND
2157
                    user_id = ".(int) $user_id." AND
2158
                    task_id = ".(int) $task_id."
2159
            ";
2160
2161
        $result = Database::query($sql);
2162
        $row = Database::fetch_assoc($result);
2163
2164
        if ($row['number'] == 0 || ($row['number'] != 0 && $task_id == $old_task_id && $user_id == $old_user_id)) {
2165
            $sql = "
2166
                UPDATE ".$tbl_blogs_tasks_rel_user."
2167
                SET
2168
                    user_id = ".(int) $user_id.",
2169
                    task_id = ".(int) $task_id.",
2170
                    target_date = '".Database::escape_string($target_date)."'
2171
                WHERE
2172
                    c_id = $course_id AND
2173
                    blog_id = ".(int) $blog_id." AND
2174
                    user_id = ".(int) $old_user_id." AND
2175
                    task_id = ".(int) $old_task_id." AND
2176
                    target_date = '".Database::escape_string($old_target_date)."'
2177
            ";
2178
            Database::query($sql);
2179
        }
2180
    }
2181
2182
    /**
2183
     * Displays a list with posts a user can select to execute his task.
2184
     *
2185
     * @param int $blog_id
2186
     * @param int $task_id
2187
     * @return string
2188
     */
2189
    public static function displayPostSelectionForTask($blog_id, $task_id)
2190
    {
2191
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
2192
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
2193
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2194
        $course_id = api_get_course_int_id();
2195
2196
2197
        $sql = "SELECT title, description FROM $tbl_blogs_tasks
2198
                WHERE task_id = '".(int) $task_id."'
2199
                AND c_id = $course_id";
2200
        $result = Database::query($sql);
2201
        $row = Database::fetch_assoc($result);
2202
        // Get posts and authors
2203
        $sql = "SELECT post.*, user.lastname, user.firstname, user.username
2204
                FROM $tbl_blogs_posts post
2205
                INNER JOIN $tbl_users user ON post.author_id = user.user_id
2206
                WHERE post.blog_id = '".(int) $blog_id."' AND post.c_id = $course_id
2207
                ORDER BY post_id DESC
2208
                LIMIT 0, 100";
2209
        $result = Database::query($sql);
2210
2211
        // Display
2212
        $return = '<span class="blogpost_title">'.get_lang('SelectTaskArticle').' "'.stripslashes($row['title']).'"</span>';
2213
        $return .= '<span style="font-style: italic;"">'.stripslashes($row['description']).'</span><br><br>';
2214
2215
        if (Database::num_rows($result) == 0) {
2216
            $return .= get_lang('NoArticles');
2217
2218
            return $return;
2219
        }
2220
2221
        while ($blog_post = Database::fetch_array($result)) {
2222
            $username = api_htmlentities(sprintf(get_lang('LoginX'), $blog_post['username']), ENT_QUOTES);
2223
            $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(
2224
                    $blog_post['title']
2225
                ).'</a>, '.get_lang('WrittenBy').' '.stripslashes(
2226
                    Display::tag(
2227
                        'span',
2228
                        api_get_person_name($blog_post['firstname'], $blog_post['lastname']),
2229
                        array('title' => $username)
2230
                    )
2231
                ).'<br />';
2232
        }
2233
2234
        return $return;
2235
    }
2236
2237
    /**
2238
     * Unsubscribe a user from a given blog
2239
     * @author Toon Keppens
2240
     *
2241
     * @param Integer $blog_id
2242
     * @param Integer $user_id
2243
     */
2244 View Code Duplication
    public static function unsubscribeUser($blog_id, $user_id)
2245
    {
2246
		// Init
2247
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
2248
        $tbl_user_permissions = Database::get_course_table(TABLE_PERMISSION_USER);
2249
2250
        // Unsubscribe the user
2251
        $sql = "DELETE FROM $tbl_blogs_rel_user
2252
                WHERE blog_id = '".(int) $blog_id."' AND user_id = '".(int) $user_id."'";
2253
        Database::query($sql);
2254
2255
        // Remove this user's permissions.
2256
        $sql = "DELETE FROM $tbl_user_permissions
2257
                WHERE user_id = '".(int) $user_id."'";
2258
        Database::query($sql);
2259
    }
2260
2261
    /**
2262
     * Displays the form to register users in a blog (in a course)
2263
     * The listed users are users subcribed in the course.
2264
     * @author Toon Keppens
2265
     *
2266
     * @param Integer $blog_id
2267
     *
2268
     * @return Html Form with sortable table with users to subcribe in a blog, in a course.
2269
     */
2270
    public static function displayUserSubscriptionForm($blog_id)
2271
    {
2272
        $_course = api_get_course_info();
2273
        $is_western_name_order = api_is_western_name_order();
2274
        $session_id = api_get_session_id();
2275
        $course_id = $_course['real_id'];
2276
2277
        $currentCourse = $_course['code'];
2278
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2279
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
2280
        $html = null;
2281
2282
        $html .= '<legend>'.get_lang('SubscribeMembers').'</legend>';
2283
2284
        $properties["width"] = "100%";
2285
2286
        // Get blog members' id.
2287
        $sql = "SELECT user.user_id FROM $tbl_users user
2288
                INNER JOIN $tbl_blogs_rel_user blogs_rel_user
2289
                ON user.user_id = blogs_rel_user.user_id
2290
                WHERE blogs_rel_user.c_id = $course_id AND blogs_rel_user.blog_id = '".intval($blog_id)."'";
2291
        $result = Database::query($sql);
2292
2293
        $blog_member_ids = array();
2294
        while ($user = Database::fetch_array($result)) {
2295
            $blog_member_ids[] = $user['user_id'];
2296
        }
2297
2298
        // Set table headers
2299
        $column_header[] = array('', false, '');
2300 View Code Duplication
        if ($is_western_name_order) {
2301
            $column_header[] = array(get_lang('FirstName'), true, '');
2302
            $column_header[] = array(get_lang('LastName'), true, '');
2303
        } else {
2304
            $column_header[] = array(get_lang('LastName'), true, '');
2305
            $column_header[] = array(get_lang('FirstName'), true, '');
2306
        }
2307
        $column_header[] = array(get_lang('Email'), false, '');
2308
        $column_header[] = array(get_lang('Register'), false, '');
2309
2310
        $student_list = CourseManager:: get_student_list_from_course_code(
2311
            $currentCourse,
2312
            false,
2313
            $session_id
2314
        );
2315
        $user_data = array();
2316
2317
        // Add users that are not in this blog to the list.
2318
        foreach ($student_list as $key => $user) {
2319
            if (isset($user['id_user'])) {
2320
                $user['user_id'] = $user['id_user'];
2321
            }
2322
            if (!in_array($user['user_id'], $blog_member_ids)) {
2323
                $a_infosUser = api_get_user_info($user['user_id']);
2324
                $row = array();
2325
                $row[] = '<input type="checkbox" name="user[]" value="'.$a_infosUser['user_id'].'" '.((isset($_GET['selectall']) && $_GET['selectall'] == "subscribe") ? ' checked="checked" ' : '').'/>';
2326
                $username = api_htmlentities(sprintf(get_lang('LoginX'), $a_infosUser["username"]), ENT_QUOTES);
2327 View Code Duplication
                if ($is_western_name_order) {
2328
                    $row[] = $a_infosUser["firstname"];
2329
                    $row[] = Display::tag('span', $a_infosUser["lastname"], array('title' => $username));
2330
                } else {
2331
                    $row[] = Display::tag('span', $a_infosUser["lastname"], array('title' => $username));
2332
                    $row[] = $a_infosUser["firstname"];
2333
                }
2334
                $row[] = Display::icon_mailto_link($a_infosUser["email"]);
2335
2336
                //Link to register users
2337 View Code Duplication
                if ($a_infosUser["user_id"] != $_SESSION['_user']['user_id']) {
2338
                    $row[] = "<a class=\"btn btn-primary \" href=\"".api_get_self(
2339
                        )."?action=manage_members&blog_id=$blog_id&register=yes&user_id=".$a_infosUser["user_id"]."\">".get_lang(
2340
                            'Register'
2341
                        )."</a>";
2342
                } else {
2343
                    $row[] = '';
2344
                }
2345
                $user_data[] = $row;
2346
            }
2347
        }
2348
2349
        // Display
2350
        $query_vars['action'] = 'manage_members';
2351
        $query_vars['blog_id'] = $blog_id;
2352
        $html .= '<form class="form-inline" method="post" action="blog.php?action=manage_members&blog_id='.$blog_id.'">';
2353
        $html.= Display::return_sortable_table($column_header, $user_data, null, null, $query_vars);
2354
        $link = '';
2355
        $link .= isset ($_GET['action']) ? 'action='.Security::remove_XSS($_GET['action']).'&' : '';
2356
        $link .= "blog_id=$blog_id&";
2357
2358
        $html .= '<a class="btn btn-default" href="blog.php?'.$link.'selectall=subscribe">'.get_lang('SelectAll').'</a> - ';
2359
        $html .= '<a class="btn btn-default" href="blog.php?'.$link.'">'.get_lang('UnSelectAll').'</a> ';
2360
        $html .= '<div class="form-group">';
2361
        $html .= '<label>';
2362
        $html .= get_lang('WithSelected').' : ';
2363
        $html .= '</label>';
2364
        $html .= '<select class="selectpicker" name="action">';
2365
        $html .= '<option value="select_subscribe">'.get_lang('Register').'</option>';
2366
        $html .= '</select>';
2367
        $html .= '<input type="hidden" name="register" value="true" />';
2368
        $html .= '<button class="btn btn-default" type="submit">'.get_lang('Ok').'</button>';
2369
        $html .= '</div>';
2370
        $html .= '</form>';
2371
        return $html;
2372
    }
2373
2374
    /**
2375
     * Displays the form to register users in a blog (in a course)
2376
     * The listed users are users subcribed in the course.
2377
     * @author Toon Keppens
2378
     *
2379
     * @param Integer $blog_id
2380
     *
2381
     * @return false|null Form with sortable table with users to unsubcribe from a blog.
2382
     */
2383
    public static function displayUserUnsubscriptionForm($blog_id)
2384
    {
2385
        $_user = api_get_user_info();
2386
        $is_western_name_order = api_is_western_name_order();
2387
        $html = null;
2388
2389
        // Init
2390
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2391
        $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
2392
2393
        $html.= '<legend>'.get_lang('UnsubscribeMembers').'</legend>';
2394
2395
        $properties["width"] = "100%";
2396
        //table column titles
2397
        $column_header[] = array('', false, '');
2398 View Code Duplication
        if ($is_western_name_order) {
2399
            $column_header[] = array(get_lang('FirstName'), true, '');
2400
            $column_header[] = array(get_lang('LastName'), true, '');
2401
        } else {
2402
            $column_header[] = array(get_lang('LastName'), true, '');
2403
            $column_header[] = array(get_lang('FirstName'), true, '');
2404
        }
2405
        $column_header[] = array(get_lang('Email'), false, '');
2406
        $column_header[] = array(get_lang('TaskManager'), true, '');
2407
        $column_header[] = array(get_lang('UnRegister'), false, '');
2408
2409
		$course_id = api_get_course_int_id();
2410
2411
		$sql = "SELECT user.user_id, user.lastname, user.firstname, user.email, user.username
2412
                FROM $tbl_users user INNER JOIN $tbl_blogs_rel_user blogs_rel_user
2413
                ON user.user_id = blogs_rel_user.user_id
2414
                WHERE blogs_rel_user.c_id = $course_id AND  blogs_rel_user.blog_id = '".(int) $blog_id."'";
2415
2416
        if (!($sql_result = Database::query($sql))) {
2417
            return false;
2418
        }
2419
2420
        $user_data = array();
2421
2422
        while ($myrow = Database::fetch_array($sql_result)) {
2423
            $row = array();
2424
            $row[] = '<input type="checkbox" name="user[]" value="'.$myrow['user_id'].'" '.((isset($_GET['selectall']) && $_GET['selectall'] == "unsubscribe") ? ' checked="checked" ' : '').'/>';
2425
            $username = api_htmlentities(sprintf(get_lang('LoginX'), $myrow["username"]), ENT_QUOTES);
2426 View Code Duplication
            if ($is_western_name_order) {
2427
                $row[] = $myrow["firstname"];
2428
                $row[] = Display::tag('span', $myrow["lastname"], array('title' => $username));
2429
            } else {
2430
                $row[] = Display::tag('span', $myrow["lastname"], array('title' => $username));
2431
                $row[] = $myrow["firstname"];
2432
            }
2433
            $row[] = Display::icon_mailto_link($myrow["email"]);
2434
2435
            $sql = "SELECT bt.title task
2436
                    FROM ".Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER)." btu
2437
                    INNER JOIN ".Database::get_course_table(TABLE_BLOGS_TASKS)." bt
2438
                    ON btu.task_id = bt.task_id
2439
                    WHERE 	btu.c_id 	= $course_id  AND
2440
                            bt.c_id 	= $course_id  AND
2441
                            btu.blog_id = $blog_id AND
2442
                            btu.user_id = ".$myrow['user_id'];
2443
            $sql_res = Database::query($sql);
2444
2445
            $task = '';
2446
2447
            while ($r = Database::fetch_array($sql_res)) {
2448
                $task .= stripslashes($r['task']).', ';
2449
            }
2450
            //echo $task;
2451
            $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...
2452
            $row[] = $task;
2453
            //Link to register users
2454
2455 View Code Duplication
            if ($myrow["user_id"] != $_user['user_id']) {
2456
                $row[] = "<a class=\"btn btn-primary\" href=\"".api_get_self(
2457
                    )."?action=manage_members&blog_id=$blog_id&unregister=yes&user_id=".$myrow['user_id']."\">".get_lang(
2458
                        'UnRegister'
2459
                    )."</a>";
2460
            } else {
2461
                $row[] = '';
2462
            }
2463
2464
            $user_data[] = $row;
2465
        }
2466
2467
        $query_vars['action'] = 'manage_members';
2468
        $query_vars['blog_id'] = $blog_id;
2469
        $html.= '<form class="form-inline" method="post" action="blog.php?action=manage_members&blog_id='.$blog_id.'">';
2470
        $html.= Display::return_sortable_table($column_header, $user_data, null, null, $query_vars);
2471
        $link = '';
2472
        $link .= isset ($_GET['action']) ? 'action='.Security::remove_XSS($_GET['action']).'&' : '';
2473
        $link .= "blog_id=$blog_id&";
2474
2475
        $html.= '<a class="btn btn-default" href="blog.php?'.$link.'selectall=unsubscribe">'.get_lang('SelectAll').'</a> - ';
2476
        $html.= '<a class="btn btn-default" href="blog.php?'.$link.'">'.get_lang('UnSelectAll').'</a> ';
2477
        $html.= '<div class="form-group">';
2478
        $html.= '<label>';
2479
        $html.= get_lang('WithSelected').' : ';
2480
        $html.= '</label>';
2481
        $html.= '<select name="action" class="selectpicker">';
2482
        $html.= '<option value="select_unsubscribe">'.get_lang('UnRegister').'</option>';
2483
        $html.= '</select>';
2484
        $html.= '<input type="hidden" name="unregister" value="true" />';
2485
        $html.= '<button class="btn btn-default" type="submit">'.get_lang('Ok').'</button>';
2486
        $html.= '</div>';
2487
        $html.= '</form>';
2488
2489
        return $html;
2490
    }
2491
2492
    /**
2493
     * Displays a matrix with selectboxes. On the left: users, on top: possible rights.
2494
     * The blog admin can thus select what a certain user can do in the current blog
2495
     *
2496
     * @param Integer $blog_id
2497
     */
2498
    public static function displayUserRightsForm($blog_id)
2499
    {
2500
        echo '<legend>'.get_lang('RightsManager').'</legend>';
2501
        echo '<br />';
2502
2503
        // Integration of patricks permissions system.
2504
        require_once api_get_path(SYS_CODE_PATH).'permissions/blog_permissions.inc.php';
2505
    }
2506
2507
	/**
2508
     * show the calender of the given month
2509
     * @author Patrick Cool
2510
     * @author Toon Keppens
2511
     *
2512
     * @param Integer $month : the integer value of the month we are viewing
2513
     * @param Integer $year : the 4-digit year indication e.g. 2005
2514
     *
2515
     * @return html code
2516
     */
2517
    public static function displayMiniMonthCalendar($month, $year, $blog_id)
2518
    {
2519
        // Init
2520
        $_user = api_get_user_info();
2521
        global $DaysShort;
2522
        global $MonthsLong;
2523
        $html = null;
2524
2525
        $posts = array();
2526
        $tasks = array();
2527
2528
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
2529
        $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
2530
        $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
2531
        $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
2532
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
2533
2534
        $course_id = api_get_course_int_id();
2535
2536
        //Handle leap year
2537
        $numberofdays = array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
2538
2539 View Code Duplication
        if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 <> 0)) {
2540
            $numberofdays[2] = 29;
2541
        }
2542
2543
        //Get the first day of the month
2544
        $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
2545
        $monthName = $MonthsLong[$month - 1];
2546
2547
        //Start the week on monday
2548
        $startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6;
2549
        $blogId = isset($_GET['blog_id']) ? intval($_GET['blog_id']) : null;
2550
        $filter = isset($_GET['filter']) ? Security::remove_XSS($_GET['filter']) : null;
2551
        $backwardsURL = api_get_self(
2552
            )."?blog_id=".$blogId."&filter=".$filter."&month=".($month == 1 ? 12 : $month - 1)."&year=".($month == 1 ? $year - 1 : $year);
2553
        $forewardsURL = api_get_self(
2554
            )."?blog_id=".$blogId."&filter=".$filter."&month=".($month == 12 ? 1 : $month + 1)."&year=".($month == 12 ? $year + 1 : $year);
2555
2556
        // Get posts for this month
2557
        $sql = "SELECT post.*, DAYOFMONTH(date_creation) as post_day, user.lastname, user.firstname
2558
                FROM $tbl_blogs_posts post
2559
                INNER JOIN $tbl_users user
2560
                ON post.author_id = user.user_id
2561
                WHERE
2562
                    post.c_id = $course_id AND
2563
                    post.blog_id = '".(int) $blog_id."' AND
2564
                    MONTH(date_creation) = '".(int) $month."' AND
2565
                    YEAR(date_creation) = '".(int) $year."'
2566
                ORDER BY date_creation";
2567
        $result = Database::query($sql);
2568
2569
        // We will create an array of days on which there are posts.
2570 View Code Duplication
        if (Database::num_rows($result) > 0) {
2571
            while ($blog_post = Database::fetch_array($result)) {
2572
                // If the day of this post is not yet in the array, add it.
2573
                if (!in_array($blog_post['post_day'], $posts)) {
2574
                    $posts[] = $blog_post['post_day'];
2575
                }
2576
            }
2577
        }
2578
2579
        // Get tasks for this month
2580
        if ($_user['user_id']) {
2581
            $sql = " SELECT task_rel_user.*,  DAYOFMONTH(target_date) as task_day, task.title, blog.blog_name
2582
                FROM $tbl_blogs_tasks_rel_user task_rel_user
2583
                INNER JOIN $tbl_blogs_tasks task ON task_rel_user.task_id = task.task_id
2584
                INNER JOIN $tbl_blogs blog ON task_rel_user.blog_id = blog.blog_id
2585
                WHERE
2586
                    task_rel_user.c_id = $course_id AND
2587
                    task.c_id = $course_id AND
2588
                    blog.c_id = $course_id AND
2589
                    task_rel_user.user_id = '".(int) $_user['user_id']."' AND
2590
                    MONTH(target_date) = '".(int) $month."' AND
2591
                    YEAR(target_date) = '".(int) $year."'
2592
                ORDER BY target_date ASC";
2593
            $result = Database::query($sql);
2594
2595
            if (Database::num_rows($result) > 0) {
2596
                while ($mytask = Database::fetch_array($result)) {
2597
                    $tasks[$mytask['task_day']][$mytask['task_id']]['task_id'] = $mytask['task_id'];
2598
                    $tasks[$mytask['task_day']][$mytask['task_id']]['title'] = $mytask['title'];
2599
                    $tasks[$mytask['task_day']][$mytask['task_id']]['blog_id'] = $mytask['blog_id'];
2600
                    $tasks[$mytask['task_day']][$mytask['task_id']]['blog_name'] = $mytask['blog_name'];
2601
                    $tasks[$mytask['task_day']][$mytask['task_id']]['day'] = $mytask['task_day'];
2602
                }
2603
            }
2604
        }
2605
2606
        $html .= '<table id="smallcalendar" class="table table-responsive">
2607
                <tr id="title">
2608
                <th width="10%"><a href="'.$backwardsURL.'">&laquo;</a></th>
2609
                <th align="center" width="80%" colspan="5" class="month">'.$monthName.' '.$year.'</th>
2610
                <th width="10%" align="right"><a href="'.$forewardsURL.'">&raquo;</a></th></tr>';
2611
2612
        $html .= '<tr>';
2613
2614 View Code Duplication
        for ($ii = 1; $ii < 8; $ii++) {
2615
            $html .= '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
2616
        }
2617
2618
        $html .= '</tr>';
2619
2620
		$curday = -1;
2621
		$today = getdate();
2622
2623
        while ($curday <= $numberofdays[$month]) {
2624
            $html .= '<tr>';
2625
            for ($ii = 0; $ii < 7; $ii++) {
2626
                if (($curday == -1) && ($ii == $startdayofweek)) {
2627
                    $curday = 1;
2628
                }
2629
2630
                if (($curday > 0) && ($curday <= $numberofdays[$month])) {
2631
                    $bgcolor = $ii < 5 ? $class = "class=\"days_week\"" : $class = "class=\"days_weekend\"";
2632
                    $dayheader = "$curday";
2633
2634 View Code Duplication
                    if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
2635
                        $dayheader = "$curday";
2636
                        $class = "class=\"days_today\"";
2637
                    }
2638
2639
                    $html .= '<td '.$class.'>';
2640
2641
                    // If there are posts on this day, create a filter link.
2642
                    if (in_array($curday, $posts)) {
2643
                        $html .= '<a href="blog.php?blog_id='.$blog_id.'&filter='.$year.'-'.$month.'-'.$curday.'&month='.$month.'&year='.$year.'" title="'.get_lang(
2644
                                'ViewPostsOfThisDay'
2645
                            ).'">'.$curday.'</a>';
2646
                    } else {
2647
                        $html .= $dayheader;
2648
                    }
2649
2650
                    if (count($tasks) > 0) {
2651
                        if (isset($tasks[$curday]) && is_array($tasks[$curday])) {
2652
                            // Add tasks to calendar
2653
                            foreach ($tasks[$curday] as $task) {
2654
                                $html .= '<a href="blog.php?action=execute_task&blog_id='.$task['blog_id'].'&task_id='.stripslashes(
2655
                                        $task['task_id']
2656
                                    ).'" title="'.$task['title'].' : '.get_lang(
2657
                                        'InBlog'
2658
                                    ).' : '.$task['blog_name'].' - '.get_lang('ExecuteThisTask').'">';
2659
                                $html .= Display::return_icon('blog_task.gif', get_lang('ExecuteThisTask'));
2660
                                $html .= '</a>';
2661
                            }
2662
                        }
2663
                    }
2664
2665
                    $html .= '</td>';
2666
                    $curday++;
2667
                } else {
2668
                    $html .= '<td>&nbsp;</td>';
2669
                }
2670
            }
2671
            $html .= '</tr>';
2672
        }
2673
        $html .= '</table>';
2674
2675
        return $html;
2676
    }
2677
2678
    /**
2679
     * Blog admin | Display the form to add a new blog.
2680
     * @return void (direct output)
2681
     */
2682
    public static function displayBlogCreateForm()
2683
    {
2684
        $form = new FormValidator('add_blog', 'post', 'blog_admin.php?action=add');
2685
        $form->addElement('header', get_lang('AddBlog'));
2686
        $form->addElement('text', 'blog_name', get_lang('Title'));
2687
        $form->addElement('textarea', 'blog_subtitle', get_lang('SubTitle'));
2688
2689
        $form->addElement('hidden', 'new_blog_submit', 'true');
2690
        $form->addButtonSave(get_lang('SaveProject'));
2691
2692
        $defaults = array(
2693
            'blog_name' => isset($_POST['blog_name']) ? Security::remove_XSS($_POST['blog_name']) : null,
2694
            'blog_subtitle' => isset($_POST['blog_subtitle']) ? Security::remove_XSS($_POST['blog_subtitle']) : null,
2695
        );
2696
        $form->setDefaults($defaults);
2697
        $form->display();
2698
    }
2699
2700
    /**
2701
     * Blog admin | Display the form to edit a blog.
2702
     *
2703
     */
2704
    public static function displayBlogEditForm($blog_id)
2705
    {
2706
        $course_id = api_get_course_int_id();
2707
        $blog_id = intval($blog_id);
2708
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
2709
2710
        $sql = "SELECT blog_id, blog_name, blog_subtitle
2711
                FROM $tbl_blogs
2712
                WHERE c_id = $course_id AND blog_id = '".$blog_id."'";
2713
        $result = Database::query($sql);
2714
        $blog = Database::fetch_array($result);
2715
2716
		// the form contained errors but we do not want to lose the changes the user already did
2717
		if ($_POST) {
2718
			$blog['blog_name'] = Security::remove_XSS($_POST['blog_name']);
2719
			$blog['blog_subtitle'] = Security::remove_XSS($_POST['blog_subtitle']);
2720
		}
2721
2722
        $form = new FormValidator('edit_blog', 'post', 'blog_admin.php?action=edit&blog_id='.intval($_GET['blog_id']));
2723
        $form->addElement('header', get_lang('EditBlog'));
2724
        $form->addElement('text', 'blog_name', get_lang('Title'));
2725
        $form->addElement('textarea', 'blog_subtitle', get_lang('SubTitle'));
2726
2727
        $form->addElement('hidden', 'edit_blog_submit', 'true');
2728
        $form->addElement('hidden', 'blog_id', $blog['blog_id']);
2729
        $form->addButtonSave(get_lang('Save'));
2730
2731
        $defaults = array();
2732
        $defaults['blog_name'] = $blog['blog_name'];
2733
        $defaults['blog_subtitle'] = $blog['blog_subtitle'];
2734
        $form->setDefaults($defaults);
2735
        $form->display();
2736
	}
2737
2738
    /**
2739
     * Blog admin | Returns table with blogs in this course
2740
     * @return void Direct output
2741
     */
2742
    public static function displayBlogsList()
2743
    {
2744
		global $charset;
2745
		$_user = api_get_user_info();
2746
        $course_id = api_get_course_int_id();
2747
2748
		$tbl_blogs = Database::get_course_table(TABLE_BLOGS);
2749
2750
		//condition for the session
2751
		$session_id = api_get_session_id();
2752
2753
        $sql = "SELECT blog_name, blog_subtitle, visibility, blog_id, session_id
2754
                FROM $tbl_blogs WHERE c_id = $course_id
2755
                ORDER BY date_creation DESC";
2756
        $result = Database::query($sql);
2757
        $list_info = array();
2758
        if (Database::num_rows($result)) {
2759
            while ($row_project = Database::fetch_row($result)) {
2760
                $list_info[] = $row_project;
2761
            }
2762
        }
2763
2764
		$list_content_blog = array();
2765
		$list_body_blog = array();
2766
2767
		if (is_array($list_info)) {
2768
			foreach ($list_info as $key => $info_log) {
2769
				// Validation when belongs to a session
2770
				$session_img = api_get_session_image($info_log[4], $_user['status']);
2771
2772
                $url_start_blog = 'blog.php'."?"."blog_id=".$info_log[3]."&".api_get_cidreq();
2773
                $title = $info_log[0];
2774
                $image = Display::return_icon('blog.png', $title);
2775
                $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;
2776
2777
				$list_body_blog[] = $list_name;
2778
				$list_body_blog[] = $info_log[1];
2779
2780
                $visibility_icon = ($info_log[2] == 0) ? 'invisible' : 'visible';
2781
                $visibility_info = ($info_log[2] == 0) ? 'Visible' : 'Invisible';
2782
                $my_image = '<a href="'.api_get_self().'?action=edit&blog_id='.$info_log[3].'">';
2783
                $my_image .= Display::return_icon('edit.png', get_lang('EditBlog'));
2784
2785
                $my_image .= "</a>";
2786
                $my_image .= '<a href="'.api_get_self().'?action=delete&blog_id='.$info_log[3].'" ';
2787
                $my_image .= 'onclick="javascript:if(!confirm(\''.addslashes(
2788
                        api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)
2789
                    ).'\')) return false;" >';
2790
                $my_image .= Display::return_icon('delete.png', get_lang('DeleteBlog'));
2791
2792
                $my_image .= "</a>";
2793
                $my_image .= '<a href="'.api_get_self().'?action=visibility&blog_id='.$info_log[3].'">';
2794
                $my_image .= Display::return_icon($visibility_icon.'.gif', get_lang($visibility_info));
2795
2796
                $my_image .= "</a>";
2797
                $list_body_blog[] = $my_image;
2798
                $list_content_blog[] = $list_body_blog;
2799
                $list_body_blog = array();
2800
            }
2801
2802
            $table = new SortableTableFromArrayConfig($list_content_blog, 1, 20, 'project');
2803
            $table->set_header(0, get_lang('Title'));
2804
            $table->set_header(1, get_lang('SubTitle'));
2805
            $table->set_header(2, get_lang('Modify'));
2806
            $table->display();
2807
        }
2808
    }
2809
2810
    /**
2811
     * Filter the post $fullText to get a extract of $length characters
2812
     * @param string $fullText
0 ignored issues
show
Bug introduced by
There is no parameter named $fullText. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
2813
     * @param int $length
0 ignored issues
show
Bug introduced by
There is no parameter named $length. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
2814
     * @return null|string
2815
     */
2816
    public static function getBlogAttachments($blog_id, $post_id = 0, $comment_id = 0)
2817
    {
2818
        $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
2819
        $blog_id = intval($blog_id);
2820
        $comment_id = intval($comment_id);
2821
        $post_id = intval($post_id);
2822
        $row = array();
2823
        $where = '';
2824
        if (!empty ($post_id) && is_numeric($post_id)) {
2825
            $where .= " AND post_id = $post_id ";
2826
        }
2827 View Code Duplication
        if (!empty ($comment_id) && is_numeric($comment_id)) {
2828
            if (!empty ($post_id)) {
2829
                $where .= ' AND ';
2830
            }
2831
            $where .= " comment_id = $comment_id ";
2832
        }
2833
        $course_id = api_get_course_int_id();
2834
        $sql = "SELECT path, filename, comment FROM $blog_table_attachment
2835
	        WHERE c_id = $course_id AND blog_id = $blog_id  $where";
2836
        $result = Database::query($sql);
2837
        if (Database::num_rows($result) != 0) {
2838
            $row = Database::fetch_array($result);
2839
        }
2840
        return $row;
2841
    }
2842
2843
    /**
2844
     * Delete the all the attachments according the parameters.
2845
     * @param int $blog_id
2846
     * @param int $post_id post's id
2847
     * @param int $comment_id the comment's id
2848
     * @return void
2849
     * @author Julio Montoya
2850
     * @version avril 2008, dokeos 1.8.5
2851
     */
2852
    public static function deleteAllBlogAttachments(
2853
        $blog_id,
2854
        $post_id = 0,
2855
        $comment_id = 0
2856
    ) {
2857
        $_course = api_get_course_info();
2858
        $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
2859
        $blog_id = intval($blog_id);
2860
        $comment_id = intval($comment_id);
2861
        $post_id = intval($post_id);
2862
        
2863
        $course_id = api_get_course_int_id();
2864
        $where = null;
2865
    
2866
        // delete files in DB
2867
        if (!empty ($post_id) && is_numeric($post_id)) {
2868
            $where .= ' AND post_id ="'.$post_id.'" ';
2869
        }
2870
    
2871 View Code Duplication
        if (!empty ($comment_id) && is_numeric($comment_id)) {
2872
            if (!empty ($post_id)) {
2873
                $where .= ' AND ';
2874
            }
2875
            $where .= ' comment_id ="'.$comment_id.'" ';
2876
        }
2877
    
2878
        // delete all files in directory
2879
        $courseDir = $_course['path'].'/upload/blog';
2880
        $sys_course_path = api_get_path(SYS_COURSE_PATH);
2881
        $updir = $sys_course_path.$courseDir;
2882
2883
        $sql = 'SELECT path FROM '.$blog_table_attachment.'
2884
                WHERE c_id = '.$course_id.' AND blog_id ="'.intval($blog_id).'"  '.$where;
2885
        $result = Database::query($sql);
2886
2887
        while ($row = Database::fetch_row($result)) {
2888
            $file = $updir.'/'.$row[0];
2889
            if (Security::check_abs_path($file, $updir)) {
2890
                @ unlink($file);
2891
            }
2892
        }
2893
        $sql = 'DELETE FROM '.$blog_table_attachment.'
2894
                WHERE c_id = '.$course_id.' AND  blog_id ="'.intval($blog_id).'"  '.$where;
2895
        Database::query($sql);
2896
    }
2897
2898
    /**
2899
     * Gets all the post from a given user id
2900
     * @param int $courseId
2901
     * @param int $userId
2902
     * @param string $courseCode
2903
     * @return string
2904
     */
2905
    public static function getBlogPostFromUser($courseId, $userId, $courseCode)
2906
    {
2907
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
2908
        $tbl_blog_post = Database::get_course_table(TABLE_BLOGS_POSTS);
2909
        $courseId = intval($courseId);
2910
        $userId = intval($userId);
2911
2912
        $sql = "SELECT DISTINCT blog.blog_id, post_id, title, full_text, post.date_creation
2913
                FROM $tbl_blogs blog
2914
                INNER JOIN  $tbl_blog_post post
2915
                ON (blog.blog_id = post.blog_id)
2916
                WHERE
2917
                    blog.c_id = $courseId AND
2918
                    post.c_id = $courseId AND
2919
                    author_id =  $userId AND visibility = 1
2920
                ORDER BY post.date_creation DESC ";
2921
        $result = Database::query($sql);
2922
        $return_data = '';
2923
2924
        if (Database::num_rows($result) != 0) {
2925
            while ($row = Database::fetch_array($result)) {
2926
                $return_data .= '<div class="clear"></div><br />';
2927
                $return_data .= '<div class="actions" style="margin-left:5px;margin-right:5px;">'.Display::return_icon(
2928
                        'blog_article.png',
2929
                        get_lang('BlogPosts')
2930
                    ).' '.$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='.$courseId.' " >'.get_lang(
2931
                        'SeeBlog'
2932
                    ).'</a></div></div>';
2933
                $return_data .= '<br / >';
2934
                $return_data .= $row['full_text'];
2935
                $return_data .= '<br /><br />';
2936
            }
2937
        }
2938
2939
        return $return_data;
2940
    }
2941
2942
    /**
2943
     * Gets all the post comments from a given user id
2944
     * @param int $courseId
2945
     * @param int $userId
2946
     * @param string $courseCode
2947
     * @return string
2948
     */
2949
    public static function getBlogCommentsFromUser($courseId, $userId, $courseCode)
2950
    {
2951
        $tbl_blogs = Database::get_course_table(TABLE_BLOGS);
2952
        $tbl_blog_comment = Database::get_course_table(TABLE_BLOGS_COMMENTS);
2953
2954
        $userId = intval($userId);
2955
        $courseId = intval($courseId);
2956
2957
        $sql = "SELECT DISTINCT blog.blog_id, comment_id, title, comment, comment.date_creation
2958
                FROM $tbl_blogs blog INNER JOIN  $tbl_blog_comment comment
2959
                ON (blog.blog_id = comment.blog_id)
2960
                WHERE 	blog.c_id = $courseId AND
2961
                        comment.c_id = $courseId AND
2962
                        author_id =  $userId AND
2963
                        visibility = 1
2964
                ORDER BY blog_name";
2965
        $result = Database::query($sql);
2966
        $return_data = '';
2967
        if (Database::num_rows($result) != 0) {
2968
            while ($row = Database::fetch_array($result)) {
2969
                $return_data .= '<div class="clear"></div><br />';
2970
                $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(
2971
                        $courseCode
2972
                    ).' " >'.get_lang('SeeBlog').'</a></div></div>';
2973
                $return_data .= '<br / >';
2974
                $return_data .= $row['comment'];
2975
                $return_data .= '<br />';
2976
            }
2977
        }
2978
2979
        return $return_data;
2980
    }
2981
2982
    /**
2983
     * Filter the post $fullText to get a extract of $length characters
2984
     * @param string $fullText
2985
     * @param int $length
2986
     * @return null|string
2987
     */
2988
    private static function getPostExtract($fullText, $length = BLOG_MAX_PREVIEW_CHARS)
2989
    {
2990
        $parts = explode(BLOG_PAGE_BREAK, $fullText);
2991
        if (count($parts) > 1) {
2992
            return $parts[0];
2993
        }
2994
        // Remove any HTML from the string
2995
        $text = strip_tags($fullText);
2996
        $text = api_html_entity_decode($text);
2997
        // Replace end of lines with spaces
2998
        $text = preg_replace('/\s+/', ' ', $text);
2999
        // Count whitespaces to add to the cut() call below
3000
        $countBlanks = substr_count($text, ' ');
3001
        // Get a version of the string without spaces for comparison purposes
3002
        $textWithoutBlanks = str_replace(' ', '', $text);
3003
        // utf8_decode replaces non-ISO chars by '?' which avoids counting
3004
        // multi-byte characters as more than one character
3005
        $stringLength = strlen(utf8_decode($textWithoutBlanks));
3006
        if ($stringLength <= $length) {
3007
            return null;
3008
        }
3009
        // Cut the string to the BLOG_MAX_PREVIEX_CHARS limit, adding
3010
        // whitespaces
3011
        $extract = cut($text, $length + $countBlanks);
3012
        // Return an HTML string for printing
3013
        return api_htmlentities($extract);
3014
    }
3015
}
3016