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

Wiki::addCategory()   B

Complexity

Conditions 9
Paths 24

Size

Total Lines 65
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 40
c 0
b 0
f 0
dl 0
loc 65
rs 7.7244
cc 9
nop 0
nc 24

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

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

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

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