Passed
Pull Request — 1.11.x (#4515)
by Angel Fernando Quiroz
07:53
created

Wiki::allPages()   C

Complexity

Conditions 13
Paths 4

Size

Total Lines 189
Code Lines 126

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 126
c 2
b 0
f 0
dl 0
loc 189
rs 5.2933
cc 13
nc 4
nop 1

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
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CourseBundle\Entity\CWiki;
6
use Chamilo\CourseBundle\Entity\CWikiCategory;
7
use ChamiloSession as Session;
8
use Doctrine\DBAL\Driver\Statement;
9
10
/**
11
 * Class Wiki
12
 * Functions library for the wiki tool.
13
 *
14
 * @author Juan Carlos Raña <[email protected]>
15
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
16
 * @author Julio Montoya <[email protected]> using the pdf.lib.php library
17
 */
18
class Wiki
19
{
20
    public $tbl_wiki;
21
    public $tbl_wiki_discuss;
22
    public $tbl_wiki_mailcue;
23
    public $tbl_wiki_conf;
24
    public $session_id = null;
25
    public $course_id = null;
26
    public $condition_session = null;
27
    public $group_id;
28
    public $assig_user_id;
29
    public $groupfilter = 'group_id=0';
30
    public $courseInfo;
31
    public $charset;
32
    public $page;
33
    public $action;
34
    public $wikiData = [];
35
    public $url;
36
37
    /**
38
     * Constructor.
39
     */
40
    public function __construct()
41
    {
42
        // Database table definition
43
        $this->tbl_wiki = Database::get_course_table(TABLE_WIKI);
44
        $this->tbl_wiki_discuss = Database::get_course_table(
45
            TABLE_WIKI_DISCUSS
46
        );
47
        $this->tbl_wiki_mailcue = Database::get_course_table(
48
            TABLE_WIKI_MAILCUE
49
        );
50
        $this->tbl_wiki_conf = Database::get_course_table(TABLE_WIKI_CONF);
51
52
        $this->session_id = api_get_session_id();
53
        $this->condition_session = api_get_session_condition($this->session_id);
54
        $this->course_id = api_get_course_int_id();
55
        $this->group_id = api_get_group_id();
56
57
        if (!empty($this->group_id)) {
58
            $this->groupfilter = ' group_id="'.$this->group_id.'"';
59
        }
60
        $this->courseInfo = api_get_course_info();
61
        $this->url = api_get_path(WEB_CODE_PATH).'wiki/index.php?'.api_get_cidreq();
62
    }
63
64
    /**
65
     * Check whether this title is already used.
66
     *
67
     * @param string $link
68
     *
69
     * @return bool False if title is already taken
70
     *
71
     * @author Patrick Cool <[email protected]>, Ghent University
72
     */
73
    public function checktitle($link)
74
    {
75
        $tbl_wiki = $this->tbl_wiki;
76
        $condition_session = $this->condition_session;
77
        $course_id = $this->course_id;
78
        $groupfilter = $this->groupfilter;
79
80
        $sql = 'SELECT * FROM '.$tbl_wiki.'
81
                WHERE
82
                    c_id = '.$course_id.' AND
83
                    reflink="'.Database::escape_string($link).'" AND
84
                    '.$groupfilter.$condition_session.'';
85
        $result = Database::query($sql);
86
        $num = Database::num_rows($result);
87
        // the value has not been found and is this available
88
        if ($num == 0) {
89
            return true;
90
        }
91
92
        return false;
93
    }
94
95
    /**
96
     * check wikilinks that has a page.
97
     *
98
     * @author Juan Carlos Raña <[email protected]>
99
     *
100
     * @param string $input
101
     *
102
     * @return string
103
     */
104
    public function links_to($input)
105
    {
106
        $input_array = preg_split(
107
            "/(\[\[|\]\])/",
108
            $input,
109
            -1,
110
            PREG_SPLIT_DELIM_CAPTURE
111
        );
112
        $all_links = [];
113
114
        foreach ($input_array as $key => $value) {
115
            if (isset($input_array[$key - 1]) && $input_array[$key - 1] == '[[' &&
116
                isset($input_array[$key + 1]) && $input_array[$key + 1] == ']]'
117
            ) {
118
                if (api_strpos($value, "|") !== false) {
119
                    $full_link_array = explode("|", $value);
120
                    $link = trim($full_link_array[0]);
121
                    $title = trim($full_link_array[1]);
122
                } else {
123
                    $link = trim($value);
124
                    $title = trim($value);
125
                }
126
                unset($input_array[$key - 1]);
127
                unset($input_array[$key + 1]);
128
                //replace blank spaces by _ within the links. But to remove links at the end add a blank space
129
                $all_links[] = Database::escape_string(
130
                    str_replace(' ', '_', $link)
131
                ).' ';
132
            }
133
        }
134
135
        return implode($all_links);
136
    }
137
138
    /**
139
     * detect and add style to external links.
140
     *
141
     * @author Juan Carlos Raña Trabado
142
     */
143
    public function detect_external_link($input)
144
    {
145
        $exlink = 'href=';
146
        $exlinkStyle = 'class="wiki_link_ext" href=';
147
148
        return str_replace($exlink, $exlinkStyle, $input);
149
    }
150
151
    /**
152
     * detect and add style to anchor links.
153
     *
154
     * @author Juan Carlos Raña Trabado
155
     */
156
    public function detect_anchor_link($input)
157
    {
158
        $anchorlink = 'href="#';
159
        $anchorlinkStyle = 'class="wiki_anchor_link" href="#';
160
        $output = str_replace($anchorlink, $anchorlinkStyle, $input);
161
162
        return $output;
163
    }
164
165
    /**
166
     * detect and add style to mail links
167
     * author Juan Carlos Raña Trabado.
168
     */
169
    public function detect_mail_link($input)
170
    {
171
        $maillink = 'href="mailto';
172
        $maillinkStyle = 'class="wiki_mail_link" href="mailto';
173
        $output = str_replace($maillink, $maillinkStyle, $input);
174
175
        return $output;
176
    }
177
178
    /**
179
     * detect and add style to ftp links.
180
     *
181
     * @author Juan Carlos Raña Trabado
182
     */
183
    public function detect_ftp_link($input)
184
    {
185
        $ftplink = 'href="ftp';
186
        $ftplinkStyle = 'class="wiki_ftp_link" href="ftp';
187
        $output = str_replace($ftplink, $ftplinkStyle, $input);
188
189
        return $output;
190
    }
191
192
    /**
193
     * detect and add style to news links.
194
     *
195
     * @author Juan Carlos Raña Trabado
196
     */
197
    public function detect_news_link($input)
198
    {
199
        $newslink = 'href="news';
200
        $newslinkStyle = 'class="wiki_news_link" href="news';
201
        $output = str_replace($newslink, $newslinkStyle, $input);
202
203
        return $output;
204
    }
205
206
    /**
207
     * detect and add style to irc links.
208
     *
209
     * @author Juan Carlos Raña Trabado
210
     */
211
    public function detect_irc_link($input)
212
    {
213
        $irclink = 'href="irc';
214
        $irclinkStyle = 'class="wiki_irc_link" href="irc';
215
        $output = str_replace($irclink, $irclinkStyle, $input);
216
217
        return $output;
218
    }
219
220
    /**
221
     * This function allows users to have [link to a title]-style links like in most regular wikis.
222
     * It is true that the adding of links is probably the most anoying part of Wiki for the people
223
     * who know something about the wiki syntax.
224
     *
225
     * @author Patrick Cool <[email protected]>, Ghent University
226
     * Improvements [[]] and [[ | ]]by Juan Carlos Raña
227
     * Improvements internal wiki style and mark group by Juan Carlos Raña
228
     */
229
    public function make_wiki_link_clickable($input)
230
    {
231
        $groupId = api_get_group_id();
232
        //now doubles brackets
233
        $input_array = preg_split(
234
            "/(\[\[|\]\])/",
235
            $input,
236
            -1,
237
            PREG_SPLIT_DELIM_CAPTURE
238
        );
239
240
        foreach ($input_array as $key => $value) {
241
            //now doubles brackets
242
            if (isset($input_array[$key - 1]) &&
243
                $input_array[$key - 1] == '[[' && $input_array[$key + 1] == ']]'
244
            ) {
245
                // now full wikilink
246
                if (api_strpos($value, "|") !== false) {
247
                    $full_link_array = explode("|", $value);
248
                    $link = trim(strip_tags($full_link_array[0]));
249
                    $title = trim($full_link_array[1]);
250
                } else {
251
                    $link = trim(strip_tags($value));
252
                    $title = trim($value);
253
                }
254
255
                //if wikilink is homepage
256
                if ($link == 'index') {
257
                    $title = get_lang('DefaultTitle');
258
                }
259
                if ($link == get_lang('DefaultTitle')) {
260
                    $link = 'index';
261
                }
262
263
                // note: checkreflink checks if the link is still free. If it is not used then it returns true, if it is used, then it returns false. Now the title may be different
264
                if (self::checktitle(
265
                    strtolower(str_replace(' ', '_', $link))
266
                )) {
267
                    $link = api_html_entity_decode($link);
268
                    $input_array[$key] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?'.api_get_cidreq().'&action=addnew&title='.Security::remove_XSS($link).'&group_id='.$groupId.'" class="new_wiki_link">'.$title.'</a>';
269
                } else {
270
                    $input_array[$key] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?'.api_get_cidreq().'&action=showpage&title='.urlencode(strtolower(str_replace(' ', '_', $link))).'&group_id='.$groupId.'" class="wiki_link">'.$title.'</a>';
271
                }
272
                unset($input_array[$key - 1]);
273
                unset($input_array[$key + 1]);
274
            }
275
        }
276
        $output = implode('', $input_array);
277
278
        return $output;
279
    }
280
281
    /**
282
     * This function saves a change in a wiki page.
283
     *
284
     * @author Patrick Cool <[email protected]>, Ghent University
285
     *
286
     * @param array $values
287
     *
288
     * @return string
289
     */
290
    public function save_wiki($values)
291
    {
292
        $tbl_wiki = $this->tbl_wiki;
293
        $tbl_wiki_conf = $this->tbl_wiki_conf;
294
295
        $_course = $this->courseInfo;
296
        $time = api_get_utc_datetime(null, false, true);
297
        $session_id = api_get_session_id();
298
        $groupId = api_get_group_id();
299
        $userId = api_get_user_id();
300
        $groupInfo = GroupManager::get_group_properties($groupId);
301
        $course_id = api_get_course_int_id();
302
303
        $_clean = [
304
            'task' => '',
305
            'feedback1' => '',
306
            'feedback2' => '',
307
            'feedback3' => '',
308
            'fprogress1' => '',
309
            'fprogress2' => '',
310
            'fprogress3' => '',
311
            'max_text' => 0,
312
            'max_version' => 0,
313
            'delayedsubmit' => '',
314
            'assignment' => 0,
315
        ];
316
317
        $pageId = intval($values['page_id']);
318
319
        // NOTE: visibility, visibility_disc and ratinglock_disc changes
320
        // are not made here, but through the interce buttons
321
322
        // cleaning the variables
323
        if (api_get_setting('htmlpurifier_wiki') == 'true') {
324
            //$purifier = new HTMLPurifier();
325
            $values['content'] = Security::remove_XSS($values['content']);
326
        }
327
        $version = intval($values['version']) + 1;
328
        $linkTo = self::links_to($values['content']); //and check links content
329
330
        //cleaning config variables
331
        if (!empty($values['task'])) {
332
            $_clean['task'] = $values['task'];
333
        }
334
335
        if (!empty($values['feedback1']) ||
336
            !empty($values['feedback2']) ||
337
            !empty($values['feedback3'])
338
        ) {
339
            $_clean['feedback1'] = $values['feedback1'];
340
            $_clean['feedback2'] = $values['feedback2'];
341
            $_clean['feedback3'] = $values['feedback3'];
342
            $_clean['fprogress1'] = $values['fprogress1'];
343
            $_clean['fprogress2'] = $values['fprogress2'];
344
            $_clean['fprogress3'] = $values['fprogress3'];
345
        }
346
347
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
348
            $_clean['startdate_assig'] = $values['startdate_assig'];
349
        } else {
350
            $_clean['startdate_assig'] = null;
351
        }
352
353
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
354
            $_clean['enddate_assig'] = $values['enddate_assig'];
355
        } else {
356
            $_clean['enddate_assig'] = null;
357
        }
358
359
        if (isset($values['delayedsubmit'])) {
360
            $_clean['delayedsubmit'] = $values['delayedsubmit'];
361
        }
362
363
        if (!empty($values['max_text']) || !empty($values['max_version'])) {
364
            $_clean['max_text'] = $values['max_text'];
365
            $_clean['max_version'] = $values['max_version'];
366
        }
367
368
        $values['assignment'] = $values['assignment'] ?? 0;
369
        $values['page_id'] = $values['page_id'] ?? 0;
370
371
        $em = Database::getManager();
372
373
        $newWiki = (new CWiki())
374
            ->setCId($course_id)
375
            ->setAddlock(1)
376
            ->setVisibility(1)
377
            ->setVisibilityDisc(1)
378
            ->setAddlockDisc(1)
379
            ->setRatinglockDisc(1)
380
            ->setPageId($pageId)
381
            ->setReflink(trim($values['reflink']))
382
            ->setTitle(trim($values['title']))
383
            ->setContent($values['content'])
384
            ->setUserId($userId)
385
            ->setGroupId($groupId)
386
            ->setDtime($time)
387
            ->setAssignment($values['assignment'])
388
            ->setComment($values['comment'])
389
            ->setProgress($values['progress'])
390
            ->setVersion($version)
391
            ->setLinksto($linkTo)
392
            ->setUserIp($_SERVER['REMOTE_ADDR'])
393
            ->setSessionId($session_id)
394
            ->setPageId($values['page_id'])
395
            ->setEditlock(0)
396
            ->setIsEditing(0)
397
            ->setTimeEdit($time)
398
            ->setTag('')
399
        ;
400
401
        $em->persist($newWiki);
402
        $em->flush();
403
404
        $id = $newWiki->getIid();
405
406
        if ($id > 0) {
407
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
408
            Database::query($sql);
409
410
            // insert into item_property
411
            api_item_property_update(
412
                $_course,
413
                TOOL_WIKI,
414
                $id,
415
                'WikiAdded',
416
                $userId,
417
                $groupInfo
418
            );
419
420
            if ($values['page_id'] == 0) {
421
                $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
422
                        WHERE c_id = '.$course_id.' AND iid ="'.$id.'"';
423
                Database::query($sql);
424
            }
425
426
            self::assignCategoriesToWiki($newWiki, $values['category']);
427
        }
428
429
        // Update wiki config
430
        if ($values['reflink'] == 'index' && $version == 1) {
431
            $params = [
432
                'c_id' => $course_id,
433
                'page_id' => $id,
434
                'task' => $_clean['task'],
435
                'feedback1' => $_clean['feedback1'],
436
                'feedback2' => $_clean['feedback2'],
437
                'feedback3' => $_clean['feedback3'],
438
                'fprogress1' => $_clean['fprogress1'],
439
                'fprogress2' => $_clean['fprogress2'],
440
                'fprogress3' => $_clean['fprogress3'],
441
                'max_text' => intval($_clean['max_text']),
442
                'max_version' => intval($_clean['max_version']),
443
                'startdate_assig' => $_clean['startdate_assig'],
444
                'enddate_assig' => $_clean['enddate_assig'],
445
                'delayedsubmit' => $_clean['delayedsubmit'],
446
            ];
447
            Database::insert($tbl_wiki_conf, $params);
448
        } else {
449
            $params = [
450
                'task' => $_clean['task'],
451
                'feedback1' => $_clean['feedback1'],
452
                'feedback2' => $_clean['feedback2'],
453
                'feedback3' => $_clean['feedback3'],
454
                'fprogress1' => $_clean['fprogress1'],
455
                'fprogress2' => $_clean['fprogress2'],
456
                'fprogress3' => $_clean['fprogress3'],
457
                'max_text' => intval($_clean['max_text']),
458
                'max_version' => intval($_clean['max_version']),
459
                'startdate_assig' => $_clean['startdate_assig'],
460
                'enddate_assig' => $_clean['enddate_assig'],
461
                'delayedsubmit' => $_clean['delayedsubmit'],
462
            ];
463
            Database::update(
464
                $tbl_wiki_conf,
465
                $params,
466
                ['page_id = ? AND c_id = ?' => [$pageId, $course_id]]
467
            );
468
        }
469
470
        api_item_property_update(
471
            $_course,
472
            'wiki',
473
            $id,
474
            'WikiAdded',
475
            $userId,
476
            $groupInfo
477
        );
478
        self::check_emailcue($_clean['reflink'], 'P', $time, $userId);
479
        $this->setWikiData($id);
480
481
        return get_lang('Saved');
482
    }
483
484
    /**
485
     * This function restore a wikipage.
486
     *
487
     * @author Juan Carlos Raña <[email protected]>
488
     *
489
     * @return string Message of success (to be printed on screen)
490
     */
491
    public function restore_wikipage(
492
        $r_page_id,
493
        $r_reflink,
494
        $r_title,
495
        $r_content,
496
        $r_group_id,
497
        $r_assignment,
498
        $r_progress,
499
        $c_version,
500
        $r_version,
501
        $r_linksto
502
    ) {
503
        $tbl_wiki = $this->tbl_wiki;
504
        $_course = $this->courseInfo;
505
        $r_user_id = api_get_user_id();
506
        $r_dtime = api_get_utc_datetime();
507
        $r_version = $r_version + 1;
508
        $r_comment = get_lang('RestoredFromVersion').': '.$c_version;
509
        $session_id = api_get_session_id();
510
        $course_id = api_get_course_int_id();
511
        $groupInfo = GroupManager::get_group_properties($r_group_id);
512
513
        $params = [
514
            'c_id' => $course_id,
515
            'page_id' => $r_page_id,
516
            'reflink' => $r_reflink,
517
            'title' => $r_title,
518
            'content' => $r_content,
519
            'user_id' => $r_user_id,
520
            'group_id' => $r_group_id,
521
            'dtime' => $r_dtime,
522
            'assignment' => $r_assignment,
523
            'comment' => $r_comment,
524
            'progress' => $r_progress,
525
            'version' => $r_version,
526
            'linksto' => $r_linksto,
527
            'user_ip' => $_SERVER['REMOTE_ADDR'],
528
            'session_id' => $session_id,
529
        ];
530
        $id = Database::insert($tbl_wiki, $params);
531
532
        if ($id) {
533
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
534
            Database::query($sql);
535
536
            api_item_property_update(
537
                $_course,
538
                'wiki',
539
                $id,
540
                'WikiAdded',
541
                api_get_user_id(),
542
                $groupInfo
543
            );
544
            self::check_emailcue($r_reflink, 'P', $r_dtime, $r_user_id);
545
        }
546
547
        return get_lang('PageRestored');
548
    }
549
550
    /**
551
     * This function delete a wiki.
552
     *
553
     * @author Juan Carlos Raña <[email protected]>
554
     *
555
     * @return string Message of success (to be printed)
556
     */
557
    public function delete_wiki()
558
    {
559
        $tbl_wiki = $this->tbl_wiki;
560
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
561
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
562
        $tbl_wiki_conf = $this->tbl_wiki_conf;
563
        $conditionSession = $this->condition_session;
564
        $groupFilter = $this->groupfilter;
565
        $course_id = $this->course_id;
566
567
        $sql = "SELECT page_id FROM $tbl_wiki
568
                WHERE c_id = $course_id AND $groupFilter $conditionSession
569
                ORDER BY id DESC";
570
571
        $result = Database::query($sql);
572
        $pageList = Database::store_result($result);
573
        if ($pageList) {
574
            foreach ($pageList as $pageData) {
575
                $pageId = $pageData['page_id'];
576
                $sql = "DELETE FROM $tbl_wiki_conf
577
                        WHERE c_id = $course_id AND page_id = $pageId";
578
                Database::query($sql);
579
580
                $sql = "DELETE FROM $tbl_wiki_discuss
581
                        WHERE c_id = $course_id AND publication_id = $pageId";
582
                Database::query($sql);
583
            }
584
        }
585
586
        $sql = "DELETE FROM $tbl_wiki_mailcue
587
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
588
        Database::query($sql);
589
590
        $sql = "DELETE FROM $tbl_wiki
591
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
592
        Database::query($sql);
593
594
        return get_lang('WikiDeleted');
595
    }
596
597
    /**
598
     * This function saves a new wiki page.
599
     *
600
     * @author Patrick Cool <[email protected]>, Ghent University
601
     *
602
     * @todo consider merging this with the function save_wiki into one single function.
603
     */
604
    public function save_new_wiki($values)
605
    {
606
        $tbl_wiki = $this->tbl_wiki;
607
        $tbl_wiki_conf = $this->tbl_wiki_conf;
608
        $assig_user_id = $this->assig_user_id;
609
        $_clean = [];
610
611
        // cleaning the variables
612
        $_clean['assignment'] = '';
613
        if (isset($values['assignment'])) {
614
            $_clean['assignment'] = $values['assignment'];
615
        }
616
617
        // session_id
618
        $session_id = api_get_session_id();
619
        // Unlike ordinary pages of pages of assignments.
620
        // Allow create a ordinary page although there is a assignment with the same name
621
        if ($_clean['assignment'] == 2 || $_clean['assignment'] == 1) {
622
            $page = str_replace(
623
                ' ',
624
                '_',
625
                $values['title']."_uass".$assig_user_id
626
            );
627
        } else {
628
            $page = str_replace(' ', '_', $values['title']);
629
        }
630
        $_clean['reflink'] = $page;
631
        $_clean['title'] = trim($values['title']);
632
        $_clean['content'] = $values['content'];
633
634
        if (api_get_setting('htmlpurifier_wiki') === 'true') {
635
            $purifier = new HTMLPurifier();
636
            $_clean['content'] = $purifier->purify($_clean['content']);
637
        }
638
639
        //re-check after strip_tags if the title is empty
640
        if (empty($_clean['title']) || empty($_clean['reflink'])) {
641
            return false;
642
        }
643
644
        if ($_clean['assignment'] == 2) {
645
            //config by default for individual assignment (students)
646
            //Identifies the user as a creator, not the teacher who created
647
            $_clean['user_id'] = intval($assig_user_id);
648
            $_clean['visibility'] = 0;
649
            $_clean['visibility_disc'] = 0;
650
            $_clean['ratinglock_disc'] = 0;
651
        } else {
652
            $_clean['user_id'] = api_get_user_id();
653
            $_clean['visibility'] = 1;
654
            $_clean['visibility_disc'] = 1;
655
            $_clean['ratinglock_disc'] = 1;
656
        }
657
658
        $_clean['comment'] = $values['comment'];
659
        $_clean['progress'] = $values['progress'];
660
        $_clean['version'] = 1;
661
662
        $groupId = api_get_group_id();
663
        $groupInfo = GroupManager::get_group_properties($groupId);
664
665
        //check wikilinks
666
        $_clean['linksto'] = self::links_to($_clean['content']);
667
668
        // cleaning config variables
669
        $_clean['task'] = $values['task'] ?? '';
670
        $_clean['feedback1'] = $values['feedback1'] ?? '';
671
        $_clean['feedback2'] = $values['feedback2'] ?? '';
672
        $_clean['feedback3'] = $values['feedback3'] ?? '';
673
        $_clean['fprogress1'] = $values['fprogress1'] ?? '';
674
        $_clean['fprogress2'] = $values['fprogress2'] ?? '';
675
        $_clean['fprogress3'] = $values['fprogress3'] ?? '';
676
677
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
678
            $_clean['startdate_assig'] = $values['startdate_assig'];
679
        } else {
680
            $_clean['startdate_assig'] = null;
681
        }
682
683
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
684
            $_clean['enddate_assig'] = $values['enddate_assig'];
685
        } else {
686
            $_clean['enddate_assig'] = null;
687
        }
688
689
        $_clean['delayedsubmit'] = $values['delayedsubmit'] ?? '';
690
        $_clean['max_text'] = $values['max_text'] ?? '';
691
        $_clean['max_version'] = $values['max_version'] ?? '';
692
693
        $course_id = api_get_course_int_id();
694
695
        // Filter no _uass
696
        if (api_strtoupper(trim($values['title'])) === 'INDEX') {
697
            Display::addFlash(
698
                Display::return_message(
699
                    get_lang('GoAndEditMainPage'),
700
                    'warning',
701
                    false
702
                )
703
            );
704
        } else {
705
            $var = $_clean['reflink'];
706
            $group_id = intval($_GET['group_id']);
707
            if (!self::checktitle($var)) {
708
                return get_lang('WikiPageTitleExist').
709
                    '<a href="index.php?action=edit&title='.$var.'&group_id='.$group_id.'">'.
710
                    $values['title'].'</a>';
711
            } else {
712
                $em = Database::getManager();
713
                $dtime = api_get_utc_datetime(null, false, true);
714
715
                $newWiki = (new CWiki())
716
                    ->setCId($course_id)
717
                    ->setReflink($_clean['reflink'])
718
                    ->setTitle($_clean['title'])
719
                    ->setContent($_clean['content'])
720
                    ->setUserId($_clean['user_id'])
721
                    ->setGroupId($groupId)
722
                    ->setDtime($dtime)
723
                    ->setVisibility($_clean['visibility'])
724
                    ->setVisibilityDisc($_clean['visibility_disc'])
725
                    ->setRatinglockDisc($_clean['ratinglock_disc'])
726
                    ->setAssignment($_clean['assignment'])
727
                    ->setComment($_clean['comment'])
728
                    ->setProgress($_clean['progress'])
729
                    ->setVersion($_clean['version'])
730
                    ->setLinksto($_clean['linksto'])
731
                    ->setUserIp($_SERVER['REMOTE_ADDR'])
732
                    ->setSessionId($session_id)
733
                    ->setAddlock(0)
734
                    ->setAddlockDisc(1)
735
                    ->setEditlock(0)
736
                    ->setIsEditing(0)
737
                    ->setTag('')
738
                ;
739
740
                $em->persist($newWiki);
741
                $em->flush();
742
743
                $id = $newWiki->getIid();
744
745
                if ($id > 0) {
746
                    $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
747
                    Database::query($sql);
748
749
                    //insert into item_property
750
                    api_item_property_update(
751
                        api_get_course_info(),
752
                        TOOL_WIKI,
753
                        $id,
754
                        'WikiAdded',
755
                        api_get_user_id(),
756
                        $groupInfo
757
                    );
758
759
                    $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
760
                            WHERE c_id = '.$course_id.' AND id = "'.$id.'"';
761
                    Database::query($sql);
762
763
                    // insert wiki config
764
                    $params = [
765
                        'c_id' => $course_id,
766
                        'page_id' => $id,
767
                        'task' => $_clean['task'],
768
                        'feedback1' => $_clean['feedback1'],
769
                        'feedback2' => $_clean['feedback2'],
770
                        'feedback3' => $_clean['feedback3'],
771
                        'fprogress1' => $_clean['fprogress1'],
772
                        'fprogress2' => $_clean['fprogress2'],
773
                        'fprogress3' => $_clean['fprogress3'],
774
                        'max_text' => $_clean['max_text'],
775
                        'max_version' => $_clean['max_version'],
776
                        'startdate_assig' => $_clean['startdate_assig'],
777
                        'enddate_assig' => $_clean['enddate_assig'],
778
                        'delayedsubmit' => $_clean['delayedsubmit'],
779
                    ];
780
781
                    Database::insert($tbl_wiki_conf, $params);
782
783
                    self::assignCategoriesToWiki($newWiki, $values['category'] ?? []);
784
785
                    $this->setWikiData($id);
786
                    self::check_emailcue(0, 'A');
787
788
                    return get_lang('NewWikiSaved');
789
                }
790
            }
791
        }
792
    }
793
794
    public function setForm(FormValidator $form, array $row = [])
795
    {
796
        $toolBar = api_is_allowed_to_edit(null, true)
797
            ? [
798
                'ToolbarSet' => 'Wiki',
799
                'Width' => '100%',
800
                'Height' => '400',
801
            ]
802
            : [
803
                'ToolbarSet' => 'WikiStudent',
804
                'Width' => '100%',
805
                'Height' => '400',
806
                'UserStatus' => 'student',
807
            ];
808
809
        $form->addHtmlEditor(
810
            'content',
811
            get_lang('Content'),
812
            false,
813
            false,
814
            $toolBar
815
        );
816
        //$content
817
        $form->addElement('text', 'comment', get_lang('Comments'));
818
        $progress = ['', 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
819
820
        $form->addElement(
821
            'select',
822
            'progress',
823
            get_lang('Progress'),
824
            $progress
825
        );
826
827
        if (true === api_get_configuration_value('wiki_categories_enabled')) {
828
            $em = Database::getManager();
829
830
            $categories = $em->getRepository(CWikiCategory::class)
831
                ->findByCourse(
832
                    api_get_course_entity(),
833
                    api_get_session_entity()
834
                );
835
836
            $form->addSelectFromCollection(
837
                'category',
838
                get_lang('Categories'),
839
                $categories,
840
                ['multiple' => 'multiple'],
841
                false,
842
                'getNodeName'
843
            );
844
        }
845
846
        if ((api_is_allowed_to_edit(false, true) ||
847
            api_is_platform_admin()) &&
848
            isset($row['reflink']) && $row['reflink'] != 'index'
849
        ) {
850
            $form->addElement(
851
                'advanced_settings',
852
                'advanced_params',
853
                get_lang('AdvancedParameters')
854
            );
855
            $form->addElement(
856
                'html',
857
                '<div id="advanced_params_options" style="display:none">'
858
            );
859
860
            $form->addHtmlEditor(
861
                'task',
862
                get_lang('DescriptionOfTheTask'),
863
                false,
864
                false,
865
                [
866
                    'ToolbarSet' => 'wiki_task',
867
                    'Width' => '100%',
868
                    'Height' => '200',
869
                ]
870
            );
871
872
            $form->addElement('label', null, get_lang('AddFeedback'));
873
            $form->addElement('textarea', 'feedback1', get_lang('Feedback1'));
874
            $form->addElement(
875
                'select',
876
                'fprogress1',
877
                get_lang('FProgress'),
878
                $progress
879
            );
880
881
            $form->addElement('textarea', 'feedback2', get_lang('Feedback2'));
882
            $form->addElement(
883
                'select',
884
                'fprogress2',
885
                get_lang('FProgress'),
886
                $progress
887
            );
888
889
            $form->addElement('textarea', 'feedback3', get_lang('Feedback3'));
890
            $form->addElement(
891
                'select',
892
                'fprogress3',
893
                get_lang('FProgress'),
894
                $progress
895
            );
896
897
            $form->addElement(
898
                'checkbox',
899
                'initstartdate',
900
                null,
901
                get_lang('StartDate'),
902
                ['id' => 'start_date_toggle']
903
            );
904
905
            $style = "display:block";
906
            $row['initstartdate'] = 1;
907
            if (empty($row['startdate_assig'])) {
908
                $style = "display:none";
909
                $row['initstartdate'] = null;
910
            }
911
912
            $form->addElement(
913
                'html',
914
                '<div id="start_date" style="'.$style.'">'
915
            );
916
            $form->addDatePicker('startdate_assig', '');
917
            $form->addElement('html', '</div>');
918
            $form->addElement(
919
                'checkbox',
920
                'initenddate',
921
                null,
922
                get_lang('EndDate'),
923
                ['id' => 'end_date_toggle']
924
            );
925
926
            $style = "display:block";
927
            $row['initenddate'] = 1;
928
            if (empty($row['enddate_assig'])) {
929
                $style = "display:none";
930
                $row['initenddate'] = null;
931
            }
932
933
            $form->addHtml('<div id="end_date" style="'.$style.'">');
934
            $form->addDatePicker('enddate_assig', '');
935
            $form->addHtml('</div>');
936
            $form->addElement(
937
                'checkbox',
938
                'delayedsubmit',
939
                null,
940
                get_lang('AllowLaterSends')
941
            );
942
            $form->addElement('text', 'max_text', get_lang('NMaxWords'));
943
            $form->addElement('text', 'max_version', get_lang('NMaxVersion'));
944
            $form->addElement(
945
                'checkbox',
946
                'assignment',
947
                null,
948
                get_lang('CreateAssignmentPage')
949
            );
950
            $form->addElement('html', '</div>');
951
        }
952
953
        $form->addElement('hidden', 'page_id');
954
        $form->addElement('hidden', 'reflink');
955
        $form->addElement('hidden', 'version');
956
        $form->addElement('hidden', 'wpost_id', api_get_unique_id());
957
    }
958
959
    /**
960
     * This function displays the form for adding a new wiki page.
961
     *
962
     * @author Patrick Cool <[email protected]>, Ghent University
963
     *
964
     * @return string html code
965
     */
966
    public function display_new_wiki_form()
967
    {
968
        $url = api_get_self().'?'.api_get_cidreq(
969
            ).'&action=addnew&group_id='.api_get_group_id();
970
        $form = new FormValidator('wiki_new', 'post', $url);
971
        $form->addElement('text', 'title', get_lang('Title'));
972
        $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
973
        self::setForm($form);
974
        $title = isset($_GET['title']) ? Security::remove_XSS(
975
            $_GET['title']
976
        ) : '';
977
        $form->setDefaults(['title' => $title]);
978
        $form->addButtonSave(get_lang('Save'), 'SaveWikiNew');
979
        $form->display();
980
981
        if ($form->validate()) {
982
            $values = $form->exportValues();
983
            if (isset($values['startdate_assig']) &&
984
                isset($values['enddate_assig']) &&
985
                strtotime($values['startdate_assig']) > strtotime(
986
                    $values['enddate_assig']
987
                )
988
            ) {
989
                Display::addFlash(
990
                    Display::return_message(
991
                        get_lang("EndDateCannotBeBeforeTheStartDate"),
992
                        'error',
993
                        false
994
                    )
995
                );
996
            } elseif (!self::double_post($_POST['wpost_id'])) {
997
                //double post
998
            } else {
999
                if (isset($values['assignment']) && $values['assignment'] == 1) {
1000
                    self::auto_add_page_users($values);
1001
                }
1002
1003
                $return_message = $this->save_new_wiki($values);
1004
1005
                if ($return_message == false) {
1006
                    Display::addFlash(
1007
                        Display::return_message(
1008
                            get_lang('NoWikiPageTitle'),
1009
                            'error',
1010
                            false
1011
                        )
1012
                    );
1013
                } else {
1014
                    Display::addFlash(
1015
                        Display::return_message(
1016
                            $return_message,
1017
                            'confirmation',
1018
                            false
1019
                        )
1020
                    );
1021
                }
1022
1023
                $wikiData = self::getWikiData();
1024
                $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq();
1025
                header('Location: '.$redirectUrl);
1026
                exit;
1027
            }
1028
        }
1029
    }
1030
1031
    /**
1032
     * This function displays a wiki entry.
1033
     *
1034
     * @author Patrick Cool <[email protected]>, Ghent University
1035
     * @author Juan Carlos Raña Trabado
1036
     */
1037
    public function display_wiki_entry(string $newtitle)
1038
    {
1039
        $tblWiki = $this->tbl_wiki;
1040
        $tblWikiConf = $this->tbl_wiki_conf;
1041
        $conditionSession = $this->condition_session;
1042
        $groupfilter = $this->groupfilter;
1043
        $page = $this->page;
1044
1045
        $sessionId = api_get_session_id();
1046
        $courseId = api_get_course_int_id();
1047
1048
        if ($newtitle) {
1049
            $pageMIX = $newtitle; //display the page after it is created
1050
        } else {
1051
            $pageMIX = $page; //display current page
1052
        }
1053
1054
        $filter = null;
1055
        if (isset($_GET['view']) && $_GET['view']) {
1056
            $_clean['view'] = Database::escape_string($_GET['view']);
1057
            $filter = ' AND w.id="'.$_clean['view'].'"';
1058
        }
1059
1060
        // First, check page visibility in the first page version
1061
        $sql = 'SELECT * FROM '.$tblWiki.'
1062
                WHERE
1063
                    c_id = '.$courseId.' AND
1064
                    reflink = "'.Database::escape_string($pageMIX).'" AND
1065
                   '.$groupfilter.$conditionSession.'
1066
                ORDER BY id';
1067
        $result = Database::query($sql);
1068
        $row = Database::fetch_array($result, 'ASSOC');
1069
1070
        $KeyVisibility = null;
1071
        if ($KeyVisibility) {
1072
            $KeyVisibility = $row['visibility'];
1073
        }
1074
1075
        // second, show the last version
1076
        $sql = 'SELECT * FROM '.$tblWiki.' w
1077
            INNER JOIN '.$tblWikiConf.' wc
1078
            ON (wc.page_id = w.page_id AND wc.c_id = w.c_id)
1079
            WHERE
1080
                w.c_id = '.$courseId.' AND
1081
                w.reflink = "'.Database::escape_string($pageMIX).'" AND
1082
                w.session_id = '.$sessionId.' AND
1083
                w.'.$groupfilter.'  '.$filter.'
1084
            ORDER BY id DESC';
1085
1086
        $result = Database::query($sql);
1087
        // we do not need awhile loop since we are always displaying the last version
1088
        $row = Database::fetch_array($result, 'ASSOC');
1089
1090
        //log users access to wiki (page_id)
1091
        if (!empty($row['page_id'])) {
1092
            Event::addEvent(LOG_WIKI_ACCESS, LOG_WIKI_PAGE_ID, $row['page_id']);
1093
        }
1094
        //update visits
1095
        if ($row && $row['id']) {
1096
            $sql = 'UPDATE '.$tblWiki.' SET hits=(hits+1)
1097
                WHERE c_id = '.$courseId.' AND id='.$row['id'];
1098
            Database::query($sql);
1099
        }
1100
1101
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1102
1103
        // if both are empty, and we are displaying the index page then we display the default text.
1104
        if (!$row || ($row['content'] == '' && $row['title'] == '' && $page == 'index')) {
1105
            if (api_is_allowed_to_edit(false, true) ||
1106
                api_is_platform_admin() ||
1107
                GroupManager::is_user_in_group(api_get_user_id(), $groupInfo) ||
1108
                api_is_allowed_in_course()
1109
            ) {
1110
                //Table structure for better export to pdf
1111
                $default_table_for_content_Start = '<div class="text-center">';
1112
                $default_table_for_content_End = '</div>';
1113
                $content = $default_table_for_content_Start.
1114
                    sprintf(
1115
                        get_lang('DefaultContent'),
1116
                        api_get_path(WEB_IMG_PATH)
1117
                    ).
1118
                    $default_table_for_content_End;
1119
                $title = get_lang('DefaultTitle');
1120
            } else {
1121
                Display::addFlash(
1122
                    Display::return_message(
1123
                        get_lang('WikiStandBy'),
1124
                        'normal',
1125
                        false
1126
                    )
1127
                );
1128
1129
                return;
1130
            }
1131
        } else {
1132
            if (true === api_get_configuration_value('wiki_html_strict_filtering')) {
1133
                $content = Security::remove_XSS($row['content'], COURSEMANAGERLOWSECURITY);
1134
            } else {
1135
                $content = Security::remove_XSS($row['content']);
1136
            }
1137
            $title = Security::remove_XSS($row['title']);
1138
        }
1139
1140
        if (self::wiki_exist($title)) {
1141
            //assignment mode: identify page type
1142
            $icon_assignment = null;
1143
            if ($row['assignment'] == 1) {
1144
                $icon_assignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'));
1145
            } elseif ($row['assignment'] == 2) {
1146
                $icon_assignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'));
1147
            }
1148
1149
            // task mode
1150
            $icon_task = null;
1151
            if (!empty($row['task'])) {
1152
                $icon_task = Display::return_icon('wiki_task.png', get_lang('StandardTask'));
1153
            }
1154
1155
            $pageTitle = $icon_assignment.PHP_EOL.$icon_task.'&nbsp;'.api_htmlentities($title);
1156
        } else {
1157
            $pageTitle = api_htmlentities($title);
1158
        }
1159
1160
        // Show page. Show page to all users if isn't hide page. Mode assignments: if student is the author, can view
1161
        if ($KeyVisibility != "1"
1162
            && !api_is_allowed_to_edit(false, true)
1163
            && !api_is_platform_admin()
1164
            && ($row['assignment'] != 2 || $KeyVisibility != "0" || api_get_user_id() != $row['user_id'])
1165
            && !api_is_allowed_in_course()
1166
        ) {
1167
            return;
1168
        }
1169
1170
        $actionsLeft = '';
1171
        $actionsRight = '';
1172
        // menu edit page
1173
        $editLink = '<a href="index.php?'.api_get_cidreq().'&action=edit&title='.api_htmlentities(urlencode($page)).'"'
1174
            .self::is_active_navigation_tab('edit').'>'
1175
            .Display::return_icon('edit.png', get_lang('EditThisPage'), [], ICON_SIZE_MEDIUM).'</a>';
1176
1177
        if (api_is_allowed_to_edit(false, true)) {
1178
            $actionsLeft .= $editLink;
1179
        } else {
1180
            if ((api_is_allowed_in_course() ||
1181
                GroupManager::is_user_in_group(
1182
                    api_get_user_id(),
1183
                    $groupInfo
1184
                ))
1185
            ) {
1186
                $actionsLeft .= $editLink;
1187
            } else {
1188
                $actionsLeft .= '';
1189
            }
1190
        }
1191
1192
        $pageProgress = 0;
1193
        $pageScore = 0;
1194
1195
        if ($row && $row['id']) {
1196
            $pageProgress = $row['progress'] * 10;
1197
            $pageScore = $row['score'];
1198
1199
            $protect_page = null;
1200
            $lock_unlock_protect = null;
1201
            // page action: protecting (locking) the page
1202
            if (api_is_allowed_to_edit(false, true) ||
1203
                api_is_platform_admin()
1204
            ) {
1205
                if (self::check_protect_page() == 1) {
1206
                    $protect_page = Display::return_icon(
1207
                        'lock.png',
1208
                        get_lang('PageLockedExtra'),
1209
                        [],
1210
                        ICON_SIZE_MEDIUM
1211
                    );
1212
                    $lock_unlock_protect = 'unlock';
1213
                } else {
1214
                    $protect_page = Display::return_icon(
1215
                        'unlock.png',
1216
                        get_lang('PageUnlockedExtra'),
1217
                        [],
1218
                        ICON_SIZE_MEDIUM
1219
                    );
1220
                    $lock_unlock_protect = 'lock';
1221
                }
1222
            }
1223
1224
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_protect
1225
                .'&title='.api_htmlentities(urlencode($page)).'">'.
1226
            $protect_page.'</a>';
1227
1228
            $visibility_page = null;
1229
            $lock_unlock_visibility = null;
1230
            //page action: visibility
1231
            if (api_is_allowed_to_edit(false, true) ||
1232
                api_is_platform_admin()
1233
            ) {
1234
                if (self::check_visibility_page() == 1) {
1235
                    $visibility_page = Display::return_icon(
1236
                        'visible.png',
1237
                        get_lang('ShowPageExtra'),
1238
                        [],
1239
                        ICON_SIZE_MEDIUM
1240
                    );
1241
                    $lock_unlock_visibility = 'invisible';
1242
                } else {
1243
                    $visibility_page = Display::return_icon(
1244
                        'invisible.png',
1245
                        get_lang('HidePageExtra'),
1246
                        [],
1247
                        ICON_SIZE_MEDIUM
1248
                    );
1249
                    $lock_unlock_visibility = 'visible';
1250
                }
1251
            }
1252
1253
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='
1254
                .$lock_unlock_visibility.'&title='.api_htmlentities(urlencode($page)).'">'.$visibility_page.'</a>';
1255
1256
            // Only available if row['id'] is set
1257
            //page action: notification
1258
            $lock_unlock_notify_page = '';
1259
1260
            if (api_is_allowed_to_session_edit()) {
1261
                if (self::check_notify_page($page) == 1) {
1262
                    $notify_page = Display::return_icon(
1263
                        'messagebox_info.png',
1264
                        get_lang('NotifyByEmail'),
1265
                        [],
1266
                        ICON_SIZE_MEDIUM
1267
                    );
1268
                    $lock_unlock_notify_page = 'unlocknotify';
1269
                } else {
1270
                    $notify_page = Display::return_icon(
1271
                        'mail.png',
1272
                        get_lang('CancelNotifyByEmail'),
1273
                        [],
1274
                        ICON_SIZE_MEDIUM
1275
                    );
1276
                    $lock_unlock_notify_page = 'locknotify';
1277
                }
1278
            }
1279
1280
            if (api_is_allowed_to_session_edit(false, true)
1281
                && api_is_allowed_to_edit()
1282
                || GroupManager::is_user_in_group(api_get_user_id(), $groupInfo)
1283
            ) {
1284
                // menu discuss page
1285
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=discuss&title='
1286
                    .api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('discuss').'>'
1287
                    .Display::return_icon(
1288
                        'discuss.png',
1289
                        get_lang('DiscussThisPage'),
1290
                        [],
1291
                        ICON_SIZE_MEDIUM
1292
                    ).'</a>';
1293
            }
1294
1295
            //menu history
1296
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=history&title='
1297
                .api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('history').'>'.
1298
                Display::return_icon(
1299
                    'history.png',
1300
                    get_lang('ShowPageHistory'),
1301
                    [],
1302
                    ICON_SIZE_MEDIUM
1303
                ).'</a>';
1304
            //menu linkspages
1305
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'action=links&title='
1306
                .api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('links').'>'
1307
                .Display::return_icon(
1308
                    'what_link_here.png',
1309
                    get_lang('LinksPages'),
1310
                    [],
1311
                    ICON_SIZE_MEDIUM
1312
                ).'</a>';
1313
1314
            //menu delete wikipage
1315
            if (api_is_allowed_to_edit(false, true) ||
1316
                api_is_platform_admin()
1317
            ) {
1318
                $actionsRight .= '<a href="index.php?action=delete&'.api_get_cidreq().'&title='
1319
                    .api_htmlentities(urlencode($page)).'"'.self::is_active_navigation_tab('delete').'>'
1320
                    .Display::return_icon(
1321
                        'delete.png',
1322
                        get_lang('DeleteThisPage'),
1323
                        [],
1324
                        ICON_SIZE_MEDIUM
1325
                    ).'</a>';
1326
            }
1327
1328
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='
1329
                .$lock_unlock_notify_page.'&title='.api_htmlentities(urlencode($page)).'">'.$notify_page.'</a>';
1330
1331
            // Page action: copy last version to doc area
1332
            if (api_is_allowed_to_edit(false, true) ||
1333
                api_is_platform_admin()
1334
            ) {
1335
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export2doc&wiki_id='.$row['id'].'">'
1336
                    .Display::return_icon(
1337
                        'export_to_documents.png',
1338
                        get_lang('ExportToDocArea'),
1339
                        [],
1340
                        ICON_SIZE_MEDIUM
1341
                    ).'</a>';
1342
            }
1343
1344
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export_to_pdf&wiki_id='.$row['id'].'">'
1345
                .Display::return_icon(
1346
                    'pdf.png',
1347
                    get_lang('ExportToPDF'),
1348
                    [],
1349
                    ICON_SIZE_MEDIUM
1350
                ).'</a>';
1351
1352
            $unoconv = api_get_configuration_value('unoconv.binaries');
1353
            if ($unoconv) {
1354
                $actionsRight .= '<a href="'.api_get_path(WEB_CODE_PATH).'wiki/index.php?action=export_to_doc_file&id='
1355
                    .$row['id'].'&'.api_get_cidreq().'">'
1356
                    .Display::return_icon(
1357
                        'export_doc.png',
1358
                        get_lang('ExportToDoc'),
1359
                        [],
1360
                        ICON_SIZE_MEDIUM
1361
                    ).'</a>';
1362
            }
1363
1364
            //export to print?>
1365
            <script>
1366
                function goprint() {
1367
                    var a = window.open('', '', 'width=800,height=600');
1368
                    a.document.open("text/html");
1369
                    a.document.write($('#wikicontent .panel-heading').html());
1370
                    a.document.write($('#wikicontent .panel-body').html());
1371
                    a.document.close();
1372
                    a.print();
1373
                }
1374
            </script>
1375
            <?php
1376
            $actionsRight .= Display::url(
1377
                Display::return_icon(
1378
                    'printer.png',
1379
                    get_lang('Print'),
1380
                    [],
1381
                    ICON_SIZE_MEDIUM
1382
                ),
1383
                '#',
1384
                ['onclick' => "javascript: goprint();"]
1385
            );
1386
        }
1387
1388
        echo Display::toolbarAction(
1389
            'toolbar-wikistudent',
1390
            [$actionsLeft, $actionsRight]
1391
        );
1392
1393
        $pageWiki = self::detect_news_link($content);
1394
        $pageWiki = self::detect_irc_link($pageWiki);
1395
        $pageWiki = self::detect_ftp_link($pageWiki);
1396
        $pageWiki = self::detect_mail_link($pageWiki);
1397
        $pageWiki = self::detect_anchor_link($pageWiki);
1398
        $pageWiki = self::detect_external_link($pageWiki);
1399
        $pageWiki = self::make_wiki_link_clickable($pageWiki);
1400
1401
        $footerWiki = '<ul class="list-inline" style="margin-bottom: 0;">'
1402
            .'<li>'.get_lang('Progress').': '.$pageProgress.'%</li>'
1403
            .'<li>'.get_lang('Rating').': '.$pageScore.'</li>'
1404
            .'<li>'.get_lang('Words').': '.self::word_count($content).'</li>';
1405
1406
        $footerWiki .= $this->returnCategoriesBlock(
1407
            !empty($row['id']) ? $row['id'] : 0,
1408
            '<li class="pull-right">',
1409
            '</li>'
1410
        );
1411
1412
        $footerWiki .= '</ul>';
1413
        // wikicontent require to print wiki document
1414
        echo '<div id="wikicontent">'.Display::panel($pageWiki, $pageTitle, $footerWiki).'</div>'; //end filter visibility
1415
    }
1416
1417
    /**
1418
     * This function counted the words in a document. Thanks Adeel Khan.
1419
     *
1420
     * @param   string  Document's text
0 ignored issues
show
Documentation Bug introduced by
The doc comment Document's at position 0 could not be parsed: Unknown type name 'Document's' at position 0 in Document's.
Loading history...
1421
     *
1422
     * @return int Number of words
1423
     */
1424
    public function word_count($document)
1425
    {
1426
        $search = [
1427
            '@<script[^>]*?>.*?</script>@si',
1428
            '@<style[^>]*?>.*?</style>@siU',
1429
            '@<div id="player.[^>]*?>.*?</div>@',
1430
            '@<![\s\S]*?--[ \t\n\r]*>@',
1431
        ];
1432
1433
        $document = preg_replace($search, '', $document);
1434
1435
        // strip all html tags
1436
        $wc = strip_tags($document);
1437
        $wc = html_entity_decode(
1438
            $wc,
1439
            ENT_NOQUOTES,
1440
            'UTF-8'
1441
        ); // TODO:test also old html_entity_decode(utf8_encode($wc))
1442
1443
        // remove 'words' that don't consist of alphanumerical characters or punctuation. And fix accents and some letters
1444
        $pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@|á|é|í|ó|ú|à|è|ì|ò|ù|ä|ë|ï|ö|ü|Á|É|Í|Ó|Ú|À|È|Ò|Ù|Ä|Ë|Ï|Ö|Ü|â|ê|î|ô|û|Â|Ê|Î|Ô|Û|ñ|Ñ|ç|Ç)]+#";
1445
        $wc = trim(preg_replace($pattern, " ", $wc));
1446
1447
        // remove one-letter 'words' that consist only of punctuation
1448
        $wc = trim(
1449
            preg_replace(
1450
                "#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#",
1451
                " ",
1452
                $wc
1453
            )
1454
        );
1455
1456
        // remove superfluous whitespace
1457
        $wc = preg_replace("/\s\s+/", " ", $wc);
1458
1459
        // split string into an array of words
1460
        $wc = explode(" ", $wc);
1461
1462
        // remove empty elements
1463
        $wc = array_filter($wc);
1464
1465
        // return the number of words
1466
        return count($wc);
1467
    }
1468
1469
    /**
1470
     * This function checks if wiki title exist.
1471
     */
1472
    public function wiki_exist($title)
1473
    {
1474
        $tbl_wiki = $this->tbl_wiki;
1475
        $groupfilter = $this->groupfilter;
1476
        $condition_session = $this->condition_session;
1477
        $course_id = api_get_course_int_id();
1478
1479
        $sql = 'SELECT id FROM '.$tbl_wiki.'
1480
              WHERE
1481
                c_id = '.$course_id.' AND
1482
                title="'.Database::escape_string($title).'" AND
1483
                '.$groupfilter.$condition_session.'
1484
              ORDER BY id ASC';
1485
        $result = Database::query($sql);
1486
        $cant = Database::num_rows($result);
1487
        if ($cant > 0) {
1488
            return true;
1489
        } else {
1490
            return false;
1491
        }
1492
    }
1493
1494
    /**
1495
     * Checks if this navigation tab has to be set to active.
1496
     *
1497
     * @author Patrick Cool <[email protected]>, Ghent University
1498
     *
1499
     * @return string html code
1500
     */
1501
    public function is_active_navigation_tab($paramwk)
1502
    {
1503
        if (isset($_GET['action']) && $_GET['action'] == $paramwk) {
1504
            return ' class="active"';
1505
        }
1506
    }
1507
1508
    /**
1509
     * Lock add pages.
1510
     *
1511
     * @author Juan Carlos Raña <[email protected]>
1512
     * return current database status of protect page and change it if get action
1513
     */
1514
    public function check_addnewpagelock()
1515
    {
1516
        $tbl_wiki = $this->tbl_wiki;
1517
        $condition_session = $this->condition_session;
1518
        $groupfilter = $this->groupfilter;
1519
        $course_id = api_get_course_int_id();
1520
1521
        $sql = 'SELECT *
1522
                FROM '.$tbl_wiki.'
1523
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1524
                ORDER BY id ASC';
1525
1526
        $result = Database::query($sql);
1527
        $row = Database::fetch_array($result);
1528
1529
        $status_addlock = null;
1530
        if ($row) {
1531
            $status_addlock = $row['addlock'];
1532
        }
1533
1534
        // Change status
1535
        if (api_is_allowed_to_edit(false, true) ||
1536
            api_is_platform_admin()
1537
        ) {
1538
            if (isset($_GET['actionpage'])) {
1539
                if ($_GET['actionpage'] == 'lockaddnew' && $status_addlock == 1) {
1540
                    $status_addlock = 0;
1541
                }
1542
                if ($_GET['actionpage'] == 'unlockaddnew' && $status_addlock == 0) {
1543
                    $status_addlock = 1;
1544
                }
1545
                $sql = 'UPDATE '.$tbl_wiki.' SET
1546
                            addlock="'.Database::escape_string($status_addlock).'"
1547
                        WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session;
1548
                Database::query($sql);
1549
            }
1550
1551
            $sql = 'SELECT *
1552
                    FROM '.$tbl_wiki.'
1553
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1554
                    ORDER BY id ASC';
1555
            $result = Database::query($sql);
1556
            $row = Database::fetch_array($result);
1557
            if ($row) {
1558
                return $row['addlock'];
1559
            }
1560
        }
1561
1562
        return null;
1563
    }
1564
1565
    /**
1566
     * Protect page.
1567
     *
1568
     * @author Juan Carlos Raña <[email protected]>
1569
     * return current database status of protect page and change it if get action
1570
     */
1571
    public function check_protect_page()
1572
    {
1573
        $tbl_wiki = $this->tbl_wiki;
1574
        $condition_session = $this->condition_session;
1575
        $groupfilter = $this->groupfilter;
1576
        $page = $this->page;
1577
1578
        $course_id = api_get_course_int_id();
1579
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1580
              WHERE
1581
                c_id = '.$course_id.' AND
1582
                reflink="'.Database::escape_string($page).'" AND
1583
                '.$groupfilter.$condition_session.'
1584
              ORDER BY id ASC';
1585
1586
        $result = Database::query($sql);
1587
        $row = Database::fetch_array($result);
1588
1589
        if (!$row) {
1590
            return 0;
1591
        }
1592
1593
        $status_editlock = $row['editlock'];
1594
        $id = $row['page_id'];
1595
1596
        // Change status
1597
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1598
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'lock' && $status_editlock == 0) {
1599
                $status_editlock = 1;
1600
            }
1601
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlock' && $status_editlock == 1) {
1602
                $status_editlock = 0;
1603
            }
1604
1605
            $sql = 'UPDATE '.$tbl_wiki.' SET
1606
                    editlock="'.Database::escape_string($status_editlock).'"
1607
                    WHERE c_id = '.$course_id.' AND page_id="'.$id.'"';
1608
            Database::query($sql);
1609
1610
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1611
                    WHERE
1612
                        c_id = '.$course_id.' AND
1613
                        reflink="'.Database::escape_string($page).'" AND
1614
                    '.$groupfilter.$condition_session.'
1615
                  ORDER BY id ASC';
1616
            $result = Database::query($sql);
1617
            $row = Database::fetch_array($result);
1618
        }
1619
1620
        //show status
1621
        return (int) $row['editlock'];
1622
    }
1623
1624
    /**
1625
     * Visibility page.
1626
     *
1627
     * @author Juan Carlos Raña <[email protected]>
1628
     * return current database status of visibility and change it if get action
1629
     */
1630
    public function check_visibility_page()
1631
    {
1632
        $tbl_wiki = $this->tbl_wiki;
1633
        $page = $this->page;
1634
        $condition_session = $this->condition_session;
1635
        $groupfilter = $this->groupfilter;
1636
        $course_id = api_get_course_int_id();
1637
1638
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1639
                WHERE
1640
                    c_id = '.$course_id.' AND
1641
                    reflink="'.Database::escape_string($page).'" AND
1642
                    '.$groupfilter.$condition_session.'
1643
                ORDER BY id';
1644
        $result = Database::query($sql);
1645
        $row = Database::fetch_array($result);
1646
1647
        if (!$row) {
1648
            return 0;
1649
        }
1650
1651
        $status_visibility = $row['visibility'];
1652
        //change status
1653
        if (api_is_allowed_to_edit(false, true) ||
1654
            api_is_platform_admin()
1655
        ) {
1656
            if (isset($_GET['actionpage']) &&
1657
                $_GET['actionpage'] == 'visible' &&
1658
                $status_visibility == 0
1659
            ) {
1660
                $status_visibility = 1;
1661
            }
1662
            if (isset($_GET['actionpage']) &&
1663
                $_GET['actionpage'] == 'invisible' &&
1664
                $status_visibility == 1
1665
            ) {
1666
                $status_visibility = 0;
1667
            }
1668
1669
            $sql = 'UPDATE '.$tbl_wiki.' SET
1670
                    visibility = "'.Database::escape_string($status_visibility).'"
1671
                    WHERE
1672
                        c_id = '.$course_id.' AND
1673
                        reflink="'.Database::escape_string($page).'" AND
1674
                        '.$groupfilter.$condition_session;
1675
            Database::query($sql);
1676
1677
            // Although the value now is assigned to all (not only the first),
1678
            // these three lines remain necessary.
1679
            // They do that by changing the page state is
1680
            // made when you press the button and not have to wait to change his page
1681
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1682
                    WHERE
1683
                        c_id = '.$course_id.' AND
1684
                        reflink="'.Database::escape_string($page).'" AND
1685
                        '.$groupfilter.$condition_session.'
1686
                    ORDER BY id ASC';
1687
            $result = Database::query($sql);
1688
            $row = Database::fetch_array($result);
1689
        }
1690
1691
        if (empty($row['id'])) {
1692
            $row['visibility'] = 1;
1693
        }
1694
1695
        //show status
1696
        return $row['visibility'];
1697
    }
1698
1699
    /**
1700
     * Visibility discussion.
1701
     *
1702
     * @author Juan Carlos Raña <[email protected]>
1703
     *
1704
     * @return int current database status of discuss visibility
1705
     *             and change it if get action page
1706
     */
1707
    public function check_visibility_discuss()
1708
    {
1709
        $tbl_wiki = $this->tbl_wiki;
1710
        $page = $this->page;
1711
        $condition_session = $this->condition_session;
1712
        $groupfilter = $this->groupfilter;
1713
        $course_id = api_get_course_int_id();
1714
1715
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1716
                WHERE
1717
                    c_id = '.$course_id.' AND
1718
                    reflink="'.Database::escape_string($page).'" AND
1719
                    '.$groupfilter.$condition_session.'
1720
                ORDER BY id ASC';
1721
        $result = Database::query($sql);
1722
        $row = Database::fetch_array($result);
1723
1724
        $status_visibility_disc = $row['visibility_disc'];
1725
1726
        //change status
1727
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1728
            if (isset($_GET['actionpage']) &&
1729
                $_GET['actionpage'] == 'showdisc' &&
1730
                $status_visibility_disc == 0
1731
            ) {
1732
                $status_visibility_disc = 1;
1733
            }
1734
            if (isset($_GET['actionpage']) &&
1735
                $_GET['actionpage'] == 'hidedisc' &&
1736
                $status_visibility_disc == 1
1737
            ) {
1738
                $status_visibility_disc = 0;
1739
            }
1740
1741
            $sql = 'UPDATE '.$tbl_wiki.' SET
1742
                    visibility_disc="'.Database::escape_string($status_visibility_disc).'"
1743
                    WHERE
1744
                        c_id = '.$course_id.' AND
1745
                        reflink="'.Database::escape_string($page).'" AND
1746
                        '.$groupfilter.$condition_session;
1747
            Database::query($sql);
1748
1749
            // Although the value now is assigned to all (not only the first),
1750
            // these three lines remain necessary.
1751
            // They do that by changing the page state is made when you press
1752
            // the button and not have to wait to change his page
1753
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1754
                    WHERE
1755
                        c_id = '.$course_id.' AND
1756
                        reflink="'.Database::escape_string($page).'" AND
1757
                        '.$groupfilter.$condition_session.'
1758
                    ORDER BY id ASC';
1759
            $result = Database::query($sql);
1760
            $row = Database::fetch_array($result);
1761
        }
1762
1763
        return $row['visibility_disc'];
1764
    }
1765
1766
    /**
1767
     * Lock add discussion.
1768
     *
1769
     * @author Juan Carlos Raña <[email protected]>
1770
     *
1771
     * @return int current database status of lock dicuss and change if get action
1772
     */
1773
    public function check_addlock_discuss()
1774
    {
1775
        $tbl_wiki = $this->tbl_wiki;
1776
        $page = $this->page;
1777
        $condition_session = $this->condition_session;
1778
        $groupfilter = $this->groupfilter;
1779
        $course_id = api_get_course_int_id();
1780
1781
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1782
                WHERE
1783
                    c_id = '.$course_id.' AND
1784
                    reflink="'.Database::escape_string($page).'" AND
1785
                    '.$groupfilter.$condition_session.'
1786
                ORDER BY id ASC';
1787
        $result = Database::query($sql);
1788
        $row = Database::fetch_array($result);
1789
1790
        $status_addlock_disc = $row['addlock_disc'];
1791
1792
        //change status
1793
        if (api_is_allowed_to_edit() || api_is_platform_admin()) {
1794
            if (isset($_GET['actionpage']) &&
1795
                $_GET['actionpage'] == 'lockdisc' &&
1796
                $status_addlock_disc == 0
1797
            ) {
1798
                $status_addlock_disc = 1;
1799
            }
1800
            if (isset($_GET['actionpage']) &&
1801
                $_GET['actionpage'] == 'unlockdisc' &&
1802
                $status_addlock_disc == 1
1803
            ) {
1804
                $status_addlock_disc = 0;
1805
            }
1806
1807
            $sql = 'UPDATE '.$tbl_wiki.' SET
1808
                    addlock_disc="'.Database::escape_string($status_addlock_disc).'"
1809
                    WHERE
1810
                        c_id = '.$course_id.' AND
1811
                        reflink = "'.Database::escape_string($page).'" AND
1812
                         '.$groupfilter.$condition_session;
1813
            Database::query($sql);
1814
1815
            // Although the value now is assigned to all (not only the first),
1816
            // these three lines remain necessary.
1817
            // They do that by changing the page state is made when you press
1818
            // the button and not have to wait to change his page
1819
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1820
                    WHERE
1821
                        c_id = '.$course_id.' AND
1822
                        reflink="'.Database::escape_string($page).'" AND
1823
                        '.$groupfilter.$condition_session.'
1824
                    ORDER BY id ASC';
1825
            $result = Database::query($sql);
1826
            $row = Database::fetch_array($result);
1827
        }
1828
1829
        return $row['addlock_disc'];
1830
    }
1831
1832
    /**
1833
     * Lock rating discussion.
1834
     *
1835
     * @author Juan Carlos Raña <[email protected]>
1836
     *
1837
     * @return int current database status of rating discuss and change it if get action
1838
     */
1839
    public function check_ratinglock_discuss()
1840
    {
1841
        $tbl_wiki = $this->tbl_wiki;
1842
        $page = $this->page;
1843
        $condition_session = $this->condition_session;
1844
        $groupfilter = $this->groupfilter;
1845
        $course_id = api_get_course_int_id();
1846
1847
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1848
                WHERE
1849
                    c_id = '.$course_id.' AND
1850
                    reflink="'.Database::escape_string($page).'" AND
1851
                    '.$groupfilter.$condition_session.'
1852
                ORDER BY id ASC';
1853
        $result = Database::query($sql);
1854
        $row = Database::fetch_array($result);
1855
        $status_ratinglock_disc = $row['ratinglock_disc'];
1856
1857
        //change status
1858
        if (api_is_allowed_to_edit(false, true) ||
1859
            api_is_platform_admin()
1860
        ) {
1861
            if (isset($_GET['actionpage']) &&
1862
                $_GET['actionpage'] == 'lockrating' &&
1863
                $status_ratinglock_disc == 0
1864
            ) {
1865
                $status_ratinglock_disc = 1;
1866
            }
1867
            if (isset($_GET['actionpage']) &&
1868
                $_GET['actionpage'] == 'unlockrating' &&
1869
                $status_ratinglock_disc == 1
1870
            ) {
1871
                $status_ratinglock_disc = 0;
1872
            }
1873
1874
            $sql = 'UPDATE '.$tbl_wiki.'
1875
                    SET ratinglock_disc="'.Database::escape_string($status_ratinglock_disc).'"
1876
                    WHERE
1877
                        c_id = '.$course_id.' AND
1878
                        reflink="'.Database::escape_string($page).'" AND
1879
                        '.$groupfilter.$condition_session;
1880
            // Visibility. Value to all,not only for the first
1881
            Database::query($sql);
1882
1883
            // Although the value now is assigned to all (not only the first),
1884
            // these three lines remain necessary. They do that by changing the
1885
            // page state is made when you press the button and not have to wait
1886
            // to change his page
1887
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1888
                    WHERE
1889
                        c_id = '.$course_id.' AND
1890
                        reflink="'.Database::escape_string($page).'" AND
1891
                    '.$groupfilter.$condition_session.'
1892
                  ORDER BY id ASC';
1893
            $result = Database::query($sql);
1894
            $row = Database::fetch_array($result);
1895
        }
1896
1897
        return $row['ratinglock_disc'];
1898
    }
1899
1900
    /**
1901
     * Notify page changes.
1902
     *
1903
     * @author Juan Carlos Raña <[email protected]>
1904
     *
1905
     * @return int the current notification status
1906
     */
1907
    public function check_notify_page($reflink)
1908
    {
1909
        $tbl_wiki = $this->tbl_wiki;
1910
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1911
        $condition_session = $this->condition_session;
1912
        $groupfilter = $this->groupfilter;
1913
        $groupId = api_get_group_id();
1914
        $session_id = api_get_session_id();
1915
        $course_id = api_get_course_int_id();
1916
        $userId = api_get_user_id();
1917
1918
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1919
                WHERE
1920
                    c_id = '.$course_id.' AND
1921
                    reflink="'.$reflink.'" AND
1922
                    '.$groupfilter.$condition_session.'
1923
                ORDER BY id ASC';
1924
        $result = Database::query($sql);
1925
        $row = Database::fetch_array($result);
1926
        $id = $row['id'];
1927
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1928
                WHERE
1929
                    c_id = '.$course_id.' AND
1930
                    id="'.$id.'" AND
1931
                    user_id="'.api_get_user_id().'" AND
1932
                    type="P"';
1933
        $result = Database::query($sql);
1934
        $row = Database::fetch_array($result);
1935
1936
        $idm = $row ? $row['id'] : 0;
1937
        if (empty($idm)) {
1938
            $status_notify = 0;
1939
        } else {
1940
            $status_notify = 1;
1941
        }
1942
1943
        // Change status
1944
        if (isset($_GET['actionpage']) &&
1945
            $_GET['actionpage'] == 'locknotify' &&
1946
            $status_notify == 0
1947
        ) {
1948
            $sql = "SELECT id FROM $tbl_wiki_mailcue
1949
                    WHERE c_id = $course_id AND id = $id AND user_id = $userId";
1950
            $result = Database::query($sql);
1951
            $exist = false;
1952
            if (Database::num_rows($result)) {
1953
                $exist = true;
1954
            }
1955
            if ($exist == false) {
1956
                $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1957
                ($course_id, '".$id."','".api_get_user_id()."','P','".$groupId."','".$session_id."')";
1958
                Database::query($sql);
1959
            }
1960
            $status_notify = 1;
1961
        }
1962
1963
        if (isset($_GET['actionpage']) &&
1964
            $_GET['actionpage'] == 'unlocknotify' &&
1965
            $status_notify == 1
1966
        ) {
1967
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1968
                    WHERE
1969
                        id="'.$id.'" AND
1970
                        user_id="'.api_get_user_id().'" AND
1971
                        type="P" AND
1972
                        c_id = '.$course_id;
1973
            Database::query($sql);
1974
            $status_notify = 0;
1975
        }
1976
1977
        return $status_notify;
1978
    }
1979
1980
    /**
1981
     * Notify discussion changes.
1982
     *
1983
     * @author Juan Carlos Raña <[email protected]>
1984
     *
1985
     * @param string $reflink
1986
     *
1987
     * @return int current database status of rating discuss and change it if get action
1988
     */
1989
    public function check_notify_discuss($reflink)
1990
    {
1991
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1992
        $tbl_wiki = $this->tbl_wiki;
1993
        $condition_session = $this->condition_session;
1994
        $groupfilter = $this->groupfilter;
1995
1996
        $course_id = api_get_course_int_id();
1997
        $groupId = api_get_group_id();
1998
        $session_id = api_get_session_id();
1999
2000
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2001
                WHERE
2002
                    c_id = '.$course_id.' AND
2003
                    reflink="'.$reflink.'" AND
2004
                    '.$groupfilter.$condition_session.'
2005
                ORDER BY id ASC';
2006
        $result = Database::query($sql);
2007
        $row = Database::fetch_array($result);
2008
        $id = $row['id'];
2009
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2010
                WHERE
2011
                    c_id = '.$course_id.' AND id="'.$id.'" AND user_id="'.api_get_user_id().'" AND type="D"';
2012
        $result = Database::query($sql);
2013
        $row = Database::fetch_array($result);
2014
        $idm = $row ? $row['id'] : 0;
2015
2016
        if (empty($idm)) {
2017
            $status_notify_disc = 0;
2018
        } else {
2019
            $status_notify_disc = 1;
2020
        }
2021
2022
        // change status
2023
        if (isset($_GET['actionpage']) &&
2024
            $_GET['actionpage'] == 'locknotifydisc' &&
2025
            $status_notify_disc == 0
2026
        ) {
2027
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
2028
            ($course_id, '".$id."','".api_get_user_id()."','D','".$groupId."','".$session_id."')";
2029
            Database::query($sql);
2030
            $status_notify_disc = 1;
2031
        }
2032
        if (isset($_GET['actionpage']) &&
2033
            $_GET['actionpage'] == 'unlocknotifydisc' &&
2034
            $status_notify_disc == 1
2035
        ) {
2036
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
2037
                    WHERE
2038
                        c_id = '.$course_id.' AND
2039
                        id="'.$id.'" AND
2040
                        user_id="'.api_get_user_id().'" AND
2041
                        type="D" AND
2042
                        c_id = '.$course_id;
2043
            Database::query($sql);
2044
            $status_notify_disc = 0;
2045
        }
2046
2047
        return $status_notify_disc;
2048
    }
2049
2050
    /**
2051
     * Notify all changes.
2052
     *
2053
     * @author Juan Carlos Raña <[email protected]>
2054
     */
2055
    public function check_notify_all()
2056
    {
2057
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
2058
        $course_id = api_get_course_int_id();
2059
        $groupId = api_get_group_id();
2060
        $session_id = api_get_session_id();
2061
2062
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2063
                WHERE
2064
                    c_id = '.$course_id.' AND
2065
                    user_id="'.api_get_user_id().'" AND
2066
                    type="F" AND
2067
                    group_id="'.$groupId.'" AND
2068
                    session_id="'.$session_id.'"';
2069
        $result = Database::query($sql);
2070
        $row = Database::fetch_array($result);
2071
2072
        $idm = $row ? $row['user_id'] : 0;
2073
2074
        if (empty($idm)) {
2075
            $status_notify_all = 0;
2076
        } else {
2077
            $status_notify_all = 1;
2078
        }
2079
2080
        //change status
2081
        if (isset($_GET['actionpage']) &&
2082
            $_GET['actionpage'] == 'locknotifyall' &&
2083
            $status_notify_all == 0
2084
        ) {
2085
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, user_id, type, group_id, session_id) VALUES
2086
            ($course_id, '".api_get_user_id()."','F','".$groupId."','".$session_id."')";
2087
            Database::query($sql);
2088
            $status_notify_all = 1;
2089
        }
2090
2091
        if (isset($_GET['actionpage']) &&
2092
            $_GET['actionpage'] == 'unlocknotifyall' &&
2093
            $status_notify_all == 1
2094
        ) {
2095
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
2096
                   WHERE
2097
                    c_id = '.$course_id.' AND
2098
                    user_id="'.api_get_user_id().'" AND
2099
                    type="F" AND
2100
                    group_id="'.$groupId.'" AND
2101
                    session_id="'.$session_id.'" AND
2102
                    c_id = '.$course_id;
2103
            Database::query($sql);
2104
            $status_notify_all = 0;
2105
        }
2106
2107
        //show status
2108
        return $status_notify_all;
2109
    }
2110
2111
    /**
2112
     * Sends pending e-mails.
2113
     */
2114
    public function check_emailcue(
2115
        $id_or_ref,
2116
        $type,
2117
        $lastime = '',
2118
        $lastuser = ''
2119
    ) {
2120
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
2121
        $tbl_wiki = $this->tbl_wiki;
2122
        $condition_session = $this->condition_session;
2123
        $groupfilter = $this->groupfilter;
2124
        $_course = $this->courseInfo;
2125
        $groupId = api_get_group_id();
2126
        $session_id = api_get_session_id();
2127
        $course_id = api_get_course_int_id();
2128
        $group_properties = GroupManager::get_group_properties($groupId);
2129
        $group_name = $group_properties['name'];
2130
        $allow_send_mail = false; //define the variable to below
2131
        $email_assignment = null;
2132
        if ($type == 'P') {
2133
            //if modifying a wiki page
2134
            //first, current author and time
2135
            //Who is the author?
2136
            $userinfo = api_get_user_info($lastuser);
2137
            $email_user_author = get_lang('EditedBy').': '.$userinfo['complete_name'];
2138
2139
            //When ?
2140
            $year = substr($lastime, 0, 4);
2141
            $month = substr($lastime, 5, 2);
2142
            $day = substr($lastime, 8, 2);
2143
            $hours = substr($lastime, 11, 2);
2144
            $minutes = substr($lastime, 14, 2);
2145
            $seconds = substr($lastime, 17, 2);
2146
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2147
2148
            //second, extract data from first reg
2149
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2150
                    WHERE
2151
                        c_id = '.$course_id.' AND
2152
                        reflink="'.$id_or_ref.'" AND
2153
                        '.$groupfilter.$condition_session.'
2154
                    ORDER BY id ASC';
2155
            $result = Database::query($sql);
2156
            $row = Database::fetch_array($result);
2157
            $id = $row['id'];
2158
            $email_page_name = $row['title'];
2159
            if ($row['visibility'] == 1) {
2160
                $allow_send_mail = true; //if visibility off - notify off
2161
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2162
                        WHERE
2163
                            c_id = '.$course_id.' AND
2164
                            id="'.$id.'" AND
2165
                            type="'.$type.'" OR
2166
                            type="F" AND
2167
                            group_id="'.$groupId.'" AND
2168
                            session_id="'.$session_id.'"';
2169
                //type: P=page, D=discuss, F=full.
2170
                $result = Database::query($sql);
2171
                $emailtext = get_lang('EmailWikipageModified').
2172
                    '<strong>'.$email_page_name.'</strong> '.
2173
                    get_lang('Wiki');
2174
            }
2175
        } elseif ($type == 'D') {
2176
            //if added a post to discuss
2177
            //first, current author and time
2178
            //Who is the author of last message?
2179
            $userinfo = api_get_user_info($lastuser);
2180
            $email_user_author = get_lang('AddedBy').': '.$userinfo['complete_name'];
2181
2182
            //When ?
2183
            $year = substr($lastime, 0, 4);
2184
            $month = substr($lastime, 5, 2);
2185
            $day = substr($lastime, 8, 2);
2186
            $hours = substr($lastime, 11, 2);
2187
            $minutes = substr($lastime, 14, 2);
2188
            $seconds = substr($lastime, 17, 2);
2189
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2190
            //second, extract data from first reg
2191
            $id = $id_or_ref; //$id_or_ref is id from tblwiki
2192
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2193
                    WHERE c_id = '.$course_id.' AND id="'.$id.'"
2194
                    ORDER BY id ASC';
2195
2196
            $result = Database::query($sql);
2197
            $row = Database::fetch_array($result);
2198
2199
            $email_page_name = $row['title'];
2200
            if ($row['visibility_disc'] == 1) {
2201
                $allow_send_mail = true; //if visibility off - notify off
2202
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2203
                        WHERE
2204
                            c_id = '.$course_id.' AND
2205
                            id="'.$id.'" AND
2206
                            type="'.$type.'" OR
2207
                            type="F" AND
2208
                            group_id="'.$groupId.'" AND
2209
                            session_id="'.$session_id.'"';
2210
                //type: P=page, D=discuss, F=full
2211
                $result = Database::query($sql);
2212
                $emailtext = get_lang(
2213
                        'EmailWikiPageDiscAdded'
2214
                    ).' <strong>'.$email_page_name.'</strong> '.get_lang(
2215
                        'Wiki'
2216
                    );
2217
            }
2218
        } elseif ($type == 'A') {
2219
            //for added pages
2220
            $id = 0; //for tbl_wiki_mailcue
2221
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2222
                    WHERE c_id = '.$course_id.'
2223
                    ORDER BY id DESC'; //the added is always the last
2224
2225
            $result = Database::query($sql);
2226
            $row = Database::fetch_array($result);
2227
            $email_page_name = $row['title'];
2228
2229
            //Who is the author?
2230
            $userinfo = api_get_user_info($row['user_id']);
2231
            $email_user_author = get_lang('AddedBy').': '.$userinfo['complete_name'];
2232
2233
            //When ?
2234
            $year = substr($row['dtime'], 0, 4);
2235
            $month = substr($row['dtime'], 5, 2);
2236
            $day = substr($row['dtime'], 8, 2);
2237
            $hours = substr($row['dtime'], 11, 2);
2238
            $minutes = substr($row['dtime'], 14, 2);
2239
            $seconds = substr($row['dtime'], 17, 2);
2240
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2241
2242
            if ($row['assignment'] == 0) {
2243
                $allow_send_mail = true;
2244
            } elseif ($row['assignment'] == 1) {
2245
                $email_assignment = get_lang('AssignmentDescExtra').' ('.get_lang('AssignmentMode').')';
2246
                $allow_send_mail = true;
2247
            } elseif ($row['assignment'] == 2) {
2248
                $allow_send_mail = false; //Mode tasks: avoids notifications to all users about all users
2249
            }
2250
2251
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2252
                    WHERE
2253
                        c_id = '.$course_id.' AND
2254
                        id="'.$id.'" AND
2255
                        type="F" AND
2256
                        group_id="'.$groupId.'" AND
2257
                        session_id="'.$session_id.'"';
2258
2259
            //type: P=page, D=discuss, F=full
2260
            $result = Database::query($sql);
2261
            $emailtext = get_lang('EmailWikiPageAdded').' <strong>'.
2262
                $email_page_name.'</strong> '.get_lang('In').' '.get_lang('Wiki');
2263
        } elseif ($type == 'E') {
2264
            $id = 0;
2265
            $allow_send_mail = true;
2266
            // Who is the author?
2267
            $userinfo = api_get_user_info(api_get_user_id()); //current user
2268
            $email_user_author = get_lang('DeletedBy').': '.$userinfo['complete_name'];
2269
            //When ?
2270
            $today = date('r'); //current time
2271
            $email_date_changes = $today;
2272
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2273
                    WHERE
2274
                        c_id = '.$course_id.' AND
2275
                        id="'.$id.'" AND type="F" AND
2276
                        group_id="'.$groupId.'" AND
2277
                        session_id="'.$session_id.'"'; //type: P=page, D=discuss, F=wiki
2278
            $result = Database::query($sql);
2279
            $emailtext = get_lang('EmailWikipageDedeleted');
2280
        }
2281
        ///make and send email
2282
        if ($allow_send_mail) {
2283
            while ($row = Database::fetch_array($result)) {
2284
                $userinfo = api_get_user_info(
2285
                    $row['user_id']
2286
                ); //$row['user_id'] obtained from tbl_wiki_mailcue
2287
                $name_to = $userinfo['complete_name'];
2288
                $email_to = $userinfo['email'];
2289
                $sender_name = api_get_setting('emailAdministrator');
2290
                $sender_email = api_get_setting('emailAdministrator');
2291
                $email_subject = get_lang(
2292
                        'EmailWikiChanges'
2293
                    ).' - '.$_course['official_code'];
2294
                $email_body = get_lang('DearUser').' '.api_get_person_name(
2295
                        $userinfo['firstname'],
2296
                        $userinfo['lastname']
2297
                    ).',<br /><br />';
2298
                if ($session_id == 0) {
2299
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' - '.$group_name.'</strong><br /><br /><br />';
2300
                } else {
2301
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' ('.api_get_session_name(
2302
                            api_get_session_id()
2303
                        ).') - '.$group_name.'</strong><br /><br /><br />';
2304
                }
2305
                $email_body .= $email_user_author.' ('.$email_date_changes.')<br /><br /><br />';
2306
                $email_body .= $email_assignment.'<br /><br /><br />';
2307
                $email_body .= '<font size="-2">'.get_lang(
2308
                        'EmailWikiChangesExt_1'
2309
                    ).': <strong>'.get_lang('NotifyChanges').'</strong><br />';
2310
                $email_body .= get_lang(
2311
                        'EmailWikiChangesExt_2'
2312
                    ).': <strong>'.get_lang(
2313
                        'NotNotifyChanges'
2314
                    ).'</strong></font><br />';
2315
                @api_mail_html(
2316
                    $name_to,
2317
                    $email_to,
2318
                    $email_subject,
2319
                    $email_body,
2320
                    $sender_name,
2321
                    $sender_email
2322
                );
2323
            }
2324
        }
2325
    }
2326
2327
    /**
2328
     * Function export last wiki page version to document area.
2329
     *
2330
     * @param int $doc_id wiki page id
2331
     *
2332
     * @return mixed
2333
     *
2334
     * @author Juan Carlos Raña <[email protected]>
2335
     */
2336
    public function export2doc($doc_id)
2337
    {
2338
        $_course = $this->courseInfo;
2339
        $groupId = api_get_group_id();
2340
        $groupInfo = GroupManager::get_group_properties($groupId);
2341
        $data = self::getWikiDataFromDb($doc_id);
2342
2343
        if (empty($data)) {
2344
            return false;
2345
        }
2346
2347
        $wikiTitle = $data['title'];
2348
        $wikiContents = $data['content'];
2349
2350
        $template =
2351
            '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2352
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{LANGUAGE}" lang="{LANGUAGE}">
2353
            <head>
2354
            <title>{TITLE}</title>
2355
            <meta http-equiv="Content-Type" content="text/html; charset={ENCODING}" />
2356
            <style type="text/css" media="screen, projection">
2357
            /*<![CDATA[*/
2358
            {CSS}
2359
            /*]]>*/
2360
            </style>
2361
            {ASCIIMATHML_SCRIPT}</head>
2362
            <body dir="{TEXT_DIRECTION}">
2363
            {CONTENT}
2364
            </body>
2365
            </html>';
2366
2367
        $css_file = api_get_path(SYS_CSS_PATH).'themes/'.api_get_setting('stylesheets').'/default.css';
2368
        if (file_exists($css_file)) {
2369
            $css = @file_get_contents($css_file);
2370
        } else {
2371
            $css = '';
2372
        }
2373
        // Fixing some bugs in css files.
2374
        $root_rel = api_get_path(REL_PATH);
2375
        $css_path = 'main/css/';
2376
        $theme = api_get_setting('stylesheets').'/';
2377
        $css = str_replace(
2378
            'behavior:url("/main/css/csshover3.htc");',
2379
            '',
2380
            $css
2381
        );
2382
        $css = str_replace('main/', $root_rel.'main/', $css);
2383
        $css = str_replace(
2384
            'images/',
2385
            $root_rel.$css_path.$theme.'images/',
2386
            $css
2387
        );
2388
        $css = str_replace('../../img/', $root_rel.'main/img/', $css);
2389
        $asciimathmal_script = (api_contains_asciimathml(
2390
                $wikiContents
2391
            ) || api_contains_asciisvg($wikiContents))
2392
            ? '<script src="'.api_get_path(
2393
                WEB_CODE_PATH
2394
            ).'inc/lib/javascript/asciimath/ASCIIMathML.js" type="text/javascript"></script>'."\n" : '';
2395
2396
        $template = str_replace(
2397
            [
2398
                '{LANGUAGE}',
2399
                '{ENCODING}',
2400
                '{TEXT_DIRECTION}',
2401
                '{TITLE}',
2402
                '{CSS}',
2403
                '{ASCIIMATHML_SCRIPT}',
2404
            ],
2405
            [
2406
                api_get_language_isocode(),
2407
                api_get_system_encoding(),
2408
                api_get_text_direction(),
2409
                $wikiTitle,
2410
                $css,
2411
                $asciimathmal_script,
2412
            ],
2413
            $template
2414
        );
2415
2416
        if (0 != $groupId) {
2417
            $groupPart = '_group'.$groupId; // and add groupId to put the same document title in different groups
2418
            $group_properties = GroupManager::get_group_properties($groupId);
2419
            $groupPath = $group_properties['directory'];
2420
        } else {
2421
            $groupPart = '';
2422
            $groupPath = '';
2423
        }
2424
2425
        $exportDir = api_get_path(SYS_COURSE_PATH).api_get_course_path(
2426
            ).'/document'.$groupPath;
2427
        $exportFile = api_replace_dangerous_char($wikiTitle).$groupPart;
2428
        $wikiContents = trim(
2429
            preg_replace(
2430
                "/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/",
2431
                "$1",
2432
                $wikiContents
2433
            )
2434
        );
2435
        //TODO: put link instead of title
2436
        $wikiContents = str_replace('{CONTENT}', $wikiContents, $template);
2437
        // replace relative path by absolute path for courses, so you can see
2438
        // items into this page wiki (images, mp3, etc..) exported in documents
2439
        if (api_strpos(
2440
                $wikiContents,
2441
                '../..'.api_get_path(REL_COURSE_PATH)
2442
            ) !== false) {
2443
            $web_course_path = api_get_path(WEB_COURSE_PATH);
2444
            $wikiContents = str_replace(
2445
                '../..'.api_get_path(REL_COURSE_PATH),
2446
                $web_course_path,
2447
                $wikiContents
2448
            );
2449
        }
2450
2451
        $i = 1;
2452
        //only export last version, but in new export new version in document area
2453
        while (file_exists($exportDir.'/'.$exportFile.'_'.$i.'.html')) {
2454
            $i++;
2455
        }
2456
2457
        $wikiFileName = $exportFile.'_'.$i.'.html';
2458
        $exportPath = $exportDir.'/'.$wikiFileName;
2459
2460
        file_put_contents($exportPath, $wikiContents);
2461
        $doc_id = add_document(
2462
            $_course,
2463
            $groupPath.'/'.$wikiFileName,
2464
            'file',
2465
            filesize($exportPath),
2466
            $wikiTitle
2467
        );
2468
2469
        api_item_property_update(
2470
            $_course,
2471
            TOOL_DOCUMENT,
2472
            $doc_id,
2473
            'DocumentAdded',
2474
            api_get_user_id(),
2475
            $groupInfo
2476
        );
2477
2478
        return $doc_id;
2479
    }
2480
2481
    /**
2482
     * Exports the wiki page to PDF.
2483
     */
2484
    public function export_to_pdf($id, $course_code)
2485
    {
2486
        if (!api_is_platform_admin()) {
2487
            if (api_get_setting('students_export2pdf') !== 'true') {
2488
                Display::addFlash(
2489
                    Display::return_message(
2490
                        get_lang('PDFDownloadNotAllowedForStudents'),
2491
                        'error',
2492
                        false
2493
                    )
2494
                );
2495
2496
                return false;
2497
            }
2498
        }
2499
2500
        $data = self::getWikiDataFromDb($id);
2501
        $content_pdf = api_html_entity_decode(
2502
            $data['content'],
2503
            ENT_QUOTES,
2504
            api_get_system_encoding()
2505
        );
2506
2507
        //clean wiki links
2508
        $content_pdf = trim(
2509
            preg_replace(
2510
                "/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/",
2511
                "$1",
2512
                $content_pdf
2513
            )
2514
        );
2515
        //TODO: It should be better to display the link insted of the tile but it is hard for [[title]] links
2516
2517
        $title_pdf = api_html_entity_decode(
2518
            $data['title'],
2519
            ENT_QUOTES,
2520
            api_get_system_encoding()
2521
        );
2522
        $title_pdf = api_utf8_encode($title_pdf, api_get_system_encoding());
2523
        $content_pdf = api_utf8_encode($content_pdf, api_get_system_encoding());
2524
2525
        $html = '
2526
        <!-- defines the headers/footers - this must occur before the headers/footers are set -->
2527
2528
        <!--mpdf
2529
        <pageheader name="odds" content-left="'.$title_pdf.'"  header-style-left="color: #880000; font-style: italic;"  line="1" />
2530
        <pagefooter name="odds" content-right="{PAGENO}/{nb}" line="1" />
2531
2532
        <!-- set the headers/footers - they will occur from here on in the document -->
2533
        <!--mpdf
2534
        <setpageheader name="odds" page="odd" value="on" show-this-page="1" />
2535
        <setpagefooter name="odds" page="O" value="on" />
2536
2537
        mpdf-->'.$content_pdf;
2538
2539
        $css = api_get_print_css();
2540
2541
        $pdf = new PDF();
2542
        $pdf->content_to_pdf($html, $css, $title_pdf, $course_code);
2543
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
2544
    }
2545
2546
    /**
2547
     * Function prevent double post (reload or F5).
2548
     */
2549
    public function double_post($wpost_id)
2550
    {
2551
        $postId = Session::read('wpost_id');
2552
        if (!empty($postId)) {
2553
            if ($wpost_id == $postId) {
2554
                return false;
2555
            } else {
2556
                Session::write('wpost_id', $wpost_id);
2557
2558
                return true;
2559
            }
2560
        } else {
2561
            Session::write('wpost_id', $wpost_id);
2562
2563
            return true;
2564
        }
2565
    }
2566
2567
    /**
2568
     * Function wizard individual assignment.
2569
     *
2570
     * @author Juan Carlos Raña <[email protected]>
2571
     */
2572
    public function auto_add_page_users($values)
2573
    {
2574
        $assignment_type = $values['assignment'];
2575
        $session_id = $this->session_id;
2576
        $groupId = api_get_group_id();
2577
        $groupInfo = GroupManager::get_group_properties($groupId);
2578
        if ($groupId == 0) {
2579
            //extract course members
2580
            if (!empty($session_id)) {
2581
                $a_users_to_add = CourseManager::get_user_list_from_course_code(
2582
                    api_get_course_id(),
2583
                    $session_id
2584
                );
2585
            } else {
2586
                $a_users_to_add = CourseManager::get_user_list_from_course_code(
2587
                    api_get_course_id(),
2588
                    0
2589
                );
2590
            }
2591
        } else {
2592
            //extract group members
2593
            $subscribed_users = GroupManager::get_subscribed_users($groupInfo);
2594
            $subscribed_tutors = GroupManager::get_subscribed_tutors(
2595
                $groupInfo
2596
            );
2597
            $a_users_to_add_with_duplicates = array_merge(
2598
                $subscribed_users,
2599
                $subscribed_tutors
2600
            );
2601
            //remove duplicates
2602
            $a_users_to_add = $a_users_to_add_with_duplicates;
2603
            $a_users_to_add = array_unique($a_users_to_add);
2604
        }
2605
2606
        $all_students_pages = [];
2607
        // Data about teacher
2608
        $userId = api_get_user_id();
2609
        $userinfo = api_get_user_info($userId);
2610
        $username = api_htmlentities(
2611
            sprintf(get_lang('LoginX'), $userinfo['username'], ENT_QUOTES)
2612
        );
2613
        $name = $userinfo['complete_name']." - ".$username;
2614
        $photo = '<img src="'.$userinfo['avatar'].'" alt="'.$name.'"  width="40" height="50" align="top" title="'.$name.'"  />';
2615
2616
        // teacher assignment title
2617
        $title_orig = $values['title'];
2618
2619
        // teacher assignment reflink
2620
        $link2teacher = $values['title'] = $title_orig."_uass".$userId;
2621
2622
        // first: teacher name, photo, and assignment description (original content)
2623
        $content_orig_A = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2624
        <table border="0">
2625
            <tr><td style="font-size:24px">'.get_lang('AssignmentDesc').'</td></tr>
2626
            <tr><td>'.$photo.'<br />'.Display::tag(
2627
                'span',
2628
                api_get_person_name(
2629
                    $userinfo['firstname'],
2630
                    $userinfo['lastname']
2631
                ),
2632
                ['title' => $username]
2633
            ).'</td></tr>
2634
        </table></div>';
2635
2636
        $content_orig_B = '<br/><div align="center" style="font-size:24px">'.
2637
            get_lang('AssignmentDescription').': '.
2638
            $title_orig.'</div><br/>'.Security::remove_XSS($_POST['content']);
2639
2640
        //Second: student list (names, photo and links to their works).
2641
        //Third: Create Students work pages.
2642
        foreach ($a_users_to_add as $o_user_to_add) {
2643
            if ($o_user_to_add['user_id'] != $userId) {
2644
                // except that puts the task
2645
                $assig_user_id = $o_user_to_add['user_id'];
2646
                // identifies each page as created by the student, not by teacher
2647
2648
                $userPicture = UserManager::getUserPicture($assig_user_id);
2649
                $username = api_htmlentities(
2650
                    sprintf(
2651
                        get_lang('LoginX'),
2652
                        $o_user_to_add['username'],
2653
                        ENT_QUOTES
2654
                    )
2655
                );
2656
                $name = api_get_person_name(
2657
                        $o_user_to_add['firstname'],
2658
                        $o_user_to_add['lastname']
2659
                    )." . ".$username;
2660
                $photo = '<img src="'.$userPicture.'" alt="'.$name.'"  width="40" height="50" align="bottom" title="'.$name.'"  />';
2661
2662
                $is_tutor_of_group = GroupManager::is_tutor_of_group(
2663
                    $assig_user_id,
2664
                    $groupInfo
2665
                ); //student is tutor
2666
                $is_tutor_and_member = GroupManager::is_tutor_of_group(
2667
                        $assig_user_id,
2668
                        $groupInfo
2669
                    ) &&
2670
                    GroupManager::is_subscribed($assig_user_id, $groupInfo);
2671
                // student is tutor and member
2672
                if ($is_tutor_and_member) {
2673
                    $status_in_group = get_lang('GroupTutorAndMember');
2674
                } else {
2675
                    if ($is_tutor_of_group) {
2676
                        $status_in_group = get_lang('GroupTutor');
2677
                    } else {
2678
                        $status_in_group = " "; //get_lang('GroupStandardMember')
2679
                    }
2680
                }
2681
2682
                if ($assignment_type == 1) {
2683
                    $values['title'] = $title_orig;
2684
                    $values['content'] = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2685
                    <table border="0">
2686
                    <tr><td style="font-size:24px">'.get_lang('AssignmentWork').'</td></tr>
2687
                    <tr><td>'.$photo.'<br />'.$name.'</td></tr></table>
2688
                    </div>[['.$link2teacher.' | '.get_lang(
2689
                            'AssignmentLinktoTeacherPage'
2690
                        ).']] ';
2691
                    //If $content_orig_B is added here, the task written by
2692
                    // the professor was copied to the page of each student.
2693
                    // TODO: config options
2694
                    // AssignmentLinktoTeacherPage
2695
                    $all_students_pages[] = '<li>'.
2696
                        Display::tag(
2697
                            'span',
2698
                            strtoupper(
2699
                                $o_user_to_add['lastname']
2700
                            ).', '.$o_user_to_add['firstname'],
2701
                            ['title' => $username]
2702
                        ).
2703
                        ' [['.Security::remove_XSS(
2704
                            $_POST['title']
2705
                        )."_uass".$assig_user_id.' | '.$photo.']] '.$status_in_group.'</li>';
2706
                    // don't change this line without guaranteeing
2707
                    // that users will be ordered by last names in the
2708
                    // following format (surname, name)
2709
                    $values['assignment'] = 2;
2710
                }
2711
                $this->assig_user_id = $assig_user_id;
2712
                $this->save_new_wiki($values);
2713
            }
2714
        }
2715
2716
        foreach ($a_users_to_add as $o_user_to_add) {
2717
            if ($o_user_to_add['user_id'] == $userId) {
2718
                $assig_user_id = $o_user_to_add['user_id'];
2719
                if ($assignment_type == 1) {
2720
                    $values['title'] = $title_orig;
2721
                    $values['comment'] = get_lang('AssignmentDesc');
2722
                    sort($all_students_pages);
2723
                    $values['content'] = $content_orig_A.$content_orig_B.'<br/>
2724
                    <div align="center" style="font-size:18px; background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2725
                    '.get_lang('AssignmentLinkstoStudentsPage').'
2726
                    </div><br/>
2727
                    <div style="background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2728
                    <ol>'.implode($all_students_pages).'</ol>
2729
                    </div>
2730
                    <br/>';
2731
                    $values['assignment'] = 1;
2732
                }
2733
                $this->assig_user_id = $assig_user_id;
2734
                $this->save_new_wiki($values);
2735
            }
2736
        }
2737
    }
2738
2739
    /**
2740
     * Displays the results of a wiki search.
2741
     */
2742
    public function display_wiki_search_results(
2743
        $search_term,
2744
        $search_content = 0,
2745
        $all_vers = 0,
2746
        array $categoryIdList = [],
2747
        bool $matchAllCategories = false
2748
    ) {
2749
        $tbl_wiki = $this->tbl_wiki;
2750
        $sessionCondition = api_get_session_condition($this->session_id, true, false, 'wp.session_id');
2751
        $groupfilter = ' wp.group_id = '.$this->group_id.' ';
2752
        $subGroupfilter = ' s2.group_id = '.$this->group_id.' ';
2753
        $subSessionCondition = api_get_session_condition($this->session_id, true, false, 's2.session_id').' ';
2754
        $categoryIdList = array_map('intval', $categoryIdList);
2755
        $categoriesJoin = '';
2756
2757
        if ($categoryIdList) {
2758
            if ($matchAllCategories) {
2759
                foreach ($categoryIdList as $categoryId) {
2760
                    $categoriesJoin .= "INNER JOIN c_wiki_rel_category AS wrc$categoryId
2761
                            ON (wp.iid = wrc$categoryId.wiki_id AND wrc$categoryId.category_id = $categoryId)
2762
                        INNER JOIN c_wiki_category AS wc$categoryId
2763
                            ON (wrc$categoryId.category_id = wc$categoryId.id) ";
2764
                }
2765
            } else {
2766
                $categoriesJoin = 'INNER JOIN c_wiki_rel_category AS wrc ON (wp.iid = wrc.wiki_id)
2767
                    INNER JOIN c_wiki_category AS wc ON (wrc.category_id = wc.id) ';
2768
            }
2769
        }
2770
2771
        $categoriesCondition = !$matchAllCategories
2772
            ? ($categoryIdList ? 'AND wc.id IN ('.implode(', ', $categoryIdList).')' : '')
2773
            : '';
2774
2775
        $course_id = api_get_course_int_id();
2776
        echo '<legend>'.get_lang('WikiSearchResults').': '.Security::remove_XSS($search_term).'</legend>';
2777
2778
        //only by professors when page is hidden
2779
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
2780
            if ($all_vers == '1') {
2781
                $sql = "SELECT * FROM $tbl_wiki AS wp $categoriesJoin
2782
                    WHERE wp.c_id = $course_id
2783
                        AND (wp.title LIKE '%".Database::escape_string($search_term)."%' ";
2784
2785
                if ($search_content == '1') {
2786
                    $sql .= "OR wp.content LIKE '%".Database::escape_string($search_term)."%' ";
2787
                }
2788
2789
                $sql .= ") AND ".$groupfilter.$sessionCondition.$categoriesCondition;
2790
            } else {
2791
                // warning don't use group by reflink because don't return the last version
2792
                $sql = "SELECT * FROM $tbl_wiki AS wp
2793
                    WHERE wp.c_id = $course_id
2794
                        AND (wp.title LIKE '%".Database::escape_string($search_term)."%' ";
2795
2796
                if ($search_content == '1') {
2797
                    // warning don't use group by reflink because don't return the last version
2798
                    $sql .= "OR wp.content LIKE '%".Database::escape_string($search_term)."%' ";
2799
                }
2800
2801
                $sql .= ") AND wp.id IN (
2802
                    SELECT MAX(s2.id)
2803
                    FROM ".$tbl_wiki." s2 $categoriesJoin
2804
                    WHERE s2.c_id = $course_id
2805
                        AND s2.reflink = wp.reflink
2806
                        AND ".$subGroupfilter.$subSessionCondition.$categoriesCondition."
2807
                )";
2808
            }
2809
        } else {
2810
            if ($all_vers == '1') {
2811
                $sql = "SELECT * FROM $tbl_wiki AS wp $categoriesJoin
2812
                    WHERE wp.c_id = $course_id
2813
                        AND wp.visibility = 1
2814
                        AND (wp.title LIKE '%".Database::escape_string($search_term)."%' ";
2815
2816
                if ($search_content == '1') {
2817
                    //search all pages and all versions
2818
                    $sql .= "OR wp.content LIKE '%".Database::escape_string($search_term)."%' ";
2819
                }
2820
2821
                $sql .= ") AND ".$groupfilter.$sessionCondition.$categoriesCondition;
2822
            } else {
2823
                // warning don't use group by reflink because don't return the last version
2824
                $sql = "SELECT * FROM $tbl_wiki AS wp 
2825
                    WHERE wp.c_id = $course_id
2826
                        AND wp.visibility = 1
2827
                        AND (wp.title LIKE '%".Database::escape_string($search_term)."%' ";
2828
2829
                if ($search_content == '1') {
2830
                    $sql .= "OR wp.content LIKE '%".Database::escape_string($search_term)."%' ";
2831
                }
2832
2833
                $sql .= ") AND wp.id IN (
2834
                        SELECT MAX(s2.id) FROM $tbl_wiki s2 $categoriesJoin
2835
                        WHERE s2.c_id = $course_id
2836
                            AND s2.reflink = wp.reflink
2837
                            AND ".$subGroupfilter.$subSessionCondition.$categoriesCondition."
2838
                    )";
2839
            }
2840
        }
2841
2842
        $result = Database::query($sql);
2843
2844
        //show table
2845
        $rows = [];
2846
        if (Database::num_rows($result) > 0) {
2847
            $self = api_get_self();
2848
            $cidReq = api_get_cidreq();
2849
2850
            $iconEdit = Display::return_icon('edit.png', get_lang('EditPage'));
2851
            $iconDiscuss = Display::return_icon('discuss.png', get_lang('Discuss'));
2852
            $iconHistory = Display::return_icon('history.png', get_lang('History'));
2853
            $iconLinks = Display::return_icon('what_link_here.png', get_lang('LinksPages'));
2854
            $iconDelete = Display::return_icon('delete.png', get_lang('Delete'));
2855
2856
            while ($obj = Database::fetch_object($result)) {
2857
                //get author
2858
                $userinfo = api_get_user_info($obj->user_id);
2859
2860
                //get type assignment icon
2861
                $ShowAssignment = '';
2862
                if ($obj->assignment == 1) {
2863
                    $ShowAssignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'));
2864
                } elseif ($obj->assignment == 2) {
2865
                    $ShowAssignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'));
2866
                } elseif ($obj->assignment == 0) {
2867
                    $ShowAssignment = Display::return_icon('px_transparent.gif');
2868
                }
2869
                $row = [];
2870
                $row[] = $ShowAssignment;
2871
2872
                $wikiLinkParams = [
2873
                    'action' => 'showpage',
2874
                    'title' => api_htmlentities($obj->reflink),
2875
                    'session_id' => $_GET['session_id'],
2876
                    'group_id' => $_GET['group_id'],
2877
                ];
2878
2879
                if ($all_vers == '1') {
2880
                    $wikiLinkParams['view'] = $obj->id;
2881
                }
2882
2883
                $row[] = Display::url(
2884
                    api_htmlentities($obj->title),
2885
                    "$self?$cidReq&".http_build_query($wikiLinkParams)
2886
                ).$this->returnCategoriesBlock($obj->iid, '<div><small>', '</small></div>');
2887
2888
                $row[] = ($obj->user_id != 0 && $userinfo !== false)
2889
                    ? UserManager::getUserProfileLink($userinfo)
2890
                    : get_lang('Anonymous').' ('.$obj->user_ip.')';
2891
                $row[] = api_convert_and_format_date($obj->dtime);
2892
2893
                if ($all_vers == '1') {
2894
                    $row[] = $obj->version;
2895
                } else {
2896
                    $showdelete = '';
2897
                    if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
2898
                        $showdelete = Display::url(
2899
                            $iconDelete,
2900
                            "$self?$cidReq&".http_build_query([
2901
                                'action' => 'delete',
2902
                                'title' => api_htmlentities($obj->reflink),
2903
                                'group_id' => $_GET['group_id'],
2904
                            ])
2905
                        );
2906
                    }
2907
2908
                    $row[] = Display::url(
2909
                            $iconEdit,
2910
                            "$self?$cidReq&".http_build_query([
2911
                                'action' => 'edit',
2912
                                'title' => api_htmlentities($obj->reflink),
2913
                                'group_id' => $_GET['group_id'],
2914
                            ])
2915
                        )
2916
                        .Display::url(
2917
                            $iconDiscuss,
2918
                            "$self?$cidReq&".http_build_query([
2919
                                'action' => 'discuss',
2920
                                'title' => api_htmlentities($obj->reflink),
2921
                                'session_id' => $_GET['session_id'],
2922
                                'group_id' => $_GET['group_id'],
2923
                            ])
2924
                        )
2925
                        .Display::url(
2926
                            $iconHistory,
2927
                            "$self?$cidReq&".http_build_query([
2928
                                'action' => 'history',
2929
                                'title' => api_htmlentities($obj->reflink),
2930
                                'session_id' => $_GET['session_id'],
2931
                                'group_id' => $_GET['group_id'],
2932
                            ])
2933
                        )
2934
                        .Display::url(
2935
                            $iconLinks,
2936
                            "$self?$cidReq&".http_build_query([
2937
                                'action' => 'links',
2938
                                'title' => api_htmlentities($obj->reflink),
2939
                                'group_id' => $_GET['group_id'],
2940
                            ])
2941
                        )
2942
                        .$showdelete;
2943
                }
2944
                $rows[] = $row;
2945
            }
2946
2947
            $table = new SortableTableFromArrayConfig(
2948
                $rows,
2949
                1,
2950
                10,
2951
                'SearchPages_table',
2952
                '',
2953
                '',
2954
                'ASC'
2955
            );
2956
            $table->set_additional_parameters(
2957
                [
2958
                    'cidReq' => $_GET['cidReq'],
2959
                    'action' => $_GET['action'],
2960
                    'group_id' => intval($_GET['group_id']),
2961
                    'mode_table' => 'yes2',
2962
                    'search_term' => $search_term,
2963
                    'search_content' => $search_content,
2964
                    'all_vers' => $all_vers,
2965
                ]
2966
            );
2967
            $table->set_header(
2968
                0,
2969
                get_lang('Type'),
2970
                true,
2971
                ['style' => 'width:30px;']
2972
            );
2973
            $table->set_header(1, get_lang('Title'));
2974
            if ($all_vers == '1') {
2975
                $table->set_header(2, get_lang('Author'));
2976
                $table->set_header(3, get_lang('Date'));
2977
                $table->set_header(4, get_lang('Version'));
2978
            } else {
2979
                $table->set_header(
2980
                    2,
2981
                    get_lang('Author').' <small>'.get_lang('LastVersion').'</small>'
2982
                );
2983
                $table->set_header(
2984
                    3,
2985
                    get_lang('Date').' <small>'.get_lang('LastVersion').'</small>'
2986
                );
2987
                $table->set_header(
2988
                    4,
2989
                    get_lang('Actions'),
2990
                    false,
2991
                    ['style' => 'width:130px;']
2992
                );
2993
            }
2994
            $table->display();
2995
        } else {
2996
            echo get_lang('NoSearchResults');
2997
        }
2998
    }
2999
3000
    /**
3001
     * Get wiki information.
3002
     *
3003
     * @param   int|bool wiki id
3004
     *
3005
     * @return array wiki data
3006
     */
3007
    public function getWikiDataFromDb($id)
3008
    {
3009
        $tbl_wiki = $this->tbl_wiki;
3010
        $course_id = api_get_course_int_id();
3011
        if ($id === false) {
3012
            return [];
3013
        }
3014
        $id = intval($id);
3015
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3016
                WHERE c_id = '.$course_id.' AND id = '.$id.' ';
3017
        $result = Database::query($sql);
3018
        $data = [];
3019
        while ($row = Database::fetch_array($result, 'ASSOC')) {
3020
            $data = $row;
3021
        }
3022
3023
        return $data;
3024
    }
3025
3026
    /**
3027
     * @param string $refLink
3028
     *
3029
     * @return array
3030
     */
3031
    public function getLastWikiData($refLink)
3032
    {
3033
        $tbl_wiki = $this->tbl_wiki;
3034
        $groupfilter = $this->groupfilter;
3035
        $condition_session = $this->condition_session;
3036
        $course_id = api_get_course_int_id();
3037
3038
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3039
                WHERE
3040
                    c_id = '.$course_id.' AND
3041
                    reflink="'.Database::escape_string($refLink).'" AND
3042
                    '.$groupfilter.$condition_session.'
3043
                ORDER BY id DESC';
3044
3045
        $result = Database::query($sql);
3046
3047
        return Database::fetch_array($result);
3048
    }
3049
3050
    /**
3051
     * Get wiki information.
3052
     *
3053
     * @param   string     wiki id
3054
     * @param int $courseId
3055
     *
3056
     * @return array wiki data
3057
     */
3058
    public function getPageByTitle($title, $courseId = null)
3059
    {
3060
        $tbl_wiki = $this->tbl_wiki;
3061
        if (empty($courseId)) {
3062
            $courseId = api_get_course_int_id();
3063
        } else {
3064
            $courseId = intval($courseId);
3065
        }
3066
3067
        if (empty($title) || empty($courseId)) {
3068
            return [];
3069
        }
3070
3071
        $title = Database::escape_string($title);
3072
        $sql = "SELECT * FROM $tbl_wiki
3073
                WHERE c_id = $courseId AND reflink = '$title'";
3074
        $result = Database::query($sql);
3075
        $data = [];
3076
        if (Database::num_rows($result)) {
3077
            $data = Database::fetch_array($result, 'ASSOC');
3078
        }
3079
3080
        return $data;
3081
    }
3082
3083
    /**
3084
     * @param string $title
3085
     * @param int    $courseId
3086
     * @param string
3087
     * @param string
3088
     *
3089
     * @return bool
3090
     */
3091
    public function deletePage(
3092
        $title,
3093
        $courseId,
3094
        $groupfilter = null,
3095
        $condition_session = null
3096
    ) {
3097
        $tbl_wiki = $this->tbl_wiki;
3098
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
3099
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
3100
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3101
3102
        $pageInfo = self::getPageByTitle($title, $courseId);
3103
        if (!empty($pageInfo)) {
3104
            $pageId = $pageInfo['id'];
3105
            $sql = "DELETE FROM $tbl_wiki_conf
3106
                    WHERE c_id = $courseId AND page_id = $pageId";
3107
            Database::query($sql);
3108
3109
            $sql = 'DELETE FROM '.$tbl_wiki_discuss.'
3110
                    WHERE c_id = '.$courseId.' AND publication_id = '.$pageId;
3111
            Database::query($sql);
3112
3113
            $sql = 'DELETE FROM  '.$tbl_wiki_mailcue.'
3114
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3115
            Database::query($sql);
3116
3117
            $sql = 'DELETE FROM '.$tbl_wiki.'
3118
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3119
            Database::query($sql);
3120
            self::check_emailcue(0, 'E');
3121
3122
            return true;
3123
        }
3124
3125
        return false;
3126
    }
3127
3128
    /**
3129
     * @return array
3130
     */
3131
    public function getAllWiki()
3132
    {
3133
        $tbl_wiki = $this->tbl_wiki;
3134
        $course_id = $this->course_id;
3135
        $condition_session = $this->condition_session;
3136
3137
        $sql = "SELECT * FROM $tbl_wiki
3138
                WHERE
3139
                    c_id = $course_id AND
3140
                    is_editing != '0' ".$condition_session;
3141
        $result = Database::query($sql);
3142
3143
        return Database::store_result($result, 'ASSOC');
3144
    }
3145
3146
    /**
3147
     * @param int $isEditing
3148
     */
3149
    public function updateWikiIsEditing($isEditing)
3150
    {
3151
        $tbl_wiki = $this->tbl_wiki;
3152
        $course_id = $this->course_id;
3153
        $condition_session = $this->condition_session;
3154
        $isEditing = Database::escape_string($isEditing);
3155
3156
        $sql = 'UPDATE '.$tbl_wiki.' SET
3157
                is_editing = "0",
3158
                time_edit = NULL
3159
                WHERE
3160
                    c_id = '.$course_id.' AND
3161
                    is_editing="'.$isEditing.'" '.
3162
            $condition_session;
3163
        Database::query($sql);
3164
    }
3165
3166
    /**
3167
     * Release of blocked pages to prevent concurrent editions.
3168
     *
3169
     * @param int    $userId
3170
     * @param string $action
3171
     */
3172
    public function blockConcurrentEditions($userId, $action = null)
3173
    {
3174
        $result = self::getAllWiki();
3175
        if (!empty($result)) {
3176
            foreach ($result as $is_editing_block) {
3177
                $max_edit_time = 1200; // 20 minutes
3178
                $timestamp_edit = strtotime($is_editing_block['time_edit']);
3179
                $time_editing = time() - $timestamp_edit;
3180
3181
                // First prevent concurrent users and double version
3182
                if ($is_editing_block['is_editing'] == $userId) {
3183
                    Session::write('_version', $is_editing_block['version']);
3184
                } else {
3185
                    Session::erase('_version');
3186
                }
3187
                // Second checks if has exceeded the time that a page may
3188
                // be available or if a page was edited and saved by its author
3189
                if ($time_editing > $max_edit_time ||
3190
                    ($is_editing_block['is_editing'] == $userId &&
3191
                        $action != 'edit')
3192
                ) {
3193
                    self::updateWikiIsEditing($is_editing_block['is_editing']);
3194
                }
3195
            }
3196
        }
3197
    }
3198
3199
    /**
3200
     * Showing wiki stats.
3201
     */
3202
    public function getStats()
3203
    {
3204
        if (!api_is_allowed_to_edit(false, true)) {
3205
            return false;
3206
        }
3207
3208
        $tbl_wiki = $this->tbl_wiki;
3209
        $course_id = $this->course_id;
3210
        $condition_session = $this->condition_session;
3211
        $groupfilter = $this->groupfilter;
3212
        $session_id = $this->session_id;
3213
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3214
3215
        echo '<div class="actions">'.get_lang('Statistics').'</div>';
3216
3217
        // Check all versions of all pages
3218
        $total_words = 0;
3219
        $total_links = 0;
3220
        $total_links_anchors = 0;
3221
        $total_links_mail = 0;
3222
        $total_links_ftp = 0;
3223
        $total_links_irc = 0;
3224
        $total_links_news = 0;
3225
        $total_wlinks = 0;
3226
        $total_images = 0;
3227
        $clean_total_flash = 0;
3228
        $total_flash = 0;
3229
        $total_mp3 = 0;
3230
        $total_flv_p = 0;
3231
        $total_flv = 0;
3232
        $total_youtube = 0;
3233
        $total_multimedia = 0;
3234
        $total_tables = 0;
3235
3236
        $sql = "SELECT *, COUNT(*) AS TOTAL_VERS, SUM(hits) AS TOTAL_VISITS
3237
                FROM ".$tbl_wiki."
3238
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3239
3240
        $allpages = Database::query($sql);
3241
        while ($row = Database::fetch_array($allpages)) {
3242
            $total_versions = $row['TOTAL_VERS'];
3243
            $total_visits = intval($row['TOTAL_VISITS']);
3244
        }
3245
3246
        $sql = "SELECT * FROM ".$tbl_wiki."
3247
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3248
        $allpages = Database::query($sql);
3249
3250
        while ($row = Database::fetch_array($allpages)) {
3251
            $total_words = $total_words + self::word_count($row['content']);
3252
            $total_links = $total_links + substr_count(
3253
                $row['content'],
3254
                "href="
3255
            );
3256
            $total_links_anchors = $total_links_anchors + substr_count(
3257
                $row['content'],
3258
                'href="#'
3259
            );
3260
            $total_links_mail = $total_links_mail + substr_count(
3261
                $row['content'],
3262
                'href="mailto'
3263
            );
3264
            $total_links_ftp = $total_links_ftp + substr_count(
3265
                $row['content'],
3266
                'href="ftp'
3267
            );
3268
            $total_links_irc = $total_links_irc + substr_count(
3269
                $row['content'],
3270
                'href="irc'
3271
            );
3272
            $total_links_news = $total_links_news + substr_count(
3273
                $row['content'],
3274
                'href="news'
3275
            );
3276
            $total_wlinks = $total_wlinks + substr_count($row['content'], "[[");
3277
            $total_images = $total_images + substr_count(
3278
                $row['content'],
3279
                "<img"
3280
            );
3281
            $clean_total_flash = preg_replace(
3282
                '/player.swf/',
3283
                ' ',
3284
                $row['content']
3285
            );
3286
            $total_flash = $total_flash + substr_count(
3287
                $clean_total_flash,
3288
                '.swf"'
3289
            );
3290
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3291
            $total_mp3 = $total_mp3 + substr_count($row['content'], ".mp3");
3292
            $total_flv_p = $total_flv_p + substr_count($row['content'], ".flv");
3293
            $total_flv = $total_flv_p / 5;
3294
            $total_youtube = $total_youtube + substr_count(
3295
                $row['content'],
3296
                "http://www.youtube.com"
3297
            );
3298
            $total_multimedia = $total_multimedia + substr_count(
3299
                $row['content'],
3300
                "video/x-msvideo"
3301
            );
3302
            $total_tables = $total_tables + substr_count(
3303
                $row['content'],
3304
                "<table"
3305
            );
3306
        }
3307
3308
        // Check only last version of all pages (current page)
3309
        $sql = ' SELECT *, COUNT(*) AS TOTAL_PAGES, SUM(hits) AS TOTAL_VISITS_LV
3310
                FROM  '.$tbl_wiki.' s1
3311
                WHERE s1.c_id = '.$course_id.' AND id=(
3312
                    SELECT MAX(s2.id)
3313
                    FROM '.$tbl_wiki.' s2
3314
                    WHERE
3315
                        s2.c_id = '.$course_id.' AND
3316
                        s1.reflink = s2.reflink AND
3317
                        '.$groupfilter.' AND
3318
                        session_id='.$session_id.')';
3319
        $allpages = Database::query($sql);
3320
        while ($row = Database::fetch_array($allpages)) {
3321
            $total_pages = $row['TOTAL_PAGES'];
3322
            $total_visits_lv = intval($row['TOTAL_VISITS_LV']);
3323
        }
3324
3325
        $total_words_lv = 0;
3326
        $total_links_lv = 0;
3327
        $total_links_anchors_lv = 0;
3328
        $total_links_mail_lv = 0;
3329
        $total_links_ftp_lv = 0;
3330
        $total_links_irc_lv = 0;
3331
        $total_links_news_lv = 0;
3332
        $total_wlinks_lv = 0;
3333
        $total_images_lv = 0;
3334
        $clean_total_flash_lv = 0;
3335
        $total_flash_lv = 0;
3336
        $total_mp3_lv = 0;
3337
        $total_flv_p_lv = 0;
3338
        $total_flv_lv = 0;
3339
        $total_youtube_lv = 0;
3340
        $total_multimedia_lv = 0;
3341
        $total_tables_lv = 0;
3342
3343
        $sql = 'SELECT * FROM  '.$tbl_wiki.' s1
3344
                WHERE s1.c_id = '.$course_id.' AND id=(
3345
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3346
                    WHERE
3347
                        s2.c_id = '.$course_id.' AND
3348
                        s1.reflink = s2.reflink AND
3349
                        '.$groupfilter.' AND
3350
                        session_id='.$session_id.'
3351
                )';
3352
        $allpages = Database::query($sql);
3353
3354
        while ($row = Database::fetch_array($allpages)) {
3355
            $total_words_lv = $total_words_lv + self::word_count(
3356
                $row['content']
3357
            );
3358
            $total_links_lv = $total_links_lv + substr_count(
3359
                $row['content'],
3360
                "href="
3361
            );
3362
            $total_links_anchors_lv = $total_links_anchors_lv + substr_count(
3363
                $row['content'],
3364
                'href="#'
3365
            );
3366
            $total_links_mail_lv = $total_links_mail_lv + substr_count(
3367
                $row['content'],
3368
                'href="mailto'
3369
            );
3370
            $total_links_ftp_lv = $total_links_ftp_lv + substr_count(
3371
                $row['content'],
3372
                'href="ftp'
3373
            );
3374
            $total_links_irc_lv = $total_links_irc_lv + substr_count(
3375
                $row['content'],
3376
                'href="irc'
3377
            );
3378
            $total_links_news_lv = $total_links_news_lv + substr_count(
3379
                $row['content'],
3380
                'href="news'
3381
            );
3382
            $total_wlinks_lv = $total_wlinks_lv + substr_count(
3383
                $row['content'],
3384
                "[["
3385
            );
3386
            $total_images_lv = $total_images_lv + substr_count(
3387
                $row['content'],
3388
                "<img"
3389
            );
3390
            $clean_total_flash_lv = preg_replace(
3391
                '/player.swf/',
3392
                ' ',
3393
                $row['content']
3394
            );
3395
            $total_flash_lv = $total_flash_lv + substr_count(
3396
                $clean_total_flash_lv,
3397
                '.swf"'
3398
            );
3399
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3400
            $total_mp3_lv = $total_mp3_lv + substr_count(
3401
                $row['content'],
3402
                ".mp3"
3403
            );
3404
            $total_flv_p_lv = $total_flv_p_lv + substr_count(
3405
                $row['content'],
3406
                ".flv"
3407
            );
3408
            $total_flv_lv = $total_flv_p_lv / 5;
3409
            $total_youtube_lv = $total_youtube_lv + substr_count(
3410
                $row['content'],
3411
                "http://www.youtube.com"
3412
            );
3413
            $total_multimedia_lv = $total_multimedia_lv + substr_count(
3414
                $row['content'],
3415
                "video/x-msvideo"
3416
            );
3417
            $total_tables_lv = $total_tables_lv + substr_count(
3418
                $row['content'],
3419
                "<table"
3420
            );
3421
        }
3422
3423
        //Total pages edited at this time
3424
        $total_editing_now = 0;
3425
        $sql = 'SELECT *, COUNT(*) AS TOTAL_EDITING_NOW
3426
                FROM  '.$tbl_wiki.' s1
3427
                WHERE is_editing!=0 AND s1.c_id = '.$course_id.' AND
3428
                id=(
3429
                    SELECT MAX(s2.id)
3430
                    FROM '.$tbl_wiki.' s2
3431
                    WHERE
3432
                        s2.c_id = '.$course_id.' AND
3433
                        s1.reflink = s2.reflink AND
3434
                        '.$groupfilter.' AND
3435
                        session_id='.$session_id.'
3436
        )';
3437
3438
        // Can not use group by because the mark is set in the latest version
3439
        $allpages = Database::query($sql);
3440
        while ($row = Database::fetch_array($allpages)) {
3441
            $total_editing_now = $row['TOTAL_EDITING_NOW'];
3442
        }
3443
3444
        // Total hidden pages
3445
        $total_hidden = 0;
3446
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3447
                WHERE
3448
                    c_id = '.$course_id.' AND
3449
                    visibility = 0 AND
3450
                    '.$groupfilter.$condition_session.'
3451
                GROUP BY reflink';
3452
        // or group by page_id. As the mark of hidden places it in all
3453
        // versions of the page, I can use group by to see the first
3454
        $allpages = Database::query($sql);
3455
        while ($row = Database::fetch_array($allpages)) {
3456
            $total_hidden = $total_hidden + 1;
3457
        }
3458
3459
        //Total protect pages
3460
        $total_protected = 0;
3461
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3462
                WHERE
3463
                    c_id = '.$course_id.' AND
3464
                    editlock = 1 AND
3465
                     '.$groupfilter.$condition_session.'
3466
                GROUP BY reflink';
3467
        // or group by page_id. As the mark of protected page is the
3468
        // first version of the page, I can use group by
3469
        $allpages = Database::query($sql);
3470
        while ($row = Database::fetch_array($allpages)) {
3471
            $total_protected = $total_protected + 1;
3472
        }
3473
3474
        // Total empty versions.
3475
        $total_empty_content = 0;
3476
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3477
                WHERE
3478
                    c_id = '.$course_id.' AND
3479
                    content="" AND
3480
                    '.$groupfilter.$condition_session.'';
3481
        $allpages = Database::query($sql);
3482
        while ($row = Database::fetch_array($allpages)) {
3483
            $total_empty_content = $total_empty_content + 1;
3484
        }
3485
3486
        //Total empty pages (last version)
3487
3488
        $total_empty_content_lv = 0;
3489
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3490
                WHERE s1.c_id = '.$course_id.' AND content="" AND id=(
3491
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3492
                    WHERE
3493
                        s1.c_id = '.$course_id.' AND
3494
                        s1.reflink = s2.reflink AND
3495
                        '.$groupfilter.' AND
3496
                        session_id='.$session_id.'
3497
                )';
3498
        $allpages = Database::query($sql);
3499
        while ($row = Database::fetch_array($allpages)) {
3500
            $total_empty_content_lv = $total_empty_content_lv + 1;
3501
        }
3502
3503
        // Total locked discuss pages
3504
        $total_lock_disc = 0;
3505
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3506
                WHERE c_id = '.$course_id.' AND addlock_disc=0 AND '.$groupfilter.$condition_session.'
3507
                GROUP BY reflink'; //group by because mark lock in all vers, then always is ok
3508
        $allpages = Database::query($sql);
3509
        while ($row = Database::fetch_array($allpages)) {
3510
            $total_lock_disc = $total_lock_disc + 1;
3511
        }
3512
3513
        // Total hidden discuss pages.
3514
        $total_hidden_disc = 0;
3515
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3516
                WHERE c_id = '.$course_id.' AND visibility_disc=0 AND '.$groupfilter.$condition_session.'
3517
                GROUP BY reflink';
3518
        //group by because mark lock in all vers, then always is ok
3519
        $allpages = Database::query($sql);
3520
        while ($row = Database::fetch_array($allpages)) {
3521
            $total_hidden_disc = $total_hidden_disc + 1;
3522
        }
3523
3524
        // Total versions with any short comment by user or system
3525
        $total_comment_version = 0;
3526
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3527
                WHERE c_id = '.$course_id.' AND comment!="" AND '.$groupfilter.$condition_session.'';
3528
        $allpages = Database::query($sql);
3529
        while ($row = Database::fetch_array($allpages)) {
3530
            $total_comment_version = $total_comment_version + 1;
3531
        }
3532
3533
        // Total pages that can only be scored by teachers.
3534
        $total_only_teachers_rating = 0;
3535
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3536
                WHERE c_id = '.$course_id.' AND
3537
                ratinglock_disc = 0 AND
3538
                '.$groupfilter.$condition_session.'
3539
                GROUP BY reflink'; //group by because mark lock in all vers, then always is ok
3540
        $allpages = Database::query($sql);
3541
        while ($row = Database::fetch_array($allpages)) {
3542
            $total_only_teachers_rating = $total_only_teachers_rating + 1;
3543
        }
3544
3545
        // Total pages scored by peers
3546
        // put always this line alfter check num all pages and num pages rated by teachers
3547
        $total_rating_by_peers = $total_pages - $total_only_teachers_rating;
3548
3549
        //Total pages identified as standard task
3550
        $total_task = 0;
3551
        $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
3552
              WHERE '.$tbl_wiki_conf.'.c_id = '.$course_id.' AND
3553
               '.$tbl_wiki_conf.'.task!="" AND
3554
               '.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
3555
                '.$tbl_wiki.'.'.$groupfilter.$condition_session;
3556
        $allpages = Database::query($sql);
3557
        while ($row = Database::fetch_array($allpages)) {
3558
            $total_task = $total_task + 1;
3559
        }
3560
3561
        //Total pages identified as teacher page (wiki portfolio mode - individual assignment)
3562
        $total_teacher_assignment = 0;
3563
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3564
                WHERE s1.c_id = '.$course_id.' AND assignment=1 AND id=(
3565
                    SELECT MAX(s2.id)
3566
                    FROM '.$tbl_wiki.' s2
3567
                    WHERE
3568
                        s2.c_id = '.$course_id.' AND
3569
                        s1.reflink = s2.reflink AND
3570
                        '.$groupfilter.' AND
3571
                         session_id='.$session_id.'
3572
                )';
3573
        //mark all versions, but do not use group by reflink because y want the pages not versions
3574
        $allpages = Database::query($sql);
3575
        while ($row = Database::fetch_array($allpages)) {
3576
            $total_teacher_assignment = $total_teacher_assignment + 1;
3577
        }
3578
3579
        //Total pages identifies as student page (wiki portfolio mode - individual assignment)
3580
        $total_student_assignment = 0;
3581
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3582
                WHERE s1.c_id = '.$course_id.' AND assignment=2 AND
3583
                id = (SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3584
                WHERE
3585
                    s2.c_id = '.$course_id.' AND
3586
                    s1.reflink = s2.reflink AND
3587
                    '.$groupfilter.' AND
3588
                    session_id='.$session_id.'
3589
                )';
3590
        //mark all versions, but do not use group by reflink because y want the pages not versions
3591
        $allpages = Database::query($sql);
3592
        while ($row = Database::fetch_array($allpages)) {
3593
            $total_student_assignment = $total_student_assignment + 1;
3594
        }
3595
3596
        //Current Wiki status add new pages
3597
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3598
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3599
                GROUP BY addlock'; //group by because mark 0 in all vers, then always is ok
3600
        $allpages = Database::query($sql);
3601
        $wiki_add_lock = null;
3602
        while ($row = Database::fetch_array($allpages)) {
3603
            $wiki_add_lock = $row['addlock'];
3604
        }
3605
3606
        if ($wiki_add_lock == 1) {
3607
            $status_add_new_pag = get_lang('Yes');
3608
        } else {
3609
            $status_add_new_pag = get_lang('No');
3610
        }
3611
3612
        // Creation date of the oldest wiki page and version
3613
        $first_wiki_date = null;
3614
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3615
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3616
                ORDER BY dtime ASC
3617
                LIMIT 1';
3618
        $allpages = Database::query($sql);
3619
        while ($row = Database::fetch_array($allpages)) {
3620
            $first_wiki_date = api_get_local_time($row['dtime']);
3621
        }
3622
3623
        // Date of publication of the latest wiki version.
3624
3625
        $last_wiki_date = null;
3626
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3627
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3628
                ORDER BY dtime DESC
3629
                LIMIT 1';
3630
        $allpages = Database::query($sql);
3631
        while ($row = Database::fetch_array($allpages)) {
3632
            $last_wiki_date = api_get_local_time($row['dtime']);
3633
        }
3634
3635
        // Average score of all wiki pages. (If a page has not scored zero rated)
3636
        $media_score = 0;
3637
        $sql = "SELECT *, SUM(score) AS TOTAL_SCORE FROM ".$tbl_wiki."
3638
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."
3639
                GROUP BY reflink ";
3640
        //group by because mark in all versions, then always is ok.
3641
        // Do not use "count" because using "group by", would give a wrong value
3642
        $allpages = Database::query($sql);
3643
        $total_score = 0;
3644
        while ($row = Database::fetch_array($allpages)) {
3645
            $total_score = $total_score + $row['TOTAL_SCORE'];
3646
        }
3647
3648
        if (!empty($total_pages)) {
3649
            $media_score = $total_score / $total_pages;
3650
            //put always this line alfter check num all pages
3651
        }
3652
3653
        // Average user progress in his pages.
3654
        $media_progress = 0;
3655
        $sql = 'SELECT  *, SUM(progress) AS TOTAL_PROGRESS
3656
                FROM  '.$tbl_wiki.' s1
3657
                WHERE s1.c_id = '.$course_id.' AND id=
3658
                (
3659
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3660
                    WHERE
3661
                        s2.c_id = '.$course_id.' AND
3662
                        s1.reflink = s2.reflink AND
3663
                        '.$groupfilter.' AND
3664
                        session_id='.$session_id.'
3665
                )';
3666
        // As the value is only the latest version I can not use group by
3667
        $allpages = Database::query($sql);
3668
        while ($row = Database::fetch_array($allpages)) {
3669
            $total_progress = $row['TOTAL_PROGRESS'];
3670
        }
3671
3672
        if (!empty($total_pages)) {
3673
            $media_progress = $total_progress / $total_pages;
3674
            //put always this line alfter check num all pages
3675
        }
3676
3677
        // Total users that have participated in the Wiki
3678
        $total_users = 0;
3679
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3680
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3681
                GROUP BY user_id';
3682
        //as the mark of user it in all versions of the page, I can use group by to see the first
3683
        $allpages = Database::query($sql);
3684
        while ($row = Database::fetch_array($allpages)) {
3685
            $total_users = $total_users + 1;
3686
        }
3687
3688
        // Total of different IP addresses that have participated in the wiki
3689
        $total_ip = 0;
3690
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3691
              WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3692
              GROUP BY user_ip';
3693
        $allpages = Database::query($sql);
3694
        while ($row = Database::fetch_array($allpages)) {
3695
            $total_ip = $total_ip + 1;
3696
        }
3697
3698
        echo '<table class="table table-hover table-striped data_table">';
3699
        echo '<thead>';
3700
        echo '<tr>';
3701
        echo '<th colspan="2">'.get_lang('General').'</th>';
3702
        echo '</tr>';
3703
        echo '</thead>';
3704
        echo '<tr>';
3705
        echo '<td>'.get_lang('StudentAddNewPages').'</td>';
3706
        echo '<td>'.$status_add_new_pag.'</td>';
3707
        echo '</tr>';
3708
        echo '<tr>';
3709
        echo '<td>'.get_lang('DateCreateOldestWikiPage').'</td>';
3710
        echo '<td>'.$first_wiki_date.'</td>';
3711
        echo '</tr>';
3712
        echo '<tr>';
3713
        echo '<td>'.get_lang('DateEditLatestWikiVersion').'</td>';
3714
        echo '<td>'.$last_wiki_date.'</td>';
3715
        echo '</tr>';
3716
        echo '<tr>';
3717
        echo '<td>'.get_lang('AverageScoreAllPages').'</td>';
3718
        echo '<td>'.$media_score.' %</td>';
3719
        echo '</tr>';
3720
        echo '<tr>';
3721
        echo '<td>'.get_lang('AverageMediaUserProgress').'</td>';
3722
        echo '<td>'.$media_progress.' %</td>';
3723
        echo '</tr>';
3724
        echo '<tr>';
3725
        echo '<td>'.get_lang('TotalWikiUsers').'</td>';
3726
        echo '<td>'.$total_users.'</td>';
3727
        echo '</tr>';
3728
        echo '<tr>';
3729
        echo '<td>'.get_lang('TotalIpAdress').'</td>';
3730
        echo '<td>'.$total_ip.'</td>';
3731
        echo '</tr>';
3732
        echo '</table>';
3733
        echo '<br/>';
3734
3735
        echo '<table class="table table-hover table-striped data_table">';
3736
        echo '<thead>';
3737
        echo '<tr>';
3738
        echo '<th colspan="2">'.get_lang('Pages').' '.get_lang(
3739
                'And'
3740
            ).' '.get_lang('Versions').'</th>';
3741
        echo '</tr>';
3742
        echo '</thead>';
3743
        echo '<tr>';
3744
        echo '<td>'.get_lang('Pages').' - '.get_lang(
3745
                'NumContributions'
3746
            ).'</td>';
3747
        echo '<td>'.$total_pages.' ('.get_lang(
3748
                'Versions'
3749
            ).': '.$total_versions.')</td>';
3750
        echo '</tr>';
3751
        echo '<tr>';
3752
        echo '<td>'.get_lang('EmptyPages').'</td>';
3753
        echo '<td>'.$total_empty_content_lv.' ('.get_lang(
3754
                'Versions'
3755
            ).': '.$total_empty_content.')</td>';
3756
        echo '</tr>';
3757
        echo '<tr>';
3758
        echo '<td>'.get_lang('NumAccess').'</td>';
3759
        echo '<td>'.$total_visits_lv.' ('.get_lang(
3760
                'Versions'
3761
            ).': '.$total_visits.')</td>';
3762
        echo '</tr>';
3763
        echo '<tr>';
3764
        echo '<td>'.get_lang('TotalPagesEditedAtThisTime').'</td>';
3765
        echo '<td>'.$total_editing_now.'</td>';
3766
        echo '</tr>';
3767
        echo '<tr>';
3768
        echo '<td>'.get_lang('TotalHiddenPages').'</td>';
3769
        echo '<td>'.$total_hidden.'</td>';
3770
        echo '</tr>';
3771
        echo '<tr>';
3772
        echo '<td>'.get_lang('NumProtectedPages').'</td>';
3773
        echo '<td>'.$total_protected.'</td>';
3774
        echo '</tr>';
3775
        echo '<tr>';
3776
        echo '<td>'.get_lang('LockedDiscussPages').'</td>';
3777
        echo '<td>'.$total_lock_disc.'</td>';
3778
        echo '</tr>';
3779
        echo '<tr>';
3780
        echo '<td>'.get_lang('HiddenDiscussPages').'</td>';
3781
        echo '<td>'.$total_hidden_disc.'</td>';
3782
        echo '</tr>';
3783
        echo '<tr>';
3784
        echo '<td>'.get_lang('TotalComments').'</td>';
3785
        echo '<td>'.$total_comment_version.'</td>';
3786
        echo '</tr>';
3787
        echo '<tr>';
3788
        echo '<td>'.get_lang('TotalOnlyRatingByTeacher').'</td>';
3789
        echo '<td>'.$total_only_teachers_rating.'</td>';
3790
        echo '</tr>';
3791
        echo '<tr>';
3792
        echo '<td>'.get_lang('TotalRatingPeers').'</td>';
3793
        echo '<td>'.$total_rating_by_peers.'</td>';
3794
        echo '</tr>';
3795
        echo '<tr>';
3796
        echo '<td>'.get_lang('TotalTeacherAssignments').' - '.get_lang(
3797
                'PortfolioMode'
3798
            ).'</td>';
3799
        echo '<td>'.$total_teacher_assignment.'</td>';
3800
        echo '</tr>';
3801
        echo '<tr>';
3802
        echo '<td>'.get_lang('TotalStudentAssignments').' - '.get_lang(
3803
                'PortfolioMode'
3804
            ).'</td>';
3805
        echo '<td>'.$total_student_assignment.'</td>';
3806
        echo '</tr>';
3807
        echo '<tr>';
3808
        echo '<td>'.get_lang('TotalTask').' - '.get_lang(
3809
                'StandardMode'
3810
            ).'</td>';
3811
        echo '<td>'.$total_task.'</td>';
3812
        echo '</tr>';
3813
        echo '</table>';
3814
        echo '<br/>';
3815
3816
        echo '<table class="table table-hover table-striped data_table">';
3817
        echo '<thead>';
3818
        echo '<tr>';
3819
        echo '<th colspan="3">'.get_lang('ContentPagesInfo').'</th>';
3820
        echo '</tr>';
3821
        echo '<tr>';
3822
        echo '<td></td>';
3823
        echo '<td>'.get_lang('InTheLastVersion').'</td>';
3824
        echo '<td>'.get_lang('InAllVersions').'</td>';
3825
        echo '</tr>';
3826
        echo '</thead>';
3827
        echo '<tr>';
3828
        echo '<td>'.get_lang('NumWords').'</td>';
3829
        echo '<td>'.$total_words_lv.'</td>';
3830
        echo '<td>'.$total_words.'</td>';
3831
        echo '</tr>';
3832
        echo '<tr>';
3833
        echo '<td>'.get_lang('NumlinksHtmlImagMedia').'</td>';
3834
        echo '<td>'.$total_links_lv.' ('.get_lang(
3835
                'Anchors'
3836
            ).':'.$total_links_anchors_lv.', Mail:'.$total_links_mail_lv.', FTP:'.$total_links_ftp_lv.' IRC:'.$total_links_irc_lv.', News:'.$total_links_news_lv.', ... ) </td>';
3837
        echo '<td>'.$total_links.' ('.get_lang(
3838
                'Anchors'
3839
            ).':'.$total_links_anchors.', Mail:'.$total_links_mail.', FTP:'.$total_links_ftp.', IRC:'.$total_links_irc.', News:'.$total_links_news.', ... ) </td>';
3840
        echo '</tr>';
3841
        echo '<tr>';
3842
        echo '<td>'.get_lang('NumWikilinks').'</td>';
3843
        echo '<td>'.$total_wlinks_lv.'</td>';
3844
        echo '<td>'.$total_wlinks.'</td>';
3845
        echo '</tr>';
3846
        echo '<tr>';
3847
        echo '<td>'.get_lang('NumImages').'</td>';
3848
        echo '<td>'.$total_images_lv.'</td>';
3849
        echo '<td>'.$total_images.'</td>';
3850
        echo '</tr>';
3851
        echo '<tr>';
3852
        echo '<td>'.get_lang('NumFlash').'</td>';
3853
        echo '<td>'.$total_flash_lv.'</td>';
3854
        echo '<td>'.$total_flash.'</td>';
3855
        echo '</tr>';
3856
        echo '<tr>';
3857
        echo '<td>'.get_lang('NumMp3').'</td>';
3858
        echo '<td>'.$total_mp3_lv.'</td>';
3859
        echo '<td>'.$total_mp3.'</td>';
3860
        echo '</tr>';
3861
        echo '<tr>';
3862
        echo '<td>'.get_lang('NumFlvVideo').'</td>';
3863
        echo '<td>'.$total_flv_lv.'</td>';
3864
        echo '<td>'.$total_flv.'</td>';
3865
        echo '</tr>';
3866
        echo '<tr>';
3867
        echo '<td>'.get_lang('NumYoutubeVideo').'</td>';
3868
        echo '<td>'.$total_youtube_lv.'</td>';
3869
        echo '<td>'.$total_youtube.'</td>';
3870
        echo '</tr>';
3871
        echo '<tr>';
3872
        echo '<td>'.get_lang('NumOtherAudioVideo').'</td>';
3873
        echo '<td>'.$total_multimedia_lv.'</td>';
3874
        echo '<td>'.$total_multimedia.'</td>';
3875
        echo '</tr>';
3876
        echo '<tr>';
3877
        echo '<td>'.get_lang('NumTables').'</td>';
3878
        echo '<td>'.$total_tables_lv.'</td>';
3879
        echo '<td>'.$total_tables.'</td>';
3880
        echo '</tr>';
3881
        echo '</table>';
3882
    }
3883
3884
    /**
3885
     * @param string $action
3886
     */
3887
    public function getActiveUsers($action)
3888
    {
3889
        $tbl_wiki = $this->tbl_wiki;
3890
        $course_id = $this->course_id;
3891
        $condition_session = $this->condition_session;
3892
        $groupfilter = $this->groupfilter;
3893
        $_course = $this->courseInfo;
3894
3895
        echo '<div class="actions">'.get_lang('MostActiveUsers').'</div>';
3896
        $sql = 'SELECT *, COUNT(*) AS NUM_EDIT FROM '.$tbl_wiki.'
3897
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3898
                GROUP BY user_id';
3899
        $allpages = Database::query($sql);
3900
3901
        //show table
3902
        if (Database::num_rows($allpages) > 0) {
3903
            while ($obj = Database::fetch_object($allpages)) {
3904
                $userinfo = api_get_user_info($obj->user_id);
3905
                $row = [];
3906
                if ($obj->user_id != 0 && $userinfo !== false) {
3907
                    $row[] = UserManager::getUserProfileLink($userinfo).'
3908
                            <a href="'.api_get_self(
3909
                        ).'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode(
3910
                            $obj->user_id
3911
                        ).
3912
                        '&session_id='.api_htmlentities(
3913
                            $_GET['session_id']
3914
                        ).'&group_id='.api_htmlentities(
3915
                            $_GET['group_id']
3916
                        ).'"></a>';
3917
                } else {
3918
                    $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
3919
                }
3920
                $row[] = '<a href="'.api_get_self(
3921
                    ).'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode(
3922
                        $obj->user_id
3923
                    ).'&session_id='.api_htmlentities(
3924
                        $_GET['session_id']
3925
                    ).'&group_id='.api_htmlentities(
3926
                        $_GET['group_id']
3927
                    ).'">'.$obj->NUM_EDIT.'</a>';
3928
                $rows[] = $row;
3929
            }
3930
3931
            $table = new SortableTableFromArrayConfig(
3932
                $rows,
3933
                1,
3934
                10,
3935
                'MostActiveUsersA_table',
3936
                '',
3937
                '',
3938
                'DESC'
3939
            );
3940
            $table->set_additional_parameters(
3941
                [
3942
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
3943
                    'action' => Security::remove_XSS($action),
3944
                    'session_id' => Security::remove_XSS($_GET['session_id']),
3945
                    'group_id' => Security::remove_XSS($_GET['group_id']),
3946
                ]
3947
            );
3948
            $table->set_header(0, get_lang('Author'), true);
3949
            $table->set_header(
3950
                1,
3951
                get_lang('Contributions'),
3952
                true,
3953
                ['style' => 'width:30px;']
3954
            );
3955
            $table->display();
3956
        }
3957
    }
3958
3959
    /**
3960
     * @param string $page
3961
     */
3962
    public function getDiscuss($page)
3963
    {
3964
        $tbl_wiki = $this->tbl_wiki;
3965
        $course_id = $this->course_id;
3966
        $condition_session = $this->condition_session;
3967
        $groupfilter = $this->groupfilter;
3968
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
3969
3970
        if (api_get_session_id() != 0 &&
3971
            api_is_allowed_to_session_edit(false, true) == false
3972
        ) {
3973
            api_not_allowed();
3974
        }
3975
3976
        if (!$_GET['title']) {
3977
            Display::addFlash(
3978
                Display::return_message(
3979
                    get_lang("MustSelectPage"),
3980
                    'error',
3981
                    false
3982
                )
3983
            );
3984
3985
            return;
3986
        }
3987
3988
        // First extract the date of last version
3989
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3990
                WHERE
3991
                    c_id = '.$course_id.' AND
3992
                    reflink = "'.Database::escape_string($page).'" AND
3993
                    '.$groupfilter.$condition_session.'
3994
                ORDER BY id DESC';
3995
        $result = Database::query($sql);
3996
        $row = Database::fetch_array($result);
3997
        $lastversiondate = api_get_local_time($row['dtime']);
3998
        $lastuserinfo = api_get_user_info($row['user_id']);
3999
4000
        // Select page to discuss
4001
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4002
                WHERE
4003
                    c_id = '.$course_id.' AND
4004
                    reflink="'.Database::escape_string($page).'" AND
4005
                    '.$groupfilter.$condition_session.'
4006
                ORDER BY id ASC';
4007
        $result = Database::query($sql);
4008
        $row = Database::fetch_array($result);
4009
        $id = $row['id'];
4010
        $firstuserid = $row['user_id'];
4011
4012
        if (isset($_POST['Submit']) && self::double_post($_POST['wpost_id'])) {
4013
            $dtime = api_get_utc_datetime();
4014
            $message_author = api_get_user_id();
4015
4016
            $params = [
4017
                'c_id' => $course_id,
4018
                'publication_id' => $id,
4019
                'userc_id' => $message_author,
4020
                'comment' => $_POST['comment'],
4021
                'p_score' => $_POST['rating'],
4022
                'dtime' => $dtime,
4023
            ];
4024
            $discussId = Database::insert($tbl_wiki_discuss, $params);
4025
            if ($discussId) {
4026
                $sql = "UPDATE $tbl_wiki_discuss SET id = iid WHERE iid = $discussId";
4027
                Database::query($sql);
4028
            }
4029
4030
            self::check_emailcue($id, 'D', $dtime, $message_author);
4031
4032
            header(
4033
                'Location: index.php?action=discuss&title='.api_htmlentities(urlencode($page)).'&'.api_get_cidreq()
4034
            );
4035
            exit;
4036
        }
4037
4038
        // mode assignment: previous to show  page type
4039
        $icon_assignment = null;
4040
        if ($row['assignment'] == 1) {
4041
            $icon_assignment = Display::return_icon(
4042
                'wiki_assignment.png',
4043
                get_lang('AssignmentDescExtra'),
4044
                '',
4045
                ICON_SIZE_SMALL
4046
            );
4047
        } elseif ($row['assignment'] == 2) {
4048
            $icon_assignment = Display::return_icon(
4049
                'wiki_work.png',
4050
                get_lang('AssignmentWorkExtra'),
4051
                '',
4052
                ICON_SIZE_SMALL
4053
            );
4054
        }
4055
4056
        $countWPost = null;
4057
        $avg_WPost_score = null;
4058
4059
        // Show title and form to discuss if page exist
4060
        if ($id != '') {
4061
            // Show discussion to students if isn't hidden.
4062
            // Show page to all teachers if is hidden.
4063
            // Mode assignments: If is hidden, show pages to student only if student is the author
4064
            if ($row['visibility_disc'] == 1 ||
4065
                api_is_allowed_to_edit(false, true) ||
4066
                api_is_platform_admin() ||
4067
                ($row['assignment'] == 2 && $row['visibility_disc'] == 0 && (api_get_user_id() == $row['user_id']))
4068
            ) {
4069
                echo '<div id="wikititle">';
4070
                // discussion action: protecting (locking) the discussion
4071
                $addlock_disc = null;
4072
                $lock_unlock_disc = null;
4073
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4074
                    if (self::check_addlock_discuss() == 1) {
4075
                        $addlock_disc = Display::return_icon(
4076
                            'unlock.png',
4077
                            get_lang('UnlockDiscussExtra'),
4078
                            '',
4079
                            ICON_SIZE_SMALL
4080
                        );
4081
                        $lock_unlock_disc = 'unlockdisc';
4082
                    } else {
4083
                        $addlock_disc = Display::return_icon(
4084
                            'lock.png',
4085
                            get_lang('LockDiscussExtra'),
4086
                            '',
4087
                            ICON_SIZE_SMALL
4088
                        );
4089
                        $lock_unlock_disc = 'lockdisc';
4090
                    }
4091
                }
4092
                echo '<span style="float:right">';
4093
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_disc.'&title='.api_htmlentities(
4094
                        urlencode($page)
4095
                    ).'">'.$addlock_disc.'</a>';
4096
                echo '</span>';
4097
4098
                // discussion action: visibility.  Show discussion to students if isn't hidden. Show page to all teachers if is hidden.
4099
                $visibility_disc = null;
4100
                $hide_show_disc = null;
4101
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4102
                    if (self::check_visibility_discuss() == 1) {
4103
                        /// TODO: 	Fix Mode assignments: If is hidden, show discussion to student only if student is the author
4104
                        $visibility_disc = Display::return_icon(
4105
                            'visible.png',
4106
                            get_lang('ShowDiscussExtra'),
4107
                            '',
4108
                            ICON_SIZE_SMALL
4109
                        );
4110
                        $hide_show_disc = 'hidedisc';
4111
                    } else {
4112
                        $visibility_disc = Display::return_icon(
4113
                            'invisible.png',
4114
                            get_lang('HideDiscussExtra'),
4115
                            '',
4116
                            ICON_SIZE_SMALL
4117
                        );
4118
                        $hide_show_disc = 'showdisc';
4119
                    }
4120
                }
4121
                echo '<span style="float:right">';
4122
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$hide_show_disc.'&title='.api_htmlentities(
4123
                        urlencode($page)
4124
                    ).'">'.$visibility_disc.'</a>';
4125
                echo '</span>';
4126
4127
                // discussion action: check add rating lock. Show/Hide list to rating for all student
4128
                $lock_unlock_rating_disc = null;
4129
                $ratinglock_disc = null;
4130
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4131
                    if (self::check_ratinglock_discuss() == 1) {
4132
                        $ratinglock_disc = Display::return_icon(
4133
                            'star.png',
4134
                            get_lang('UnlockRatingDiscussExtra'),
4135
                            '',
4136
                            ICON_SIZE_SMALL
4137
                        );
4138
                        $lock_unlock_rating_disc = 'unlockrating';
4139
                    } else {
4140
                        $ratinglock_disc = Display::return_icon(
4141
                            'star_na.png',
4142
                            get_lang('LockRatingDiscussExtra'),
4143
                            '',
4144
                            ICON_SIZE_SMALL
4145
                        );
4146
                        $lock_unlock_rating_disc = 'lockrating';
4147
                    }
4148
                }
4149
4150
                echo '<span style="float:right">';
4151
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_rating_disc.'&title='.api_htmlentities(
4152
                        urlencode($page)
4153
                    ).'">'.$ratinglock_disc.'</a>';
4154
                echo '</span>';
4155
4156
                // discussion action: email notification
4157
                if (self::check_notify_discuss($page) == 1) {
4158
                    $notify_disc = Display::return_icon(
4159
                        'messagebox_info.png',
4160
                        get_lang('NotifyDiscussByEmail'),
4161
                        '',
4162
                        ICON_SIZE_SMALL
4163
                    );
4164
                    $lock_unlock_notify_disc = 'unlocknotifydisc';
4165
                } else {
4166
                    $notify_disc = Display::return_icon(
4167
                        'mail.png',
4168
                        get_lang('CancelNotifyDiscussByEmail'),
4169
                        '',
4170
                        ICON_SIZE_SMALL
4171
                    );
4172
                    $lock_unlock_notify_disc = 'locknotifydisc';
4173
                }
4174
                echo '<span style="float:right">';
4175
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_notify_disc.'&title='.api_htmlentities(
4176
                        urlencode($page)
4177
                    ).'">'.$notify_disc.'</a>';
4178
                echo '</span>';
4179
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities(
4180
                        $row['title']
4181
                    );
4182
                if ($lastuserinfo !== false) {
4183
                    echo ' ('.get_lang('MostRecentVersionBy').' '.
4184
                        UserManager::getUserProfileLink($lastuserinfo).' '.$lastversiondate.$countWPost.')'.$avg_WPost_score.' '; //TODO: read average score
4185
                }
4186
4187
                echo '</div>';
4188
                if ($row['addlock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4189
                    //show comments but students can't add theirs
4190
                    ?>
4191
                    <div class="panel panel-default">
4192
                        <div class="panel-body">
4193
                            <form name="form1" method="post" action=""
4194
                                  class="form-horizontal">
4195
                                <div class="form-group">
4196
                                    <label
4197
                                        class="col-sm-2 control-label">
4198
                                        <?php echo get_lang('Comments'); ?>:</label>
4199
                                    <div class="col-sm-10">
4200
                                        <?php echo '<input type="hidden" name="wpost_id" value="'.md5(uniqid(rand(), true)).'">'; //prevent double post?>
4201
                                        <textarea class="form-control"
4202
                                                  name="comment" cols="80"
4203
                                                  rows="5"
4204
                                                  id="comment">
4205
                                        </textarea>
4206
                                    </div>
4207
                                </div>
4208
                                <div class="form-group">
4209
                                    <?php
4210
                                    //check if rating is allowed
4211
                                    if ($row['ratinglock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4212
                                        ?>
4213
                                        <label
4214
                                            class="col-sm-2 control-label"><?php echo get_lang('Rating'); ?>:</label>
4215
                                        <div class="col-sm-10">
4216
                                            <select name="rating" id="rating" class="selectpicker">
4217
                                                <option value="-" selected>-</option>
4218
                                                <option value="0">0</option>
4219
                                                <option value="1">1</option>
4220
                                                <option value="2">2</option>
4221
                                                <option value="3">3</option>
4222
                                                <option value="4">4</option>
4223
                                                <option value="5">5</option>
4224
                                                <option value="6">6</option>
4225
                                                <option value="7">7</option>
4226
                                                <option value="8">8</option>
4227
                                                <option value="9">9</option>
4228
                                                <option value="10">10</option>
4229
                                            </select>
4230
                                        </div>
4231
                                        <?php
4232
                                    } else {
4233
                                        echo '<input type=hidden name="rating" value="-">';
4234
                                        // must pass a default value to avoid rate automatically
4235
                                    } ?>
4236
4237
                                </div>
4238
                                <div class="form-group">
4239
                                    <div class="col-sm-offset-2 col-sm-10">
4240
                                        <?php echo '<button class="btn btn-default" type="submit" name="Submit"> '.
4241
                                            get_lang('Send').'</button>'; ?>
4242
                                    </div>
4243
                                </div>
4244
                        </div>
4245
                    </div>
4246
                    </form>
4247
                    <?php
4248
                }
4249
                // end discuss lock
4250
4251
                echo '<hr noshade size="1">';
4252
                $user_table = Database::get_main_table(TABLE_MAIN_USER);
4253
4254
                $sql = "SELECT *
4255
                        FROM $tbl_wiki_discuss reviews, $user_table user
4256
                        WHERE
4257
                            reviews.c_id = $course_id AND
4258
                            reviews.publication_id='".$id."' AND
4259
                            user.user_id='".$firstuserid."'
4260
                        ORDER BY reviews.id DESC";
4261
                $result = Database::query($sql);
4262
4263
                $countWPost = Database::num_rows($result);
4264
                echo get_lang('NumComments').": ".$countWPost; //comment's numbers
4265
4266
                $sql = "SELECT SUM(p_score) as sumWPost
4267
                        FROM $tbl_wiki_discuss
4268
                        WHERE c_id = $course_id AND publication_id = '".$id."' AND NOT p_score='-'
4269
                        ORDER BY id DESC";
4270
                $result2 = Database::query($sql);
4271
                $row2 = Database::fetch_array($result2);
4272
4273
                $sql = "SELECT * FROM $tbl_wiki_discuss
4274
                        WHERE c_id = $course_id AND publication_id='".$id."' AND NOT p_score='-'";
4275
                $result3 = Database::query($sql);
4276
                $countWPost_score = Database::num_rows($result3);
4277
4278
                echo ' - '.get_lang('NumCommentsScore').': '.$countWPost_score;
4279
4280
                if ($countWPost_score != 0) {
4281
                    $avg_WPost_score = round($row2['sumWPost'] / $countWPost_score, 2).' / 10';
4282
                } else {
4283
                    $avg_WPost_score = $countWPost_score;
4284
                }
4285
4286
                echo ' - '.get_lang('RatingMedia').': '.$avg_WPost_score; // average rating
4287
4288
                $sql = 'UPDATE '.$tbl_wiki.' SET
4289
                        score = "'.Database::escape_string($avg_WPost_score).'"
4290
                        WHERE
4291
                            c_id = '.$course_id.' AND
4292
                            reflink="'.Database::escape_string($page).'" AND
4293
                            '.$groupfilter.$condition_session;
4294
                // check if work ok. TODO:
4295
                Database::query($sql);
4296
4297
                echo '<hr noshade size="1">';
4298
                while ($row = Database::fetch_array($result)) {
4299
                    $userinfo = api_get_user_info($row['userc_id']);
4300
                    if (($userinfo['status']) == "5") {
4301
                        $author_status = get_lang('Student');
4302
                    } else {
4303
                        $author_status = get_lang('Teacher');
4304
                    }
4305
4306
                    $name = $userinfo['complete_name'];
4307
                    $author_photo = '<img src="'.$userinfo['avatar'].'" alt="'.api_htmlentities($name).'"  width="40" height="50" align="top"  title="'.api_htmlentities($name).'"  />';
4308
4309
                    // stars
4310
                    $p_score = $row['p_score'];
4311
                    switch ($p_score) {
4312
                        case 0:
4313
                            $imagerating = Display::return_icon(
4314
                                'rating/stars_0.gif'
4315
                            );
4316
                            break;
4317
                        case 1:
4318
                            $imagerating = Display::return_icon(
4319
                                'rating/stars_5.gif'
4320
                            );
4321
                            break;
4322
                        case 2:
4323
                            $imagerating = Display::return_icon(
4324
                                'rating/stars_10.gif'
4325
                            );
4326
                            break;
4327
                        case 3:
4328
                            $imagerating = Display::return_icon(
4329
                                'rating/stars_15.gif'
4330
                            );
4331
                            break;
4332
                        case 4:
4333
                            $imagerating = Display::return_icon(
4334
                                'rating/stars_20.gif'
4335
                            );
4336
                            break;
4337
                        case 5:
4338
                            $imagerating = Display::return_icon(
4339
                                'rating/stars_25.gif'
4340
                            );
4341
                            break;
4342
                        case 6:
4343
                            $imagerating = Display::return_icon(
4344
                                'rating/stars_30.gif'
4345
                            );
4346
                            break;
4347
                        case 7:
4348
                            $imagerating = Display::return_icon(
4349
                                'rating/stars_35.gif'
4350
                            );
4351
                            break;
4352
                        case 8:
4353
                            $imagerating = Display::return_icon(
4354
                                'rating/stars_40.gif'
4355
                            );
4356
                            break;
4357
                        case 9:
4358
                            $imagerating = Display::return_icon(
4359
                                'rating/stars_45.gif'
4360
                            );
4361
                            break;
4362
                        case 10:
4363
                            $imagerating = Display::return_icon(
4364
                                'rating/stars_50.gif'
4365
                            );
4366
                            break;
4367
                    }
4368
                    echo '<p><table>';
4369
                    echo '<tr>';
4370
                    echo '<td rowspan="2">'.$author_photo.'</td>';
4371
                    $userProfile = '';
4372
                    if ($userinfo !== false) {
4373
                        $userProfile = UserManager::getUserProfileLink(
4374
                            $userinfo
4375
                        );
4376
                    }
4377
                    echo '<td style=" color:#999999">'.$userProfile.' ('.$author_status.') '.
4378
                        api_get_local_time(
4379
                            $row['dtime']
4380
                        ).
4381
                        ' - '.get_lang(
4382
                            'Rating'
4383
                        ).': '.$row['p_score'].' '.$imagerating.' </td>';
4384
                    echo '</tr>';
4385
                    echo '<tr>';
4386
                    echo '<td>'.api_htmlentities($row['comment']).'</td>';
4387
                    echo '</tr>';
4388
                    echo "</table>";
4389
                }
4390
            } else {
4391
                Display::addFlash(
4392
                    Display::return_message(
4393
                        get_lang('LockByTeacher'),
4394
                        'warning',
4395
                        false
4396
                    )
4397
                );
4398
            }
4399
        } else {
4400
            Display::addFlash(
4401
                Display::return_message(
4402
                    get_lang('DiscussNotAvailable'),
4403
                    'normal',
4404
                    false
4405
                )
4406
            );
4407
        }
4408
    }
4409
4410
    /**
4411
     * Show all pages.
4412
     */
4413
    public function allPages($action)
4414
    {
4415
        $_course = $this->courseInfo;
4416
4417
        echo '<div class="actions">'.get_lang('AllPages');
4418
4419
        // menu delete all wiki
4420
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4421
            echo ' <a href="index.php?action=deletewiki&'.api_get_cidreq().'">'.
4422
                Display::return_icon(
4423
                    'delete.png',
4424
                    get_lang('DeleteWiki'),
4425
                    '',
4426
                    ICON_SIZE_MEDIUM
4427
                ).'</a>';
4428
        }
4429
        echo '</div>';
4430
4431
        //show table
4432
        $table = new SortableTable(
4433
            'AllPages_table',
4434
            function () {
4435
                $result = $this->gelAllPagesQuery(true);
4436
4437
                return (int) Database::fetch_assoc($result)['nbr'];
4438
            },
4439
            function ($from, $numberOfItems, $column, $direction) {
4440
                $result = $this->gelAllPagesQuery(false, $from, $numberOfItems, $column, $direction);
4441
                $rows = [];
4442
4443
                while ($data = Database::fetch_assoc($result)) {
4444
                    $rows[] = [
4445
                        $data['col0'],
4446
                        [$data['col1'], $data['reflink'], $data['iid']],
4447
                        [$data['col2'], $data['user_ip']],
4448
                        $data['col3'],
4449
                        $data['reflink'],
4450
                    ];
4451
                }
4452
4453
                return $rows;
4454
            }
4455
        );
4456
        $table->set_additional_parameters(
4457
            [
4458
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
4459
                'action' => Security::remove_XSS($action),
4460
                'group_id' => Security::remove_XSS($_GET['group_id']),
4461
            ]
4462
        );
4463
        $table->set_header(
4464
            0,
4465
            get_lang('Type'),
4466
            true,
4467
            ['style' => 'width:30px;']
4468
        );
4469
        $table->set_header(1, get_lang('Title'));
4470
        $table->set_header(
4471
            2,
4472
            get_lang('Author').' <small>'.get_lang('LastVersion').'</small>'
4473
        );
4474
        $table->set_header(
4475
            3,
4476
            get_lang('Date').' <small>'.get_lang('LastVersion').'</small>'
4477
        );
4478
        if (api_is_allowed_to_session_edit(false, true)) {
4479
            $table->set_header(
4480
                4,
4481
                get_lang('Actions'),
4482
                false,
4483
                ['style' => 'width: 145px;']
4484
            );
4485
        }
4486
        $table->set_column_filter(
4487
            0,
4488
            function ($value, string $urlParams, array $row) {
4489
                $return = '';
4490
                //get type assignment icon
4491
                if (1 == $value) {
4492
                    $return .= Display::return_icon(
4493
                        'wiki_assignment.png',
4494
                        get_lang('AssignmentDesc'),
4495
                        '',
4496
                        ICON_SIZE_SMALL
4497
                    );
4498
                } elseif (2 == $value) {
4499
                    $return .= Display::return_icon(
4500
                        'wiki_work.png',
4501
                        get_lang('AssignmentWork'),
4502
                        '',
4503
                        ICON_SIZE_SMALL
4504
                    );
4505
                } elseif (0 == $value) {
4506
                    $return .= Display::return_icon(
4507
                        'px_transparent.gif'
4508
                    );
4509
                }
4510
4511
                //get icon task
4512
                if (!empty($row['task'])) {
4513
                    $return .= Display::return_icon(
4514
                        'wiki_task.png',
4515
                        get_lang('StandardTask'),
4516
                        '',
4517
                        ICON_SIZE_SMALL
4518
                    );
4519
                } else {
4520
                    $return .= Display::return_icon('px_transparent.gif');
4521
                }
4522
4523
                return $return;
4524
            }
4525
        );
4526
        $table->set_column_filter(
4527
            1,
4528
            function ($value) use ($_course) {
4529
                list($title, $refLink, $iid) = $value;
4530
4531
                return '<a href="'.api_get_self().'?cidReq='.$_course['code']
4532
                    .'&action=showpage&title='.api_htmlentities(urlencode($refLink))
4533
                    .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4534
                    .'&group_id='.api_htmlentities($_GET['group_id']).'">
4535
                    '.api_htmlentities($title).'</a>'
4536
                    .$this->returnCategoriesBlock($iid, '<div><small>', '</small></div>');
4537
            }
4538
        );
4539
        $table->set_column_filter(
4540
            2,
4541
            function ($value) {
4542
                list($userId, $userIp) = $value;
4543
                //get author
4544
                $userinfo = api_get_user_info($userId);
4545
4546
                if ($userinfo !== false) {
4547
                    return UserManager::getUserProfileLink($userinfo);
4548
                }
4549
4550
                return get_lang('Anonymous').' ('.api_htmlentities($userIp).')';
4551
            }
4552
        );
4553
        $table->set_column_filter(
4554
            3,
4555
            function ($value) {
4556
                return api_get_local_time($value);
4557
            }
4558
        );
4559
        $table->set_column_filter(
4560
            4,
4561
            function ($value) use ($_course) {
4562
                $actions = '';
4563
4564
                if (api_is_allowed_to_session_edit(false, true)) {
4565
                    $actions = '<a href="'.api_get_self(
4566
                        ).'?cidReq='.$_course['code']
4567
                        .'&action=edit&title='.api_htmlentities(urlencode($value))
4568
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4569
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4570
                        .Display::return_icon('edit.png', get_lang('EditPage'))
4571
                        .'</a> <a href="'.api_get_self().'?cidReq='.$_course['code']
4572
                        .'&action=discuss&title='.api_htmlentities(urlencode($value))
4573
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4574
                        .Display::return_icon('discuss.png', get_lang('Discuss'))
4575
                        .'</a> <a href="'.api_get_self().'?cidReq='.$_course['code']
4576
                        .'&action=history&title='.api_htmlentities(urlencode($value))
4577
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4578
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4579
                        .Display::return_icon('history.png', get_lang('History'))
4580
                        .'</a> <a href="'.api_get_self().'?cidReq='.$_course['code']
4581
                        .'&action=links&title='.api_htmlentities(urlencode($value))
4582
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '').'&group_id='
4583
                        .api_htmlentities($_GET['group_id']).'">'.
4584
                        Display::return_icon('what_link_here.png', get_lang('LinksPages')).'</a>';
4585
                }
4586
4587
                if (api_is_allowed_to_edit(
4588
                        false,
4589
                        true
4590
                    ) || api_is_platform_admin()) {
4591
                    $actions .= ' <a href="'.api_get_self().'?cidReq='.$_course['code']
4592
                        .'&action=delete&title='.api_htmlentities(urlencode($value))
4593
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4594
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4595
                        .Display::return_icon('delete.png', get_lang('Delete')).'</a>';
4596
                }
4597
4598
                return $actions;
4599
            }
4600
        );
4601
        $table->display();
4602
    }
4603
4604
    /**
4605
     * Get recent changes.
4606
     *
4607
     * @param string $page
4608
     * @param string $action
4609
     */
4610
    public function recentChanges($page, $action)
4611
    {
4612
        $tbl_wiki = $this->tbl_wiki;
4613
        $course_id = $this->course_id;
4614
        $condition_session = $this->condition_session;
4615
        $groupfilter = $this->groupfilter;
4616
        $tbl_wiki_conf = $this->tbl_wiki_conf;
4617
4618
        if (api_is_allowed_to_session_edit(false, true)) {
4619
            if (self::check_notify_all() == 1) {
4620
                $notify_all = Display::return_icon(
4621
                        'messagebox_info.png',
4622
                        get_lang('NotifyByEmail'),
4623
                        '',
4624
                        ICON_SIZE_SMALL
4625
                    ).' '.get_lang('NotNotifyChanges');
4626
                $lock_unlock_notify_all = 'unlocknotifyall';
4627
            } else {
4628
                $notify_all = Display::return_icon(
4629
                        'mail.png',
4630
                        get_lang('CancelNotifyByEmail'),
4631
                        '',
4632
                        ICON_SIZE_SMALL
4633
                    ).' '.get_lang('NotifyChanges');
4634
                $lock_unlock_notify_all = 'locknotifyall';
4635
            }
4636
        }
4637
4638
        echo '<div class="actions"><span style="float: right;">';
4639
        echo '<a href="index.php?action=recentchanges&actionpage='.$lock_unlock_notify_all.'&'.api_get_cidreq().'&title='.api_htmlentities(
4640
                urlencode($page)
4641
            ).'">'.$notify_all.'</a>';
4642
        echo '</span>'.get_lang('RecentChanges').'</div>';
4643
4644
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4645
            //only by professors if page is hidden
4646
            $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
4647
        		WHERE 	'.$tbl_wiki_conf.'.c_id= '.$course_id.' AND
4648
        				'.$tbl_wiki.'.c_id= '.$course_id.' AND
4649
        				'.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
4650
        				'.$tbl_wiki.'.'.$groupfilter.$condition_session.'
4651
        		ORDER BY dtime DESC'; // new version
4652
        } else {
4653
            $sql = 'SELECT *
4654
                FROM '.$tbl_wiki.'
4655
                WHERE
4656
                    c_id = '.$course_id.' AND
4657
                    '.$groupfilter.$condition_session.' AND
4658
                    visibility=1
4659
                ORDER BY dtime DESC';
4660
            // old version TODO: Replace by the bottom line
4661
        }
4662
4663
        $allpages = Database::query($sql);
4664
4665
        //show table
4666
        if (Database::num_rows($allpages) > 0) {
4667
            $rows = [];
4668
            while ($obj = Database::fetch_object($allpages)) {
4669
                //get author
4670
                $userinfo = api_get_user_info($obj->user_id);
4671
4672
                //get type assignment icon
4673
                if ($obj->assignment == 1) {
4674
                    $ShowAssignment = Display::return_icon(
4675
                        'wiki_assignment.png',
4676
                        get_lang('AssignmentDesc'),
4677
                        '',
4678
                        ICON_SIZE_SMALL
4679
                    );
4680
                } elseif ($obj->assignment == 2) {
4681
                    $ShowAssignment = Display::return_icon(
4682
                        'wiki_work.png',
4683
                        get_lang('AssignmentWork'),
4684
                        '',
4685
                        ICON_SIZE_SMALL
4686
                    );
4687
                } elseif ($obj->assignment == 0) {
4688
                    $ShowAssignment = Display::return_icon(
4689
                        'px_transparent.gif'
4690
                    );
4691
                }
4692
4693
                // Get icon task
4694
                if (!empty($obj->task)) {
4695
                    $icon_task = Display::return_icon(
4696
                        'wiki_task.png',
4697
                        get_lang('StandardTask'),
4698
                        '',
4699
                        ICON_SIZE_SMALL
4700
                    );
4701
                } else {
4702
                    $icon_task = Display::return_icon('px_transparent.gif');
4703
                }
4704
4705
                $row = [];
4706
                $row[] = api_get_local_time(
4707
                    $obj->dtime
4708
                );
4709
                $row[] = $ShowAssignment.$icon_task;
4710
                $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
4711
                    ).'&action=showpage&title='.api_htmlentities(
4712
                        urlencode($obj->reflink)
4713
                    ).'&view='.$obj->id.'&session_id='.api_get_session_id(
4714
                    ).'&group_id='.api_get_group_id().'">'.
4715
                    api_htmlentities($obj->title).'</a>';
4716
                $row[] = $obj->version > 1 ? get_lang('EditedBy') : get_lang(
4717
                    'AddedBy'
4718
                );
4719
                if ($userinfo !== false) {
4720
                    $row[] = UserManager::getUserProfileLink($userinfo);
4721
                } else {
4722
                    $row[] = get_lang('Anonymous').' ('.api_htmlentities(
4723
                            $obj->user_ip
4724
                        ).')';
4725
                }
4726
                $rows[] = $row;
4727
            }
4728
4729
            $table = new SortableTableFromArrayConfig(
4730
                $rows,
4731
                0,
4732
                10,
4733
                'RecentPages_table',
4734
                '',
4735
                '',
4736
                'DESC'
4737
            );
4738
            $table->set_additional_parameters(
4739
                [
4740
                    'cidReq' => api_get_course_id(),
4741
                    'action' => Security::remove_XSS($action),
4742
                    'session_id' => api_get_session_id(),
4743
                    'group_id' => api_get_group_id(),
4744
                ]
4745
            );
4746
            $table->set_header(
4747
                0,
4748
                get_lang('Date'),
4749
                true,
4750
                ['style' => 'width:200px;']
4751
            );
4752
            $table->set_header(
4753
                1,
4754
                get_lang('Type'),
4755
                true,
4756
                ['style' => 'width:30px;']
4757
            );
4758
            $table->set_header(2, get_lang('Title'), true);
4759
            $table->set_header(
4760
                3,
4761
                get_lang('Actions'),
4762
                true,
4763
                ['style' => 'width:80px;']
4764
            );
4765
            $table->set_header(4, get_lang('Author'), true);
4766
            $table->display();
4767
        }
4768
    }
4769
4770
    /**
4771
     * What links here. Show pages that have linked this page.
4772
     *
4773
     * @param string $page
4774
     */
4775
    public function getLinks($page)
4776
    {
4777
        $tbl_wiki = $this->tbl_wiki;
4778
        $course_id = $this->course_id;
4779
        $condition_session = $this->condition_session;
4780
        $groupfilter = $this->groupfilter;
4781
        $_course = $this->courseInfo;
4782
        $action = $this->action;
4783
4784
        if (!$_GET['title']) {
4785
            Display::addFlash(
4786
                Display::return_message(
4787
                    get_lang("MustSelectPage"),
4788
                    'error',
4789
                    false
4790
                )
4791
            );
4792
        } else {
4793
            $sql = 'SELECT * FROM '.$tbl_wiki.'
4794
                    WHERE
4795
                        c_id = '.$course_id.' AND
4796
                        reflink="'.Database::escape_string($page).'" AND
4797
                        '.$groupfilter.$condition_session;
4798
            $result = Database::query($sql);
4799
            $row = Database::fetch_array($result);
4800
4801
            //get type assignment icon
4802
            $ShowAssignment = '';
4803
            if ($row['assignment'] == 1) {
4804
                $ShowAssignment = Display::return_icon(
4805
                    'wiki_assignment.png',
4806
                    get_lang('AssignmentDesc'),
4807
                    '',
4808
                    ICON_SIZE_SMALL
4809
                );
4810
            } elseif ($row['assignment'] == 2) {
4811
                $ShowAssignment = Display::return_icon(
4812
                    'wiki_work.png',
4813
                    get_lang('AssignmentWork'),
4814
                    '',
4815
                    ICON_SIZE_SMALL
4816
                );
4817
            } elseif ($row['assignment'] == 0) {
4818
                $ShowAssignment = Display::return_icon('px_transparent.gif');
4819
            }
4820
4821
            //fix Title to reflink (link Main Page)
4822
            if ($page == get_lang('DefaultTitle')) {
4823
                $page = 'index';
4824
            }
4825
4826
            echo '<div id="wikititle">';
4827
            echo get_lang(
4828
                    'LinksPagesFrom'
4829
                ).': '.$ShowAssignment.' <a href="'.api_get_self(
4830
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4831
                    urlencode($page)
4832
                ).'&session_id='.api_htmlentities(
4833
                    $_GET['session_id']
4834
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4835
                api_htmlentities($row['title']).'</a>';
4836
            echo '</div>';
4837
4838
            //fix index to title Main page into linksto
4839
4840
            if ($page == 'index') {
4841
                $page = str_replace(' ', '_', get_lang('DefaultTitle'));
4842
            }
4843
4844
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4845
                // only by professors if page is hidden
4846
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4847
                        WHERE s1.c_id = $course_id AND linksto LIKE '%".Database::escape_string(
4848
                        $page
4849
                    )."%' AND id=(
4850
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4851
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4852
            } else {
4853
                //add blank space after like '%" " %' to identify each word
4854
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4855
                        WHERE s1.c_id = $course_id AND visibility=1 AND linksto LIKE '%".Database::escape_string(
4856
                        $page
4857
                    )."%' AND id=(
4858
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4859
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4860
            }
4861
4862
            $allpages = Database::query($sql);
4863
4864
            //show table
4865
            if (Database::num_rows($allpages) > 0) {
4866
                $rows = [];
4867
                while ($obj = Database::fetch_object($allpages)) {
4868
                    //get author
4869
                    $userinfo = api_get_user_info($obj->user_id);
4870
4871
                    //get time
4872
                    $year = substr($obj->dtime, 0, 4);
4873
                    $month = substr($obj->dtime, 5, 2);
4874
                    $day = substr($obj->dtime, 8, 2);
4875
                    $hours = substr($obj->dtime, 11, 2);
4876
                    $minutes = substr($obj->dtime, 14, 2);
4877
                    $seconds = substr($obj->dtime, 17, 2);
4878
4879
                    //get type assignment icon
4880
                    if ($obj->assignment == 1) {
4881
                        $ShowAssignment = Display::return_icon(
4882
                            'wiki_assignment.png',
4883
                            get_lang('AssignmentDesc'),
4884
                            '',
4885
                            ICON_SIZE_SMALL
4886
                        );
4887
                    } elseif ($obj->assignment == 2) {
4888
                        $ShowAssignment = Display::return_icon(
4889
                            'wiki_work.png',
4890
                            get_lang('AssignmentWork'),
4891
                            '',
4892
                            ICON_SIZE_SMALL
4893
                        );
4894
                    } elseif ($obj->assignment == 0) {
4895
                        $ShowAssignment = Display::return_icon(
4896
                            'px_transparent.gif'
4897
                        );
4898
                    }
4899
4900
                    $row = [];
4901
                    $row[] = $ShowAssignment;
4902
                    $row[] = '<a href="'.api_get_self(
4903
                        ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4904
                            urlencode($obj->reflink)
4905
                        ).'&session_id='.api_htmlentities(
4906
                            $_GET['session_id']
4907
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4908
                        api_htmlentities($obj->title).'</a>';
4909
                    if ($userinfo !== false) {
4910
                        $row[] = UserManager::getUserProfileLink($userinfo);
4911
                    } else {
4912
                        $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
4913
                    }
4914
                    $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
4915
                    $rows[] = $row;
4916
                }
4917
4918
                $table = new SortableTableFromArrayConfig(
4919
                    $rows,
4920
                    1,
4921
                    10,
4922
                    'AllPages_table',
4923
                    '',
4924
                    '',
4925
                    'ASC'
4926
                );
4927
                $table->set_additional_parameters(
4928
                    [
4929
                        'cidReq' => Security::remove_XSS($_GET['cidReq']),
4930
                        'action' => Security::remove_XSS($action),
4931
                        'group_id' => intval($_GET['group_id']),
4932
                    ]
4933
                );
4934
                $table->set_header(
4935
                    0,
4936
                    get_lang('Type'),
4937
                    true,
4938
                    ['style' => 'width:30px;']
4939
                );
4940
                $table->set_header(1, get_lang('Title'), true);
4941
                $table->set_header(2, get_lang('Author'), true);
4942
                $table->set_header(3, get_lang('Date'), true);
4943
                $table->display();
4944
            }
4945
        }
4946
    }
4947
4948
    /**
4949
     * @param string $action
4950
     */
4951
    public function getSearchPages($action)
4952
    {
4953
        echo '<div class="actions">'.get_lang('SearchPages').'</div>';
4954
        if (isset($_GET['mode_table'])) {
4955
            if (!isset($_GET['SearchPages_table_page_nr'])) {
4956
                $_GET['search_term'] = $_POST['search_term'] ?? '';
4957
                $_GET['search_content'] = $_POST['search_content'] ?? '';
4958
                $_GET['all_vers'] = $_POST['all_vers'] ?? '';
4959
                $_GET['categories'] = $_POST['categories'] ?? [];
4960
                $_GET['match_all_categories'] = isset($_POST['match_all_categories']);
4961
            }
4962
            $this->display_wiki_search_results(
4963
                $_GET['search_term'],
4964
                $_GET['search_content'],
4965
                $_GET['all_vers'],
4966
                $_GET['categories'],
4967
                $_GET['match_all_categories']
4968
            );
4969
        } else {
4970
            // initiate the object
4971
            $form = new FormValidator(
4972
                'wiki_search',
4973
                'post',
4974
                api_get_self().'?cidReq='.api_get_course_id().'&action='.api_htmlentities($action)
4975
                    .'&session_id='.api_get_session_id().'&group_id='.api_get_group_id().'&mode_table=yes1'
4976
            );
4977
4978
            // Setting the form elements
4979
4980
            $form->addText(
4981
                'search_term',
4982
                get_lang('SearchTerm'),
4983
                true,
4984
                ['autofocus' => 'autofocus']
4985
            );
4986
            $form->addCheckBox('search_content', '', get_lang('AlsoSearchContent'));
4987
            $form->addCheckbox('all_vers', '', get_lang('IncludeAllVersions'));
4988
4989
            if (true === api_get_configuration_value('wiki_categories_enabled')) {
4990
                $categories = Database::getManager()
4991
                    ->getRepository(CWikiCategory::class)
4992
                    ->findByCourse(api_get_course_entity(), api_get_session_entity())
4993
                ;
4994
4995
                $form->addSelectFromCollection(
4996
                    'categories',
4997
                    get_lang('Categories'),
4998
                    $categories,
4999
                    ['multiple' => 'multiple'],
5000
                    false,
5001
                    'getNodeName'
5002
                );
5003
                $form->addCheckBox(
5004
                    'match_all_categories',
5005
                    '',
5006
                    get_lang('OnlyThoseThatCorrespondToAllTheSelectedCategories')
5007
                );
5008
            }
5009
5010
            $form->addButtonSearch(get_lang('Search'), 'SubmitWikiSearch');
5011
5012
            // setting the rules
5013
            $form->addRule(
5014
                'search_term',
5015
                get_lang('TooShort'),
5016
                'minlength',
5017
                3
5018
            ); //TODO: before fixing the pagination rules worked, not now
5019
5020
            if ($form->validate()) {
5021
                $form->display();
5022
                $values = $form->exportValues();
5023
                $this->display_wiki_search_results(
5024
                    $values['search_term'],
5025
                    $values['search_content'],
5026
                    $values['all_vers'],
5027
                    $values['categories'] ?? [],
5028
                    isset($values['match_all_categories'])
5029
                );
5030
            } else {
5031
                $form->display();
5032
            }
5033
        }
5034
    }
5035
5036
    /**
5037
     * @param int    $userId
5038
     * @param string $action
5039
     */
5040
    public function getUserContributions($userId, $action)
5041
    {
5042
        $_course = $this->courseInfo;
5043
        $tbl_wiki = $this->tbl_wiki;
5044
        $course_id = $this->course_id;
5045
        $condition_session = $this->condition_session;
5046
        $groupfilter = $this->groupfilter;
5047
        $userId = intval($userId);
5048
        $userinfo = api_get_user_info($userId);
5049
        if ($userinfo !== false) {
5050
            echo '<div class="actions">'.
5051
                get_lang('UserContributions').': '.UserManager::getUserProfileLink($userinfo).
5052
                '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.$userId.
5053
                '&session_id='.$this->session_id.'&group_id='.$this->group_id.'">'.
5054
                '</a></div>';
5055
        }
5056
5057
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5058
            //only by professors if page is hidden
5059
            $sql = 'SELECT * FROM '.$tbl_wiki.'
5060
                    WHERE
5061
                        c_id = '.$course_id.' AND
5062
                        '.$groupfilter.$condition_session.' AND
5063
                        user_id="'.$userId.'"';
5064
        } else {
5065
            $sql = 'SELECT * FROM '.$tbl_wiki.'
5066
                    WHERE
5067
                        c_id = '.$course_id.' AND
5068
                        '.$groupfilter.$condition_session.' AND
5069
                        user_id="'.$userId.'" AND
5070
                        visibility=1';
5071
        }
5072
5073
        $allpages = Database::query($sql);
5074
5075
        //show table
5076
        if (Database::num_rows($allpages) > 0) {
5077
            $rows = [];
5078
            while ($obj = Database::fetch_object($allpages)) {
5079
                //get type assignment icon
5080
                $ShowAssignment = '';
5081
                if ($obj->assignment == 1) {
5082
                    $ShowAssignment = Display::return_icon(
5083
                        'wiki_assignment.png',
5084
                        get_lang('AssignmentDescExtra'),
5085
                        '',
5086
                        ICON_SIZE_SMALL
5087
                    );
5088
                } elseif ($obj->assignment == 2) {
5089
                    $ShowAssignment = Display::return_icon(
5090
                        'wiki_work.png',
5091
                        get_lang('AssignmentWork'),
5092
                        '',
5093
                        ICON_SIZE_SMALL
5094
                    );
5095
                } elseif ($obj->assignment == 0) {
5096
                    $ShowAssignment = Display::return_icon(
5097
                        'px_transparent.gif'
5098
                    );
5099
                }
5100
5101
                $row = [];
5102
                $row[] = api_get_local_time($obj->dtime);
5103
                $row[] = $ShowAssignment;
5104
                $row[] = '<a href="'.api_get_self(
5105
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5106
                        urlencode($obj->reflink)
5107
                    ).'&view='.$obj->id.'&session_id='.api_get_session_id(
5108
                    ).'&group_id='.api_get_group_id().'">'.
5109
                    api_htmlentities($obj->title).'</a>';
5110
                $row[] = Security::remove_XSS($obj->version);
5111
                $row[] = Security::remove_XSS($obj->comment);
5112
                $row[] = Security::remove_XSS($obj->progress).' %';
5113
                $row[] = Security::remove_XSS($obj->score);
5114
                $rows[] = $row;
5115
            }
5116
5117
            $table = new SortableTableFromArrayConfig(
5118
                $rows,
5119
                2,
5120
                10,
5121
                'UsersContributions_table',
5122
                '',
5123
                '',
5124
                'ASC'
5125
            );
5126
            $table->set_additional_parameters(
5127
                [
5128
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5129
                    'action' => Security::remove_XSS($action),
5130
                    'user_id' => intval($userId),
5131
                    'session_id' => intval($_GET['session_id']),
5132
                    'group_id' => intval($_GET['group_id']),
5133
                ]
5134
            );
5135
            $table->set_header(
5136
                0,
5137
                get_lang('Date'),
5138
                true,
5139
                ['style' => 'width:200px;']
5140
            );
5141
            $table->set_header(
5142
                1,
5143
                get_lang('Type'),
5144
                true,
5145
                ['style' => 'width:30px;']
5146
            );
5147
            $table->set_header(
5148
                2,
5149
                get_lang('Title'),
5150
                true,
5151
                ['style' => 'width:200px;']
5152
            );
5153
            $table->set_header(
5154
                3,
5155
                get_lang('Version'),
5156
                true,
5157
                ['style' => 'width:30px;']
5158
            );
5159
            $table->set_header(
5160
                4,
5161
                get_lang('Comment'),
5162
                true,
5163
                ['style' => 'width:200px;']
5164
            );
5165
            $table->set_header(
5166
                5,
5167
                get_lang('Progress'),
5168
                true,
5169
                ['style' => 'width:30px;']
5170
            );
5171
            $table->set_header(
5172
                6,
5173
                get_lang('Rating'),
5174
                true,
5175
                ['style' => 'width:30px;']
5176
            );
5177
            $table->display();
5178
        }
5179
    }
5180
5181
    /**
5182
     * @param string $action
5183
     */
5184
    public function getMostChangedPages($action)
5185
    {
5186
        $_course = $this->courseInfo;
5187
        $tbl_wiki = $this->tbl_wiki;
5188
        $course_id = $this->course_id;
5189
        $condition_session = $this->condition_session;
5190
        $groupfilter = $this->groupfilter;
5191
5192
        echo '<div class="actions">'.get_lang('MostChangedPages').'</div>';
5193
5194
        if (api_is_allowed_to_edit(false, true) ||
5195
            api_is_platform_admin()
5196
        ) { //only by professors if page is hidden
5197
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
5198
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5199
                    GROUP BY reflink'; //TODO:check MAX and group by return last version
5200
        } else {
5201
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
5202
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND visibility=1
5203
                    GROUP BY reflink'; //TODO:check MAX and group by return last version
5204
        }
5205
5206
        $allpages = Database::query($sql);
5207
5208
        //show table
5209
        if (Database::num_rows($allpages) > 0) {
5210
            $rows = [];
5211
            while ($obj = Database::fetch_object($allpages)) {
5212
                //get type assignment icon
5213
                $ShowAssignment = '';
5214
                if ($obj->assignment == 1) {
5215
                    $ShowAssignment = Display::return_icon(
5216
                        'wiki_assignment.png',
5217
                        get_lang('AssignmentDesc'),
5218
                        '',
5219
                        ICON_SIZE_SMALL
5220
                    );
5221
                } elseif ($obj->assignment == 2) {
5222
                    $ShowAssignment = Display::return_icon(
5223
                        'wiki_work.png',
5224
                        get_lang('AssignmentWork'),
5225
                        '',
5226
                        ICON_SIZE_SMALL
5227
                    );
5228
                } elseif ($obj->assignment == 0) {
5229
                    $ShowAssignment = Display::return_icon(
5230
                        'px_transparent.gif'
5231
                    );
5232
                }
5233
5234
                $row = [];
5235
                $row[] = $ShowAssignment;
5236
                $row[] = '<a href="'.api_get_self(
5237
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5238
                        urlencode($obj->reflink)
5239
                    ).'&session_id='.api_htmlentities(
5240
                        $_GET['session_id']
5241
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5242
                    api_htmlentities($obj->title).'</a>';
5243
                $row[] = $obj->MAX;
5244
                $rows[] = $row;
5245
            }
5246
5247
            $table = new SortableTableFromArrayConfig(
5248
                $rows,
5249
                2,
5250
                10,
5251
                'MostChangedPages_table',
5252
                '',
5253
                '',
5254
                'DESC'
5255
            );
5256
            $table->set_additional_parameters(
5257
                [
5258
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5259
                    'action' => Security::remove_XSS($action),
5260
                    'session_id' => intval($_GET['session_id']),
5261
                    'group_id' => intval($_GET['group_id']),
5262
                ]
5263
            );
5264
            $table->set_header(
5265
                0,
5266
                get_lang('Type'),
5267
                true,
5268
                ['style' => 'width:30px;']
5269
            );
5270
            $table->set_header(1, get_lang('Title'), true);
5271
            $table->set_header(2, get_lang('Changes'), true);
5272
            $table->display();
5273
        }
5274
    }
5275
5276
    /**
5277
     * Restore page.
5278
     *
5279
     * @return bool
5280
     */
5281
    public function restorePage()
5282
    {
5283
        $userId = api_get_user_id();
5284
        $_course = $this->courseInfo;
5285
        $current_row = $this->getWikiData();
5286
        $last_row = $this->getLastWikiData($this->page);
5287
5288
        if (empty($last_row)) {
5289
            return false;
5290
        }
5291
5292
        $PassEdit = false;
5293
5294
        /* Only teachers and platform admin can edit the index page.
5295
        Only teachers and platform admin can edit an assignment teacher*/
5296
        if (($current_row['reflink'] == 'index' ||
5297
                $current_row['reflink'] == '' ||
5298
                $current_row['assignment'] == 1) &&
5299
            (!api_is_allowed_to_edit(false, true) &&
5300
                $this->group_id == 0)
5301
        ) {
5302
            Display::addFlash(
5303
                Display::return_message(
5304
                    get_lang('OnlyEditPagesCourseManager'),
5305
                    'normal',
5306
                    false
5307
                )
5308
            );
5309
        } else {
5310
            // check if is a wiki group
5311
            if ($current_row['group_id'] != 0) {
5312
                $groupInfo = GroupManager::get_group_properties(
5313
                    $this->group_id
5314
                );
5315
                //Only teacher, platform admin and group members can edit a wiki group
5316
                if (api_is_allowed_to_edit(false, true) ||
5317
                    api_is_platform_admin() ||
5318
                    GroupManager::is_user_in_group($userId, $groupInfo) ||
5319
                    api_is_allowed_in_course()
5320
                ) {
5321
                    $PassEdit = true;
5322
                } else {
5323
                    Display::addFlash(
5324
                        Display::return_message(
5325
                            get_lang('OnlyEditPagesGroupMembers'),
5326
                            'normal',
5327
                            false
5328
                        )
5329
                    );
5330
                }
5331
            } else {
5332
                $PassEdit = true;
5333
            }
5334
5335
            // check if is an assignment
5336
            //$icon_assignment = null;
5337
            if ($current_row['assignment'] == 1) {
5338
                Display::addFlash(
5339
                    Display::return_message(
5340
                        get_lang('EditAssignmentWarning'),
5341
                        'normal',
5342
                        false
5343
                    )
5344
                );
5345
            } elseif ($current_row['assignment'] == 2) {
5346
                if (($userId == $current_row['user_id']) == false) {
5347
                    if (api_is_allowed_to_edit(
5348
                            false,
5349
                            true
5350
                        ) || api_is_platform_admin()) {
5351
                        $PassEdit = true;
5352
                    } else {
5353
                        Display::addFlash(
5354
                            Display::return_message(
5355
                                get_lang('LockByTeacher'),
5356
                                'normal',
5357
                                false
5358
                            )
5359
                        );
5360
                        $PassEdit = false;
5361
                    }
5362
                } else {
5363
                    $PassEdit = true;
5364
                }
5365
            }
5366
5367
            //show editor if edit is allowed
5368
            if ($PassEdit) {
5369
                if ($current_row['editlock'] == 1 &&
5370
                    (api_is_allowed_to_edit(false, true) == false ||
5371
                        api_is_platform_admin() == false)
5372
                ) {
5373
                    Display::addFlash(
5374
                        Display::return_message(
5375
                            get_lang('PageLockedExtra'),
5376
                            'normal',
5377
                            false
5378
                        )
5379
                    );
5380
                } else {
5381
                    if ($last_row['is_editing'] != 0 && $last_row['is_editing'] != $userId) {
5382
                        // Checking for concurrent users
5383
                        $timestamp_edit = strtotime($last_row['time_edit']);
5384
                        $time_editing = time() - $timestamp_edit;
5385
                        $max_edit_time = 1200; // 20 minutes
5386
                        $rest_time = $max_edit_time - $time_editing;
5387
                        $userinfo = api_get_user_info($last_row['is_editing']);
5388
                        $is_being_edited = get_lang(
5389
                                'ThisPageisBeginEditedBy'
5390
                            ).' <a href='.$userinfo['profile_url'].'>'.
5391
                            Display::tag(
5392
                                'span',
5393
                                $userinfo['complete_name_with_username']
5394
                            ).
5395
                            get_lang('ThisPageisBeginEditedTryLater').' '.date(
5396
                                "i",
5397
                                $rest_time
5398
                            ).' '.get_lang('MinMinutes');
5399
                        Display::addFlash(
5400
                            Display::return_message(
5401
                                $is_being_edited,
5402
                                'normal',
5403
                                false
5404
                            )
5405
                        );
5406
                    } else {
5407
                        Display::addFlash(
5408
                            Display::return_message(
5409
                                self::restore_wikipage(
5410
                                    $current_row['page_id'],
5411
                                    $current_row['reflink'],
5412
                                    $current_row['title'],
5413
                                    $current_row['content'],
5414
                                    $current_row['group_id'],
5415
                                    $current_row['assignment'],
5416
                                    $current_row['progress'],
5417
                                    $current_row['version'],
5418
                                    $last_row['version'],
5419
                                    $current_row['linksto']
5420
                                ).': <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5421
                                    urlencode($last_row['reflink'])
5422
                                ).'&session_id='.$last_row['session_id'].'&group_id='.$last_row['group_id'].'">'.
5423
                                api_htmlentities($last_row['title']).'</a>',
5424
                                'confirmation',
5425
                                false
5426
                            )
5427
                        );
5428
                    }
5429
                }
5430
            }
5431
        }
5432
    }
5433
5434
    /**
5435
     * @param int|bool $wikiId
5436
     */
5437
    public function setWikiData($wikiId)
5438
    {
5439
        $this->wikiData = self::getWikiDataFromDb($wikiId);
5440
    }
5441
5442
    /**
5443
     * @return array
5444
     */
5445
    public function getWikiData()
5446
    {
5447
        return $this->wikiData;
5448
    }
5449
5450
    /**
5451
     * Check last version.
5452
     *
5453
     * @param int $view
5454
     *
5455
     * @return bool
5456
     */
5457
    public function checkLastVersion($view)
5458
    {
5459
        $tbl_wiki = $this->tbl_wiki;
5460
        $course_id = $this->course_id;
5461
        $condition_session = $this->condition_session;
5462
        $groupfilter = $this->groupfilter;
5463
        $page = $this->page;
5464
        $_course = $this->courseInfo;
5465
5466
        if (empty($view)) {
5467
            return false;
5468
        }
5469
5470
        $current_row = $this->getWikiData();
5471
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5472
                WHERE
5473
                    c_id = '.$course_id.' AND
5474
                    reflink = "'.Database::escape_string($page).'" AND
5475
                    '.$groupfilter.$condition_session.'
5476
                ORDER BY id DESC'; //last version
5477
        $result = Database::query($sql);
5478
        $last_row = Database::fetch_array($result);
5479
5480
        if ($view < $last_row['id']) {
5481
            $message = '<center>'.get_lang('NoAreSeeingTheLastVersion').'<br />
5482
            '.get_lang("Version").' (
5483
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5484
                    urlencode($current_row['reflink'])
5485
                ).'&group_id='.$current_row['group_id'].'&session_id='.$current_row['session_id'].'&view='.api_htmlentities(
5486
                    $_GET['view']
5487
                ).'" title="'.get_lang('CurrentVersion').'">
5488
            '.$current_row['version'].'
5489
            </a> /
5490
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5491
                    urlencode($last_row['reflink'])
5492
                ).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'" title="'.get_lang(
5493
                    'LastVersion'
5494
                ).'">
5495
            '.$last_row['version'].'
5496
            </a>) <br />'.get_lang("ConvertToLastVersion").':
5497
            <a href="index.php?cidReq='.$_course['id'].'&action=restorepage&title='.api_htmlentities(
5498
                    urlencode($last_row['reflink'])
5499
                ).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'&view='.api_htmlentities(
5500
                    $_GET['view']
5501
                ).'">'.
5502
                get_lang("Restore").'</a></center>';
5503
            Display::addFlash(
5504
                Display::return_message($message, 'warning', false)
5505
            );
5506
        }
5507
    }
5508
5509
    /**
5510
     *  Get most linked pages.
5511
     */
5512
    public function getMostLinked()
5513
    {
5514
        $tbl_wiki = $this->tbl_wiki;
5515
        $course_id = $this->course_id;
5516
        $groupfilter = $this->groupfilter;
5517
        $condition_session = $this->condition_session;
5518
        $_course = $this->courseInfo;
5519
5520
        echo '<div class="actions">'.get_lang('MostLinkedPages').'</div>';
5521
        $pages = [];
5522
        $linked = [];
5523
5524
        // Get name pages
5525
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5526
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5527
                GROUP BY reflink
5528
                ORDER BY reflink ASC';
5529
        $allpages = Database::query($sql);
5530
        while ($row = Database::fetch_array($allpages)) {
5531
            if ($row['reflink'] == 'index') {
5532
                $row['reflink'] = str_replace(
5533
                    ' ',
5534
                    '_',
5535
                    get_lang('DefaultTitle')
5536
                );
5537
            }
5538
            $pages[] = $row['reflink'];
5539
        }
5540
5541
        // Get name refs in last pages
5542
        $sql = 'SELECT *
5543
                FROM '.$tbl_wiki.' s1
5544
                WHERE s1.c_id = '.$course_id.' AND id=(
5545
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5546
                    WHERE
5547
                        s2.c_id = '.$course_id.' AND
5548
                        s1.reflink = s2.reflink AND
5549
                        '.$groupfilter.$condition_session.'
5550
                )';
5551
5552
        $allpages = Database::query($sql);
5553
5554
        while ($row = Database::fetch_array($allpages)) {
5555
            //remove self reference
5556
            $row['linksto'] = str_replace(
5557
                $row["reflink"],
5558
                " ",
5559
                trim($row["linksto"])
5560
            );
5561
            $refs = explode(" ", trim($row["linksto"]));
5562
5563
            // Find linksto into reflink. If found ->page is linked
5564
            foreach ($refs as $v) {
5565
                if (in_array($v, $pages)) {
5566
                    if (trim($v) != "") {
5567
                        $linked[] = $v;
5568
                    }
5569
                }
5570
            }
5571
        }
5572
5573
        $linked = array_unique($linked);
5574
        //make a unique list. TODO:delete this line and count how many for each page
5575
        //show table
5576
        $rows = [];
5577
        foreach ($linked as $linked_show) {
5578
            $row = [];
5579
            $row[] = '<a href="'.api_get_self(
5580
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5581
                    urlencode(str_replace('_', ' ', $linked_show))
5582
                ).'&session_id='.api_htmlentities(
5583
                    $_GET['session_id']
5584
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5585
                str_replace('_', ' ', $linked_show).'</a>';
5586
            $rows[] = $row;
5587
        }
5588
5589
        $table = new SortableTableFromArrayConfig(
5590
            $rows,
5591
            0,
5592
            10,
5593
            'LinkedPages_table',
5594
            '',
5595
            '',
5596
            'DESC'
5597
        );
5598
        $table->set_additional_parameters(
5599
            [
5600
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5601
                'action' => Security::remove_XSS($this->action),
5602
                'session_id' => intval($_GET['session_id']),
5603
                'group_id' => intval($_GET['group_id']),
5604
            ]
5605
        );
5606
        $table->set_header(0, get_lang('Title'), true);
5607
        $table->display();
5608
    }
5609
5610
    /**
5611
     * Get orphan pages.
5612
     */
5613
    public function getOrphaned()
5614
    {
5615
        $tbl_wiki = $this->tbl_wiki;
5616
        $course_id = $this->course_id;
5617
        $groupfilter = $this->groupfilter;
5618
        $condition_session = $this->condition_session;
5619
        $_course = $this->courseInfo;
5620
5621
        echo '<div class="actions">'.get_lang('OrphanedPages').'</div>';
5622
5623
        $pages = [];
5624
        $orphaned = [];
5625
5626
        //get name pages
5627
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5628
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5629
                GROUP BY reflink
5630
                ORDER BY reflink ASC';
5631
        $allpages = Database::query($sql);
5632
        while ($row = Database::fetch_array($allpages)) {
5633
            $pages[] = $row['reflink'];
5634
        }
5635
5636
        //get name refs in last pages and make a unique list
5637
        $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1
5638
                WHERE s1.c_id = '.$course_id.' AND id=(
5639
                SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5640
                WHERE
5641
                    s2.c_id = '.$course_id.' AND
5642
                    s1.reflink = s2.reflink AND
5643
                    '.$groupfilter.$condition_session.'
5644
                )';
5645
        $allpages = Database::query($sql);
5646
        $array_refs_linked = [];
5647
        while ($row = Database::fetch_array($allpages)) {
5648
            $row['linksto'] = str_replace(
5649
                $row["reflink"],
5650
                " ",
5651
                trim($row["linksto"])
5652
            ); //remove self reference
5653
            $refs = explode(" ", trim($row["linksto"]));
5654
            foreach ($refs as $ref_linked) {
5655
                if ($ref_linked == str_replace(
5656
                        ' ',
5657
                        '_',
5658
                        get_lang('DefaultTitle')
5659
                    )) {
5660
                    $ref_linked = 'index';
5661
                }
5662
                $array_refs_linked[] = $ref_linked;
5663
            }
5664
        }
5665
5666
        $array_refs_linked = array_unique($array_refs_linked);
5667
5668
        //search each name of list linksto into list reflink
5669
        foreach ($pages as $v) {
5670
            if (!in_array($v, $array_refs_linked)) {
5671
                $orphaned[] = $v;
5672
            }
5673
        }
5674
        $rows = [];
5675
        foreach ($orphaned as $orphaned_show) {
5676
            // get visibility status and title
5677
            $sql = 'SELECT *
5678
                    FROM  '.$tbl_wiki.'
5679
		            WHERE
5680
		                c_id = '.$course_id.' AND
5681
		                '.$groupfilter.$condition_session.' AND
5682
		                reflink="'.Database::escape_string($orphaned_show).'"
5683
                    GROUP BY reflink';
5684
            $allpages = Database::query($sql);
5685
            while ($row = Database::fetch_array($allpages)) {
5686
                $orphaned_title = $row['title'];
5687
                $orphaned_visibility = $row['visibility'];
5688
                if ($row['assignment'] == 1) {
5689
                    $ShowAssignment = Display::return_icon(
5690
                        'wiki_assignment.png',
5691
                        '',
5692
                        '',
5693
                        ICON_SIZE_SMALL
5694
                    );
5695
                } elseif ($row['assignment'] == 2) {
5696
                    $ShowAssignment = Display::return_icon(
5697
                        'wiki_work.png',
5698
                        '',
5699
                        '',
5700
                        ICON_SIZE_SMALL
5701
                    );
5702
                } elseif ($row['assignment'] == 0) {
5703
                    $ShowAssignment = Display::return_icon(
5704
                        'px_transparent.gif'
5705
                    );
5706
                }
5707
            }
5708
5709
            if (!api_is_allowed_to_edit(false, true) || !api_is_platform_admin(
5710
                ) && $orphaned_visibility == 0) {
5711
                continue;
5712
            }
5713
5714
            //show table
5715
            $row = [];
5716
            $row[] = $ShowAssignment;
5717
            $row[] = '<a href="'.api_get_self(
5718
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5719
                    urlencode($orphaned_show)
5720
                ).'&session_id='.api_htmlentities(
5721
                    $_GET['session_id']
5722
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5723
                api_htmlentities($orphaned_title).'</a>';
5724
            $rows[] = $row;
5725
        }
5726
5727
        $table = new SortableTableFromArrayConfig(
5728
            $rows,
5729
            1,
5730
            10,
5731
            'OrphanedPages_table',
5732
            '',
5733
            '',
5734
            'DESC'
5735
        );
5736
        $table->set_additional_parameters(
5737
            [
5738
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5739
                'action' => Security::remove_XSS($this->action),
5740
                'session_id' => intval($_GET['session_id']),
5741
                'group_id' => intval($_GET['group_id']),
5742
            ]
5743
        );
5744
        $table->set_header(
5745
            0,
5746
            get_lang('Type'),
5747
            true,
5748
            ['style' => 'width:30px;']
5749
        );
5750
        $table->set_header(1, get_lang('Title'), true);
5751
        $table->display();
5752
    }
5753
5754
    /**
5755
     * Get wanted pages.
5756
     */
5757
    public function getWantedPages()
5758
    {
5759
        $tbl_wiki = $this->tbl_wiki;
5760
        $course_id = $this->course_id;
5761
        $groupfilter = $this->groupfilter;
5762
        $condition_session = $this->condition_session;
5763
5764
        echo '<div class="actions">'.get_lang('WantedPages').'</div>';
5765
        $pages = [];
5766
        $wanted = [];
5767
        //get name pages
5768
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5769
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5770
                GROUP BY reflink
5771
                ORDER BY reflink ASC';
5772
        $allpages = Database::query($sql);
5773
5774
        while ($row = Database::fetch_array($allpages)) {
5775
            if ($row['reflink'] == 'index') {
5776
                $row['reflink'] = str_replace(
5777
                    ' ',
5778
                    '_',
5779
                    get_lang('DefaultTitle')
5780
                );
5781
            }
5782
            $pages[] = $row['reflink'];
5783
        }
5784
5785
        //get name refs in last pages
5786
        $sql = 'SELECT * FROM   '.$tbl_wiki.' s1
5787
                WHERE s1.c_id = '.$course_id.' AND id=(
5788
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5789
                    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.$condition_session.'
5790
                )';
5791
5792
        $allpages = Database::query($sql);
5793
5794
        while ($row = Database::fetch_array($allpages)) {
5795
            $refs = explode(" ", trim($row["linksto"]));
5796
            // Find linksto into reflink. If not found ->page is wanted
5797
            foreach ($refs as $v) {
5798
                if (!in_array($v, $pages)) {
5799
                    if (trim($v) != "") {
5800
                        $wanted[] = $v;
5801
                    }
5802
                }
5803
            }
5804
        }
5805
5806
        $wanted = array_unique($wanted); //make a unique list
5807
5808
        //show table
5809
        $rows = [];
5810
        foreach ($wanted as $wanted_show) {
5811
            $row = [];
5812
            $wanted_show = Security::remove_XSS($wanted_show);
5813
            $row[] = '<a href="'.api_get_path(
5814
                    WEB_PATH
5815
                ).'main/wiki/index.php?cidReq=&action=addnew&title='.str_replace(
5816
                    '_',
5817
                    ' ',
5818
                    $wanted_show
5819
                ).'&session_id='.api_htmlentities(
5820
                    $_GET['session_id']
5821
                ).'&group_id='.api_htmlentities(
5822
                    $_GET['group_id']
5823
                ).'" class="new_wiki_link">'.str_replace(
5824
                    '_',
5825
                    ' ',
5826
                    $wanted_show
5827
                ).'</a>'; //meter un remove xss en lugar de htmlentities
5828
            $rows[] = $row;
5829
        }
5830
5831
        $table = new SortableTableFromArrayConfig(
5832
            $rows,
5833
            0,
5834
            10,
5835
            'WantedPages_table',
5836
            '',
5837
            '',
5838
            'DESC'
5839
        );
5840
        $table->set_additional_parameters(
5841
            [
5842
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5843
                'action' => Security::remove_XSS($this->action),
5844
                'session_id' => intval($_GET['session_id']),
5845
                'group_id' => intval($_GET['group_id']),
5846
            ]
5847
        );
5848
        $table->set_header(0, get_lang('Title'), true);
5849
        $table->display();
5850
    }
5851
5852
    /**
5853
     * Most visited.
5854
     */
5855
    public function getMostVisited()
5856
    {
5857
        $tbl_wiki = $this->tbl_wiki;
5858
        $course_id = $this->course_id;
5859
        $groupfilter = $this->groupfilter;
5860
        $condition_session = $this->condition_session;
5861
        $_course = $this->courseInfo;
5862
5863
        echo '<div class="actions">'.get_lang('MostVisitedPages').'</div>';
5864
5865
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin(
5866
            )) { //only by professors if page is hidden
5867
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5868
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5869
                    GROUP BY reflink';
5870
        } else {
5871
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5872
                    WHERE
5873
                        c_id = '.$course_id.' AND
5874
                        '.$groupfilter.$condition_session.' AND
5875
                        visibility=1
5876
                    GROUP BY reflink';
5877
        }
5878
5879
        $allpages = Database::query($sql);
5880
5881
        //show table
5882
        if (Database::num_rows($allpages) > 0) {
5883
            $rows = [];
5884
            while ($obj = Database::fetch_object($allpages)) {
5885
                //get type assignment icon
5886
                $ShowAssignment = '';
5887
                if ($obj->assignment == 1) {
5888
                    $ShowAssignment = Display::return_icon(
5889
                        'wiki_assignment.png',
5890
                        get_lang('AssignmentDesc'),
5891
                        '',
5892
                        ICON_SIZE_SMALL
5893
                    );
5894
                } elseif ($obj->assignment == 2) {
5895
                    $ShowAssignment = $ShowAssignment = Display::return_icon(
5896
                        'wiki_work.png',
5897
                        get_lang('AssignmentWork'),
5898
                        '',
5899
                        ICON_SIZE_SMALL
5900
                    );
5901
                } elseif ($obj->assignment == 0) {
5902
                    $ShowAssignment = Display::return_icon(
5903
                        'px_transparent.gif'
5904
                    );
5905
                }
5906
5907
                $row = [];
5908
                $row[] = $ShowAssignment;
5909
                $row[] = '<a href="'.api_get_self(
5910
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5911
                        urlencode($obj->reflink)
5912
                    ).'&session_id='.api_htmlentities(
5913
                        $_GET['session_id']
5914
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5915
                    api_htmlentities($obj->title).'</a>';
5916
                $row[] = $obj->tsum;
5917
                $rows[] = $row;
5918
            }
5919
5920
            $table = new SortableTableFromArrayConfig(
5921
                $rows,
5922
                2,
5923
                10,
5924
                'MostVisitedPages_table',
5925
                '',
5926
                '',
5927
                'DESC'
5928
            );
5929
            $table->set_additional_parameters(
5930
                [
5931
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5932
                    'action' => Security::remove_XSS($this->action),
5933
                    'session_id' => intval($_GET['session_id']),
5934
                    'group_id' => intval($_GET['group_id']),
5935
                ]
5936
            );
5937
            $table->set_header(
5938
                0,
5939
                get_lang('Type'),
5940
                true,
5941
                ['style' => 'width:30px;']
5942
            );
5943
            $table->set_header(1, get_lang('Title'), true);
5944
            $table->set_header(2, get_lang('Visits'), true);
5945
            $table->display();
5946
        }
5947
    }
5948
5949
    /**
5950
     * Get actions bar.
5951
     */
5952
    public function showActionBar()
5953
    {
5954
        $_course = $this->courseInfo;
5955
        $session_id = $this->session_id;
5956
        $groupId = $this->group_id;
5957
        $page = $this->page;
5958
        $actionsLeft = '<a href="index.php?action=showpage&title=index&cidReq='.$_course['id'].'&session_id='.$session_id.'&group_id='.$groupId.'">'.
5959
            Display::return_icon(
5960
                'home.png',
5961
                get_lang('Home'),
5962
                '',
5963
                ICON_SIZE_MEDIUM
5964
            ).'</a>';
5965
5966
        if (api_is_allowed_to_session_edit(false, true) && api_is_allowed_to_edit()) {
5967
            // menu add page
5968
            $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=addnew&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
5969
                    'addnew'
5970
                ).'>'
5971
                .Display::return_icon(
5972
                    'new_document.png',
5973
                    get_lang('AddNew'),
5974
                    '',
5975
                    ICON_SIZE_MEDIUM
5976
                ).'</a>';
5977
        }
5978
5979
        $lock_unlock_addnew = null;
5980
        $protect_addnewpage = null;
5981
5982
        if (
5983
            true === api_get_configuration_value('wiki_categories_enabled')
5984
            && (api_is_allowed_to_edit(false, true) || api_is_platform_admin())
5985
        ) {
5986
            $actionsLeft .= Display::url(
5987
                Display::return_icon('folder.png', get_lang('Categories'), [], ICON_SIZE_MEDIUM),
5988
                'index.php?'.http_build_query([
5989
                    'cidReq' => $_course['id'],
5990
                    'session_id' => $session_id,
5991
                    'id_session' => $session_id,
5992
                    'group_id' => $groupId,
5993
                    'action' => 'category',
5994
                ])
5995
            );
5996
5997
            // page action: enable or disable the adding of new pages
5998
            if (self::check_addnewpagelock() == 0) {
5999
                $protect_addnewpage = Display::return_icon(
6000
                    'off.png',
6001
                    get_lang('AddOptionProtected')
6002
                );
6003
                $lock_unlock_addnew = 'unlockaddnew';
6004
            } else {
6005
                $protect_addnewpage = Display::return_icon(
6006
                    'on.png',
6007
                    get_lang('AddOptionUnprotected')
6008
                );
6009
                $lock_unlock_addnew = 'lockaddnew';
6010
            }
6011
        }
6012
6013
        // menu find
6014
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6015
                'searchpages'
6016
            ).'>'.
6017
            Display::return_icon(
6018
                'search.png',
6019
                get_lang('SearchPages'),
6020
                '',
6021
                ICON_SIZE_MEDIUM
6022
            ).'</a>';
6023
        ///menu more
6024
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'&action=more&title='.api_htmlentities(
6025
                urlencode($page)
6026
            ).'"'.self::is_active_navigation_tab('more').'>'.
6027
            Display::return_icon(
6028
                'statistics.png',
6029
                get_lang('Statistics'),
6030
                '',
6031
                ICON_SIZE_MEDIUM
6032
            ).'</a>';
6033
6034
        // menu all pages
6035
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=allpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6036
                'allpages'
6037
            ).'>'.
6038
            Display::return_icon(
6039
                'list_badges.png',
6040
                get_lang('AllPages'),
6041
                '',
6042
                ICON_SIZE_MEDIUM
6043
            ).'</a>';
6044
        // menu recent changes
6045
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=recentchanges&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6046
                'recentchanges'
6047
            ).'>'.
6048
            Display::return_icon(
6049
                'history.png',
6050
                get_lang('RecentChanges'),
6051
                '',
6052
                ICON_SIZE_MEDIUM
6053
            ).'</a>';
6054
        echo Display::toolbarAction('toolbar-wiki', [$actionsLeft]);
6055
    }
6056
6057
    /**
6058
     * Showing warning.
6059
     */
6060
    public function deletePageWarning()
6061
    {
6062
        $page = $this->page;
6063
        $course_id = $this->course_id;
6064
        $groupfilter = $this->groupfilter;
6065
        $condition_session = $this->condition_session;
6066
6067
        if (!$_GET['title']) {
6068
            Display::addFlash(
6069
                Display::return_message(
6070
                    get_lang('MustSelectPage'),
6071
                    'error',
6072
                    false
6073
                )
6074
            );
6075
6076
            return;
6077
        }
6078
6079
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6080
            Display::addFlash(
6081
                '<div id="wikititle">'.get_lang('DeletePageHistory').'</div>'
6082
            );
6083
            if ($page == "index") {
6084
                Display::addFlash(
6085
                    Display::return_message(
6086
                        get_lang('WarningDeleteMainPage'),
6087
                        'warning',
6088
                        false
6089
                    )
6090
                );
6091
            }
6092
            $message = get_lang('ConfirmDeletePage')."
6093
                <a href=\"index.php?".api_get_cidreq()."\">".get_lang("No")."</a>
6094
                <a href=\"".api_get_self()."?".api_get_cidreq(
6095
                )."&action=delete&title=".api_htmlentities(
6096
                    urlencode($page)
6097
                )."&delete=yes\">".
6098
                get_lang("Yes")."</a>";
6099
6100
            if (!isset($_GET['delete'])) {
6101
                Display::addFlash(
6102
                    Display::return_message($message, 'warning', false)
6103
                );
6104
            }
6105
6106
            if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
6107
                $result = self::deletePage(
6108
                    $page,
6109
                    $course_id,
6110
                    $groupfilter,
6111
                    $condition_session
6112
                );
6113
                if ($result) {
6114
                    Display::addFlash(
6115
                        Display::return_message(
6116
                            get_lang('WikiPageDeleted'),
6117
                            'confirmation',
6118
                            false
6119
                        )
6120
                    );
6121
                }
6122
            }
6123
        } else {
6124
            Display::addFlash(
6125
                Display::return_message(
6126
                    get_lang('OnlyAdminDeletePageWiki'),
6127
                    'normal',
6128
                    false
6129
                )
6130
            );
6131
        }
6132
    }
6133
6134
    /**
6135
     * Edit page.
6136
     */
6137
    public function editPage()
6138
    {
6139
        $tbl_wiki = $this->tbl_wiki;
6140
        $tbl_wiki_conf = $this->tbl_wiki_conf;
6141
        $condition_session = $this->condition_session;
6142
        $groupfilter = $this->groupfilter;
6143
        $page = $this->page;
6144
        $course_id = $this->course_id;
6145
        $groupId = $this->group_id;
6146
        $userId = api_get_user_id();
6147
6148
        if (api_get_session_id() != 0 &&
6149
            api_is_allowed_to_session_edit(false, true) == false
6150
        ) {
6151
            api_not_allowed();
6152
        }
6153
6154
        $sql = 'SELECT *
6155
            FROM '.$tbl_wiki.' w INNER JOIN '.$tbl_wiki_conf.' c
6156
            ON  (w.c_id = c.c_id AND w.page_id = c.page_id)
6157
            WHERE
6158
                w.c_id = '.$course_id.' AND
6159
                w.reflink= "'.Database::escape_string($page).'" AND
6160
                w.'.$groupfilter.$condition_session.'
6161
            ORDER BY id DESC';
6162
        $result = Database::query($sql);
6163
        $row = Database::fetch_array($result);
6164
6165
        $PassEdit = false;
6166
        // Check if is a wiki group
6167
        if (!empty($groupId)) {
6168
            $groupInfo = GroupManager::get_group_properties($groupId);
6169
            //Only teacher, platform admin and group members can edit a wiki group
6170
            if (api_is_allowed_to_edit(false, true) ||
6171
                api_is_platform_admin() ||
6172
                GroupManager::is_user_in_group($userId, $groupInfo)
6173
            ) {
6174
                $PassEdit = true;
6175
            } else {
6176
                Display::addFlash(
6177
                    Display::return_message(
6178
                        get_lang('OnlyEditPagesGroupMembers')
6179
                    )
6180
                );
6181
            }
6182
        } else {
6183
            $PassEdit = true;
6184
        }
6185
6186
        $content = '<div class="text-center">'
6187
            .sprintf(get_lang('DefaultContent'), api_get_path(WEB_IMG_PATH))
6188
            .'</div>';
6189
        $title = get_lang('DefaultTitle');
6190
        $page_id = 0;
6191
6192
        $icon_assignment = '';
6193
6194
        // we do not need awhile loop since we are always displaying the last version
6195
        if ($row) {
6196
            if ($row['content'] == '' && $row['title'] == '' && $page == '') {
6197
                Display::addFlash(
6198
                    Display::return_message(get_lang('MustSelectPage'), 'error', false)
6199
                );
6200
6201
                return;
6202
            }
6203
6204
            $content = api_html_entity_decode($row['content']);
6205
            $title = api_html_entity_decode($row['title']);
6206
            $page_id = $row['page_id'];
6207
6208
            // Only teachers and platform admin can edit the index page.
6209
            // Only teachers and platform admin can edit an assignment teacher.
6210
            // And users in groups
6211
6212
            if (($row['reflink'] == 'index' || $row['reflink'] == '' || $row['assignment'] == 1)
6213
                && (!api_is_allowed_to_edit(false, true) && $groupId == 0)
6214
                && !api_is_allowed_in_course()
6215
            ) {
6216
                Display::addFlash(
6217
                    Display::return_message(get_lang('OnlyEditPagesCourseManager'), 'error')
6218
                );
6219
6220
                return;
6221
            }
6222
6223
            // check if is an assignment
6224
            if ($row['assignment'] == 1) {
6225
                Display::addFlash(
6226
                    Display::return_message(get_lang('EditAssignmentWarning'))
6227
                );
6228
6229
                $icon_assignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'));
6230
            } elseif ($row['assignment'] == 2) {
6231
                $icon_assignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWorkExtra'));
6232
                if (($userId == $row['user_id']) == false) {
6233
                    if (api_is_allowed_to_edit(
6234
                            false,
6235
                            true
6236
                        ) || api_is_platform_admin()) {
6237
                        $PassEdit = true;
6238
                    } else {
6239
                        Display::addFlash(
6240
                            Display::return_message(get_lang('LockByTeacher'), 'warning')
6241
                        );
6242
                        $PassEdit = false;
6243
                    }
6244
                } else {
6245
                    $PassEdit = true;
6246
                }
6247
            }
6248
6249
            if ($PassEdit) {
6250
                if ($row['editlock'] == 1 &&
6251
                    (api_is_allowed_to_edit(false, true) == false ||
6252
                        api_is_platform_admin() == false)
6253
                ) {
6254
                    Display::addFlash(
6255
                        Display::return_message(get_lang('PageLockedExtra'))
6256
                    );
6257
                }
6258
            }
6259
        }
6260
6261
        if ($PassEdit) {
6262
            //show editor if edit is allowed <<<<<
6263
            if ((!empty($row['id']) && $row['editlock'] != 1)
6264
                || api_is_allowed_to_edit(false, true) != false
6265
                && api_is_platform_admin() != false
6266
            ) {
6267
                // Check tasks
6268
                if (!empty($row['startdate_assig']) && time() <
6269
                    api_strtotime($row['startdate_assig'])
6270
                ) {
6271
                    $message = get_lang('TheTaskDoesNotBeginUntil').': '.api_get_local_time($row['startdate_assig']);
6272
6273
                    Display::addFlash(
6274
                        Display::return_message($message, 'warning')
6275
                    );
6276
6277
                    if (!api_is_allowed_to_edit(false, true)) {
6278
                        $this->redirectHome();
6279
                    }
6280
                }
6281
6282
                if (!empty($row['enddate_assig']) &&
6283
                    time() > strtotime($row['enddate_assig']) &&
6284
                    $row['delayedsubmit'] == 0
6285
                ) {
6286
                    $message = get_lang('TheDeadlineHasBeenCompleted').': '.api_get_local_time($row['enddate_assig']);
6287
                    Display::addFlash(
6288
                        Display::return_message($message, 'warning')
6289
                    );
6290
                    if (!api_is_allowed_to_edit(false, true)) {
6291
                        $this->redirectHome();
6292
                    }
6293
                }
6294
6295
                if (!empty($row['max_version']) && $row['version'] >= $row['max_version']) {
6296
                    $message = get_lang('HasReachedMaxiNumVersions');
6297
                    Display::addFlash(
6298
                        Display::return_message($message, 'warning')
6299
                    );
6300
                    if (!api_is_allowed_to_edit(false, true)) {
6301
                        $this->redirectHome();
6302
                    }
6303
                }
6304
6305
                if (!empty($row['max_text']) && $row['max_text'] <= self::word_count(
6306
                        $row['content']
6307
                    )) {
6308
                    $message = get_lang('HasReachedMaxNumWords');
6309
                    Display::addFlash(
6310
                        Display::return_message($message, 'warning')
6311
                    );
6312
                    if (!api_is_allowed_to_edit(false, true)) {
6313
                        $this->redirectHome();
6314
                    }
6315
                }
6316
6317
                if (!empty($row['task'])) {
6318
                    //previous change 0 by text
6319
                    $message_task_startdate = empty($row['startdate_assig'])
6320
                        ? api_get_local_time($row['startdate_assig'])
6321
                        : get_lang('No');
6322
6323
                    $message_task_enddate = empty($row['enddate_assig'])
6324
                        ? api_get_local_time($row['enddate_assig'])
6325
                        : get_lang('No');
6326
6327
                    $message_task_delayedsubmit = $row['delayedsubmit'] == 0 ? get_lang('No') : get_lang('Yes');
6328
6329
                    $message_task_max_version = $row['max_version'] == 0 ? get_lang('No') : $row['max_version'];
6330
6331
                    $message_task_max_text = $row['max_text'] == 0 ? get_lang('No') : $row['max_text'];
6332
6333
                    // Comp message
6334
                    $message_task = '<b>'.get_lang('DescriptionOfTheTask').'</b><p>'.$row['task'].'</p><hr>'
6335
                        .'<p>'.get_lang('StartDate').': '.$message_task_startdate.'</p>'
6336
                        .'<p>'.get_lang('EndDate').': '.$message_task_enddate
6337
                        .' ('.get_lang('AllowLaterSends').') '.$message_task_delayedsubmit.'</p>'
6338
                        .'<p>'.get_lang('OtherSettings').': '.get_lang('NMaxVersion').': '.$message_task_max_version
6339
                        .' '.get_lang('NMaxWords').': '.$message_task_max_text.'</p>';
6340
                    // Display message
6341
                    Display::addFlash(
6342
                        Display::return_message($message_task)
6343
                    );
6344
                }
6345
6346
                if (!empty($row['id'])) {
6347
                    $feedback_message = '';
6348
                    if ($row['progress'] == $row['fprogress1'] && !empty($row['fprogress1'])) {
6349
                        $feedback_message = '<b>'.get_lang('Feedback').'</b>'
6350
                            .'<p>'.api_htmlentities($row['feedback1']).'</p>';
6351
                    } elseif ($row['progress'] == $row['fprogress2'] && !empty($row['fprogress2'])) {
6352
                        $feedback_message = '<b>'.get_lang('Feedback').'</b>'
6353
                            .'<p>'.api_htmlentities($row['feedback2']).'</p>';
6354
                    } elseif ($row['progress'] == $row['fprogress3'] && !empty($row['fprogress3'])) {
6355
                        $feedback_message = '<b>'.get_lang('Feedback').'</b>'
6356
                            .'<p>'.api_htmlentities($row['feedback3']).'</p>';
6357
                    }
6358
6359
                    if (!empty($feedback_message)) {
6360
                        Display::addFlash(
6361
                            Display::return_message($feedback_message)
6362
                        );
6363
                    }
6364
                }
6365
6366
                // Previous checking for concurrent editions
6367
                if (!empty($row['id']) && $row['is_editing'] == 0) {
6368
                    Display::addFlash(
6369
                        Display::return_message(get_lang('WarningMaxEditingTime'))
6370
                    );
6371
                    $time_edit = api_get_utc_datetime();
6372
                    $sql = 'UPDATE '.$tbl_wiki.' SET
6373
                            is_editing = "'.$userId.'",
6374
                            time_edit = "'.$time_edit.'"
6375
                            WHERE c_id = '.$course_id.' AND id="'.$row['id'].'"';
6376
                    Database::query($sql);
6377
                } elseif (!empty($row['id']) && $row['is_editing'] != $userId) {
6378
                    $timestamp_edit = strtotime($row['time_edit']);
6379
                    $time_editing = time() - $timestamp_edit;
6380
                    $max_edit_time = 1200; // 20 minutes
6381
                    $rest_time = $max_edit_time - $time_editing;
6382
6383
                    $userinfo = api_get_user_info($row['is_editing']);
6384
                    if ($userinfo !== false) {
6385
                        $is_being_edited = get_lang('ThisPageisBeginEditedBy').PHP_EOL
6386
                            .UserManager::getUserProfileLink($userinfo).PHP_EOL
6387
                            .get_lang('ThisPageisBeginEditedTryLater').PHP_EOL
6388
                            .date("i", $rest_time).PHP_EOL
6389
                            .get_lang('MinMinutes');
6390
6391
                        Display::addFlash(
6392
                            Display::return_message($is_being_edited, 'normal', false)
6393
                        );
6394
                    }
6395
6396
                    $this->redirectHome();
6397
                }
6398
6399
                // Form.
6400
                $url = api_get_self().'?action=edit&title='.urlencode($page).'&session_id='.api_get_session_id()
6401
                    .'&group_id='.api_get_group_id().'&'.api_get_cidreq();
6402
                $form = new FormValidator('wiki', 'post', $url);
6403
                $form->addElement(
6404
                    'header',
6405
                    $icon_assignment.str_repeat('&nbsp;', 3).api_htmlentities($title)
6406
                );
6407
                self::setForm($form, !empty($row['id']) ? $row : []);
6408
                $form->addElement('hidden', 'title');
6409
                $form->addButtonSave(get_lang('Save'), 'SaveWikiChange');
6410
                $row['title'] = $title;
6411
                $row['page_id'] = $page_id;
6412
                $row['reflink'] = $page;
6413
                $row['content'] = $content;
6414
6415
                if (!empty($row['id']) && true === api_get_configuration_value('wiki_categories_enabled')) {
6416
                    $wiki = Database::getManager()->find(CWiki::class, $row['id']);
6417
6418
                    foreach ($wiki->getCategories() as $category) {
6419
                        $row['category'][] = $category->getId();
6420
                    }
6421
                }
6422
6423
                $form->setDefaults($row);
6424
                $form->display();
6425
6426
                // Saving a change
6427
                if ($form->validate()) {
6428
                    $versionFromSession = Session::read('_version');
6429
                    if (empty($_POST['title'])) {
6430
                        Display::addFlash(
6431
                            Display::return_message(
6432
                                get_lang("NoWikiPageTitle"),
6433
                                'error'
6434
                            )
6435
                        );
6436
                    } elseif (!self::double_post($_POST['wpost_id'])) {
6437
                        //double post
6438
                    } elseif ($_POST['version'] != '' && $versionFromSession != 0 && $_POST['version'] != $versionFromSession) {
6439
                        //prevent concurrent users and double version
6440
                        Display::addFlash(
6441
                            Display::return_message(
6442
                                get_lang("EditedByAnotherUser"),
6443
                                'error'
6444
                            )
6445
                        );
6446
                    } else {
6447
                        $returnMessage = self::save_wiki(
6448
                            $form->exportValues()
6449
                        );
6450
                        Display::addFlash(
6451
                            Display::return_message(
6452
                                $returnMessage,
6453
                                'confirmation'
6454
                            )
6455
                        );
6456
                    }
6457
                    $wikiData = self::getWikiData();
6458
                    $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq();
6459
                    header('Location: '.$redirectUrl);
6460
                    exit;
6461
                }
6462
            }
6463
        }
6464
    }
6465
6466
    /**
6467
     * Get history.
6468
     */
6469
    public function getHistory()
6470
    {
6471
        $tbl_wiki = $this->tbl_wiki;
6472
        $condition_session = $this->condition_session;
6473
        $groupfilter = $this->groupfilter;
6474
        $page = $this->page;
6475
        $course_id = $this->course_id;
6476
        $session_id = $this->session_id;
6477
        $userId = api_get_user_id();
6478
6479
        if (!$_GET['title']) {
6480
            Display::addFlash(
6481
                Display::return_message(
6482
                    get_lang("MustSelectPage"),
6483
                    'error',
6484
                    false
6485
                )
6486
            );
6487
6488
            return;
6489
        }
6490
6491
        /* First, see the property visibility that is at the last register and
6492
        therefore we should select descending order.
6493
        But to give ownership to each record,
6494
        this is no longer necessary except for the title. TODO: check this*/
6495
6496
        $sql = 'SELECT * FROM '.$tbl_wiki.'
6497
                WHERE
6498
                    c_id = '.$course_id.' AND
6499
                    reflink="'.Database::escape_string($page).'" AND
6500
                    '.$groupfilter.$condition_session.'
6501
                ORDER BY id DESC';
6502
        $result = Database::query($sql);
6503
6504
        $KeyVisibility = null;
6505
        $KeyAssignment = null;
6506
        $KeyTitle = null;
6507
        $KeyUserId = null;
6508
        while ($row = Database::fetch_array($result)) {
6509
            $KeyVisibility = $row['visibility'];
6510
            $KeyAssignment = $row['assignment'];
6511
            $KeyTitle = $row['title'];
6512
            $KeyUserId = $row['user_id'];
6513
        }
6514
        $icon_assignment = null;
6515
        if ($KeyAssignment == 1) {
6516
            $icon_assignment = Display::return_icon(
6517
                'wiki_assignment.png',
6518
                get_lang('AssignmentDescExtra'),
6519
                '',
6520
                ICON_SIZE_SMALL
6521
            );
6522
        } elseif ($KeyAssignment == 2) {
6523
            $icon_assignment = Display::return_icon(
6524
                'wiki_work.png',
6525
                get_lang('AssignmentWorkExtra'),
6526
                '',
6527
                ICON_SIZE_SMALL
6528
            );
6529
        }
6530
6531
        // Second, show
6532
        //if the page is hidden and is a job only sees its author and professor
6533
        if ($KeyVisibility == 1 ||
6534
            api_is_allowed_to_edit(false, true) ||
6535
            api_is_platform_admin() ||
6536
            (
6537
                $KeyAssignment == 2 && $KeyVisibility == 0 &&
6538
                ($userId == $KeyUserId)
6539
            )
6540
        ) {
6541
            // We show the complete history
6542
            if (!isset($_POST['HistoryDifferences']) &&
6543
                !isset($_POST['HistoryDifferences2'])
6544
            ) {
6545
                $sql = 'SELECT * FROM '.$tbl_wiki.'
6546
                        WHERE
6547
                            c_id = '.$course_id.' AND
6548
                            reflink="'.Database::escape_string($page).'" AND
6549
                            '.$groupfilter.$condition_session.'
6550
                        ORDER BY id DESC';
6551
                $result = Database::query($sql);
6552
                $title = $_GET['title'];
6553
                $group_id = api_get_group_id();
6554
6555
                echo '<div id="wikititle">';
6556
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities(
6557
                        $KeyTitle
6558
                    );
6559
                echo '</div>';
6560
6561
                echo '<form id="differences" method="POST" action="index.php?'.api_get_cidreq(
6562
                    ).'&action=history&title='.api_htmlentities(
6563
                        urlencode($title)
6564
                    ).'&session_id='.api_htmlentities(
6565
                        $session_id
6566
                    ).'&group_id='.api_htmlentities($group_id).'">';
6567
6568
                echo '<ul style="list-style-type: none;">';
6569
                echo '<br/>';
6570
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.
6571
                    get_lang('ShowDifferences').' '.get_lang(
6572
                        'LinesDiff'
6573
                    ).'</button>';
6574
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.
6575
                    get_lang('ShowDifferences').' '.get_lang(
6576
                        'WordsDiff'
6577
                    ).'</button>';
6578
                echo '<br/><br/>';
6579
6580
                $counter = 0;
6581
                $total_versions = Database::num_rows($result);
6582
6583
                while ($row = Database::fetch_array($result)) {
6584
                    $userinfo = api_get_user_info($row['user_id']);
6585
                    $username = api_htmlentities(
6586
                        sprintf(get_lang('LoginX'), $userinfo['username']),
6587
                        ENT_QUOTES
6588
                    );
6589
6590
                    echo '<li style="margin-bottom: 5px;">';
6591
                    ($counter == 0) ? $oldstyle = 'style="visibility: hidden;"' : $oldstyle = '';
6592
                    ($counter == 0) ? $newchecked = ' checked' : $newchecked = '';
6593
                    ($counter == $total_versions - 1) ? $newstyle = 'style="visibility: hidden;"' : $newstyle = '';
6594
                    ($counter == 1) ? $oldchecked = ' checked' : $oldchecked = '';
6595
                    echo '<input name="old" value="'.$row['id'].'" type="radio" '.$oldstyle.' '.$oldchecked.'/> ';
6596
                    echo '<input name="new" value="'.$row['id'].'" type="radio" '.$newstyle.' '.$newchecked.'/> ';
6597
                    echo '<a href="'.api_get_self(
6598
                        ).'?action=showpage&title='.api_htmlentities(
6599
                            urlencode($page)
6600
                        ).'&view='.$row['id'].'">';
6601
                    echo '<a href="'.api_get_self().'?'.api_get_cidreq(
6602
                        ).'&action=showpage&title='.api_htmlentities(
6603
                            urlencode($page)
6604
                        ).'&view='.$row['id'].'">';
6605
                    echo api_get_local_time(
6606
                        $row['dtime']
6607
                    );
6608
                    echo '</a>';
6609
                    echo ' ('.get_lang('Version').' '.$row['version'].')';
6610
                    echo ' '.get_lang('By').' ';
6611
                    if ($userinfo !== false) {
6612
                        echo UserManager::getUserProfileLink($userinfo);
6613
                    } else {
6614
                        echo get_lang('Anonymous').' ('.api_htmlentities(
6615
                                $row['user_ip']
6616
                            ).')';
6617
                    }
6618
                    echo ' ( '.get_lang('Progress').': '.api_htmlentities(
6619
                            $row['progress']
6620
                        ).'%, ';
6621
                    $comment = $row['comment'];
6622
                    if (!empty($comment)) {
6623
                        $comment = api_substr($comment, 0, 100);
6624
                        if ($comment !== false) {
6625
                            $comment = api_htmlentities($comment);
6626
                            echo get_lang('Comments').': '.$comment;
6627
                            if (api_strlen($row['comment']) > 100) {
6628
                                echo '... ';
6629
                            }
6630
                        }
6631
                    } else {
6632
                        echo get_lang('Comments').':  ---';
6633
                    }
6634
                    echo ' ) </li>';
6635
                    $counter++;
6636
                } //end while
6637
6638
                echo '<br/>';
6639
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.get_lang(
6640
                        'ShowDifferences'
6641
                    ).' '.get_lang('LinesDiff').'</button>';
6642
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.get_lang(
6643
                        'ShowDifferences'
6644
                    ).' '.get_lang('WordsDiff').'</button>';
6645
                echo '</ul></form>';
6646
            } else { // We show the differences between two versions
6647
                $version_old = [];
6648
                if (isset($_POST['old'])) {
6649
                    $sql_old = "SELECT * FROM $tbl_wiki
6650
                                WHERE c_id = $course_id AND id='".Database::escape_string(
6651
                            $_POST['old']
6652
                        )."'";
6653
                    $result_old = Database::query($sql_old);
6654
                    $version_old = Database::fetch_array($result_old);
6655
                }
6656
6657
                $sql_new = "SELECT * FROM $tbl_wiki
6658
                            WHERE
6659
                              c_id = $course_id AND
6660
                              id = '".Database::escape_string($_POST['new'])."'";
6661
                $result_new = Database::query($sql_new);
6662
                $version_new = Database::fetch_array($result_new);
6663
                $oldTime = isset($version_old['dtime']) ? api_get_local_time($version_old['dtime']) : null;
6664
                $oldContent = isset($version_old['content']) ? $version_old['content'] : null;
6665
6666
                if (isset($_POST['HistoryDifferences'])) {
6667
                    include 'diff.inc.php';
6668
                    //title
6669
                    echo '<div id="wikititle">'.api_htmlentities(
6670
                            $version_new['title']
6671
                        ).'
6672
                            <font size="-2"><i>('.get_lang('DifferencesNew').'</i>
6673
                            <font style="background-color:#aaaaaa">'.api_get_local_time($version_new['dtime']).'</font>
6674
                            <i>'.get_lang('DifferencesOld').'</i>
6675
                            <font style="background-color:#aaaaaa">'.$oldTime.'</font>
6676
                ) '.get_lang('Legend').':  <span class="diffAdded" >'.get_lang(
6677
                            'WikiDiffAddedLine'
6678
                        ).'</span>
6679
                <span class="diffDeleted" >'.get_lang(
6680
                            'WikiDiffDeletedLine'
6681
                        ).'</span> <span class="diffMoved">'.get_lang(
6682
                            'WikiDiffMovedLine'
6683
                        ).'</span></font>
6684
                </div>';
6685
                }
6686
                if (isset($_POST['HistoryDifferences2'])) {
6687
                    //title
6688
                    echo '<div id="wikititle">'.api_htmlentities(
6689
                            $version_new['title']
6690
                        ).'
6691
                        <font size="-2"><i>('.get_lang(
6692
                            'DifferencesNew'
6693
                        ).'</i> <font style="background-color:#aaaaaa">'.api_get_local_time($version_new['dtime']).'</font>
6694
                        <i>'.get_lang(
6695
                            'DifferencesOld'
6696
                        ).'</i> <font style="background-color:#aaaaaa">'.$oldTime.'</font>)
6697
                        '.get_lang(
6698
                            'Legend'
6699
                        ).':  <span class="diffAddedTex" >'.get_lang(
6700
                            'WikiDiffAddedTex'
6701
                        ).'</span>
6702
                        <span class="diffDeletedTex" >'.get_lang(
6703
                            'WikiDiffDeletedTex'
6704
                        ).'</span></font></div>';
6705
                }
6706
6707
                if (isset($_POST['HistoryDifferences'])) {
6708
                    echo '<table>'.diff(
6709
                            $oldContent,
6710
                            $version_new['content'],
6711
                            true,
6712
                            'format_table_line'
6713
                        ).'</table>'; // format_line mode is better for words
6714
                    echo '<br />';
6715
                    echo '<strong>'.get_lang(
6716
                            'Legend'
6717
                        ).'</strong><div class="diff">'."\n";
6718
                    echo '<table><tr>';
6719
                    echo '<td>';
6720
                    echo '</td><td>';
6721
                    echo '<span class="diffEqual" >'.get_lang(
6722
                            'WikiDiffUnchangedLine'
6723
                        ).'</span><br />';
6724
                    echo '<span class="diffAdded" >'.get_lang(
6725
                            'WikiDiffAddedLine'
6726
                        ).'</span><br />';
6727
                    echo '<span class="diffDeleted" >'.get_lang(
6728
                            'WikiDiffDeletedLine'
6729
                        ).'</span><br />';
6730
                    echo '<span class="diffMoved" >'.get_lang(
6731
                            'WikiDiffMovedLine'
6732
                        ).'</span><br />';
6733
                    echo '</td>';
6734
                    echo '</tr></table>';
6735
                }
6736
6737
                if (isset($_POST['HistoryDifferences2'])) {
6738
                    $lines1 = [strip_tags($oldContent)]; //without <> tags
6739
                    $lines2 = [
6740
                        strip_tags(
6741
                            $version_new['content']
6742
                        ),
6743
                    ]; //without <> tags
6744
                    $diff = new Text_Diff($lines1, $lines2);
6745
                    $renderer = new Text_Diff_Renderer_inline();
6746
                    echo '<style>del{background:#fcc}ins{background:#cfc}</style>'.$renderer->render(
6747
                            $diff
6748
                        ); // Code inline
6749
                    echo '<br />';
6750
                    echo '<strong>'.get_lang(
6751
                            'Legend'
6752
                        ).'</strong><div class="diff">'."\n";
6753
                    echo '<table><tr>';
6754
                    echo '<td>';
6755
                    echo '</td><td>';
6756
                    echo '<span class="diffAddedTex" >'.get_lang(
6757
                            'WikiDiffAddedTex'
6758
                        ).'</span><br />';
6759
                    echo '<span class="diffDeletedTex" >'.get_lang(
6760
                            'WikiDiffDeletedTex'
6761
                        ).'</span><br />';
6762
                    echo '</td>';
6763
                    echo '</tr></table>';
6764
                }
6765
            }
6766
        }
6767
    }
6768
6769
    /**
6770
     * Get stat tables.
6771
     */
6772
    public function getStatsTable()
6773
    {
6774
        $_course = $this->courseInfo;
6775
        $session_id = $this->session_id;
6776
        $groupId = $this->group_id;
6777
6778
        echo '<div class="actions">'.get_lang('More').'</div>';
6779
        echo '<table border="0">';
6780
        echo '  <tr>';
6781
        echo '    <td>';
6782
        echo '      <ul>';
6783
        //Submenu Most active users
6784
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mactiveusers&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6785
                'MostActiveUsers'
6786
            ).'</a></li>';
6787
        //Submenu Most visited pages
6788
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mvisited&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6789
                'MostVisitedPages'
6790
            ).'</a></li>';
6791
        //Submenu Most changed pages
6792
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mostchanged&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6793
                'MostChangedPages'
6794
            ).'</a></li>';
6795
        echo '      </ul>';
6796
        echo '    </td>';
6797
        echo '    <td>';
6798
        echo '      <ul>';
6799
        // Submenu Orphaned pages
6800
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=orphaned&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6801
                'OrphanedPages'
6802
            ).'</a></li>';
6803
        // Submenu Wanted pages
6804
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=wanted&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6805
                'WantedPages'
6806
            ).'</a></li>';
6807
        // Submenu Most linked pages
6808
        echo '<li><a href="index.php?cidReq='.$_course['code'].'&action=mostlinked&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6809
                'MostLinkedPages'
6810
            ).'</a></li>';
6811
        echo '</ul>';
6812
        echo '</td>';
6813
        echo '<td style="vertical-align:top">';
6814
        echo '<ul>';
6815
        // Submenu Statistics
6816
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6817
            echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=statistics&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6818
                    'Statistics'
6819
                ).'</a></li>';
6820
        }
6821
        echo '      </ul>';
6822
        echo '    </td>';
6823
        echo '  </tr>';
6824
        echo '</table>';
6825
    }
6826
6827
    /**
6828
     * Kind of controller.
6829
     */
6830
    public function handleAction(string $action)
6831
    {
6832
        $page = $this->page;
6833
        switch ($action) {
6834
            case 'export_to_pdf':
6835
                if (isset($_GET['wiki_id'])) {
6836
                    self::export_to_pdf($_GET['wiki_id'], api_get_course_id());
6837
                    break;
6838
                }
6839
                break;
6840
            case 'export2doc':
6841
                if (isset($_GET['wiki_id'])) {
6842
                    $export2doc = self::export2doc($_GET['wiki_id']);
6843
                    if ($export2doc) {
6844
                        Display::addFlash(
6845
                            Display::return_message(
6846
                                get_lang('ThePageHasBeenExportedToDocArea'),
6847
                                'confirmation',
6848
                                false
6849
                            )
6850
                        );
6851
                    }
6852
                }
6853
                break;
6854
            case 'restorepage':
6855
                self::restorePage();
6856
                break;
6857
            case 'more':
6858
                self::getStatsTable();
6859
                break;
6860
            case 'statistics':
6861
                self::getStats();
6862
                break;
6863
            case 'mactiveusers':
6864
                self::getActiveUsers($action);
6865
                break;
6866
            case 'usercontrib':
6867
                self::getUserContributions($_GET['user_id'], $action);
6868
                break;
6869
            case 'mostchanged':
6870
                $this->getMostChangedPages($action);
6871
                break;
6872
            case 'mvisited':
6873
                self::getMostVisited();
6874
                break;
6875
            case 'wanted':
6876
                $this->getWantedPages();
6877
                break;
6878
            case 'orphaned':
6879
                self::getOrphaned();
6880
                break;
6881
            case 'mostlinked':
6882
                self::getMostLinked();
6883
                break;
6884
            case 'delete':
6885
                self::deletePageWarning($page);
6886
                break;
6887
            case 'deletewiki':
6888
                $title = '<div class="actions">'.get_lang(
6889
                        'DeleteWiki'
6890
                    ).'</div>';
6891
                if (api_is_allowed_to_edit(
6892
                        false,
6893
                        true
6894
                    ) || api_is_platform_admin()) {
6895
                    $message = get_lang('ConfirmDeleteWiki');
6896
                    $message .= '<p>
6897
                        <a href="index.php?'.api_get_cidreq().'">'.get_lang(
6898
                            'No'
6899
                        ).'</a>
6900
                        &nbsp;&nbsp;|&nbsp;&nbsp;
6901
                        <a href="'.api_get_self().'?'.api_get_cidreq(
6902
                        ).'&action=deletewiki&delete=yes">'.
6903
                        get_lang('Yes').'</a>
6904
                    </p>';
6905
6906
                    if (!isset($_GET['delete'])) {
6907
                        Display::addFlash(
6908
                            $title.Display::return_message(
6909
                                $message,
6910
                                'warning',
6911
                                false
6912
                            )
6913
                        );
6914
                    }
6915
                } else {
6916
                    Display::addFlash(
6917
                        Display::return_message(
6918
                            get_lang("OnlyAdminDeleteWiki"),
6919
                            'normal',
6920
                            false
6921
                        )
6922
                    );
6923
                }
6924
6925
                if (api_is_allowed_to_edit(
6926
                        false,
6927
                        true
6928
                    ) || api_is_platform_admin()) {
6929
                    if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
6930
                        $return_message = self::delete_wiki();
6931
                        Display::addFlash(
6932
                            Display::return_message(
6933
                                $return_message,
6934
                                'confirmation',
6935
                                false
6936
                            )
6937
                        );
6938
                        $this->redirectHome();
6939
                    }
6940
                }
6941
                break;
6942
            case 'searchpages':
6943
                self::getSearchPages($action);
6944
                break;
6945
            case 'links':
6946
                self::getLinks($page);
6947
                break;
6948
            case 'addnew':
6949
                if (api_get_session_id() != 0 && api_is_allowed_to_session_edit(false, true) == false) {
6950
                    api_not_allowed();
6951
                }
6952
                $groupInfo = GroupManager::get_group_properties(
6953
                    api_get_group_id()
6954
                );
6955
                echo '<div class="actions">'.get_lang('AddNew').'</div>';
6956
                echo '<br/>';
6957
                //first, check if page index was created. chektitle=false
6958
                if (self::checktitle('index')) {
6959
                    if (api_is_allowed_to_edit(false, true) ||
6960
                        api_is_platform_admin() ||
6961
                        GroupManager::is_user_in_group(
6962
                            api_get_user_id(),
6963
                            $groupInfo
6964
                        ) ||
6965
                        api_is_allowed_in_course()
6966
                    ) {
6967
                        Display::addFlash(
6968
                            Display::return_message(get_lang('GoAndEditMainPage'), 'normal', false)
6969
                        );
6970
                    } else {
6971
                        Display::addFlash(
6972
                            Display::return_message(get_lang('WikiStandBy'), 'normal', false)
6973
                        );
6974
                    }
6975
                } elseif (self::check_addnewpagelock() == 0
6976
                    && (
6977
                        api_is_allowed_to_edit(false, true) == false
6978
                        || api_is_platform_admin() == false
6979
                    )
6980
                ) {
6981
                    Display::addFlash(
6982
                        Display::return_message(get_lang('AddPagesLocked'), 'error', false)
6983
                    );
6984
                } else {
6985
                    $groupInfo = GroupManager::get_group_properties(
6986
                        api_get_group_id()
6987
                    );
6988
                    if (api_is_allowed_to_edit(false, true) ||
6989
                        api_is_platform_admin() ||
6990
                        GroupManager::is_user_in_group(
6991
                            api_get_user_id(),
6992
                            $groupInfo
6993
                        ) ||
6994
                        $_GET['group_id'] == 0
6995
                    ) {
6996
                        self::display_new_wiki_form();
6997
                    } else {
6998
                        Display::addFlash(
6999
                            Display::return_message(get_lang('OnlyAddPagesGroupMembers'), 'normal', false)
7000
                        );
7001
                    }
7002
                }
7003
                break;
7004
            case 'show':
7005
            case 'showpage':
7006
                self::display_wiki_entry($page);
7007
                break;
7008
            case 'edit':
7009
                self::editPage();
7010
                break;
7011
            case 'history':
7012
                self::getHistory();
7013
                break;
7014
            case 'recentchanges':
7015
                self::recentChanges($page, $action);
7016
                break;
7017
            case 'allpages':
7018
                self::allPages($action);
7019
                break;
7020
            case 'discuss':
7021
                self::getDiscuss($page);
7022
                break;
7023
            case 'export_to_doc_file':
7024
                self::exportTo($_GET['id'], 'odt');
7025
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
7026
                break;
7027
            case 'category':
7028
                $this->addCategory();
7029
                break;
7030
            case 'delete_category':
7031
                $this->deleteCategory();
7032
                break;
7033
        }
7034
    }
7035
7036
    /**
7037
     * Redirect to home.
7038
     */
7039
    public function redirectHome()
7040
    {
7041
        $redirectUrl = $this->url.'&action=showpage&title=index';
7042
        header('Location: '.$redirectUrl.'&'.api_get_cidreq());
7043
        exit;
7044
    }
7045
7046
    /**
7047
     * Export wiki content in a ODF.
7048
     *
7049
     * @param int $id
7050
     * @param string int
7051
     *
7052
     * @return bool
7053
     */
7054
    public function exportTo($id, $format = 'doc')
7055
    {
7056
        $data = self::getWikiDataFromDb($id);
7057
7058
        if (isset($data['content']) && !empty($data['content'])) {
7059
            Export::htmlToOdt($data['content'], $data['reflink'], $format);
7060
        }
7061
7062
        return false;
7063
    }
7064
7065
    private function returnCategoriesBlock(int $wikiId, string $tagStart = '<div>', string $tagEnd = '</div>'): string
7066
    {
7067
        if (true !== api_get_configuration_value('wiki_categories_enabled') || empty($wikiId)) {
7068
            return '';
7069
        }
7070
7071
        $wiki = Database::getManager()->find(CWiki::class, $wikiId);
7072
7073
        return $tagStart.implode(', ', $wiki->getCategories()->getValues()).$tagEnd;
7074
    }
7075
7076
    private function gelAllPagesQuery(
7077
        $onlyCount = false,
7078
        $from = 0,
7079
        $numberOfItems = 10,
7080
        $column = 0,
7081
        $direction = 'ASC'
7082
    ): ?Statement {
7083
        $tblWiki = $this->tbl_wiki;
7084
7085
        $fields = $onlyCount
7086
            ? 'COUNT(s1.iid) AS nbr'
7087
            : 's1.assignment col0, s1.title col1, s1.user_id col2, s1.dtime col3, s1.reflink, s1.user_ip, s1.iid';
7088
7089
        $query = 'SELECT '.$fields.' FROM '.$tblWiki.' s1 WHERE s1.c_id = '.$this->course_id.' ';
7090
7091
        if (!api_is_allowed_to_edit(false, true) && !api_is_platform_admin()) {
7092
            // warning don't use group by reflink because does not return the last version
7093
            $query .= 'AND visibility = 1 ';
7094
        }
7095
7096
        $query .= 'AND id = (
7097
            SELECT MAX(s2.id) FROM '.$tblWiki.' s2
7098
            WHERE s2.c_id = '.$this->course_id.'
7099
                AND s1.reflink = s2.reflink
7100
                AND '.$this->groupfilter.'
7101
                AND session_id = '.$this->session_id.'
7102
        ) ';
7103
7104
        if (!$onlyCount) {
7105
            $query .= "ORDER BY col$column $direction LIMIT $from, $numberOfItems";
7106
        }
7107
7108
        return Database::query($query);
7109
    }
7110
7111
    private function deleteCategory()
7112
    {
7113
        if (!api_is_allowed_to_edit(false, true) && !api_is_platform_admin()) {
7114
            api_not_allowed(true);
7115
        }
7116
7117
        if (true !== api_get_configuration_value('wiki_categories_enabled')) {
7118
            api_not_allowed(true);
7119
        }
7120
7121
        $em = Database::getManager();
7122
7123
        $category = null;
7124
7125
        if (isset($_GET['id'])) {
7126
            $category = $em->find(CWikiCategory::class, $_GET['id']);
7127
7128
            if (!$category) {
7129
                api_not_allowed(true);
7130
            }
7131
        }
7132
7133
        $em->remove($category);
7134
        $em->flush();
7135
7136
        Display::addFlash(
7137
            Display::return_message(get_lang('CategoryDeleted'), 'success')
7138
        );
7139
7140
        header('Location: index.php?'.api_get_cidreq().'&action=category');
7141
        exit;
7142
    }
7143
7144
    private function addCategory()
7145
    {
7146
        if (!api_is_allowed_to_edit(false, true) && !api_is_platform_admin()) {
7147
            api_not_allowed(true);
7148
        }
7149
7150
        if (true !== api_get_configuration_value('wiki_categories_enabled')) {
7151
            api_not_allowed(true);
7152
        }
7153
7154
        $categoryRepo = Database::getManager()->getRepository(CWikiCategory::class);
7155
7156
        $categoryToEdit = null;
7157
7158
        if (isset($_GET['id'])) {
7159
            $categoryToEdit = $categoryRepo->find($_GET['id']);
7160
7161
            if (!$categoryToEdit) {
7162
                api_not_allowed(true);
7163
            }
7164
        }
7165
7166
        $course = api_get_course_entity();
7167
        $session = api_get_session_entity();
7168
7169
        if ($categoryToEdit
7170
            && ($course !== $categoryToEdit->getCourse() || $session !== $categoryToEdit->getSession())
7171
        ) {
7172
            api_not_allowed(true);
7173
        }
7174
7175
        $self = api_get_self();
7176
        $cidReq = api_get_cidreq();
7177
        $iconEdit = Display::return_icon('edit.png', get_lang('Edit'));
7178
        $iconDelete = Display::return_icon('delete.png', get_lang('Delete'));
7179
7180
        $categories = $categoryRepo->findByCourse($course, $session);
7181
        $categoryList = array_map(
7182
            function (CWikiCategory $category) use ($self, $cidReq, $iconEdit, $iconDelete) {
7183
                $actions = [];
7184
                $actions[] = Display::url(
7185
                    $iconEdit,
7186
                    "$self?$cidReq&".http_build_query(['action' => 'category', 'id' => $category->getId()])
7187
                );
7188
                $actions[] = Display::url(
7189
                    $iconDelete,
7190
                    "$self?$cidReq&".http_build_query(['action' => 'delete_category', 'id' => $category->getId()])
7191
                );
7192
7193
                return [
7194
                    $category->getNodeName(),
7195
                    implode(PHP_EOL, $actions),
7196
                ];
7197
            },
7198
            $categories
7199
        );
7200
7201
        $table = new SortableTableFromArray($categoryList);
7202
        $table->set_header(0, get_lang('Name'), false);
7203
        $table->set_header(1, get_lang('Actions'), false, ['class' => 'text-right'], ['class' => 'text-right']);
7204
7205
        $form = $this->createCategoryForm($categoryToEdit);
7206
        $form->display();
7207
        echo '<hr>';
7208
        $table->display();
7209
    }
7210
7211
    private function createCategoryForm(CWikiCategory $category = null): FormValidator
7212
    {
7213
        $em = Database::getManager();
7214
        $categoryRepo = $em->getRepository(CWikiCategory::class);
7215
7216
        $course = api_get_course_entity($this->courseInfo['real_id']);
7217
        $session = api_get_session_entity($this->session_id);
7218
7219
        $categories = $categoryRepo->findByCourse($course, $session);
7220
7221
        $formAction = api_get_self().'?'.http_build_query([
7222
            'cidReq' => $course->getCode(),
7223
            'session_id' => $session ? $session->getId() : 0,
7224
            'id_session' => $session ? $session->getId() : 0,
7225
            'group_id' => $this->group_id,
7226
            'action' => 'category',
7227
            'id' => $category ? $category->getId() : null,
7228
        ]);
7229
7230
        $form = new FormValidator('category', 'post', $formAction);
7231
        $form->addHeader(get_lang('AddCategory'));
7232
        $form->addSelectFromCollection('parent', get_lang('Parent'), $categories, [], true, 'getNodeName');
7233
        $form->addText('name', get_lang('Name'));
7234
7235
        if ($category) {
7236
            $form->addButtonUpdate(get_lang('Update'));
7237
        } else {
7238
            $form->addButtonSave(get_lang('Save'));
7239
        }
7240
7241
        if ($form->validate()) {
7242
            $values = $form->exportValues();
7243
            $parent = $categoryRepo->find($values['parent']);
7244
7245
            if (!$category) {
7246
                $category = (new CWikiCategory())
7247
                    ->setCourse($course)
7248
                    ->setSession($session)
7249
                ;
7250
7251
                $em->persist($category);
7252
7253
                Display::addFlash(
7254
                    Display::return_message(get_lang('CategoryAdded'), 'success')
7255
                );
7256
            } else {
7257
                Display::addFlash(
7258
                    Display::return_message(get_lang('CategoryEdited'), 'success')
7259
                );
7260
            }
7261
7262
            $category
7263
                ->setName($values['name'])
7264
                ->setParent($parent)
7265
            ;
7266
7267
            $em->flush();
7268
7269
            header('Location: index.php?'.api_get_cidreq().'&action=category');
7270
            exit;
7271
        }
7272
7273
        if ($category) {
7274
            $form->setDefaults([
7275
                'parent' => $category->getParent() ? $category->getParent()->getId() : 0,
7276
                'name' => $category->getName(),
7277
            ]);
7278
        }
7279
7280
        return $form;
7281
    }
7282
7283
    private static function assignCategoriesToWiki(CWiki $wiki, array $categoriesIdList)
7284
    {
7285
        if (true !== api_get_configuration_value('wiki_categories_enabled')) {
7286
            return;
7287
        }
7288
7289
        $em = Database::getManager();
7290
7291
        foreach ($categoriesIdList as $categoryId) {
7292
            $category = $em->find(CWikiCategory::class, $categoryId);
7293
            $wiki->addCategory($category);
7294
        }
7295
7296
        $em->flush();
7297
    }
7298
}
7299