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

Wiki::check_notify_page()   B

Complexity

Conditions 11
Paths 40

Size

Total Lines 71
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 50
c 1
b 0
f 0
dl 0
loc 71
rs 7.3166
cc 11
nc 40
nop 1

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use ChamiloSession as Session;
6
use Doctrine\DBAL\Driver\Statement;
7
8
/**
9
 * Class Wiki
10
 * Functions library for the wiki tool.
11
 *
12
 * @author Juan Carlos Raña <[email protected]>
13
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
14
 * @author Julio Montoya <[email protected]> using the pdf.lib.php library
15
 */
16
class Wiki
17
{
18
    public $tbl_wiki;
19
    public $tbl_wiki_discuss;
20
    public $tbl_wiki_mailcue;
21
    public $tbl_wiki_conf;
22
    public $session_id = null;
23
    public $course_id = null;
24
    public $condition_session = null;
25
    public $group_id;
26
    public $assig_user_id;
27
    public $groupfilter = 'group_id=0';
28
    public $courseInfo;
29
    public $charset;
30
    public $page;
31
    public $action;
32
    public $wikiData = [];
33
    public $url;
34
35
    /**
36
     * Constructor.
37
     */
38
    public function __construct()
39
    {
40
        // Database table definition
41
        $this->tbl_wiki = Database::get_course_table(TABLE_WIKI);
42
        $this->tbl_wiki_discuss = Database::get_course_table(
43
            TABLE_WIKI_DISCUSS
44
        );
45
        $this->tbl_wiki_mailcue = Database::get_course_table(
46
            TABLE_WIKI_MAILCUE
47
        );
48
        $this->tbl_wiki_conf = Database::get_course_table(TABLE_WIKI_CONF);
49
50
        $this->session_id = api_get_session_id();
51
        $this->condition_session = api_get_session_condition($this->session_id);
52
        $this->course_id = api_get_course_int_id();
53
        $this->group_id = api_get_group_id();
54
55
        if (!empty($this->group_id)) {
56
            $this->groupfilter = ' group_id="'.$this->group_id.'"';
57
        }
58
        $this->courseInfo = api_get_course_info();
59
        $this->url = api_get_path(WEB_CODE_PATH).'wiki/index.php?'.api_get_cidreq();
60
    }
61
62
    /**
63
     * Check whether this title is already used.
64
     *
65
     * @param string $link
66
     *
67
     * @return bool False if title is already taken
68
     *
69
     * @author Patrick Cool <[email protected]>, Ghent University
70
     */
71
    public function checktitle($link)
72
    {
73
        $tbl_wiki = $this->tbl_wiki;
74
        $condition_session = $this->condition_session;
75
        $course_id = $this->course_id;
76
        $groupfilter = $this->groupfilter;
77
78
        $sql = 'SELECT * FROM '.$tbl_wiki.'
79
                WHERE
80
                    c_id = '.$course_id.' AND
81
                    reflink="'.Database::escape_string($link).'" AND
82
                    '.$groupfilter.$condition_session.'';
83
        $result = Database::query($sql);
84
        $num = Database::num_rows($result);
85
        // the value has not been found and is this available
86
        if ($num == 0) {
87
            return true;
88
        }
89
90
        return false;
91
    }
92
93
    /**
94
     * check wikilinks that has a page.
95
     *
96
     * @author Juan Carlos Raña <[email protected]>
97
     *
98
     * @param string $input
99
     *
100
     * @return string
101
     */
102
    public function links_to($input)
103
    {
104
        $input_array = preg_split(
105
            "/(\[\[|\]\])/",
106
            $input,
107
            -1,
108
            PREG_SPLIT_DELIM_CAPTURE
109
        );
110
        $all_links = [];
111
112
        foreach ($input_array as $key => $value) {
113
            if (isset($input_array[$key - 1]) && $input_array[$key - 1] == '[[' &&
114
                isset($input_array[$key + 1]) && $input_array[$key + 1] == ']]'
115
            ) {
116
                if (api_strpos($value, "|") !== false) {
117
                    $full_link_array = explode("|", $value);
118
                    $link = trim($full_link_array[0]);
119
                    $title = trim($full_link_array[1]);
120
                } else {
121
                    $link = trim($value);
122
                    $title = trim($value);
123
                }
124
                unset($input_array[$key - 1]);
125
                unset($input_array[$key + 1]);
126
                //replace blank spaces by _ within the links. But to remove links at the end add a blank space
127
                $all_links[] = Database::escape_string(
128
                    str_replace(' ', '_', $link)
129
                ).' ';
130
            }
131
        }
132
133
        return implode($all_links);
134
    }
135
136
    /**
137
     * detect and add style to external links.
138
     *
139
     * @author Juan Carlos Raña Trabado
140
     */
141
    public function detect_external_link($input)
142
    {
143
        $exlink = 'href=';
144
        $exlinkStyle = 'class="wiki_link_ext" href=';
145
146
        return str_replace($exlink, $exlinkStyle, $input);
147
    }
148
149
    /**
150
     * detect and add style to anchor links.
151
     *
152
     * @author Juan Carlos Raña Trabado
153
     */
154
    public function detect_anchor_link($input)
155
    {
156
        $anchorlink = 'href="#';
157
        $anchorlinkStyle = 'class="wiki_anchor_link" href="#';
158
        $output = str_replace($anchorlink, $anchorlinkStyle, $input);
159
160
        return $output;
161
    }
162
163
    /**
164
     * detect and add style to mail links
165
     * author Juan Carlos Raña Trabado.
166
     */
167
    public function detect_mail_link($input)
168
    {
169
        $maillink = 'href="mailto';
170
        $maillinkStyle = 'class="wiki_mail_link" href="mailto';
171
        $output = str_replace($maillink, $maillinkStyle, $input);
172
173
        return $output;
174
    }
175
176
    /**
177
     * detect and add style to ftp links.
178
     *
179
     * @author Juan Carlos Raña Trabado
180
     */
181
    public function detect_ftp_link($input)
182
    {
183
        $ftplink = 'href="ftp';
184
        $ftplinkStyle = 'class="wiki_ftp_link" href="ftp';
185
        $output = str_replace($ftplink, $ftplinkStyle, $input);
186
187
        return $output;
188
    }
189
190
    /**
191
     * detect and add style to news links.
192
     *
193
     * @author Juan Carlos Raña Trabado
194
     */
195
    public function detect_news_link($input)
196
    {
197
        $newslink = 'href="news';
198
        $newslinkStyle = 'class="wiki_news_link" href="news';
199
        $output = str_replace($newslink, $newslinkStyle, $input);
200
201
        return $output;
202
    }
203
204
    /**
205
     * detect and add style to irc links.
206
     *
207
     * @author Juan Carlos Raña Trabado
208
     */
209
    public function detect_irc_link($input)
210
    {
211
        $irclink = 'href="irc';
212
        $irclinkStyle = 'class="wiki_irc_link" href="irc';
213
        $output = str_replace($irclink, $irclinkStyle, $input);
214
215
        return $output;
216
    }
217
218
    /**
219
     * This function allows users to have [link to a title]-style links like in most regular wikis.
220
     * It is true that the adding of links is probably the most anoying part of Wiki for the people
221
     * who know something about the wiki syntax.
222
     *
223
     * @author Patrick Cool <[email protected]>, Ghent University
224
     * Improvements [[]] and [[ | ]]by Juan Carlos Raña
225
     * Improvements internal wiki style and mark group by Juan Carlos Raña
226
     */
227
    public function make_wiki_link_clickable($input)
228
    {
229
        $groupId = api_get_group_id();
230
        //now doubles brackets
231
        $input_array = preg_split(
232
            "/(\[\[|\]\])/",
233
            $input,
234
            -1,
235
            PREG_SPLIT_DELIM_CAPTURE
236
        );
237
238
        foreach ($input_array as $key => $value) {
239
            //now doubles brackets
240
            if (isset($input_array[$key - 1]) &&
241
                $input_array[$key - 1] == '[[' && $input_array[$key + 1] == ']]'
242
            ) {
243
                // now full wikilink
244
                if (api_strpos($value, "|") !== false) {
245
                    $full_link_array = explode("|", $value);
246
                    $link = trim(strip_tags($full_link_array[0]));
247
                    $title = trim($full_link_array[1]);
248
                } else {
249
                    $link = trim(strip_tags($value));
250
                    $title = trim($value);
251
                }
252
253
                //if wikilink is homepage
254
                if ($link == 'index') {
255
                    $title = get_lang('DefaultTitle');
256
                }
257
                if ($link == get_lang('DefaultTitle')) {
258
                    $link = 'index';
259
                }
260
261
                // 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
262
                if (self::checktitle(
263
                    strtolower(str_replace(' ', '_', $link))
264
                )) {
265
                    $link = api_html_entity_decode($link);
266
                    $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>';
267
                } else {
268
                    $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>';
269
                }
270
                unset($input_array[$key - 1]);
271
                unset($input_array[$key + 1]);
272
            }
273
        }
274
        $output = implode('', $input_array);
275
276
        return $output;
277
    }
278
279
    /**
280
     * This function saves a change in a wiki page.
281
     *
282
     * @author Patrick Cool <[email protected]>, Ghent University
283
     *
284
     * @param array $values
285
     *
286
     * @return string
287
     */
288
    public function save_wiki($values)
289
    {
290
        $tbl_wiki = $this->tbl_wiki;
291
        $tbl_wiki_conf = $this->tbl_wiki_conf;
292
293
        $_course = $this->courseInfo;
294
        $time = api_get_utc_datetime();
295
        $session_id = api_get_session_id();
296
        $groupId = api_get_group_id();
297
        $userId = api_get_user_id();
298
        $groupInfo = GroupManager::get_group_properties($groupId);
299
        $course_id = api_get_course_int_id();
300
301
        $_clean = [
302
            'task' => '',
303
            'feedback1' => '',
304
            'feedback2' => '',
305
            'feedback3' => '',
306
            'fprogress1' => '',
307
            'fprogress2' => '',
308
            'fprogress3' => '',
309
            'max_text' => 0,
310
            'max_version' => 0,
311
            'delayedsubmit' => '',
312
            'assignment' => 0,
313
        ];
314
315
        $pageId = intval($values['page_id']);
316
317
        // NOTE: visibility, visibility_disc and ratinglock_disc changes
318
        // are not made here, but through the interce buttons
319
320
        // cleaning the variables
321
        if (api_get_setting('htmlpurifier_wiki') == 'true') {
322
            //$purifier = new HTMLPurifier();
323
            $values['content'] = Security::remove_XSS($values['content']);
324
        }
325
        $version = intval($values['version']) + 1;
326
        $linkTo = self::links_to($values['content']); //and check links content
327
328
        //cleaning config variables
329
        if (!empty($values['task'])) {
330
            $_clean['task'] = $values['task'];
331
        }
332
333
        if (!empty($values['feedback1']) ||
334
            !empty($values['feedback2']) ||
335
            !empty($values['feedback3'])
336
        ) {
337
            $_clean['feedback1'] = $values['feedback1'];
338
            $_clean['feedback2'] = $values['feedback2'];
339
            $_clean['feedback3'] = $values['feedback3'];
340
            $_clean['fprogress1'] = $values['fprogress1'];
341
            $_clean['fprogress2'] = $values['fprogress2'];
342
            $_clean['fprogress3'] = $values['fprogress3'];
343
        }
344
345
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
346
            $_clean['startdate_assig'] = $values['startdate_assig'];
347
        } else {
348
            $_clean['startdate_assig'] = null;
349
        }
350
351
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
352
            $_clean['enddate_assig'] = $values['enddate_assig'];
353
        } else {
354
            $_clean['enddate_assig'] = null;
355
        }
356
357
        if (isset($values['delayedsubmit'])) {
358
            $_clean['delayedsubmit'] = $values['delayedsubmit'];
359
        }
360
361
        if (!empty($values['max_text']) || !empty($values['max_version'])) {
362
            $_clean['max_text'] = $values['max_text'];
363
            $_clean['max_version'] = $values['max_version'];
364
        }
365
366
        $values['assignment'] = $values['assignment'] ?? 0;
367
        $values['page_id'] = $values['page_id'] ?? 0;
368
369
        $params = [
370
            'c_id' => $course_id,
371
            'addlock' => 1,
372
            'visibility' => 1,
373
            'visibility_disc' => 1,
374
            'addlock_disc' => 1,
375
            'ratinglock_disc' => 1,
376
            'page_id' => $pageId,
377
            'reflink' => trim($values['reflink']),
378
            'title' => trim($values['title']),
379
            'content' => $values['content'],
380
            'user_id' => $userId,
381
            'group_id' => $groupId,
382
            'dtime' => $time,
383
            'assignment' => $values['assignment'],
384
            'comment' => $values['comment'],
385
            'progress' => $values['progress'],
386
            'version' => $version,
387
            'linksto' => $linkTo,
388
            'user_ip' => $_SERVER['REMOTE_ADDR'],
389
            'session_id' => $session_id,
390
            'page_id' => $values['page_id'],
391
            'editlock' => 0,
392
            'is_editing' => 0,
393
            'time_edit' => $time,
394
            'tag' => '',
395
        ];
396
397
        $id = Database::insert($tbl_wiki, $params);
398
399
        if ($id > 0) {
400
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
401
            Database::query($sql);
402
403
            // insert into item_property
404
            api_item_property_update(
405
                $_course,
406
                TOOL_WIKI,
407
                $id,
408
                'WikiAdded',
409
                $userId,
410
                $groupInfo
411
            );
412
413
            if ($values['page_id'] == 0) {
414
                $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
415
                        WHERE c_id = '.$course_id.' AND iid ="'.$id.'"';
416
                Database::query($sql);
417
            }
418
        }
419
420
        // Update wiki config
421
        if ($values['reflink'] == 'index' && $version == 1) {
422
            $params = [
423
                'c_id' => $course_id,
424
                'page_id' => $id,
425
                'task' => $_clean['task'],
426
                'feedback1' => $_clean['feedback1'],
427
                'feedback2' => $_clean['feedback2'],
428
                'feedback3' => $_clean['feedback3'],
429
                'fprogress1' => $_clean['fprogress1'],
430
                'fprogress2' => $_clean['fprogress2'],
431
                'fprogress3' => $_clean['fprogress3'],
432
                'max_text' => intval($_clean['max_text']),
433
                'max_version' => intval($_clean['max_version']),
434
                'startdate_assig' => $_clean['startdate_assig'],
435
                'enddate_assig' => $_clean['enddate_assig'],
436
                'delayedsubmit' => $_clean['delayedsubmit'],
437
            ];
438
            Database::insert($tbl_wiki_conf, $params);
439
        } else {
440
            $params = [
441
                'task' => $_clean['task'],
442
                'feedback1' => $_clean['feedback1'],
443
                'feedback2' => $_clean['feedback2'],
444
                'feedback3' => $_clean['feedback3'],
445
                'fprogress1' => $_clean['fprogress1'],
446
                'fprogress2' => $_clean['fprogress2'],
447
                'fprogress3' => $_clean['fprogress3'],
448
                'max_text' => intval($_clean['max_text']),
449
                'max_version' => intval($_clean['max_version']),
450
                'startdate_assig' => $_clean['startdate_assig'],
451
                'enddate_assig' => $_clean['enddate_assig'],
452
                'delayedsubmit' => $_clean['delayedsubmit'],
453
            ];
454
            Database::update(
455
                $tbl_wiki_conf,
456
                $params,
457
                ['page_id = ? AND c_id = ?' => [$pageId, $course_id]]
458
            );
459
        }
460
461
        api_item_property_update(
462
            $_course,
463
            'wiki',
464
            $id,
465
            'WikiAdded',
466
            $userId,
467
            $groupInfo
468
        );
469
        self::check_emailcue($_clean['reflink'], 'P', $time, $userId);
470
        $this->setWikiData($id);
471
472
        return get_lang('Saved');
473
    }
474
475
    /**
476
     * This function restore a wikipage.
477
     *
478
     * @author Juan Carlos Raña <[email protected]>
479
     *
480
     * @return string Message of success (to be printed on screen)
481
     */
482
    public function restore_wikipage(
483
        $r_page_id,
484
        $r_reflink,
485
        $r_title,
486
        $r_content,
487
        $r_group_id,
488
        $r_assignment,
489
        $r_progress,
490
        $c_version,
491
        $r_version,
492
        $r_linksto
493
    ) {
494
        $tbl_wiki = $this->tbl_wiki;
495
        $_course = $this->courseInfo;
496
        $r_user_id = api_get_user_id();
497
        $r_dtime = api_get_utc_datetime();
498
        $r_version = $r_version + 1;
499
        $r_comment = get_lang('RestoredFromVersion').': '.$c_version;
500
        $session_id = api_get_session_id();
501
        $course_id = api_get_course_int_id();
502
        $groupInfo = GroupManager::get_group_properties($r_group_id);
503
504
        $params = [
505
            'c_id' => $course_id,
506
            'page_id' => $r_page_id,
507
            'reflink' => $r_reflink,
508
            'title' => $r_title,
509
            'content' => $r_content,
510
            'user_id' => $r_user_id,
511
            'group_id' => $r_group_id,
512
            'dtime' => $r_dtime,
513
            'assignment' => $r_assignment,
514
            'comment' => $r_comment,
515
            'progress' => $r_progress,
516
            'version' => $r_version,
517
            'linksto' => $r_linksto,
518
            'user_ip' => $_SERVER['REMOTE_ADDR'],
519
            'session_id' => $session_id,
520
        ];
521
        $id = Database::insert($tbl_wiki, $params);
522
523
        if ($id) {
524
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
525
            Database::query($sql);
526
527
            api_item_property_update(
528
                $_course,
529
                'wiki',
530
                $id,
531
                'WikiAdded',
532
                api_get_user_id(),
533
                $groupInfo
534
            );
535
            self::check_emailcue($r_reflink, 'P', $r_dtime, $r_user_id);
536
        }
537
538
        return get_lang('PageRestored');
539
    }
540
541
    /**
542
     * This function delete a wiki.
543
     *
544
     * @author Juan Carlos Raña <[email protected]>
545
     *
546
     * @return string Message of success (to be printed)
547
     */
548
    public function delete_wiki()
549
    {
550
        $tbl_wiki = $this->tbl_wiki;
551
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
552
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
553
        $tbl_wiki_conf = $this->tbl_wiki_conf;
554
        $conditionSession = $this->condition_session;
555
        $groupFilter = $this->groupfilter;
556
        $course_id = $this->course_id;
557
558
        $sql = "SELECT page_id FROM $tbl_wiki
559
                WHERE c_id = $course_id AND $groupFilter $conditionSession
560
                ORDER BY id DESC";
561
562
        $result = Database::query($sql);
563
        $pageList = Database::store_result($result);
564
        if ($pageList) {
565
            foreach ($pageList as $pageData) {
566
                $pageId = $pageData['page_id'];
567
                $sql = "DELETE FROM $tbl_wiki_conf
568
                        WHERE c_id = $course_id AND page_id = $pageId";
569
                Database::query($sql);
570
571
                $sql = "DELETE FROM $tbl_wiki_discuss
572
                        WHERE c_id = $course_id AND publication_id = $pageId";
573
                Database::query($sql);
574
            }
575
        }
576
577
        $sql = "DELETE FROM $tbl_wiki_mailcue
578
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
579
        Database::query($sql);
580
581
        $sql = "DELETE FROM $tbl_wiki
582
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
583
        Database::query($sql);
584
585
        return get_lang('WikiDeleted');
586
    }
587
588
    /**
589
     * This function saves a new wiki page.
590
     *
591
     * @author Patrick Cool <[email protected]>, Ghent University
592
     *
593
     * @todo consider merging this with the function save_wiki into one single function.
594
     */
595
    private function save_new_wiki($values)
596
    {
597
        $tbl_wiki = $this->tbl_wiki;
598
        $tbl_wiki_conf = $this->tbl_wiki_conf;
599
        $assig_user_id = $this->assig_user_id;
600
        $_clean = [];
601
602
        // cleaning the variables
603
        $_clean['assignment'] = '';
604
        if (isset($values['assignment'])) {
605
            $_clean['assignment'] = $values['assignment'];
606
        }
607
608
        // session_id
609
        $session_id = api_get_session_id();
610
        // Unlike ordinary pages of pages of assignments.
611
        // Allow create a ordinary page although there is a assignment with the same name
612
        if ($_clean['assignment'] == 2 || $_clean['assignment'] == 1) {
613
            $page = str_replace(
614
                ' ',
615
                '_',
616
                $values['title']."_uass".$assig_user_id
617
            );
618
        } else {
619
            $page = str_replace(' ', '_', $values['title']);
620
        }
621
        $_clean['reflink'] = $page;
622
        $_clean['title'] = trim($values['title']);
623
        $_clean['content'] = $values['content'];
624
625
        if (api_get_setting('htmlpurifier_wiki') === 'true') {
626
            $purifier = new HTMLPurifier();
627
            $_clean['content'] = $purifier->purify($_clean['content']);
628
        }
629
630
        //re-check after strip_tags if the title is empty
631
        if (empty($_clean['title']) || empty($_clean['reflink'])) {
632
            return false;
633
        }
634
635
        if ($_clean['assignment'] == 2) {
636
            //config by default for individual assignment (students)
637
            //Identifies the user as a creator, not the teacher who created
638
            $_clean['user_id'] = intval($assig_user_id);
639
            $_clean['visibility'] = 0;
640
            $_clean['visibility_disc'] = 0;
641
            $_clean['ratinglock_disc'] = 0;
642
        } else {
643
            $_clean['user_id'] = api_get_user_id();
644
            $_clean['visibility'] = 1;
645
            $_clean['visibility_disc'] = 1;
646
            $_clean['ratinglock_disc'] = 1;
647
        }
648
649
        $_clean['comment'] = $values['comment'];
650
        $_clean['progress'] = $values['progress'];
651
        $_clean['version'] = 1;
652
653
        $groupId = api_get_group_id();
654
        $groupInfo = GroupManager::get_group_properties($groupId);
655
656
        //check wikilinks
657
        $_clean['linksto'] = self::links_to($_clean['content']);
658
659
        // cleaning config variables
660
        $_clean['task'] = $values['task'] ?? '';
661
        $_clean['feedback1'] = $values['feedback1'] ?? '';
662
        $_clean['feedback2'] = $values['feedback2'] ?? '';
663
        $_clean['feedback3'] = $values['feedback3'] ?? '';
664
        $_clean['fprogress1'] = $values['fprogress1'] ?? '';
665
        $_clean['fprogress2'] = $values['fprogress2'] ?? '';
666
        $_clean['fprogress3'] = $values['fprogress3'] ?? '';
667
668
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
669
            $_clean['startdate_assig'] = $values['startdate_assig'];
670
        } else {
671
            $_clean['startdate_assig'] = null;
672
        }
673
674
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
675
            $_clean['enddate_assig'] = $values['enddate_assig'];
676
        } else {
677
            $_clean['enddate_assig'] = null;
678
        }
679
680
        $_clean['delayedsubmit'] = $values['delayedsubmit'] ?? '';
681
        $_clean['max_text'] = $values['max_text'] ?? '';
682
        $_clean['max_version'] = $values['max_version'] ?? '';
683
684
        $course_id = api_get_course_int_id();
685
686
        // Filter no _uass
687
        if (api_strtoupper(trim($values['title'])) === 'INDEX') {
688
            Display::addFlash(
689
                Display::return_message(
690
                    get_lang('GoAndEditMainPage'),
691
                    'warning',
692
                    false
693
                )
694
            );
695
        } else {
696
            $var = $_clean['reflink'];
697
            $group_id = intval($_GET['group_id']);
698
            if (!self::checktitle($var)) {
699
                return get_lang('WikiPageTitleExist').
700
                    '<a href="index.php?action=edit&title='.$var.'&group_id='.$group_id.'">'.
701
                    $values['title'].'</a>';
702
            } else {
703
                $dtime = api_get_utc_datetime();
704
705
                $params = [
706
                    'c_id' => $course_id,
707
                    'reflink' => $_clean['reflink'],
708
                    'title' => $_clean['title'],
709
                    'content' => $_clean['content'],
710
                    'user_id' => $_clean['user_id'],
711
                    'group_id' => $groupId,
712
                    'dtime' => $dtime,
713
                    'visibility' => $_clean['visibility'],
714
                    'visibility_disc' => $_clean['visibility_disc'],
715
                    'ratinglock_disc' => $_clean['ratinglock_disc'],
716
                    'assignment' => $_clean['assignment'],
717
                    'comment' => $_clean['comment'],
718
                    'progress' => $_clean['progress'],
719
                    'version' => $_clean['version'],
720
                    'linksto' => $_clean['linksto'],
721
                    'user_ip' => $_SERVER['REMOTE_ADDR'],
722
                    'session_id' => $session_id,
723
                    'addlock_disc' => 1,
724
                ];
725
                $id = Database::insert($tbl_wiki, $params);
726
                if ($id > 0) {
727
                    $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
728
                    Database::query($sql);
729
730
                    //insert into item_property
731
                    api_item_property_update(
732
                        api_get_course_info(),
733
                        TOOL_WIKI,
734
                        $id,
735
                        'WikiAdded',
736
                        api_get_user_id(),
737
                        $groupInfo
738
                    );
739
740
                    $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
741
                            WHERE c_id = '.$course_id.' AND id = "'.$id.'"';
742
                    Database::query($sql);
743
744
                    // insert wiki config
745
                    $params = [
746
                        'c_id' => $course_id,
747
                        'page_id' => $id,
748
                        'task' => $_clean['task'],
749
                        'feedback1' => $_clean['feedback1'],
750
                        'feedback2' => $_clean['feedback2'],
751
                        'feedback3' => $_clean['feedback3'],
752
                        'fprogress1' => $_clean['fprogress1'],
753
                        'fprogress2' => $_clean['fprogress2'],
754
                        'fprogress3' => $_clean['fprogress3'],
755
                        'max_text' => $_clean['max_text'],
756
                        'max_version' => $_clean['max_version'],
757
                        'startdate_assig' => $_clean['startdate_assig'],
758
                        'enddate_assig' => $_clean['enddate_assig'],
759
                        'delayedsubmit' => $_clean['delayedsubmit'],
760
                    ];
761
762
                    Database::insert($tbl_wiki_conf, $params);
763
764
                    $this->setWikiData($id);
765
                    self::check_emailcue(0, 'A');
766
767
                    return get_lang('NewWikiSaved');
768
                }
769
            }
770
        }
771
    }
772
773
    public function setForm(FormValidator $form, array $row = [])
774
    {
775
        $toolBar = api_is_allowed_to_edit(null, true)
776
            ? [
777
                'ToolbarSet' => 'Wiki',
778
                'Width' => '100%',
779
                'Height' => '400',
780
            ]
781
            : [
782
                'ToolbarSet' => 'WikiStudent',
783
                'Width' => '100%',
784
                'Height' => '400',
785
                'UserStatus' => 'student',
786
            ];
787
788
        $form->addHtmlEditor(
789
            'content',
790
            get_lang('Content'),
791
            false,
792
            false,
793
            $toolBar
794
        );
795
        //$content
796
        $form->addElement('text', 'comment', get_lang('Comments'));
797
        $progress = ['', 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
798
799
        $form->addElement(
800
            'select',
801
            'progress',
802
            get_lang('Progress'),
803
            $progress
804
        );
805
806
        if ((api_is_allowed_to_edit(false, true) ||
807
            api_is_platform_admin()) &&
808
            isset($row['reflink']) && $row['reflink'] != 'index'
809
        ) {
810
            $form->addElement(
811
                'advanced_settings',
812
                'advanced_params',
813
                get_lang('AdvancedParameters')
814
            );
815
            $form->addElement(
816
                'html',
817
                '<div id="advanced_params_options" style="display:none">'
818
            );
819
820
            $form->addHtmlEditor(
821
                'task',
822
                get_lang('DescriptionOfTheTask'),
823
                false,
824
                false,
825
                [
826
                    'ToolbarSet' => 'wiki_task',
827
                    'Width' => '100%',
828
                    'Height' => '200',
829
                ]
830
            );
831
832
            $form->addElement('label', null, get_lang('AddFeedback'));
833
            $form->addElement('textarea', 'feedback1', get_lang('Feedback1'));
834
            $form->addElement(
835
                'select',
836
                'fprogress1',
837
                get_lang('FProgress'),
838
                $progress
839
            );
840
841
            $form->addElement('textarea', 'feedback2', get_lang('Feedback2'));
842
            $form->addElement(
843
                'select',
844
                'fprogress2',
845
                get_lang('FProgress'),
846
                $progress
847
            );
848
849
            $form->addElement('textarea', 'feedback3', get_lang('Feedback3'));
850
            $form->addElement(
851
                'select',
852
                'fprogress3',
853
                get_lang('FProgress'),
854
                $progress
855
            );
856
857
            $form->addElement(
858
                'checkbox',
859
                'initstartdate',
860
                null,
861
                get_lang('StartDate'),
862
                ['id' => 'start_date_toggle']
863
            );
864
865
            $style = "display:block";
866
            $row['initstartdate'] = 1;
867
            if (empty($row['startdate_assig'])) {
868
                $style = "display:none";
869
                $row['initstartdate'] = null;
870
            }
871
872
            $form->addElement(
873
                'html',
874
                '<div id="start_date" style="'.$style.'">'
875
            );
876
            $form->addDatePicker('startdate_assig', '');
877
            $form->addElement('html', '</div>');
878
            $form->addElement(
879
                'checkbox',
880
                'initenddate',
881
                null,
882
                get_lang('EndDate'),
883
                ['id' => 'end_date_toggle']
884
            );
885
886
            $style = "display:block";
887
            $row['initenddate'] = 1;
888
            if (empty($row['enddate_assig'])) {
889
                $style = "display:none";
890
                $row['initenddate'] = null;
891
            }
892
893
            $form->addHtml('<div id="end_date" style="'.$style.'">');
894
            $form->addDatePicker('enddate_assig', '');
895
            $form->addHtml('</div>');
896
            $form->addElement(
897
                'checkbox',
898
                'delayedsubmit',
899
                null,
900
                get_lang('AllowLaterSends')
901
            );
902
            $form->addElement('text', 'max_text', get_lang('NMaxWords'));
903
            $form->addElement('text', 'max_version', get_lang('NMaxVersion'));
904
            $form->addElement(
905
                'checkbox',
906
                'assignment',
907
                null,
908
                get_lang('CreateAssignmentPage')
909
            );
910
            $form->addElement('html', '</div>');
911
        }
912
913
        $form->addElement('hidden', 'page_id');
914
        $form->addElement('hidden', 'reflink');
915
        $form->addElement('hidden', 'version');
916
        $form->addElement('hidden', 'wpost_id', api_get_unique_id());
917
    }
918
919
    /**
920
     * This function displays the form for adding a new wiki page.
921
     *
922
     * @author Patrick Cool <[email protected]>, Ghent University
923
     *
924
     * @return string html code
925
     */
926
    public function display_new_wiki_form()
927
    {
928
        $url = api_get_self().'?'.api_get_cidreq(
929
            ).'&action=addnew&group_id='.api_get_group_id();
930
        $form = new FormValidator('wiki_new', 'post', $url);
931
        $form->addElement('text', 'title', get_lang('Title'));
932
        $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
933
        self::setForm($form);
934
        $title = isset($_GET['title']) ? Security::remove_XSS(
935
            $_GET['title']
936
        ) : '';
937
        $form->setDefaults(['title' => $title]);
938
        $form->addButtonSave(get_lang('Save'), 'SaveWikiNew');
939
        $form->display();
940
941
        if ($form->validate()) {
942
            $values = $form->exportValues();
943
            if (isset($values['startdate_assig']) &&
944
                isset($values['enddate_assig']) &&
945
                strtotime($values['startdate_assig']) > strtotime(
946
                    $values['enddate_assig']
947
                )
948
            ) {
949
                Display::addFlash(
950
                    Display::return_message(
951
                        get_lang("EndDateCannotBeBeforeTheStartDate"),
952
                        'error',
953
                        false
954
                    )
955
                );
956
            } elseif (!self::double_post($_POST['wpost_id'])) {
957
                //double post
958
            } else {
959
                if (isset($values['assignment']) && $values['assignment'] == 1) {
960
                    self::auto_add_page_users($values);
961
                }
962
963
                $return_message = $this->save_new_wiki($values);
964
965
                if ($return_message == false) {
966
                    Display::addFlash(
967
                        Display::return_message(
968
                            get_lang('NoWikiPageTitle'),
969
                            'error',
970
                            false
971
                        )
972
                    );
973
                } else {
974
                    Display::addFlash(
975
                        Display::return_message(
976
                            $return_message,
977
                            'confirmation',
978
                            false
979
                        )
980
                    );
981
                }
982
983
                $wikiData = self::getWikiData();
984
                $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq();
985
                header('Location: '.$redirectUrl);
986
                exit;
987
            }
988
        }
989
    }
990
991
    /**
992
     * This function displays a wiki entry.
993
     *
994
     * @author Patrick Cool <[email protected]>, Ghent University
995
     * @author Juan Carlos Raña Trabado
996
     */
997
    public function display_wiki_entry(string $newtitle)
998
    {
999
        $tblWiki = $this->tbl_wiki;
1000
        $tblWikiConf = $this->tbl_wiki_conf;
1001
        $conditionSession = $this->condition_session;
1002
        $groupfilter = $this->groupfilter;
1003
        $page = $this->page;
1004
1005
        $sessionId = api_get_session_id();
1006
        $courseId = api_get_course_int_id();
1007
1008
        if ($newtitle) {
1009
            $pageMIX = $newtitle; //display the page after it is created
1010
        } else {
1011
            $pageMIX = $page; //display current page
1012
        }
1013
1014
        $filter = null;
1015
        if (isset($_GET['view']) && $_GET['view']) {
1016
            $_clean['view'] = Database::escape_string($_GET['view']);
1017
            $filter = ' AND w.id="'.$_clean['view'].'"';
1018
        }
1019
1020
        // First, check page visibility in the first page version
1021
        $sql = 'SELECT * FROM '.$tblWiki.'
1022
                WHERE
1023
                    c_id = '.$courseId.' AND
1024
                    reflink = "'.Database::escape_string($pageMIX).'" AND
1025
                   '.$groupfilter.$conditionSession.'
1026
                ORDER BY id';
1027
        $result = Database::query($sql);
1028
        $row = Database::fetch_array($result, 'ASSOC');
1029
1030
        $KeyVisibility = null;
1031
        if ($KeyVisibility) {
1032
            $KeyVisibility = $row['visibility'];
1033
        }
1034
1035
        // second, show the last version
1036
        $sql = 'SELECT * FROM '.$tblWiki.' w
1037
            INNER JOIN '.$tblWikiConf.' wc
1038
            ON (wc.page_id = w.page_id AND wc.c_id = w.c_id)
1039
            WHERE
1040
                w.c_id = '.$courseId.' AND
1041
                w.reflink = "'.Database::escape_string($pageMIX).'" AND
1042
                w.session_id = '.$sessionId.' AND
1043
                w.'.$groupfilter.'  '.$filter.'
1044
            ORDER BY id DESC';
1045
1046
        $result = Database::query($sql);
1047
        // we do not need awhile loop since we are always displaying the last version
1048
        $row = Database::fetch_array($result, 'ASSOC');
1049
1050
        //log users access to wiki (page_id)
1051
        if (!empty($row['page_id'])) {
1052
            Event::addEvent(LOG_WIKI_ACCESS, LOG_WIKI_PAGE_ID, $row['page_id']);
1053
        }
1054
        //update visits
1055
        if ($row && $row['id']) {
1056
            $sql = 'UPDATE '.$tblWiki.' SET hits=(hits+1)
1057
                WHERE c_id = '.$courseId.' AND id='.$row['id'];
1058
            Database::query($sql);
1059
        }
1060
1061
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1062
1063
        // if both are empty, and we are displaying the index page then we display the default text.
1064
        if (!$row || ($row['content'] == '' && $row['title'] == '' && $page == 'index')) {
1065
            if (api_is_allowed_to_edit(false, true) ||
1066
                api_is_platform_admin() ||
1067
                GroupManager::is_user_in_group(api_get_user_id(), $groupInfo) ||
1068
                api_is_allowed_in_course()
1069
            ) {
1070
                //Table structure for better export to pdf
1071
                $default_table_for_content_Start = '<div class="text-center">';
1072
                $default_table_for_content_End = '</div>';
1073
                $content = $default_table_for_content_Start.
1074
                    sprintf(
1075
                        get_lang('DefaultContent'),
1076
                        api_get_path(WEB_IMG_PATH)
1077
                    ).
1078
                    $default_table_for_content_End;
1079
                $title = get_lang('DefaultTitle');
1080
            } else {
1081
                Display::addFlash(
1082
                    Display::return_message(
1083
                        get_lang('WikiStandBy'),
1084
                        'normal',
1085
                        false
1086
                    )
1087
                );
1088
1089
                return;
1090
            }
1091
        } else {
1092
            if (true === api_get_configuration_value('wiki_html_strict_filtering')) {
1093
                $content = Security::remove_XSS($row['content'], COURSEMANAGERLOWSECURITY);
1094
            } else {
1095
                $content = Security::remove_XSS($row['content']);
1096
            }
1097
            $title = Security::remove_XSS($row['title']);
1098
        }
1099
1100
        if (self::wiki_exist($title)) {
1101
            //assignment mode: identify page type
1102
            $icon_assignment = null;
1103
            if ($row['assignment'] == 1) {
1104
                $icon_assignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'));
1105
            } elseif ($row['assignment'] == 2) {
1106
                $icon_assignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'));
1107
            }
1108
1109
            // task mode
1110
            $icon_task = null;
1111
            if (!empty($row['task'])) {
1112
                $icon_task = Display::return_icon('wiki_task.png', get_lang('StandardTask'));
1113
            }
1114
1115
            $pageTitle = $icon_assignment.PHP_EOL.$icon_task.'&nbsp;'.api_htmlentities($title);
1116
        } else {
1117
            $pageTitle = api_htmlentities($title);
1118
        }
1119
1120
        // Show page. Show page to all users if isn't hide page. Mode assignments: if student is the author, can view
1121
        if ($KeyVisibility != "1"
1122
            && !api_is_allowed_to_edit(false, true)
1123
            && !api_is_platform_admin()
1124
            && ($row['assignment'] != 2 || $KeyVisibility != "0" || api_get_user_id() != $row['user_id'])
1125
            && !api_is_allowed_in_course()
1126
        ) {
1127
            return;
1128
        }
1129
1130
        $actionsLeft = '';
1131
        $actionsRight = '';
1132
        // menu edit page
1133
        $editLink = '<a href="index.php?'.api_get_cidreq().'&action=edit&title='.api_htmlentities(urlencode($page)).'"'
1134
            .self::is_active_navigation_tab('edit').'>'
1135
            .Display::return_icon('edit.png', get_lang('EditThisPage'), [], ICON_SIZE_MEDIUM).'</a>';
1136
1137
        if (api_is_allowed_to_edit(false, true)) {
1138
            $actionsLeft .= $editLink;
1139
        } else {
1140
            if ((api_is_allowed_in_course() ||
1141
                GroupManager::is_user_in_group(
1142
                    api_get_user_id(),
1143
                    $groupInfo
1144
                ))
1145
            ) {
1146
                $actionsLeft .= $editLink;
1147
            } else {
1148
                $actionsLeft .= '';
1149
            }
1150
        }
1151
1152
        $pageProgress = 0;
1153
        $pageScore = 0;
1154
1155
        if ($row && $row['id']) {
1156
            $pageProgress = $row['progress'] * 10;
1157
            $pageScore = $row['score'];
1158
1159
            $protect_page = null;
1160
            $lock_unlock_protect = null;
1161
            // page action: protecting (locking) the page
1162
            if (api_is_allowed_to_edit(false, true) ||
1163
                api_is_platform_admin()
1164
            ) {
1165
                if (self::check_protect_page() == 1) {
1166
                    $protect_page = Display::return_icon(
1167
                        'lock.png',
1168
                        get_lang('PageLockedExtra'),
1169
                        [],
1170
                        ICON_SIZE_MEDIUM
1171
                    );
1172
                    $lock_unlock_protect = 'unlock';
1173
                } else {
1174
                    $protect_page = Display::return_icon(
1175
                        'unlock.png',
1176
                        get_lang('PageUnlockedExtra'),
1177
                        [],
1178
                        ICON_SIZE_MEDIUM
1179
                    );
1180
                    $lock_unlock_protect = 'lock';
1181
                }
1182
            }
1183
1184
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_protect
1185
                .'&title='.api_htmlentities(urlencode($page)).'">'.
1186
            $protect_page.'</a>';
1187
1188
            $visibility_page = null;
1189
            $lock_unlock_visibility = null;
1190
            //page action: visibility
1191
            if (api_is_allowed_to_edit(false, true) ||
1192
                api_is_platform_admin()
1193
            ) {
1194
                if (self::check_visibility_page() == 1) {
1195
                    $visibility_page = Display::return_icon(
1196
                        'visible.png',
1197
                        get_lang('ShowPageExtra'),
1198
                        [],
1199
                        ICON_SIZE_MEDIUM
1200
                    );
1201
                    $lock_unlock_visibility = 'invisible';
1202
                } else {
1203
                    $visibility_page = Display::return_icon(
1204
                        'invisible.png',
1205
                        get_lang('HidePageExtra'),
1206
                        [],
1207
                        ICON_SIZE_MEDIUM
1208
                    );
1209
                    $lock_unlock_visibility = 'visible';
1210
                }
1211
            }
1212
1213
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='
1214
                .$lock_unlock_visibility.'&title='.api_htmlentities(urlencode($page)).'">'.$visibility_page.'</a>';
1215
1216
            // Only available if row['id'] is set
1217
            //page action: notification
1218
            $lock_unlock_notify_page = '';
1219
1220
            if (api_is_allowed_to_session_edit()) {
1221
                if (self::check_notify_page($page) == 1) {
1222
                    $notify_page = Display::return_icon(
1223
                        'messagebox_info.png',
1224
                        get_lang('NotifyByEmail'),
1225
                        [],
1226
                        ICON_SIZE_MEDIUM
1227
                    );
1228
                    $lock_unlock_notify_page = 'unlocknotify';
1229
                } else {
1230
                    $notify_page = Display::return_icon(
1231
                        'mail.png',
1232
                        get_lang('CancelNotifyByEmail'),
1233
                        [],
1234
                        ICON_SIZE_MEDIUM
1235
                    );
1236
                    $lock_unlock_notify_page = 'locknotify';
1237
                }
1238
            }
1239
1240
            if (api_is_allowed_to_session_edit(false, true)
1241
                && api_is_allowed_to_edit()
1242
                || GroupManager::is_user_in_group(api_get_user_id(), $groupInfo)
1243
            ) {
1244
                // menu discuss page
1245
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=discuss&title='
1246
                    .api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('discuss').'>'
1247
                    .Display::return_icon(
1248
                        'discuss.png',
1249
                        get_lang('DiscussThisPage'),
1250
                        [],
1251
                        ICON_SIZE_MEDIUM
1252
                    ).'</a>';
1253
            }
1254
1255
            //menu history
1256
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=history&title='
1257
                .api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('history').'>'.
1258
                Display::return_icon(
1259
                    'history.png',
1260
                    get_lang('ShowPageHistory'),
1261
                    [],
1262
                    ICON_SIZE_MEDIUM
1263
                ).'</a>';
1264
            //menu linkspages
1265
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'action=links&title='
1266
                .api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('links').'>'
1267
                .Display::return_icon(
1268
                    'what_link_here.png',
1269
                    get_lang('LinksPages'),
1270
                    [],
1271
                    ICON_SIZE_MEDIUM
1272
                ).'</a>';
1273
1274
            //menu delete wikipage
1275
            if (api_is_allowed_to_edit(false, true) ||
1276
                api_is_platform_admin()
1277
            ) {
1278
                $actionsRight .= '<a href="index.php?action=delete&'.api_get_cidreq().'&title='
1279
                    .api_htmlentities(urlencode($page)).'"'.self::is_active_navigation_tab('delete').'>'
1280
                    .Display::return_icon(
1281
                        'delete.png',
1282
                        get_lang('DeleteThisPage'),
1283
                        [],
1284
                        ICON_SIZE_MEDIUM
1285
                    ).'</a>';
1286
            }
1287
1288
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='
1289
                .$lock_unlock_notify_page.'&title='.api_htmlentities(urlencode($page)).'">'.$notify_page.'</a>';
1290
1291
            // Page action: copy last version to doc area
1292
            if (api_is_allowed_to_edit(false, true) ||
1293
                api_is_platform_admin()
1294
            ) {
1295
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export2doc&wiki_id='.$row['id'].'">'
1296
                    .Display::return_icon(
1297
                        'export_to_documents.png',
1298
                        get_lang('ExportToDocArea'),
1299
                        [],
1300
                        ICON_SIZE_MEDIUM
1301
                    ).'</a>';
1302
            }
1303
1304
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export_to_pdf&wiki_id='.$row['id'].'">'
1305
                .Display::return_icon(
1306
                    'pdf.png',
1307
                    get_lang('ExportToPDF'),
1308
                    [],
1309
                    ICON_SIZE_MEDIUM
1310
                ).'</a>';
1311
1312
            $unoconv = api_get_configuration_value('unoconv.binaries');
1313
            if ($unoconv) {
1314
                $actionsRight .= '<a href="'.api_get_path(WEB_CODE_PATH).'wiki/index.php?action=export_to_doc_file&id='
1315
                    .$row['id'].'&'.api_get_cidreq().'">'
1316
                    .Display::return_icon(
1317
                        'export_doc.png',
1318
                        get_lang('ExportToDoc'),
1319
                        [],
1320
                        ICON_SIZE_MEDIUM
1321
                    ).'</a>';
1322
            }
1323
1324
            //export to print?>
1325
            <script>
1326
                function goprint() {
1327
                    var a = window.open('', '', 'width=800,height=600');
1328
                    a.document.open("text/html");
1329
                    a.document.write($('#wikicontent .panel-heading').html());
1330
                    a.document.write($('#wikicontent .panel-body').html());
1331
                    a.document.close();
1332
                    a.print();
1333
                }
1334
            </script>
1335
            <?php
1336
            $actionsRight .= Display::url(
1337
                Display::return_icon(
1338
                    'printer.png',
1339
                    get_lang('Print'),
1340
                    [],
1341
                    ICON_SIZE_MEDIUM
1342
                ),
1343
                '#',
1344
                ['onclick' => "javascript: goprint();"]
1345
            );
1346
        }
1347
1348
        echo Display::toolbarAction(
1349
            'toolbar-wikistudent',
1350
            [$actionsLeft, $actionsRight]
1351
        );
1352
1353
        $pageWiki = self::detect_news_link($content);
1354
        $pageWiki = self::detect_irc_link($pageWiki);
1355
        $pageWiki = self::detect_ftp_link($pageWiki);
1356
        $pageWiki = self::detect_mail_link($pageWiki);
1357
        $pageWiki = self::detect_anchor_link($pageWiki);
1358
        $pageWiki = self::detect_external_link($pageWiki);
1359
        $pageWiki = self::make_wiki_link_clickable($pageWiki);
1360
1361
        $footerWiki = '<ul class="list-inline" style="margin-bottom: 0;">'
1362
            .'<li>'.get_lang('Progress').': '.$pageProgress.'%</li>'
1363
            .'<li>'.get_lang('Rating').': '.$pageScore.'</li>'
1364
            .'<li>'.get_lang('Words').': '.self::word_count($content).'</li>'
1365
            .'</ul>';
1366
        // wikicontent require to print wiki document
1367
        echo '<div id="wikicontent">'.Display::panel($pageWiki, $pageTitle, $footerWiki).'</div>'; //end filter visibility
1368
    }
1369
1370
    /**
1371
     * This function counted the words in a document. Thanks Adeel Khan.
1372
     *
1373
     * @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...
1374
     *
1375
     * @return int Number of words
1376
     */
1377
    public function word_count($document)
1378
    {
1379
        $search = [
1380
            '@<script[^>]*?>.*?</script>@si',
1381
            '@<style[^>]*?>.*?</style>@siU',
1382
            '@<div id="player.[^>]*?>.*?</div>@',
1383
            '@<![\s\S]*?--[ \t\n\r]*>@',
1384
        ];
1385
1386
        $document = preg_replace($search, '', $document);
1387
1388
        // strip all html tags
1389
        $wc = strip_tags($document);
1390
        $wc = html_entity_decode(
1391
            $wc,
1392
            ENT_NOQUOTES,
1393
            'UTF-8'
1394
        ); // TODO:test also old html_entity_decode(utf8_encode($wc))
1395
1396
        // remove 'words' that don't consist of alphanumerical characters or punctuation. And fix accents and some letters
1397
        $pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@|á|é|í|ó|ú|à|è|ì|ò|ù|ä|ë|ï|ö|ü|Á|É|Í|Ó|Ú|À|È|Ò|Ù|Ä|Ë|Ï|Ö|Ü|â|ê|î|ô|û|Â|Ê|Î|Ô|Û|ñ|Ñ|ç|Ç)]+#";
1398
        $wc = trim(preg_replace($pattern, " ", $wc));
1399
1400
        // remove one-letter 'words' that consist only of punctuation
1401
        $wc = trim(
1402
            preg_replace(
1403
                "#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#",
1404
                " ",
1405
                $wc
1406
            )
1407
        );
1408
1409
        // remove superfluous whitespace
1410
        $wc = preg_replace("/\s\s+/", " ", $wc);
1411
1412
        // split string into an array of words
1413
        $wc = explode(" ", $wc);
1414
1415
        // remove empty elements
1416
        $wc = array_filter($wc);
1417
1418
        // return the number of words
1419
        return count($wc);
1420
    }
1421
1422
    /**
1423
     * This function checks if wiki title exist.
1424
     */
1425
    public function wiki_exist($title)
1426
    {
1427
        $tbl_wiki = $this->tbl_wiki;
1428
        $groupfilter = $this->groupfilter;
1429
        $condition_session = $this->condition_session;
1430
        $course_id = api_get_course_int_id();
1431
1432
        $sql = 'SELECT id FROM '.$tbl_wiki.'
1433
              WHERE
1434
                c_id = '.$course_id.' AND
1435
                title="'.Database::escape_string($title).'" AND
1436
                '.$groupfilter.$condition_session.'
1437
              ORDER BY id ASC';
1438
        $result = Database::query($sql);
1439
        $cant = Database::num_rows($result);
1440
        if ($cant > 0) {
1441
            return true;
1442
        } else {
1443
            return false;
1444
        }
1445
    }
1446
1447
    /**
1448
     * Checks if this navigation tab has to be set to active.
1449
     *
1450
     * @author Patrick Cool <[email protected]>, Ghent University
1451
     *
1452
     * @return string html code
1453
     */
1454
    public function is_active_navigation_tab($paramwk)
1455
    {
1456
        if (isset($_GET['action']) && $_GET['action'] == $paramwk) {
1457
            return ' class="active"';
1458
        }
1459
    }
1460
1461
    /**
1462
     * Lock add pages.
1463
     *
1464
     * @author Juan Carlos Raña <[email protected]>
1465
     * return current database status of protect page and change it if get action
1466
     */
1467
    public function check_addnewpagelock()
1468
    {
1469
        $tbl_wiki = $this->tbl_wiki;
1470
        $condition_session = $this->condition_session;
1471
        $groupfilter = $this->groupfilter;
1472
        $course_id = api_get_course_int_id();
1473
1474
        $sql = 'SELECT *
1475
                FROM '.$tbl_wiki.'
1476
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1477
                ORDER BY id ASC';
1478
1479
        $result = Database::query($sql);
1480
        $row = Database::fetch_array($result);
1481
1482
        $status_addlock = null;
1483
        if ($row) {
1484
            $status_addlock = $row['addlock'];
1485
        }
1486
1487
        // Change status
1488
        if (api_is_allowed_to_edit(false, true) ||
1489
            api_is_platform_admin()
1490
        ) {
1491
            if (isset($_GET['actionpage'])) {
1492
                if ($_GET['actionpage'] == 'lockaddnew' && $status_addlock == 1) {
1493
                    $status_addlock = 0;
1494
                }
1495
                if ($_GET['actionpage'] == 'unlockaddnew' && $status_addlock == 0) {
1496
                    $status_addlock = 1;
1497
                }
1498
                $sql = 'UPDATE '.$tbl_wiki.' SET
1499
                            addlock="'.Database::escape_string($status_addlock).'"
1500
                        WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session;
1501
                Database::query($sql);
1502
            }
1503
1504
            $sql = 'SELECT *
1505
                    FROM '.$tbl_wiki.'
1506
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1507
                    ORDER BY id ASC';
1508
            $result = Database::query($sql);
1509
            $row = Database::fetch_array($result);
1510
            if ($row) {
1511
                return $row['addlock'];
1512
            }
1513
        }
1514
1515
        return null;
1516
    }
1517
1518
    /**
1519
     * Protect page.
1520
     *
1521
     * @author Juan Carlos Raña <[email protected]>
1522
     * return current database status of protect page and change it if get action
1523
     */
1524
    public function check_protect_page()
1525
    {
1526
        $tbl_wiki = $this->tbl_wiki;
1527
        $condition_session = $this->condition_session;
1528
        $groupfilter = $this->groupfilter;
1529
        $page = $this->page;
1530
1531
        $course_id = api_get_course_int_id();
1532
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1533
              WHERE
1534
                c_id = '.$course_id.' AND
1535
                reflink="'.Database::escape_string($page).'" AND
1536
                '.$groupfilter.$condition_session.'
1537
              ORDER BY id ASC';
1538
1539
        $result = Database::query($sql);
1540
        $row = Database::fetch_array($result);
1541
1542
        if (!$row) {
1543
            return 0;
1544
        }
1545
1546
        $status_editlock = $row['editlock'];
1547
        $id = $row['page_id'];
1548
1549
        // Change status
1550
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1551
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'lock' && $status_editlock == 0) {
1552
                $status_editlock = 1;
1553
            }
1554
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlock' && $status_editlock == 1) {
1555
                $status_editlock = 0;
1556
            }
1557
1558
            $sql = 'UPDATE '.$tbl_wiki.' SET
1559
                    editlock="'.Database::escape_string($status_editlock).'"
1560
                    WHERE c_id = '.$course_id.' AND page_id="'.$id.'"';
1561
            Database::query($sql);
1562
1563
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1564
                    WHERE
1565
                        c_id = '.$course_id.' AND
1566
                        reflink="'.Database::escape_string($page).'" AND
1567
                    '.$groupfilter.$condition_session.'
1568
                  ORDER BY id ASC';
1569
            $result = Database::query($sql);
1570
            $row = Database::fetch_array($result);
1571
        }
1572
1573
        //show status
1574
        return (int) $row['editlock'];
1575
    }
1576
1577
    /**
1578
     * Visibility page.
1579
     *
1580
     * @author Juan Carlos Raña <[email protected]>
1581
     * return current database status of visibility and change it if get action
1582
     */
1583
    public function check_visibility_page()
1584
    {
1585
        $tbl_wiki = $this->tbl_wiki;
1586
        $page = $this->page;
1587
        $condition_session = $this->condition_session;
1588
        $groupfilter = $this->groupfilter;
1589
        $course_id = api_get_course_int_id();
1590
1591
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1592
                WHERE
1593
                    c_id = '.$course_id.' AND
1594
                    reflink="'.Database::escape_string($page).'" AND
1595
                    '.$groupfilter.$condition_session.'
1596
                ORDER BY id';
1597
        $result = Database::query($sql);
1598
        $row = Database::fetch_array($result);
1599
1600
        if (!$row) {
1601
            return 0;
1602
        }
1603
1604
        $status_visibility = $row['visibility'];
1605
        //change status
1606
        if (api_is_allowed_to_edit(false, true) ||
1607
            api_is_platform_admin()
1608
        ) {
1609
            if (isset($_GET['actionpage']) &&
1610
                $_GET['actionpage'] == 'visible' &&
1611
                $status_visibility == 0
1612
            ) {
1613
                $status_visibility = 1;
1614
            }
1615
            if (isset($_GET['actionpage']) &&
1616
                $_GET['actionpage'] == 'invisible' &&
1617
                $status_visibility == 1
1618
            ) {
1619
                $status_visibility = 0;
1620
            }
1621
1622
            $sql = 'UPDATE '.$tbl_wiki.' SET
1623
                    visibility = "'.Database::escape_string($status_visibility).'"
1624
                    WHERE
1625
                        c_id = '.$course_id.' AND
1626
                        reflink="'.Database::escape_string($page).'" AND
1627
                        '.$groupfilter.$condition_session;
1628
            Database::query($sql);
1629
1630
            // Although the value now is assigned to all (not only the first),
1631
            // these three lines remain necessary.
1632
            // They do that by changing the page state is
1633
            // made when you press the button and not have to wait to change his page
1634
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1635
                    WHERE
1636
                        c_id = '.$course_id.' AND
1637
                        reflink="'.Database::escape_string($page).'" AND
1638
                        '.$groupfilter.$condition_session.'
1639
                    ORDER BY id ASC';
1640
            $result = Database::query($sql);
1641
            $row = Database::fetch_array($result);
1642
        }
1643
1644
        if (empty($row['id'])) {
1645
            $row['visibility'] = 1;
1646
        }
1647
1648
        //show status
1649
        return $row['visibility'];
1650
    }
1651
1652
    /**
1653
     * Visibility discussion.
1654
     *
1655
     * @author Juan Carlos Raña <[email protected]>
1656
     *
1657
     * @return int current database status of discuss visibility
1658
     *             and change it if get action page
1659
     */
1660
    public function check_visibility_discuss()
1661
    {
1662
        $tbl_wiki = $this->tbl_wiki;
1663
        $page = $this->page;
1664
        $condition_session = $this->condition_session;
1665
        $groupfilter = $this->groupfilter;
1666
        $course_id = api_get_course_int_id();
1667
1668
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1669
                WHERE
1670
                    c_id = '.$course_id.' AND
1671
                    reflink="'.Database::escape_string($page).'" AND
1672
                    '.$groupfilter.$condition_session.'
1673
                ORDER BY id ASC';
1674
        $result = Database::query($sql);
1675
        $row = Database::fetch_array($result);
1676
1677
        $status_visibility_disc = $row['visibility_disc'];
1678
1679
        //change status
1680
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1681
            if (isset($_GET['actionpage']) &&
1682
                $_GET['actionpage'] == 'showdisc' &&
1683
                $status_visibility_disc == 0
1684
            ) {
1685
                $status_visibility_disc = 1;
1686
            }
1687
            if (isset($_GET['actionpage']) &&
1688
                $_GET['actionpage'] == 'hidedisc' &&
1689
                $status_visibility_disc == 1
1690
            ) {
1691
                $status_visibility_disc = 0;
1692
            }
1693
1694
            $sql = 'UPDATE '.$tbl_wiki.' SET
1695
                    visibility_disc="'.Database::escape_string($status_visibility_disc).'"
1696
                    WHERE
1697
                        c_id = '.$course_id.' AND
1698
                        reflink="'.Database::escape_string($page).'" AND
1699
                        '.$groupfilter.$condition_session;
1700
            Database::query($sql);
1701
1702
            // Although the value now is assigned to all (not only the first),
1703
            // these three lines remain necessary.
1704
            // They do that by changing the page state is made when you press
1705
            // the button and not have to wait to change his page
1706
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1707
                    WHERE
1708
                        c_id = '.$course_id.' AND
1709
                        reflink="'.Database::escape_string($page).'" AND
1710
                        '.$groupfilter.$condition_session.'
1711
                    ORDER BY id ASC';
1712
            $result = Database::query($sql);
1713
            $row = Database::fetch_array($result);
1714
        }
1715
1716
        return $row['visibility_disc'];
1717
    }
1718
1719
    /**
1720
     * Lock add discussion.
1721
     *
1722
     * @author Juan Carlos Raña <[email protected]>
1723
     *
1724
     * @return int current database status of lock dicuss and change if get action
1725
     */
1726
    public function check_addlock_discuss()
1727
    {
1728
        $tbl_wiki = $this->tbl_wiki;
1729
        $page = $this->page;
1730
        $condition_session = $this->condition_session;
1731
        $groupfilter = $this->groupfilter;
1732
        $course_id = api_get_course_int_id();
1733
1734
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1735
                WHERE
1736
                    c_id = '.$course_id.' AND
1737
                    reflink="'.Database::escape_string($page).'" AND
1738
                    '.$groupfilter.$condition_session.'
1739
                ORDER BY id ASC';
1740
        $result = Database::query($sql);
1741
        $row = Database::fetch_array($result);
1742
1743
        $status_addlock_disc = $row['addlock_disc'];
1744
1745
        //change status
1746
        if (api_is_allowed_to_edit() || api_is_platform_admin()) {
1747
            if (isset($_GET['actionpage']) &&
1748
                $_GET['actionpage'] == 'lockdisc' &&
1749
                $status_addlock_disc == 0
1750
            ) {
1751
                $status_addlock_disc = 1;
1752
            }
1753
            if (isset($_GET['actionpage']) &&
1754
                $_GET['actionpage'] == 'unlockdisc' &&
1755
                $status_addlock_disc == 1
1756
            ) {
1757
                $status_addlock_disc = 0;
1758
            }
1759
1760
            $sql = 'UPDATE '.$tbl_wiki.' SET
1761
                    addlock_disc="'.Database::escape_string($status_addlock_disc).'"
1762
                    WHERE
1763
                        c_id = '.$course_id.' AND
1764
                        reflink = "'.Database::escape_string($page).'" AND
1765
                         '.$groupfilter.$condition_session;
1766
            Database::query($sql);
1767
1768
            // Although the value now is assigned to all (not only the first),
1769
            // these three lines remain necessary.
1770
            // They do that by changing the page state is made when you press
1771
            // the button and not have to wait to change his page
1772
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1773
                    WHERE
1774
                        c_id = '.$course_id.' AND
1775
                        reflink="'.Database::escape_string($page).'" AND
1776
                        '.$groupfilter.$condition_session.'
1777
                    ORDER BY id ASC';
1778
            $result = Database::query($sql);
1779
            $row = Database::fetch_array($result);
1780
        }
1781
1782
        return $row['addlock_disc'];
1783
    }
1784
1785
    /**
1786
     * Lock rating discussion.
1787
     *
1788
     * @author Juan Carlos Raña <[email protected]>
1789
     *
1790
     * @return int current database status of rating discuss and change it if get action
1791
     */
1792
    public function check_ratinglock_discuss()
1793
    {
1794
        $tbl_wiki = $this->tbl_wiki;
1795
        $page = $this->page;
1796
        $condition_session = $this->condition_session;
1797
        $groupfilter = $this->groupfilter;
1798
        $course_id = api_get_course_int_id();
1799
1800
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1801
                WHERE
1802
                    c_id = '.$course_id.' AND
1803
                    reflink="'.Database::escape_string($page).'" AND
1804
                    '.$groupfilter.$condition_session.'
1805
                ORDER BY id ASC';
1806
        $result = Database::query($sql);
1807
        $row = Database::fetch_array($result);
1808
        $status_ratinglock_disc = $row['ratinglock_disc'];
1809
1810
        //change status
1811
        if (api_is_allowed_to_edit(false, true) ||
1812
            api_is_platform_admin()
1813
        ) {
1814
            if (isset($_GET['actionpage']) &&
1815
                $_GET['actionpage'] == 'lockrating' &&
1816
                $status_ratinglock_disc == 0
1817
            ) {
1818
                $status_ratinglock_disc = 1;
1819
            }
1820
            if (isset($_GET['actionpage']) &&
1821
                $_GET['actionpage'] == 'unlockrating' &&
1822
                $status_ratinglock_disc == 1
1823
            ) {
1824
                $status_ratinglock_disc = 0;
1825
            }
1826
1827
            $sql = 'UPDATE '.$tbl_wiki.'
1828
                    SET ratinglock_disc="'.Database::escape_string($status_ratinglock_disc).'"
1829
                    WHERE
1830
                        c_id = '.$course_id.' AND
1831
                        reflink="'.Database::escape_string($page).'" AND
1832
                        '.$groupfilter.$condition_session;
1833
            // Visibility. Value to all,not only for the first
1834
            Database::query($sql);
1835
1836
            // Although the value now is assigned to all (not only the first),
1837
            // these three lines remain necessary. They do that by changing the
1838
            // page state is made when you press the button and not have to wait
1839
            // to change his page
1840
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1841
                    WHERE
1842
                        c_id = '.$course_id.' AND
1843
                        reflink="'.Database::escape_string($page).'" AND
1844
                    '.$groupfilter.$condition_session.'
1845
                  ORDER BY id ASC';
1846
            $result = Database::query($sql);
1847
            $row = Database::fetch_array($result);
1848
        }
1849
1850
        return $row['ratinglock_disc'];
1851
    }
1852
1853
    /**
1854
     * Notify page changes.
1855
     *
1856
     * @author Juan Carlos Raña <[email protected]>
1857
     *
1858
     * @return int the current notification status
1859
     */
1860
    public function check_notify_page($reflink)
1861
    {
1862
        $tbl_wiki = $this->tbl_wiki;
1863
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1864
        $condition_session = $this->condition_session;
1865
        $groupfilter = $this->groupfilter;
1866
        $groupId = api_get_group_id();
1867
        $session_id = api_get_session_id();
1868
        $course_id = api_get_course_int_id();
1869
        $userId = api_get_user_id();
1870
1871
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1872
                WHERE
1873
                    c_id = '.$course_id.' AND
1874
                    reflink="'.$reflink.'" AND
1875
                    '.$groupfilter.$condition_session.'
1876
                ORDER BY id ASC';
1877
        $result = Database::query($sql);
1878
        $row = Database::fetch_array($result);
1879
        $id = $row['id'];
1880
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1881
                WHERE
1882
                    c_id = '.$course_id.' AND
1883
                    id="'.$id.'" AND
1884
                    user_id="'.api_get_user_id().'" AND
1885
                    type="P"';
1886
        $result = Database::query($sql);
1887
        $row = Database::fetch_array($result);
1888
1889
        $idm = $row ? $row['id'] : 0;
1890
        if (empty($idm)) {
1891
            $status_notify = 0;
1892
        } else {
1893
            $status_notify = 1;
1894
        }
1895
1896
        // Change status
1897
        if (isset($_GET['actionpage']) &&
1898
            $_GET['actionpage'] == 'locknotify' &&
1899
            $status_notify == 0
1900
        ) {
1901
            $sql = "SELECT id FROM $tbl_wiki_mailcue
1902
                    WHERE c_id = $course_id AND id = $id AND user_id = $userId";
1903
            $result = Database::query($sql);
1904
            $exist = false;
1905
            if (Database::num_rows($result)) {
1906
                $exist = true;
1907
            }
1908
            if ($exist == false) {
1909
                $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1910
                ($course_id, '".$id."','".api_get_user_id()."','P','".$groupId."','".$session_id."')";
1911
                Database::query($sql);
1912
            }
1913
            $status_notify = 1;
1914
        }
1915
1916
        if (isset($_GET['actionpage']) &&
1917
            $_GET['actionpage'] == 'unlocknotify' &&
1918
            $status_notify == 1
1919
        ) {
1920
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1921
                    WHERE
1922
                        id="'.$id.'" AND
1923
                        user_id="'.api_get_user_id().'" AND
1924
                        type="P" AND
1925
                        c_id = '.$course_id;
1926
            Database::query($sql);
1927
            $status_notify = 0;
1928
        }
1929
1930
        return $status_notify;
1931
    }
1932
1933
    /**
1934
     * Notify discussion changes.
1935
     *
1936
     * @author Juan Carlos Raña <[email protected]>
1937
     *
1938
     * @param string $reflink
1939
     *
1940
     * @return int current database status of rating discuss and change it if get action
1941
     */
1942
    public function check_notify_discuss($reflink)
1943
    {
1944
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1945
        $tbl_wiki = $this->tbl_wiki;
1946
        $condition_session = $this->condition_session;
1947
        $groupfilter = $this->groupfilter;
1948
1949
        $course_id = api_get_course_int_id();
1950
        $groupId = api_get_group_id();
1951
        $session_id = api_get_session_id();
1952
1953
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1954
                WHERE
1955
                    c_id = '.$course_id.' AND
1956
                    reflink="'.$reflink.'" AND
1957
                    '.$groupfilter.$condition_session.'
1958
                ORDER BY id ASC';
1959
        $result = Database::query($sql);
1960
        $row = Database::fetch_array($result);
1961
        $id = $row['id'];
1962
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1963
                WHERE
1964
                    c_id = '.$course_id.' AND id="'.$id.'" AND user_id="'.api_get_user_id().'" AND type="D"';
1965
        $result = Database::query($sql);
1966
        $row = Database::fetch_array($result);
1967
        $idm = $row ? $row['id'] : 0;
1968
1969
        if (empty($idm)) {
1970
            $status_notify_disc = 0;
1971
        } else {
1972
            $status_notify_disc = 1;
1973
        }
1974
1975
        // change status
1976
        if (isset($_GET['actionpage']) &&
1977
            $_GET['actionpage'] == 'locknotifydisc' &&
1978
            $status_notify_disc == 0
1979
        ) {
1980
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1981
            ($course_id, '".$id."','".api_get_user_id()."','D','".$groupId."','".$session_id."')";
1982
            Database::query($sql);
1983
            $status_notify_disc = 1;
1984
        }
1985
        if (isset($_GET['actionpage']) &&
1986
            $_GET['actionpage'] == 'unlocknotifydisc' &&
1987
            $status_notify_disc == 1
1988
        ) {
1989
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1990
                    WHERE
1991
                        c_id = '.$course_id.' AND
1992
                        id="'.$id.'" AND
1993
                        user_id="'.api_get_user_id().'" AND
1994
                        type="D" AND
1995
                        c_id = '.$course_id;
1996
            Database::query($sql);
1997
            $status_notify_disc = 0;
1998
        }
1999
2000
        return $status_notify_disc;
2001
    }
2002
2003
    /**
2004
     * Notify all changes.
2005
     *
2006
     * @author Juan Carlos Raña <[email protected]>
2007
     */
2008
    public function check_notify_all()
2009
    {
2010
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
2011
        $course_id = api_get_course_int_id();
2012
        $groupId = api_get_group_id();
2013
        $session_id = api_get_session_id();
2014
2015
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2016
                WHERE
2017
                    c_id = '.$course_id.' AND
2018
                    user_id="'.api_get_user_id().'" AND
2019
                    type="F" AND
2020
                    group_id="'.$groupId.'" AND
2021
                    session_id="'.$session_id.'"';
2022
        $result = Database::query($sql);
2023
        $row = Database::fetch_array($result);
2024
2025
        $idm = $row ? $row['user_id'] : 0;
2026
2027
        if (empty($idm)) {
2028
            $status_notify_all = 0;
2029
        } else {
2030
            $status_notify_all = 1;
2031
        }
2032
2033
        //change status
2034
        if (isset($_GET['actionpage']) &&
2035
            $_GET['actionpage'] == 'locknotifyall' &&
2036
            $status_notify_all == 0
2037
        ) {
2038
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, user_id, type, group_id, session_id) VALUES
2039
            ($course_id, '".api_get_user_id()."','F','".$groupId."','".$session_id."')";
2040
            Database::query($sql);
2041
            $status_notify_all = 1;
2042
        }
2043
2044
        if (isset($_GET['actionpage']) &&
2045
            $_GET['actionpage'] == 'unlocknotifyall' &&
2046
            $status_notify_all == 1
2047
        ) {
2048
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
2049
                   WHERE
2050
                    c_id = '.$course_id.' AND
2051
                    user_id="'.api_get_user_id().'" AND
2052
                    type="F" AND
2053
                    group_id="'.$groupId.'" AND
2054
                    session_id="'.$session_id.'" AND
2055
                    c_id = '.$course_id;
2056
            Database::query($sql);
2057
            $status_notify_all = 0;
2058
        }
2059
2060
        //show status
2061
        return $status_notify_all;
2062
    }
2063
2064
    /**
2065
     * Sends pending e-mails.
2066
     */
2067
    public function check_emailcue(
2068
        $id_or_ref,
2069
        $type,
2070
        $lastime = '',
2071
        $lastuser = ''
2072
    ) {
2073
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
2074
        $tbl_wiki = $this->tbl_wiki;
2075
        $condition_session = $this->condition_session;
2076
        $groupfilter = $this->groupfilter;
2077
        $_course = $this->courseInfo;
2078
        $groupId = api_get_group_id();
2079
        $session_id = api_get_session_id();
2080
        $course_id = api_get_course_int_id();
2081
        $group_properties = GroupManager::get_group_properties($groupId);
2082
        $group_name = $group_properties['name'];
2083
        $allow_send_mail = false; //define the variable to below
2084
        $email_assignment = null;
2085
        if ($type == 'P') {
2086
            //if modifying a wiki page
2087
            //first, current author and time
2088
            //Who is the author?
2089
            $userinfo = api_get_user_info($lastuser);
2090
            $email_user_author = get_lang('EditedBy').': '.$userinfo['complete_name'];
2091
2092
            //When ?
2093
            $year = substr($lastime, 0, 4);
2094
            $month = substr($lastime, 5, 2);
2095
            $day = substr($lastime, 8, 2);
2096
            $hours = substr($lastime, 11, 2);
2097
            $minutes = substr($lastime, 14, 2);
2098
            $seconds = substr($lastime, 17, 2);
2099
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2100
2101
            //second, extract data from first reg
2102
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2103
                    WHERE
2104
                        c_id = '.$course_id.' AND
2105
                        reflink="'.$id_or_ref.'" AND
2106
                        '.$groupfilter.$condition_session.'
2107
                    ORDER BY id ASC';
2108
            $result = Database::query($sql);
2109
            $row = Database::fetch_array($result);
2110
            $id = $row['id'];
2111
            $email_page_name = $row['title'];
2112
            if ($row['visibility'] == 1) {
2113
                $allow_send_mail = true; //if visibility off - notify off
2114
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2115
                        WHERE
2116
                            c_id = '.$course_id.' AND
2117
                            id="'.$id.'" AND
2118
                            type="'.$type.'" OR
2119
                            type="F" AND
2120
                            group_id="'.$groupId.'" AND
2121
                            session_id="'.$session_id.'"';
2122
                //type: P=page, D=discuss, F=full.
2123
                $result = Database::query($sql);
2124
                $emailtext = get_lang('EmailWikipageModified').
2125
                    '<strong>'.$email_page_name.'</strong> '.
2126
                    get_lang('Wiki');
2127
            }
2128
        } elseif ($type == 'D') {
2129
            //if added a post to discuss
2130
            //first, current author and time
2131
            //Who is the author of last message?
2132
            $userinfo = api_get_user_info($lastuser);
2133
            $email_user_author = get_lang('AddedBy').': '.$userinfo['complete_name'];
2134
2135
            //When ?
2136
            $year = substr($lastime, 0, 4);
2137
            $month = substr($lastime, 5, 2);
2138
            $day = substr($lastime, 8, 2);
2139
            $hours = substr($lastime, 11, 2);
2140
            $minutes = substr($lastime, 14, 2);
2141
            $seconds = substr($lastime, 17, 2);
2142
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2143
            //second, extract data from first reg
2144
            $id = $id_or_ref; //$id_or_ref is id from tblwiki
2145
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2146
                    WHERE c_id = '.$course_id.' AND id="'.$id.'"
2147
                    ORDER BY id ASC';
2148
2149
            $result = Database::query($sql);
2150
            $row = Database::fetch_array($result);
2151
2152
            $email_page_name = $row['title'];
2153
            if ($row['visibility_disc'] == 1) {
2154
                $allow_send_mail = true; //if visibility off - notify off
2155
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2156
                        WHERE
2157
                            c_id = '.$course_id.' AND
2158
                            id="'.$id.'" AND
2159
                            type="'.$type.'" OR
2160
                            type="F" AND
2161
                            group_id="'.$groupId.'" AND
2162
                            session_id="'.$session_id.'"';
2163
                //type: P=page, D=discuss, F=full
2164
                $result = Database::query($sql);
2165
                $emailtext = get_lang(
2166
                        'EmailWikiPageDiscAdded'
2167
                    ).' <strong>'.$email_page_name.'</strong> '.get_lang(
2168
                        'Wiki'
2169
                    );
2170
            }
2171
        } elseif ($type == 'A') {
2172
            //for added pages
2173
            $id = 0; //for tbl_wiki_mailcue
2174
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2175
                    WHERE c_id = '.$course_id.'
2176
                    ORDER BY id DESC'; //the added is always the last
2177
2178
            $result = Database::query($sql);
2179
            $row = Database::fetch_array($result);
2180
            $email_page_name = $row['title'];
2181
2182
            //Who is the author?
2183
            $userinfo = api_get_user_info($row['user_id']);
2184
            $email_user_author = get_lang('AddedBy').': '.$userinfo['complete_name'];
2185
2186
            //When ?
2187
            $year = substr($row['dtime'], 0, 4);
2188
            $month = substr($row['dtime'], 5, 2);
2189
            $day = substr($row['dtime'], 8, 2);
2190
            $hours = substr($row['dtime'], 11, 2);
2191
            $minutes = substr($row['dtime'], 14, 2);
2192
            $seconds = substr($row['dtime'], 17, 2);
2193
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2194
2195
            if ($row['assignment'] == 0) {
2196
                $allow_send_mail = true;
2197
            } elseif ($row['assignment'] == 1) {
2198
                $email_assignment = get_lang('AssignmentDescExtra').' ('.get_lang('AssignmentMode').')';
2199
                $allow_send_mail = true;
2200
            } elseif ($row['assignment'] == 2) {
2201
                $allow_send_mail = false; //Mode tasks: avoids notifications to all users about all users
2202
            }
2203
2204
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2205
                    WHERE
2206
                        c_id = '.$course_id.' AND
2207
                        id="'.$id.'" AND
2208
                        type="F" AND
2209
                        group_id="'.$groupId.'" AND
2210
                        session_id="'.$session_id.'"';
2211
2212
            //type: P=page, D=discuss, F=full
2213
            $result = Database::query($sql);
2214
            $emailtext = get_lang('EmailWikiPageAdded').' <strong>'.
2215
                $email_page_name.'</strong> '.get_lang('In').' '.get_lang('Wiki');
2216
        } elseif ($type == 'E') {
2217
            $id = 0;
2218
            $allow_send_mail = true;
2219
            // Who is the author?
2220
            $userinfo = api_get_user_info(api_get_user_id()); //current user
2221
            $email_user_author = get_lang('DeletedBy').': '.$userinfo['complete_name'];
2222
            //When ?
2223
            $today = date('r'); //current time
2224
            $email_date_changes = $today;
2225
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2226
                    WHERE
2227
                        c_id = '.$course_id.' AND
2228
                        id="'.$id.'" AND type="F" AND
2229
                        group_id="'.$groupId.'" AND
2230
                        session_id="'.$session_id.'"'; //type: P=page, D=discuss, F=wiki
2231
            $result = Database::query($sql);
2232
            $emailtext = get_lang('EmailWikipageDedeleted');
2233
        }
2234
        ///make and send email
2235
        if ($allow_send_mail) {
2236
            while ($row = Database::fetch_array($result)) {
2237
                $userinfo = api_get_user_info(
2238
                    $row['user_id']
2239
                ); //$row['user_id'] obtained from tbl_wiki_mailcue
2240
                $name_to = $userinfo['complete_name'];
2241
                $email_to = $userinfo['email'];
2242
                $sender_name = api_get_setting('emailAdministrator');
2243
                $sender_email = api_get_setting('emailAdministrator');
2244
                $email_subject = get_lang(
2245
                        'EmailWikiChanges'
2246
                    ).' - '.$_course['official_code'];
2247
                $email_body = get_lang('DearUser').' '.api_get_person_name(
2248
                        $userinfo['firstname'],
2249
                        $userinfo['lastname']
2250
                    ).',<br /><br />';
2251
                if ($session_id == 0) {
2252
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' - '.$group_name.'</strong><br /><br /><br />';
2253
                } else {
2254
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' ('.api_get_session_name(
2255
                            api_get_session_id()
2256
                        ).') - '.$group_name.'</strong><br /><br /><br />';
2257
                }
2258
                $email_body .= $email_user_author.' ('.$email_date_changes.')<br /><br /><br />';
2259
                $email_body .= $email_assignment.'<br /><br /><br />';
2260
                $email_body .= '<font size="-2">'.get_lang(
2261
                        'EmailWikiChangesExt_1'
2262
                    ).': <strong>'.get_lang('NotifyChanges').'</strong><br />';
2263
                $email_body .= get_lang(
2264
                        'EmailWikiChangesExt_2'
2265
                    ).': <strong>'.get_lang(
2266
                        'NotNotifyChanges'
2267
                    ).'</strong></font><br />';
2268
                @api_mail_html(
2269
                    $name_to,
2270
                    $email_to,
2271
                    $email_subject,
2272
                    $email_body,
2273
                    $sender_name,
2274
                    $sender_email
2275
                );
2276
            }
2277
        }
2278
    }
2279
2280
    /**
2281
     * Function export last wiki page version to document area.
2282
     *
2283
     * @param int $doc_id wiki page id
2284
     *
2285
     * @return mixed
2286
     *
2287
     * @author Juan Carlos Raña <[email protected]>
2288
     */
2289
    public function export2doc($doc_id)
2290
    {
2291
        $_course = $this->courseInfo;
2292
        $groupId = api_get_group_id();
2293
        $groupInfo = GroupManager::get_group_properties($groupId);
2294
        $data = self::getWikiDataFromDb($doc_id);
2295
2296
        if (empty($data)) {
2297
            return false;
2298
        }
2299
2300
        $wikiTitle = $data['title'];
2301
        $wikiContents = $data['content'];
2302
2303
        $template =
2304
            '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2305
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{LANGUAGE}" lang="{LANGUAGE}">
2306
            <head>
2307
            <title>{TITLE}</title>
2308
            <meta http-equiv="Content-Type" content="text/html; charset={ENCODING}" />
2309
            <style type="text/css" media="screen, projection">
2310
            /*<![CDATA[*/
2311
            {CSS}
2312
            /*]]>*/
2313
            </style>
2314
            {ASCIIMATHML_SCRIPT}</head>
2315
            <body dir="{TEXT_DIRECTION}">
2316
            {CONTENT}
2317
            </body>
2318
            </html>';
2319
2320
        $css_file = api_get_path(SYS_CSS_PATH).'themes/'.api_get_setting('stylesheets').'/default.css';
2321
        if (file_exists($css_file)) {
2322
            $css = @file_get_contents($css_file);
2323
        } else {
2324
            $css = '';
2325
        }
2326
        // Fixing some bugs in css files.
2327
        $root_rel = api_get_path(REL_PATH);
2328
        $css_path = 'main/css/';
2329
        $theme = api_get_setting('stylesheets').'/';
2330
        $css = str_replace(
2331
            'behavior:url("/main/css/csshover3.htc");',
2332
            '',
2333
            $css
2334
        );
2335
        $css = str_replace('main/', $root_rel.'main/', $css);
2336
        $css = str_replace(
2337
            'images/',
2338
            $root_rel.$css_path.$theme.'images/',
2339
            $css
2340
        );
2341
        $css = str_replace('../../img/', $root_rel.'main/img/', $css);
2342
        $asciimathmal_script = (api_contains_asciimathml(
2343
                $wikiContents
2344
            ) || api_contains_asciisvg($wikiContents))
2345
            ? '<script src="'.api_get_path(
2346
                WEB_CODE_PATH
2347
            ).'inc/lib/javascript/asciimath/ASCIIMathML.js" type="text/javascript"></script>'."\n" : '';
2348
2349
        $template = str_replace(
2350
            [
2351
                '{LANGUAGE}',
2352
                '{ENCODING}',
2353
                '{TEXT_DIRECTION}',
2354
                '{TITLE}',
2355
                '{CSS}',
2356
                '{ASCIIMATHML_SCRIPT}',
2357
            ],
2358
            [
2359
                api_get_language_isocode(),
2360
                api_get_system_encoding(),
2361
                api_get_text_direction(),
2362
                $wikiTitle,
2363
                $css,
2364
                $asciimathmal_script,
2365
            ],
2366
            $template
2367
        );
2368
2369
        if (0 != $groupId) {
2370
            $groupPart = '_group'.$groupId; // and add groupId to put the same document title in different groups
2371
            $group_properties = GroupManager::get_group_properties($groupId);
2372
            $groupPath = $group_properties['directory'];
2373
        } else {
2374
            $groupPart = '';
2375
            $groupPath = '';
2376
        }
2377
2378
        $exportDir = api_get_path(SYS_COURSE_PATH).api_get_course_path(
2379
            ).'/document'.$groupPath;
2380
        $exportFile = api_replace_dangerous_char($wikiTitle).$groupPart;
2381
        $wikiContents = trim(
2382
            preg_replace(
2383
                "/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/",
2384
                "$1",
2385
                $wikiContents
2386
            )
2387
        );
2388
        //TODO: put link instead of title
2389
        $wikiContents = str_replace('{CONTENT}', $wikiContents, $template);
2390
        // replace relative path by absolute path for courses, so you can see
2391
        // items into this page wiki (images, mp3, etc..) exported in documents
2392
        if (api_strpos(
2393
                $wikiContents,
2394
                '../..'.api_get_path(REL_COURSE_PATH)
2395
            ) !== false) {
2396
            $web_course_path = api_get_path(WEB_COURSE_PATH);
2397
            $wikiContents = str_replace(
2398
                '../..'.api_get_path(REL_COURSE_PATH),
2399
                $web_course_path,
2400
                $wikiContents
2401
            );
2402
        }
2403
2404
        $i = 1;
2405
        //only export last version, but in new export new version in document area
2406
        while (file_exists($exportDir.'/'.$exportFile.'_'.$i.'.html')) {
2407
            $i++;
2408
        }
2409
2410
        $wikiFileName = $exportFile.'_'.$i.'.html';
2411
        $exportPath = $exportDir.'/'.$wikiFileName;
2412
2413
        file_put_contents($exportPath, $wikiContents);
2414
        $doc_id = add_document(
2415
            $_course,
2416
            $groupPath.'/'.$wikiFileName,
2417
            'file',
2418
            filesize($exportPath),
2419
            $wikiTitle
2420
        );
2421
2422
        api_item_property_update(
2423
            $_course,
2424
            TOOL_DOCUMENT,
2425
            $doc_id,
2426
            'DocumentAdded',
2427
            api_get_user_id(),
2428
            $groupInfo
2429
        );
2430
2431
        return $doc_id;
2432
    }
2433
2434
    /**
2435
     * Exports the wiki page to PDF.
2436
     */
2437
    public function export_to_pdf($id, $course_code)
2438
    {
2439
        if (!api_is_platform_admin()) {
2440
            if (api_get_setting('students_export2pdf') !== 'true') {
2441
                Display::addFlash(
2442
                    Display::return_message(
2443
                        get_lang('PDFDownloadNotAllowedForStudents'),
2444
                        'error',
2445
                        false
2446
                    )
2447
                );
2448
2449
                return false;
2450
            }
2451
        }
2452
2453
        $data = self::getWikiDataFromDb($id);
2454
        $content_pdf = api_html_entity_decode(
2455
            $data['content'],
2456
            ENT_QUOTES,
2457
            api_get_system_encoding()
2458
        );
2459
2460
        //clean wiki links
2461
        $content_pdf = trim(
2462
            preg_replace(
2463
                "/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/",
2464
                "$1",
2465
                $content_pdf
2466
            )
2467
        );
2468
        //TODO: It should be better to display the link insted of the tile but it is hard for [[title]] links
2469
2470
        $title_pdf = api_html_entity_decode(
2471
            $data['title'],
2472
            ENT_QUOTES,
2473
            api_get_system_encoding()
2474
        );
2475
        $title_pdf = api_utf8_encode($title_pdf, api_get_system_encoding());
2476
        $content_pdf = api_utf8_encode($content_pdf, api_get_system_encoding());
2477
2478
        $html = '
2479
        <!-- defines the headers/footers - this must occur before the headers/footers are set -->
2480
2481
        <!--mpdf
2482
        <pageheader name="odds" content-left="'.$title_pdf.'"  header-style-left="color: #880000; font-style: italic;"  line="1" />
2483
        <pagefooter name="odds" content-right="{PAGENO}/{nb}" line="1" />
2484
2485
        <!-- set the headers/footers - they will occur from here on in the document -->
2486
        <!--mpdf
2487
        <setpageheader name="odds" page="odd" value="on" show-this-page="1" />
2488
        <setpagefooter name="odds" page="O" value="on" />
2489
2490
        mpdf-->'.$content_pdf;
2491
2492
        $css = api_get_print_css();
2493
2494
        $pdf = new PDF();
2495
        $pdf->content_to_pdf($html, $css, $title_pdf, $course_code);
2496
        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...
2497
    }
2498
2499
    /**
2500
     * Function prevent double post (reload or F5).
2501
     */
2502
    public function double_post($wpost_id)
2503
    {
2504
        $postId = Session::read('wpost_id');
2505
        if (!empty($postId)) {
2506
            if ($wpost_id == $postId) {
2507
                return false;
2508
            } else {
2509
                Session::write('wpost_id', $wpost_id);
2510
2511
                return true;
2512
            }
2513
        } else {
2514
            Session::write('wpost_id', $wpost_id);
2515
2516
            return true;
2517
        }
2518
    }
2519
2520
    /**
2521
     * Function wizard individual assignment.
2522
     *
2523
     * @author Juan Carlos Raña <[email protected]>
2524
     */
2525
    public function auto_add_page_users($values)
2526
    {
2527
        $assignment_type = $values['assignment'];
2528
        $session_id = $this->session_id;
2529
        $groupId = api_get_group_id();
2530
        $groupInfo = GroupManager::get_group_properties($groupId);
2531
        if ($groupId == 0) {
2532
            //extract course members
2533
            if (!empty($session_id)) {
2534
                $a_users_to_add = CourseManager::get_user_list_from_course_code(
2535
                    api_get_course_id(),
2536
                    $session_id
2537
                );
2538
            } else {
2539
                $a_users_to_add = CourseManager::get_user_list_from_course_code(
2540
                    api_get_course_id(),
2541
                    0
2542
                );
2543
            }
2544
        } else {
2545
            //extract group members
2546
            $subscribed_users = GroupManager::get_subscribed_users($groupInfo);
2547
            $subscribed_tutors = GroupManager::get_subscribed_tutors(
2548
                $groupInfo
2549
            );
2550
            $a_users_to_add_with_duplicates = array_merge(
2551
                $subscribed_users,
2552
                $subscribed_tutors
2553
            );
2554
            //remove duplicates
2555
            $a_users_to_add = $a_users_to_add_with_duplicates;
2556
            $a_users_to_add = array_unique($a_users_to_add);
2557
        }
2558
2559
        $all_students_pages = [];
2560
        // Data about teacher
2561
        $userId = api_get_user_id();
2562
        $userinfo = api_get_user_info($userId);
2563
        $username = api_htmlentities(
2564
            sprintf(get_lang('LoginX'), $userinfo['username'], ENT_QUOTES)
2565
        );
2566
        $name = $userinfo['complete_name']." - ".$username;
2567
        $photo = '<img src="'.$userinfo['avatar'].'" alt="'.$name.'"  width="40" height="50" align="top" title="'.$name.'"  />';
2568
2569
        // teacher assignment title
2570
        $title_orig = $values['title'];
2571
2572
        // teacher assignment reflink
2573
        $link2teacher = $values['title'] = $title_orig."_uass".$userId;
2574
2575
        // first: teacher name, photo, and assignment description (original content)
2576
        $content_orig_A = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2577
        <table border="0">
2578
            <tr><td style="font-size:24px">'.get_lang('AssignmentDesc').'</td></tr>
2579
            <tr><td>'.$photo.'<br />'.Display::tag(
2580
                'span',
2581
                api_get_person_name(
2582
                    $userinfo['firstname'],
2583
                    $userinfo['lastname']
2584
                ),
2585
                ['title' => $username]
2586
            ).'</td></tr>
2587
        </table></div>';
2588
2589
        $content_orig_B = '<br/><div align="center" style="font-size:24px">'.
2590
            get_lang('AssignmentDescription').': '.
2591
            $title_orig.'</div><br/>'.Security::remove_XSS($_POST['content']);
2592
2593
        //Second: student list (names, photo and links to their works).
2594
        //Third: Create Students work pages.
2595
        foreach ($a_users_to_add as $o_user_to_add) {
2596
            if ($o_user_to_add['user_id'] != $userId) {
2597
                // except that puts the task
2598
                $assig_user_id = $o_user_to_add['user_id'];
2599
                // identifies each page as created by the student, not by teacher
2600
2601
                $userPicture = UserManager::getUserPicture($assig_user_id);
2602
                $username = api_htmlentities(
2603
                    sprintf(
2604
                        get_lang('LoginX'),
2605
                        $o_user_to_add['username'],
2606
                        ENT_QUOTES
2607
                    )
2608
                );
2609
                $name = api_get_person_name(
2610
                        $o_user_to_add['firstname'],
2611
                        $o_user_to_add['lastname']
2612
                    )." . ".$username;
2613
                $photo = '<img src="'.$userPicture.'" alt="'.$name.'"  width="40" height="50" align="bottom" title="'.$name.'"  />';
2614
2615
                $is_tutor_of_group = GroupManager::is_tutor_of_group(
2616
                    $assig_user_id,
2617
                    $groupInfo
2618
                ); //student is tutor
2619
                $is_tutor_and_member = GroupManager::is_tutor_of_group(
2620
                        $assig_user_id,
2621
                        $groupInfo
2622
                    ) &&
2623
                    GroupManager::is_subscribed($assig_user_id, $groupInfo);
2624
                // student is tutor and member
2625
                if ($is_tutor_and_member) {
2626
                    $status_in_group = get_lang('GroupTutorAndMember');
2627
                } else {
2628
                    if ($is_tutor_of_group) {
2629
                        $status_in_group = get_lang('GroupTutor');
2630
                    } else {
2631
                        $status_in_group = " "; //get_lang('GroupStandardMember')
2632
                    }
2633
                }
2634
2635
                if ($assignment_type == 1) {
2636
                    $values['title'] = $title_orig;
2637
                    $values['content'] = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2638
                    <table border="0">
2639
                    <tr><td style="font-size:24px">'.get_lang('AssignmentWork').'</td></tr>
2640
                    <tr><td>'.$photo.'<br />'.$name.'</td></tr></table>
2641
                    </div>[['.$link2teacher.' | '.get_lang(
2642
                            'AssignmentLinktoTeacherPage'
2643
                        ).']] ';
2644
                    //If $content_orig_B is added here, the task written by
2645
                    // the professor was copied to the page of each student.
2646
                    // TODO: config options
2647
                    // AssignmentLinktoTeacherPage
2648
                    $all_students_pages[] = '<li>'.
2649
                        Display::tag(
2650
                            'span',
2651
                            strtoupper(
2652
                                $o_user_to_add['lastname']
2653
                            ).', '.$o_user_to_add['firstname'],
2654
                            ['title' => $username]
2655
                        ).
2656
                        ' [['.Security::remove_XSS(
2657
                            $_POST['title']
2658
                        )."_uass".$assig_user_id.' | '.$photo.']] '.$status_in_group.'</li>';
2659
                    // don't change this line without guaranteeing
2660
                    // that users will be ordered by last names in the
2661
                    // following format (surname, name)
2662
                    $values['assignment'] = 2;
2663
                }
2664
                $this->assig_user_id = $assig_user_id;
2665
                $this->save_new_wiki($values);
2666
            }
2667
        }
2668
2669
        foreach ($a_users_to_add as $o_user_to_add) {
2670
            if ($o_user_to_add['user_id'] == $userId) {
2671
                $assig_user_id = $o_user_to_add['user_id'];
2672
                if ($assignment_type == 1) {
2673
                    $values['title'] = $title_orig;
2674
                    $values['comment'] = get_lang('AssignmentDesc');
2675
                    sort($all_students_pages);
2676
                    $values['content'] = $content_orig_A.$content_orig_B.'<br/>
2677
                    <div align="center" style="font-size:18px; background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2678
                    '.get_lang('AssignmentLinkstoStudentsPage').'
2679
                    </div><br/>
2680
                    <div style="background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2681
                    <ol>'.implode($all_students_pages).'</ol>
2682
                    </div>
2683
                    <br/>';
2684
                    $values['assignment'] = 1;
2685
                }
2686
                $this->assig_user_id = $assig_user_id;
2687
                $this->save_new_wiki($values);
2688
            }
2689
        }
2690
    }
2691
2692
    /**
2693
     * Displays the results of a wiki search.
2694
     *
2695
     * @param   string  Search term
2696
     * @param   int     Whether to search the contents (1) or just the titles (0)
2697
     * @param int
2698
     */
2699
    public function display_wiki_search_results(
2700
        $search_term,
2701
        $search_content = 0,
2702
        $all_vers = 0
2703
    ) {
2704
        $tbl_wiki = $this->tbl_wiki;
2705
        $condition_session = $this->condition_session;
2706
        $groupfilter = $this->groupfilter;
2707
        $_course = $this->courseInfo;
2708
        $course_id = api_get_course_int_id();
2709
        echo '<legend>'.get_lang('WikiSearchResults').': '.Security::remove_XSS(
2710
                $search_term
2711
            );
2712
        echo '</legend>';
2713
2714
        //only by professors when page is hidden
2715
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
2716
            if ($all_vers == '1') {
2717
                if ($search_content == '1') {
2718
                    $sql = "SELECT * FROM ".$tbl_wiki."
2719
                            WHERE
2720
                                c_id = $course_id AND
2721
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2722
                                content LIKE '%".Database::escape_string(
2723
                            $search_term
2724
                        )."%' AND ".$groupfilter.$condition_session;
2725
                } else {
2726
                    $sql = "SELECT * FROM ".$tbl_wiki."
2727
                            WHERE
2728
                                c_id = $course_id AND
2729
                                title LIKE '%".Database::escape_string(
2730
                            $search_term
2731
                        )."%' AND ".$groupfilter.$condition_session;
2732
                }
2733
            } else {
2734
                if ($search_content == '1') {
2735
                    // warning don't use group by reflink because don't return the last version
2736
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2737
                            WHERE
2738
                                s1.c_id = $course_id AND
2739
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2740
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2741
                                id=(
2742
                                    SELECT MAX(s2.id)
2743
                                    FROM ".$tbl_wiki." s2
2744
                                    WHERE
2745
                                        s2.c_id = $course_id AND
2746
                                        s1.reflink = s2.reflink AND
2747
                                        ".$groupfilter.$condition_session.")";
2748
                } else {
2749
                    // warning don't use group by reflink because don't return the last version
2750
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2751
                            WHERE
2752
                                s1.c_id = $course_id AND
2753
                                title LIKE '%".Database::escape_string(
2754
                            $search_term
2755
                        )."%' AND
2756
                                id = (
2757
                                    SELECT MAX(s2.id)
2758
                                    FROM ".$tbl_wiki." s2
2759
                                    WHERE
2760
                                        s2.c_id = $course_id AND
2761
                                        s1.reflink = s2.reflink AND
2762
                                        ".$groupfilter.$condition_session.")";
2763
                }
2764
            }
2765
        } else {
2766
            if ($all_vers == '1') {
2767
                if ($search_content == '1') {
2768
                    //search all pages and all versions
2769
                    $sql = "SELECT * FROM ".$tbl_wiki."
2770
                            WHERE
2771
                                c_id = $course_id AND
2772
                                visibility=1 AND
2773
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2774
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2775
                                ".$groupfilter.$condition_session;
2776
                } else {
2777
                    $sql = "SELECT * FROM ".$tbl_wiki."
2778
                            WHERE
2779
                                c_id = $course_id AND
2780
                                visibility=1 AND
2781
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2782
                                ".$groupfilter.$condition_session;
2783
                }
2784
            } else {
2785
                if ($search_content == '1') {
2786
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2787
                            WHERE
2788
                                s1.c_id = $course_id AND
2789
                                visibility=1 AND
2790
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2791
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2792
                                id=(
2793
                                    SELECT MAX(s2.id)
2794
                                    FROM ".$tbl_wiki." s2
2795
                                    WHERE s2.c_id = $course_id AND
2796
                                    s1.reflink = s2.reflink AND
2797
                                    ".$groupfilter.$condition_session.")";
2798
                } else {
2799
                    // warning don't use group by reflink because don't return the last version
2800
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2801
                            WHERE
2802
                                s1.c_id = $course_id AND
2803
                                visibility=1 AND
2804
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2805
                            id = (
2806
                                SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
2807
                                WHERE s2.c_id = $course_id AND
2808
                                s1.reflink = s2.reflink AND
2809
                                ".$groupfilter.$condition_session.")";
2810
                }
2811
            }
2812
        }
2813
2814
        $result = Database::query($sql);
2815
2816
        //show table
2817
        $rows = [];
2818
        if (Database::num_rows($result) > 0) {
2819
            while ($obj = Database::fetch_object($result)) {
2820
                //get author
2821
                $userinfo = api_get_user_info($obj->user_id);
2822
                //get time
2823
                $year = substr($obj->dtime, 0, 4);
2824
                $month = substr($obj->dtime, 5, 2);
2825
                $day = substr($obj->dtime, 8, 2);
2826
                $hours = substr($obj->dtime, 11, 2);
2827
                $minutes = substr($obj->dtime, 14, 2);
2828
                $seconds = substr($obj->dtime, 17, 2);
2829
2830
                //get type assignment icon
2831
                if ($obj->assignment == 1) {
2832
                    $ShowAssignment = Display::return_icon(
2833
                        'wiki_assignment.png',
2834
                        get_lang('AssignmentDesc'),
2835
                        '',
2836
                        ICON_SIZE_SMALL
2837
                    );
2838
                } elseif ($obj->assignment == 2) {
2839
                    $ShowAssignment = Display::return_icon(
2840
                        'wiki_work.png',
2841
                        get_lang('AssignmentWork'),
2842
                        '',
2843
                        ICON_SIZE_SMALL
2844
                    );
2845
                } elseif ($obj->assignment == 0) {
2846
                    $ShowAssignment = Display::return_icon(
2847
                        'px_transparent.gif'
2848
                    );
2849
                }
2850
                $row = [];
2851
                $row[] = $ShowAssignment;
2852
2853
                if ($all_vers == '1') {
2854
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2855
                        ).'&action=showpage&title='.api_htmlentities(
2856
                            urlencode($obj->reflink)
2857
                        ).'&view='.$obj->id.'&session_id='.api_htmlentities(
2858
                            urlencode($_GET['$session_id'])
2859
                        ).'&group_id='.api_htmlentities(
2860
                            urlencode($_GET['group_id'])
2861
                        ).'">'.
2862
                        api_htmlentities($obj->title).'</a>';
2863
                } else {
2864
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2865
                        ).'&action=showpage&title='.api_htmlentities(
2866
                            urlencode($obj->reflink)
2867
                        ).'&session_id='.api_htmlentities(
2868
                            $_GET['session_id']
2869
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2870
                        $obj->title.'</a>';
2871
                }
2872
2873
                $row[] = ($obj->user_id != 0 && $userinfo !== false) ? UserManager::getUserProfileLink(
2874
                    $userinfo
2875
                ) : get_lang('Anonymous').' ('.$obj->user_ip.')';
2876
                $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
2877
2878
                if ($all_vers == '1') {
2879
                    $row[] = $obj->version;
2880
                } else {
2881
                    $showdelete = '';
2882
                    if (api_is_allowed_to_edit(
2883
                            false,
2884
                            true
2885
                        ) || api_is_platform_admin()) {
2886
                        $showdelete = ' <a href="'.api_get_self(
2887
                            ).'?'.api_get_cidreq(
2888
                            ).'&action=delete&title='.api_htmlentities(
2889
                                urlencode($obj->reflink)
2890
                            ).'&group_id='.api_htmlentities(
2891
                                $_GET['group_id']
2892
                            ).'">'.
2893
                            Display::return_icon(
2894
                                'delete.png',
2895
                                get_lang('Delete'),
2896
                                '',
2897
                                ICON_SIZE_SMALL
2898
                            );
2899
                    }
2900
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2901
                        ).'&action=edit&title='.api_htmlentities(
2902
                            urlencode($obj->reflink)
2903
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2904
                        Display::return_icon(
2905
                            'edit.png',
2906
                            get_lang('EditPage'),
2907
                            '',
2908
                            ICON_SIZE_SMALL
2909
                        ).'</a>
2910
                        <a href="'.api_get_self(
2911
                        ).'?cidReq='.$_course['code'].'&action=discuss&title='.api_htmlentities(
2912
                            urlencode($obj->reflink)
2913
                        ).'&session_id='.api_htmlentities(
2914
                            $_GET['session_id']
2915
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2916
                        Display::return_icon(
2917
                            'discuss.png',
2918
                            get_lang('Discuss'),
2919
                            '',
2920
                            ICON_SIZE_SMALL
2921
                        ).'</a>
2922
                        <a href="'.api_get_self(
2923
                        ).'?cidReq='.$_course['code'].'&action=history&title='.api_htmlentities(
2924
                            urlencode($obj->reflink)
2925
                        ).'&session_id='.api_htmlentities(
2926
                            $_GET['session_id']
2927
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2928
                        Display::return_icon(
2929
                            'history.png',
2930
                            get_lang('History'),
2931
                            '',
2932
                            ICON_SIZE_SMALL
2933
                        ).'</a> <a href="'.api_get_self(
2934
                        ).'?cidReq='.$_course['code'].'&action=links&title='.api_htmlentities(
2935
                            urlencode($obj->reflink)
2936
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2937
                        Display::return_icon(
2938
                            'what_link_here.png',
2939
                            get_lang('LinksPages'),
2940
                            '',
2941
                            ICON_SIZE_SMALL
2942
                        ).'</a>'.$showdelete;
2943
                }
2944
                $rows[] = $row;
2945
            }
2946
2947
            $table = new SortableTableFromArrayConfig(
2948
                $rows,
2949
                1,
2950
                10,
2951
                'SearchPages_table',
2952
                '',
2953
                '',
2954
                'ASC'
2955
            );
2956
            $table->set_additional_parameters(
2957
                [
2958
                    'cidReq' => $_GET['cidReq'],
2959
                    'action' => $_GET['action'],
2960
                    'group_id' => intval($_GET['group_id']),
2961
                    'mode_table' => 'yes2',
2962
                    'search_term' => $search_term,
2963
                    'search_content' => $search_content,
2964
                    'all_vers' => $all_vers,
2965
                ]
2966
            );
2967
            $table->set_header(
2968
                0,
2969
                get_lang('Type'),
2970
                true,
2971
                ['style' => 'width:30px;']
2972
            );
2973
            $table->set_header(1, get_lang('Title'), true);
2974
            if ($all_vers == '1') {
2975
                $table->set_header(2, get_lang('Author'), true);
2976
                $table->set_header(3, get_lang('Date'), true);
2977
                $table->set_header(4, get_lang('Version'), true);
2978
            } else {
2979
                $table->set_header(
2980
                    2,
2981
                    get_lang('Author').' ('.get_lang('LastVersion').')',
2982
                    true
2983
                );
2984
                $table->set_header(
2985
                    3,
2986
                    get_lang('Date').' ('.get_lang('LastVersion').')',
2987
                    true
2988
                );
2989
                $table->set_header(
2990
                    4,
2991
                    get_lang('Actions'),
2992
                    false,
2993
                    ['style' => 'width:130px;']
2994
                );
2995
            }
2996
            $table->display();
2997
        } else {
2998
            echo get_lang('NoSearchResults');
2999
        }
3000
    }
3001
3002
    /**
3003
     * Get wiki information.
3004
     *
3005
     * @param   int|bool wiki id
3006
     *
3007
     * @return array wiki data
3008
     */
3009
    public function getWikiDataFromDb($id)
3010
    {
3011
        $tbl_wiki = $this->tbl_wiki;
3012
        $course_id = api_get_course_int_id();
3013
        if ($id === false) {
3014
            return [];
3015
        }
3016
        $id = intval($id);
3017
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3018
                WHERE c_id = '.$course_id.' AND id = '.$id.' ';
3019
        $result = Database::query($sql);
3020
        $data = [];
3021
        while ($row = Database::fetch_array($result, 'ASSOC')) {
3022
            $data = $row;
3023
        }
3024
3025
        return $data;
3026
    }
3027
3028
    /**
3029
     * @param string $refLink
3030
     *
3031
     * @return array
3032
     */
3033
    public function getLastWikiData($refLink)
3034
    {
3035
        $tbl_wiki = $this->tbl_wiki;
3036
        $groupfilter = $this->groupfilter;
3037
        $condition_session = $this->condition_session;
3038
        $course_id = api_get_course_int_id();
3039
3040
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3041
                WHERE
3042
                    c_id = '.$course_id.' AND
3043
                    reflink="'.Database::escape_string($refLink).'" AND
3044
                    '.$groupfilter.$condition_session.'
3045
                ORDER BY id DESC';
3046
3047
        $result = Database::query($sql);
3048
3049
        return Database::fetch_array($result);
3050
    }
3051
3052
    /**
3053
     * Get wiki information.
3054
     *
3055
     * @param   string     wiki id
3056
     * @param int $courseId
3057
     *
3058
     * @return array wiki data
3059
     */
3060
    public function getPageByTitle($title, $courseId = null)
3061
    {
3062
        $tbl_wiki = $this->tbl_wiki;
3063
        if (empty($courseId)) {
3064
            $courseId = api_get_course_int_id();
3065
        } else {
3066
            $courseId = intval($courseId);
3067
        }
3068
3069
        if (empty($title) || empty($courseId)) {
3070
            return [];
3071
        }
3072
3073
        $title = Database::escape_string($title);
3074
        $sql = "SELECT * FROM $tbl_wiki
3075
                WHERE c_id = $courseId AND reflink = '$title'";
3076
        $result = Database::query($sql);
3077
        $data = [];
3078
        if (Database::num_rows($result)) {
3079
            $data = Database::fetch_array($result, 'ASSOC');
3080
        }
3081
3082
        return $data;
3083
    }
3084
3085
    /**
3086
     * @param string $title
3087
     * @param int    $courseId
3088
     * @param string
3089
     * @param string
3090
     *
3091
     * @return bool
3092
     */
3093
    public function deletePage(
3094
        $title,
3095
        $courseId,
3096
        $groupfilter = null,
3097
        $condition_session = null
3098
    ) {
3099
        $tbl_wiki = $this->tbl_wiki;
3100
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
3101
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
3102
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3103
3104
        $pageInfo = self::getPageByTitle($title, $courseId);
3105
        if (!empty($pageInfo)) {
3106
            $pageId = $pageInfo['id'];
3107
            $sql = "DELETE FROM $tbl_wiki_conf
3108
                    WHERE c_id = $courseId AND page_id = $pageId";
3109
            Database::query($sql);
3110
3111
            $sql = 'DELETE FROM '.$tbl_wiki_discuss.'
3112
                    WHERE c_id = '.$courseId.' AND publication_id = '.$pageId;
3113
            Database::query($sql);
3114
3115
            $sql = 'DELETE FROM  '.$tbl_wiki_mailcue.'
3116
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3117
            Database::query($sql);
3118
3119
            $sql = 'DELETE FROM '.$tbl_wiki.'
3120
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3121
            Database::query($sql);
3122
            self::check_emailcue(0, 'E');
3123
3124
            return true;
3125
        }
3126
3127
        return false;
3128
    }
3129
3130
    /**
3131
     * @return array
3132
     */
3133
    public function getAllWiki()
3134
    {
3135
        $tbl_wiki = $this->tbl_wiki;
3136
        $course_id = $this->course_id;
3137
        $condition_session = $this->condition_session;
3138
3139
        $sql = "SELECT * FROM $tbl_wiki
3140
                WHERE
3141
                    c_id = $course_id AND
3142
                    is_editing != '0' ".$condition_session;
3143
        $result = Database::query($sql);
3144
3145
        return Database::store_result($result, 'ASSOC');
3146
    }
3147
3148
    /**
3149
     * @param int $isEditing
3150
     */
3151
    public function updateWikiIsEditing($isEditing)
3152
    {
3153
        $tbl_wiki = $this->tbl_wiki;
3154
        $course_id = $this->course_id;
3155
        $condition_session = $this->condition_session;
3156
        $isEditing = Database::escape_string($isEditing);
3157
3158
        $sql = 'UPDATE '.$tbl_wiki.' SET
3159
                is_editing = "0",
3160
                time_edit = NULL
3161
                WHERE
3162
                    c_id = '.$course_id.' AND
3163
                    is_editing="'.$isEditing.'" '.
3164
            $condition_session;
3165
        Database::query($sql);
3166
    }
3167
3168
    /**
3169
     * Release of blocked pages to prevent concurrent editions.
3170
     *
3171
     * @param int    $userId
3172
     * @param string $action
3173
     */
3174
    public function blockConcurrentEditions($userId, $action = null)
3175
    {
3176
        $result = self::getAllWiki();
3177
        if (!empty($result)) {
3178
            foreach ($result as $is_editing_block) {
3179
                $max_edit_time = 1200; // 20 minutes
3180
                $timestamp_edit = strtotime($is_editing_block['time_edit']);
3181
                $time_editing = time() - $timestamp_edit;
3182
3183
                // First prevent concurrent users and double version
3184
                if ($is_editing_block['is_editing'] == $userId) {
3185
                    Session::write('_version', $is_editing_block['version']);
3186
                } else {
3187
                    Session::erase('_version');
3188
                }
3189
                // Second checks if has exceeded the time that a page may
3190
                // be available or if a page was edited and saved by its author
3191
                if ($time_editing > $max_edit_time ||
3192
                    ($is_editing_block['is_editing'] == $userId &&
3193
                        $action != 'edit')
3194
                ) {
3195
                    self::updateWikiIsEditing($is_editing_block['is_editing']);
3196
                }
3197
            }
3198
        }
3199
    }
3200
3201
    /**
3202
     * Showing wiki stats.
3203
     */
3204
    public function getStats()
3205
    {
3206
        if (!api_is_allowed_to_edit(false, true)) {
3207
            return false;
3208
        }
3209
3210
        $tbl_wiki = $this->tbl_wiki;
3211
        $course_id = $this->course_id;
3212
        $condition_session = $this->condition_session;
3213
        $groupfilter = $this->groupfilter;
3214
        $session_id = $this->session_id;
3215
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3216
3217
        echo '<div class="actions">'.get_lang('Statistics').'</div>';
3218
3219
        // Check all versions of all pages
3220
        $total_words = 0;
3221
        $total_links = 0;
3222
        $total_links_anchors = 0;
3223
        $total_links_mail = 0;
3224
        $total_links_ftp = 0;
3225
        $total_links_irc = 0;
3226
        $total_links_news = 0;
3227
        $total_wlinks = 0;
3228
        $total_images = 0;
3229
        $clean_total_flash = 0;
3230
        $total_flash = 0;
3231
        $total_mp3 = 0;
3232
        $total_flv_p = 0;
3233
        $total_flv = 0;
3234
        $total_youtube = 0;
3235
        $total_multimedia = 0;
3236
        $total_tables = 0;
3237
3238
        $sql = "SELECT *, COUNT(*) AS TOTAL_VERS, SUM(hits) AS TOTAL_VISITS
3239
                FROM ".$tbl_wiki."
3240
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3241
3242
        $allpages = Database::query($sql);
3243
        while ($row = Database::fetch_array($allpages)) {
3244
            $total_versions = $row['TOTAL_VERS'];
3245
            $total_visits = intval($row['TOTAL_VISITS']);
3246
        }
3247
3248
        $sql = "SELECT * FROM ".$tbl_wiki."
3249
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3250
        $allpages = Database::query($sql);
3251
3252
        while ($row = Database::fetch_array($allpages)) {
3253
            $total_words = $total_words + self::word_count($row['content']);
3254
            $total_links = $total_links + substr_count(
3255
                $row['content'],
3256
                "href="
3257
            );
3258
            $total_links_anchors = $total_links_anchors + substr_count(
3259
                $row['content'],
3260
                'href="#'
3261
            );
3262
            $total_links_mail = $total_links_mail + substr_count(
3263
                $row['content'],
3264
                'href="mailto'
3265
            );
3266
            $total_links_ftp = $total_links_ftp + substr_count(
3267
                $row['content'],
3268
                'href="ftp'
3269
            );
3270
            $total_links_irc = $total_links_irc + substr_count(
3271
                $row['content'],
3272
                'href="irc'
3273
            );
3274
            $total_links_news = $total_links_news + substr_count(
3275
                $row['content'],
3276
                'href="news'
3277
            );
3278
            $total_wlinks = $total_wlinks + substr_count($row['content'], "[[");
3279
            $total_images = $total_images + substr_count(
3280
                $row['content'],
3281
                "<img"
3282
            );
3283
            $clean_total_flash = preg_replace(
3284
                '/player.swf/',
3285
                ' ',
3286
                $row['content']
3287
            );
3288
            $total_flash = $total_flash + substr_count(
3289
                $clean_total_flash,
3290
                '.swf"'
3291
            );
3292
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3293
            $total_mp3 = $total_mp3 + substr_count($row['content'], ".mp3");
3294
            $total_flv_p = $total_flv_p + substr_count($row['content'], ".flv");
3295
            $total_flv = $total_flv_p / 5;
3296
            $total_youtube = $total_youtube + substr_count(
3297
                $row['content'],
3298
                "http://www.youtube.com"
3299
            );
3300
            $total_multimedia = $total_multimedia + substr_count(
3301
                $row['content'],
3302
                "video/x-msvideo"
3303
            );
3304
            $total_tables = $total_tables + substr_count(
3305
                $row['content'],
3306
                "<table"
3307
            );
3308
        }
3309
3310
        // Check only last version of all pages (current page)
3311
        $sql = ' SELECT *, COUNT(*) AS TOTAL_PAGES, SUM(hits) AS TOTAL_VISITS_LV
3312
                FROM  '.$tbl_wiki.' s1
3313
                WHERE s1.c_id = '.$course_id.' AND id=(
3314
                    SELECT MAX(s2.id)
3315
                    FROM '.$tbl_wiki.' s2
3316
                    WHERE
3317
                        s2.c_id = '.$course_id.' AND
3318
                        s1.reflink = s2.reflink AND
3319
                        '.$groupfilter.' AND
3320
                        session_id='.$session_id.')';
3321
        $allpages = Database::query($sql);
3322
        while ($row = Database::fetch_array($allpages)) {
3323
            $total_pages = $row['TOTAL_PAGES'];
3324
            $total_visits_lv = intval($row['TOTAL_VISITS_LV']);
3325
        }
3326
3327
        $total_words_lv = 0;
3328
        $total_links_lv = 0;
3329
        $total_links_anchors_lv = 0;
3330
        $total_links_mail_lv = 0;
3331
        $total_links_ftp_lv = 0;
3332
        $total_links_irc_lv = 0;
3333
        $total_links_news_lv = 0;
3334
        $total_wlinks_lv = 0;
3335
        $total_images_lv = 0;
3336
        $clean_total_flash_lv = 0;
3337
        $total_flash_lv = 0;
3338
        $total_mp3_lv = 0;
3339
        $total_flv_p_lv = 0;
3340
        $total_flv_lv = 0;
3341
        $total_youtube_lv = 0;
3342
        $total_multimedia_lv = 0;
3343
        $total_tables_lv = 0;
3344
3345
        $sql = 'SELECT * FROM  '.$tbl_wiki.' s1
3346
                WHERE s1.c_id = '.$course_id.' AND id=(
3347
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3348
                    WHERE
3349
                        s2.c_id = '.$course_id.' AND
3350
                        s1.reflink = s2.reflink AND
3351
                        '.$groupfilter.' AND
3352
                        session_id='.$session_id.'
3353
                )';
3354
        $allpages = Database::query($sql);
3355
3356
        while ($row = Database::fetch_array($allpages)) {
3357
            $total_words_lv = $total_words_lv + self::word_count(
3358
                $row['content']
3359
            );
3360
            $total_links_lv = $total_links_lv + substr_count(
3361
                $row['content'],
3362
                "href="
3363
            );
3364
            $total_links_anchors_lv = $total_links_anchors_lv + substr_count(
3365
                $row['content'],
3366
                'href="#'
3367
            );
3368
            $total_links_mail_lv = $total_links_mail_lv + substr_count(
3369
                $row['content'],
3370
                'href="mailto'
3371
            );
3372
            $total_links_ftp_lv = $total_links_ftp_lv + substr_count(
3373
                $row['content'],
3374
                'href="ftp'
3375
            );
3376
            $total_links_irc_lv = $total_links_irc_lv + substr_count(
3377
                $row['content'],
3378
                'href="irc'
3379
            );
3380
            $total_links_news_lv = $total_links_news_lv + substr_count(
3381
                $row['content'],
3382
                'href="news'
3383
            );
3384
            $total_wlinks_lv = $total_wlinks_lv + substr_count(
3385
                $row['content'],
3386
                "[["
3387
            );
3388
            $total_images_lv = $total_images_lv + substr_count(
3389
                $row['content'],
3390
                "<img"
3391
            );
3392
            $clean_total_flash_lv = preg_replace(
3393
                '/player.swf/',
3394
                ' ',
3395
                $row['content']
3396
            );
3397
            $total_flash_lv = $total_flash_lv + substr_count(
3398
                $clean_total_flash_lv,
3399
                '.swf"'
3400
            );
3401
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3402
            $total_mp3_lv = $total_mp3_lv + substr_count(
3403
                $row['content'],
3404
                ".mp3"
3405
            );
3406
            $total_flv_p_lv = $total_flv_p_lv + substr_count(
3407
                $row['content'],
3408
                ".flv"
3409
            );
3410
            $total_flv_lv = $total_flv_p_lv / 5;
3411
            $total_youtube_lv = $total_youtube_lv + substr_count(
3412
                $row['content'],
3413
                "http://www.youtube.com"
3414
            );
3415
            $total_multimedia_lv = $total_multimedia_lv + substr_count(
3416
                $row['content'],
3417
                "video/x-msvideo"
3418
            );
3419
            $total_tables_lv = $total_tables_lv + substr_count(
3420
                $row['content'],
3421
                "<table"
3422
            );
3423
        }
3424
3425
        //Total pages edited at this time
3426
        $total_editing_now = 0;
3427
        $sql = 'SELECT *, COUNT(*) AS TOTAL_EDITING_NOW
3428
                FROM  '.$tbl_wiki.' s1
3429
                WHERE is_editing!=0 AND s1.c_id = '.$course_id.' AND
3430
                id=(
3431
                    SELECT MAX(s2.id)
3432
                    FROM '.$tbl_wiki.' s2
3433
                    WHERE
3434
                        s2.c_id = '.$course_id.' AND
3435
                        s1.reflink = s2.reflink AND
3436
                        '.$groupfilter.' AND
3437
                        session_id='.$session_id.'
3438
        )';
3439
3440
        // Can not use group by because the mark is set in the latest version
3441
        $allpages = Database::query($sql);
3442
        while ($row = Database::fetch_array($allpages)) {
3443
            $total_editing_now = $row['TOTAL_EDITING_NOW'];
3444
        }
3445
3446
        // Total hidden pages
3447
        $total_hidden = 0;
3448
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3449
                WHERE
3450
                    c_id = '.$course_id.' AND
3451
                    visibility = 0 AND
3452
                    '.$groupfilter.$condition_session.'
3453
                GROUP BY reflink';
3454
        // or group by page_id. As the mark of hidden places it in all
3455
        // versions of the page, I can use group by to see the first
3456
        $allpages = Database::query($sql);
3457
        while ($row = Database::fetch_array($allpages)) {
3458
            $total_hidden = $total_hidden + 1;
3459
        }
3460
3461
        //Total protect pages
3462
        $total_protected = 0;
3463
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3464
                WHERE
3465
                    c_id = '.$course_id.' AND
3466
                    editlock = 1 AND
3467
                     '.$groupfilter.$condition_session.'
3468
                GROUP BY reflink';
3469
        // or group by page_id. As the mark of protected page is the
3470
        // first version of the page, I can use group by
3471
        $allpages = Database::query($sql);
3472
        while ($row = Database::fetch_array($allpages)) {
3473
            $total_protected = $total_protected + 1;
3474
        }
3475
3476
        // Total empty versions.
3477
        $total_empty_content = 0;
3478
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3479
                WHERE
3480
                    c_id = '.$course_id.' AND
3481
                    content="" AND
3482
                    '.$groupfilter.$condition_session.'';
3483
        $allpages = Database::query($sql);
3484
        while ($row = Database::fetch_array($allpages)) {
3485
            $total_empty_content = $total_empty_content + 1;
3486
        }
3487
3488
        //Total empty pages (last version)
3489
3490
        $total_empty_content_lv = 0;
3491
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3492
                WHERE s1.c_id = '.$course_id.' AND content="" AND id=(
3493
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3494
                    WHERE
3495
                        s1.c_id = '.$course_id.' AND
3496
                        s1.reflink = s2.reflink AND
3497
                        '.$groupfilter.' AND
3498
                        session_id='.$session_id.'
3499
                )';
3500
        $allpages = Database::query($sql);
3501
        while ($row = Database::fetch_array($allpages)) {
3502
            $total_empty_content_lv = $total_empty_content_lv + 1;
3503
        }
3504
3505
        // Total locked discuss pages
3506
        $total_lock_disc = 0;
3507
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3508
                WHERE c_id = '.$course_id.' AND addlock_disc=0 AND '.$groupfilter.$condition_session.'
3509
                GROUP BY reflink'; //group by because mark lock in all vers, then always is ok
3510
        $allpages = Database::query($sql);
3511
        while ($row = Database::fetch_array($allpages)) {
3512
            $total_lock_disc = $total_lock_disc + 1;
3513
        }
3514
3515
        // Total hidden discuss pages.
3516
        $total_hidden_disc = 0;
3517
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3518
                WHERE c_id = '.$course_id.' AND visibility_disc=0 AND '.$groupfilter.$condition_session.'
3519
                GROUP BY reflink';
3520
        //group by because mark lock in all vers, then always is ok
3521
        $allpages = Database::query($sql);
3522
        while ($row = Database::fetch_array($allpages)) {
3523
            $total_hidden_disc = $total_hidden_disc + 1;
3524
        }
3525
3526
        // Total versions with any short comment by user or system
3527
        $total_comment_version = 0;
3528
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3529
                WHERE c_id = '.$course_id.' AND comment!="" AND '.$groupfilter.$condition_session.'';
3530
        $allpages = Database::query($sql);
3531
        while ($row = Database::fetch_array($allpages)) {
3532
            $total_comment_version = $total_comment_version + 1;
3533
        }
3534
3535
        // Total pages that can only be scored by teachers.
3536
        $total_only_teachers_rating = 0;
3537
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3538
                WHERE c_id = '.$course_id.' AND
3539
                ratinglock_disc = 0 AND
3540
                '.$groupfilter.$condition_session.'
3541
                GROUP BY reflink'; //group by because mark lock in all vers, then always is ok
3542
        $allpages = Database::query($sql);
3543
        while ($row = Database::fetch_array($allpages)) {
3544
            $total_only_teachers_rating = $total_only_teachers_rating + 1;
3545
        }
3546
3547
        // Total pages scored by peers
3548
        // put always this line alfter check num all pages and num pages rated by teachers
3549
        $total_rating_by_peers = $total_pages - $total_only_teachers_rating;
3550
3551
        //Total pages identified as standard task
3552
        $total_task = 0;
3553
        $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
3554
              WHERE '.$tbl_wiki_conf.'.c_id = '.$course_id.' AND
3555
               '.$tbl_wiki_conf.'.task!="" AND
3556
               '.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
3557
                '.$tbl_wiki.'.'.$groupfilter.$condition_session;
3558
        $allpages = Database::query($sql);
3559
        while ($row = Database::fetch_array($allpages)) {
3560
            $total_task = $total_task + 1;
3561
        }
3562
3563
        //Total pages identified as teacher page (wiki portfolio mode - individual assignment)
3564
        $total_teacher_assignment = 0;
3565
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3566
                WHERE s1.c_id = '.$course_id.' AND assignment=1 AND id=(
3567
                    SELECT MAX(s2.id)
3568
                    FROM '.$tbl_wiki.' s2
3569
                    WHERE
3570
                        s2.c_id = '.$course_id.' AND
3571
                        s1.reflink = s2.reflink AND
3572
                        '.$groupfilter.' AND
3573
                         session_id='.$session_id.'
3574
                )';
3575
        //mark all versions, but do not use group by reflink because y want the pages not versions
3576
        $allpages = Database::query($sql);
3577
        while ($row = Database::fetch_array($allpages)) {
3578
            $total_teacher_assignment = $total_teacher_assignment + 1;
3579
        }
3580
3581
        //Total pages identifies as student page (wiki portfolio mode - individual assignment)
3582
        $total_student_assignment = 0;
3583
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3584
                WHERE s1.c_id = '.$course_id.' AND assignment=2 AND
3585
                id = (SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3586
                WHERE
3587
                    s2.c_id = '.$course_id.' AND
3588
                    s1.reflink = s2.reflink AND
3589
                    '.$groupfilter.' AND
3590
                    session_id='.$session_id.'
3591
                )';
3592
        //mark all versions, but do not use group by reflink because y want the pages not versions
3593
        $allpages = Database::query($sql);
3594
        while ($row = Database::fetch_array($allpages)) {
3595
            $total_student_assignment = $total_student_assignment + 1;
3596
        }
3597
3598
        //Current Wiki status add new pages
3599
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3600
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3601
                GROUP BY addlock'; //group by because mark 0 in all vers, then always is ok
3602
        $allpages = Database::query($sql);
3603
        $wiki_add_lock = null;
3604
        while ($row = Database::fetch_array($allpages)) {
3605
            $wiki_add_lock = $row['addlock'];
3606
        }
3607
3608
        if ($wiki_add_lock == 1) {
3609
            $status_add_new_pag = get_lang('Yes');
3610
        } else {
3611
            $status_add_new_pag = get_lang('No');
3612
        }
3613
3614
        // Creation date of the oldest wiki page and version
3615
        $first_wiki_date = null;
3616
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3617
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3618
                ORDER BY dtime ASC
3619
                LIMIT 1';
3620
        $allpages = Database::query($sql);
3621
        while ($row = Database::fetch_array($allpages)) {
3622
            $first_wiki_date = api_get_local_time($row['dtime']);
3623
        }
3624
3625
        // Date of publication of the latest wiki version.
3626
3627
        $last_wiki_date = null;
3628
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3629
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3630
                ORDER BY dtime DESC
3631
                LIMIT 1';
3632
        $allpages = Database::query($sql);
3633
        while ($row = Database::fetch_array($allpages)) {
3634
            $last_wiki_date = api_get_local_time($row['dtime']);
3635
        }
3636
3637
        // Average score of all wiki pages. (If a page has not scored zero rated)
3638
        $media_score = 0;
3639
        $sql = "SELECT *, SUM(score) AS TOTAL_SCORE FROM ".$tbl_wiki."
3640
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."
3641
                GROUP BY reflink ";
3642
        //group by because mark in all versions, then always is ok.
3643
        // Do not use "count" because using "group by", would give a wrong value
3644
        $allpages = Database::query($sql);
3645
        $total_score = 0;
3646
        while ($row = Database::fetch_array($allpages)) {
3647
            $total_score = $total_score + $row['TOTAL_SCORE'];
3648
        }
3649
3650
        if (!empty($total_pages)) {
3651
            $media_score = $total_score / $total_pages;
3652
            //put always this line alfter check num all pages
3653
        }
3654
3655
        // Average user progress in his pages.
3656
        $media_progress = 0;
3657
        $sql = 'SELECT  *, SUM(progress) AS TOTAL_PROGRESS
3658
                FROM  '.$tbl_wiki.' s1
3659
                WHERE s1.c_id = '.$course_id.' AND id=
3660
                (
3661
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3662
                    WHERE
3663
                        s2.c_id = '.$course_id.' AND
3664
                        s1.reflink = s2.reflink AND
3665
                        '.$groupfilter.' AND
3666
                        session_id='.$session_id.'
3667
                )';
3668
        // As the value is only the latest version I can not use group by
3669
        $allpages = Database::query($sql);
3670
        while ($row = Database::fetch_array($allpages)) {
3671
            $total_progress = $row['TOTAL_PROGRESS'];
3672
        }
3673
3674
        if (!empty($total_pages)) {
3675
            $media_progress = $total_progress / $total_pages;
3676
            //put always this line alfter check num all pages
3677
        }
3678
3679
        // Total users that have participated in the Wiki
3680
        $total_users = 0;
3681
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3682
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3683
                GROUP BY user_id';
3684
        //as the mark of user it in all versions of the page, I can use group by to see the first
3685
        $allpages = Database::query($sql);
3686
        while ($row = Database::fetch_array($allpages)) {
3687
            $total_users = $total_users + 1;
3688
        }
3689
3690
        // Total of different IP addresses that have participated in the wiki
3691
        $total_ip = 0;
3692
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3693
              WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3694
              GROUP BY user_ip';
3695
        $allpages = Database::query($sql);
3696
        while ($row = Database::fetch_array($allpages)) {
3697
            $total_ip = $total_ip + 1;
3698
        }
3699
3700
        echo '<table class="table table-hover table-striped data_table">';
3701
        echo '<thead>';
3702
        echo '<tr>';
3703
        echo '<th colspan="2">'.get_lang('General').'</th>';
3704
        echo '</tr>';
3705
        echo '</thead>';
3706
        echo '<tr>';
3707
        echo '<td>'.get_lang('StudentAddNewPages').'</td>';
3708
        echo '<td>'.$status_add_new_pag.'</td>';
3709
        echo '</tr>';
3710
        echo '<tr>';
3711
        echo '<td>'.get_lang('DateCreateOldestWikiPage').'</td>';
3712
        echo '<td>'.$first_wiki_date.'</td>';
3713
        echo '</tr>';
3714
        echo '<tr>';
3715
        echo '<td>'.get_lang('DateEditLatestWikiVersion').'</td>';
3716
        echo '<td>'.$last_wiki_date.'</td>';
3717
        echo '</tr>';
3718
        echo '<tr>';
3719
        echo '<td>'.get_lang('AverageScoreAllPages').'</td>';
3720
        echo '<td>'.$media_score.' %</td>';
3721
        echo '</tr>';
3722
        echo '<tr>';
3723
        echo '<td>'.get_lang('AverageMediaUserProgress').'</td>';
3724
        echo '<td>'.$media_progress.' %</td>';
3725
        echo '</tr>';
3726
        echo '<tr>';
3727
        echo '<td>'.get_lang('TotalWikiUsers').'</td>';
3728
        echo '<td>'.$total_users.'</td>';
3729
        echo '</tr>';
3730
        echo '<tr>';
3731
        echo '<td>'.get_lang('TotalIpAdress').'</td>';
3732
        echo '<td>'.$total_ip.'</td>';
3733
        echo '</tr>';
3734
        echo '</table>';
3735
        echo '<br/>';
3736
3737
        echo '<table class="table table-hover table-striped data_table">';
3738
        echo '<thead>';
3739
        echo '<tr>';
3740
        echo '<th colspan="2">'.get_lang('Pages').' '.get_lang(
3741
                'And'
3742
            ).' '.get_lang('Versions').'</th>';
3743
        echo '</tr>';
3744
        echo '</thead>';
3745
        echo '<tr>';
3746
        echo '<td>'.get_lang('Pages').' - '.get_lang(
3747
                'NumContributions'
3748
            ).'</td>';
3749
        echo '<td>'.$total_pages.' ('.get_lang(
3750
                'Versions'
3751
            ).': '.$total_versions.')</td>';
3752
        echo '</tr>';
3753
        echo '<tr>';
3754
        echo '<td>'.get_lang('EmptyPages').'</td>';
3755
        echo '<td>'.$total_empty_content_lv.' ('.get_lang(
3756
                'Versions'
3757
            ).': '.$total_empty_content.')</td>';
3758
        echo '</tr>';
3759
        echo '<tr>';
3760
        echo '<td>'.get_lang('NumAccess').'</td>';
3761
        echo '<td>'.$total_visits_lv.' ('.get_lang(
3762
                'Versions'
3763
            ).': '.$total_visits.')</td>';
3764
        echo '</tr>';
3765
        echo '<tr>';
3766
        echo '<td>'.get_lang('TotalPagesEditedAtThisTime').'</td>';
3767
        echo '<td>'.$total_editing_now.'</td>';
3768
        echo '</tr>';
3769
        echo '<tr>';
3770
        echo '<td>'.get_lang('TotalHiddenPages').'</td>';
3771
        echo '<td>'.$total_hidden.'</td>';
3772
        echo '</tr>';
3773
        echo '<tr>';
3774
        echo '<td>'.get_lang('NumProtectedPages').'</td>';
3775
        echo '<td>'.$total_protected.'</td>';
3776
        echo '</tr>';
3777
        echo '<tr>';
3778
        echo '<td>'.get_lang('LockedDiscussPages').'</td>';
3779
        echo '<td>'.$total_lock_disc.'</td>';
3780
        echo '</tr>';
3781
        echo '<tr>';
3782
        echo '<td>'.get_lang('HiddenDiscussPages').'</td>';
3783
        echo '<td>'.$total_hidden_disc.'</td>';
3784
        echo '</tr>';
3785
        echo '<tr>';
3786
        echo '<td>'.get_lang('TotalComments').'</td>';
3787
        echo '<td>'.$total_comment_version.'</td>';
3788
        echo '</tr>';
3789
        echo '<tr>';
3790
        echo '<td>'.get_lang('TotalOnlyRatingByTeacher').'</td>';
3791
        echo '<td>'.$total_only_teachers_rating.'</td>';
3792
        echo '</tr>';
3793
        echo '<tr>';
3794
        echo '<td>'.get_lang('TotalRatingPeers').'</td>';
3795
        echo '<td>'.$total_rating_by_peers.'</td>';
3796
        echo '</tr>';
3797
        echo '<tr>';
3798
        echo '<td>'.get_lang('TotalTeacherAssignments').' - '.get_lang(
3799
                'PortfolioMode'
3800
            ).'</td>';
3801
        echo '<td>'.$total_teacher_assignment.'</td>';
3802
        echo '</tr>';
3803
        echo '<tr>';
3804
        echo '<td>'.get_lang('TotalStudentAssignments').' - '.get_lang(
3805
                'PortfolioMode'
3806
            ).'</td>';
3807
        echo '<td>'.$total_student_assignment.'</td>';
3808
        echo '</tr>';
3809
        echo '<tr>';
3810
        echo '<td>'.get_lang('TotalTask').' - '.get_lang(
3811
                'StandardMode'
3812
            ).'</td>';
3813
        echo '<td>'.$total_task.'</td>';
3814
        echo '</tr>';
3815
        echo '</table>';
3816
        echo '<br/>';
3817
3818
        echo '<table class="table table-hover table-striped data_table">';
3819
        echo '<thead>';
3820
        echo '<tr>';
3821
        echo '<th colspan="3">'.get_lang('ContentPagesInfo').'</th>';
3822
        echo '</tr>';
3823
        echo '<tr>';
3824
        echo '<td></td>';
3825
        echo '<td>'.get_lang('InTheLastVersion').'</td>';
3826
        echo '<td>'.get_lang('InAllVersions').'</td>';
3827
        echo '</tr>';
3828
        echo '</thead>';
3829
        echo '<tr>';
3830
        echo '<td>'.get_lang('NumWords').'</td>';
3831
        echo '<td>'.$total_words_lv.'</td>';
3832
        echo '<td>'.$total_words.'</td>';
3833
        echo '</tr>';
3834
        echo '<tr>';
3835
        echo '<td>'.get_lang('NumlinksHtmlImagMedia').'</td>';
3836
        echo '<td>'.$total_links_lv.' ('.get_lang(
3837
                'Anchors'
3838
            ).':'.$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>';
3839
        echo '<td>'.$total_links.' ('.get_lang(
3840
                'Anchors'
3841
            ).':'.$total_links_anchors.', Mail:'.$total_links_mail.', FTP:'.$total_links_ftp.', IRC:'.$total_links_irc.', News:'.$total_links_news.', ... ) </td>';
3842
        echo '</tr>';
3843
        echo '<tr>';
3844
        echo '<td>'.get_lang('NumWikilinks').'</td>';
3845
        echo '<td>'.$total_wlinks_lv.'</td>';
3846
        echo '<td>'.$total_wlinks.'</td>';
3847
        echo '</tr>';
3848
        echo '<tr>';
3849
        echo '<td>'.get_lang('NumImages').'</td>';
3850
        echo '<td>'.$total_images_lv.'</td>';
3851
        echo '<td>'.$total_images.'</td>';
3852
        echo '</tr>';
3853
        echo '<tr>';
3854
        echo '<td>'.get_lang('NumFlash').'</td>';
3855
        echo '<td>'.$total_flash_lv.'</td>';
3856
        echo '<td>'.$total_flash.'</td>';
3857
        echo '</tr>';
3858
        echo '<tr>';
3859
        echo '<td>'.get_lang('NumMp3').'</td>';
3860
        echo '<td>'.$total_mp3_lv.'</td>';
3861
        echo '<td>'.$total_mp3.'</td>';
3862
        echo '</tr>';
3863
        echo '<tr>';
3864
        echo '<td>'.get_lang('NumFlvVideo').'</td>';
3865
        echo '<td>'.$total_flv_lv.'</td>';
3866
        echo '<td>'.$total_flv.'</td>';
3867
        echo '</tr>';
3868
        echo '<tr>';
3869
        echo '<td>'.get_lang('NumYoutubeVideo').'</td>';
3870
        echo '<td>'.$total_youtube_lv.'</td>';
3871
        echo '<td>'.$total_youtube.'</td>';
3872
        echo '</tr>';
3873
        echo '<tr>';
3874
        echo '<td>'.get_lang('NumOtherAudioVideo').'</td>';
3875
        echo '<td>'.$total_multimedia_lv.'</td>';
3876
        echo '<td>'.$total_multimedia.'</td>';
3877
        echo '</tr>';
3878
        echo '<tr>';
3879
        echo '<td>'.get_lang('NumTables').'</td>';
3880
        echo '<td>'.$total_tables_lv.'</td>';
3881
        echo '<td>'.$total_tables.'</td>';
3882
        echo '</tr>';
3883
        echo '</table>';
3884
    }
3885
3886
    /**
3887
     * @param string $action
3888
     */
3889
    public function getActiveUsers($action)
3890
    {
3891
        $tbl_wiki = $this->tbl_wiki;
3892
        $course_id = $this->course_id;
3893
        $condition_session = $this->condition_session;
3894
        $groupfilter = $this->groupfilter;
3895
        $_course = $this->courseInfo;
3896
3897
        echo '<div class="actions">'.get_lang('MostActiveUsers').'</div>';
3898
        $sql = 'SELECT *, COUNT(*) AS NUM_EDIT FROM '.$tbl_wiki.'
3899
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3900
                GROUP BY user_id';
3901
        $allpages = Database::query($sql);
3902
3903
        //show table
3904
        if (Database::num_rows($allpages) > 0) {
3905
            while ($obj = Database::fetch_object($allpages)) {
3906
                $userinfo = api_get_user_info($obj->user_id);
3907
                $row = [];
3908
                if ($obj->user_id != 0 && $userinfo !== false) {
3909
                    $row[] = UserManager::getUserProfileLink($userinfo).'
3910
                            <a href="'.api_get_self(
3911
                        ).'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode(
3912
                            $obj->user_id
3913
                        ).
3914
                        '&session_id='.api_htmlentities(
3915
                            $_GET['session_id']
3916
                        ).'&group_id='.api_htmlentities(
3917
                            $_GET['group_id']
3918
                        ).'"></a>';
3919
                } else {
3920
                    $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
3921
                }
3922
                $row[] = '<a href="'.api_get_self(
3923
                    ).'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode(
3924
                        $obj->user_id
3925
                    ).'&session_id='.api_htmlentities(
3926
                        $_GET['session_id']
3927
                    ).'&group_id='.api_htmlentities(
3928
                        $_GET['group_id']
3929
                    ).'">'.$obj->NUM_EDIT.'</a>';
3930
                $rows[] = $row;
3931
            }
3932
3933
            $table = new SortableTableFromArrayConfig(
3934
                $rows,
3935
                1,
3936
                10,
3937
                'MostActiveUsersA_table',
3938
                '',
3939
                '',
3940
                'DESC'
3941
            );
3942
            $table->set_additional_parameters(
3943
                [
3944
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
3945
                    'action' => Security::remove_XSS($action),
3946
                    'session_id' => Security::remove_XSS($_GET['session_id']),
3947
                    'group_id' => Security::remove_XSS($_GET['group_id']),
3948
                ]
3949
            );
3950
            $table->set_header(0, get_lang('Author'), true);
3951
            $table->set_header(
3952
                1,
3953
                get_lang('Contributions'),
3954
                true,
3955
                ['style' => 'width:30px;']
3956
            );
3957
            $table->display();
3958
        }
3959
    }
3960
3961
    /**
3962
     * @param string $page
3963
     */
3964
    public function getDiscuss($page)
3965
    {
3966
        $tbl_wiki = $this->tbl_wiki;
3967
        $course_id = $this->course_id;
3968
        $condition_session = $this->condition_session;
3969
        $groupfilter = $this->groupfilter;
3970
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
3971
3972
        if (api_get_session_id() != 0 &&
3973
            api_is_allowed_to_session_edit(false, true) == false
3974
        ) {
3975
            api_not_allowed();
3976
        }
3977
3978
        if (!$_GET['title']) {
3979
            Display::addFlash(
3980
                Display::return_message(
3981
                    get_lang("MustSelectPage"),
3982
                    'error',
3983
                    false
3984
                )
3985
            );
3986
3987
            return;
3988
        }
3989
3990
        // First extract the date of last version
3991
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3992
                WHERE
3993
                    c_id = '.$course_id.' AND
3994
                    reflink = "'.Database::escape_string($page).'" AND
3995
                    '.$groupfilter.$condition_session.'
3996
                ORDER BY id DESC';
3997
        $result = Database::query($sql);
3998
        $row = Database::fetch_array($result);
3999
        $lastversiondate = api_get_local_time($row['dtime']);
4000
        $lastuserinfo = api_get_user_info($row['user_id']);
4001
4002
        // Select page to discuss
4003
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4004
                WHERE
4005
                    c_id = '.$course_id.' AND
4006
                    reflink="'.Database::escape_string($page).'" AND
4007
                    '.$groupfilter.$condition_session.'
4008
                ORDER BY id ASC';
4009
        $result = Database::query($sql);
4010
        $row = Database::fetch_array($result);
4011
        $id = $row['id'];
4012
        $firstuserid = $row['user_id'];
4013
4014
        if (isset($_POST['Submit']) && self::double_post($_POST['wpost_id'])) {
4015
            $dtime = api_get_utc_datetime();
4016
            $message_author = api_get_user_id();
4017
4018
            $params = [
4019
                'c_id' => $course_id,
4020
                'publication_id' => $id,
4021
                'userc_id' => $message_author,
4022
                'comment' => $_POST['comment'],
4023
                'p_score' => $_POST['rating'],
4024
                'dtime' => $dtime,
4025
            ];
4026
            $discussId = Database::insert($tbl_wiki_discuss, $params);
4027
            if ($discussId) {
4028
                $sql = "UPDATE $tbl_wiki_discuss SET id = iid WHERE iid = $discussId";
4029
                Database::query($sql);
4030
            }
4031
4032
            self::check_emailcue($id, 'D', $dtime, $message_author);
4033
4034
            header(
4035
                'Location: index.php?action=discuss&title='.api_htmlentities(urlencode($page)).'&'.api_get_cidreq()
4036
            );
4037
            exit;
4038
        }
4039
4040
        // mode assignment: previous to show  page type
4041
        $icon_assignment = null;
4042
        if ($row['assignment'] == 1) {
4043
            $icon_assignment = Display::return_icon(
4044
                'wiki_assignment.png',
4045
                get_lang('AssignmentDescExtra'),
4046
                '',
4047
                ICON_SIZE_SMALL
4048
            );
4049
        } elseif ($row['assignment'] == 2) {
4050
            $icon_assignment = Display::return_icon(
4051
                'wiki_work.png',
4052
                get_lang('AssignmentWorkExtra'),
4053
                '',
4054
                ICON_SIZE_SMALL
4055
            );
4056
        }
4057
4058
        $countWPost = null;
4059
        $avg_WPost_score = null;
4060
4061
        // Show title and form to discuss if page exist
4062
        if ($id != '') {
4063
            // Show discussion to students if isn't hidden.
4064
            // Show page to all teachers if is hidden.
4065
            // Mode assignments: If is hidden, show pages to student only if student is the author
4066
            if ($row['visibility_disc'] == 1 ||
4067
                api_is_allowed_to_edit(false, true) ||
4068
                api_is_platform_admin() ||
4069
                ($row['assignment'] == 2 && $row['visibility_disc'] == 0 && (api_get_user_id() == $row['user_id']))
4070
            ) {
4071
                echo '<div id="wikititle">';
4072
                // discussion action: protecting (locking) the discussion
4073
                $addlock_disc = null;
4074
                $lock_unlock_disc = null;
4075
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4076
                    if (self::check_addlock_discuss() == 1) {
4077
                        $addlock_disc = Display::return_icon(
4078
                            'unlock.png',
4079
                            get_lang('UnlockDiscussExtra'),
4080
                            '',
4081
                            ICON_SIZE_SMALL
4082
                        );
4083
                        $lock_unlock_disc = 'unlockdisc';
4084
                    } else {
4085
                        $addlock_disc = Display::return_icon(
4086
                            'lock.png',
4087
                            get_lang('LockDiscussExtra'),
4088
                            '',
4089
                            ICON_SIZE_SMALL
4090
                        );
4091
                        $lock_unlock_disc = 'lockdisc';
4092
                    }
4093
                }
4094
                echo '<span style="float:right">';
4095
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_disc.'&title='.api_htmlentities(
4096
                        urlencode($page)
4097
                    ).'">'.$addlock_disc.'</a>';
4098
                echo '</span>';
4099
4100
                // discussion action: visibility.  Show discussion to students if isn't hidden. Show page to all teachers if is hidden.
4101
                $visibility_disc = null;
4102
                $hide_show_disc = null;
4103
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4104
                    if (self::check_visibility_discuss() == 1) {
4105
                        /// TODO: 	Fix Mode assignments: If is hidden, show discussion to student only if student is the author
4106
                        $visibility_disc = Display::return_icon(
4107
                            'visible.png',
4108
                            get_lang('ShowDiscussExtra'),
4109
                            '',
4110
                            ICON_SIZE_SMALL
4111
                        );
4112
                        $hide_show_disc = 'hidedisc';
4113
                    } else {
4114
                        $visibility_disc = Display::return_icon(
4115
                            'invisible.png',
4116
                            get_lang('HideDiscussExtra'),
4117
                            '',
4118
                            ICON_SIZE_SMALL
4119
                        );
4120
                        $hide_show_disc = 'showdisc';
4121
                    }
4122
                }
4123
                echo '<span style="float:right">';
4124
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$hide_show_disc.'&title='.api_htmlentities(
4125
                        urlencode($page)
4126
                    ).'">'.$visibility_disc.'</a>';
4127
                echo '</span>';
4128
4129
                // discussion action: check add rating lock. Show/Hide list to rating for all student
4130
                $lock_unlock_rating_disc = null;
4131
                $ratinglock_disc = null;
4132
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4133
                    if (self::check_ratinglock_discuss() == 1) {
4134
                        $ratinglock_disc = Display::return_icon(
4135
                            'star.png',
4136
                            get_lang('UnlockRatingDiscussExtra'),
4137
                            '',
4138
                            ICON_SIZE_SMALL
4139
                        );
4140
                        $lock_unlock_rating_disc = 'unlockrating';
4141
                    } else {
4142
                        $ratinglock_disc = Display::return_icon(
4143
                            'star_na.png',
4144
                            get_lang('LockRatingDiscussExtra'),
4145
                            '',
4146
                            ICON_SIZE_SMALL
4147
                        );
4148
                        $lock_unlock_rating_disc = 'lockrating';
4149
                    }
4150
                }
4151
4152
                echo '<span style="float:right">';
4153
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_rating_disc.'&title='.api_htmlentities(
4154
                        urlencode($page)
4155
                    ).'">'.$ratinglock_disc.'</a>';
4156
                echo '</span>';
4157
4158
                // discussion action: email notification
4159
                if (self::check_notify_discuss($page) == 1) {
4160
                    $notify_disc = Display::return_icon(
4161
                        'messagebox_info.png',
4162
                        get_lang('NotifyDiscussByEmail'),
4163
                        '',
4164
                        ICON_SIZE_SMALL
4165
                    );
4166
                    $lock_unlock_notify_disc = 'unlocknotifydisc';
4167
                } else {
4168
                    $notify_disc = Display::return_icon(
4169
                        'mail.png',
4170
                        get_lang('CancelNotifyDiscussByEmail'),
4171
                        '',
4172
                        ICON_SIZE_SMALL
4173
                    );
4174
                    $lock_unlock_notify_disc = 'locknotifydisc';
4175
                }
4176
                echo '<span style="float:right">';
4177
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_notify_disc.'&title='.api_htmlentities(
4178
                        urlencode($page)
4179
                    ).'">'.$notify_disc.'</a>';
4180
                echo '</span>';
4181
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities(
4182
                        $row['title']
4183
                    );
4184
                if ($lastuserinfo !== false) {
4185
                    echo ' ('.get_lang('MostRecentVersionBy').' '.
4186
                        UserManager::getUserProfileLink($lastuserinfo).' '.$lastversiondate.$countWPost.')'.$avg_WPost_score.' '; //TODO: read average score
4187
                }
4188
4189
                echo '</div>';
4190
                if ($row['addlock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4191
                    //show comments but students can't add theirs
4192
                    ?>
4193
                    <div class="panel panel-default">
4194
                        <div class="panel-body">
4195
                            <form name="form1" method="post" action=""
4196
                                  class="form-horizontal">
4197
                                <div class="form-group">
4198
                                    <label
4199
                                        class="col-sm-2 control-label">
4200
                                        <?php echo get_lang('Comments'); ?>:</label>
4201
                                    <div class="col-sm-10">
4202
                                        <?php echo '<input type="hidden" name="wpost_id" value="'.md5(uniqid(rand(), true)).'">'; //prevent double post?>
4203
                                        <textarea class="form-control"
4204
                                                  name="comment" cols="80"
4205
                                                  rows="5"
4206
                                                  id="comment">
4207
                                        </textarea>
4208
                                    </div>
4209
                                </div>
4210
                                <div class="form-group">
4211
                                    <?php
4212
                                    //check if rating is allowed
4213
                                    if ($row['ratinglock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4214
                                        ?>
4215
                                        <label
4216
                                            class="col-sm-2 control-label"><?php echo get_lang('Rating'); ?>:</label>
4217
                                        <div class="col-sm-10">
4218
                                            <select name="rating" id="rating" class="selectpicker">
4219
                                                <option value="-" selected>-</option>
4220
                                                <option value="0">0</option>
4221
                                                <option value="1">1</option>
4222
                                                <option value="2">2</option>
4223
                                                <option value="3">3</option>
4224
                                                <option value="4">4</option>
4225
                                                <option value="5">5</option>
4226
                                                <option value="6">6</option>
4227
                                                <option value="7">7</option>
4228
                                                <option value="8">8</option>
4229
                                                <option value="9">9</option>
4230
                                                <option value="10">10</option>
4231
                                            </select>
4232
                                        </div>
4233
                                        <?php
4234
                                    } else {
4235
                                        echo '<input type=hidden name="rating" value="-">';
4236
                                        // must pass a default value to avoid rate automatically
4237
                                    } ?>
4238
4239
                                </div>
4240
                                <div class="form-group">
4241
                                    <div class="col-sm-offset-2 col-sm-10">
4242
                                        <?php echo '<button class="btn btn-default" type="submit" name="Submit"> '.
4243
                                            get_lang('Send').'</button>'; ?>
4244
                                    </div>
4245
                                </div>
4246
                        </div>
4247
                    </div>
4248
                    </form>
4249
                    <?php
4250
                }
4251
                // end discuss lock
4252
4253
                echo '<hr noshade size="1">';
4254
                $user_table = Database::get_main_table(TABLE_MAIN_USER);
4255
4256
                $sql = "SELECT *
4257
                        FROM $tbl_wiki_discuss reviews, $user_table user
4258
                        WHERE
4259
                            reviews.c_id = $course_id AND
4260
                            reviews.publication_id='".$id."' AND
4261
                            user.user_id='".$firstuserid."'
4262
                        ORDER BY reviews.id DESC";
4263
                $result = Database::query($sql);
4264
4265
                $countWPost = Database::num_rows($result);
4266
                echo get_lang('NumComments').": ".$countWPost; //comment's numbers
4267
4268
                $sql = "SELECT SUM(p_score) as sumWPost
4269
                        FROM $tbl_wiki_discuss
4270
                        WHERE c_id = $course_id AND publication_id = '".$id."' AND NOT p_score='-'
4271
                        ORDER BY id DESC";
4272
                $result2 = Database::query($sql);
4273
                $row2 = Database::fetch_array($result2);
4274
4275
                $sql = "SELECT * FROM $tbl_wiki_discuss
4276
                        WHERE c_id = $course_id AND publication_id='".$id."' AND NOT p_score='-'";
4277
                $result3 = Database::query($sql);
4278
                $countWPost_score = Database::num_rows($result3);
4279
4280
                echo ' - '.get_lang('NumCommentsScore').': '.$countWPost_score;
4281
4282
                if ($countWPost_score != 0) {
4283
                    $avg_WPost_score = round($row2['sumWPost'] / $countWPost_score, 2).' / 10';
4284
                } else {
4285
                    $avg_WPost_score = $countWPost_score;
4286
                }
4287
4288
                echo ' - '.get_lang('RatingMedia').': '.$avg_WPost_score; // average rating
4289
4290
                $sql = 'UPDATE '.$tbl_wiki.' SET
4291
                        score = "'.Database::escape_string($avg_WPost_score).'"
4292
                        WHERE
4293
                            c_id = '.$course_id.' AND
4294
                            reflink="'.Database::escape_string($page).'" AND
4295
                            '.$groupfilter.$condition_session;
4296
                // check if work ok. TODO:
4297
                Database::query($sql);
4298
4299
                echo '<hr noshade size="1">';
4300
                while ($row = Database::fetch_array($result)) {
4301
                    $userinfo = api_get_user_info($row['userc_id']);
4302
                    if (($userinfo['status']) == "5") {
4303
                        $author_status = get_lang('Student');
4304
                    } else {
4305
                        $author_status = get_lang('Teacher');
4306
                    }
4307
4308
                    $name = $userinfo['complete_name'];
4309
                    $author_photo = '<img src="'.$userinfo['avatar'].'" alt="'.api_htmlentities($name).'"  width="40" height="50" align="top"  title="'.api_htmlentities($name).'"  />';
4310
4311
                    // stars
4312
                    $p_score = $row['p_score'];
4313
                    switch ($p_score) {
4314
                        case 0:
4315
                            $imagerating = Display::return_icon(
4316
                                'rating/stars_0.gif'
4317
                            );
4318
                            break;
4319
                        case 1:
4320
                            $imagerating = Display::return_icon(
4321
                                'rating/stars_5.gif'
4322
                            );
4323
                            break;
4324
                        case 2:
4325
                            $imagerating = Display::return_icon(
4326
                                'rating/stars_10.gif'
4327
                            );
4328
                            break;
4329
                        case 3:
4330
                            $imagerating = Display::return_icon(
4331
                                'rating/stars_15.gif'
4332
                            );
4333
                            break;
4334
                        case 4:
4335
                            $imagerating = Display::return_icon(
4336
                                'rating/stars_20.gif'
4337
                            );
4338
                            break;
4339
                        case 5:
4340
                            $imagerating = Display::return_icon(
4341
                                'rating/stars_25.gif'
4342
                            );
4343
                            break;
4344
                        case 6:
4345
                            $imagerating = Display::return_icon(
4346
                                'rating/stars_30.gif'
4347
                            );
4348
                            break;
4349
                        case 7:
4350
                            $imagerating = Display::return_icon(
4351
                                'rating/stars_35.gif'
4352
                            );
4353
                            break;
4354
                        case 8:
4355
                            $imagerating = Display::return_icon(
4356
                                'rating/stars_40.gif'
4357
                            );
4358
                            break;
4359
                        case 9:
4360
                            $imagerating = Display::return_icon(
4361
                                'rating/stars_45.gif'
4362
                            );
4363
                            break;
4364
                        case 10:
4365
                            $imagerating = Display::return_icon(
4366
                                'rating/stars_50.gif'
4367
                            );
4368
                            break;
4369
                    }
4370
                    echo '<p><table>';
4371
                    echo '<tr>';
4372
                    echo '<td rowspan="2">'.$author_photo.'</td>';
4373
                    $userProfile = '';
4374
                    if ($userinfo !== false) {
4375
                        $userProfile = UserManager::getUserProfileLink(
4376
                            $userinfo
4377
                        );
4378
                    }
4379
                    echo '<td style=" color:#999999">'.$userProfile.' ('.$author_status.') '.
4380
                        api_get_local_time(
4381
                            $row['dtime']
4382
                        ).
4383
                        ' - '.get_lang(
4384
                            'Rating'
4385
                        ).': '.$row['p_score'].' '.$imagerating.' </td>';
4386
                    echo '</tr>';
4387
                    echo '<tr>';
4388
                    echo '<td>'.api_htmlentities($row['comment']).'</td>';
4389
                    echo '</tr>';
4390
                    echo "</table>";
4391
                }
4392
            } else {
4393
                Display::addFlash(
4394
                    Display::return_message(
4395
                        get_lang('LockByTeacher'),
4396
                        'warning',
4397
                        false
4398
                    )
4399
                );
4400
            }
4401
        } else {
4402
            Display::addFlash(
4403
                Display::return_message(
4404
                    get_lang('DiscussNotAvailable'),
4405
                    'normal',
4406
                    false
4407
                )
4408
            );
4409
        }
4410
    }
4411
4412
    /**
4413
     * Show all pages.
4414
     */
4415
    public function allPages($action)
4416
    {
4417
        $_course = $this->courseInfo;
4418
4419
        echo '<div class="actions">'.get_lang('AllPages');
4420
4421
        // menu delete all wiki
4422
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4423
            echo ' <a href="index.php?action=deletewiki&'.api_get_cidreq().'">'.
4424
                Display::return_icon(
4425
                    'delete.png',
4426
                    get_lang('DeleteWiki'),
4427
                    '',
4428
                    ICON_SIZE_MEDIUM
4429
                ).'</a>';
4430
        }
4431
        echo '</div>';
4432
4433
        //show table
4434
        $table = new SortableTable(
4435
            'AllPages_table',
4436
            function () {
4437
                $result = $this->gelAllPagesQuery(true);
4438
4439
                return (int) Database::fetch_assoc($result)['nbr'];
4440
            },
4441
            function ($from, $numberOfItems, $column, $direction) {
4442
                $result = $this->gelAllPagesQuery(false, $from, $numberOfItems, $column, $direction);
4443
                $rows = [];
4444
4445
                while ($data = Database::fetch_assoc($result)) {
4446
                    $rows[] = [
4447
                        $data['col0'],
4448
                        [$data['col1'], $data['reflink']],
4449
                        [$data['col2'], $data['user_ip']],
4450
                        $data['col3'],
4451
                        $data['reflink'],
4452
                    ];
4453
                }
4454
4455
                return $rows;
4456
            }
4457
        );
4458
        $table->set_additional_parameters(
4459
            [
4460
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
4461
                'action' => Security::remove_XSS($action),
4462
                'group_id' => Security::remove_XSS($_GET['group_id']),
4463
            ]
4464
        );
4465
        $table->set_header(
4466
            0,
4467
            get_lang('Type'),
4468
            true,
4469
            ['style' => 'width:30px;']
4470
        );
4471
        $table->set_header(1, get_lang('Title'));
4472
        $table->set_header(
4473
            2,
4474
            get_lang('Author').' <small>'.get_lang('LastVersion').'</small>'
4475
        );
4476
        $table->set_header(
4477
            3,
4478
            get_lang('Date').' <small>'.get_lang('LastVersion').'</small>'
4479
        );
4480
        if (api_is_allowed_to_session_edit(false, true)) {
4481
            $table->set_header(
4482
                4,
4483
                get_lang('Actions'),
4484
                false,
4485
                ['style' => 'width: 145px;']
4486
            );
4487
        }
4488
        $table->set_column_filter(
4489
            0,
4490
            function ($value, string $urlParams, array $row) {
4491
                $return = '';
4492
                //get type assignment icon
4493
                if (1 == $value) {
4494
                    $return .= Display::return_icon(
4495
                        'wiki_assignment.png',
4496
                        get_lang('AssignmentDesc'),
4497
                        '',
4498
                        ICON_SIZE_SMALL
4499
                    );
4500
                } elseif (2 == $value) {
4501
                    $return .= Display::return_icon(
4502
                        'wiki_work.png',
4503
                        get_lang('AssignmentWork'),
4504
                        '',
4505
                        ICON_SIZE_SMALL
4506
                    );
4507
                } elseif (0 == $value) {
4508
                    $return .= Display::return_icon(
4509
                        'px_transparent.gif'
4510
                    );
4511
                }
4512
4513
                //get icon task
4514
                if (!empty($row['task'])) {
4515
                    $return .= Display::return_icon(
4516
                        'wiki_task.png',
4517
                        get_lang('StandardTask'),
4518
                        '',
4519
                        ICON_SIZE_SMALL
4520
                    );
4521
                } else {
4522
                    $return .= Display::return_icon('px_transparent.gif');
4523
                }
4524
4525
                return $return;
4526
            }
4527
        );
4528
        $table->set_column_filter(
4529
            1,
4530
            function ($value) use ($_course) {
4531
                list($title, $refLink) = $value;
4532
4533
                return '<a href="'.api_get_self().'?cidReq='.$_course['code']
4534
                    .'&action=showpage&title='.api_htmlentities(urlencode($refLink))
4535
                    .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4536
                    .'&group_id='.api_htmlentities($_GET['group_id']).'">
4537
                    '.api_htmlentities($title).'</a>';
4538
            }
4539
        );
4540
        $table->set_column_filter(
4541
            2,
4542
            function ($value) {
4543
                list($userId, $userIp) = $value;
4544
                //get author
4545
                $userinfo = api_get_user_info($userId);
4546
4547
                if ($userinfo !== false) {
4548
                    return UserManager::getUserProfileLink($userinfo);
4549
                }
4550
4551
                return get_lang('Anonymous').' ('.api_htmlentities($userIp).')';
4552
            }
4553
        );
4554
        $table->set_column_filter(
4555
            3,
4556
            function ($value) {
4557
                return api_get_local_time($value);
4558
            }
4559
        );
4560
        $table->set_column_filter(
4561
            4,
4562
            function ($value) use ($_course) {
4563
                $actions = '';
4564
4565
                if (api_is_allowed_to_session_edit(false, true)) {
4566
                    $actions = '<a href="'.api_get_self(
4567
                        ).'?cidReq='.$_course['code']
4568
                        .'&action=edit&title='.api_htmlentities(urlencode($value))
4569
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4570
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4571
                        .Display::return_icon('edit.png', get_lang('EditPage'))
4572
                        .'</a> <a href="'.api_get_self().'?cidReq='.$_course['code']
4573
                        .'&action=discuss&title='.api_htmlentities(urlencode($value))
4574
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4575
                        .Display::return_icon('discuss.png', get_lang('Discuss'))
4576
                        .'</a> <a href="'.api_get_self().'?cidReq='.$_course['code']
4577
                        .'&action=history&title='.api_htmlentities(urlencode($value))
4578
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4579
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4580
                        .Display::return_icon('history.png', get_lang('History'))
4581
                        .'</a> <a href="'.api_get_self().'?cidReq='.$_course['code']
4582
                        .'&action=links&title='.api_htmlentities(urlencode($value))
4583
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '').'&group_id='
4584
                        .api_htmlentities($_GET['group_id']).'">'.
4585
                        Display::return_icon('what_link_here.png', get_lang('LinksPages')).'</a>';
4586
                }
4587
4588
                if (api_is_allowed_to_edit(
4589
                        false,
4590
                        true
4591
                    ) || api_is_platform_admin()) {
4592
                    $actions .= ' <a href="'.api_get_self().'?cidReq='.$_course['code']
4593
                        .'&action=delete&title='.api_htmlentities(urlencode($value))
4594
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4595
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4596
                        .Display::return_icon('delete.png', get_lang('Delete')).'</a>';
4597
                }
4598
4599
                return $actions;
4600
            }
4601
        );
4602
        $table->display();
4603
    }
4604
4605
    /**
4606
     * Get recent changes.
4607
     *
4608
     * @param string $page
4609
     * @param string $action
4610
     */
4611
    public function recentChanges($page, $action)
4612
    {
4613
        $tbl_wiki = $this->tbl_wiki;
4614
        $course_id = $this->course_id;
4615
        $condition_session = $this->condition_session;
4616
        $groupfilter = $this->groupfilter;
4617
        $tbl_wiki_conf = $this->tbl_wiki_conf;
4618
4619
        if (api_is_allowed_to_session_edit(false, true)) {
4620
            if (self::check_notify_all() == 1) {
4621
                $notify_all = Display::return_icon(
4622
                        'messagebox_info.png',
4623
                        get_lang('NotifyByEmail'),
4624
                        '',
4625
                        ICON_SIZE_SMALL
4626
                    ).' '.get_lang('NotNotifyChanges');
4627
                $lock_unlock_notify_all = 'unlocknotifyall';
4628
            } else {
4629
                $notify_all = Display::return_icon(
4630
                        'mail.png',
4631
                        get_lang('CancelNotifyByEmail'),
4632
                        '',
4633
                        ICON_SIZE_SMALL
4634
                    ).' '.get_lang('NotifyChanges');
4635
                $lock_unlock_notify_all = 'locknotifyall';
4636
            }
4637
        }
4638
4639
        echo '<div class="actions"><span style="float: right;">';
4640
        echo '<a href="index.php?action=recentchanges&actionpage='.$lock_unlock_notify_all.'&'.api_get_cidreq().'&title='.api_htmlentities(
4641
                urlencode($page)
4642
            ).'">'.$notify_all.'</a>';
4643
        echo '</span>'.get_lang('RecentChanges').'</div>';
4644
4645
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4646
            //only by professors if page is hidden
4647
            $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
4648
        		WHERE 	'.$tbl_wiki_conf.'.c_id= '.$course_id.' AND
4649
        				'.$tbl_wiki.'.c_id= '.$course_id.' AND
4650
        				'.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
4651
        				'.$tbl_wiki.'.'.$groupfilter.$condition_session.'
4652
        		ORDER BY dtime DESC'; // new version
4653
        } else {
4654
            $sql = 'SELECT *
4655
                FROM '.$tbl_wiki.'
4656
                WHERE
4657
                    c_id = '.$course_id.' AND
4658
                    '.$groupfilter.$condition_session.' AND
4659
                    visibility=1
4660
                ORDER BY dtime DESC';
4661
            // old version TODO: Replace by the bottom line
4662
        }
4663
4664
        $allpages = Database::query($sql);
4665
4666
        //show table
4667
        if (Database::num_rows($allpages) > 0) {
4668
            $rows = [];
4669
            while ($obj = Database::fetch_object($allpages)) {
4670
                //get author
4671
                $userinfo = api_get_user_info($obj->user_id);
4672
4673
                //get type assignment icon
4674
                if ($obj->assignment == 1) {
4675
                    $ShowAssignment = Display::return_icon(
4676
                        'wiki_assignment.png',
4677
                        get_lang('AssignmentDesc'),
4678
                        '',
4679
                        ICON_SIZE_SMALL
4680
                    );
4681
                } elseif ($obj->assignment == 2) {
4682
                    $ShowAssignment = Display::return_icon(
4683
                        'wiki_work.png',
4684
                        get_lang('AssignmentWork'),
4685
                        '',
4686
                        ICON_SIZE_SMALL
4687
                    );
4688
                } elseif ($obj->assignment == 0) {
4689
                    $ShowAssignment = Display::return_icon(
4690
                        'px_transparent.gif'
4691
                    );
4692
                }
4693
4694
                // Get icon task
4695
                if (!empty($obj->task)) {
4696
                    $icon_task = Display::return_icon(
4697
                        'wiki_task.png',
4698
                        get_lang('StandardTask'),
4699
                        '',
4700
                        ICON_SIZE_SMALL
4701
                    );
4702
                } else {
4703
                    $icon_task = Display::return_icon('px_transparent.gif');
4704
                }
4705
4706
                $row = [];
4707
                $row[] = api_get_local_time(
4708
                    $obj->dtime
4709
                );
4710
                $row[] = $ShowAssignment.$icon_task;
4711
                $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
4712
                    ).'&action=showpage&title='.api_htmlentities(
4713
                        urlencode($obj->reflink)
4714
                    ).'&view='.$obj->id.'&session_id='.api_get_session_id(
4715
                    ).'&group_id='.api_get_group_id().'">'.
4716
                    api_htmlentities($obj->title).'</a>';
4717
                $row[] = $obj->version > 1 ? get_lang('EditedBy') : get_lang(
4718
                    'AddedBy'
4719
                );
4720
                if ($userinfo !== false) {
4721
                    $row[] = UserManager::getUserProfileLink($userinfo);
4722
                } else {
4723
                    $row[] = get_lang('Anonymous').' ('.api_htmlentities(
4724
                            $obj->user_ip
4725
                        ).')';
4726
                }
4727
                $rows[] = $row;
4728
            }
4729
4730
            $table = new SortableTableFromArrayConfig(
4731
                $rows,
4732
                0,
4733
                10,
4734
                'RecentPages_table',
4735
                '',
4736
                '',
4737
                'DESC'
4738
            );
4739
            $table->set_additional_parameters(
4740
                [
4741
                    'cidReq' => api_get_course_id(),
4742
                    'action' => Security::remove_XSS($action),
4743
                    'session_id' => api_get_session_id(),
4744
                    'group_id' => api_get_group_id(),
4745
                ]
4746
            );
4747
            $table->set_header(
4748
                0,
4749
                get_lang('Date'),
4750
                true,
4751
                ['style' => 'width:200px;']
4752
            );
4753
            $table->set_header(
4754
                1,
4755
                get_lang('Type'),
4756
                true,
4757
                ['style' => 'width:30px;']
4758
            );
4759
            $table->set_header(2, get_lang('Title'), true);
4760
            $table->set_header(
4761
                3,
4762
                get_lang('Actions'),
4763
                true,
4764
                ['style' => 'width:80px;']
4765
            );
4766
            $table->set_header(4, get_lang('Author'), true);
4767
            $table->display();
4768
        }
4769
    }
4770
4771
    /**
4772
     * What links here. Show pages that have linked this page.
4773
     *
4774
     * @param string $page
4775
     */
4776
    public function getLinks($page)
4777
    {
4778
        $tbl_wiki = $this->tbl_wiki;
4779
        $course_id = $this->course_id;
4780
        $condition_session = $this->condition_session;
4781
        $groupfilter = $this->groupfilter;
4782
        $_course = $this->courseInfo;
4783
        $action = $this->action;
4784
4785
        if (!$_GET['title']) {
4786
            Display::addFlash(
4787
                Display::return_message(
4788
                    get_lang("MustSelectPage"),
4789
                    'error',
4790
                    false
4791
                )
4792
            );
4793
        } else {
4794
            $sql = 'SELECT * FROM '.$tbl_wiki.'
4795
                    WHERE
4796
                        c_id = '.$course_id.' AND
4797
                        reflink="'.Database::escape_string($page).'" AND
4798
                        '.$groupfilter.$condition_session;
4799
            $result = Database::query($sql);
4800
            $row = Database::fetch_array($result);
4801
4802
            //get type assignment icon
4803
            $ShowAssignment = '';
4804
            if ($row['assignment'] == 1) {
4805
                $ShowAssignment = Display::return_icon(
4806
                    'wiki_assignment.png',
4807
                    get_lang('AssignmentDesc'),
4808
                    '',
4809
                    ICON_SIZE_SMALL
4810
                );
4811
            } elseif ($row['assignment'] == 2) {
4812
                $ShowAssignment = Display::return_icon(
4813
                    'wiki_work.png',
4814
                    get_lang('AssignmentWork'),
4815
                    '',
4816
                    ICON_SIZE_SMALL
4817
                );
4818
            } elseif ($row['assignment'] == 0) {
4819
                $ShowAssignment = Display::return_icon('px_transparent.gif');
4820
            }
4821
4822
            //fix Title to reflink (link Main Page)
4823
            if ($page == get_lang('DefaultTitle')) {
4824
                $page = 'index';
4825
            }
4826
4827
            echo '<div id="wikititle">';
4828
            echo get_lang(
4829
                    'LinksPagesFrom'
4830
                ).': '.$ShowAssignment.' <a href="'.api_get_self(
4831
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4832
                    urlencode($page)
4833
                ).'&session_id='.api_htmlentities(
4834
                    $_GET['session_id']
4835
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4836
                api_htmlentities($row['title']).'</a>';
4837
            echo '</div>';
4838
4839
            //fix index to title Main page into linksto
4840
4841
            if ($page == 'index') {
4842
                $page = str_replace(' ', '_', get_lang('DefaultTitle'));
4843
            }
4844
4845
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4846
                // only by professors if page is hidden
4847
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4848
                        WHERE s1.c_id = $course_id AND linksto LIKE '%".Database::escape_string(
4849
                        $page
4850
                    )."%' AND id=(
4851
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4852
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4853
            } else {
4854
                //add blank space after like '%" " %' to identify each word
4855
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4856
                        WHERE s1.c_id = $course_id AND visibility=1 AND linksto LIKE '%".Database::escape_string(
4857
                        $page
4858
                    )."%' AND id=(
4859
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4860
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4861
            }
4862
4863
            $allpages = Database::query($sql);
4864
4865
            //show table
4866
            if (Database::num_rows($allpages) > 0) {
4867
                $rows = [];
4868
                while ($obj = Database::fetch_object($allpages)) {
4869
                    //get author
4870
                    $userinfo = api_get_user_info($obj->user_id);
4871
4872
                    //get time
4873
                    $year = substr($obj->dtime, 0, 4);
4874
                    $month = substr($obj->dtime, 5, 2);
4875
                    $day = substr($obj->dtime, 8, 2);
4876
                    $hours = substr($obj->dtime, 11, 2);
4877
                    $minutes = substr($obj->dtime, 14, 2);
4878
                    $seconds = substr($obj->dtime, 17, 2);
4879
4880
                    //get type assignment icon
4881
                    if ($obj->assignment == 1) {
4882
                        $ShowAssignment = Display::return_icon(
4883
                            'wiki_assignment.png',
4884
                            get_lang('AssignmentDesc'),
4885
                            '',
4886
                            ICON_SIZE_SMALL
4887
                        );
4888
                    } elseif ($obj->assignment == 2) {
4889
                        $ShowAssignment = Display::return_icon(
4890
                            'wiki_work.png',
4891
                            get_lang('AssignmentWork'),
4892
                            '',
4893
                            ICON_SIZE_SMALL
4894
                        );
4895
                    } elseif ($obj->assignment == 0) {
4896
                        $ShowAssignment = Display::return_icon(
4897
                            'px_transparent.gif'
4898
                        );
4899
                    }
4900
4901
                    $row = [];
4902
                    $row[] = $ShowAssignment;
4903
                    $row[] = '<a href="'.api_get_self(
4904
                        ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4905
                            urlencode($obj->reflink)
4906
                        ).'&session_id='.api_htmlentities(
4907
                            $_GET['session_id']
4908
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4909
                        api_htmlentities($obj->title).'</a>';
4910
                    if ($userinfo !== false) {
4911
                        $row[] = UserManager::getUserProfileLink($userinfo);
4912
                    } else {
4913
                        $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
4914
                    }
4915
                    $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
4916
                    $rows[] = $row;
4917
                }
4918
4919
                $table = new SortableTableFromArrayConfig(
4920
                    $rows,
4921
                    1,
4922
                    10,
4923
                    'AllPages_table',
4924
                    '',
4925
                    '',
4926
                    'ASC'
4927
                );
4928
                $table->set_additional_parameters(
4929
                    [
4930
                        'cidReq' => Security::remove_XSS($_GET['cidReq']),
4931
                        'action' => Security::remove_XSS($action),
4932
                        'group_id' => intval($_GET['group_id']),
4933
                    ]
4934
                );
4935
                $table->set_header(
4936
                    0,
4937
                    get_lang('Type'),
4938
                    true,
4939
                    ['style' => 'width:30px;']
4940
                );
4941
                $table->set_header(1, get_lang('Title'), true);
4942
                $table->set_header(2, get_lang('Author'), true);
4943
                $table->set_header(3, get_lang('Date'), true);
4944
                $table->display();
4945
            }
4946
        }
4947
    }
4948
4949
    /**
4950
     * @param string $action
4951
     */
4952
    public function getSearchPages($action)
4953
    {
4954
        echo '<div class="actions">'.get_lang('SearchPages').'</div>';
4955
        if (isset($_GET['mode_table'])) {
4956
            if (!isset($_GET['SearchPages_table_page_nr'])) {
4957
                $_GET['search_term'] = isset($_POST['search_term']) ? $_POST['search_term'] : '';
4958
                $_GET['search_content'] = isset($_POST['search_content']) ? $_POST['search_content'] : '';
4959
                $_GET['all_vers'] = isset($_POST['all_vers']) ? $_POST['all_vers'] : '';
4960
            }
4961
            self::display_wiki_search_results(
4962
                $_GET['search_term'],
4963
                $_GET['search_content'],
4964
                $_GET['all_vers']
4965
            );
4966
        } else {
4967
            // initiate the object
4968
            $form = new FormValidator(
4969
                'wiki_search',
4970
                'post',
4971
                api_get_self().'?cidReq='.api_get_course_id(
4972
                ).'&action='.api_htmlentities(
4973
                    $action
4974
                ).'&session_id='.api_get_session_id(
4975
                ).'&group_id='.api_get_group_id().'&mode_table=yes1'
4976
            );
4977
4978
            // Setting the form elements
4979
4980
            $form->addText(
4981
                'search_term',
4982
                get_lang('SearchTerm'),
4983
                true,
4984
                ['autofocus' => 'autofocus']
4985
            );
4986
            $form->addElement(
4987
                'checkbox',
4988
                'search_content',
4989
                null,
4990
                get_lang('AlsoSearchContent')
4991
            );
4992
            $form->addElement(
4993
                'checkbox',
4994
                'all_vers',
4995
                null,
4996
                get_lang('IncludeAllVersions')
4997
            );
4998
            $form->addButtonSearch(get_lang('Search'), 'SubmitWikiSearch');
4999
5000
            // setting the rules
5001
            $form->addRule(
5002
                'search_term',
5003
                get_lang('TooShort'),
5004
                'minlength',
5005
                3
5006
            ); //TODO: before fixing the pagination rules worked, not now
5007
5008
            if ($form->validate()) {
5009
                $form->display();
5010
                $values = $form->exportValues();
5011
                self::display_wiki_search_results(
5012
                    $values['search_term'],
5013
                    $values['search_content'],
5014
                    $values['all_vers']
5015
                );
5016
            } else {
5017
                $form->display();
5018
            }
5019
        }
5020
    }
5021
5022
    /**
5023
     * @param int    $userId
5024
     * @param string $action
5025
     */
5026
    public function getUserContributions($userId, $action)
5027
    {
5028
        $_course = $this->courseInfo;
5029
        $tbl_wiki = $this->tbl_wiki;
5030
        $course_id = $this->course_id;
5031
        $condition_session = $this->condition_session;
5032
        $groupfilter = $this->groupfilter;
5033
        $userId = intval($userId);
5034
        $userinfo = api_get_user_info($userId);
5035
        if ($userinfo !== false) {
5036
            echo '<div class="actions">'.
5037
                get_lang('UserContributions').': '.UserManager::getUserProfileLink($userinfo).
5038
                '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.$userId.
5039
                '&session_id='.$this->session_id.'&group_id='.$this->group_id.'">'.
5040
                '</a></div>';
5041
        }
5042
5043
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5044
            //only by professors if page is hidden
5045
            $sql = 'SELECT * FROM '.$tbl_wiki.'
5046
                    WHERE
5047
                        c_id = '.$course_id.' AND
5048
                        '.$groupfilter.$condition_session.' AND
5049
                        user_id="'.$userId.'"';
5050
        } else {
5051
            $sql = 'SELECT * FROM '.$tbl_wiki.'
5052
                    WHERE
5053
                        c_id = '.$course_id.' AND
5054
                        '.$groupfilter.$condition_session.' AND
5055
                        user_id="'.$userId.'" AND
5056
                        visibility=1';
5057
        }
5058
5059
        $allpages = Database::query($sql);
5060
5061
        //show table
5062
        if (Database::num_rows($allpages) > 0) {
5063
            $rows = [];
5064
            while ($obj = Database::fetch_object($allpages)) {
5065
                //get type assignment icon
5066
                $ShowAssignment = '';
5067
                if ($obj->assignment == 1) {
5068
                    $ShowAssignment = Display::return_icon(
5069
                        'wiki_assignment.png',
5070
                        get_lang('AssignmentDescExtra'),
5071
                        '',
5072
                        ICON_SIZE_SMALL
5073
                    );
5074
                } elseif ($obj->assignment == 2) {
5075
                    $ShowAssignment = Display::return_icon(
5076
                        'wiki_work.png',
5077
                        get_lang('AssignmentWork'),
5078
                        '',
5079
                        ICON_SIZE_SMALL
5080
                    );
5081
                } elseif ($obj->assignment == 0) {
5082
                    $ShowAssignment = Display::return_icon(
5083
                        'px_transparent.gif'
5084
                    );
5085
                }
5086
5087
                $row = [];
5088
                $row[] = api_get_local_time($obj->dtime);
5089
                $row[] = $ShowAssignment;
5090
                $row[] = '<a href="'.api_get_self(
5091
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5092
                        urlencode($obj->reflink)
5093
                    ).'&view='.$obj->id.'&session_id='.api_get_session_id(
5094
                    ).'&group_id='.api_get_group_id().'">'.
5095
                    api_htmlentities($obj->title).'</a>';
5096
                $row[] = Security::remove_XSS($obj->version);
5097
                $row[] = Security::remove_XSS($obj->comment);
5098
                $row[] = Security::remove_XSS($obj->progress).' %';
5099
                $row[] = Security::remove_XSS($obj->score);
5100
                $rows[] = $row;
5101
            }
5102
5103
            $table = new SortableTableFromArrayConfig(
5104
                $rows,
5105
                2,
5106
                10,
5107
                'UsersContributions_table',
5108
                '',
5109
                '',
5110
                'ASC'
5111
            );
5112
            $table->set_additional_parameters(
5113
                [
5114
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5115
                    'action' => Security::remove_XSS($action),
5116
                    'user_id' => intval($userId),
5117
                    'session_id' => intval($_GET['session_id']),
5118
                    'group_id' => intval($_GET['group_id']),
5119
                ]
5120
            );
5121
            $table->set_header(
5122
                0,
5123
                get_lang('Date'),
5124
                true,
5125
                ['style' => 'width:200px;']
5126
            );
5127
            $table->set_header(
5128
                1,
5129
                get_lang('Type'),
5130
                true,
5131
                ['style' => 'width:30px;']
5132
            );
5133
            $table->set_header(
5134
                2,
5135
                get_lang('Title'),
5136
                true,
5137
                ['style' => 'width:200px;']
5138
            );
5139
            $table->set_header(
5140
                3,
5141
                get_lang('Version'),
5142
                true,
5143
                ['style' => 'width:30px;']
5144
            );
5145
            $table->set_header(
5146
                4,
5147
                get_lang('Comment'),
5148
                true,
5149
                ['style' => 'width:200px;']
5150
            );
5151
            $table->set_header(
5152
                5,
5153
                get_lang('Progress'),
5154
                true,
5155
                ['style' => 'width:30px;']
5156
            );
5157
            $table->set_header(
5158
                6,
5159
                get_lang('Rating'),
5160
                true,
5161
                ['style' => 'width:30px;']
5162
            );
5163
            $table->display();
5164
        }
5165
    }
5166
5167
    /**
5168
     * @param string $action
5169
     */
5170
    public function getMostChangedPages($action)
5171
    {
5172
        $_course = $this->courseInfo;
5173
        $tbl_wiki = $this->tbl_wiki;
5174
        $course_id = $this->course_id;
5175
        $condition_session = $this->condition_session;
5176
        $groupfilter = $this->groupfilter;
5177
5178
        echo '<div class="actions">'.get_lang('MostChangedPages').'</div>';
5179
5180
        if (api_is_allowed_to_edit(false, true) ||
5181
            api_is_platform_admin()
5182
        ) { //only by professors if page is hidden
5183
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
5184
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5185
                    GROUP BY reflink'; //TODO:check MAX and group by return last version
5186
        } else {
5187
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
5188
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND visibility=1
5189
                    GROUP BY reflink'; //TODO:check MAX and group by return last version
5190
        }
5191
5192
        $allpages = Database::query($sql);
5193
5194
        //show table
5195
        if (Database::num_rows($allpages) > 0) {
5196
            $rows = [];
5197
            while ($obj = Database::fetch_object($allpages)) {
5198
                //get type assignment icon
5199
                $ShowAssignment = '';
5200
                if ($obj->assignment == 1) {
5201
                    $ShowAssignment = Display::return_icon(
5202
                        'wiki_assignment.png',
5203
                        get_lang('AssignmentDesc'),
5204
                        '',
5205
                        ICON_SIZE_SMALL
5206
                    );
5207
                } elseif ($obj->assignment == 2) {
5208
                    $ShowAssignment = Display::return_icon(
5209
                        'wiki_work.png',
5210
                        get_lang('AssignmentWork'),
5211
                        '',
5212
                        ICON_SIZE_SMALL
5213
                    );
5214
                } elseif ($obj->assignment == 0) {
5215
                    $ShowAssignment = Display::return_icon(
5216
                        'px_transparent.gif'
5217
                    );
5218
                }
5219
5220
                $row = [];
5221
                $row[] = $ShowAssignment;
5222
                $row[] = '<a href="'.api_get_self(
5223
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5224
                        urlencode($obj->reflink)
5225
                    ).'&session_id='.api_htmlentities(
5226
                        $_GET['session_id']
5227
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5228
                    api_htmlentities($obj->title).'</a>';
5229
                $row[] = $obj->MAX;
5230
                $rows[] = $row;
5231
            }
5232
5233
            $table = new SortableTableFromArrayConfig(
5234
                $rows,
5235
                2,
5236
                10,
5237
                'MostChangedPages_table',
5238
                '',
5239
                '',
5240
                'DESC'
5241
            );
5242
            $table->set_additional_parameters(
5243
                [
5244
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5245
                    'action' => Security::remove_XSS($action),
5246
                    'session_id' => intval($_GET['session_id']),
5247
                    'group_id' => intval($_GET['group_id']),
5248
                ]
5249
            );
5250
            $table->set_header(
5251
                0,
5252
                get_lang('Type'),
5253
                true,
5254
                ['style' => 'width:30px;']
5255
            );
5256
            $table->set_header(1, get_lang('Title'), true);
5257
            $table->set_header(2, get_lang('Changes'), true);
5258
            $table->display();
5259
        }
5260
    }
5261
5262
    /**
5263
     * Restore page.
5264
     *
5265
     * @return bool
5266
     */
5267
    public function restorePage()
5268
    {
5269
        $userId = api_get_user_id();
5270
        $_course = $this->courseInfo;
5271
        $current_row = $this->getWikiData();
5272
        $last_row = $this->getLastWikiData($this->page);
5273
5274
        if (empty($last_row)) {
5275
            return false;
5276
        }
5277
5278
        $PassEdit = false;
5279
5280
        /* Only teachers and platform admin can edit the index page.
5281
        Only teachers and platform admin can edit an assignment teacher*/
5282
        if (($current_row['reflink'] == 'index' ||
5283
                $current_row['reflink'] == '' ||
5284
                $current_row['assignment'] == 1) &&
5285
            (!api_is_allowed_to_edit(false, true) &&
5286
                $this->group_id == 0)
5287
        ) {
5288
            Display::addFlash(
5289
                Display::return_message(
5290
                    get_lang('OnlyEditPagesCourseManager'),
5291
                    'normal',
5292
                    false
5293
                )
5294
            );
5295
        } else {
5296
            // check if is a wiki group
5297
            if ($current_row['group_id'] != 0) {
5298
                $groupInfo = GroupManager::get_group_properties(
5299
                    $this->group_id
5300
                );
5301
                //Only teacher, platform admin and group members can edit a wiki group
5302
                if (api_is_allowed_to_edit(false, true) ||
5303
                    api_is_platform_admin() ||
5304
                    GroupManager::is_user_in_group($userId, $groupInfo) ||
5305
                    api_is_allowed_in_course()
5306
                ) {
5307
                    $PassEdit = true;
5308
                } else {
5309
                    Display::addFlash(
5310
                        Display::return_message(
5311
                            get_lang('OnlyEditPagesGroupMembers'),
5312
                            'normal',
5313
                            false
5314
                        )
5315
                    );
5316
                }
5317
            } else {
5318
                $PassEdit = true;
5319
            }
5320
5321
            // check if is an assignment
5322
            //$icon_assignment = null;
5323
            if ($current_row['assignment'] == 1) {
5324
                Display::addFlash(
5325
                    Display::return_message(
5326
                        get_lang('EditAssignmentWarning'),
5327
                        'normal',
5328
                        false
5329
                    )
5330
                );
5331
            } elseif ($current_row['assignment'] == 2) {
5332
                if (($userId == $current_row['user_id']) == false) {
5333
                    if (api_is_allowed_to_edit(
5334
                            false,
5335
                            true
5336
                        ) || api_is_platform_admin()) {
5337
                        $PassEdit = true;
5338
                    } else {
5339
                        Display::addFlash(
5340
                            Display::return_message(
5341
                                get_lang('LockByTeacher'),
5342
                                'normal',
5343
                                false
5344
                            )
5345
                        );
5346
                        $PassEdit = false;
5347
                    }
5348
                } else {
5349
                    $PassEdit = true;
5350
                }
5351
            }
5352
5353
            //show editor if edit is allowed
5354
            if ($PassEdit) {
5355
                if ($current_row['editlock'] == 1 &&
5356
                    (api_is_allowed_to_edit(false, true) == false ||
5357
                        api_is_platform_admin() == false)
5358
                ) {
5359
                    Display::addFlash(
5360
                        Display::return_message(
5361
                            get_lang('PageLockedExtra'),
5362
                            'normal',
5363
                            false
5364
                        )
5365
                    );
5366
                } else {
5367
                    if ($last_row['is_editing'] != 0 && $last_row['is_editing'] != $userId) {
5368
                        // Checking for concurrent users
5369
                        $timestamp_edit = strtotime($last_row['time_edit']);
5370
                        $time_editing = time() - $timestamp_edit;
5371
                        $max_edit_time = 1200; // 20 minutes
5372
                        $rest_time = $max_edit_time - $time_editing;
5373
                        $userinfo = api_get_user_info($last_row['is_editing']);
5374
                        $is_being_edited = get_lang(
5375
                                'ThisPageisBeginEditedBy'
5376
                            ).' <a href='.$userinfo['profile_url'].'>'.
5377
                            Display::tag(
5378
                                'span',
5379
                                $userinfo['complete_name_with_username']
5380
                            ).
5381
                            get_lang('ThisPageisBeginEditedTryLater').' '.date(
5382
                                "i",
5383
                                $rest_time
5384
                            ).' '.get_lang('MinMinutes');
5385
                        Display::addFlash(
5386
                            Display::return_message(
5387
                                $is_being_edited,
5388
                                'normal',
5389
                                false
5390
                            )
5391
                        );
5392
                    } else {
5393
                        Display::addFlash(
5394
                            Display::return_message(
5395
                                self::restore_wikipage(
5396
                                    $current_row['page_id'],
5397
                                    $current_row['reflink'],
5398
                                    $current_row['title'],
5399
                                    $current_row['content'],
5400
                                    $current_row['group_id'],
5401
                                    $current_row['assignment'],
5402
                                    $current_row['progress'],
5403
                                    $current_row['version'],
5404
                                    $last_row['version'],
5405
                                    $current_row['linksto']
5406
                                ).': <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5407
                                    urlencode($last_row['reflink'])
5408
                                ).'&session_id='.$last_row['session_id'].'&group_id='.$last_row['group_id'].'">'.
5409
                                api_htmlentities($last_row['title']).'</a>',
5410
                                'confirmation',
5411
                                false
5412
                            )
5413
                        );
5414
                    }
5415
                }
5416
            }
5417
        }
5418
    }
5419
5420
    /**
5421
     * @param int|bool $wikiId
5422
     */
5423
    public function setWikiData($wikiId)
5424
    {
5425
        $this->wikiData = self::getWikiDataFromDb($wikiId);
5426
    }
5427
5428
    /**
5429
     * @return array
5430
     */
5431
    public function getWikiData()
5432
    {
5433
        return $this->wikiData;
5434
    }
5435
5436
    /**
5437
     * Check last version.
5438
     *
5439
     * @param int $view
5440
     *
5441
     * @return bool
5442
     */
5443
    public function checkLastVersion($view)
5444
    {
5445
        $tbl_wiki = $this->tbl_wiki;
5446
        $course_id = $this->course_id;
5447
        $condition_session = $this->condition_session;
5448
        $groupfilter = $this->groupfilter;
5449
        $page = $this->page;
5450
        $_course = $this->courseInfo;
5451
5452
        if (empty($view)) {
5453
            return false;
5454
        }
5455
5456
        $current_row = $this->getWikiData();
5457
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5458
                WHERE
5459
                    c_id = '.$course_id.' AND
5460
                    reflink = "'.Database::escape_string($page).'" AND
5461
                    '.$groupfilter.$condition_session.'
5462
                ORDER BY id DESC'; //last version
5463
        $result = Database::query($sql);
5464
        $last_row = Database::fetch_array($result);
5465
5466
        if ($view < $last_row['id']) {
5467
            $message = '<center>'.get_lang('NoAreSeeingTheLastVersion').'<br />
5468
            '.get_lang("Version").' (
5469
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5470
                    urlencode($current_row['reflink'])
5471
                ).'&group_id='.$current_row['group_id'].'&session_id='.$current_row['session_id'].'&view='.api_htmlentities(
5472
                    $_GET['view']
5473
                ).'" title="'.get_lang('CurrentVersion').'">
5474
            '.$current_row['version'].'
5475
            </a> /
5476
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5477
                    urlencode($last_row['reflink'])
5478
                ).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'" title="'.get_lang(
5479
                    'LastVersion'
5480
                ).'">
5481
            '.$last_row['version'].'
5482
            </a>) <br />'.get_lang("ConvertToLastVersion").':
5483
            <a href="index.php?cidReq='.$_course['id'].'&action=restorepage&title='.api_htmlentities(
5484
                    urlencode($last_row['reflink'])
5485
                ).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'&view='.api_htmlentities(
5486
                    $_GET['view']
5487
                ).'">'.
5488
                get_lang("Restore").'</a></center>';
5489
            Display::addFlash(
5490
                Display::return_message($message, 'warning', false)
5491
            );
5492
        }
5493
    }
5494
5495
    /**
5496
     *  Get most linked pages.
5497
     */
5498
    public function getMostLinked()
5499
    {
5500
        $tbl_wiki = $this->tbl_wiki;
5501
        $course_id = $this->course_id;
5502
        $groupfilter = $this->groupfilter;
5503
        $condition_session = $this->condition_session;
5504
        $_course = $this->courseInfo;
5505
5506
        echo '<div class="actions">'.get_lang('MostLinkedPages').'</div>';
5507
        $pages = [];
5508
        $linked = [];
5509
5510
        // Get name pages
5511
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5512
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5513
                GROUP BY reflink
5514
                ORDER BY reflink ASC';
5515
        $allpages = Database::query($sql);
5516
        while ($row = Database::fetch_array($allpages)) {
5517
            if ($row['reflink'] == 'index') {
5518
                $row['reflink'] = str_replace(
5519
                    ' ',
5520
                    '_',
5521
                    get_lang('DefaultTitle')
5522
                );
5523
            }
5524
            $pages[] = $row['reflink'];
5525
        }
5526
5527
        // Get name refs in last pages
5528
        $sql = 'SELECT *
5529
                FROM '.$tbl_wiki.' s1
5530
                WHERE s1.c_id = '.$course_id.' AND id=(
5531
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5532
                    WHERE
5533
                        s2.c_id = '.$course_id.' AND
5534
                        s1.reflink = s2.reflink AND
5535
                        '.$groupfilter.$condition_session.'
5536
                )';
5537
5538
        $allpages = Database::query($sql);
5539
5540
        while ($row = Database::fetch_array($allpages)) {
5541
            //remove self reference
5542
            $row['linksto'] = str_replace(
5543
                $row["reflink"],
5544
                " ",
5545
                trim($row["linksto"])
5546
            );
5547
            $refs = explode(" ", trim($row["linksto"]));
5548
5549
            // Find linksto into reflink. If found ->page is linked
5550
            foreach ($refs as $v) {
5551
                if (in_array($v, $pages)) {
5552
                    if (trim($v) != "") {
5553
                        $linked[] = $v;
5554
                    }
5555
                }
5556
            }
5557
        }
5558
5559
        $linked = array_unique($linked);
5560
        //make a unique list. TODO:delete this line and count how many for each page
5561
        //show table
5562
        $rows = [];
5563
        foreach ($linked as $linked_show) {
5564
            $row = [];
5565
            $row[] = '<a href="'.api_get_self(
5566
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5567
                    urlencode(str_replace('_', ' ', $linked_show))
5568
                ).'&session_id='.api_htmlentities(
5569
                    $_GET['session_id']
5570
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5571
                str_replace('_', ' ', $linked_show).'</a>';
5572
            $rows[] = $row;
5573
        }
5574
5575
        $table = new SortableTableFromArrayConfig(
5576
            $rows,
5577
            0,
5578
            10,
5579
            'LinkedPages_table',
5580
            '',
5581
            '',
5582
            'DESC'
5583
        );
5584
        $table->set_additional_parameters(
5585
            [
5586
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5587
                'action' => Security::remove_XSS($this->action),
5588
                'session_id' => intval($_GET['session_id']),
5589
                'group_id' => intval($_GET['group_id']),
5590
            ]
5591
        );
5592
        $table->set_header(0, get_lang('Title'), true);
5593
        $table->display();
5594
    }
5595
5596
    /**
5597
     * Get orphan pages.
5598
     */
5599
    public function getOrphaned()
5600
    {
5601
        $tbl_wiki = $this->tbl_wiki;
5602
        $course_id = $this->course_id;
5603
        $groupfilter = $this->groupfilter;
5604
        $condition_session = $this->condition_session;
5605
        $_course = $this->courseInfo;
5606
5607
        echo '<div class="actions">'.get_lang('OrphanedPages').'</div>';
5608
5609
        $pages = [];
5610
        $orphaned = [];
5611
5612
        //get name pages
5613
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5614
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5615
                GROUP BY reflink
5616
                ORDER BY reflink ASC';
5617
        $allpages = Database::query($sql);
5618
        while ($row = Database::fetch_array($allpages)) {
5619
            $pages[] = $row['reflink'];
5620
        }
5621
5622
        //get name refs in last pages and make a unique list
5623
        $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1
5624
                WHERE s1.c_id = '.$course_id.' AND id=(
5625
                SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5626
                WHERE
5627
                    s2.c_id = '.$course_id.' AND
5628
                    s1.reflink = s2.reflink AND
5629
                    '.$groupfilter.$condition_session.'
5630
                )';
5631
        $allpages = Database::query($sql);
5632
        $array_refs_linked = [];
5633
        while ($row = Database::fetch_array($allpages)) {
5634
            $row['linksto'] = str_replace(
5635
                $row["reflink"],
5636
                " ",
5637
                trim($row["linksto"])
5638
            ); //remove self reference
5639
            $refs = explode(" ", trim($row["linksto"]));
5640
            foreach ($refs as $ref_linked) {
5641
                if ($ref_linked == str_replace(
5642
                        ' ',
5643
                        '_',
5644
                        get_lang('DefaultTitle')
5645
                    )) {
5646
                    $ref_linked = 'index';
5647
                }
5648
                $array_refs_linked[] = $ref_linked;
5649
            }
5650
        }
5651
5652
        $array_refs_linked = array_unique($array_refs_linked);
5653
5654
        //search each name of list linksto into list reflink
5655
        foreach ($pages as $v) {
5656
            if (!in_array($v, $array_refs_linked)) {
5657
                $orphaned[] = $v;
5658
            }
5659
        }
5660
        $rows = [];
5661
        foreach ($orphaned as $orphaned_show) {
5662
            // get visibility status and title
5663
            $sql = 'SELECT *
5664
                    FROM  '.$tbl_wiki.'
5665
		            WHERE
5666
		                c_id = '.$course_id.' AND
5667
		                '.$groupfilter.$condition_session.' AND
5668
		                reflink="'.Database::escape_string($orphaned_show).'"
5669
                    GROUP BY reflink';
5670
            $allpages = Database::query($sql);
5671
            while ($row = Database::fetch_array($allpages)) {
5672
                $orphaned_title = $row['title'];
5673
                $orphaned_visibility = $row['visibility'];
5674
                if ($row['assignment'] == 1) {
5675
                    $ShowAssignment = Display::return_icon(
5676
                        'wiki_assignment.png',
5677
                        '',
5678
                        '',
5679
                        ICON_SIZE_SMALL
5680
                    );
5681
                } elseif ($row['assignment'] == 2) {
5682
                    $ShowAssignment = Display::return_icon(
5683
                        'wiki_work.png',
5684
                        '',
5685
                        '',
5686
                        ICON_SIZE_SMALL
5687
                    );
5688
                } elseif ($row['assignment'] == 0) {
5689
                    $ShowAssignment = Display::return_icon(
5690
                        'px_transparent.gif'
5691
                    );
5692
                }
5693
            }
5694
5695
            if (!api_is_allowed_to_edit(false, true) || !api_is_platform_admin(
5696
                ) && $orphaned_visibility == 0) {
5697
                continue;
5698
            }
5699
5700
            //show table
5701
            $row = [];
5702
            $row[] = $ShowAssignment;
5703
            $row[] = '<a href="'.api_get_self(
5704
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5705
                    urlencode($orphaned_show)
5706
                ).'&session_id='.api_htmlentities(
5707
                    $_GET['session_id']
5708
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5709
                api_htmlentities($orphaned_title).'</a>';
5710
            $rows[] = $row;
5711
        }
5712
5713
        $table = new SortableTableFromArrayConfig(
5714
            $rows,
5715
            1,
5716
            10,
5717
            'OrphanedPages_table',
5718
            '',
5719
            '',
5720
            'DESC'
5721
        );
5722
        $table->set_additional_parameters(
5723
            [
5724
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5725
                'action' => Security::remove_XSS($this->action),
5726
                'session_id' => intval($_GET['session_id']),
5727
                'group_id' => intval($_GET['group_id']),
5728
            ]
5729
        );
5730
        $table->set_header(
5731
            0,
5732
            get_lang('Type'),
5733
            true,
5734
            ['style' => 'width:30px;']
5735
        );
5736
        $table->set_header(1, get_lang('Title'), true);
5737
        $table->display();
5738
    }
5739
5740
    /**
5741
     * Get wanted pages.
5742
     */
5743
    public function getWantedPages()
5744
    {
5745
        $tbl_wiki = $this->tbl_wiki;
5746
        $course_id = $this->course_id;
5747
        $groupfilter = $this->groupfilter;
5748
        $condition_session = $this->condition_session;
5749
5750
        echo '<div class="actions">'.get_lang('WantedPages').'</div>';
5751
        $pages = [];
5752
        $wanted = [];
5753
        //get name pages
5754
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5755
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5756
                GROUP BY reflink
5757
                ORDER BY reflink ASC';
5758
        $allpages = Database::query($sql);
5759
5760
        while ($row = Database::fetch_array($allpages)) {
5761
            if ($row['reflink'] == 'index') {
5762
                $row['reflink'] = str_replace(
5763
                    ' ',
5764
                    '_',
5765
                    get_lang('DefaultTitle')
5766
                );
5767
            }
5768
            $pages[] = $row['reflink'];
5769
        }
5770
5771
        //get name refs in last pages
5772
        $sql = 'SELECT * FROM   '.$tbl_wiki.' s1
5773
                WHERE s1.c_id = '.$course_id.' AND id=(
5774
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5775
                    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.$condition_session.'
5776
                )';
5777
5778
        $allpages = Database::query($sql);
5779
5780
        while ($row = Database::fetch_array($allpages)) {
5781
            $refs = explode(" ", trim($row["linksto"]));
5782
            // Find linksto into reflink. If not found ->page is wanted
5783
            foreach ($refs as $v) {
5784
                if (!in_array($v, $pages)) {
5785
                    if (trim($v) != "") {
5786
                        $wanted[] = $v;
5787
                    }
5788
                }
5789
            }
5790
        }
5791
5792
        $wanted = array_unique($wanted); //make a unique list
5793
5794
        //show table
5795
        $rows = [];
5796
        foreach ($wanted as $wanted_show) {
5797
            $row = [];
5798
            $wanted_show = Security::remove_XSS($wanted_show);
5799
            $row[] = '<a href="'.api_get_path(
5800
                    WEB_PATH
5801
                ).'main/wiki/index.php?cidReq=&action=addnew&title='.str_replace(
5802
                    '_',
5803
                    ' ',
5804
                    $wanted_show
5805
                ).'&session_id='.api_htmlentities(
5806
                    $_GET['session_id']
5807
                ).'&group_id='.api_htmlentities(
5808
                    $_GET['group_id']
5809
                ).'" class="new_wiki_link">'.str_replace(
5810
                    '_',
5811
                    ' ',
5812
                    $wanted_show
5813
                ).'</a>'; //meter un remove xss en lugar de htmlentities
5814
            $rows[] = $row;
5815
        }
5816
5817
        $table = new SortableTableFromArrayConfig(
5818
            $rows,
5819
            0,
5820
            10,
5821
            'WantedPages_table',
5822
            '',
5823
            '',
5824
            'DESC'
5825
        );
5826
        $table->set_additional_parameters(
5827
            [
5828
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5829
                'action' => Security::remove_XSS($this->action),
5830
                'session_id' => intval($_GET['session_id']),
5831
                'group_id' => intval($_GET['group_id']),
5832
            ]
5833
        );
5834
        $table->set_header(0, get_lang('Title'), true);
5835
        $table->display();
5836
    }
5837
5838
    /**
5839
     * Most visited.
5840
     */
5841
    public function getMostVisited()
5842
    {
5843
        $tbl_wiki = $this->tbl_wiki;
5844
        $course_id = $this->course_id;
5845
        $groupfilter = $this->groupfilter;
5846
        $condition_session = $this->condition_session;
5847
        $_course = $this->courseInfo;
5848
5849
        echo '<div class="actions">'.get_lang('MostVisitedPages').'</div>';
5850
5851
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin(
5852
            )) { //only by professors if page is hidden
5853
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5854
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5855
                    GROUP BY reflink';
5856
        } else {
5857
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5858
                    WHERE
5859
                        c_id = '.$course_id.' AND
5860
                        '.$groupfilter.$condition_session.' AND
5861
                        visibility=1
5862
                    GROUP BY reflink';
5863
        }
5864
5865
        $allpages = Database::query($sql);
5866
5867
        //show table
5868
        if (Database::num_rows($allpages) > 0) {
5869
            $rows = [];
5870
            while ($obj = Database::fetch_object($allpages)) {
5871
                //get type assignment icon
5872
                $ShowAssignment = '';
5873
                if ($obj->assignment == 1) {
5874
                    $ShowAssignment = Display::return_icon(
5875
                        'wiki_assignment.png',
5876
                        get_lang('AssignmentDesc'),
5877
                        '',
5878
                        ICON_SIZE_SMALL
5879
                    );
5880
                } elseif ($obj->assignment == 2) {
5881
                    $ShowAssignment = $ShowAssignment = Display::return_icon(
5882
                        'wiki_work.png',
5883
                        get_lang('AssignmentWork'),
5884
                        '',
5885
                        ICON_SIZE_SMALL
5886
                    );
5887
                } elseif ($obj->assignment == 0) {
5888
                    $ShowAssignment = Display::return_icon(
5889
                        'px_transparent.gif'
5890
                    );
5891
                }
5892
5893
                $row = [];
5894
                $row[] = $ShowAssignment;
5895
                $row[] = '<a href="'.api_get_self(
5896
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5897
                        urlencode($obj->reflink)
5898
                    ).'&session_id='.api_htmlentities(
5899
                        $_GET['session_id']
5900
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5901
                    api_htmlentities($obj->title).'</a>';
5902
                $row[] = $obj->tsum;
5903
                $rows[] = $row;
5904
            }
5905
5906
            $table = new SortableTableFromArrayConfig(
5907
                $rows,
5908
                2,
5909
                10,
5910
                'MostVisitedPages_table',
5911
                '',
5912
                '',
5913
                'DESC'
5914
            );
5915
            $table->set_additional_parameters(
5916
                [
5917
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5918
                    'action' => Security::remove_XSS($this->action),
5919
                    'session_id' => intval($_GET['session_id']),
5920
                    'group_id' => intval($_GET['group_id']),
5921
                ]
5922
            );
5923
            $table->set_header(
5924
                0,
5925
                get_lang('Type'),
5926
                true,
5927
                ['style' => 'width:30px;']
5928
            );
5929
            $table->set_header(1, get_lang('Title'), true);
5930
            $table->set_header(2, get_lang('Visits'), true);
5931
            $table->display();
5932
        }
5933
    }
5934
5935
    /**
5936
     * Get actions bar.
5937
     */
5938
    public function showActionBar()
5939
    {
5940
        $_course = $this->courseInfo;
5941
        $session_id = $this->session_id;
5942
        $groupId = $this->group_id;
5943
        $page = $this->page;
5944
        $actionsLeft = '<a href="index.php?action=showpage&title=index&cidReq='.$_course['id'].'&session_id='.$session_id.'&group_id='.$groupId.'">'.
5945
            Display::return_icon(
5946
                'home.png',
5947
                get_lang('Home'),
5948
                '',
5949
                ICON_SIZE_MEDIUM
5950
            ).'</a>';
5951
5952
        if (api_is_allowed_to_session_edit(false, true) && api_is_allowed_to_edit()) {
5953
            // menu add page
5954
            $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=addnew&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
5955
                    'addnew'
5956
                ).'>'
5957
                .Display::return_icon(
5958
                    'new_document.png',
5959
                    get_lang('AddNew'),
5960
                    '',
5961
                    ICON_SIZE_MEDIUM
5962
                ).'</a>';
5963
        }
5964
5965
        $lock_unlock_addnew = null;
5966
        $protect_addnewpage = null;
5967
5968
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5969
            // page action: enable or disable the adding of new pages
5970
            if (self::check_addnewpagelock() == 0) {
5971
                $protect_addnewpage = Display::return_icon(
5972
                    'off.png',
5973
                    get_lang('AddOptionProtected')
5974
                );
5975
                $lock_unlock_addnew = 'unlockaddnew';
5976
            } else {
5977
                $protect_addnewpage = Display::return_icon(
5978
                    'on.png',
5979
                    get_lang('AddOptionUnprotected')
5980
                );
5981
                $lock_unlock_addnew = 'lockaddnew';
5982
            }
5983
        }
5984
5985
        // menu find
5986
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
5987
                'searchpages'
5988
            ).'>'.
5989
            Display::return_icon(
5990
                'search.png',
5991
                get_lang('SearchPages'),
5992
                '',
5993
                ICON_SIZE_MEDIUM
5994
            ).'</a>';
5995
        ///menu more
5996
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'&action=more&title='.api_htmlentities(
5997
                urlencode($page)
5998
            ).'"'.self::is_active_navigation_tab('more').'>'.
5999
            Display::return_icon(
6000
                'statistics.png',
6001
                get_lang('Statistics'),
6002
                '',
6003
                ICON_SIZE_MEDIUM
6004
            ).'</a>';
6005
6006
        // menu all pages
6007
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=allpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6008
                'allpages'
6009
            ).'>'.
6010
            Display::return_icon(
6011
                'list_badges.png',
6012
                get_lang('AllPages'),
6013
                '',
6014
                ICON_SIZE_MEDIUM
6015
            ).'</a>';
6016
        // menu recent changes
6017
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=recentchanges&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6018
                'recentchanges'
6019
            ).'>'.
6020
            Display::return_icon(
6021
                'history.png',
6022
                get_lang('RecentChanges'),
6023
                '',
6024
                ICON_SIZE_MEDIUM
6025
            ).'</a>';
6026
        echo Display::toolbarAction('toolbar-wiki', [$actionsLeft]);
6027
    }
6028
6029
    /**
6030
     * Showing warning.
6031
     */
6032
    public function deletePageWarning()
6033
    {
6034
        $page = $this->page;
6035
        $course_id = $this->course_id;
6036
        $groupfilter = $this->groupfilter;
6037
        $condition_session = $this->condition_session;
6038
6039
        if (!$_GET['title']) {
6040
            Display::addFlash(
6041
                Display::return_message(
6042
                    get_lang('MustSelectPage'),
6043
                    'error',
6044
                    false
6045
                )
6046
            );
6047
6048
            return;
6049
        }
6050
6051
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6052
            Display::addFlash(
6053
                '<div id="wikititle">'.get_lang('DeletePageHistory').'</div>'
6054
            );
6055
            if ($page == "index") {
6056
                Display::addFlash(
6057
                    Display::return_message(
6058
                        get_lang('WarningDeleteMainPage'),
6059
                        'warning',
6060
                        false
6061
                    )
6062
                );
6063
            }
6064
            $message = get_lang('ConfirmDeletePage')."
6065
                <a href=\"index.php?".api_get_cidreq()."\">".get_lang("No")."</a>
6066
                <a href=\"".api_get_self()."?".api_get_cidreq(
6067
                )."&action=delete&title=".api_htmlentities(
6068
                    urlencode($page)
6069
                )."&delete=yes\">".
6070
                get_lang("Yes")."</a>";
6071
6072
            if (!isset($_GET['delete'])) {
6073
                Display::addFlash(
6074
                    Display::return_message($message, 'warning', false)
6075
                );
6076
            }
6077
6078
            if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
6079
                $result = self::deletePage(
6080
                    $page,
6081
                    $course_id,
6082
                    $groupfilter,
6083
                    $condition_session
6084
                );
6085
                if ($result) {
6086
                    Display::addFlash(
6087
                        Display::return_message(
6088
                            get_lang('WikiPageDeleted'),
6089
                            'confirmation',
6090
                            false
6091
                        )
6092
                    );
6093
                }
6094
            }
6095
        } else {
6096
            Display::addFlash(
6097
                Display::return_message(
6098
                    get_lang('OnlyAdminDeletePageWiki'),
6099
                    'normal',
6100
                    false
6101
                )
6102
            );
6103
        }
6104
    }
6105
6106
    /**
6107
     * Edit page.
6108
     */
6109
    public function editPage()
6110
    {
6111
        $tbl_wiki = $this->tbl_wiki;
6112
        $tbl_wiki_conf = $this->tbl_wiki_conf;
6113
        $condition_session = $this->condition_session;
6114
        $groupfilter = $this->groupfilter;
6115
        $page = $this->page;
6116
        $course_id = $this->course_id;
6117
        $groupId = $this->group_id;
6118
        $userId = api_get_user_id();
6119
6120
        if (api_get_session_id() != 0 &&
6121
            api_is_allowed_to_session_edit(false, true) == false
6122
        ) {
6123
            api_not_allowed();
6124
        }
6125
6126
        $sql = 'SELECT *
6127
            FROM '.$tbl_wiki.' w INNER JOIN '.$tbl_wiki_conf.' c
6128
            ON  (w.c_id = c.c_id AND w.page_id = c.page_id)
6129
            WHERE
6130
                w.c_id = '.$course_id.' AND
6131
                w.reflink= "'.Database::escape_string($page).'" AND
6132
                w.'.$groupfilter.$condition_session.'
6133
            ORDER BY id DESC';
6134
        $result = Database::query($sql);
6135
        $row = Database::fetch_array($result);
6136
6137
        $PassEdit = false;
6138
        // Check if is a wiki group
6139
        if (!empty($groupId)) {
6140
            $groupInfo = GroupManager::get_group_properties($groupId);
6141
            //Only teacher, platform admin and group members can edit a wiki group
6142
            if (api_is_allowed_to_edit(false, true) ||
6143
                api_is_platform_admin() ||
6144
                GroupManager::is_user_in_group($userId, $groupInfo)
6145
            ) {
6146
                $PassEdit = true;
6147
            } else {
6148
                Display::addFlash(
6149
                    Display::return_message(
6150
                        get_lang('OnlyEditPagesGroupMembers')
6151
                    )
6152
                );
6153
            }
6154
        } else {
6155
            $PassEdit = true;
6156
        }
6157
6158
        $content = '<div class="text-center">'
6159
            .sprintf(get_lang('DefaultContent'), api_get_path(WEB_IMG_PATH))
6160
            .'</div>';
6161
        $title = get_lang('DefaultTitle');
6162
        $page_id = 0;
6163
6164
        $icon_assignment = '';
6165
6166
        // we do not need awhile loop since we are always displaying the last version
6167
        if ($row) {
6168
            if ($row['content'] == '' && $row['title'] == '' && $page == '') {
6169
                Display::addFlash(
6170
                    Display::return_message(get_lang('MustSelectPage'), 'error', false)
6171
                );
6172
6173
                return;
6174
            }
6175
6176
            $content = api_html_entity_decode($row['content']);
6177
            $title = api_html_entity_decode($row['title']);
6178
            $page_id = $row['page_id'];
6179
6180
            // Only teachers and platform admin can edit the index page.
6181
            // Only teachers and platform admin can edit an assignment teacher.
6182
            // And users in groups
6183
6184
            if (($row['reflink'] == 'index' || $row['reflink'] == '' || $row['assignment'] == 1)
6185
                && (!api_is_allowed_to_edit(false, true) && $groupId == 0)
6186
                && !api_is_allowed_in_course()
6187
            ) {
6188
                Display::addFlash(
6189
                    Display::return_message(get_lang('OnlyEditPagesCourseManager'), 'error')
6190
                );
6191
6192
                return;
6193
            }
6194
6195
            // check if is an assignment
6196
            if ($row['assignment'] == 1) {
6197
                Display::addFlash(
6198
                    Display::return_message(get_lang('EditAssignmentWarning'))
6199
                );
6200
6201
                $icon_assignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'));
6202
            } elseif ($row['assignment'] == 2) {
6203
                $icon_assignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWorkExtra'));
6204
                if (($userId == $row['user_id']) == false) {
6205
                    if (api_is_allowed_to_edit(
6206
                            false,
6207
                            true
6208
                        ) || api_is_platform_admin()) {
6209
                        $PassEdit = true;
6210
                    } else {
6211
                        Display::addFlash(
6212
                            Display::return_message(get_lang('LockByTeacher'), 'warning')
6213
                        );
6214
                        $PassEdit = false;
6215
                    }
6216
                } else {
6217
                    $PassEdit = true;
6218
                }
6219
            }
6220
6221
            if ($PassEdit) {
6222
                if ($row['editlock'] == 1 &&
6223
                    (api_is_allowed_to_edit(false, true) == false ||
6224
                        api_is_platform_admin() == false)
6225
                ) {
6226
                    Display::addFlash(
6227
                        Display::return_message(get_lang('PageLockedExtra'))
6228
                    );
6229
                }
6230
            }
6231
        }
6232
6233
        if ($PassEdit) {
6234
            //show editor if edit is allowed <<<<<
6235
            if ($row['editlock'] != 1
6236
                || api_is_allowed_to_edit(false, true) != false
6237
                && api_is_platform_admin() != false
6238
            ) {
6239
                // Check tasks
6240
                if (!empty($row['startdate_assig']) && time() <
6241
                    api_strtotime($row['startdate_assig'])
6242
                ) {
6243
                    $message = get_lang('TheTaskDoesNotBeginUntil').': '.api_get_local_time($row['startdate_assig']);
6244
6245
                    Display::addFlash(
6246
                        Display::return_message($message, 'warning')
6247
                    );
6248
6249
                    if (!api_is_allowed_to_edit(false, true)) {
6250
                        $this->redirectHome();
6251
                    }
6252
                }
6253
6254
                if (!empty($row['enddate_assig']) &&
6255
                    time() > strtotime($row['enddate_assig']) &&
6256
                    $row['delayedsubmit'] == 0
6257
                ) {
6258
                    $message = get_lang('TheDeadlineHasBeenCompleted').': '.api_get_local_time($row['enddate_assig']);
6259
                    Display::addFlash(
6260
                        Display::return_message($message, 'warning')
6261
                    );
6262
                    if (!api_is_allowed_to_edit(false, true)) {
6263
                        $this->redirectHome();
6264
                    }
6265
                }
6266
6267
                if (!empty($row['max_version']) && $row['version'] >= $row['max_version']) {
6268
                    $message = get_lang('HasReachedMaxiNumVersions');
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_text']) && $row['max_text'] <= self::word_count(
6278
                        $row['content']
6279
                    )) {
6280
                    $message = get_lang('HasReachedMaxNumWords');
6281
                    Display::addFlash(
6282
                        Display::return_message($message, 'warning')
6283
                    );
6284
                    if (!api_is_allowed_to_edit(false, true)) {
6285
                        $this->redirectHome();
6286
                    }
6287
                }
6288
6289
                if (!empty($row['task'])) {
6290
                    //previous change 0 by text
6291
                    $message_task_startdate = empty($row['startdate_assig'])
6292
                        ? api_get_local_time($row['startdate_assig'])
6293
                        : get_lang('No');
6294
6295
                    $message_task_enddate = empty($row['enddate_assig'])
6296
                        ? api_get_local_time($row['enddate_assig'])
6297
                        : get_lang('No');
6298
6299
                    $message_task_delayedsubmit = $row['delayedsubmit'] == 0 ? get_lang('No') : get_lang('Yes');
6300
6301
                    $message_task_max_version = $row['max_version'] == 0 ? get_lang('No') : $row['max_version'];
6302
6303
                    $message_task_max_text = $row['max_text'] == 0 ? get_lang('No') : $row['max_text'];
6304
6305
                    // Comp message
6306
                    $message_task = '<b>'.get_lang('DescriptionOfTheTask').'</b><p>'.$row['task'].'</p><hr>'
6307
                        .'<p>'.get_lang('StartDate').': '.$message_task_startdate.'</p>'
6308
                        .'<p>'.get_lang('EndDate').': '.$message_task_enddate
6309
                        .' ('.get_lang('AllowLaterSends').') '.$message_task_delayedsubmit.'</p>'
6310
                        .'<p>'.get_lang('OtherSettings').': '.get_lang('NMaxVersion').': '.$message_task_max_version
6311
                        .' '.get_lang('NMaxWords').': '.$message_task_max_text.'</p>';
6312
                    // Display message
6313
                    Display::addFlash(
6314
                        Display::return_message($message_task)
6315
                    );
6316
                }
6317
6318
                $feedback_message = '';
6319
                if ($row['progress'] == $row['fprogress1'] && !empty($row['fprogress1'])) {
6320
                    $feedback_message = '<b>'.get_lang('Feedback').'</b>'
6321
                        .'<p>'.api_htmlentities($row['feedback1']).'</p>';
6322
                } elseif ($row['progress'] == $row['fprogress2'] && !empty($row['fprogress2'])) {
6323
                    $feedback_message = '<b>'.get_lang('Feedback').'</b>'
6324
                        .'<p>'.api_htmlentities($row['feedback2']).'</p>';
6325
                } elseif ($row['progress'] == $row['fprogress3'] && !empty($row['fprogress3'])) {
6326
                    $feedback_message = '<b>'.get_lang('Feedback').'</b>'
6327
                        .'<p>'.api_htmlentities($row['feedback3']).'</p>';
6328
                }
6329
6330
                if (!empty($feedback_message)) {
6331
                    Display::addFlash(
6332
                        Display::return_message($feedback_message)
6333
                    );
6334
                }
6335
6336
                // Previous checking for concurrent editions
6337
                if ($row['is_editing'] == 0) {
6338
                    Display::addFlash(
6339
                        Display::return_message(get_lang('WarningMaxEditingTime'))
6340
                    );
6341
                    $time_edit = api_get_utc_datetime();
6342
                    $sql = 'UPDATE '.$tbl_wiki.' SET
6343
                            is_editing = "'.$userId.'",
6344
                            time_edit = "'.$time_edit.'"
6345
                            WHERE c_id = '.$course_id.' AND id="'.$row['id'].'"';
6346
                    Database::query($sql);
6347
                } elseif ($row['is_editing'] != $userId) {
6348
                    $timestamp_edit = strtotime($row['time_edit']);
6349
                    $time_editing = time() - $timestamp_edit;
6350
                    $max_edit_time = 1200; // 20 minutes
6351
                    $rest_time = $max_edit_time - $time_editing;
6352
6353
                    $userinfo = api_get_user_info($row['is_editing']);
6354
                    if ($userinfo !== false) {
6355
                        $is_being_edited = get_lang('ThisPageisBeginEditedBy').PHP_EOL
6356
                            .UserManager::getUserProfileLink($userinfo).PHP_EOL
6357
                            .get_lang('ThisPageisBeginEditedTryLater').PHP_EOL
6358
                            .date("i", $rest_time).PHP_EOL
6359
                            .get_lang('MinMinutes');
6360
6361
                        Display::addFlash(
6362
                            Display::return_message($is_being_edited, 'normal', false)
6363
                        );
6364
                    }
6365
6366
                    $this->redirectHome();
6367
                }
6368
6369
                // Form.
6370
                $url = api_get_self().'?action=edit&title='.urlencode($page).'&session_id='.api_get_session_id()
6371
                    .'&group_id='.api_get_group_id().'&'.api_get_cidreq();
6372
                $form = new FormValidator('wiki', 'post', $url);
6373
                $form->addElement(
6374
                    'header',
6375
                    $icon_assignment.str_repeat('&nbsp;', 3).api_htmlentities($title)
6376
                );
6377
                self::setForm($form, $row);
6378
                $form->addElement('hidden', 'title');
6379
                $form->addButtonSave(get_lang('Save'), 'SaveWikiChange');
6380
                $row['title'] = $title;
6381
                $row['page_id'] = $page_id;
6382
                $row['reflink'] = $page;
6383
                $row['content'] = $content;
6384
6385
                $form->setDefaults($row);
6386
                $form->display();
6387
6388
                // Saving a change
6389
                if ($form->validate()) {
6390
                    $versionFromSession = Session::read('_version');
6391
                    if (empty($_POST['title'])) {
6392
                        Display::addFlash(
6393
                            Display::return_message(
6394
                                get_lang("NoWikiPageTitle"),
6395
                                'error'
6396
                            )
6397
                        );
6398
                    } elseif (!self::double_post($_POST['wpost_id'])) {
6399
                        //double post
6400
                    } elseif ($_POST['version'] != '' && $versionFromSession != 0 && $_POST['version'] != $versionFromSession) {
6401
                        //prevent concurrent users and double version
6402
                        Display::addFlash(
6403
                            Display::return_message(
6404
                                get_lang("EditedByAnotherUser"),
6405
                                'error'
6406
                            )
6407
                        );
6408
                    } else {
6409
                        $returnMessage = self::save_wiki(
6410
                            $form->exportValues()
6411
                        );
6412
                        Display::addFlash(
6413
                            Display::return_message(
6414
                                $returnMessage,
6415
                                'confirmation'
6416
                            )
6417
                        );
6418
                    }
6419
                    $wikiData = self::getWikiData();
6420
                    $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq();
6421
                    header('Location: '.$redirectUrl);
6422
                    exit;
6423
                }
6424
            }
6425
        }
6426
    }
6427
6428
    /**
6429
     * Get history.
6430
     */
6431
    public function getHistory()
6432
    {
6433
        $tbl_wiki = $this->tbl_wiki;
6434
        $condition_session = $this->condition_session;
6435
        $groupfilter = $this->groupfilter;
6436
        $page = $this->page;
6437
        $course_id = $this->course_id;
6438
        $session_id = $this->session_id;
6439
        $userId = api_get_user_id();
6440
6441
        if (!$_GET['title']) {
6442
            Display::addFlash(
6443
                Display::return_message(
6444
                    get_lang("MustSelectPage"),
6445
                    'error',
6446
                    false
6447
                )
6448
            );
6449
6450
            return;
6451
        }
6452
6453
        /* First, see the property visibility that is at the last register and
6454
        therefore we should select descending order.
6455
        But to give ownership to each record,
6456
        this is no longer necessary except for the title. TODO: check this*/
6457
6458
        $sql = 'SELECT * FROM '.$tbl_wiki.'
6459
                WHERE
6460
                    c_id = '.$course_id.' AND
6461
                    reflink="'.Database::escape_string($page).'" AND
6462
                    '.$groupfilter.$condition_session.'
6463
                ORDER BY id DESC';
6464
        $result = Database::query($sql);
6465
6466
        $KeyVisibility = null;
6467
        $KeyAssignment = null;
6468
        $KeyTitle = null;
6469
        $KeyUserId = null;
6470
        while ($row = Database::fetch_array($result)) {
6471
            $KeyVisibility = $row['visibility'];
6472
            $KeyAssignment = $row['assignment'];
6473
            $KeyTitle = $row['title'];
6474
            $KeyUserId = $row['user_id'];
6475
        }
6476
        $icon_assignment = null;
6477
        if ($KeyAssignment == 1) {
6478
            $icon_assignment = Display::return_icon(
6479
                'wiki_assignment.png',
6480
                get_lang('AssignmentDescExtra'),
6481
                '',
6482
                ICON_SIZE_SMALL
6483
            );
6484
        } elseif ($KeyAssignment == 2) {
6485
            $icon_assignment = Display::return_icon(
6486
                'wiki_work.png',
6487
                get_lang('AssignmentWorkExtra'),
6488
                '',
6489
                ICON_SIZE_SMALL
6490
            );
6491
        }
6492
6493
        // Second, show
6494
        //if the page is hidden and is a job only sees its author and professor
6495
        if ($KeyVisibility == 1 ||
6496
            api_is_allowed_to_edit(false, true) ||
6497
            api_is_platform_admin() ||
6498
            (
6499
                $KeyAssignment == 2 && $KeyVisibility == 0 &&
6500
                ($userId == $KeyUserId)
6501
            )
6502
        ) {
6503
            // We show the complete history
6504
            if (!isset($_POST['HistoryDifferences']) &&
6505
                !isset($_POST['HistoryDifferences2'])
6506
            ) {
6507
                $sql = 'SELECT * FROM '.$tbl_wiki.'
6508
                        WHERE
6509
                            c_id = '.$course_id.' AND
6510
                            reflink="'.Database::escape_string($page).'" AND
6511
                            '.$groupfilter.$condition_session.'
6512
                        ORDER BY id DESC';
6513
                $result = Database::query($sql);
6514
                $title = $_GET['title'];
6515
                $group_id = api_get_group_id();
6516
6517
                echo '<div id="wikititle">';
6518
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities(
6519
                        $KeyTitle
6520
                    );
6521
                echo '</div>';
6522
6523
                echo '<form id="differences" method="POST" action="index.php?'.api_get_cidreq(
6524
                    ).'&action=history&title='.api_htmlentities(
6525
                        urlencode($title)
6526
                    ).'&session_id='.api_htmlentities(
6527
                        $session_id
6528
                    ).'&group_id='.api_htmlentities($group_id).'">';
6529
6530
                echo '<ul style="list-style-type: none;">';
6531
                echo '<br/>';
6532
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.
6533
                    get_lang('ShowDifferences').' '.get_lang(
6534
                        'LinesDiff'
6535
                    ).'</button>';
6536
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.
6537
                    get_lang('ShowDifferences').' '.get_lang(
6538
                        'WordsDiff'
6539
                    ).'</button>';
6540
                echo '<br/><br/>';
6541
6542
                $counter = 0;
6543
                $total_versions = Database::num_rows($result);
6544
6545
                while ($row = Database::fetch_array($result)) {
6546
                    $userinfo = api_get_user_info($row['user_id']);
6547
                    $username = api_htmlentities(
6548
                        sprintf(get_lang('LoginX'), $userinfo['username']),
6549
                        ENT_QUOTES
6550
                    );
6551
6552
                    echo '<li style="margin-bottom: 5px;">';
6553
                    ($counter == 0) ? $oldstyle = 'style="visibility: hidden;"' : $oldstyle = '';
6554
                    ($counter == 0) ? $newchecked = ' checked' : $newchecked = '';
6555
                    ($counter == $total_versions - 1) ? $newstyle = 'style="visibility: hidden;"' : $newstyle = '';
6556
                    ($counter == 1) ? $oldchecked = ' checked' : $oldchecked = '';
6557
                    echo '<input name="old" value="'.$row['id'].'" type="radio" '.$oldstyle.' '.$oldchecked.'/> ';
6558
                    echo '<input name="new" value="'.$row['id'].'" type="radio" '.$newstyle.' '.$newchecked.'/> ';
6559
                    echo '<a href="'.api_get_self(
6560
                        ).'?action=showpage&title='.api_htmlentities(
6561
                            urlencode($page)
6562
                        ).'&view='.$row['id'].'">';
6563
                    echo '<a href="'.api_get_self().'?'.api_get_cidreq(
6564
                        ).'&action=showpage&title='.api_htmlentities(
6565
                            urlencode($page)
6566
                        ).'&view='.$row['id'].'">';
6567
                    echo api_get_local_time(
6568
                        $row['dtime']
6569
                    );
6570
                    echo '</a>';
6571
                    echo ' ('.get_lang('Version').' '.$row['version'].')';
6572
                    echo ' '.get_lang('By').' ';
6573
                    if ($userinfo !== false) {
6574
                        echo UserManager::getUserProfileLink($userinfo);
6575
                    } else {
6576
                        echo get_lang('Anonymous').' ('.api_htmlentities(
6577
                                $row['user_ip']
6578
                            ).')';
6579
                    }
6580
                    echo ' ( '.get_lang('Progress').': '.api_htmlentities(
6581
                            $row['progress']
6582
                        ).'%, ';
6583
                    $comment = $row['comment'];
6584
                    if (!empty($comment)) {
6585
                        $comment = api_substr($comment, 0, 100);
6586
                        if ($comment !== false) {
6587
                            $comment = api_htmlentities($comment);
6588
                            echo get_lang('Comments').': '.$comment;
6589
                            if (api_strlen($row['comment']) > 100) {
6590
                                echo '... ';
6591
                            }
6592
                        }
6593
                    } else {
6594
                        echo get_lang('Comments').':  ---';
6595
                    }
6596
                    echo ' ) </li>';
6597
                    $counter++;
6598
                } //end while
6599
6600
                echo '<br/>';
6601
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.get_lang(
6602
                        'ShowDifferences'
6603
                    ).' '.get_lang('LinesDiff').'</button>';
6604
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.get_lang(
6605
                        'ShowDifferences'
6606
                    ).' '.get_lang('WordsDiff').'</button>';
6607
                echo '</ul></form>';
6608
            } else { // We show the differences between two versions
6609
                $version_old = [];
6610
                if (isset($_POST['old'])) {
6611
                    $sql_old = "SELECT * FROM $tbl_wiki
6612
                                WHERE c_id = $course_id AND id='".Database::escape_string(
6613
                            $_POST['old']
6614
                        )."'";
6615
                    $result_old = Database::query($sql_old);
6616
                    $version_old = Database::fetch_array($result_old);
6617
                }
6618
6619
                $sql_new = "SELECT * FROM $tbl_wiki
6620
                            WHERE
6621
                              c_id = $course_id AND
6622
                              id = '".Database::escape_string($_POST['new'])."'";
6623
                $result_new = Database::query($sql_new);
6624
                $version_new = Database::fetch_array($result_new);
6625
                $oldTime = isset($version_old['dtime']) ? api_get_local_time($version_old['dtime']) : null;
6626
                $oldContent = isset($version_old['content']) ? $version_old['content'] : null;
6627
6628
                if (isset($_POST['HistoryDifferences'])) {
6629
                    include 'diff.inc.php';
6630
                    //title
6631
                    echo '<div id="wikititle">'.api_htmlentities(
6632
                            $version_new['title']
6633
                        ).'
6634
                            <font size="-2"><i>('.get_lang('DifferencesNew').'</i>
6635
                            <font style="background-color:#aaaaaa">'.api_get_local_time($version_new['dtime']).'</font>
6636
                            <i>'.get_lang('DifferencesOld').'</i>
6637
                            <font style="background-color:#aaaaaa">'.$oldTime.'</font>
6638
                ) '.get_lang('Legend').':  <span class="diffAdded" >'.get_lang(
6639
                            'WikiDiffAddedLine'
6640
                        ).'</span>
6641
                <span class="diffDeleted" >'.get_lang(
6642
                            'WikiDiffDeletedLine'
6643
                        ).'</span> <span class="diffMoved">'.get_lang(
6644
                            'WikiDiffMovedLine'
6645
                        ).'</span></font>
6646
                </div>';
6647
                }
6648
                if (isset($_POST['HistoryDifferences2'])) {
6649
                    //title
6650
                    echo '<div id="wikititle">'.api_htmlentities(
6651
                            $version_new['title']
6652
                        ).'
6653
                        <font size="-2"><i>('.get_lang(
6654
                            'DifferencesNew'
6655
                        ).'</i> <font style="background-color:#aaaaaa">'.api_get_local_time($version_new['dtime']).'</font>
6656
                        <i>'.get_lang(
6657
                            'DifferencesOld'
6658
                        ).'</i> <font style="background-color:#aaaaaa">'.$oldTime.'</font>)
6659
                        '.get_lang(
6660
                            'Legend'
6661
                        ).':  <span class="diffAddedTex" >'.get_lang(
6662
                            'WikiDiffAddedTex'
6663
                        ).'</span>
6664
                        <span class="diffDeletedTex" >'.get_lang(
6665
                            'WikiDiffDeletedTex'
6666
                        ).'</span></font></div>';
6667
                }
6668
6669
                if (isset($_POST['HistoryDifferences'])) {
6670
                    echo '<table>'.diff(
6671
                            $oldContent,
6672
                            $version_new['content'],
6673
                            true,
6674
                            'format_table_line'
6675
                        ).'</table>'; // format_line mode is better for words
6676
                    echo '<br />';
6677
                    echo '<strong>'.get_lang(
6678
                            'Legend'
6679
                        ).'</strong><div class="diff">'."\n";
6680
                    echo '<table><tr>';
6681
                    echo '<td>';
6682
                    echo '</td><td>';
6683
                    echo '<span class="diffEqual" >'.get_lang(
6684
                            'WikiDiffUnchangedLine'
6685
                        ).'</span><br />';
6686
                    echo '<span class="diffAdded" >'.get_lang(
6687
                            'WikiDiffAddedLine'
6688
                        ).'</span><br />';
6689
                    echo '<span class="diffDeleted" >'.get_lang(
6690
                            'WikiDiffDeletedLine'
6691
                        ).'</span><br />';
6692
                    echo '<span class="diffMoved" >'.get_lang(
6693
                            'WikiDiffMovedLine'
6694
                        ).'</span><br />';
6695
                    echo '</td>';
6696
                    echo '</tr></table>';
6697
                }
6698
6699
                if (isset($_POST['HistoryDifferences2'])) {
6700
                    $lines1 = [strip_tags($oldContent)]; //without <> tags
6701
                    $lines2 = [
6702
                        strip_tags(
6703
                            $version_new['content']
6704
                        ),
6705
                    ]; //without <> tags
6706
                    $diff = new Text_Diff($lines1, $lines2);
6707
                    $renderer = new Text_Diff_Renderer_inline();
6708
                    echo '<style>del{background:#fcc}ins{background:#cfc}</style>'.$renderer->render(
6709
                            $diff
6710
                        ); // Code inline
6711
                    echo '<br />';
6712
                    echo '<strong>'.get_lang(
6713
                            'Legend'
6714
                        ).'</strong><div class="diff">'."\n";
6715
                    echo '<table><tr>';
6716
                    echo '<td>';
6717
                    echo '</td><td>';
6718
                    echo '<span class="diffAddedTex" >'.get_lang(
6719
                            'WikiDiffAddedTex'
6720
                        ).'</span><br />';
6721
                    echo '<span class="diffDeletedTex" >'.get_lang(
6722
                            'WikiDiffDeletedTex'
6723
                        ).'</span><br />';
6724
                    echo '</td>';
6725
                    echo '</tr></table>';
6726
                }
6727
            }
6728
        }
6729
    }
6730
6731
    /**
6732
     * Get stat tables.
6733
     */
6734
    public function getStatsTable()
6735
    {
6736
        $_course = $this->courseInfo;
6737
        $session_id = $this->session_id;
6738
        $groupId = $this->group_id;
6739
6740
        echo '<div class="actions">'.get_lang('More').'</div>';
6741
        echo '<table border="0">';
6742
        echo '  <tr>';
6743
        echo '    <td>';
6744
        echo '      <ul>';
6745
        //Submenu Most active users
6746
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mactiveusers&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6747
                'MostActiveUsers'
6748
            ).'</a></li>';
6749
        //Submenu Most visited pages
6750
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mvisited&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6751
                'MostVisitedPages'
6752
            ).'</a></li>';
6753
        //Submenu Most changed pages
6754
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mostchanged&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6755
                'MostChangedPages'
6756
            ).'</a></li>';
6757
        echo '      </ul>';
6758
        echo '    </td>';
6759
        echo '    <td>';
6760
        echo '      <ul>';
6761
        // Submenu Orphaned pages
6762
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=orphaned&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6763
                'OrphanedPages'
6764
            ).'</a></li>';
6765
        // Submenu Wanted pages
6766
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=wanted&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6767
                'WantedPages'
6768
            ).'</a></li>';
6769
        // Submenu Most linked pages
6770
        echo '<li><a href="index.php?cidReq='.$_course['code'].'&action=mostlinked&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6771
                'MostLinkedPages'
6772
            ).'</a></li>';
6773
        echo '</ul>';
6774
        echo '</td>';
6775
        echo '<td style="vertical-align:top">';
6776
        echo '<ul>';
6777
        // Submenu Statistics
6778
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6779
            echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=statistics&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6780
                    'Statistics'
6781
                ).'</a></li>';
6782
        }
6783
        echo '      </ul>';
6784
        echo '    </td>';
6785
        echo '  </tr>';
6786
        echo '</table>';
6787
    }
6788
6789
    /**
6790
     * Kind of controller.
6791
     */
6792
    public function handleAction(string $action)
6793
    {
6794
        $page = $this->page;
6795
        switch ($action) {
6796
            case 'export_to_pdf':
6797
                if (isset($_GET['wiki_id'])) {
6798
                    self::export_to_pdf($_GET['wiki_id'], api_get_course_id());
6799
                    break;
6800
                }
6801
                break;
6802
            case 'export2doc':
6803
                if (isset($_GET['wiki_id'])) {
6804
                    $export2doc = self::export2doc($_GET['wiki_id']);
6805
                    if ($export2doc) {
6806
                        Display::addFlash(
6807
                            Display::return_message(
6808
                                get_lang('ThePageHasBeenExportedToDocArea'),
6809
                                'confirmation',
6810
                                false
6811
                            )
6812
                        );
6813
                    }
6814
                }
6815
                break;
6816
            case 'restorepage':
6817
                self::restorePage();
6818
                break;
6819
            case 'more':
6820
                self::getStatsTable();
6821
                break;
6822
            case 'statistics':
6823
                self::getStats();
6824
                break;
6825
            case 'mactiveusers':
6826
                self::getActiveUsers($action);
6827
                break;
6828
            case 'usercontrib':
6829
                self::getUserContributions($_GET['user_id'], $action);
6830
                break;
6831
            case 'mostchanged':
6832
                $this->getMostChangedPages($action);
6833
                break;
6834
            case 'mvisited':
6835
                self::getMostVisited();
6836
                break;
6837
            case 'wanted':
6838
                $this->getWantedPages();
6839
                break;
6840
            case 'orphaned':
6841
                self::getOrphaned();
6842
                break;
6843
            case 'mostlinked':
6844
                self::getMostLinked();
6845
                break;
6846
            case 'delete':
6847
                self::deletePageWarning($page);
6848
                break;
6849
            case 'deletewiki':
6850
                $title = '<div class="actions">'.get_lang(
6851
                        'DeleteWiki'
6852
                    ).'</div>';
6853
                if (api_is_allowed_to_edit(
6854
                        false,
6855
                        true
6856
                    ) || api_is_platform_admin()) {
6857
                    $message = get_lang('ConfirmDeleteWiki');
6858
                    $message .= '<p>
6859
                        <a href="index.php?'.api_get_cidreq().'">'.get_lang(
6860
                            'No'
6861
                        ).'</a>
6862
                        &nbsp;&nbsp;|&nbsp;&nbsp;
6863
                        <a href="'.api_get_self().'?'.api_get_cidreq(
6864
                        ).'&action=deletewiki&delete=yes">'.
6865
                        get_lang('Yes').'</a>
6866
                    </p>';
6867
6868
                    if (!isset($_GET['delete'])) {
6869
                        Display::addFlash(
6870
                            $title.Display::return_message(
6871
                                $message,
6872
                                'warning',
6873
                                false
6874
                            )
6875
                        );
6876
                    }
6877
                } else {
6878
                    Display::addFlash(
6879
                        Display::return_message(
6880
                            get_lang("OnlyAdminDeleteWiki"),
6881
                            'normal',
6882
                            false
6883
                        )
6884
                    );
6885
                }
6886
6887
                if (api_is_allowed_to_edit(
6888
                        false,
6889
                        true
6890
                    ) || api_is_platform_admin()) {
6891
                    if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
6892
                        $return_message = self::delete_wiki();
6893
                        Display::addFlash(
6894
                            Display::return_message(
6895
                                $return_message,
6896
                                'confirmation',
6897
                                false
6898
                            )
6899
                        );
6900
                        $this->redirectHome();
6901
                    }
6902
                }
6903
                break;
6904
            case 'searchpages':
6905
                self::getSearchPages($action);
6906
                break;
6907
            case 'links':
6908
                self::getLinks($page);
6909
                break;
6910
            case 'addnew':
6911
                if (api_get_session_id() != 0 && api_is_allowed_to_session_edit(false, true) == false) {
6912
                    api_not_allowed();
6913
                }
6914
                $groupInfo = GroupManager::get_group_properties(
6915
                    api_get_group_id()
6916
                );
6917
                echo '<div class="actions">'.get_lang('AddNew').'</div>';
6918
                echo '<br/>';
6919
                //first, check if page index was created. chektitle=false
6920
                if (self::checktitle('index')) {
6921
                    if (api_is_allowed_to_edit(false, true) ||
6922
                        api_is_platform_admin() ||
6923
                        GroupManager::is_user_in_group(
6924
                            api_get_user_id(),
6925
                            $groupInfo
6926
                        ) ||
6927
                        api_is_allowed_in_course()
6928
                    ) {
6929
                        Display::addFlash(
6930
                            Display::return_message(get_lang('GoAndEditMainPage'), 'normal', false)
6931
                        );
6932
                    } else {
6933
                        Display::addFlash(
6934
                            Display::return_message(get_lang('WikiStandBy'), 'normal', false)
6935
                        );
6936
                    }
6937
                } elseif (self::check_addnewpagelock() == 0
6938
                    && (
6939
                        api_is_allowed_to_edit(false, true) == false
6940
                        || api_is_platform_admin() == false
6941
                    )
6942
                ) {
6943
                    Display::addFlash(
6944
                        Display::return_message(get_lang('AddPagesLocked'), 'error', false)
6945
                    );
6946
                } else {
6947
                    $groupInfo = GroupManager::get_group_properties(
6948
                        api_get_group_id()
6949
                    );
6950
                    if (api_is_allowed_to_edit(false, true) ||
6951
                        api_is_platform_admin() ||
6952
                        GroupManager::is_user_in_group(
6953
                            api_get_user_id(),
6954
                            $groupInfo
6955
                        ) ||
6956
                        $_GET['group_id'] == 0
6957
                    ) {
6958
                        self::display_new_wiki_form();
6959
                    } else {
6960
                        Display::addFlash(
6961
                            Display::return_message(get_lang('OnlyAddPagesGroupMembers'), 'normal', false)
6962
                        );
6963
                    }
6964
                }
6965
                break;
6966
            case 'show':
6967
            case 'showpage':
6968
                self::display_wiki_entry($page);
6969
                break;
6970
            case 'edit':
6971
                self::editPage();
6972
                break;
6973
            case 'history':
6974
                self::getHistory();
6975
                break;
6976
            case 'recentchanges':
6977
                self::recentChanges($page, $action);
6978
                break;
6979
            case 'allpages':
6980
                self::allPages($action);
6981
                break;
6982
            case 'discuss':
6983
                self::getDiscuss($page);
6984
                break;
6985
            case 'export_to_doc_file':
6986
                self::exportTo($_GET['id'], 'odt');
6987
                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...
6988
                break;
6989
        }
6990
    }
6991
6992
    /**
6993
     * Redirect to home.
6994
     */
6995
    public function redirectHome()
6996
    {
6997
        $redirectUrl = $this->url.'&action=showpage&title=index';
6998
        header('Location: '.$redirectUrl.'&'.api_get_cidreq());
6999
        exit;
7000
    }
7001
7002
    /**
7003
     * Export wiki content in a ODF.
7004
     *
7005
     * @param int $id
7006
     * @param string int
7007
     *
7008
     * @return bool
7009
     */
7010
    public function exportTo($id, $format = 'doc')
7011
    {
7012
        $data = self::getWikiDataFromDb($id);
7013
7014
        if (isset($data['content']) && !empty($data['content'])) {
7015
            Export::htmlToOdt($data['content'], $data['reflink'], $format);
7016
        }
7017
7018
        return false;
7019
    }
7020
7021
    private function gelAllPagesQuery(
7022
        $onlyCount = false,
7023
        $from = 0,
7024
        $numberOfItems = 10,
7025
        $column = 0,
7026
        $direction = 'ASC'
7027
    ): ?Statement {
7028
        $tblWiki = $this->tbl_wiki;
7029
7030
        $fields = $onlyCount
7031
            ? 'COUNT(s1.iid) AS nbr'
7032
            : 's1.assignment AS col0, s1.title AS col1, s1.user_id AS col2, s1.dtime AS col3, s1.reflink, s1.user_ip';
7033
7034
        $query = 'SELECT '.$fields.' FROM '.$tblWiki.' s1 WHERE s1.c_id = '.$this->course_id.' ';
7035
7036
        if (!api_is_allowed_to_edit(false, true) && !api_is_platform_admin()) {
7037
            // warning don't use group by reflink because does not return the last version
7038
            $query .= 'AND visibility = 1 ';
7039
        }
7040
7041
        $query .= 'AND id = (
7042
            SELECT MAX(s2.id) FROM '.$tblWiki.' s2
7043
            WHERE s2.c_id = '.$this->course_id.'
7044
                AND s1.reflink = s2.reflink
7045
                AND '.$this->groupfilter.'
7046
                AND session_id = '.$this->session_id.'
7047
        ) ';
7048
7049
        if (!$onlyCount) {
7050
            $query .= "ORDER BY col$column $direction LIMIT $from, $numberOfItems";
7051
        }
7052
7053
        return Database::query($query);
7054
    }
7055
}
7056