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

Wiki::createCategoryForm()   B

Complexity

Conditions 9
Paths 8

Size

Total Lines 70
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 44
c 0
b 0
f 0
dl 0
loc 70
rs 7.6604
cc 9
nop 1
nc 8

How to fix   Long Method   

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