Passed
Pull Request — 1.11.x (#4515)
by Angel Fernando Quiroz
10:47 queued 18s
created

Wiki::allPages()   C

Complexity

Conditions 13
Paths 4

Size

Total Lines 188
Code Lines 125

Duplication

Lines 0
Ratio 0 %

Importance

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

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CourseBundle\Entity\CWiki;
6
use Chamilo\CourseBundle\Entity\CWikiCategory;
7
use ChamiloSession as Session;
8
use Doctrine\DBAL\Driver\Statement;
9
10
/**
11
 * Class Wiki
12
 * Functions library for the wiki tool.
13
 *
14
 * @author Juan Carlos Raña <[email protected]>
15
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
16
 * @author Julio Montoya <[email protected]> using the pdf.lib.php library
17
 */
18
class Wiki
19
{
20
    public $tbl_wiki;
21
    public $tbl_wiki_discuss;
22
    public $tbl_wiki_mailcue;
23
    public $tbl_wiki_conf;
24
    public $session_id = null;
25
    public $course_id = null;
26
    public $condition_session = null;
27
    public $group_id;
28
    public $assig_user_id;
29
    public $groupfilter = 'group_id=0';
30
    public $courseInfo;
31
    public $charset;
32
    public $page;
33
    public $action;
34
    public $wikiData = [];
35
    public $url;
36
37
    /**
38
     * Constructor.
39
     */
40
    public function __construct()
41
    {
42
        // Database table definition
43
        $this->tbl_wiki = Database::get_course_table(TABLE_WIKI);
44
        $this->tbl_wiki_discuss = Database::get_course_table(
45
            TABLE_WIKI_DISCUSS
46
        );
47
        $this->tbl_wiki_mailcue = Database::get_course_table(
48
            TABLE_WIKI_MAILCUE
49
        );
50
        $this->tbl_wiki_conf = Database::get_course_table(TABLE_WIKI_CONF);
51
52
        $this->session_id = api_get_session_id();
53
        $this->condition_session = api_get_session_condition($this->session_id);
54
        $this->course_id = api_get_course_int_id();
55
        $this->group_id = api_get_group_id();
56
57
        if (!empty($this->group_id)) {
58
            $this->groupfilter = ' group_id="'.$this->group_id.'"';
59
        }
60
        $this->courseInfo = api_get_course_info();
61
        $this->url = api_get_path(WEB_CODE_PATH).'wiki/index.php?'.api_get_cidreq();
62
    }
63
64
    /**
65
     * Check whether this title is already used.
66
     *
67
     * @param string $link
68
     *
69
     * @return bool False if title is already taken
70
     *
71
     * @author Patrick Cool <[email protected]>, Ghent University
72
     */
73
    public function checktitle($link)
74
    {
75
        $tbl_wiki = $this->tbl_wiki;
76
        $condition_session = $this->condition_session;
77
        $course_id = $this->course_id;
78
        $groupfilter = $this->groupfilter;
79
80
        $sql = 'SELECT * FROM '.$tbl_wiki.'
81
                WHERE
82
                    c_id = '.$course_id.' AND
83
                    reflink="'.Database::escape_string($link).'" AND
84
                    '.$groupfilter.$condition_session.'';
85
        $result = Database::query($sql);
86
        $num = Database::num_rows($result);
87
        // the value has not been found and is this available
88
        if ($num == 0) {
89
            return true;
90
        }
91
92
        return false;
93
    }
94
95
    /**
96
     * check wikilinks that has a page.
97
     *
98
     * @author Juan Carlos Raña <[email protected]>
99
     *
100
     * @param string $input
101
     *
102
     * @return string
103
     */
104
    public function links_to($input)
105
    {
106
        $input_array = preg_split(
107
            "/(\[\[|\]\])/",
108
            $input,
109
            -1,
110
            PREG_SPLIT_DELIM_CAPTURE
111
        );
112
        $all_links = [];
113
114
        foreach ($input_array as $key => $value) {
115
            if (isset($input_array[$key - 1]) && $input_array[$key - 1] == '[[' &&
116
                isset($input_array[$key + 1]) && $input_array[$key + 1] == ']]'
117
            ) {
118
                if (api_strpos($value, "|") !== false) {
119
                    $full_link_array = explode("|", $value);
120
                    $link = trim($full_link_array[0]);
121
                    $title = trim($full_link_array[1]);
122
                } else {
123
                    $link = trim($value);
124
                    $title = trim($value);
125
                }
126
                unset($input_array[$key - 1]);
127
                unset($input_array[$key + 1]);
128
                //replace blank spaces by _ within the links. But to remove links at the end add a blank space
129
                $all_links[] = Database::escape_string(
130
                    str_replace(' ', '_', $link)
131
                ).' ';
132
            }
133
        }
134
135
        return implode($all_links);
136
    }
137
138
    /**
139
     * detect and add style to external links.
140
     *
141
     * @author Juan Carlos Raña Trabado
142
     */
143
    public function detect_external_link($input)
144
    {
145
        $exlink = 'href=';
146
        $exlinkStyle = 'class="wiki_link_ext" href=';
147
148
        return str_replace($exlink, $exlinkStyle, $input);
149
    }
150
151
    /**
152
     * detect and add style to anchor links.
153
     *
154
     * @author Juan Carlos Raña Trabado
155
     */
156
    public function detect_anchor_link($input)
157
    {
158
        $anchorlink = 'href="#';
159
        $anchorlinkStyle = 'class="wiki_anchor_link" href="#';
160
        $output = str_replace($anchorlink, $anchorlinkStyle, $input);
161
162
        return $output;
163
    }
164
165
    /**
166
     * detect and add style to mail links
167
     * author Juan Carlos Raña Trabado.
168
     */
169
    public function detect_mail_link($input)
170
    {
171
        $maillink = 'href="mailto';
172
        $maillinkStyle = 'class="wiki_mail_link" href="mailto';
173
        $output = str_replace($maillink, $maillinkStyle, $input);
174
175
        return $output;
176
    }
177
178
    /**
179
     * detect and add style to ftp links.
180
     *
181
     * @author Juan Carlos Raña Trabado
182
     */
183
    public function detect_ftp_link($input)
184
    {
185
        $ftplink = 'href="ftp';
186
        $ftplinkStyle = 'class="wiki_ftp_link" href="ftp';
187
        $output = str_replace($ftplink, $ftplinkStyle, $input);
188
189
        return $output;
190
    }
191
192
    /**
193
     * detect and add style to news links.
194
     *
195
     * @author Juan Carlos Raña Trabado
196
     */
197
    public function detect_news_link($input)
198
    {
199
        $newslink = 'href="news';
200
        $newslinkStyle = 'class="wiki_news_link" href="news';
201
        $output = str_replace($newslink, $newslinkStyle, $input);
202
203
        return $output;
204
    }
205
206
    /**
207
     * detect and add style to irc links.
208
     *
209
     * @author Juan Carlos Raña Trabado
210
     */
211
    public function detect_irc_link($input)
212
    {
213
        $irclink = 'href="irc';
214
        $irclinkStyle = 'class="wiki_irc_link" href="irc';
215
        $output = str_replace($irclink, $irclinkStyle, $input);
216
217
        return $output;
218
    }
219
220
    /**
221
     * This function allows users to have [link to a title]-style links like in most regular wikis.
222
     * It is true that the adding of links is probably the most anoying part of Wiki for the people
223
     * who know something about the wiki syntax.
224
     *
225
     * @author Patrick Cool <[email protected]>, Ghent University
226
     * Improvements [[]] and [[ | ]]by Juan Carlos Raña
227
     * Improvements internal wiki style and mark group by Juan Carlos Raña
228
     */
229
    public function make_wiki_link_clickable($input)
230
    {
231
        $groupId = api_get_group_id();
232
        //now doubles brackets
233
        $input_array = preg_split(
234
            "/(\[\[|\]\])/",
235
            $input,
236
            -1,
237
            PREG_SPLIT_DELIM_CAPTURE
238
        );
239
240
        foreach ($input_array as $key => $value) {
241
            //now doubles brackets
242
            if (isset($input_array[$key - 1]) &&
243
                $input_array[$key - 1] == '[[' && $input_array[$key + 1] == ']]'
244
            ) {
245
                // now full wikilink
246
                if (api_strpos($value, "|") !== false) {
247
                    $full_link_array = explode("|", $value);
248
                    $link = trim(strip_tags($full_link_array[0]));
249
                    $title = trim($full_link_array[1]);
250
                } else {
251
                    $link = trim(strip_tags($value));
252
                    $title = trim($value);
253
                }
254
255
                //if wikilink is homepage
256
                if ($link == 'index') {
257
                    $title = get_lang('DefaultTitle');
258
                }
259
                if ($link == get_lang('DefaultTitle')) {
260
                    $link = 'index';
261
                }
262
263
                // note: checkreflink checks if the link is still free. If it is not used then it returns true, if it is used, then it returns false. Now the title may be different
264
                if (self::checktitle(
265
                    strtolower(str_replace(' ', '_', $link))
266
                )) {
267
                    $link = api_html_entity_decode($link);
268
                    $input_array[$key] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?'.api_get_cidreq().'&action=addnew&title='.Security::remove_XSS($link).'&group_id='.$groupId.'" class="new_wiki_link">'.$title.'</a>';
269
                } else {
270
                    $input_array[$key] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?'.api_get_cidreq().'&action=showpage&title='.urlencode(strtolower(str_replace(' ', '_', $link))).'&group_id='.$groupId.'" class="wiki_link">'.$title.'</a>';
271
                }
272
                unset($input_array[$key - 1]);
273
                unset($input_array[$key + 1]);
274
            }
275
        }
276
        $output = implode('', $input_array);
277
278
        return $output;
279
    }
280
281
    /**
282
     * This function saves a change in a wiki page.
283
     *
284
     * @author Patrick Cool <[email protected]>, Ghent University
285
     *
286
     * @param array $values
287
     *
288
     * @return string
289
     */
290
    public function save_wiki($values)
291
    {
292
        $tbl_wiki = $this->tbl_wiki;
293
        $tbl_wiki_conf = $this->tbl_wiki_conf;
294
295
        $_course = $this->courseInfo;
296
        $time = api_get_utc_datetime(null, false, true);
297
        $session_id = api_get_session_id();
298
        $groupId = api_get_group_id();
299
        $userId = api_get_user_id();
300
        $groupInfo = GroupManager::get_group_properties($groupId);
301
        $course_id = api_get_course_int_id();
302
303
        $_clean = [
304
            'task' => '',
305
            'feedback1' => '',
306
            'feedback2' => '',
307
            'feedback3' => '',
308
            'fprogress1' => '',
309
            'fprogress2' => '',
310
            'fprogress3' => '',
311
            'max_text' => 0,
312
            'max_version' => 0,
313
            'delayedsubmit' => '',
314
            'assignment' => 0,
315
        ];
316
317
        $pageId = intval($values['page_id']);
318
319
        // NOTE: visibility, visibility_disc and ratinglock_disc changes
320
        // are not made here, but through the interce buttons
321
322
        // cleaning the variables
323
        if (api_get_setting('htmlpurifier_wiki') == 'true') {
324
            //$purifier = new HTMLPurifier();
325
            $values['content'] = Security::remove_XSS($values['content']);
326
        }
327
        $version = intval($values['version']) + 1;
328
        $linkTo = self::links_to($values['content']); //and check links content
329
330
        //cleaning config variables
331
        if (!empty($values['task'])) {
332
            $_clean['task'] = $values['task'];
333
        }
334
335
        if (!empty($values['feedback1']) ||
336
            !empty($values['feedback2']) ||
337
            !empty($values['feedback3'])
338
        ) {
339
            $_clean['feedback1'] = $values['feedback1'];
340
            $_clean['feedback2'] = $values['feedback2'];
341
            $_clean['feedback3'] = $values['feedback3'];
342
            $_clean['fprogress1'] = $values['fprogress1'];
343
            $_clean['fprogress2'] = $values['fprogress2'];
344
            $_clean['fprogress3'] = $values['fprogress3'];
345
        }
346
347
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
348
            $_clean['startdate_assig'] = $values['startdate_assig'];
349
        } else {
350
            $_clean['startdate_assig'] = null;
351
        }
352
353
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
354
            $_clean['enddate_assig'] = $values['enddate_assig'];
355
        } else {
356
            $_clean['enddate_assig'] = null;
357
        }
358
359
        if (isset($values['delayedsubmit'])) {
360
            $_clean['delayedsubmit'] = $values['delayedsubmit'];
361
        }
362
363
        if (!empty($values['max_text']) || !empty($values['max_version'])) {
364
            $_clean['max_text'] = $values['max_text'];
365
            $_clean['max_version'] = $values['max_version'];
366
        }
367
368
        $values['assignment'] = $values['assignment'] ?? 0;
369
        $values['page_id'] = $values['page_id'] ?? 0;
370
371
        $em = Database::getManager();
372
373
        $newWiki = (new CWiki())
374
            ->setCId($course_id)
375
            ->setAddlock(1)
376
            ->setVisibility(1)
377
            ->setVisibilityDisc(1)
378
            ->setAddlockDisc(1)
379
            ->setRatinglockDisc(1)
380
            ->setPageId($pageId)
381
            ->setReflink(trim($values['reflink']))
382
            ->setTitle(trim($values['title']))
383
            ->setContent($values['content'])
384
            ->setUserId($userId)
385
            ->setGroupId($groupId)
386
            ->setDtime($time)
387
            ->setAssignment($values['assignment'])
388
            ->setComment($values['comment'])
389
            ->setProgress($values['progress'])
390
            ->setVersion($version)
391
            ->setLinksto($linkTo)
392
            ->setUserIp($_SERVER['REMOTE_ADDR'])
393
            ->setSessionId($session_id)
394
            ->setPageId($values['page_id'])
395
            ->setEditlock(0)
396
            ->setIsEditing(0)
397
            ->setTimeEdit($time)
398
            ->setTag('')
399
        ;
400
401
        $em->persist($newWiki);
402
        $em->flush();
403
404
        $id = $newWiki->getIid();
405
406
        if ($id > 0) {
407
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
408
            Database::query($sql);
409
410
            // insert into item_property
411
            api_item_property_update(
412
                $_course,
413
                TOOL_WIKI,
414
                $id,
415
                'WikiAdded',
416
                $userId,
417
                $groupInfo
418
            );
419
420
            if ($values['page_id'] == 0) {
421
                $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
422
                        WHERE c_id = '.$course_id.' AND iid ="'.$id.'"';
423
                Database::query($sql);
424
            }
425
426
            self::assignCategoriesToWiki($newWiki, $values['category']);
427
        }
428
429
        // Update wiki config
430
        if ($values['reflink'] == 'index' && $version == 1) {
431
            $params = [
432
                'c_id' => $course_id,
433
                'page_id' => $id,
434
                'task' => $_clean['task'],
435
                'feedback1' => $_clean['feedback1'],
436
                'feedback2' => $_clean['feedback2'],
437
                'feedback3' => $_clean['feedback3'],
438
                'fprogress1' => $_clean['fprogress1'],
439
                'fprogress2' => $_clean['fprogress2'],
440
                'fprogress3' => $_clean['fprogress3'],
441
                'max_text' => intval($_clean['max_text']),
442
                'max_version' => intval($_clean['max_version']),
443
                'startdate_assig' => $_clean['startdate_assig'],
444
                'enddate_assig' => $_clean['enddate_assig'],
445
                'delayedsubmit' => $_clean['delayedsubmit'],
446
            ];
447
            Database::insert($tbl_wiki_conf, $params);
448
        } else {
449
            $params = [
450
                'task' => $_clean['task'],
451
                'feedback1' => $_clean['feedback1'],
452
                'feedback2' => $_clean['feedback2'],
453
                'feedback3' => $_clean['feedback3'],
454
                'fprogress1' => $_clean['fprogress1'],
455
                'fprogress2' => $_clean['fprogress2'],
456
                'fprogress3' => $_clean['fprogress3'],
457
                'max_text' => intval($_clean['max_text']),
458
                'max_version' => intval($_clean['max_version']),
459
                'startdate_assig' => $_clean['startdate_assig'],
460
                'enddate_assig' => $_clean['enddate_assig'],
461
                'delayedsubmit' => $_clean['delayedsubmit'],
462
            ];
463
            Database::update(
464
                $tbl_wiki_conf,
465
                $params,
466
                ['page_id = ? AND c_id = ?' => [$pageId, $course_id]]
467
            );
468
        }
469
470
        api_item_property_update(
471
            $_course,
472
            'wiki',
473
            $id,
474
            'WikiAdded',
475
            $userId,
476
            $groupInfo
477
        );
478
        self::check_emailcue($_clean['reflink'], 'P', $time, $userId);
479
        $this->setWikiData($id);
480
481
        return get_lang('Saved');
482
    }
483
484
    /**
485
     * This function restore a wikipage.
486
     *
487
     * @author Juan Carlos Raña <[email protected]>
488
     *
489
     * @return string Message of success (to be printed on screen)
490
     */
491
    public function restore_wikipage(
492
        $r_page_id,
493
        $r_reflink,
494
        $r_title,
495
        $r_content,
496
        $r_group_id,
497
        $r_assignment,
498
        $r_progress,
499
        $c_version,
500
        $r_version,
501
        $r_linksto
502
    ) {
503
        $tbl_wiki = $this->tbl_wiki;
504
        $_course = $this->courseInfo;
505
        $r_user_id = api_get_user_id();
506
        $r_dtime = api_get_utc_datetime();
507
        $r_version = $r_version + 1;
508
        $r_comment = get_lang('RestoredFromVersion').': '.$c_version;
509
        $session_id = api_get_session_id();
510
        $course_id = api_get_course_int_id();
511
        $groupInfo = GroupManager::get_group_properties($r_group_id);
512
513
        $params = [
514
            'c_id' => $course_id,
515
            'page_id' => $r_page_id,
516
            'reflink' => $r_reflink,
517
            'title' => $r_title,
518
            'content' => $r_content,
519
            'user_id' => $r_user_id,
520
            'group_id' => $r_group_id,
521
            'dtime' => $r_dtime,
522
            'assignment' => $r_assignment,
523
            'comment' => $r_comment,
524
            'progress' => $r_progress,
525
            'version' => $r_version,
526
            'linksto' => $r_linksto,
527
            'user_ip' => $_SERVER['REMOTE_ADDR'],
528
            'session_id' => $session_id,
529
        ];
530
        $id = Database::insert($tbl_wiki, $params);
531
532
        if ($id) {
533
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
534
            Database::query($sql);
535
536
            api_item_property_update(
537
                $_course,
538
                'wiki',
539
                $id,
540
                'WikiAdded',
541
                api_get_user_id(),
542
                $groupInfo
543
            );
544
            self::check_emailcue($r_reflink, 'P', $r_dtime, $r_user_id);
545
        }
546
547
        return get_lang('PageRestored');
548
    }
549
550
    /**
551
     * This function delete a wiki.
552
     *
553
     * @author Juan Carlos Raña <[email protected]>
554
     *
555
     * @return string Message of success (to be printed)
556
     */
557
    public function delete_wiki()
558
    {
559
        $tbl_wiki = $this->tbl_wiki;
560
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
561
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
562
        $tbl_wiki_conf = $this->tbl_wiki_conf;
563
        $conditionSession = $this->condition_session;
564
        $groupFilter = $this->groupfilter;
565
        $course_id = $this->course_id;
566
567
        $sql = "SELECT page_id FROM $tbl_wiki
568
                WHERE c_id = $course_id AND $groupFilter $conditionSession
569
                ORDER BY id DESC";
570
571
        $result = Database::query($sql);
572
        $pageList = Database::store_result($result);
573
        if ($pageList) {
574
            foreach ($pageList as $pageData) {
575
                $pageId = $pageData['page_id'];
576
                $sql = "DELETE FROM $tbl_wiki_conf
577
                        WHERE c_id = $course_id AND page_id = $pageId";
578
                Database::query($sql);
579
580
                $sql = "DELETE FROM $tbl_wiki_discuss
581
                        WHERE c_id = $course_id AND publication_id = $pageId";
582
                Database::query($sql);
583
            }
584
        }
585
586
        $sql = "DELETE FROM $tbl_wiki_mailcue
587
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
588
        Database::query($sql);
589
590
        $sql = "DELETE FROM $tbl_wiki
591
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
592
        Database::query($sql);
593
594
        return get_lang('WikiDeleted');
595
    }
596
597
    /**
598
     * This function saves a new wiki page.
599
     *
600
     * @author Patrick Cool <[email protected]>, Ghent University
601
     *
602
     * @todo consider merging this with the function save_wiki into one single function.
603
     */
604
    public function save_new_wiki($values)
605
    {
606
        $tbl_wiki = $this->tbl_wiki;
607
        $tbl_wiki_conf = $this->tbl_wiki_conf;
608
        $assig_user_id = $this->assig_user_id;
609
        $_clean = [];
610
611
        // cleaning the variables
612
        $_clean['assignment'] = '';
613
        if (isset($values['assignment'])) {
614
            $_clean['assignment'] = $values['assignment'];
615
        }
616
617
        // session_id
618
        $session_id = api_get_session_id();
619
        // Unlike ordinary pages of pages of assignments.
620
        // Allow create a ordinary page although there is a assignment with the same name
621
        if ($_clean['assignment'] == 2 || $_clean['assignment'] == 1) {
622
            $page = str_replace(
623
                ' ',
624
                '_',
625
                $values['title']."_uass".$assig_user_id
626
            );
627
        } else {
628
            $page = str_replace(' ', '_', $values['title']);
629
        }
630
        $_clean['reflink'] = $page;
631
        $_clean['title'] = trim($values['title']);
632
        $_clean['content'] = $values['content'];
633
634
        if (api_get_setting('htmlpurifier_wiki') === 'true') {
635
            $purifier = new HTMLPurifier();
636
            $_clean['content'] = $purifier->purify($_clean['content']);
637
        }
638
639
        //re-check after strip_tags if the title is empty
640
        if (empty($_clean['title']) || empty($_clean['reflink'])) {
641
            return false;
642
        }
643
644
        if ($_clean['assignment'] == 2) {
645
            //config by default for individual assignment (students)
646
            //Identifies the user as a creator, not the teacher who created
647
            $_clean['user_id'] = intval($assig_user_id);
648
            $_clean['visibility'] = 0;
649
            $_clean['visibility_disc'] = 0;
650
            $_clean['ratinglock_disc'] = 0;
651
        } else {
652
            $_clean['user_id'] = api_get_user_id();
653
            $_clean['visibility'] = 1;
654
            $_clean['visibility_disc'] = 1;
655
            $_clean['ratinglock_disc'] = 1;
656
        }
657
658
        $_clean['comment'] = $values['comment'];
659
        $_clean['progress'] = $values['progress'];
660
        $_clean['version'] = 1;
661
662
        $groupId = api_get_group_id();
663
        $groupInfo = GroupManager::get_group_properties($groupId);
664
665
        //check wikilinks
666
        $_clean['linksto'] = self::links_to($_clean['content']);
667
668
        // cleaning config variables
669
        $_clean['task'] = $values['task'] ?? '';
670
        $_clean['feedback1'] = $values['feedback1'] ?? '';
671
        $_clean['feedback2'] = $values['feedback2'] ?? '';
672
        $_clean['feedback3'] = $values['feedback3'] ?? '';
673
        $_clean['fprogress1'] = $values['fprogress1'] ?? '';
674
        $_clean['fprogress2'] = $values['fprogress2'] ?? '';
675
        $_clean['fprogress3'] = $values['fprogress3'] ?? '';
676
677
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
678
            $_clean['startdate_assig'] = $values['startdate_assig'];
679
        } else {
680
            $_clean['startdate_assig'] = null;
681
        }
682
683
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
684
            $_clean['enddate_assig'] = $values['enddate_assig'];
685
        } else {
686
            $_clean['enddate_assig'] = null;
687
        }
688
689
        $_clean['delayedsubmit'] = $values['delayedsubmit'] ?? '';
690
        $_clean['max_text'] = $values['max_text'] ?? '';
691
        $_clean['max_version'] = $values['max_version'] ?? '';
692
693
        $course_id = api_get_course_int_id();
694
695
        // Filter no _uass
696
        if (api_strtoupper(trim($values['title'])) === 'INDEX') {
697
            Display::addFlash(
698
                Display::return_message(
699
                    get_lang('GoAndEditMainPage'),
700
                    'warning',
701
                    false
702
                )
703
            );
704
        } else {
705
            $var = $_clean['reflink'];
706
            $group_id = intval($_GET['group_id']);
707
            if (!self::checktitle($var)) {
708
                return get_lang('WikiPageTitleExist').
709
                    '<a href="index.php?action=edit&title='.$var.'&group_id='.$group_id.'">'.
710
                    $values['title'].'</a>';
711
            } else {
712
                $em = Database::getManager();
713
                $dtime = api_get_utc_datetime(null, false, true);
714
715
                $newWiki = (new CWiki())
716
                    ->setCId($course_id)
717
                    ->setReflink($_clean['reflink'])
718
                    ->setTitle($_clean['title'])
719
                    ->setContent($_clean['content'])
720
                    ->setUserId($_clean['user_id'])
721
                    ->setGroupId($groupId)
722
                    ->setDtime($dtime)
723
                    ->setVisibility($_clean['visibility'])
724
                    ->setVisibilityDisc($_clean['visibility_disc'])
725
                    ->setRatinglockDisc($_clean['ratinglock_disc'])
726
                    ->setAssignment($_clean['assignment'])
727
                    ->setComment($_clean['comment'])
728
                    ->setProgress($_clean['progress'])
729
                    ->setVersion($_clean['version'])
730
                    ->setLinksto($_clean['linksto'])
731
                    ->setUserIp($_SERVER['REMOTE_ADDR'])
732
                    ->setSessionId($session_id)
733
                    ->setAddlock(0)
734
                    ->setAddlockDisc(1)
735
                    ->setEditlock(0)
736
                    ->setIsEditing(0)
737
                    ->setTag('')
738
                ;
739
740
                $em->persist($newWiki);
741
                $em->flush();
742
743
                $id = $newWiki->getIid();
744
745
                if ($id > 0) {
746
                    $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
747
                    Database::query($sql);
748
749
                    //insert into item_property
750
                    api_item_property_update(
751
                        api_get_course_info(),
752
                        TOOL_WIKI,
753
                        $id,
754
                        'WikiAdded',
755
                        api_get_user_id(),
756
                        $groupInfo
757
                    );
758
759
                    $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
760
                            WHERE c_id = '.$course_id.' AND id = "'.$id.'"';
761
                    Database::query($sql);
762
763
                    // insert wiki config
764
                    $params = [
765
                        'c_id' => $course_id,
766
                        'page_id' => $id,
767
                        'task' => $_clean['task'],
768
                        'feedback1' => $_clean['feedback1'],
769
                        'feedback2' => $_clean['feedback2'],
770
                        'feedback3' => $_clean['feedback3'],
771
                        'fprogress1' => $_clean['fprogress1'],
772
                        'fprogress2' => $_clean['fprogress2'],
773
                        'fprogress3' => $_clean['fprogress3'],
774
                        'max_text' => $_clean['max_text'],
775
                        'max_version' => $_clean['max_version'],
776
                        'startdate_assig' => $_clean['startdate_assig'],
777
                        'enddate_assig' => $_clean['enddate_assig'],
778
                        'delayedsubmit' => $_clean['delayedsubmit'],
779
                    ];
780
781
                    Database::insert($tbl_wiki_conf, $params);
782
783
                    self::assignCategoriesToWiki($newWiki, $values['category']);
784
785
                    $this->setWikiData($id);
786
                    self::check_emailcue(0, 'A');
787
788
                    return get_lang('NewWikiSaved');
789
                }
790
            }
791
        }
792
    }
793
794
    public function setForm(FormValidator $form, array $row = [])
795
    {
796
        $toolBar = api_is_allowed_to_edit(null, true)
797
            ? [
798
                'ToolbarSet' => 'Wiki',
799
                'Width' => '100%',
800
                'Height' => '400',
801
            ]
802
            : [
803
                'ToolbarSet' => 'WikiStudent',
804
                'Width' => '100%',
805
                'Height' => '400',
806
                'UserStatus' => 'student',
807
            ];
808
809
        $form->addHtmlEditor(
810
            'content',
811
            get_lang('Content'),
812
            false,
813
            false,
814
            $toolBar
815
        );
816
        //$content
817
        $form->addElement('text', 'comment', get_lang('Comments'));
818
        $progress = ['', 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
819
820
        $form->addElement(
821
            'select',
822
            'progress',
823
            get_lang('Progress'),
824
            $progress
825
        );
826
827
        if (true === api_get_configuration_value('wiki_categories_enabled')) {
828
            $em = Database::getManager();
829
830
            $categories = $em->getRepository(CWikiCategory::class)
831
                ->findByCourse(
832
                    api_get_course_entity(),
833
                    api_get_session_entity()
834
                );
835
836
            $form->addSelectFromCollection(
837
                'category',
838
                get_lang('Categories'),
839
                $categories,
840
                ['multiple' => 'multiple'],
841
                false,
842
                'getNodeName'
843
            );
844
        }
845
846
        if ((api_is_allowed_to_edit(false, true) ||
847
            api_is_platform_admin()) &&
848
            isset($row['reflink']) && $row['reflink'] != 'index'
849
        ) {
850
            $form->addElement(
851
                'advanced_settings',
852
                'advanced_params',
853
                get_lang('AdvancedParameters')
854
            );
855
            $form->addElement(
856
                'html',
857
                '<div id="advanced_params_options" style="display:none">'
858
            );
859
860
            $form->addHtmlEditor(
861
                'task',
862
                get_lang('DescriptionOfTheTask'),
863
                false,
864
                false,
865
                [
866
                    'ToolbarSet' => 'wiki_task',
867
                    'Width' => '100%',
868
                    'Height' => '200',
869
                ]
870
            );
871
872
            $form->addElement('label', null, get_lang('AddFeedback'));
873
            $form->addElement('textarea', 'feedback1', get_lang('Feedback1'));
874
            $form->addElement(
875
                'select',
876
                'fprogress1',
877
                get_lang('FProgress'),
878
                $progress
879
            );
880
881
            $form->addElement('textarea', 'feedback2', get_lang('Feedback2'));
882
            $form->addElement(
883
                'select',
884
                'fprogress2',
885
                get_lang('FProgress'),
886
                $progress
887
            );
888
889
            $form->addElement('textarea', 'feedback3', get_lang('Feedback3'));
890
            $form->addElement(
891
                'select',
892
                'fprogress3',
893
                get_lang('FProgress'),
894
                $progress
895
            );
896
897
            $form->addElement(
898
                'checkbox',
899
                'initstartdate',
900
                null,
901
                get_lang('StartDate'),
902
                ['id' => 'start_date_toggle']
903
            );
904
905
            $style = "display:block";
906
            $row['initstartdate'] = 1;
907
            if (empty($row['startdate_assig'])) {
908
                $style = "display:none";
909
                $row['initstartdate'] = null;
910
            }
911
912
            $form->addElement(
913
                'html',
914
                '<div id="start_date" style="'.$style.'">'
915
            );
916
            $form->addDatePicker('startdate_assig', '');
917
            $form->addElement('html', '</div>');
918
            $form->addElement(
919
                'checkbox',
920
                'initenddate',
921
                null,
922
                get_lang('EndDate'),
923
                ['id' => 'end_date_toggle']
924
            );
925
926
            $style = "display:block";
927
            $row['initenddate'] = 1;
928
            if (empty($row['enddate_assig'])) {
929
                $style = "display:none";
930
                $row['initenddate'] = null;
931
            }
932
933
            $form->addHtml('<div id="end_date" style="'.$style.'">');
934
            $form->addDatePicker('enddate_assig', '');
935
            $form->addHtml('</div>');
936
            $form->addElement(
937
                'checkbox',
938
                'delayedsubmit',
939
                null,
940
                get_lang('AllowLaterSends')
941
            );
942
            $form->addElement('text', 'max_text', get_lang('NMaxWords'));
943
            $form->addElement('text', 'max_version', get_lang('NMaxVersion'));
944
            $form->addElement(
945
                'checkbox',
946
                'assignment',
947
                null,
948
                get_lang('CreateAssignmentPage')
949
            );
950
            $form->addElement('html', '</div>');
951
        }
952
953
        $form->addElement('hidden', 'page_id');
954
        $form->addElement('hidden', 'reflink');
955
        $form->addElement('hidden', 'version');
956
        $form->addElement('hidden', 'wpost_id', api_get_unique_id());
957
    }
958
959
    /**
960
     * This function displays the form for adding a new wiki page.
961
     *
962
     * @author Patrick Cool <[email protected]>, Ghent University
963
     *
964
     * @return string html code
965
     */
966
    public function display_new_wiki_form()
967
    {
968
        $url = api_get_self().'?'.api_get_cidreq(
969
            ).'&action=addnew&group_id='.api_get_group_id();
970
        $form = new FormValidator('wiki_new', 'post', $url);
971
        $form->addElement('text', 'title', get_lang('Title'));
972
        $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
973
        self::setForm($form);
974
        $title = isset($_GET['title']) ? Security::remove_XSS(
975
            $_GET['title']
976
        ) : '';
977
        $form->setDefaults(['title' => $title]);
978
        $form->addButtonSave(get_lang('Save'), 'SaveWikiNew');
979
        $form->display();
980
981
        if ($form->validate()) {
982
            $values = $form->exportValues();
983
            if (isset($values['startdate_assig']) &&
984
                isset($values['enddate_assig']) &&
985
                strtotime($values['startdate_assig']) > strtotime(
986
                    $values['enddate_assig']
987
                )
988
            ) {
989
                Display::addFlash(
990
                    Display::return_message(
991
                        get_lang("EndDateCannotBeBeforeTheStartDate"),
992
                        'error',
993
                        false
994
                    )
995
                );
996
            } elseif (!self::double_post($_POST['wpost_id'])) {
997
                //double post
998
            } else {
999
                if (isset($values['assignment']) && $values['assignment'] == 1) {
1000
                    self::auto_add_page_users($values);
1001
                }
1002
1003
                $return_message = $this->save_new_wiki($values);
1004
1005
                if ($return_message == false) {
1006
                    Display::addFlash(
1007
                        Display::return_message(
1008
                            get_lang('NoWikiPageTitle'),
1009
                            'error',
1010
                            false
1011
                        )
1012
                    );
1013
                } else {
1014
                    Display::addFlash(
1015
                        Display::return_message(
1016
                            $return_message,
1017
                            'confirmation',
1018
                            false
1019
                        )
1020
                    );
1021
                }
1022
1023
                $wikiData = self::getWikiData();
1024
                $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq();
1025
                header('Location: '.$redirectUrl);
1026
                exit;
1027
            }
1028
        }
1029
    }
1030
1031
    /**
1032
     * This function displays a wiki entry.
1033
     *
1034
     * @author Patrick Cool <[email protected]>, Ghent University
1035
     * @author Juan Carlos Raña Trabado
1036
     */
1037
    public function display_wiki_entry(string $newtitle)
1038
    {
1039
        $tblWiki = $this->tbl_wiki;
1040
        $tblWikiConf = $this->tbl_wiki_conf;
1041
        $conditionSession = $this->condition_session;
1042
        $groupfilter = $this->groupfilter;
1043
        $page = $this->page;
1044
1045
        $sessionId = api_get_session_id();
1046
        $courseId = api_get_course_int_id();
1047
1048
        if ($newtitle) {
1049
            $pageMIX = $newtitle; //display the page after it is created
1050
        } else {
1051
            $pageMIX = $page; //display current page
1052
        }
1053
1054
        $filter = null;
1055
        if (isset($_GET['view']) && $_GET['view']) {
1056
            $_clean['view'] = Database::escape_string($_GET['view']);
1057
            $filter = ' AND w.id="'.$_clean['view'].'"';
1058
        }
1059
1060
        // First, check page visibility in the first page version
1061
        $sql = 'SELECT * FROM '.$tblWiki.'
1062
                WHERE
1063
                    c_id = '.$courseId.' AND
1064
                    reflink = "'.Database::escape_string($pageMIX).'" AND
1065
                   '.$groupfilter.$conditionSession.'
1066
                ORDER BY id';
1067
        $result = Database::query($sql);
1068
        $row = Database::fetch_array($result, 'ASSOC');
1069
1070
        $KeyVisibility = null;
1071
        if ($KeyVisibility) {
1072
            $KeyVisibility = $row['visibility'];
1073
        }
1074
1075
        // second, show the last version
1076
        $sql = 'SELECT * FROM '.$tblWiki.' w
1077
            INNER JOIN '.$tblWikiConf.' wc
1078
            ON (wc.page_id = w.page_id AND wc.c_id = w.c_id)
1079
            WHERE
1080
                w.c_id = '.$courseId.' AND
1081
                w.reflink = "'.Database::escape_string($pageMIX).'" AND
1082
                w.session_id = '.$sessionId.' AND
1083
                w.'.$groupfilter.'  '.$filter.'
1084
            ORDER BY id DESC';
1085
1086
        $result = Database::query($sql);
1087
        // we do not need awhile loop since we are always displaying the last version
1088
        $row = Database::fetch_array($result, 'ASSOC');
1089
1090
        //log users access to wiki (page_id)
1091
        if (!empty($row['page_id'])) {
1092
            Event::addEvent(LOG_WIKI_ACCESS, LOG_WIKI_PAGE_ID, $row['page_id']);
1093
        }
1094
        //update visits
1095
        if ($row && $row['id']) {
1096
            $sql = 'UPDATE '.$tblWiki.' SET hits=(hits+1)
1097
                WHERE c_id = '.$courseId.' AND id='.$row['id'];
1098
            Database::query($sql);
1099
        }
1100
1101
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1102
1103
        // if both are empty, and we are displaying the index page then we display the default text.
1104
        if (!$row || ($row['content'] == '' && $row['title'] == '' && $page == 'index')) {
1105
            if (api_is_allowed_to_edit(false, true) ||
1106
                api_is_platform_admin() ||
1107
                GroupManager::is_user_in_group(api_get_user_id(), $groupInfo) ||
1108
                api_is_allowed_in_course()
1109
            ) {
1110
                //Table structure for better export to pdf
1111
                $default_table_for_content_Start = '<div class="text-center">';
1112
                $default_table_for_content_End = '</div>';
1113
                $content = $default_table_for_content_Start.
1114
                    sprintf(
1115
                        get_lang('DefaultContent'),
1116
                        api_get_path(WEB_IMG_PATH)
1117
                    ).
1118
                    $default_table_for_content_End;
1119
                $title = get_lang('DefaultTitle');
1120
            } else {
1121
                Display::addFlash(
1122
                    Display::return_message(
1123
                        get_lang('WikiStandBy'),
1124
                        'normal',
1125
                        false
1126
                    )
1127
                );
1128
1129
                return;
1130
            }
1131
        } else {
1132
            if (true === api_get_configuration_value('wiki_html_strict_filtering')) {
1133
                $content = Security::remove_XSS($row['content'], COURSEMANAGERLOWSECURITY);
1134
            } else {
1135
                $content = Security::remove_XSS($row['content']);
1136
            }
1137
            $title = Security::remove_XSS($row['title']);
1138
        }
1139
1140
        if (self::wiki_exist($title)) {
1141
            //assignment mode: identify page type
1142
            $icon_assignment = null;
1143
            if ($row['assignment'] == 1) {
1144
                $icon_assignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'));
1145
            } elseif ($row['assignment'] == 2) {
1146
                $icon_assignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'));
1147
            }
1148
1149
            // task mode
1150
            $icon_task = null;
1151
            if (!empty($row['task'])) {
1152
                $icon_task = Display::return_icon('wiki_task.png', get_lang('StandardTask'));
1153
            }
1154
1155
            $pageTitle = $icon_assignment.PHP_EOL.$icon_task.'&nbsp;'.api_htmlentities($title);
1156
        } else {
1157
            $pageTitle = api_htmlentities($title);
1158
        }
1159
1160
        // Show page. Show page to all users if isn't hide page. Mode assignments: if student is the author, can view
1161
        if ($KeyVisibility != "1"
1162
            && !api_is_allowed_to_edit(false, true)
1163
            && !api_is_platform_admin()
1164
            && ($row['assignment'] != 2 || $KeyVisibility != "0" || api_get_user_id() != $row['user_id'])
1165
            && !api_is_allowed_in_course()
1166
        ) {
1167
            return;
1168
        }
1169
1170
        $actionsLeft = '';
1171
        $actionsRight = '';
1172
        // menu edit page
1173
        $editLink = '<a href="index.php?'.api_get_cidreq().'&action=edit&title='.api_htmlentities(urlencode($page)).'"'
1174
            .self::is_active_navigation_tab('edit').'>'
1175
            .Display::return_icon('edit.png', get_lang('EditThisPage'), [], ICON_SIZE_MEDIUM).'</a>';
1176
1177
        if (api_is_allowed_to_edit(false, true)) {
1178
            $actionsLeft .= $editLink;
1179
        } else {
1180
            if ((api_is_allowed_in_course() ||
1181
                GroupManager::is_user_in_group(
1182
                    api_get_user_id(),
1183
                    $groupInfo
1184
                ))
1185
            ) {
1186
                $actionsLeft .= $editLink;
1187
            } else {
1188
                $actionsLeft .= '';
1189
            }
1190
        }
1191
1192
        $pageProgress = 0;
1193
        $pageScore = 0;
1194
1195
        if ($row && $row['id']) {
1196
            $pageProgress = $row['progress'] * 10;
1197
            $pageScore = $row['score'];
1198
1199
            $protect_page = null;
1200
            $lock_unlock_protect = null;
1201
            // page action: protecting (locking) the page
1202
            if (api_is_allowed_to_edit(false, true) ||
1203
                api_is_platform_admin()
1204
            ) {
1205
                if (self::check_protect_page() == 1) {
1206
                    $protect_page = Display::return_icon(
1207
                        'lock.png',
1208
                        get_lang('PageLockedExtra'),
1209
                        [],
1210
                        ICON_SIZE_MEDIUM
1211
                    );
1212
                    $lock_unlock_protect = 'unlock';
1213
                } else {
1214
                    $protect_page = Display::return_icon(
1215
                        'unlock.png',
1216
                        get_lang('PageUnlockedExtra'),
1217
                        [],
1218
                        ICON_SIZE_MEDIUM
1219
                    );
1220
                    $lock_unlock_protect = 'lock';
1221
                }
1222
            }
1223
1224
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_protect
1225
                .'&title='.api_htmlentities(urlencode($page)).'">'.
1226
            $protect_page.'</a>';
1227
1228
            $visibility_page = null;
1229
            $lock_unlock_visibility = null;
1230
            //page action: visibility
1231
            if (api_is_allowed_to_edit(false, true) ||
1232
                api_is_platform_admin()
1233
            ) {
1234
                if (self::check_visibility_page() == 1) {
1235
                    $visibility_page = Display::return_icon(
1236
                        'visible.png',
1237
                        get_lang('ShowPageExtra'),
1238
                        [],
1239
                        ICON_SIZE_MEDIUM
1240
                    );
1241
                    $lock_unlock_visibility = 'invisible';
1242
                } else {
1243
                    $visibility_page = Display::return_icon(
1244
                        'invisible.png',
1245
                        get_lang('HidePageExtra'),
1246
                        [],
1247
                        ICON_SIZE_MEDIUM
1248
                    );
1249
                    $lock_unlock_visibility = 'visible';
1250
                }
1251
            }
1252
1253
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='
1254
                .$lock_unlock_visibility.'&title='.api_htmlentities(urlencode($page)).'">'.$visibility_page.'</a>';
1255
1256
            // Only available if row['id'] is set
1257
            //page action: notification
1258
            $lock_unlock_notify_page = '';
1259
1260
            if (api_is_allowed_to_session_edit()) {
1261
                if (self::check_notify_page($page) == 1) {
1262
                    $notify_page = Display::return_icon(
1263
                        'messagebox_info.png',
1264
                        get_lang('NotifyByEmail'),
1265
                        [],
1266
                        ICON_SIZE_MEDIUM
1267
                    );
1268
                    $lock_unlock_notify_page = 'unlocknotify';
1269
                } else {
1270
                    $notify_page = Display::return_icon(
1271
                        'mail.png',
1272
                        get_lang('CancelNotifyByEmail'),
1273
                        [],
1274
                        ICON_SIZE_MEDIUM
1275
                    );
1276
                    $lock_unlock_notify_page = 'locknotify';
1277
                }
1278
            }
1279
1280
            if (api_is_allowed_to_session_edit(false, true)
1281
                && api_is_allowed_to_edit()
1282
                || GroupManager::is_user_in_group(api_get_user_id(), $groupInfo)
1283
            ) {
1284
                // menu discuss page
1285
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=discuss&title='
1286
                    .api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('discuss').'>'
1287
                    .Display::return_icon(
1288
                        'discuss.png',
1289
                        get_lang('DiscussThisPage'),
1290
                        [],
1291
                        ICON_SIZE_MEDIUM
1292
                    ).'</a>';
1293
            }
1294
1295
            //menu history
1296
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=history&title='
1297
                .api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('history').'>'.
1298
                Display::return_icon(
1299
                    'history.png',
1300
                    get_lang('ShowPageHistory'),
1301
                    [],
1302
                    ICON_SIZE_MEDIUM
1303
                ).'</a>';
1304
            //menu linkspages
1305
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'action=links&title='
1306
                .api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('links').'>'
1307
                .Display::return_icon(
1308
                    'what_link_here.png',
1309
                    get_lang('LinksPages'),
1310
                    [],
1311
                    ICON_SIZE_MEDIUM
1312
                ).'</a>';
1313
1314
            //menu delete wikipage
1315
            if (api_is_allowed_to_edit(false, true) ||
1316
                api_is_platform_admin()
1317
            ) {
1318
                $actionsRight .= '<a href="index.php?action=delete&'.api_get_cidreq().'&title='
1319
                    .api_htmlentities(urlencode($page)).'"'.self::is_active_navigation_tab('delete').'>'
1320
                    .Display::return_icon(
1321
                        'delete.png',
1322
                        get_lang('DeleteThisPage'),
1323
                        [],
1324
                        ICON_SIZE_MEDIUM
1325
                    ).'</a>';
1326
            }
1327
1328
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='
1329
                .$lock_unlock_notify_page.'&title='.api_htmlentities(urlencode($page)).'">'.$notify_page.'</a>';
1330
1331
            // Page action: copy last version to doc area
1332
            if (api_is_allowed_to_edit(false, true) ||
1333
                api_is_platform_admin()
1334
            ) {
1335
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export2doc&wiki_id='.$row['id'].'">'
1336
                    .Display::return_icon(
1337
                        'export_to_documents.png',
1338
                        get_lang('ExportToDocArea'),
1339
                        [],
1340
                        ICON_SIZE_MEDIUM
1341
                    ).'</a>';
1342
            }
1343
1344
            $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export_to_pdf&wiki_id='.$row['id'].'">'
1345
                .Display::return_icon(
1346
                    'pdf.png',
1347
                    get_lang('ExportToPDF'),
1348
                    [],
1349
                    ICON_SIZE_MEDIUM
1350
                ).'</a>';
1351
1352
            $unoconv = api_get_configuration_value('unoconv.binaries');
1353
            if ($unoconv) {
1354
                $actionsRight .= '<a href="'.api_get_path(WEB_CODE_PATH).'wiki/index.php?action=export_to_doc_file&id='
1355
                    .$row['id'].'&'.api_get_cidreq().'">'
1356
                    .Display::return_icon(
1357
                        'export_doc.png',
1358
                        get_lang('ExportToDoc'),
1359
                        [],
1360
                        ICON_SIZE_MEDIUM
1361
                    ).'</a>';
1362
            }
1363
1364
            //export to print?>
1365
            <script>
1366
                function goprint() {
1367
                    var a = window.open('', '', 'width=800,height=600');
1368
                    a.document.open("text/html");
1369
                    a.document.write($('#wikicontent .panel-heading').html());
1370
                    a.document.write($('#wikicontent .panel-body').html());
1371
                    a.document.close();
1372
                    a.print();
1373
                }
1374
            </script>
1375
            <?php
1376
            $actionsRight .= Display::url(
1377
                Display::return_icon(
1378
                    'printer.png',
1379
                    get_lang('Print'),
1380
                    [],
1381
                    ICON_SIZE_MEDIUM
1382
                ),
1383
                '#',
1384
                ['onclick' => "javascript: goprint();"]
1385
            );
1386
        }
1387
1388
        echo Display::toolbarAction(
1389
            'toolbar-wikistudent',
1390
            [$actionsLeft, $actionsRight]
1391
        );
1392
1393
        $pageWiki = self::detect_news_link($content);
1394
        $pageWiki = self::detect_irc_link($pageWiki);
1395
        $pageWiki = self::detect_ftp_link($pageWiki);
1396
        $pageWiki = self::detect_mail_link($pageWiki);
1397
        $pageWiki = self::detect_anchor_link($pageWiki);
1398
        $pageWiki = self::detect_external_link($pageWiki);
1399
        $pageWiki = self::make_wiki_link_clickable($pageWiki);
1400
1401
        $footerWiki = '<ul class="list-inline" style="margin-bottom: 0;">'
1402
            .'<li>'.get_lang('Progress').': '.$pageProgress.'%</li>'
1403
            .'<li>'.get_lang('Rating').': '.$pageScore.'</li>'
1404
            .'<li>'.get_lang('Words').': '.self::word_count($content).'</li>';
1405
1406
        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 = $this->courseInfo;
2755
        $course_id = api_get_course_int_id();
2756
        echo '<legend>'.get_lang('WikiSearchResults').': '.Security::remove_XSS(
2757
                $search_term
2758
            );
2759
        echo '</legend>';
2760
2761
        //only by professors when page is hidden
2762
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
2763
            if ($all_vers == '1') {
2764
                if ($search_content == '1') {
2765
                    $sql = "SELECT * FROM ".$tbl_wiki."
2766
                            WHERE
2767
                                c_id = $course_id AND
2768
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2769
                                content LIKE '%".Database::escape_string(
2770
                            $search_term
2771
                        )."%' AND ".$groupfilter.$condition_session;
2772
                } else {
2773
                    $sql = "SELECT * FROM ".$tbl_wiki."
2774
                            WHERE
2775
                                c_id = $course_id AND
2776
                                title LIKE '%".Database::escape_string(
2777
                            $search_term
2778
                        )."%' AND ".$groupfilter.$condition_session;
2779
                }
2780
            } else {
2781
                if ($search_content == '1') {
2782
                    // warning don't use group by reflink because don't return the last version
2783
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2784
                            WHERE
2785
                                s1.c_id = $course_id AND
2786
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2787
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2788
                                id=(
2789
                                    SELECT MAX(s2.id)
2790
                                    FROM ".$tbl_wiki." s2
2791
                                    WHERE
2792
                                        s2.c_id = $course_id AND
2793
                                        s1.reflink = s2.reflink AND
2794
                                        ".$groupfilter.$condition_session.")";
2795
                } else {
2796
                    // warning don't use group by reflink because don't return the last version
2797
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2798
                            WHERE
2799
                                s1.c_id = $course_id AND
2800
                                title LIKE '%".Database::escape_string(
2801
                            $search_term
2802
                        )."%' AND
2803
                                id = (
2804
                                    SELECT MAX(s2.id)
2805
                                    FROM ".$tbl_wiki." s2
2806
                                    WHERE
2807
                                        s2.c_id = $course_id AND
2808
                                        s1.reflink = s2.reflink AND
2809
                                        ".$groupfilter.$condition_session.")";
2810
                }
2811
            }
2812
        } else {
2813
            if ($all_vers == '1') {
2814
                if ($search_content == '1') {
2815
                    //search all pages and all versions
2816
                    $sql = "SELECT * FROM ".$tbl_wiki."
2817
                            WHERE
2818
                                c_id = $course_id AND
2819
                                visibility=1 AND
2820
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2821
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2822
                                ".$groupfilter.$condition_session;
2823
                } else {
2824
                    $sql = "SELECT * FROM ".$tbl_wiki."
2825
                            WHERE
2826
                                c_id = $course_id AND
2827
                                visibility=1 AND
2828
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2829
                                ".$groupfilter.$condition_session;
2830
                }
2831
            } else {
2832
                if ($search_content == '1') {
2833
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2834
                            WHERE
2835
                                s1.c_id = $course_id AND
2836
                                visibility=1 AND
2837
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2838
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2839
                                id=(
2840
                                    SELECT MAX(s2.id)
2841
                                    FROM ".$tbl_wiki." s2
2842
                                    WHERE s2.c_id = $course_id AND
2843
                                    s1.reflink = s2.reflink AND
2844
                                    ".$groupfilter.$condition_session.")";
2845
                } else {
2846
                    // warning don't use group by reflink because don't return the last version
2847
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2848
                            WHERE
2849
                                s1.c_id = $course_id AND
2850
                                visibility=1 AND
2851
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2852
                            id = (
2853
                                SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
2854
                                WHERE s2.c_id = $course_id AND
2855
                                s1.reflink = s2.reflink AND
2856
                                ".$groupfilter.$condition_session.")";
2857
                }
2858
            }
2859
        }
2860
2861
        $result = Database::query($sql);
2862
2863
        //show table
2864
        $rows = [];
2865
        if (Database::num_rows($result) > 0) {
2866
            while ($obj = Database::fetch_object($result)) {
2867
                //get author
2868
                $userinfo = api_get_user_info($obj->user_id);
2869
                //get time
2870
                $year = substr($obj->dtime, 0, 4);
2871
                $month = substr($obj->dtime, 5, 2);
2872
                $day = substr($obj->dtime, 8, 2);
2873
                $hours = substr($obj->dtime, 11, 2);
2874
                $minutes = substr($obj->dtime, 14, 2);
2875
                $seconds = substr($obj->dtime, 17, 2);
2876
2877
                //get type assignment icon
2878
                if ($obj->assignment == 1) {
2879
                    $ShowAssignment = Display::return_icon(
2880
                        'wiki_assignment.png',
2881
                        get_lang('AssignmentDesc'),
2882
                        '',
2883
                        ICON_SIZE_SMALL
2884
                    );
2885
                } elseif ($obj->assignment == 2) {
2886
                    $ShowAssignment = Display::return_icon(
2887
                        'wiki_work.png',
2888
                        get_lang('AssignmentWork'),
2889
                        '',
2890
                        ICON_SIZE_SMALL
2891
                    );
2892
                } elseif ($obj->assignment == 0) {
2893
                    $ShowAssignment = Display::return_icon(
2894
                        'px_transparent.gif'
2895
                    );
2896
                }
2897
                $row = [];
2898
                $row[] = $ShowAssignment;
2899
2900
                if ($all_vers == '1') {
2901
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2902
                        ).'&action=showpage&title='.api_htmlentities(
2903
                            urlencode($obj->reflink)
2904
                        ).'&view='.$obj->id.'&session_id='.api_htmlentities(
2905
                            urlencode($_GET['$session_id'])
2906
                        ).'&group_id='.api_htmlentities(
2907
                            urlencode($_GET['group_id'])
2908
                        ).'">'.
2909
                        api_htmlentities($obj->title).'</a>';
2910
                } else {
2911
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2912
                        ).'&action=showpage&title='.api_htmlentities(
2913
                            urlencode($obj->reflink)
2914
                        ).'&session_id='.api_htmlentities(
2915
                            $_GET['session_id']
2916
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2917
                        $obj->title.'</a>';
2918
                }
2919
2920
                $row[] = ($obj->user_id != 0 && $userinfo !== false) ? UserManager::getUserProfileLink(
2921
                    $userinfo
2922
                ) : get_lang('Anonymous').' ('.$obj->user_ip.')';
2923
                $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
2924
2925
                if ($all_vers == '1') {
2926
                    $row[] = $obj->version;
2927
                } else {
2928
                    $showdelete = '';
2929
                    if (api_is_allowed_to_edit(
2930
                            false,
2931
                            true
2932
                        ) || api_is_platform_admin()) {
2933
                        $showdelete = ' <a href="'.api_get_self(
2934
                            ).'?'.api_get_cidreq(
2935
                            ).'&action=delete&title='.api_htmlentities(
2936
                                urlencode($obj->reflink)
2937
                            ).'&group_id='.api_htmlentities(
2938
                                $_GET['group_id']
2939
                            ).'">'.
2940
                            Display::return_icon(
2941
                                'delete.png',
2942
                                get_lang('Delete'),
2943
                                '',
2944
                                ICON_SIZE_SMALL
2945
                            );
2946
                    }
2947
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2948
                        ).'&action=edit&title='.api_htmlentities(
2949
                            urlencode($obj->reflink)
2950
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2951
                        Display::return_icon(
2952
                            'edit.png',
2953
                            get_lang('EditPage'),
2954
                            '',
2955
                            ICON_SIZE_SMALL
2956
                        ).'</a>
2957
                        <a href="'.api_get_self(
2958
                        ).'?cidReq='.$_course['code'].'&action=discuss&title='.api_htmlentities(
2959
                            urlencode($obj->reflink)
2960
                        ).'&session_id='.api_htmlentities(
2961
                            $_GET['session_id']
2962
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2963
                        Display::return_icon(
2964
                            'discuss.png',
2965
                            get_lang('Discuss'),
2966
                            '',
2967
                            ICON_SIZE_SMALL
2968
                        ).'</a>
2969
                        <a href="'.api_get_self(
2970
                        ).'?cidReq='.$_course['code'].'&action=history&title='.api_htmlentities(
2971
                            urlencode($obj->reflink)
2972
                        ).'&session_id='.api_htmlentities(
2973
                            $_GET['session_id']
2974
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2975
                        Display::return_icon(
2976
                            'history.png',
2977
                            get_lang('History'),
2978
                            '',
2979
                            ICON_SIZE_SMALL
2980
                        ).'</a> <a href="'.api_get_self(
2981
                        ).'?cidReq='.$_course['code'].'&action=links&title='.api_htmlentities(
2982
                            urlencode($obj->reflink)
2983
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2984
                        Display::return_icon(
2985
                            'what_link_here.png',
2986
                            get_lang('LinksPages'),
2987
                            '',
2988
                            ICON_SIZE_SMALL
2989
                        ).'</a>'.$showdelete;
2990
                }
2991
                $rows[] = $row;
2992
            }
2993
2994
            $table = new SortableTableFromArrayConfig(
2995
                $rows,
2996
                1,
2997
                10,
2998
                'SearchPages_table',
2999
                '',
3000
                '',
3001
                'ASC'
3002
            );
3003
            $table->set_additional_parameters(
3004
                [
3005
                    'cidReq' => $_GET['cidReq'],
3006
                    'action' => $_GET['action'],
3007
                    'group_id' => intval($_GET['group_id']),
3008
                    'mode_table' => 'yes2',
3009
                    'search_term' => $search_term,
3010
                    'search_content' => $search_content,
3011
                    'all_vers' => $all_vers,
3012
                ]
3013
            );
3014
            $table->set_header(
3015
                0,
3016
                get_lang('Type'),
3017
                true,
3018
                ['style' => 'width:30px;']
3019
            );
3020
            $table->set_header(1, get_lang('Title'), true);
3021
            if ($all_vers == '1') {
3022
                $table->set_header(2, get_lang('Author'), true);
3023
                $table->set_header(3, get_lang('Date'), true);
3024
                $table->set_header(4, get_lang('Version'), true);
3025
            } else {
3026
                $table->set_header(
3027
                    2,
3028
                    get_lang('Author').' ('.get_lang('LastVersion').')',
3029
                    true
3030
                );
3031
                $table->set_header(
3032
                    3,
3033
                    get_lang('Date').' ('.get_lang('LastVersion').')',
3034
                    true
3035
                );
3036
                $table->set_header(
3037
                    4,
3038
                    get_lang('Actions'),
3039
                    false,
3040
                    ['style' => 'width:130px;']
3041
                );
3042
            }
3043
            $table->display();
3044
        } else {
3045
            echo get_lang('NoSearchResults');
3046
        }
3047
    }
3048
3049
    /**
3050
     * Get wiki information.
3051
     *
3052
     * @param   int|bool wiki id
3053
     *
3054
     * @return array wiki data
3055
     */
3056
    public function getWikiDataFromDb($id)
3057
    {
3058
        $tbl_wiki = $this->tbl_wiki;
3059
        $course_id = api_get_course_int_id();
3060
        if ($id === false) {
3061
            return [];
3062
        }
3063
        $id = intval($id);
3064
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3065
                WHERE c_id = '.$course_id.' AND id = '.$id.' ';
3066
        $result = Database::query($sql);
3067
        $data = [];
3068
        while ($row = Database::fetch_array($result, 'ASSOC')) {
3069
            $data = $row;
3070
        }
3071
3072
        return $data;
3073
    }
3074
3075
    /**
3076
     * @param string $refLink
3077
     *
3078
     * @return array
3079
     */
3080
    public function getLastWikiData($refLink)
3081
    {
3082
        $tbl_wiki = $this->tbl_wiki;
3083
        $groupfilter = $this->groupfilter;
3084
        $condition_session = $this->condition_session;
3085
        $course_id = api_get_course_int_id();
3086
3087
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3088
                WHERE
3089
                    c_id = '.$course_id.' AND
3090
                    reflink="'.Database::escape_string($refLink).'" AND
3091
                    '.$groupfilter.$condition_session.'
3092
                ORDER BY id DESC';
3093
3094
        $result = Database::query($sql);
3095
3096
        return Database::fetch_array($result);
3097
    }
3098
3099
    /**
3100
     * Get wiki information.
3101
     *
3102
     * @param   string     wiki id
3103
     * @param int $courseId
3104
     *
3105
     * @return array wiki data
3106
     */
3107
    public function getPageByTitle($title, $courseId = null)
3108
    {
3109
        $tbl_wiki = $this->tbl_wiki;
3110
        if (empty($courseId)) {
3111
            $courseId = api_get_course_int_id();
3112
        } else {
3113
            $courseId = intval($courseId);
3114
        }
3115
3116
        if (empty($title) || empty($courseId)) {
3117
            return [];
3118
        }
3119
3120
        $title = Database::escape_string($title);
3121
        $sql = "SELECT * FROM $tbl_wiki
3122
                WHERE c_id = $courseId AND reflink = '$title'";
3123
        $result = Database::query($sql);
3124
        $data = [];
3125
        if (Database::num_rows($result)) {
3126
            $data = Database::fetch_array($result, 'ASSOC');
3127
        }
3128
3129
        return $data;
3130
    }
3131
3132
    /**
3133
     * @param string $title
3134
     * @param int    $courseId
3135
     * @param string
3136
     * @param string
3137
     *
3138
     * @return bool
3139
     */
3140
    public function deletePage(
3141
        $title,
3142
        $courseId,
3143
        $groupfilter = null,
3144
        $condition_session = null
3145
    ) {
3146
        $tbl_wiki = $this->tbl_wiki;
3147
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
3148
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
3149
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3150
3151
        $pageInfo = self::getPageByTitle($title, $courseId);
3152
        if (!empty($pageInfo)) {
3153
            $pageId = $pageInfo['id'];
3154
            $sql = "DELETE FROM $tbl_wiki_conf
3155
                    WHERE c_id = $courseId AND page_id = $pageId";
3156
            Database::query($sql);
3157
3158
            $sql = 'DELETE FROM '.$tbl_wiki_discuss.'
3159
                    WHERE c_id = '.$courseId.' AND publication_id = '.$pageId;
3160
            Database::query($sql);
3161
3162
            $sql = 'DELETE FROM  '.$tbl_wiki_mailcue.'
3163
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3164
            Database::query($sql);
3165
3166
            $sql = 'DELETE FROM '.$tbl_wiki.'
3167
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3168
            Database::query($sql);
3169
            self::check_emailcue(0, 'E');
3170
3171
            return true;
3172
        }
3173
3174
        return false;
3175
    }
3176
3177
    /**
3178
     * @return array
3179
     */
3180
    public function getAllWiki()
3181
    {
3182
        $tbl_wiki = $this->tbl_wiki;
3183
        $course_id = $this->course_id;
3184
        $condition_session = $this->condition_session;
3185
3186
        $sql = "SELECT * FROM $tbl_wiki
3187
                WHERE
3188
                    c_id = $course_id AND
3189
                    is_editing != '0' ".$condition_session;
3190
        $result = Database::query($sql);
3191
3192
        return Database::store_result($result, 'ASSOC');
3193
    }
3194
3195
    /**
3196
     * @param int $isEditing
3197
     */
3198
    public function updateWikiIsEditing($isEditing)
3199
    {
3200
        $tbl_wiki = $this->tbl_wiki;
3201
        $course_id = $this->course_id;
3202
        $condition_session = $this->condition_session;
3203
        $isEditing = Database::escape_string($isEditing);
3204
3205
        $sql = 'UPDATE '.$tbl_wiki.' SET
3206
                is_editing = "0",
3207
                time_edit = NULL
3208
                WHERE
3209
                    c_id = '.$course_id.' AND
3210
                    is_editing="'.$isEditing.'" '.
3211
            $condition_session;
3212
        Database::query($sql);
3213
    }
3214
3215
    /**
3216
     * Release of blocked pages to prevent concurrent editions.
3217
     *
3218
     * @param int    $userId
3219
     * @param string $action
3220
     */
3221
    public function blockConcurrentEditions($userId, $action = null)
3222
    {
3223
        $result = self::getAllWiki();
3224
        if (!empty($result)) {
3225
            foreach ($result as $is_editing_block) {
3226
                $max_edit_time = 1200; // 20 minutes
3227
                $timestamp_edit = strtotime($is_editing_block['time_edit']);
3228
                $time_editing = time() - $timestamp_edit;
3229
3230
                // First prevent concurrent users and double version
3231
                if ($is_editing_block['is_editing'] == $userId) {
3232
                    Session::write('_version', $is_editing_block['version']);
3233
                } else {
3234
                    Session::erase('_version');
3235
                }
3236
                // Second checks if has exceeded the time that a page may
3237
                // be available or if a page was edited and saved by its author
3238
                if ($time_editing > $max_edit_time ||
3239
                    ($is_editing_block['is_editing'] == $userId &&
3240
                        $action != 'edit')
3241
                ) {
3242
                    self::updateWikiIsEditing($is_editing_block['is_editing']);
3243
                }
3244
            }
3245
        }
3246
    }
3247
3248
    /**
3249
     * Showing wiki stats.
3250
     */
3251
    public function getStats()
3252
    {
3253
        if (!api_is_allowed_to_edit(false, true)) {
3254
            return false;
3255
        }
3256
3257
        $tbl_wiki = $this->tbl_wiki;
3258
        $course_id = $this->course_id;
3259
        $condition_session = $this->condition_session;
3260
        $groupfilter = $this->groupfilter;
3261
        $session_id = $this->session_id;
3262
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3263
3264
        echo '<div class="actions">'.get_lang('Statistics').'</div>';
3265
3266
        // Check all versions of all pages
3267
        $total_words = 0;
3268
        $total_links = 0;
3269
        $total_links_anchors = 0;
3270
        $total_links_mail = 0;
3271
        $total_links_ftp = 0;
3272
        $total_links_irc = 0;
3273
        $total_links_news = 0;
3274
        $total_wlinks = 0;
3275
        $total_images = 0;
3276
        $clean_total_flash = 0;
3277
        $total_flash = 0;
3278
        $total_mp3 = 0;
3279
        $total_flv_p = 0;
3280
        $total_flv = 0;
3281
        $total_youtube = 0;
3282
        $total_multimedia = 0;
3283
        $total_tables = 0;
3284
3285
        $sql = "SELECT *, COUNT(*) AS TOTAL_VERS, SUM(hits) AS TOTAL_VISITS
3286
                FROM ".$tbl_wiki."
3287
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3288
3289
        $allpages = Database::query($sql);
3290
        while ($row = Database::fetch_array($allpages)) {
3291
            $total_versions = $row['TOTAL_VERS'];
3292
            $total_visits = intval($row['TOTAL_VISITS']);
3293
        }
3294
3295
        $sql = "SELECT * FROM ".$tbl_wiki."
3296
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3297
        $allpages = Database::query($sql);
3298
3299
        while ($row = Database::fetch_array($allpages)) {
3300
            $total_words = $total_words + self::word_count($row['content']);
3301
            $total_links = $total_links + substr_count(
3302
                $row['content'],
3303
                "href="
3304
            );
3305
            $total_links_anchors = $total_links_anchors + substr_count(
3306
                $row['content'],
3307
                'href="#'
3308
            );
3309
            $total_links_mail = $total_links_mail + substr_count(
3310
                $row['content'],
3311
                'href="mailto'
3312
            );
3313
            $total_links_ftp = $total_links_ftp + substr_count(
3314
                $row['content'],
3315
                'href="ftp'
3316
            );
3317
            $total_links_irc = $total_links_irc + substr_count(
3318
                $row['content'],
3319
                'href="irc'
3320
            );
3321
            $total_links_news = $total_links_news + substr_count(
3322
                $row['content'],
3323
                'href="news'
3324
            );
3325
            $total_wlinks = $total_wlinks + substr_count($row['content'], "[[");
3326
            $total_images = $total_images + substr_count(
3327
                $row['content'],
3328
                "<img"
3329
            );
3330
            $clean_total_flash = preg_replace(
3331
                '/player.swf/',
3332
                ' ',
3333
                $row['content']
3334
            );
3335
            $total_flash = $total_flash + substr_count(
3336
                $clean_total_flash,
3337
                '.swf"'
3338
            );
3339
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3340
            $total_mp3 = $total_mp3 + substr_count($row['content'], ".mp3");
3341
            $total_flv_p = $total_flv_p + substr_count($row['content'], ".flv");
3342
            $total_flv = $total_flv_p / 5;
3343
            $total_youtube = $total_youtube + substr_count(
3344
                $row['content'],
3345
                "http://www.youtube.com"
3346
            );
3347
            $total_multimedia = $total_multimedia + substr_count(
3348
                $row['content'],
3349
                "video/x-msvideo"
3350
            );
3351
            $total_tables = $total_tables + substr_count(
3352
                $row['content'],
3353
                "<table"
3354
            );
3355
        }
3356
3357
        // Check only last version of all pages (current page)
3358
        $sql = ' SELECT *, COUNT(*) AS TOTAL_PAGES, SUM(hits) AS TOTAL_VISITS_LV
3359
                FROM  '.$tbl_wiki.' s1
3360
                WHERE s1.c_id = '.$course_id.' AND id=(
3361
                    SELECT MAX(s2.id)
3362
                    FROM '.$tbl_wiki.' s2
3363
                    WHERE
3364
                        s2.c_id = '.$course_id.' AND
3365
                        s1.reflink = s2.reflink AND
3366
                        '.$groupfilter.' AND
3367
                        session_id='.$session_id.')';
3368
        $allpages = Database::query($sql);
3369
        while ($row = Database::fetch_array($allpages)) {
3370
            $total_pages = $row['TOTAL_PAGES'];
3371
            $total_visits_lv = intval($row['TOTAL_VISITS_LV']);
3372
        }
3373
3374
        $total_words_lv = 0;
3375
        $total_links_lv = 0;
3376
        $total_links_anchors_lv = 0;
3377
        $total_links_mail_lv = 0;
3378
        $total_links_ftp_lv = 0;
3379
        $total_links_irc_lv = 0;
3380
        $total_links_news_lv = 0;
3381
        $total_wlinks_lv = 0;
3382
        $total_images_lv = 0;
3383
        $clean_total_flash_lv = 0;
3384
        $total_flash_lv = 0;
3385
        $total_mp3_lv = 0;
3386
        $total_flv_p_lv = 0;
3387
        $total_flv_lv = 0;
3388
        $total_youtube_lv = 0;
3389
        $total_multimedia_lv = 0;
3390
        $total_tables_lv = 0;
3391
3392
        $sql = 'SELECT * FROM  '.$tbl_wiki.' s1
3393
                WHERE s1.c_id = '.$course_id.' AND id=(
3394
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3395
                    WHERE
3396
                        s2.c_id = '.$course_id.' AND
3397
                        s1.reflink = s2.reflink AND
3398
                        '.$groupfilter.' AND
3399
                        session_id='.$session_id.'
3400
                )';
3401
        $allpages = Database::query($sql);
3402
3403
        while ($row = Database::fetch_array($allpages)) {
3404
            $total_words_lv = $total_words_lv + self::word_count(
3405
                $row['content']
3406
            );
3407
            $total_links_lv = $total_links_lv + substr_count(
3408
                $row['content'],
3409
                "href="
3410
            );
3411
            $total_links_anchors_lv = $total_links_anchors_lv + substr_count(
3412
                $row['content'],
3413
                'href="#'
3414
            );
3415
            $total_links_mail_lv = $total_links_mail_lv + substr_count(
3416
                $row['content'],
3417
                'href="mailto'
3418
            );
3419
            $total_links_ftp_lv = $total_links_ftp_lv + substr_count(
3420
                $row['content'],
3421
                'href="ftp'
3422
            );
3423
            $total_links_irc_lv = $total_links_irc_lv + substr_count(
3424
                $row['content'],
3425
                'href="irc'
3426
            );
3427
            $total_links_news_lv = $total_links_news_lv + substr_count(
3428
                $row['content'],
3429
                'href="news'
3430
            );
3431
            $total_wlinks_lv = $total_wlinks_lv + substr_count(
3432
                $row['content'],
3433
                "[["
3434
            );
3435
            $total_images_lv = $total_images_lv + substr_count(
3436
                $row['content'],
3437
                "<img"
3438
            );
3439
            $clean_total_flash_lv = preg_replace(
3440
                '/player.swf/',
3441
                ' ',
3442
                $row['content']
3443
            );
3444
            $total_flash_lv = $total_flash_lv + substr_count(
3445
                $clean_total_flash_lv,
3446
                '.swf"'
3447
            );
3448
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3449
            $total_mp3_lv = $total_mp3_lv + substr_count(
3450
                $row['content'],
3451
                ".mp3"
3452
            );
3453
            $total_flv_p_lv = $total_flv_p_lv + substr_count(
3454
                $row['content'],
3455
                ".flv"
3456
            );
3457
            $total_flv_lv = $total_flv_p_lv / 5;
3458
            $total_youtube_lv = $total_youtube_lv + substr_count(
3459
                $row['content'],
3460
                "http://www.youtube.com"
3461
            );
3462
            $total_multimedia_lv = $total_multimedia_lv + substr_count(
3463
                $row['content'],
3464
                "video/x-msvideo"
3465
            );
3466
            $total_tables_lv = $total_tables_lv + substr_count(
3467
                $row['content'],
3468
                "<table"
3469
            );
3470
        }
3471
3472
        //Total pages edited at this time
3473
        $total_editing_now = 0;
3474
        $sql = 'SELECT *, COUNT(*) AS TOTAL_EDITING_NOW
3475
                FROM  '.$tbl_wiki.' s1
3476
                WHERE is_editing!=0 AND s1.c_id = '.$course_id.' AND
3477
                id=(
3478
                    SELECT MAX(s2.id)
3479
                    FROM '.$tbl_wiki.' s2
3480
                    WHERE
3481
                        s2.c_id = '.$course_id.' AND
3482
                        s1.reflink = s2.reflink AND
3483
                        '.$groupfilter.' AND
3484
                        session_id='.$session_id.'
3485
        )';
3486
3487
        // Can not use group by because the mark is set in the latest version
3488
        $allpages = Database::query($sql);
3489
        while ($row = Database::fetch_array($allpages)) {
3490
            $total_editing_now = $row['TOTAL_EDITING_NOW'];
3491
        }
3492
3493
        // Total hidden pages
3494
        $total_hidden = 0;
3495
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3496
                WHERE
3497
                    c_id = '.$course_id.' AND
3498
                    visibility = 0 AND
3499
                    '.$groupfilter.$condition_session.'
3500
                GROUP BY reflink';
3501
        // or group by page_id. As the mark of hidden places it in all
3502
        // versions of the page, I can use group by to see the first
3503
        $allpages = Database::query($sql);
3504
        while ($row = Database::fetch_array($allpages)) {
3505
            $total_hidden = $total_hidden + 1;
3506
        }
3507
3508
        //Total protect pages
3509
        $total_protected = 0;
3510
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3511
                WHERE
3512
                    c_id = '.$course_id.' AND
3513
                    editlock = 1 AND
3514
                     '.$groupfilter.$condition_session.'
3515
                GROUP BY reflink';
3516
        // or group by page_id. As the mark of protected page is the
3517
        // first version of the page, I can use group by
3518
        $allpages = Database::query($sql);
3519
        while ($row = Database::fetch_array($allpages)) {
3520
            $total_protected = $total_protected + 1;
3521
        }
3522
3523
        // Total empty versions.
3524
        $total_empty_content = 0;
3525
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3526
                WHERE
3527
                    c_id = '.$course_id.' AND
3528
                    content="" AND
3529
                    '.$groupfilter.$condition_session.'';
3530
        $allpages = Database::query($sql);
3531
        while ($row = Database::fetch_array($allpages)) {
3532
            $total_empty_content = $total_empty_content + 1;
3533
        }
3534
3535
        //Total empty pages (last version)
3536
3537
        $total_empty_content_lv = 0;
3538
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3539
                WHERE s1.c_id = '.$course_id.' AND content="" AND id=(
3540
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3541
                    WHERE
3542
                        s1.c_id = '.$course_id.' AND
3543
                        s1.reflink = s2.reflink AND
3544
                        '.$groupfilter.' AND
3545
                        session_id='.$session_id.'
3546
                )';
3547
        $allpages = Database::query($sql);
3548
        while ($row = Database::fetch_array($allpages)) {
3549
            $total_empty_content_lv = $total_empty_content_lv + 1;
3550
        }
3551
3552
        // Total locked discuss pages
3553
        $total_lock_disc = 0;
3554
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3555
                WHERE c_id = '.$course_id.' AND addlock_disc=0 AND '.$groupfilter.$condition_session.'
3556
                GROUP BY reflink'; //group by because mark lock in all vers, then always is ok
3557
        $allpages = Database::query($sql);
3558
        while ($row = Database::fetch_array($allpages)) {
3559
            $total_lock_disc = $total_lock_disc + 1;
3560
        }
3561
3562
        // Total hidden discuss pages.
3563
        $total_hidden_disc = 0;
3564
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3565
                WHERE c_id = '.$course_id.' AND visibility_disc=0 AND '.$groupfilter.$condition_session.'
3566
                GROUP BY reflink';
3567
        //group by because mark lock in all vers, then always is ok
3568
        $allpages = Database::query($sql);
3569
        while ($row = Database::fetch_array($allpages)) {
3570
            $total_hidden_disc = $total_hidden_disc + 1;
3571
        }
3572
3573
        // Total versions with any short comment by user or system
3574
        $total_comment_version = 0;
3575
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3576
                WHERE c_id = '.$course_id.' AND comment!="" AND '.$groupfilter.$condition_session.'';
3577
        $allpages = Database::query($sql);
3578
        while ($row = Database::fetch_array($allpages)) {
3579
            $total_comment_version = $total_comment_version + 1;
3580
        }
3581
3582
        // Total pages that can only be scored by teachers.
3583
        $total_only_teachers_rating = 0;
3584
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3585
                WHERE c_id = '.$course_id.' AND
3586
                ratinglock_disc = 0 AND
3587
                '.$groupfilter.$condition_session.'
3588
                GROUP BY reflink'; //group by because mark lock in all vers, then always is ok
3589
        $allpages = Database::query($sql);
3590
        while ($row = Database::fetch_array($allpages)) {
3591
            $total_only_teachers_rating = $total_only_teachers_rating + 1;
3592
        }
3593
3594
        // Total pages scored by peers
3595
        // put always this line alfter check num all pages and num pages rated by teachers
3596
        $total_rating_by_peers = $total_pages - $total_only_teachers_rating;
3597
3598
        //Total pages identified as standard task
3599
        $total_task = 0;
3600
        $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
3601
              WHERE '.$tbl_wiki_conf.'.c_id = '.$course_id.' AND
3602
               '.$tbl_wiki_conf.'.task!="" AND
3603
               '.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
3604
                '.$tbl_wiki.'.'.$groupfilter.$condition_session;
3605
        $allpages = Database::query($sql);
3606
        while ($row = Database::fetch_array($allpages)) {
3607
            $total_task = $total_task + 1;
3608
        }
3609
3610
        //Total pages identified as teacher page (wiki portfolio mode - individual assignment)
3611
        $total_teacher_assignment = 0;
3612
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3613
                WHERE s1.c_id = '.$course_id.' AND assignment=1 AND id=(
3614
                    SELECT MAX(s2.id)
3615
                    FROM '.$tbl_wiki.' s2
3616
                    WHERE
3617
                        s2.c_id = '.$course_id.' AND
3618
                        s1.reflink = s2.reflink AND
3619
                        '.$groupfilter.' AND
3620
                         session_id='.$session_id.'
3621
                )';
3622
        //mark all versions, but do not use group by reflink because y want the pages not versions
3623
        $allpages = Database::query($sql);
3624
        while ($row = Database::fetch_array($allpages)) {
3625
            $total_teacher_assignment = $total_teacher_assignment + 1;
3626
        }
3627
3628
        //Total pages identifies as student page (wiki portfolio mode - individual assignment)
3629
        $total_student_assignment = 0;
3630
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3631
                WHERE s1.c_id = '.$course_id.' AND assignment=2 AND
3632
                id = (SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3633
                WHERE
3634
                    s2.c_id = '.$course_id.' AND
3635
                    s1.reflink = s2.reflink AND
3636
                    '.$groupfilter.' AND
3637
                    session_id='.$session_id.'
3638
                )';
3639
        //mark all versions, but do not use group by reflink because y want the pages not versions
3640
        $allpages = Database::query($sql);
3641
        while ($row = Database::fetch_array($allpages)) {
3642
            $total_student_assignment = $total_student_assignment + 1;
3643
        }
3644
3645
        //Current Wiki status add new pages
3646
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3647
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3648
                GROUP BY addlock'; //group by because mark 0 in all vers, then always is ok
3649
        $allpages = Database::query($sql);
3650
        $wiki_add_lock = null;
3651
        while ($row = Database::fetch_array($allpages)) {
3652
            $wiki_add_lock = $row['addlock'];
3653
        }
3654
3655
        if ($wiki_add_lock == 1) {
3656
            $status_add_new_pag = get_lang('Yes');
3657
        } else {
3658
            $status_add_new_pag = get_lang('No');
3659
        }
3660
3661
        // Creation date of the oldest wiki page and version
3662
        $first_wiki_date = null;
3663
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3664
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3665
                ORDER BY dtime ASC
3666
                LIMIT 1';
3667
        $allpages = Database::query($sql);
3668
        while ($row = Database::fetch_array($allpages)) {
3669
            $first_wiki_date = api_get_local_time($row['dtime']);
3670
        }
3671
3672
        // Date of publication of the latest wiki version.
3673
3674
        $last_wiki_date = null;
3675
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3676
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3677
                ORDER BY dtime DESC
3678
                LIMIT 1';
3679
        $allpages = Database::query($sql);
3680
        while ($row = Database::fetch_array($allpages)) {
3681
            $last_wiki_date = api_get_local_time($row['dtime']);
3682
        }
3683
3684
        // Average score of all wiki pages. (If a page has not scored zero rated)
3685
        $media_score = 0;
3686
        $sql = "SELECT *, SUM(score) AS TOTAL_SCORE FROM ".$tbl_wiki."
3687
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."
3688
                GROUP BY reflink ";
3689
        //group by because mark in all versions, then always is ok.
3690
        // Do not use "count" because using "group by", would give a wrong value
3691
        $allpages = Database::query($sql);
3692
        $total_score = 0;
3693
        while ($row = Database::fetch_array($allpages)) {
3694
            $total_score = $total_score + $row['TOTAL_SCORE'];
3695
        }
3696
3697
        if (!empty($total_pages)) {
3698
            $media_score = $total_score / $total_pages;
3699
            //put always this line alfter check num all pages
3700
        }
3701
3702
        // Average user progress in his pages.
3703
        $media_progress = 0;
3704
        $sql = 'SELECT  *, SUM(progress) AS TOTAL_PROGRESS
3705
                FROM  '.$tbl_wiki.' s1
3706
                WHERE s1.c_id = '.$course_id.' AND id=
3707
                (
3708
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3709
                    WHERE
3710
                        s2.c_id = '.$course_id.' AND
3711
                        s1.reflink = s2.reflink AND
3712
                        '.$groupfilter.' AND
3713
                        session_id='.$session_id.'
3714
                )';
3715
        // As the value is only the latest version I can not use group by
3716
        $allpages = Database::query($sql);
3717
        while ($row = Database::fetch_array($allpages)) {
3718
            $total_progress = $row['TOTAL_PROGRESS'];
3719
        }
3720
3721
        if (!empty($total_pages)) {
3722
            $media_progress = $total_progress / $total_pages;
3723
            //put always this line alfter check num all pages
3724
        }
3725
3726
        // Total users that have participated in the Wiki
3727
        $total_users = 0;
3728
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3729
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3730
                GROUP BY user_id';
3731
        //as the mark of user it in all versions of the page, I can use group by to see the first
3732
        $allpages = Database::query($sql);
3733
        while ($row = Database::fetch_array($allpages)) {
3734
            $total_users = $total_users + 1;
3735
        }
3736
3737
        // Total of different IP addresses that have participated in the wiki
3738
        $total_ip = 0;
3739
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3740
              WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3741
              GROUP BY user_ip';
3742
        $allpages = Database::query($sql);
3743
        while ($row = Database::fetch_array($allpages)) {
3744
            $total_ip = $total_ip + 1;
3745
        }
3746
3747
        echo '<table class="table table-hover table-striped data_table">';
3748
        echo '<thead>';
3749
        echo '<tr>';
3750
        echo '<th colspan="2">'.get_lang('General').'</th>';
3751
        echo '</tr>';
3752
        echo '</thead>';
3753
        echo '<tr>';
3754
        echo '<td>'.get_lang('StudentAddNewPages').'</td>';
3755
        echo '<td>'.$status_add_new_pag.'</td>';
3756
        echo '</tr>';
3757
        echo '<tr>';
3758
        echo '<td>'.get_lang('DateCreateOldestWikiPage').'</td>';
3759
        echo '<td>'.$first_wiki_date.'</td>';
3760
        echo '</tr>';
3761
        echo '<tr>';
3762
        echo '<td>'.get_lang('DateEditLatestWikiVersion').'</td>';
3763
        echo '<td>'.$last_wiki_date.'</td>';
3764
        echo '</tr>';
3765
        echo '<tr>';
3766
        echo '<td>'.get_lang('AverageScoreAllPages').'</td>';
3767
        echo '<td>'.$media_score.' %</td>';
3768
        echo '</tr>';
3769
        echo '<tr>';
3770
        echo '<td>'.get_lang('AverageMediaUserProgress').'</td>';
3771
        echo '<td>'.$media_progress.' %</td>';
3772
        echo '</tr>';
3773
        echo '<tr>';
3774
        echo '<td>'.get_lang('TotalWikiUsers').'</td>';
3775
        echo '<td>'.$total_users.'</td>';
3776
        echo '</tr>';
3777
        echo '<tr>';
3778
        echo '<td>'.get_lang('TotalIpAdress').'</td>';
3779
        echo '<td>'.$total_ip.'</td>';
3780
        echo '</tr>';
3781
        echo '</table>';
3782
        echo '<br/>';
3783
3784
        echo '<table class="table table-hover table-striped data_table">';
3785
        echo '<thead>';
3786
        echo '<tr>';
3787
        echo '<th colspan="2">'.get_lang('Pages').' '.get_lang(
3788
                'And'
3789
            ).' '.get_lang('Versions').'</th>';
3790
        echo '</tr>';
3791
        echo '</thead>';
3792
        echo '<tr>';
3793
        echo '<td>'.get_lang('Pages').' - '.get_lang(
3794
                'NumContributions'
3795
            ).'</td>';
3796
        echo '<td>'.$total_pages.' ('.get_lang(
3797
                'Versions'
3798
            ).': '.$total_versions.')</td>';
3799
        echo '</tr>';
3800
        echo '<tr>';
3801
        echo '<td>'.get_lang('EmptyPages').'</td>';
3802
        echo '<td>'.$total_empty_content_lv.' ('.get_lang(
3803
                'Versions'
3804
            ).': '.$total_empty_content.')</td>';
3805
        echo '</tr>';
3806
        echo '<tr>';
3807
        echo '<td>'.get_lang('NumAccess').'</td>';
3808
        echo '<td>'.$total_visits_lv.' ('.get_lang(
3809
                'Versions'
3810
            ).': '.$total_visits.')</td>';
3811
        echo '</tr>';
3812
        echo '<tr>';
3813
        echo '<td>'.get_lang('TotalPagesEditedAtThisTime').'</td>';
3814
        echo '<td>'.$total_editing_now.'</td>';
3815
        echo '</tr>';
3816
        echo '<tr>';
3817
        echo '<td>'.get_lang('TotalHiddenPages').'</td>';
3818
        echo '<td>'.$total_hidden.'</td>';
3819
        echo '</tr>';
3820
        echo '<tr>';
3821
        echo '<td>'.get_lang('NumProtectedPages').'</td>';
3822
        echo '<td>'.$total_protected.'</td>';
3823
        echo '</tr>';
3824
        echo '<tr>';
3825
        echo '<td>'.get_lang('LockedDiscussPages').'</td>';
3826
        echo '<td>'.$total_lock_disc.'</td>';
3827
        echo '</tr>';
3828
        echo '<tr>';
3829
        echo '<td>'.get_lang('HiddenDiscussPages').'</td>';
3830
        echo '<td>'.$total_hidden_disc.'</td>';
3831
        echo '</tr>';
3832
        echo '<tr>';
3833
        echo '<td>'.get_lang('TotalComments').'</td>';
3834
        echo '<td>'.$total_comment_version.'</td>';
3835
        echo '</tr>';
3836
        echo '<tr>';
3837
        echo '<td>'.get_lang('TotalOnlyRatingByTeacher').'</td>';
3838
        echo '<td>'.$total_only_teachers_rating.'</td>';
3839
        echo '</tr>';
3840
        echo '<tr>';
3841
        echo '<td>'.get_lang('TotalRatingPeers').'</td>';
3842
        echo '<td>'.$total_rating_by_peers.'</td>';
3843
        echo '</tr>';
3844
        echo '<tr>';
3845
        echo '<td>'.get_lang('TotalTeacherAssignments').' - '.get_lang(
3846
                'PortfolioMode'
3847
            ).'</td>';
3848
        echo '<td>'.$total_teacher_assignment.'</td>';
3849
        echo '</tr>';
3850
        echo '<tr>';
3851
        echo '<td>'.get_lang('TotalStudentAssignments').' - '.get_lang(
3852
                'PortfolioMode'
3853
            ).'</td>';
3854
        echo '<td>'.$total_student_assignment.'</td>';
3855
        echo '</tr>';
3856
        echo '<tr>';
3857
        echo '<td>'.get_lang('TotalTask').' - '.get_lang(
3858
                'StandardMode'
3859
            ).'</td>';
3860
        echo '<td>'.$total_task.'</td>';
3861
        echo '</tr>';
3862
        echo '</table>';
3863
        echo '<br/>';
3864
3865
        echo '<table class="table table-hover table-striped data_table">';
3866
        echo '<thead>';
3867
        echo '<tr>';
3868
        echo '<th colspan="3">'.get_lang('ContentPagesInfo').'</th>';
3869
        echo '</tr>';
3870
        echo '<tr>';
3871
        echo '<td></td>';
3872
        echo '<td>'.get_lang('InTheLastVersion').'</td>';
3873
        echo '<td>'.get_lang('InAllVersions').'</td>';
3874
        echo '</tr>';
3875
        echo '</thead>';
3876
        echo '<tr>';
3877
        echo '<td>'.get_lang('NumWords').'</td>';
3878
        echo '<td>'.$total_words_lv.'</td>';
3879
        echo '<td>'.$total_words.'</td>';
3880
        echo '</tr>';
3881
        echo '<tr>';
3882
        echo '<td>'.get_lang('NumlinksHtmlImagMedia').'</td>';
3883
        echo '<td>'.$total_links_lv.' ('.get_lang(
3884
                'Anchors'
3885
            ).':'.$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>';
3886
        echo '<td>'.$total_links.' ('.get_lang(
3887
                'Anchors'
3888
            ).':'.$total_links_anchors.', Mail:'.$total_links_mail.', FTP:'.$total_links_ftp.', IRC:'.$total_links_irc.', News:'.$total_links_news.', ... ) </td>';
3889
        echo '</tr>';
3890
        echo '<tr>';
3891
        echo '<td>'.get_lang('NumWikilinks').'</td>';
3892
        echo '<td>'.$total_wlinks_lv.'</td>';
3893
        echo '<td>'.$total_wlinks.'</td>';
3894
        echo '</tr>';
3895
        echo '<tr>';
3896
        echo '<td>'.get_lang('NumImages').'</td>';
3897
        echo '<td>'.$total_images_lv.'</td>';
3898
        echo '<td>'.$total_images.'</td>';
3899
        echo '</tr>';
3900
        echo '<tr>';
3901
        echo '<td>'.get_lang('NumFlash').'</td>';
3902
        echo '<td>'.$total_flash_lv.'</td>';
3903
        echo '<td>'.$total_flash.'</td>';
3904
        echo '</tr>';
3905
        echo '<tr>';
3906
        echo '<td>'.get_lang('NumMp3').'</td>';
3907
        echo '<td>'.$total_mp3_lv.'</td>';
3908
        echo '<td>'.$total_mp3.'</td>';
3909
        echo '</tr>';
3910
        echo '<tr>';
3911
        echo '<td>'.get_lang('NumFlvVideo').'</td>';
3912
        echo '<td>'.$total_flv_lv.'</td>';
3913
        echo '<td>'.$total_flv.'</td>';
3914
        echo '</tr>';
3915
        echo '<tr>';
3916
        echo '<td>'.get_lang('NumYoutubeVideo').'</td>';
3917
        echo '<td>'.$total_youtube_lv.'</td>';
3918
        echo '<td>'.$total_youtube.'</td>';
3919
        echo '</tr>';
3920
        echo '<tr>';
3921
        echo '<td>'.get_lang('NumOtherAudioVideo').'</td>';
3922
        echo '<td>'.$total_multimedia_lv.'</td>';
3923
        echo '<td>'.$total_multimedia.'</td>';
3924
        echo '</tr>';
3925
        echo '<tr>';
3926
        echo '<td>'.get_lang('NumTables').'</td>';
3927
        echo '<td>'.$total_tables_lv.'</td>';
3928
        echo '<td>'.$total_tables.'</td>';
3929
        echo '</tr>';
3930
        echo '</table>';
3931
    }
3932
3933
    /**
3934
     * @param string $action
3935
     */
3936
    public function getActiveUsers($action)
3937
    {
3938
        $tbl_wiki = $this->tbl_wiki;
3939
        $course_id = $this->course_id;
3940
        $condition_session = $this->condition_session;
3941
        $groupfilter = $this->groupfilter;
3942
        $_course = $this->courseInfo;
3943
3944
        echo '<div class="actions">'.get_lang('MostActiveUsers').'</div>';
3945
        $sql = 'SELECT *, COUNT(*) AS NUM_EDIT FROM '.$tbl_wiki.'
3946
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3947
                GROUP BY user_id';
3948
        $allpages = Database::query($sql);
3949
3950
        //show table
3951
        if (Database::num_rows($allpages) > 0) {
3952
            while ($obj = Database::fetch_object($allpages)) {
3953
                $userinfo = api_get_user_info($obj->user_id);
3954
                $row = [];
3955
                if ($obj->user_id != 0 && $userinfo !== false) {
3956
                    $row[] = UserManager::getUserProfileLink($userinfo).'
3957
                            <a href="'.api_get_self(
3958
                        ).'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode(
3959
                            $obj->user_id
3960
                        ).
3961
                        '&session_id='.api_htmlentities(
3962
                            $_GET['session_id']
3963
                        ).'&group_id='.api_htmlentities(
3964
                            $_GET['group_id']
3965
                        ).'"></a>';
3966
                } else {
3967
                    $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
3968
                }
3969
                $row[] = '<a href="'.api_get_self(
3970
                    ).'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode(
3971
                        $obj->user_id
3972
                    ).'&session_id='.api_htmlentities(
3973
                        $_GET['session_id']
3974
                    ).'&group_id='.api_htmlentities(
3975
                        $_GET['group_id']
3976
                    ).'">'.$obj->NUM_EDIT.'</a>';
3977
                $rows[] = $row;
3978
            }
3979
3980
            $table = new SortableTableFromArrayConfig(
3981
                $rows,
3982
                1,
3983
                10,
3984
                'MostActiveUsersA_table',
3985
                '',
3986
                '',
3987
                'DESC'
3988
            );
3989
            $table->set_additional_parameters(
3990
                [
3991
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
3992
                    'action' => Security::remove_XSS($action),
3993
                    'session_id' => Security::remove_XSS($_GET['session_id']),
3994
                    'group_id' => Security::remove_XSS($_GET['group_id']),
3995
                ]
3996
            );
3997
            $table->set_header(0, get_lang('Author'), true);
3998
            $table->set_header(
3999
                1,
4000
                get_lang('Contributions'),
4001
                true,
4002
                ['style' => 'width:30px;']
4003
            );
4004
            $table->display();
4005
        }
4006
    }
4007
4008
    /**
4009
     * @param string $page
4010
     */
4011
    public function getDiscuss($page)
4012
    {
4013
        $tbl_wiki = $this->tbl_wiki;
4014
        $course_id = $this->course_id;
4015
        $condition_session = $this->condition_session;
4016
        $groupfilter = $this->groupfilter;
4017
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
4018
4019
        if (api_get_session_id() != 0 &&
4020
            api_is_allowed_to_session_edit(false, true) == false
4021
        ) {
4022
            api_not_allowed();
4023
        }
4024
4025
        if (!$_GET['title']) {
4026
            Display::addFlash(
4027
                Display::return_message(
4028
                    get_lang("MustSelectPage"),
4029
                    'error',
4030
                    false
4031
                )
4032
            );
4033
4034
            return;
4035
        }
4036
4037
        // First extract the date of last version
4038
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4039
                WHERE
4040
                    c_id = '.$course_id.' AND
4041
                    reflink = "'.Database::escape_string($page).'" AND
4042
                    '.$groupfilter.$condition_session.'
4043
                ORDER BY id DESC';
4044
        $result = Database::query($sql);
4045
        $row = Database::fetch_array($result);
4046
        $lastversiondate = api_get_local_time($row['dtime']);
4047
        $lastuserinfo = api_get_user_info($row['user_id']);
4048
4049
        // Select page to discuss
4050
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4051
                WHERE
4052
                    c_id = '.$course_id.' AND
4053
                    reflink="'.Database::escape_string($page).'" AND
4054
                    '.$groupfilter.$condition_session.'
4055
                ORDER BY id ASC';
4056
        $result = Database::query($sql);
4057
        $row = Database::fetch_array($result);
4058
        $id = $row['id'];
4059
        $firstuserid = $row['user_id'];
4060
4061
        if (isset($_POST['Submit']) && self::double_post($_POST['wpost_id'])) {
4062
            $dtime = api_get_utc_datetime();
4063
            $message_author = api_get_user_id();
4064
4065
            $params = [
4066
                'c_id' => $course_id,
4067
                'publication_id' => $id,
4068
                'userc_id' => $message_author,
4069
                'comment' => $_POST['comment'],
4070
                'p_score' => $_POST['rating'],
4071
                'dtime' => $dtime,
4072
            ];
4073
            $discussId = Database::insert($tbl_wiki_discuss, $params);
4074
            if ($discussId) {
4075
                $sql = "UPDATE $tbl_wiki_discuss SET id = iid WHERE iid = $discussId";
4076
                Database::query($sql);
4077
            }
4078
4079
            self::check_emailcue($id, 'D', $dtime, $message_author);
4080
4081
            header(
4082
                'Location: index.php?action=discuss&title='.api_htmlentities(urlencode($page)).'&'.api_get_cidreq()
4083
            );
4084
            exit;
4085
        }
4086
4087
        // mode assignment: previous to show  page type
4088
        $icon_assignment = null;
4089
        if ($row['assignment'] == 1) {
4090
            $icon_assignment = Display::return_icon(
4091
                'wiki_assignment.png',
4092
                get_lang('AssignmentDescExtra'),
4093
                '',
4094
                ICON_SIZE_SMALL
4095
            );
4096
        } elseif ($row['assignment'] == 2) {
4097
            $icon_assignment = Display::return_icon(
4098
                'wiki_work.png',
4099
                get_lang('AssignmentWorkExtra'),
4100
                '',
4101
                ICON_SIZE_SMALL
4102
            );
4103
        }
4104
4105
        $countWPost = null;
4106
        $avg_WPost_score = null;
4107
4108
        // Show title and form to discuss if page exist
4109
        if ($id != '') {
4110
            // Show discussion to students if isn't hidden.
4111
            // Show page to all teachers if is hidden.
4112
            // Mode assignments: If is hidden, show pages to student only if student is the author
4113
            if ($row['visibility_disc'] == 1 ||
4114
                api_is_allowed_to_edit(false, true) ||
4115
                api_is_platform_admin() ||
4116
                ($row['assignment'] == 2 && $row['visibility_disc'] == 0 && (api_get_user_id() == $row['user_id']))
4117
            ) {
4118
                echo '<div id="wikititle">';
4119
                // discussion action: protecting (locking) the discussion
4120
                $addlock_disc = null;
4121
                $lock_unlock_disc = null;
4122
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4123
                    if (self::check_addlock_discuss() == 1) {
4124
                        $addlock_disc = Display::return_icon(
4125
                            'unlock.png',
4126
                            get_lang('UnlockDiscussExtra'),
4127
                            '',
4128
                            ICON_SIZE_SMALL
4129
                        );
4130
                        $lock_unlock_disc = 'unlockdisc';
4131
                    } else {
4132
                        $addlock_disc = Display::return_icon(
4133
                            'lock.png',
4134
                            get_lang('LockDiscussExtra'),
4135
                            '',
4136
                            ICON_SIZE_SMALL
4137
                        );
4138
                        $lock_unlock_disc = 'lockdisc';
4139
                    }
4140
                }
4141
                echo '<span style="float:right">';
4142
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_disc.'&title='.api_htmlentities(
4143
                        urlencode($page)
4144
                    ).'">'.$addlock_disc.'</a>';
4145
                echo '</span>';
4146
4147
                // discussion action: visibility.  Show discussion to students if isn't hidden. Show page to all teachers if is hidden.
4148
                $visibility_disc = null;
4149
                $hide_show_disc = null;
4150
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4151
                    if (self::check_visibility_discuss() == 1) {
4152
                        /// TODO: 	Fix Mode assignments: If is hidden, show discussion to student only if student is the author
4153
                        $visibility_disc = Display::return_icon(
4154
                            'visible.png',
4155
                            get_lang('ShowDiscussExtra'),
4156
                            '',
4157
                            ICON_SIZE_SMALL
4158
                        );
4159
                        $hide_show_disc = 'hidedisc';
4160
                    } else {
4161
                        $visibility_disc = Display::return_icon(
4162
                            'invisible.png',
4163
                            get_lang('HideDiscussExtra'),
4164
                            '',
4165
                            ICON_SIZE_SMALL
4166
                        );
4167
                        $hide_show_disc = 'showdisc';
4168
                    }
4169
                }
4170
                echo '<span style="float:right">';
4171
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$hide_show_disc.'&title='.api_htmlentities(
4172
                        urlencode($page)
4173
                    ).'">'.$visibility_disc.'</a>';
4174
                echo '</span>';
4175
4176
                // discussion action: check add rating lock. Show/Hide list to rating for all student
4177
                $lock_unlock_rating_disc = null;
4178
                $ratinglock_disc = null;
4179
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4180
                    if (self::check_ratinglock_discuss() == 1) {
4181
                        $ratinglock_disc = Display::return_icon(
4182
                            'star.png',
4183
                            get_lang('UnlockRatingDiscussExtra'),
4184
                            '',
4185
                            ICON_SIZE_SMALL
4186
                        );
4187
                        $lock_unlock_rating_disc = 'unlockrating';
4188
                    } else {
4189
                        $ratinglock_disc = Display::return_icon(
4190
                            'star_na.png',
4191
                            get_lang('LockRatingDiscussExtra'),
4192
                            '',
4193
                            ICON_SIZE_SMALL
4194
                        );
4195
                        $lock_unlock_rating_disc = 'lockrating';
4196
                    }
4197
                }
4198
4199
                echo '<span style="float:right">';
4200
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_rating_disc.'&title='.api_htmlentities(
4201
                        urlencode($page)
4202
                    ).'">'.$ratinglock_disc.'</a>';
4203
                echo '</span>';
4204
4205
                // discussion action: email notification
4206
                if (self::check_notify_discuss($page) == 1) {
4207
                    $notify_disc = Display::return_icon(
4208
                        'messagebox_info.png',
4209
                        get_lang('NotifyDiscussByEmail'),
4210
                        '',
4211
                        ICON_SIZE_SMALL
4212
                    );
4213
                    $lock_unlock_notify_disc = 'unlocknotifydisc';
4214
                } else {
4215
                    $notify_disc = Display::return_icon(
4216
                        'mail.png',
4217
                        get_lang('CancelNotifyDiscussByEmail'),
4218
                        '',
4219
                        ICON_SIZE_SMALL
4220
                    );
4221
                    $lock_unlock_notify_disc = 'locknotifydisc';
4222
                }
4223
                echo '<span style="float:right">';
4224
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_notify_disc.'&title='.api_htmlentities(
4225
                        urlencode($page)
4226
                    ).'">'.$notify_disc.'</a>';
4227
                echo '</span>';
4228
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities(
4229
                        $row['title']
4230
                    );
4231
                if ($lastuserinfo !== false) {
4232
                    echo ' ('.get_lang('MostRecentVersionBy').' '.
4233
                        UserManager::getUserProfileLink($lastuserinfo).' '.$lastversiondate.$countWPost.')'.$avg_WPost_score.' '; //TODO: read average score
4234
                }
4235
4236
                echo '</div>';
4237
                if ($row['addlock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4238
                    //show comments but students can't add theirs
4239
                    ?>
4240
                    <div class="panel panel-default">
4241
                        <div class="panel-body">
4242
                            <form name="form1" method="post" action=""
4243
                                  class="form-horizontal">
4244
                                <div class="form-group">
4245
                                    <label
4246
                                        class="col-sm-2 control-label">
4247
                                        <?php echo get_lang('Comments'); ?>:</label>
4248
                                    <div class="col-sm-10">
4249
                                        <?php echo '<input type="hidden" name="wpost_id" value="'.md5(uniqid(rand(), true)).'">'; //prevent double post?>
4250
                                        <textarea class="form-control"
4251
                                                  name="comment" cols="80"
4252
                                                  rows="5"
4253
                                                  id="comment">
4254
                                        </textarea>
4255
                                    </div>
4256
                                </div>
4257
                                <div class="form-group">
4258
                                    <?php
4259
                                    //check if rating is allowed
4260
                                    if ($row['ratinglock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4261
                                        ?>
4262
                                        <label
4263
                                            class="col-sm-2 control-label"><?php echo get_lang('Rating'); ?>:</label>
4264
                                        <div class="col-sm-10">
4265
                                            <select name="rating" id="rating" class="selectpicker">
4266
                                                <option value="-" selected>-</option>
4267
                                                <option value="0">0</option>
4268
                                                <option value="1">1</option>
4269
                                                <option value="2">2</option>
4270
                                                <option value="3">3</option>
4271
                                                <option value="4">4</option>
4272
                                                <option value="5">5</option>
4273
                                                <option value="6">6</option>
4274
                                                <option value="7">7</option>
4275
                                                <option value="8">8</option>
4276
                                                <option value="9">9</option>
4277
                                                <option value="10">10</option>
4278
                                            </select>
4279
                                        </div>
4280
                                        <?php
4281
                                    } else {
4282
                                        echo '<input type=hidden name="rating" value="-">';
4283
                                        // must pass a default value to avoid rate automatically
4284
                                    } ?>
4285
4286
                                </div>
4287
                                <div class="form-group">
4288
                                    <div class="col-sm-offset-2 col-sm-10">
4289
                                        <?php echo '<button class="btn btn-default" type="submit" name="Submit"> '.
4290
                                            get_lang('Send').'</button>'; ?>
4291
                                    </div>
4292
                                </div>
4293
                        </div>
4294
                    </div>
4295
                    </form>
4296
                    <?php
4297
                }
4298
                // end discuss lock
4299
4300
                echo '<hr noshade size="1">';
4301
                $user_table = Database::get_main_table(TABLE_MAIN_USER);
4302
4303
                $sql = "SELECT *
4304
                        FROM $tbl_wiki_discuss reviews, $user_table user
4305
                        WHERE
4306
                            reviews.c_id = $course_id AND
4307
                            reviews.publication_id='".$id."' AND
4308
                            user.user_id='".$firstuserid."'
4309
                        ORDER BY reviews.id DESC";
4310
                $result = Database::query($sql);
4311
4312
                $countWPost = Database::num_rows($result);
4313
                echo get_lang('NumComments').": ".$countWPost; //comment's numbers
4314
4315
                $sql = "SELECT SUM(p_score) as sumWPost
4316
                        FROM $tbl_wiki_discuss
4317
                        WHERE c_id = $course_id AND publication_id = '".$id."' AND NOT p_score='-'
4318
                        ORDER BY id DESC";
4319
                $result2 = Database::query($sql);
4320
                $row2 = Database::fetch_array($result2);
4321
4322
                $sql = "SELECT * FROM $tbl_wiki_discuss
4323
                        WHERE c_id = $course_id AND publication_id='".$id."' AND NOT p_score='-'";
4324
                $result3 = Database::query($sql);
4325
                $countWPost_score = Database::num_rows($result3);
4326
4327
                echo ' - '.get_lang('NumCommentsScore').': '.$countWPost_score;
4328
4329
                if ($countWPost_score != 0) {
4330
                    $avg_WPost_score = round($row2['sumWPost'] / $countWPost_score, 2).' / 10';
4331
                } else {
4332
                    $avg_WPost_score = $countWPost_score;
4333
                }
4334
4335
                echo ' - '.get_lang('RatingMedia').': '.$avg_WPost_score; // average rating
4336
4337
                $sql = 'UPDATE '.$tbl_wiki.' SET
4338
                        score = "'.Database::escape_string($avg_WPost_score).'"
4339
                        WHERE
4340
                            c_id = '.$course_id.' AND
4341
                            reflink="'.Database::escape_string($page).'" AND
4342
                            '.$groupfilter.$condition_session;
4343
                // check if work ok. TODO:
4344
                Database::query($sql);
4345
4346
                echo '<hr noshade size="1">';
4347
                while ($row = Database::fetch_array($result)) {
4348
                    $userinfo = api_get_user_info($row['userc_id']);
4349
                    if (($userinfo['status']) == "5") {
4350
                        $author_status = get_lang('Student');
4351
                    } else {
4352
                        $author_status = get_lang('Teacher');
4353
                    }
4354
4355
                    $name = $userinfo['complete_name'];
4356
                    $author_photo = '<img src="'.$userinfo['avatar'].'" alt="'.api_htmlentities($name).'"  width="40" height="50" align="top"  title="'.api_htmlentities($name).'"  />';
4357
4358
                    // stars
4359
                    $p_score = $row['p_score'];
4360
                    switch ($p_score) {
4361
                        case 0:
4362
                            $imagerating = Display::return_icon(
4363
                                'rating/stars_0.gif'
4364
                            );
4365
                            break;
4366
                        case 1:
4367
                            $imagerating = Display::return_icon(
4368
                                'rating/stars_5.gif'
4369
                            );
4370
                            break;
4371
                        case 2:
4372
                            $imagerating = Display::return_icon(
4373
                                'rating/stars_10.gif'
4374
                            );
4375
                            break;
4376
                        case 3:
4377
                            $imagerating = Display::return_icon(
4378
                                'rating/stars_15.gif'
4379
                            );
4380
                            break;
4381
                        case 4:
4382
                            $imagerating = Display::return_icon(
4383
                                'rating/stars_20.gif'
4384
                            );
4385
                            break;
4386
                        case 5:
4387
                            $imagerating = Display::return_icon(
4388
                                'rating/stars_25.gif'
4389
                            );
4390
                            break;
4391
                        case 6:
4392
                            $imagerating = Display::return_icon(
4393
                                'rating/stars_30.gif'
4394
                            );
4395
                            break;
4396
                        case 7:
4397
                            $imagerating = Display::return_icon(
4398
                                'rating/stars_35.gif'
4399
                            );
4400
                            break;
4401
                        case 8:
4402
                            $imagerating = Display::return_icon(
4403
                                'rating/stars_40.gif'
4404
                            );
4405
                            break;
4406
                        case 9:
4407
                            $imagerating = Display::return_icon(
4408
                                'rating/stars_45.gif'
4409
                            );
4410
                            break;
4411
                        case 10:
4412
                            $imagerating = Display::return_icon(
4413
                                'rating/stars_50.gif'
4414
                            );
4415
                            break;
4416
                    }
4417
                    echo '<p><table>';
4418
                    echo '<tr>';
4419
                    echo '<td rowspan="2">'.$author_photo.'</td>';
4420
                    $userProfile = '';
4421
                    if ($userinfo !== false) {
4422
                        $userProfile = UserManager::getUserProfileLink(
4423
                            $userinfo
4424
                        );
4425
                    }
4426
                    echo '<td style=" color:#999999">'.$userProfile.' ('.$author_status.') '.
4427
                        api_get_local_time(
4428
                            $row['dtime']
4429
                        ).
4430
                        ' - '.get_lang(
4431
                            'Rating'
4432
                        ).': '.$row['p_score'].' '.$imagerating.' </td>';
4433
                    echo '</tr>';
4434
                    echo '<tr>';
4435
                    echo '<td>'.api_htmlentities($row['comment']).'</td>';
4436
                    echo '</tr>';
4437
                    echo "</table>";
4438
                }
4439
            } else {
4440
                Display::addFlash(
4441
                    Display::return_message(
4442
                        get_lang('LockByTeacher'),
4443
                        'warning',
4444
                        false
4445
                    )
4446
                );
4447
            }
4448
        } else {
4449
            Display::addFlash(
4450
                Display::return_message(
4451
                    get_lang('DiscussNotAvailable'),
4452
                    'normal',
4453
                    false
4454
                )
4455
            );
4456
        }
4457
    }
4458
4459
    /**
4460
     * Show all pages.
4461
     */
4462
    public function allPages($action)
4463
    {
4464
        $_course = $this->courseInfo;
4465
4466
        echo '<div class="actions">'.get_lang('AllPages');
4467
4468
        // menu delete all wiki
4469
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4470
            echo ' <a href="index.php?action=deletewiki&'.api_get_cidreq().'">'.
4471
                Display::return_icon(
4472
                    'delete.png',
4473
                    get_lang('DeleteWiki'),
4474
                    '',
4475
                    ICON_SIZE_MEDIUM
4476
                ).'</a>';
4477
        }
4478
        echo '</div>';
4479
4480
        //show table
4481
        $table = new SortableTable(
4482
            'AllPages_table',
4483
            function () {
4484
                $result = $this->gelAllPagesQuery(true);
4485
4486
                return (int) Database::fetch_assoc($result)['nbr'];
4487
            },
4488
            function ($from, $numberOfItems, $column, $direction) {
4489
                $result = $this->gelAllPagesQuery(false, $from, $numberOfItems, $column, $direction);
4490
                $rows = [];
4491
4492
                while ($data = Database::fetch_assoc($result)) {
4493
                    $rows[] = [
4494
                        $data['col0'],
4495
                        [$data['col1'], $data['reflink']],
4496
                        [$data['col2'], $data['user_ip']],
4497
                        $data['col3'],
4498
                        $data['reflink'],
4499
                    ];
4500
                }
4501
4502
                return $rows;
4503
            }
4504
        );
4505
        $table->set_additional_parameters(
4506
            [
4507
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
4508
                'action' => Security::remove_XSS($action),
4509
                'group_id' => Security::remove_XSS($_GET['group_id']),
4510
            ]
4511
        );
4512
        $table->set_header(
4513
            0,
4514
            get_lang('Type'),
4515
            true,
4516
            ['style' => 'width:30px;']
4517
        );
4518
        $table->set_header(1, get_lang('Title'));
4519
        $table->set_header(
4520
            2,
4521
            get_lang('Author').' <small>'.get_lang('LastVersion').'</small>'
4522
        );
4523
        $table->set_header(
4524
            3,
4525
            get_lang('Date').' <small>'.get_lang('LastVersion').'</small>'
4526
        );
4527
        if (api_is_allowed_to_session_edit(false, true)) {
4528
            $table->set_header(
4529
                4,
4530
                get_lang('Actions'),
4531
                false,
4532
                ['style' => 'width: 145px;']
4533
            );
4534
        }
4535
        $table->set_column_filter(
4536
            0,
4537
            function ($value, string $urlParams, array $row) {
4538
                $return = '';
4539
                //get type assignment icon
4540
                if (1 == $value) {
4541
                    $return .= Display::return_icon(
4542
                        'wiki_assignment.png',
4543
                        get_lang('AssignmentDesc'),
4544
                        '',
4545
                        ICON_SIZE_SMALL
4546
                    );
4547
                } elseif (2 == $value) {
4548
                    $return .= Display::return_icon(
4549
                        'wiki_work.png',
4550
                        get_lang('AssignmentWork'),
4551
                        '',
4552
                        ICON_SIZE_SMALL
4553
                    );
4554
                } elseif (0 == $value) {
4555
                    $return .= Display::return_icon(
4556
                        'px_transparent.gif'
4557
                    );
4558
                }
4559
4560
                //get icon task
4561
                if (!empty($row['task'])) {
4562
                    $return .= Display::return_icon(
4563
                        'wiki_task.png',
4564
                        get_lang('StandardTask'),
4565
                        '',
4566
                        ICON_SIZE_SMALL
4567
                    );
4568
                } else {
4569
                    $return .= Display::return_icon('px_transparent.gif');
4570
                }
4571
4572
                return $return;
4573
            }
4574
        );
4575
        $table->set_column_filter(
4576
            1,
4577
            function ($value) use ($_course) {
4578
                list($title, $refLink) = $value;
4579
4580
                return '<a href="'.api_get_self().'?cidReq='.$_course['code']
4581
                    .'&action=showpage&title='.api_htmlentities(urlencode($refLink))
4582
                    .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4583
                    .'&group_id='.api_htmlentities($_GET['group_id']).'">
4584
                    '.api_htmlentities($title).'</a>';
4585
            }
4586
        );
4587
        $table->set_column_filter(
4588
            2,
4589
            function ($value) {
4590
                list($userId, $userIp) = $value;
4591
                //get author
4592
                $userinfo = api_get_user_info($userId);
4593
4594
                if ($userinfo !== false) {
4595
                    return UserManager::getUserProfileLink($userinfo);
4596
                }
4597
4598
                return get_lang('Anonymous').' ('.api_htmlentities($userIp).')';
4599
            }
4600
        );
4601
        $table->set_column_filter(
4602
            3,
4603
            function ($value) {
4604
                return api_get_local_time($value);
4605
            }
4606
        );
4607
        $table->set_column_filter(
4608
            4,
4609
            function ($value) use ($_course) {
4610
                $actions = '';
4611
4612
                if (api_is_allowed_to_session_edit(false, true)) {
4613
                    $actions = '<a href="'.api_get_self(
4614
                        ).'?cidReq='.$_course['code']
4615
                        .'&action=edit&title='.api_htmlentities(urlencode($value))
4616
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4617
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4618
                        .Display::return_icon('edit.png', get_lang('EditPage'))
4619
                        .'</a> <a href="'.api_get_self().'?cidReq='.$_course['code']
4620
                        .'&action=discuss&title='.api_htmlentities(urlencode($value))
4621
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4622
                        .Display::return_icon('discuss.png', get_lang('Discuss'))
4623
                        .'</a> <a href="'.api_get_self().'?cidReq='.$_course['code']
4624
                        .'&action=history&title='.api_htmlentities(urlencode($value))
4625
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4626
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4627
                        .Display::return_icon('history.png', get_lang('History'))
4628
                        .'</a> <a href="'.api_get_self().'?cidReq='.$_course['code']
4629
                        .'&action=links&title='.api_htmlentities(urlencode($value))
4630
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '').'&group_id='
4631
                        .api_htmlentities($_GET['group_id']).'">'.
4632
                        Display::return_icon('what_link_here.png', get_lang('LinksPages')).'</a>';
4633
                }
4634
4635
                if (api_is_allowed_to_edit(
4636
                        false,
4637
                        true
4638
                    ) || api_is_platform_admin()) {
4639
                    $actions .= ' <a href="'.api_get_self().'?cidReq='.$_course['code']
4640
                        .'&action=delete&title='.api_htmlentities(urlencode($value))
4641
                        .'&session_id='.api_htmlentities($_GET['session_id'] ?? '')
4642
                        .'&group_id='.api_htmlentities($_GET['group_id']).'">'
4643
                        .Display::return_icon('delete.png', get_lang('Delete')).'</a>';
4644
                }
4645
4646
                return $actions;
4647
            }
4648
        );
4649
        $table->display();
4650
    }
4651
4652
    /**
4653
     * Get recent changes.
4654
     *
4655
     * @param string $page
4656
     * @param string $action
4657
     */
4658
    public function recentChanges($page, $action)
4659
    {
4660
        $tbl_wiki = $this->tbl_wiki;
4661
        $course_id = $this->course_id;
4662
        $condition_session = $this->condition_session;
4663
        $groupfilter = $this->groupfilter;
4664
        $tbl_wiki_conf = $this->tbl_wiki_conf;
4665
4666
        if (api_is_allowed_to_session_edit(false, true)) {
4667
            if (self::check_notify_all() == 1) {
4668
                $notify_all = Display::return_icon(
4669
                        'messagebox_info.png',
4670
                        get_lang('NotifyByEmail'),
4671
                        '',
4672
                        ICON_SIZE_SMALL
4673
                    ).' '.get_lang('NotNotifyChanges');
4674
                $lock_unlock_notify_all = 'unlocknotifyall';
4675
            } else {
4676
                $notify_all = Display::return_icon(
4677
                        'mail.png',
4678
                        get_lang('CancelNotifyByEmail'),
4679
                        '',
4680
                        ICON_SIZE_SMALL
4681
                    ).' '.get_lang('NotifyChanges');
4682
                $lock_unlock_notify_all = 'locknotifyall';
4683
            }
4684
        }
4685
4686
        echo '<div class="actions"><span style="float: right;">';
4687
        echo '<a href="index.php?action=recentchanges&actionpage='.$lock_unlock_notify_all.'&'.api_get_cidreq().'&title='.api_htmlentities(
4688
                urlencode($page)
4689
            ).'">'.$notify_all.'</a>';
4690
        echo '</span>'.get_lang('RecentChanges').'</div>';
4691
4692
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4693
            //only by professors if page is hidden
4694
            $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
4695
        		WHERE 	'.$tbl_wiki_conf.'.c_id= '.$course_id.' AND
4696
        				'.$tbl_wiki.'.c_id= '.$course_id.' AND
4697
        				'.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
4698
        				'.$tbl_wiki.'.'.$groupfilter.$condition_session.'
4699
        		ORDER BY dtime DESC'; // new version
4700
        } else {
4701
            $sql = 'SELECT *
4702
                FROM '.$tbl_wiki.'
4703
                WHERE
4704
                    c_id = '.$course_id.' AND
4705
                    '.$groupfilter.$condition_session.' AND
4706
                    visibility=1
4707
                ORDER BY dtime DESC';
4708
            // old version TODO: Replace by the bottom line
4709
        }
4710
4711
        $allpages = Database::query($sql);
4712
4713
        //show table
4714
        if (Database::num_rows($allpages) > 0) {
4715
            $rows = [];
4716
            while ($obj = Database::fetch_object($allpages)) {
4717
                //get author
4718
                $userinfo = api_get_user_info($obj->user_id);
4719
4720
                //get type assignment icon
4721
                if ($obj->assignment == 1) {
4722
                    $ShowAssignment = Display::return_icon(
4723
                        'wiki_assignment.png',
4724
                        get_lang('AssignmentDesc'),
4725
                        '',
4726
                        ICON_SIZE_SMALL
4727
                    );
4728
                } elseif ($obj->assignment == 2) {
4729
                    $ShowAssignment = Display::return_icon(
4730
                        'wiki_work.png',
4731
                        get_lang('AssignmentWork'),
4732
                        '',
4733
                        ICON_SIZE_SMALL
4734
                    );
4735
                } elseif ($obj->assignment == 0) {
4736
                    $ShowAssignment = Display::return_icon(
4737
                        'px_transparent.gif'
4738
                    );
4739
                }
4740
4741
                // Get icon task
4742
                if (!empty($obj->task)) {
4743
                    $icon_task = Display::return_icon(
4744
                        'wiki_task.png',
4745
                        get_lang('StandardTask'),
4746
                        '',
4747
                        ICON_SIZE_SMALL
4748
                    );
4749
                } else {
4750
                    $icon_task = Display::return_icon('px_transparent.gif');
4751
                }
4752
4753
                $row = [];
4754
                $row[] = api_get_local_time(
4755
                    $obj->dtime
4756
                );
4757
                $row[] = $ShowAssignment.$icon_task;
4758
                $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
4759
                    ).'&action=showpage&title='.api_htmlentities(
4760
                        urlencode($obj->reflink)
4761
                    ).'&view='.$obj->id.'&session_id='.api_get_session_id(
4762
                    ).'&group_id='.api_get_group_id().'">'.
4763
                    api_htmlentities($obj->title).'</a>';
4764
                $row[] = $obj->version > 1 ? get_lang('EditedBy') : get_lang(
4765
                    'AddedBy'
4766
                );
4767
                if ($userinfo !== false) {
4768
                    $row[] = UserManager::getUserProfileLink($userinfo);
4769
                } else {
4770
                    $row[] = get_lang('Anonymous').' ('.api_htmlentities(
4771
                            $obj->user_ip
4772
                        ).')';
4773
                }
4774
                $rows[] = $row;
4775
            }
4776
4777
            $table = new SortableTableFromArrayConfig(
4778
                $rows,
4779
                0,
4780
                10,
4781
                'RecentPages_table',
4782
                '',
4783
                '',
4784
                'DESC'
4785
            );
4786
            $table->set_additional_parameters(
4787
                [
4788
                    'cidReq' => api_get_course_id(),
4789
                    'action' => Security::remove_XSS($action),
4790
                    'session_id' => api_get_session_id(),
4791
                    'group_id' => api_get_group_id(),
4792
                ]
4793
            );
4794
            $table->set_header(
4795
                0,
4796
                get_lang('Date'),
4797
                true,
4798
                ['style' => 'width:200px;']
4799
            );
4800
            $table->set_header(
4801
                1,
4802
                get_lang('Type'),
4803
                true,
4804
                ['style' => 'width:30px;']
4805
            );
4806
            $table->set_header(2, get_lang('Title'), true);
4807
            $table->set_header(
4808
                3,
4809
                get_lang('Actions'),
4810
                true,
4811
                ['style' => 'width:80px;']
4812
            );
4813
            $table->set_header(4, get_lang('Author'), true);
4814
            $table->display();
4815
        }
4816
    }
4817
4818
    /**
4819
     * What links here. Show pages that have linked this page.
4820
     *
4821
     * @param string $page
4822
     */
4823
    public function getLinks($page)
4824
    {
4825
        $tbl_wiki = $this->tbl_wiki;
4826
        $course_id = $this->course_id;
4827
        $condition_session = $this->condition_session;
4828
        $groupfilter = $this->groupfilter;
4829
        $_course = $this->courseInfo;
4830
        $action = $this->action;
4831
4832
        if (!$_GET['title']) {
4833
            Display::addFlash(
4834
                Display::return_message(
4835
                    get_lang("MustSelectPage"),
4836
                    'error',
4837
                    false
4838
                )
4839
            );
4840
        } else {
4841
            $sql = 'SELECT * FROM '.$tbl_wiki.'
4842
                    WHERE
4843
                        c_id = '.$course_id.' AND
4844
                        reflink="'.Database::escape_string($page).'" AND
4845
                        '.$groupfilter.$condition_session;
4846
            $result = Database::query($sql);
4847
            $row = Database::fetch_array($result);
4848
4849
            //get type assignment icon
4850
            $ShowAssignment = '';
4851
            if ($row['assignment'] == 1) {
4852
                $ShowAssignment = Display::return_icon(
4853
                    'wiki_assignment.png',
4854
                    get_lang('AssignmentDesc'),
4855
                    '',
4856
                    ICON_SIZE_SMALL
4857
                );
4858
            } elseif ($row['assignment'] == 2) {
4859
                $ShowAssignment = Display::return_icon(
4860
                    'wiki_work.png',
4861
                    get_lang('AssignmentWork'),
4862
                    '',
4863
                    ICON_SIZE_SMALL
4864
                );
4865
            } elseif ($row['assignment'] == 0) {
4866
                $ShowAssignment = Display::return_icon('px_transparent.gif');
4867
            }
4868
4869
            //fix Title to reflink (link Main Page)
4870
            if ($page == get_lang('DefaultTitle')) {
4871
                $page = 'index';
4872
            }
4873
4874
            echo '<div id="wikititle">';
4875
            echo get_lang(
4876
                    'LinksPagesFrom'
4877
                ).': '.$ShowAssignment.' <a href="'.api_get_self(
4878
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4879
                    urlencode($page)
4880
                ).'&session_id='.api_htmlentities(
4881
                    $_GET['session_id']
4882
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4883
                api_htmlentities($row['title']).'</a>';
4884
            echo '</div>';
4885
4886
            //fix index to title Main page into linksto
4887
4888
            if ($page == 'index') {
4889
                $page = str_replace(' ', '_', get_lang('DefaultTitle'));
4890
            }
4891
4892
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4893
                // only by professors if page is hidden
4894
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4895
                        WHERE s1.c_id = $course_id AND linksto LIKE '%".Database::escape_string(
4896
                        $page
4897
                    )."%' AND id=(
4898
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4899
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4900
            } else {
4901
                //add blank space after like '%" " %' to identify each word
4902
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4903
                        WHERE s1.c_id = $course_id AND visibility=1 AND linksto LIKE '%".Database::escape_string(
4904
                        $page
4905
                    )."%' AND id=(
4906
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4907
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4908
            }
4909
4910
            $allpages = Database::query($sql);
4911
4912
            //show table
4913
            if (Database::num_rows($allpages) > 0) {
4914
                $rows = [];
4915
                while ($obj = Database::fetch_object($allpages)) {
4916
                    //get author
4917
                    $userinfo = api_get_user_info($obj->user_id);
4918
4919
                    //get time
4920
                    $year = substr($obj->dtime, 0, 4);
4921
                    $month = substr($obj->dtime, 5, 2);
4922
                    $day = substr($obj->dtime, 8, 2);
4923
                    $hours = substr($obj->dtime, 11, 2);
4924
                    $minutes = substr($obj->dtime, 14, 2);
4925
                    $seconds = substr($obj->dtime, 17, 2);
4926
4927
                    //get type assignment icon
4928
                    if ($obj->assignment == 1) {
4929
                        $ShowAssignment = Display::return_icon(
4930
                            'wiki_assignment.png',
4931
                            get_lang('AssignmentDesc'),
4932
                            '',
4933
                            ICON_SIZE_SMALL
4934
                        );
4935
                    } elseif ($obj->assignment == 2) {
4936
                        $ShowAssignment = Display::return_icon(
4937
                            'wiki_work.png',
4938
                            get_lang('AssignmentWork'),
4939
                            '',
4940
                            ICON_SIZE_SMALL
4941
                        );
4942
                    } elseif ($obj->assignment == 0) {
4943
                        $ShowAssignment = Display::return_icon(
4944
                            'px_transparent.gif'
4945
                        );
4946
                    }
4947
4948
                    $row = [];
4949
                    $row[] = $ShowAssignment;
4950
                    $row[] = '<a href="'.api_get_self(
4951
                        ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4952
                            urlencode($obj->reflink)
4953
                        ).'&session_id='.api_htmlentities(
4954
                            $_GET['session_id']
4955
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4956
                        api_htmlentities($obj->title).'</a>';
4957
                    if ($userinfo !== false) {
4958
                        $row[] = UserManager::getUserProfileLink($userinfo);
4959
                    } else {
4960
                        $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
4961
                    }
4962
                    $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
4963
                    $rows[] = $row;
4964
                }
4965
4966
                $table = new SortableTableFromArrayConfig(
4967
                    $rows,
4968
                    1,
4969
                    10,
4970
                    'AllPages_table',
4971
                    '',
4972
                    '',
4973
                    'ASC'
4974
                );
4975
                $table->set_additional_parameters(
4976
                    [
4977
                        'cidReq' => Security::remove_XSS($_GET['cidReq']),
4978
                        'action' => Security::remove_XSS($action),
4979
                        'group_id' => intval($_GET['group_id']),
4980
                    ]
4981
                );
4982
                $table->set_header(
4983
                    0,
4984
                    get_lang('Type'),
4985
                    true,
4986
                    ['style' => 'width:30px;']
4987
                );
4988
                $table->set_header(1, get_lang('Title'), true);
4989
                $table->set_header(2, get_lang('Author'), true);
4990
                $table->set_header(3, get_lang('Date'), true);
4991
                $table->display();
4992
            }
4993
        }
4994
    }
4995
4996
    /**
4997
     * @param string $action
4998
     */
4999
    public function getSearchPages($action)
5000
    {
5001
        echo '<div class="actions">'.get_lang('SearchPages').'</div>';
5002
        if (isset($_GET['mode_table'])) {
5003
            if (!isset($_GET['SearchPages_table_page_nr'])) {
5004
                $_GET['search_term'] = isset($_POST['search_term']) ? $_POST['search_term'] : '';
5005
                $_GET['search_content'] = isset($_POST['search_content']) ? $_POST['search_content'] : '';
5006
                $_GET['all_vers'] = isset($_POST['all_vers']) ? $_POST['all_vers'] : '';
5007
            }
5008
            self::display_wiki_search_results(
5009
                $_GET['search_term'],
5010
                $_GET['search_content'],
5011
                $_GET['all_vers']
5012
            );
5013
        } else {
5014
            // initiate the object
5015
            $form = new FormValidator(
5016
                'wiki_search',
5017
                'post',
5018
                api_get_self().'?cidReq='.api_get_course_id(
5019
                ).'&action='.api_htmlentities(
5020
                    $action
5021
                ).'&session_id='.api_get_session_id(
5022
                ).'&group_id='.api_get_group_id().'&mode_table=yes1'
5023
            );
5024
5025
            // Setting the form elements
5026
5027
            $form->addText(
5028
                'search_term',
5029
                get_lang('SearchTerm'),
5030
                true,
5031
                ['autofocus' => 'autofocus']
5032
            );
5033
            $form->addElement(
5034
                'checkbox',
5035
                'search_content',
5036
                null,
5037
                get_lang('AlsoSearchContent')
5038
            );
5039
            $form->addElement(
5040
                'checkbox',
5041
                'all_vers',
5042
                null,
5043
                get_lang('IncludeAllVersions')
5044
            );
5045
            $form->addButtonSearch(get_lang('Search'), 'SubmitWikiSearch');
5046
5047
            // setting the rules
5048
            $form->addRule(
5049
                'search_term',
5050
                get_lang('TooShort'),
5051
                'minlength',
5052
                3
5053
            ); //TODO: before fixing the pagination rules worked, not now
5054
5055
            if ($form->validate()) {
5056
                $form->display();
5057
                $values = $form->exportValues();
5058
                self::display_wiki_search_results(
5059
                    $values['search_term'],
5060
                    $values['search_content'],
5061
                    $values['all_vers']
5062
                );
5063
            } else {
5064
                $form->display();
5065
            }
5066
        }
5067
    }
5068
5069
    /**
5070
     * @param int    $userId
5071
     * @param string $action
5072
     */
5073
    public function getUserContributions($userId, $action)
5074
    {
5075
        $_course = $this->courseInfo;
5076
        $tbl_wiki = $this->tbl_wiki;
5077
        $course_id = $this->course_id;
5078
        $condition_session = $this->condition_session;
5079
        $groupfilter = $this->groupfilter;
5080
        $userId = intval($userId);
5081
        $userinfo = api_get_user_info($userId);
5082
        if ($userinfo !== false) {
5083
            echo '<div class="actions">'.
5084
                get_lang('UserContributions').': '.UserManager::getUserProfileLink($userinfo).
5085
                '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.$userId.
5086
                '&session_id='.$this->session_id.'&group_id='.$this->group_id.'">'.
5087
                '</a></div>';
5088
        }
5089
5090
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5091
            //only by professors if page is hidden
5092
            $sql = 'SELECT * FROM '.$tbl_wiki.'
5093
                    WHERE
5094
                        c_id = '.$course_id.' AND
5095
                        '.$groupfilter.$condition_session.' AND
5096
                        user_id="'.$userId.'"';
5097
        } else {
5098
            $sql = 'SELECT * FROM '.$tbl_wiki.'
5099
                    WHERE
5100
                        c_id = '.$course_id.' AND
5101
                        '.$groupfilter.$condition_session.' AND
5102
                        user_id="'.$userId.'" AND
5103
                        visibility=1';
5104
        }
5105
5106
        $allpages = Database::query($sql);
5107
5108
        //show table
5109
        if (Database::num_rows($allpages) > 0) {
5110
            $rows = [];
5111
            while ($obj = Database::fetch_object($allpages)) {
5112
                //get type assignment icon
5113
                $ShowAssignment = '';
5114
                if ($obj->assignment == 1) {
5115
                    $ShowAssignment = Display::return_icon(
5116
                        'wiki_assignment.png',
5117
                        get_lang('AssignmentDescExtra'),
5118
                        '',
5119
                        ICON_SIZE_SMALL
5120
                    );
5121
                } elseif ($obj->assignment == 2) {
5122
                    $ShowAssignment = Display::return_icon(
5123
                        'wiki_work.png',
5124
                        get_lang('AssignmentWork'),
5125
                        '',
5126
                        ICON_SIZE_SMALL
5127
                    );
5128
                } elseif ($obj->assignment == 0) {
5129
                    $ShowAssignment = Display::return_icon(
5130
                        'px_transparent.gif'
5131
                    );
5132
                }
5133
5134
                $row = [];
5135
                $row[] = api_get_local_time($obj->dtime);
5136
                $row[] = $ShowAssignment;
5137
                $row[] = '<a href="'.api_get_self(
5138
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5139
                        urlencode($obj->reflink)
5140
                    ).'&view='.$obj->id.'&session_id='.api_get_session_id(
5141
                    ).'&group_id='.api_get_group_id().'">'.
5142
                    api_htmlentities($obj->title).'</a>';
5143
                $row[] = Security::remove_XSS($obj->version);
5144
                $row[] = Security::remove_XSS($obj->comment);
5145
                $row[] = Security::remove_XSS($obj->progress).' %';
5146
                $row[] = Security::remove_XSS($obj->score);
5147
                $rows[] = $row;
5148
            }
5149
5150
            $table = new SortableTableFromArrayConfig(
5151
                $rows,
5152
                2,
5153
                10,
5154
                'UsersContributions_table',
5155
                '',
5156
                '',
5157
                'ASC'
5158
            );
5159
            $table->set_additional_parameters(
5160
                [
5161
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5162
                    'action' => Security::remove_XSS($action),
5163
                    'user_id' => intval($userId),
5164
                    'session_id' => intval($_GET['session_id']),
5165
                    'group_id' => intval($_GET['group_id']),
5166
                ]
5167
            );
5168
            $table->set_header(
5169
                0,
5170
                get_lang('Date'),
5171
                true,
5172
                ['style' => 'width:200px;']
5173
            );
5174
            $table->set_header(
5175
                1,
5176
                get_lang('Type'),
5177
                true,
5178
                ['style' => 'width:30px;']
5179
            );
5180
            $table->set_header(
5181
                2,
5182
                get_lang('Title'),
5183
                true,
5184
                ['style' => 'width:200px;']
5185
            );
5186
            $table->set_header(
5187
                3,
5188
                get_lang('Version'),
5189
                true,
5190
                ['style' => 'width:30px;']
5191
            );
5192
            $table->set_header(
5193
                4,
5194
                get_lang('Comment'),
5195
                true,
5196
                ['style' => 'width:200px;']
5197
            );
5198
            $table->set_header(
5199
                5,
5200
                get_lang('Progress'),
5201
                true,
5202
                ['style' => 'width:30px;']
5203
            );
5204
            $table->set_header(
5205
                6,
5206
                get_lang('Rating'),
5207
                true,
5208
                ['style' => 'width:30px;']
5209
            );
5210
            $table->display();
5211
        }
5212
    }
5213
5214
    /**
5215
     * @param string $action
5216
     */
5217
    public function getMostChangedPages($action)
5218
    {
5219
        $_course = $this->courseInfo;
5220
        $tbl_wiki = $this->tbl_wiki;
5221
        $course_id = $this->course_id;
5222
        $condition_session = $this->condition_session;
5223
        $groupfilter = $this->groupfilter;
5224
5225
        echo '<div class="actions">'.get_lang('MostChangedPages').'</div>';
5226
5227
        if (api_is_allowed_to_edit(false, true) ||
5228
            api_is_platform_admin()
5229
        ) { //only by professors if page is hidden
5230
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
5231
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5232
                    GROUP BY reflink'; //TODO:check MAX and group by return last version
5233
        } else {
5234
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
5235
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND visibility=1
5236
                    GROUP BY reflink'; //TODO:check MAX and group by return last version
5237
        }
5238
5239
        $allpages = Database::query($sql);
5240
5241
        //show table
5242
        if (Database::num_rows($allpages) > 0) {
5243
            $rows = [];
5244
            while ($obj = Database::fetch_object($allpages)) {
5245
                //get type assignment icon
5246
                $ShowAssignment = '';
5247
                if ($obj->assignment == 1) {
5248
                    $ShowAssignment = Display::return_icon(
5249
                        'wiki_assignment.png',
5250
                        get_lang('AssignmentDesc'),
5251
                        '',
5252
                        ICON_SIZE_SMALL
5253
                    );
5254
                } elseif ($obj->assignment == 2) {
5255
                    $ShowAssignment = Display::return_icon(
5256
                        'wiki_work.png',
5257
                        get_lang('AssignmentWork'),
5258
                        '',
5259
                        ICON_SIZE_SMALL
5260
                    );
5261
                } elseif ($obj->assignment == 0) {
5262
                    $ShowAssignment = Display::return_icon(
5263
                        'px_transparent.gif'
5264
                    );
5265
                }
5266
5267
                $row = [];
5268
                $row[] = $ShowAssignment;
5269
                $row[] = '<a href="'.api_get_self(
5270
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5271
                        urlencode($obj->reflink)
5272
                    ).'&session_id='.api_htmlentities(
5273
                        $_GET['session_id']
5274
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5275
                    api_htmlentities($obj->title).'</a>';
5276
                $row[] = $obj->MAX;
5277
                $rows[] = $row;
5278
            }
5279
5280
            $table = new SortableTableFromArrayConfig(
5281
                $rows,
5282
                2,
5283
                10,
5284
                'MostChangedPages_table',
5285
                '',
5286
                '',
5287
                'DESC'
5288
            );
5289
            $table->set_additional_parameters(
5290
                [
5291
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5292
                    'action' => Security::remove_XSS($action),
5293
                    'session_id' => intval($_GET['session_id']),
5294
                    'group_id' => intval($_GET['group_id']),
5295
                ]
5296
            );
5297
            $table->set_header(
5298
                0,
5299
                get_lang('Type'),
5300
                true,
5301
                ['style' => 'width:30px;']
5302
            );
5303
            $table->set_header(1, get_lang('Title'), true);
5304
            $table->set_header(2, get_lang('Changes'), true);
5305
            $table->display();
5306
        }
5307
    }
5308
5309
    /**
5310
     * Restore page.
5311
     *
5312
     * @return bool
5313
     */
5314
    public function restorePage()
5315
    {
5316
        $userId = api_get_user_id();
5317
        $_course = $this->courseInfo;
5318
        $current_row = $this->getWikiData();
5319
        $last_row = $this->getLastWikiData($this->page);
5320
5321
        if (empty($last_row)) {
5322
            return false;
5323
        }
5324
5325
        $PassEdit = false;
5326
5327
        /* Only teachers and platform admin can edit the index page.
5328
        Only teachers and platform admin can edit an assignment teacher*/
5329
        if (($current_row['reflink'] == 'index' ||
5330
                $current_row['reflink'] == '' ||
5331
                $current_row['assignment'] == 1) &&
5332
            (!api_is_allowed_to_edit(false, true) &&
5333
                $this->group_id == 0)
5334
        ) {
5335
            Display::addFlash(
5336
                Display::return_message(
5337
                    get_lang('OnlyEditPagesCourseManager'),
5338
                    'normal',
5339
                    false
5340
                )
5341
            );
5342
        } else {
5343
            // check if is a wiki group
5344
            if ($current_row['group_id'] != 0) {
5345
                $groupInfo = GroupManager::get_group_properties(
5346
                    $this->group_id
5347
                );
5348
                //Only teacher, platform admin and group members can edit a wiki group
5349
                if (api_is_allowed_to_edit(false, true) ||
5350
                    api_is_platform_admin() ||
5351
                    GroupManager::is_user_in_group($userId, $groupInfo) ||
5352
                    api_is_allowed_in_course()
5353
                ) {
5354
                    $PassEdit = true;
5355
                } else {
5356
                    Display::addFlash(
5357
                        Display::return_message(
5358
                            get_lang('OnlyEditPagesGroupMembers'),
5359
                            'normal',
5360
                            false
5361
                        )
5362
                    );
5363
                }
5364
            } else {
5365
                $PassEdit = true;
5366
            }
5367
5368
            // check if is an assignment
5369
            //$icon_assignment = null;
5370
            if ($current_row['assignment'] == 1) {
5371
                Display::addFlash(
5372
                    Display::return_message(
5373
                        get_lang('EditAssignmentWarning'),
5374
                        'normal',
5375
                        false
5376
                    )
5377
                );
5378
            } elseif ($current_row['assignment'] == 2) {
5379
                if (($userId == $current_row['user_id']) == false) {
5380
                    if (api_is_allowed_to_edit(
5381
                            false,
5382
                            true
5383
                        ) || api_is_platform_admin()) {
5384
                        $PassEdit = true;
5385
                    } else {
5386
                        Display::addFlash(
5387
                            Display::return_message(
5388
                                get_lang('LockByTeacher'),
5389
                                'normal',
5390
                                false
5391
                            )
5392
                        );
5393
                        $PassEdit = false;
5394
                    }
5395
                } else {
5396
                    $PassEdit = true;
5397
                }
5398
            }
5399
5400
            //show editor if edit is allowed
5401
            if ($PassEdit) {
5402
                if ($current_row['editlock'] == 1 &&
5403
                    (api_is_allowed_to_edit(false, true) == false ||
5404
                        api_is_platform_admin() == false)
5405
                ) {
5406
                    Display::addFlash(
5407
                        Display::return_message(
5408
                            get_lang('PageLockedExtra'),
5409
                            'normal',
5410
                            false
5411
                        )
5412
                    );
5413
                } else {
5414
                    if ($last_row['is_editing'] != 0 && $last_row['is_editing'] != $userId) {
5415
                        // Checking for concurrent users
5416
                        $timestamp_edit = strtotime($last_row['time_edit']);
5417
                        $time_editing = time() - $timestamp_edit;
5418
                        $max_edit_time = 1200; // 20 minutes
5419
                        $rest_time = $max_edit_time - $time_editing;
5420
                        $userinfo = api_get_user_info($last_row['is_editing']);
5421
                        $is_being_edited = get_lang(
5422
                                'ThisPageisBeginEditedBy'
5423
                            ).' <a href='.$userinfo['profile_url'].'>'.
5424
                            Display::tag(
5425
                                'span',
5426
                                $userinfo['complete_name_with_username']
5427
                            ).
5428
                            get_lang('ThisPageisBeginEditedTryLater').' '.date(
5429
                                "i",
5430
                                $rest_time
5431
                            ).' '.get_lang('MinMinutes');
5432
                        Display::addFlash(
5433
                            Display::return_message(
5434
                                $is_being_edited,
5435
                                'normal',
5436
                                false
5437
                            )
5438
                        );
5439
                    } else {
5440
                        Display::addFlash(
5441
                            Display::return_message(
5442
                                self::restore_wikipage(
5443
                                    $current_row['page_id'],
5444
                                    $current_row['reflink'],
5445
                                    $current_row['title'],
5446
                                    $current_row['content'],
5447
                                    $current_row['group_id'],
5448
                                    $current_row['assignment'],
5449
                                    $current_row['progress'],
5450
                                    $current_row['version'],
5451
                                    $last_row['version'],
5452
                                    $current_row['linksto']
5453
                                ).': <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5454
                                    urlencode($last_row['reflink'])
5455
                                ).'&session_id='.$last_row['session_id'].'&group_id='.$last_row['group_id'].'">'.
5456
                                api_htmlentities($last_row['title']).'</a>',
5457
                                'confirmation',
5458
                                false
5459
                            )
5460
                        );
5461
                    }
5462
                }
5463
            }
5464
        }
5465
    }
5466
5467
    /**
5468
     * @param int|bool $wikiId
5469
     */
5470
    public function setWikiData($wikiId)
5471
    {
5472
        $this->wikiData = self::getWikiDataFromDb($wikiId);
5473
    }
5474
5475
    /**
5476
     * @return array
5477
     */
5478
    public function getWikiData()
5479
    {
5480
        return $this->wikiData;
5481
    }
5482
5483
    /**
5484
     * Check last version.
5485
     *
5486
     * @param int $view
5487
     *
5488
     * @return bool
5489
     */
5490
    public function checkLastVersion($view)
5491
    {
5492
        $tbl_wiki = $this->tbl_wiki;
5493
        $course_id = $this->course_id;
5494
        $condition_session = $this->condition_session;
5495
        $groupfilter = $this->groupfilter;
5496
        $page = $this->page;
5497
        $_course = $this->courseInfo;
5498
5499
        if (empty($view)) {
5500
            return false;
5501
        }
5502
5503
        $current_row = $this->getWikiData();
5504
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5505
                WHERE
5506
                    c_id = '.$course_id.' AND
5507
                    reflink = "'.Database::escape_string($page).'" AND
5508
                    '.$groupfilter.$condition_session.'
5509
                ORDER BY id DESC'; //last version
5510
        $result = Database::query($sql);
5511
        $last_row = Database::fetch_array($result);
5512
5513
        if ($view < $last_row['id']) {
5514
            $message = '<center>'.get_lang('NoAreSeeingTheLastVersion').'<br />
5515
            '.get_lang("Version").' (
5516
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5517
                    urlencode($current_row['reflink'])
5518
                ).'&group_id='.$current_row['group_id'].'&session_id='.$current_row['session_id'].'&view='.api_htmlentities(
5519
                    $_GET['view']
5520
                ).'" title="'.get_lang('CurrentVersion').'">
5521
            '.$current_row['version'].'
5522
            </a> /
5523
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5524
                    urlencode($last_row['reflink'])
5525
                ).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'" title="'.get_lang(
5526
                    'LastVersion'
5527
                ).'">
5528
            '.$last_row['version'].'
5529
            </a>) <br />'.get_lang("ConvertToLastVersion").':
5530
            <a href="index.php?cidReq='.$_course['id'].'&action=restorepage&title='.api_htmlentities(
5531
                    urlencode($last_row['reflink'])
5532
                ).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'&view='.api_htmlentities(
5533
                    $_GET['view']
5534
                ).'">'.
5535
                get_lang("Restore").'</a></center>';
5536
            Display::addFlash(
5537
                Display::return_message($message, 'warning', false)
5538
            );
5539
        }
5540
    }
5541
5542
    /**
5543
     *  Get most linked pages.
5544
     */
5545
    public function getMostLinked()
5546
    {
5547
        $tbl_wiki = $this->tbl_wiki;
5548
        $course_id = $this->course_id;
5549
        $groupfilter = $this->groupfilter;
5550
        $condition_session = $this->condition_session;
5551
        $_course = $this->courseInfo;
5552
5553
        echo '<div class="actions">'.get_lang('MostLinkedPages').'</div>';
5554
        $pages = [];
5555
        $linked = [];
5556
5557
        // Get name pages
5558
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5559
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5560
                GROUP BY reflink
5561
                ORDER BY reflink ASC';
5562
        $allpages = Database::query($sql);
5563
        while ($row = Database::fetch_array($allpages)) {
5564
            if ($row['reflink'] == 'index') {
5565
                $row['reflink'] = str_replace(
5566
                    ' ',
5567
                    '_',
5568
                    get_lang('DefaultTitle')
5569
                );
5570
            }
5571
            $pages[] = $row['reflink'];
5572
        }
5573
5574
        // Get name refs in last pages
5575
        $sql = 'SELECT *
5576
                FROM '.$tbl_wiki.' s1
5577
                WHERE s1.c_id = '.$course_id.' AND id=(
5578
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5579
                    WHERE
5580
                        s2.c_id = '.$course_id.' AND
5581
                        s1.reflink = s2.reflink AND
5582
                        '.$groupfilter.$condition_session.'
5583
                )';
5584
5585
        $allpages = Database::query($sql);
5586
5587
        while ($row = Database::fetch_array($allpages)) {
5588
            //remove self reference
5589
            $row['linksto'] = str_replace(
5590
                $row["reflink"],
5591
                " ",
5592
                trim($row["linksto"])
5593
            );
5594
            $refs = explode(" ", trim($row["linksto"]));
5595
5596
            // Find linksto into reflink. If found ->page is linked
5597
            foreach ($refs as $v) {
5598
                if (in_array($v, $pages)) {
5599
                    if (trim($v) != "") {
5600
                        $linked[] = $v;
5601
                    }
5602
                }
5603
            }
5604
        }
5605
5606
        $linked = array_unique($linked);
5607
        //make a unique list. TODO:delete this line and count how many for each page
5608
        //show table
5609
        $rows = [];
5610
        foreach ($linked as $linked_show) {
5611
            $row = [];
5612
            $row[] = '<a href="'.api_get_self(
5613
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5614
                    urlencode(str_replace('_', ' ', $linked_show))
5615
                ).'&session_id='.api_htmlentities(
5616
                    $_GET['session_id']
5617
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5618
                str_replace('_', ' ', $linked_show).'</a>';
5619
            $rows[] = $row;
5620
        }
5621
5622
        $table = new SortableTableFromArrayConfig(
5623
            $rows,
5624
            0,
5625
            10,
5626
            'LinkedPages_table',
5627
            '',
5628
            '',
5629
            'DESC'
5630
        );
5631
        $table->set_additional_parameters(
5632
            [
5633
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5634
                'action' => Security::remove_XSS($this->action),
5635
                'session_id' => intval($_GET['session_id']),
5636
                'group_id' => intval($_GET['group_id']),
5637
            ]
5638
        );
5639
        $table->set_header(0, get_lang('Title'), true);
5640
        $table->display();
5641
    }
5642
5643
    /**
5644
     * Get orphan pages.
5645
     */
5646
    public function getOrphaned()
5647
    {
5648
        $tbl_wiki = $this->tbl_wiki;
5649
        $course_id = $this->course_id;
5650
        $groupfilter = $this->groupfilter;
5651
        $condition_session = $this->condition_session;
5652
        $_course = $this->courseInfo;
5653
5654
        echo '<div class="actions">'.get_lang('OrphanedPages').'</div>';
5655
5656
        $pages = [];
5657
        $orphaned = [];
5658
5659
        //get name pages
5660
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5661
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5662
                GROUP BY reflink
5663
                ORDER BY reflink ASC';
5664
        $allpages = Database::query($sql);
5665
        while ($row = Database::fetch_array($allpages)) {
5666
            $pages[] = $row['reflink'];
5667
        }
5668
5669
        //get name refs in last pages and make a unique list
5670
        $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1
5671
                WHERE s1.c_id = '.$course_id.' AND id=(
5672
                SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5673
                WHERE
5674
                    s2.c_id = '.$course_id.' AND
5675
                    s1.reflink = s2.reflink AND
5676
                    '.$groupfilter.$condition_session.'
5677
                )';
5678
        $allpages = Database::query($sql);
5679
        $array_refs_linked = [];
5680
        while ($row = Database::fetch_array($allpages)) {
5681
            $row['linksto'] = str_replace(
5682
                $row["reflink"],
5683
                " ",
5684
                trim($row["linksto"])
5685
            ); //remove self reference
5686
            $refs = explode(" ", trim($row["linksto"]));
5687
            foreach ($refs as $ref_linked) {
5688
                if ($ref_linked == str_replace(
5689
                        ' ',
5690
                        '_',
5691
                        get_lang('DefaultTitle')
5692
                    )) {
5693
                    $ref_linked = 'index';
5694
                }
5695
                $array_refs_linked[] = $ref_linked;
5696
            }
5697
        }
5698
5699
        $array_refs_linked = array_unique($array_refs_linked);
5700
5701
        //search each name of list linksto into list reflink
5702
        foreach ($pages as $v) {
5703
            if (!in_array($v, $array_refs_linked)) {
5704
                $orphaned[] = $v;
5705
            }
5706
        }
5707
        $rows = [];
5708
        foreach ($orphaned as $orphaned_show) {
5709
            // get visibility status and title
5710
            $sql = 'SELECT *
5711
                    FROM  '.$tbl_wiki.'
5712
		            WHERE
5713
		                c_id = '.$course_id.' AND
5714
		                '.$groupfilter.$condition_session.' AND
5715
		                reflink="'.Database::escape_string($orphaned_show).'"
5716
                    GROUP BY reflink';
5717
            $allpages = Database::query($sql);
5718
            while ($row = Database::fetch_array($allpages)) {
5719
                $orphaned_title = $row['title'];
5720
                $orphaned_visibility = $row['visibility'];
5721
                if ($row['assignment'] == 1) {
5722
                    $ShowAssignment = Display::return_icon(
5723
                        'wiki_assignment.png',
5724
                        '',
5725
                        '',
5726
                        ICON_SIZE_SMALL
5727
                    );
5728
                } elseif ($row['assignment'] == 2) {
5729
                    $ShowAssignment = Display::return_icon(
5730
                        'wiki_work.png',
5731
                        '',
5732
                        '',
5733
                        ICON_SIZE_SMALL
5734
                    );
5735
                } elseif ($row['assignment'] == 0) {
5736
                    $ShowAssignment = Display::return_icon(
5737
                        'px_transparent.gif'
5738
                    );
5739
                }
5740
            }
5741
5742
            if (!api_is_allowed_to_edit(false, true) || !api_is_platform_admin(
5743
                ) && $orphaned_visibility == 0) {
5744
                continue;
5745
            }
5746
5747
            //show table
5748
            $row = [];
5749
            $row[] = $ShowAssignment;
5750
            $row[] = '<a href="'.api_get_self(
5751
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5752
                    urlencode($orphaned_show)
5753
                ).'&session_id='.api_htmlentities(
5754
                    $_GET['session_id']
5755
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5756
                api_htmlentities($orphaned_title).'</a>';
5757
            $rows[] = $row;
5758
        }
5759
5760
        $table = new SortableTableFromArrayConfig(
5761
            $rows,
5762
            1,
5763
            10,
5764
            'OrphanedPages_table',
5765
            '',
5766
            '',
5767
            'DESC'
5768
        );
5769
        $table->set_additional_parameters(
5770
            [
5771
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5772
                'action' => Security::remove_XSS($this->action),
5773
                'session_id' => intval($_GET['session_id']),
5774
                'group_id' => intval($_GET['group_id']),
5775
            ]
5776
        );
5777
        $table->set_header(
5778
            0,
5779
            get_lang('Type'),
5780
            true,
5781
            ['style' => 'width:30px;']
5782
        );
5783
        $table->set_header(1, get_lang('Title'), true);
5784
        $table->display();
5785
    }
5786
5787
    /**
5788
     * Get wanted pages.
5789
     */
5790
    public function getWantedPages()
5791
    {
5792
        $tbl_wiki = $this->tbl_wiki;
5793
        $course_id = $this->course_id;
5794
        $groupfilter = $this->groupfilter;
5795
        $condition_session = $this->condition_session;
5796
5797
        echo '<div class="actions">'.get_lang('WantedPages').'</div>';
5798
        $pages = [];
5799
        $wanted = [];
5800
        //get name pages
5801
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5802
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5803
                GROUP BY reflink
5804
                ORDER BY reflink ASC';
5805
        $allpages = Database::query($sql);
5806
5807
        while ($row = Database::fetch_array($allpages)) {
5808
            if ($row['reflink'] == 'index') {
5809
                $row['reflink'] = str_replace(
5810
                    ' ',
5811
                    '_',
5812
                    get_lang('DefaultTitle')
5813
                );
5814
            }
5815
            $pages[] = $row['reflink'];
5816
        }
5817
5818
        //get name refs in last pages
5819
        $sql = 'SELECT * FROM   '.$tbl_wiki.' s1
5820
                WHERE s1.c_id = '.$course_id.' AND id=(
5821
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5822
                    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.$condition_session.'
5823
                )';
5824
5825
        $allpages = Database::query($sql);
5826
5827
        while ($row = Database::fetch_array($allpages)) {
5828
            $refs = explode(" ", trim($row["linksto"]));
5829
            // Find linksto into reflink. If not found ->page is wanted
5830
            foreach ($refs as $v) {
5831
                if (!in_array($v, $pages)) {
5832
                    if (trim($v) != "") {
5833
                        $wanted[] = $v;
5834
                    }
5835
                }
5836
            }
5837
        }
5838
5839
        $wanted = array_unique($wanted); //make a unique list
5840
5841
        //show table
5842
        $rows = [];
5843
        foreach ($wanted as $wanted_show) {
5844
            $row = [];
5845
            $wanted_show = Security::remove_XSS($wanted_show);
5846
            $row[] = '<a href="'.api_get_path(
5847
                    WEB_PATH
5848
                ).'main/wiki/index.php?cidReq=&action=addnew&title='.str_replace(
5849
                    '_',
5850
                    ' ',
5851
                    $wanted_show
5852
                ).'&session_id='.api_htmlentities(
5853
                    $_GET['session_id']
5854
                ).'&group_id='.api_htmlentities(
5855
                    $_GET['group_id']
5856
                ).'" class="new_wiki_link">'.str_replace(
5857
                    '_',
5858
                    ' ',
5859
                    $wanted_show
5860
                ).'</a>'; //meter un remove xss en lugar de htmlentities
5861
            $rows[] = $row;
5862
        }
5863
5864
        $table = new SortableTableFromArrayConfig(
5865
            $rows,
5866
            0,
5867
            10,
5868
            'WantedPages_table',
5869
            '',
5870
            '',
5871
            'DESC'
5872
        );
5873
        $table->set_additional_parameters(
5874
            [
5875
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5876
                'action' => Security::remove_XSS($this->action),
5877
                'session_id' => intval($_GET['session_id']),
5878
                'group_id' => intval($_GET['group_id']),
5879
            ]
5880
        );
5881
        $table->set_header(0, get_lang('Title'), true);
5882
        $table->display();
5883
    }
5884
5885
    /**
5886
     * Most visited.
5887
     */
5888
    public function getMostVisited()
5889
    {
5890
        $tbl_wiki = $this->tbl_wiki;
5891
        $course_id = $this->course_id;
5892
        $groupfilter = $this->groupfilter;
5893
        $condition_session = $this->condition_session;
5894
        $_course = $this->courseInfo;
5895
5896
        echo '<div class="actions">'.get_lang('MostVisitedPages').'</div>';
5897
5898
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin(
5899
            )) { //only by professors if page is hidden
5900
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5901
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5902
                    GROUP BY reflink';
5903
        } else {
5904
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5905
                    WHERE
5906
                        c_id = '.$course_id.' AND
5907
                        '.$groupfilter.$condition_session.' AND
5908
                        visibility=1
5909
                    GROUP BY reflink';
5910
        }
5911
5912
        $allpages = Database::query($sql);
5913
5914
        //show table
5915
        if (Database::num_rows($allpages) > 0) {
5916
            $rows = [];
5917
            while ($obj = Database::fetch_object($allpages)) {
5918
                //get type assignment icon
5919
                $ShowAssignment = '';
5920
                if ($obj->assignment == 1) {
5921
                    $ShowAssignment = Display::return_icon(
5922
                        'wiki_assignment.png',
5923
                        get_lang('AssignmentDesc'),
5924
                        '',
5925
                        ICON_SIZE_SMALL
5926
                    );
5927
                } elseif ($obj->assignment == 2) {
5928
                    $ShowAssignment = $ShowAssignment = Display::return_icon(
5929
                        'wiki_work.png',
5930
                        get_lang('AssignmentWork'),
5931
                        '',
5932
                        ICON_SIZE_SMALL
5933
                    );
5934
                } elseif ($obj->assignment == 0) {
5935
                    $ShowAssignment = Display::return_icon(
5936
                        'px_transparent.gif'
5937
                    );
5938
                }
5939
5940
                $row = [];
5941
                $row[] = $ShowAssignment;
5942
                $row[] = '<a href="'.api_get_self(
5943
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5944
                        urlencode($obj->reflink)
5945
                    ).'&session_id='.api_htmlentities(
5946
                        $_GET['session_id']
5947
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5948
                    api_htmlentities($obj->title).'</a>';
5949
                $row[] = $obj->tsum;
5950
                $rows[] = $row;
5951
            }
5952
5953
            $table = new SortableTableFromArrayConfig(
5954
                $rows,
5955
                2,
5956
                10,
5957
                'MostVisitedPages_table',
5958
                '',
5959
                '',
5960
                'DESC'
5961
            );
5962
            $table->set_additional_parameters(
5963
                [
5964
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5965
                    'action' => Security::remove_XSS($this->action),
5966
                    'session_id' => intval($_GET['session_id']),
5967
                    'group_id' => intval($_GET['group_id']),
5968
                ]
5969
            );
5970
            $table->set_header(
5971
                0,
5972
                get_lang('Type'),
5973
                true,
5974
                ['style' => 'width:30px;']
5975
            );
5976
            $table->set_header(1, get_lang('Title'), true);
5977
            $table->set_header(2, get_lang('Visits'), true);
5978
            $table->display();
5979
        }
5980
    }
5981
5982
    /**
5983
     * Get actions bar.
5984
     */
5985
    public function showActionBar()
5986
    {
5987
        $_course = $this->courseInfo;
5988
        $session_id = $this->session_id;
5989
        $groupId = $this->group_id;
5990
        $page = $this->page;
5991
        $actionsLeft = '<a href="index.php?action=showpage&title=index&cidReq='.$_course['id'].'&session_id='.$session_id.'&group_id='.$groupId.'">'.
5992
            Display::return_icon(
5993
                'home.png',
5994
                get_lang('Home'),
5995
                '',
5996
                ICON_SIZE_MEDIUM
5997
            ).'</a>';
5998
5999
        if (api_is_allowed_to_session_edit(false, true) && api_is_allowed_to_edit()) {
6000
            // menu add page
6001
            $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=addnew&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6002
                    'addnew'
6003
                ).'>'
6004
                .Display::return_icon(
6005
                    'new_document.png',
6006
                    get_lang('AddNew'),
6007
                    '',
6008
                    ICON_SIZE_MEDIUM
6009
                ).'</a>';
6010
        }
6011
6012
        $lock_unlock_addnew = null;
6013
        $protect_addnewpage = null;
6014
6015
        if (
6016
            true === api_get_configuration_value('wiki_categories_enabled')
6017
            && (api_is_allowed_to_edit(false, true) || api_is_platform_admin())
6018
        ) {
6019
            $actionsLeft .= Display::url(
6020
                Display::return_icon('folder.png', get_lang('Categories'), [], ICON_SIZE_MEDIUM),
6021
                'index.php?'.http_build_query([
6022
                    'cidReq' => $_course['id'],
6023
                    'session_id' => $session_id,
6024
                    'id_session' => $session_id,
6025
                    'group_id' => $groupId,
6026
                    'action' => 'category',
6027
                ])
6028
            );
6029
6030
            // page action: enable or disable the adding of new pages
6031
            if (self::check_addnewpagelock() == 0) {
6032
                $protect_addnewpage = Display::return_icon(
6033
                    'off.png',
6034
                    get_lang('AddOptionProtected')
6035
                );
6036
                $lock_unlock_addnew = 'unlockaddnew';
6037
            } else {
6038
                $protect_addnewpage = Display::return_icon(
6039
                    'on.png',
6040
                    get_lang('AddOptionUnprotected')
6041
                );
6042
                $lock_unlock_addnew = 'lockaddnew';
6043
            }
6044
        }
6045
6046
        // menu find
6047
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6048
                'searchpages'
6049
            ).'>'.
6050
            Display::return_icon(
6051
                'search.png',
6052
                get_lang('SearchPages'),
6053
                '',
6054
                ICON_SIZE_MEDIUM
6055
            ).'</a>';
6056
        ///menu more
6057
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'&action=more&title='.api_htmlentities(
6058
                urlencode($page)
6059
            ).'"'.self::is_active_navigation_tab('more').'>'.
6060
            Display::return_icon(
6061
                'statistics.png',
6062
                get_lang('Statistics'),
6063
                '',
6064
                ICON_SIZE_MEDIUM
6065
            ).'</a>';
6066
6067
        // menu all pages
6068
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=allpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6069
                'allpages'
6070
            ).'>'.
6071
            Display::return_icon(
6072
                'list_badges.png',
6073
                get_lang('AllPages'),
6074
                '',
6075
                ICON_SIZE_MEDIUM
6076
            ).'</a>';
6077
        // menu recent changes
6078
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=recentchanges&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6079
                'recentchanges'
6080
            ).'>'.
6081
            Display::return_icon(
6082
                'history.png',
6083
                get_lang('RecentChanges'),
6084
                '',
6085
                ICON_SIZE_MEDIUM
6086
            ).'</a>';
6087
        echo Display::toolbarAction('toolbar-wiki', [$actionsLeft]);
6088
    }
6089
6090
    /**
6091
     * Showing warning.
6092
     */
6093
    public function deletePageWarning()
6094
    {
6095
        $page = $this->page;
6096
        $course_id = $this->course_id;
6097
        $groupfilter = $this->groupfilter;
6098
        $condition_session = $this->condition_session;
6099
6100
        if (!$_GET['title']) {
6101
            Display::addFlash(
6102
                Display::return_message(
6103
                    get_lang('MustSelectPage'),
6104
                    'error',
6105
                    false
6106
                )
6107
            );
6108
6109
            return;
6110
        }
6111
6112
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6113
            Display::addFlash(
6114
                '<div id="wikititle">'.get_lang('DeletePageHistory').'</div>'
6115
            );
6116
            if ($page == "index") {
6117
                Display::addFlash(
6118
                    Display::return_message(
6119
                        get_lang('WarningDeleteMainPage'),
6120
                        'warning',
6121
                        false
6122
                    )
6123
                );
6124
            }
6125
            $message = get_lang('ConfirmDeletePage')."
6126
                <a href=\"index.php?".api_get_cidreq()."\">".get_lang("No")."</a>
6127
                <a href=\"".api_get_self()."?".api_get_cidreq(
6128
                )."&action=delete&title=".api_htmlentities(
6129
                    urlencode($page)
6130
                )."&delete=yes\">".
6131
                get_lang("Yes")."</a>";
6132
6133
            if (!isset($_GET['delete'])) {
6134
                Display::addFlash(
6135
                    Display::return_message($message, 'warning', false)
6136
                );
6137
            }
6138
6139
            if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
6140
                $result = self::deletePage(
6141
                    $page,
6142
                    $course_id,
6143
                    $groupfilter,
6144
                    $condition_session
6145
                );
6146
                if ($result) {
6147
                    Display::addFlash(
6148
                        Display::return_message(
6149
                            get_lang('WikiPageDeleted'),
6150
                            'confirmation',
6151
                            false
6152
                        )
6153
                    );
6154
                }
6155
            }
6156
        } else {
6157
            Display::addFlash(
6158
                Display::return_message(
6159
                    get_lang('OnlyAdminDeletePageWiki'),
6160
                    'normal',
6161
                    false
6162
                )
6163
            );
6164
        }
6165
    }
6166
6167
    /**
6168
     * Edit page.
6169
     */
6170
    public function editPage()
6171
    {
6172
        $tbl_wiki = $this->tbl_wiki;
6173
        $tbl_wiki_conf = $this->tbl_wiki_conf;
6174
        $condition_session = $this->condition_session;
6175
        $groupfilter = $this->groupfilter;
6176
        $page = $this->page;
6177
        $course_id = $this->course_id;
6178
        $groupId = $this->group_id;
6179
        $userId = api_get_user_id();
6180
6181
        if (api_get_session_id() != 0 &&
6182
            api_is_allowed_to_session_edit(false, true) == false
6183
        ) {
6184
            api_not_allowed();
6185
        }
6186
6187
        $sql = 'SELECT *
6188
            FROM '.$tbl_wiki.' w INNER JOIN '.$tbl_wiki_conf.' c
6189
            ON  (w.c_id = c.c_id AND w.page_id = c.page_id)
6190
            WHERE
6191
                w.c_id = '.$course_id.' AND
6192
                w.reflink= "'.Database::escape_string($page).'" AND
6193
                w.'.$groupfilter.$condition_session.'
6194
            ORDER BY id DESC';
6195
        $result = Database::query($sql);
6196
        $row = Database::fetch_array($result);
6197
6198
        $PassEdit = false;
6199
        // Check if is a wiki group
6200
        if (!empty($groupId)) {
6201
            $groupInfo = GroupManager::get_group_properties($groupId);
6202
            //Only teacher, platform admin and group members can edit a wiki group
6203
            if (api_is_allowed_to_edit(false, true) ||
6204
                api_is_platform_admin() ||
6205
                GroupManager::is_user_in_group($userId, $groupInfo)
6206
            ) {
6207
                $PassEdit = true;
6208
            } else {
6209
                Display::addFlash(
6210
                    Display::return_message(
6211
                        get_lang('OnlyEditPagesGroupMembers')
6212
                    )
6213
                );
6214
            }
6215
        } else {
6216
            $PassEdit = true;
6217
        }
6218
6219
        $content = '<div class="text-center">'
6220
            .sprintf(get_lang('DefaultContent'), api_get_path(WEB_IMG_PATH))
6221
            .'</div>';
6222
        $title = get_lang('DefaultTitle');
6223
        $page_id = 0;
6224
6225
        $icon_assignment = '';
6226
6227
        // we do not need awhile loop since we are always displaying the last version
6228
        if ($row) {
6229
            if ($row['content'] == '' && $row['title'] == '' && $page == '') {
6230
                Display::addFlash(
6231
                    Display::return_message(get_lang('MustSelectPage'), 'error', false)
6232
                );
6233
6234
                return;
6235
            }
6236
6237
            $content = api_html_entity_decode($row['content']);
6238
            $title = api_html_entity_decode($row['title']);
6239
            $page_id = $row['page_id'];
6240
6241
            // Only teachers and platform admin can edit the index page.
6242
            // Only teachers and platform admin can edit an assignment teacher.
6243
            // And users in groups
6244
6245
            if (($row['reflink'] == 'index' || $row['reflink'] == '' || $row['assignment'] == 1)
6246
                && (!api_is_allowed_to_edit(false, true) && $groupId == 0)
6247
                && !api_is_allowed_in_course()
6248
            ) {
6249
                Display::addFlash(
6250
                    Display::return_message(get_lang('OnlyEditPagesCourseManager'), 'error')
6251
                );
6252
6253
                return;
6254
            }
6255
6256
            // check if is an assignment
6257
            if ($row['assignment'] == 1) {
6258
                Display::addFlash(
6259
                    Display::return_message(get_lang('EditAssignmentWarning'))
6260
                );
6261
6262
                $icon_assignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'));
6263
            } elseif ($row['assignment'] == 2) {
6264
                $icon_assignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWorkExtra'));
6265
                if (($userId == $row['user_id']) == false) {
6266
                    if (api_is_allowed_to_edit(
6267
                            false,
6268
                            true
6269
                        ) || api_is_platform_admin()) {
6270
                        $PassEdit = true;
6271
                    } else {
6272
                        Display::addFlash(
6273
                            Display::return_message(get_lang('LockByTeacher'), 'warning')
6274
                        );
6275
                        $PassEdit = false;
6276
                    }
6277
                } else {
6278
                    $PassEdit = true;
6279
                }
6280
            }
6281
6282
            if ($PassEdit) {
6283
                if ($row['editlock'] == 1 &&
6284
                    (api_is_allowed_to_edit(false, true) == false ||
6285
                        api_is_platform_admin() == false)
6286
                ) {
6287
                    Display::addFlash(
6288
                        Display::return_message(get_lang('PageLockedExtra'))
6289
                    );
6290
                }
6291
            }
6292
        }
6293
6294
        if ($PassEdit) {
6295
            //show editor if edit is allowed <<<<<
6296
            if ($row['editlock'] != 1
6297
                || api_is_allowed_to_edit(false, true) != false
6298
                && api_is_platform_admin() != false
6299
            ) {
6300
                // Check tasks
6301
                if (!empty($row['startdate_assig']) && time() <
6302
                    api_strtotime($row['startdate_assig'])
6303
                ) {
6304
                    $message = get_lang('TheTaskDoesNotBeginUntil').': '.api_get_local_time($row['startdate_assig']);
6305
6306
                    Display::addFlash(
6307
                        Display::return_message($message, 'warning')
6308
                    );
6309
6310
                    if (!api_is_allowed_to_edit(false, true)) {
6311
                        $this->redirectHome();
6312
                    }
6313
                }
6314
6315
                if (!empty($row['enddate_assig']) &&
6316
                    time() > strtotime($row['enddate_assig']) &&
6317
                    $row['delayedsubmit'] == 0
6318
                ) {
6319
                    $message = get_lang('TheDeadlineHasBeenCompleted').': '.api_get_local_time($row['enddate_assig']);
6320
                    Display::addFlash(
6321
                        Display::return_message($message, 'warning')
6322
                    );
6323
                    if (!api_is_allowed_to_edit(false, true)) {
6324
                        $this->redirectHome();
6325
                    }
6326
                }
6327
6328
                if (!empty($row['max_version']) && $row['version'] >= $row['max_version']) {
6329
                    $message = get_lang('HasReachedMaxiNumVersions');
6330
                    Display::addFlash(
6331
                        Display::return_message($message, 'warning')
6332
                    );
6333
                    if (!api_is_allowed_to_edit(false, true)) {
6334
                        $this->redirectHome();
6335
                    }
6336
                }
6337
6338
                if (!empty($row['max_text']) && $row['max_text'] <= self::word_count(
6339
                        $row['content']
6340
                    )) {
6341
                    $message = get_lang('HasReachedMaxNumWords');
6342
                    Display::addFlash(
6343
                        Display::return_message($message, 'warning')
6344
                    );
6345
                    if (!api_is_allowed_to_edit(false, true)) {
6346
                        $this->redirectHome();
6347
                    }
6348
                }
6349
6350
                if (!empty($row['task'])) {
6351
                    //previous change 0 by text
6352
                    $message_task_startdate = empty($row['startdate_assig'])
6353
                        ? api_get_local_time($row['startdate_assig'])
6354
                        : get_lang('No');
6355
6356
                    $message_task_enddate = empty($row['enddate_assig'])
6357
                        ? api_get_local_time($row['enddate_assig'])
6358
                        : get_lang('No');
6359
6360
                    $message_task_delayedsubmit = $row['delayedsubmit'] == 0 ? get_lang('No') : get_lang('Yes');
6361
6362
                    $message_task_max_version = $row['max_version'] == 0 ? get_lang('No') : $row['max_version'];
6363
6364
                    $message_task_max_text = $row['max_text'] == 0 ? get_lang('No') : $row['max_text'];
6365
6366
                    // Comp message
6367
                    $message_task = '<b>'.get_lang('DescriptionOfTheTask').'</b><p>'.$row['task'].'</p><hr>'
6368
                        .'<p>'.get_lang('StartDate').': '.$message_task_startdate.'</p>'
6369
                        .'<p>'.get_lang('EndDate').': '.$message_task_enddate
6370
                        .' ('.get_lang('AllowLaterSends').') '.$message_task_delayedsubmit.'</p>'
6371
                        .'<p>'.get_lang('OtherSettings').': '.get_lang('NMaxVersion').': '.$message_task_max_version
6372
                        .' '.get_lang('NMaxWords').': '.$message_task_max_text.'</p>';
6373
                    // Display message
6374
                    Display::addFlash(
6375
                        Display::return_message($message_task)
6376
                    );
6377
                }
6378
6379
                $feedback_message = '';
6380
                if ($row['progress'] == $row['fprogress1'] && !empty($row['fprogress1'])) {
6381
                    $feedback_message = '<b>'.get_lang('Feedback').'</b>'
6382
                        .'<p>'.api_htmlentities($row['feedback1']).'</p>';
6383
                } elseif ($row['progress'] == $row['fprogress2'] && !empty($row['fprogress2'])) {
6384
                    $feedback_message = '<b>'.get_lang('Feedback').'</b>'
6385
                        .'<p>'.api_htmlentities($row['feedback2']).'</p>';
6386
                } elseif ($row['progress'] == $row['fprogress3'] && !empty($row['fprogress3'])) {
6387
                    $feedback_message = '<b>'.get_lang('Feedback').'</b>'
6388
                        .'<p>'.api_htmlentities($row['feedback3']).'</p>';
6389
                }
6390
6391
                if (!empty($feedback_message)) {
6392
                    Display::addFlash(
6393
                        Display::return_message($feedback_message)
6394
                    );
6395
                }
6396
6397
                // Previous checking for concurrent editions
6398
                if ($row['is_editing'] == 0) {
6399
                    Display::addFlash(
6400
                        Display::return_message(get_lang('WarningMaxEditingTime'))
6401
                    );
6402
                    $time_edit = api_get_utc_datetime();
6403
                    $sql = 'UPDATE '.$tbl_wiki.' SET
6404
                            is_editing = "'.$userId.'",
6405
                            time_edit = "'.$time_edit.'"
6406
                            WHERE c_id = '.$course_id.' AND id="'.$row['id'].'"';
6407
                    Database::query($sql);
6408
                } elseif ($row['is_editing'] != $userId) {
6409
                    $timestamp_edit = strtotime($row['time_edit']);
6410
                    $time_editing = time() - $timestamp_edit;
6411
                    $max_edit_time = 1200; // 20 minutes
6412
                    $rest_time = $max_edit_time - $time_editing;
6413
6414
                    $userinfo = api_get_user_info($row['is_editing']);
6415
                    if ($userinfo !== false) {
6416
                        $is_being_edited = get_lang('ThisPageisBeginEditedBy').PHP_EOL
6417
                            .UserManager::getUserProfileLink($userinfo).PHP_EOL
6418
                            .get_lang('ThisPageisBeginEditedTryLater').PHP_EOL
6419
                            .date("i", $rest_time).PHP_EOL
6420
                            .get_lang('MinMinutes');
6421
6422
                        Display::addFlash(
6423
                            Display::return_message($is_being_edited, 'normal', false)
6424
                        );
6425
                    }
6426
6427
                    $this->redirectHome();
6428
                }
6429
6430
                // Form.
6431
                $url = api_get_self().'?action=edit&title='.urlencode($page).'&session_id='.api_get_session_id()
6432
                    .'&group_id='.api_get_group_id().'&'.api_get_cidreq();
6433
                $form = new FormValidator('wiki', 'post', $url);
6434
                $form->addElement(
6435
                    'header',
6436
                    $icon_assignment.str_repeat('&nbsp;', 3).api_htmlentities($title)
6437
                );
6438
                self::setForm($form, $row);
6439
                $form->addElement('hidden', 'title');
6440
                $form->addButtonSave(get_lang('Save'), 'SaveWikiChange');
6441
                $row['title'] = $title;
6442
                $row['page_id'] = $page_id;
6443
                $row['reflink'] = $page;
6444
                $row['content'] = $content;
6445
6446
                if (true === api_get_configuration_value('wiki_categories_enabled')) {
6447
                    $wiki = Database::getManager()->find(CWiki::class, $row['id']);
6448
6449
                    foreach ($wiki->getCategories() as $category) {
6450
                        $row['category'][] = $category->getId();
6451
                    }
6452
                }
6453
6454
                $form->setDefaults($row);
6455
                $form->display();
6456
6457
                // Saving a change
6458
                if ($form->validate()) {
6459
                    $versionFromSession = Session::read('_version');
6460
                    if (empty($_POST['title'])) {
6461
                        Display::addFlash(
6462
                            Display::return_message(
6463
                                get_lang("NoWikiPageTitle"),
6464
                                'error'
6465
                            )
6466
                        );
6467
                    } elseif (!self::double_post($_POST['wpost_id'])) {
6468
                        //double post
6469
                    } elseif ($_POST['version'] != '' && $versionFromSession != 0 && $_POST['version'] != $versionFromSession) {
6470
                        //prevent concurrent users and double version
6471
                        Display::addFlash(
6472
                            Display::return_message(
6473
                                get_lang("EditedByAnotherUser"),
6474
                                'error'
6475
                            )
6476
                        );
6477
                    } else {
6478
                        $returnMessage = self::save_wiki(
6479
                            $form->exportValues()
6480
                        );
6481
                        Display::addFlash(
6482
                            Display::return_message(
6483
                                $returnMessage,
6484
                                'confirmation'
6485
                            )
6486
                        );
6487
                    }
6488
                    $wikiData = self::getWikiData();
6489
                    $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq();
6490
                    header('Location: '.$redirectUrl);
6491
                    exit;
6492
                }
6493
            }
6494
        }
6495
    }
6496
6497
    /**
6498
     * Get history.
6499
     */
6500
    public function getHistory()
6501
    {
6502
        $tbl_wiki = $this->tbl_wiki;
6503
        $condition_session = $this->condition_session;
6504
        $groupfilter = $this->groupfilter;
6505
        $page = $this->page;
6506
        $course_id = $this->course_id;
6507
        $session_id = $this->session_id;
6508
        $userId = api_get_user_id();
6509
6510
        if (!$_GET['title']) {
6511
            Display::addFlash(
6512
                Display::return_message(
6513
                    get_lang("MustSelectPage"),
6514
                    'error',
6515
                    false
6516
                )
6517
            );
6518
6519
            return;
6520
        }
6521
6522
        /* First, see the property visibility that is at the last register and
6523
        therefore we should select descending order.
6524
        But to give ownership to each record,
6525
        this is no longer necessary except for the title. TODO: check this*/
6526
6527
        $sql = 'SELECT * FROM '.$tbl_wiki.'
6528
                WHERE
6529
                    c_id = '.$course_id.' AND
6530
                    reflink="'.Database::escape_string($page).'" AND
6531
                    '.$groupfilter.$condition_session.'
6532
                ORDER BY id DESC';
6533
        $result = Database::query($sql);
6534
6535
        $KeyVisibility = null;
6536
        $KeyAssignment = null;
6537
        $KeyTitle = null;
6538
        $KeyUserId = null;
6539
        while ($row = Database::fetch_array($result)) {
6540
            $KeyVisibility = $row['visibility'];
6541
            $KeyAssignment = $row['assignment'];
6542
            $KeyTitle = $row['title'];
6543
            $KeyUserId = $row['user_id'];
6544
        }
6545
        $icon_assignment = null;
6546
        if ($KeyAssignment == 1) {
6547
            $icon_assignment = Display::return_icon(
6548
                'wiki_assignment.png',
6549
                get_lang('AssignmentDescExtra'),
6550
                '',
6551
                ICON_SIZE_SMALL
6552
            );
6553
        } elseif ($KeyAssignment == 2) {
6554
            $icon_assignment = Display::return_icon(
6555
                'wiki_work.png',
6556
                get_lang('AssignmentWorkExtra'),
6557
                '',
6558
                ICON_SIZE_SMALL
6559
            );
6560
        }
6561
6562
        // Second, show
6563
        //if the page is hidden and is a job only sees its author and professor
6564
        if ($KeyVisibility == 1 ||
6565
            api_is_allowed_to_edit(false, true) ||
6566
            api_is_platform_admin() ||
6567
            (
6568
                $KeyAssignment == 2 && $KeyVisibility == 0 &&
6569
                ($userId == $KeyUserId)
6570
            )
6571
        ) {
6572
            // We show the complete history
6573
            if (!isset($_POST['HistoryDifferences']) &&
6574
                !isset($_POST['HistoryDifferences2'])
6575
            ) {
6576
                $sql = 'SELECT * FROM '.$tbl_wiki.'
6577
                        WHERE
6578
                            c_id = '.$course_id.' AND
6579
                            reflink="'.Database::escape_string($page).'" AND
6580
                            '.$groupfilter.$condition_session.'
6581
                        ORDER BY id DESC';
6582
                $result = Database::query($sql);
6583
                $title = $_GET['title'];
6584
                $group_id = api_get_group_id();
6585
6586
                echo '<div id="wikititle">';
6587
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities(
6588
                        $KeyTitle
6589
                    );
6590
                echo '</div>';
6591
6592
                echo '<form id="differences" method="POST" action="index.php?'.api_get_cidreq(
6593
                    ).'&action=history&title='.api_htmlentities(
6594
                        urlencode($title)
6595
                    ).'&session_id='.api_htmlentities(
6596
                        $session_id
6597
                    ).'&group_id='.api_htmlentities($group_id).'">';
6598
6599
                echo '<ul style="list-style-type: none;">';
6600
                echo '<br/>';
6601
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.
6602
                    get_lang('ShowDifferences').' '.get_lang(
6603
                        'LinesDiff'
6604
                    ).'</button>';
6605
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.
6606
                    get_lang('ShowDifferences').' '.get_lang(
6607
                        'WordsDiff'
6608
                    ).'</button>';
6609
                echo '<br/><br/>';
6610
6611
                $counter = 0;
6612
                $total_versions = Database::num_rows($result);
6613
6614
                while ($row = Database::fetch_array($result)) {
6615
                    $userinfo = api_get_user_info($row['user_id']);
6616
                    $username = api_htmlentities(
6617
                        sprintf(get_lang('LoginX'), $userinfo['username']),
6618
                        ENT_QUOTES
6619
                    );
6620
6621
                    echo '<li style="margin-bottom: 5px;">';
6622
                    ($counter == 0) ? $oldstyle = 'style="visibility: hidden;"' : $oldstyle = '';
6623
                    ($counter == 0) ? $newchecked = ' checked' : $newchecked = '';
6624
                    ($counter == $total_versions - 1) ? $newstyle = 'style="visibility: hidden;"' : $newstyle = '';
6625
                    ($counter == 1) ? $oldchecked = ' checked' : $oldchecked = '';
6626
                    echo '<input name="old" value="'.$row['id'].'" type="radio" '.$oldstyle.' '.$oldchecked.'/> ';
6627
                    echo '<input name="new" value="'.$row['id'].'" type="radio" '.$newstyle.' '.$newchecked.'/> ';
6628
                    echo '<a href="'.api_get_self(
6629
                        ).'?action=showpage&title='.api_htmlentities(
6630
                            urlencode($page)
6631
                        ).'&view='.$row['id'].'">';
6632
                    echo '<a href="'.api_get_self().'?'.api_get_cidreq(
6633
                        ).'&action=showpage&title='.api_htmlentities(
6634
                            urlencode($page)
6635
                        ).'&view='.$row['id'].'">';
6636
                    echo api_get_local_time(
6637
                        $row['dtime']
6638
                    );
6639
                    echo '</a>';
6640
                    echo ' ('.get_lang('Version').' '.$row['version'].')';
6641
                    echo ' '.get_lang('By').' ';
6642
                    if ($userinfo !== false) {
6643
                        echo UserManager::getUserProfileLink($userinfo);
6644
                    } else {
6645
                        echo get_lang('Anonymous').' ('.api_htmlentities(
6646
                                $row['user_ip']
6647
                            ).')';
6648
                    }
6649
                    echo ' ( '.get_lang('Progress').': '.api_htmlentities(
6650
                            $row['progress']
6651
                        ).'%, ';
6652
                    $comment = $row['comment'];
6653
                    if (!empty($comment)) {
6654
                        $comment = api_substr($comment, 0, 100);
6655
                        if ($comment !== false) {
6656
                            $comment = api_htmlentities($comment);
6657
                            echo get_lang('Comments').': '.$comment;
6658
                            if (api_strlen($row['comment']) > 100) {
6659
                                echo '... ';
6660
                            }
6661
                        }
6662
                    } else {
6663
                        echo get_lang('Comments').':  ---';
6664
                    }
6665
                    echo ' ) </li>';
6666
                    $counter++;
6667
                } //end while
6668
6669
                echo '<br/>';
6670
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.get_lang(
6671
                        'ShowDifferences'
6672
                    ).' '.get_lang('LinesDiff').'</button>';
6673
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.get_lang(
6674
                        'ShowDifferences'
6675
                    ).' '.get_lang('WordsDiff').'</button>';
6676
                echo '</ul></form>';
6677
            } else { // We show the differences between two versions
6678
                $version_old = [];
6679
                if (isset($_POST['old'])) {
6680
                    $sql_old = "SELECT * FROM $tbl_wiki
6681
                                WHERE c_id = $course_id AND id='".Database::escape_string(
6682
                            $_POST['old']
6683
                        )."'";
6684
                    $result_old = Database::query($sql_old);
6685
                    $version_old = Database::fetch_array($result_old);
6686
                }
6687
6688
                $sql_new = "SELECT * FROM $tbl_wiki
6689
                            WHERE
6690
                              c_id = $course_id AND
6691
                              id = '".Database::escape_string($_POST['new'])."'";
6692
                $result_new = Database::query($sql_new);
6693
                $version_new = Database::fetch_array($result_new);
6694
                $oldTime = isset($version_old['dtime']) ? api_get_local_time($version_old['dtime']) : null;
6695
                $oldContent = isset($version_old['content']) ? $version_old['content'] : null;
6696
6697
                if (isset($_POST['HistoryDifferences'])) {
6698
                    include 'diff.inc.php';
6699
                    //title
6700
                    echo '<div id="wikititle">'.api_htmlentities(
6701
                            $version_new['title']
6702
                        ).'
6703
                            <font size="-2"><i>('.get_lang('DifferencesNew').'</i>
6704
                            <font style="background-color:#aaaaaa">'.api_get_local_time($version_new['dtime']).'</font>
6705
                            <i>'.get_lang('DifferencesOld').'</i>
6706
                            <font style="background-color:#aaaaaa">'.$oldTime.'</font>
6707
                ) '.get_lang('Legend').':  <span class="diffAdded" >'.get_lang(
6708
                            'WikiDiffAddedLine'
6709
                        ).'</span>
6710
                <span class="diffDeleted" >'.get_lang(
6711
                            'WikiDiffDeletedLine'
6712
                        ).'</span> <span class="diffMoved">'.get_lang(
6713
                            'WikiDiffMovedLine'
6714
                        ).'</span></font>
6715
                </div>';
6716
                }
6717
                if (isset($_POST['HistoryDifferences2'])) {
6718
                    //title
6719
                    echo '<div id="wikititle">'.api_htmlentities(
6720
                            $version_new['title']
6721
                        ).'
6722
                        <font size="-2"><i>('.get_lang(
6723
                            'DifferencesNew'
6724
                        ).'</i> <font style="background-color:#aaaaaa">'.api_get_local_time($version_new['dtime']).'</font>
6725
                        <i>'.get_lang(
6726
                            'DifferencesOld'
6727
                        ).'</i> <font style="background-color:#aaaaaa">'.$oldTime.'</font>)
6728
                        '.get_lang(
6729
                            'Legend'
6730
                        ).':  <span class="diffAddedTex" >'.get_lang(
6731
                            'WikiDiffAddedTex'
6732
                        ).'</span>
6733
                        <span class="diffDeletedTex" >'.get_lang(
6734
                            'WikiDiffDeletedTex'
6735
                        ).'</span></font></div>';
6736
                }
6737
6738
                if (isset($_POST['HistoryDifferences'])) {
6739
                    echo '<table>'.diff(
6740
                            $oldContent,
6741
                            $version_new['content'],
6742
                            true,
6743
                            'format_table_line'
6744
                        ).'</table>'; // format_line mode is better for words
6745
                    echo '<br />';
6746
                    echo '<strong>'.get_lang(
6747
                            'Legend'
6748
                        ).'</strong><div class="diff">'."\n";
6749
                    echo '<table><tr>';
6750
                    echo '<td>';
6751
                    echo '</td><td>';
6752
                    echo '<span class="diffEqual" >'.get_lang(
6753
                            'WikiDiffUnchangedLine'
6754
                        ).'</span><br />';
6755
                    echo '<span class="diffAdded" >'.get_lang(
6756
                            'WikiDiffAddedLine'
6757
                        ).'</span><br />';
6758
                    echo '<span class="diffDeleted" >'.get_lang(
6759
                            'WikiDiffDeletedLine'
6760
                        ).'</span><br />';
6761
                    echo '<span class="diffMoved" >'.get_lang(
6762
                            'WikiDiffMovedLine'
6763
                        ).'</span><br />';
6764
                    echo '</td>';
6765
                    echo '</tr></table>';
6766
                }
6767
6768
                if (isset($_POST['HistoryDifferences2'])) {
6769
                    $lines1 = [strip_tags($oldContent)]; //without <> tags
6770
                    $lines2 = [
6771
                        strip_tags(
6772
                            $version_new['content']
6773
                        ),
6774
                    ]; //without <> tags
6775
                    $diff = new Text_Diff($lines1, $lines2);
6776
                    $renderer = new Text_Diff_Renderer_inline();
6777
                    echo '<style>del{background:#fcc}ins{background:#cfc}</style>'.$renderer->render(
6778
                            $diff
6779
                        ); // Code inline
6780
                    echo '<br />';
6781
                    echo '<strong>'.get_lang(
6782
                            'Legend'
6783
                        ).'</strong><div class="diff">'."\n";
6784
                    echo '<table><tr>';
6785
                    echo '<td>';
6786
                    echo '</td><td>';
6787
                    echo '<span class="diffAddedTex" >'.get_lang(
6788
                            'WikiDiffAddedTex'
6789
                        ).'</span><br />';
6790
                    echo '<span class="diffDeletedTex" >'.get_lang(
6791
                            'WikiDiffDeletedTex'
6792
                        ).'</span><br />';
6793
                    echo '</td>';
6794
                    echo '</tr></table>';
6795
                }
6796
            }
6797
        }
6798
    }
6799
6800
    /**
6801
     * Get stat tables.
6802
     */
6803
    public function getStatsTable()
6804
    {
6805
        $_course = $this->courseInfo;
6806
        $session_id = $this->session_id;
6807
        $groupId = $this->group_id;
6808
6809
        echo '<div class="actions">'.get_lang('More').'</div>';
6810
        echo '<table border="0">';
6811
        echo '  <tr>';
6812
        echo '    <td>';
6813
        echo '      <ul>';
6814
        //Submenu Most active users
6815
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mactiveusers&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6816
                'MostActiveUsers'
6817
            ).'</a></li>';
6818
        //Submenu Most visited pages
6819
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mvisited&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6820
                'MostVisitedPages'
6821
            ).'</a></li>';
6822
        //Submenu Most changed pages
6823
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mostchanged&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6824
                'MostChangedPages'
6825
            ).'</a></li>';
6826
        echo '      </ul>';
6827
        echo '    </td>';
6828
        echo '    <td>';
6829
        echo '      <ul>';
6830
        // Submenu Orphaned pages
6831
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=orphaned&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6832
                'OrphanedPages'
6833
            ).'</a></li>';
6834
        // Submenu Wanted pages
6835
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=wanted&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6836
                'WantedPages'
6837
            ).'</a></li>';
6838
        // Submenu Most linked pages
6839
        echo '<li><a href="index.php?cidReq='.$_course['code'].'&action=mostlinked&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6840
                'MostLinkedPages'
6841
            ).'</a></li>';
6842
        echo '</ul>';
6843
        echo '</td>';
6844
        echo '<td style="vertical-align:top">';
6845
        echo '<ul>';
6846
        // Submenu Statistics
6847
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6848
            echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=statistics&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6849
                    'Statistics'
6850
                ).'</a></li>';
6851
        }
6852
        echo '      </ul>';
6853
        echo '    </td>';
6854
        echo '  </tr>';
6855
        echo '</table>';
6856
    }
6857
6858
    /**
6859
     * Kind of controller.
6860
     */
6861
    public function handleAction(string $action)
6862
    {
6863
        $page = $this->page;
6864
        switch ($action) {
6865
            case 'export_to_pdf':
6866
                if (isset($_GET['wiki_id'])) {
6867
                    self::export_to_pdf($_GET['wiki_id'], api_get_course_id());
6868
                    break;
6869
                }
6870
                break;
6871
            case 'export2doc':
6872
                if (isset($_GET['wiki_id'])) {
6873
                    $export2doc = self::export2doc($_GET['wiki_id']);
6874
                    if ($export2doc) {
6875
                        Display::addFlash(
6876
                            Display::return_message(
6877
                                get_lang('ThePageHasBeenExportedToDocArea'),
6878
                                'confirmation',
6879
                                false
6880
                            )
6881
                        );
6882
                    }
6883
                }
6884
                break;
6885
            case 'restorepage':
6886
                self::restorePage();
6887
                break;
6888
            case 'more':
6889
                self::getStatsTable();
6890
                break;
6891
            case 'statistics':
6892
                self::getStats();
6893
                break;
6894
            case 'mactiveusers':
6895
                self::getActiveUsers($action);
6896
                break;
6897
            case 'usercontrib':
6898
                self::getUserContributions($_GET['user_id'], $action);
6899
                break;
6900
            case 'mostchanged':
6901
                $this->getMostChangedPages($action);
6902
                break;
6903
            case 'mvisited':
6904
                self::getMostVisited();
6905
                break;
6906
            case 'wanted':
6907
                $this->getWantedPages();
6908
                break;
6909
            case 'orphaned':
6910
                self::getOrphaned();
6911
                break;
6912
            case 'mostlinked':
6913
                self::getMostLinked();
6914
                break;
6915
            case 'delete':
6916
                self::deletePageWarning($page);
6917
                break;
6918
            case 'deletewiki':
6919
                $title = '<div class="actions">'.get_lang(
6920
                        'DeleteWiki'
6921
                    ).'</div>';
6922
                if (api_is_allowed_to_edit(
6923
                        false,
6924
                        true
6925
                    ) || api_is_platform_admin()) {
6926
                    $message = get_lang('ConfirmDeleteWiki');
6927
                    $message .= '<p>
6928
                        <a href="index.php?'.api_get_cidreq().'">'.get_lang(
6929
                            'No'
6930
                        ).'</a>
6931
                        &nbsp;&nbsp;|&nbsp;&nbsp;
6932
                        <a href="'.api_get_self().'?'.api_get_cidreq(
6933
                        ).'&action=deletewiki&delete=yes">'.
6934
                        get_lang('Yes').'</a>
6935
                    </p>';
6936
6937
                    if (!isset($_GET['delete'])) {
6938
                        Display::addFlash(
6939
                            $title.Display::return_message(
6940
                                $message,
6941
                                'warning',
6942
                                false
6943
                            )
6944
                        );
6945
                    }
6946
                } else {
6947
                    Display::addFlash(
6948
                        Display::return_message(
6949
                            get_lang("OnlyAdminDeleteWiki"),
6950
                            'normal',
6951
                            false
6952
                        )
6953
                    );
6954
                }
6955
6956
                if (api_is_allowed_to_edit(
6957
                        false,
6958
                        true
6959
                    ) || api_is_platform_admin()) {
6960
                    if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
6961
                        $return_message = self::delete_wiki();
6962
                        Display::addFlash(
6963
                            Display::return_message(
6964
                                $return_message,
6965
                                'confirmation',
6966
                                false
6967
                            )
6968
                        );
6969
                        $this->redirectHome();
6970
                    }
6971
                }
6972
                break;
6973
            case 'searchpages':
6974
                self::getSearchPages($action);
6975
                break;
6976
            case 'links':
6977
                self::getLinks($page);
6978
                break;
6979
            case 'addnew':
6980
                if (api_get_session_id() != 0 && api_is_allowed_to_session_edit(false, true) == false) {
6981
                    api_not_allowed();
6982
                }
6983
                $groupInfo = GroupManager::get_group_properties(
6984
                    api_get_group_id()
6985
                );
6986
                echo '<div class="actions">'.get_lang('AddNew').'</div>';
6987
                echo '<br/>';
6988
                //first, check if page index was created. chektitle=false
6989
                if (self::checktitle('index')) {
6990
                    if (api_is_allowed_to_edit(false, true) ||
6991
                        api_is_platform_admin() ||
6992
                        GroupManager::is_user_in_group(
6993
                            api_get_user_id(),
6994
                            $groupInfo
6995
                        ) ||
6996
                        api_is_allowed_in_course()
6997
                    ) {
6998
                        Display::addFlash(
6999
                            Display::return_message(get_lang('GoAndEditMainPage'), 'normal', false)
7000
                        );
7001
                    } else {
7002
                        Display::addFlash(
7003
                            Display::return_message(get_lang('WikiStandBy'), 'normal', false)
7004
                        );
7005
                    }
7006
                } elseif (self::check_addnewpagelock() == 0
7007
                    && (
7008
                        api_is_allowed_to_edit(false, true) == false
7009
                        || api_is_platform_admin() == false
7010
                    )
7011
                ) {
7012
                    Display::addFlash(
7013
                        Display::return_message(get_lang('AddPagesLocked'), 'error', false)
7014
                    );
7015
                } else {
7016
                    $groupInfo = GroupManager::get_group_properties(
7017
                        api_get_group_id()
7018
                    );
7019
                    if (api_is_allowed_to_edit(false, true) ||
7020
                        api_is_platform_admin() ||
7021
                        GroupManager::is_user_in_group(
7022
                            api_get_user_id(),
7023
                            $groupInfo
7024
                        ) ||
7025
                        $_GET['group_id'] == 0
7026
                    ) {
7027
                        self::display_new_wiki_form();
7028
                    } else {
7029
                        Display::addFlash(
7030
                            Display::return_message(get_lang('OnlyAddPagesGroupMembers'), 'normal', false)
7031
                        );
7032
                    }
7033
                }
7034
                break;
7035
            case 'show':
7036
            case 'showpage':
7037
                self::display_wiki_entry($page);
7038
                break;
7039
            case 'edit':
7040
                self::editPage();
7041
                break;
7042
            case 'history':
7043
                self::getHistory();
7044
                break;
7045
            case 'recentchanges':
7046
                self::recentChanges($page, $action);
7047
                break;
7048
            case 'allpages':
7049
                self::allPages($action);
7050
                break;
7051
            case 'discuss':
7052
                self::getDiscuss($page);
7053
                break;
7054
            case 'export_to_doc_file':
7055
                self::exportTo($_GET['id'], 'odt');
7056
                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...
7057
                break;
7058
            case 'category':
7059
                $this->addCategory();
7060
                break;
7061
            case 'delete_category':
7062
                $this->deleteCategory();
7063
                break;
7064
        }
7065
    }
7066
7067
    /**
7068
     * Redirect to home.
7069
     */
7070
    public function redirectHome()
7071
    {
7072
        $redirectUrl = $this->url.'&action=showpage&title=index';
7073
        header('Location: '.$redirectUrl.'&'.api_get_cidreq());
7074
        exit;
7075
    }
7076
7077
    /**
7078
     * Export wiki content in a ODF.
7079
     *
7080
     * @param int $id
7081
     * @param string int
7082
     *
7083
     * @return bool
7084
     */
7085
    public function exportTo($id, $format = 'doc')
7086
    {
7087
        $data = self::getWikiDataFromDb($id);
7088
7089
        if (isset($data['content']) && !empty($data['content'])) {
7090
            Export::htmlToOdt($data['content'], $data['reflink'], $format);
7091
        }
7092
7093
        return false;
7094
    }
7095
7096
    private function gelAllPagesQuery(
7097
        $onlyCount = false,
7098
        $from = 0,
7099
        $numberOfItems = 10,
7100
        $column = 0,
7101
        $direction = 'ASC'
7102
    ): ?Statement {
7103
        $tblWiki = $this->tbl_wiki;
7104
7105
        $fields = $onlyCount
7106
            ? 'COUNT(s1.iid) AS nbr'
7107
            : 's1.assignment AS col0, s1.title AS col1, s1.user_id AS col2, s1.dtime AS col3, s1.reflink, s1.user_ip';
7108
7109
        $query = 'SELECT '.$fields.' FROM '.$tblWiki.' s1 WHERE s1.c_id = '.$this->course_id.' ';
7110
7111
        if (!api_is_allowed_to_edit(false, true) && !api_is_platform_admin()) {
7112
            // warning don't use group by reflink because does not return the last version
7113
            $query .= 'AND visibility = 1 ';
7114
        }
7115
7116
        $query .= 'AND id = (
7117
            SELECT MAX(s2.id) FROM '.$tblWiki.' s2
7118
            WHERE s2.c_id = '.$this->course_id.'
7119
                AND s1.reflink = s2.reflink
7120
                AND '.$this->groupfilter.'
7121
                AND session_id = '.$this->session_id.'
7122
        ) ';
7123
7124
        if (!$onlyCount) {
7125
            $query .= "ORDER BY col$column $direction LIMIT $from, $numberOfItems";
7126
        }
7127
7128
        return Database::query($query);
7129
    }
7130
7131
    private function deleteCategory()
7132
    {
7133
        if (!api_is_allowed_to_edit(false, true) && !api_is_platform_admin()) {
7134
            api_not_allowed(true);
7135
        }
7136
7137
        if (true !== api_get_configuration_value('wiki_categories_enabled')) {
7138
            api_not_allowed(true);
7139
        }
7140
7141
        $em = Database::getManager();
7142
7143
        $category = null;
7144
7145
        if (isset($_GET['id'])) {
7146
            $category = $em->find(CWikiCategory::class, $_GET['id']);
7147
7148
            if (!$category) {
7149
                api_not_allowed(true);
7150
            }
7151
        }
7152
7153
        $em->remove($category);
7154
        $em->flush();
7155
7156
        Display::addFlash(
7157
            Display::return_message(get_lang('CategoryDeleted'), 'success')
7158
        );
7159
7160
        header('Location: index.php?'.api_get_cidreq().'&action=category');
7161
        exit;
7162
    }
7163
7164
    private function addCategory()
7165
    {
7166
        if (!api_is_allowed_to_edit(false, true) && !api_is_platform_admin()) {
7167
            api_not_allowed(true);
7168
        }
7169
7170
        if (true !== api_get_configuration_value('wiki_categories_enabled')) {
7171
            api_not_allowed(true);
7172
        }
7173
7174
        $categoryRepo = Database::getManager()->getRepository(CWikiCategory::class);
7175
7176
        $categoryToEdit = null;
7177
7178
        if (isset($_GET['id'])) {
7179
            $categoryToEdit = $categoryRepo->find($_GET['id']);
7180
7181
            if (!$categoryToEdit) {
7182
                api_not_allowed(true);
7183
            }
7184
        }
7185
7186
        $course = api_get_course_entity();
7187
        $session = api_get_session_entity();
7188
7189
        if ($categoryToEdit
7190
            && ($course !== $categoryToEdit->getCourse() || $session !== $categoryToEdit->getSession())
7191
        ) {
7192
            api_not_allowed(true);
7193
        }
7194
7195
        $self = api_get_self();
7196
        $cidReq = api_get_cidreq();
7197
        $iconEdit = Display::return_icon('edit.png', get_lang('Edit'));
7198
        $iconDelete = Display::return_icon('delete.png', get_lang('Delete'));
7199
7200
        $categories = $categoryRepo->findByCourse($course, $session);
7201
        $categoryList = array_map(
7202
            function (CWikiCategory $category) use ($self, $cidReq, $iconEdit, $iconDelete) {
7203
                $actions = [];
7204
                $actions[] = Display::url(
7205
                    $iconEdit,
7206
                    "$self?$cidReq&".http_build_query(['action' => 'category', 'id' => $category->getId()])
7207
                );
7208
                $actions[] = Display::url(
7209
                    $iconDelete,
7210
                    "$self?$cidReq&".http_build_query(['action' => 'delete_category', 'id' => $category->getId()])
7211
                );
7212
7213
                return [
7214
                    $category->getNodeName(),
7215
                    implode(PHP_EOL, $actions),
7216
                ];
7217
            },
7218
            $categories
7219
        );
7220
7221
        $table = new SortableTableFromArray($categoryList);
7222
        $table->set_header(0, get_lang('Name'), false);
7223
        $table->set_header(1, get_lang('Actions'), false, ['class' => 'text-right'], ['class' => 'text-right']);
7224
7225
        $form = $this->createCategoryForm($categoryToEdit);
7226
        $form->display();
7227
        echo '<hr>';
7228
        $table->display();
7229
    }
7230
7231
    private function createCategoryForm(CWikiCategory $category = null): FormValidator
7232
    {
7233
        $em = Database::getManager();
7234
        $categoryRepo = $em->getRepository(CWikiCategory::class);
7235
7236
        $course = api_get_course_entity($this->courseInfo['real_id']);
7237
        $session = api_get_session_entity($this->session_id);
7238
7239
        $categories = $categoryRepo->findByCourse($course, $session);
7240
7241
        $formAction = api_get_self().'?'.http_build_query([
7242
            'cidReq' => $course->getCode(),
7243
            'session_id' => $session ? $session->getId() : 0,
7244
            'id_session' => $session ? $session->getId() : 0,
7245
            'group_id' => $this->group_id,
7246
            'action' => 'category',
7247
            'id' => $category ? $category->getId() : null,
7248
        ]);
7249
7250
        $form = new FormValidator('category', 'post', $formAction);
7251
        $form->addHeader(get_lang('AddCategory'));
7252
        $form->addSelectFromCollection('parent', get_lang('Parent'), $categories, [], true, 'getNodeName');
7253
        $form->addText('name', get_lang('Name'));
7254
7255
        if ($category) {
7256
            $form->addButtonUpdate(get_lang('Update'));
7257
        } else {
7258
            $form->addButtonSave(get_lang('Save'));
7259
        }
7260
7261
        if ($form->validate()) {
7262
            $values = $form->exportValues();
7263
            $parent = $categoryRepo->find($values['parent']);
7264
7265
            if (!$category) {
7266
                $category = (new CWikiCategory())
7267
                    ->setCourse($course)
7268
                    ->setSession($session)
7269
                ;
7270
7271
                $em->persist($category);
7272
7273
                Display::addFlash(
7274
                    Display::return_message(get_lang('CategoryAdded'), 'success')
7275
                );
7276
            } else {
7277
                Display::addFlash(
7278
                    Display::return_message(get_lang('CategoryEdited'), 'success')
7279
                );
7280
            }
7281
7282
            $category
7283
                ->setName($values['name'])
7284
                ->setParent($parent)
7285
            ;
7286
7287
            $em->flush();
7288
7289
            header('Location: index.php?'.api_get_cidreq().'&action=category');
7290
            exit;
7291
        }
7292
7293
        if ($category) {
7294
            $form->setDefaults([
7295
                'parent' => $category->getParent() ? $category->getParent()->getId() : 0,
7296
                'name' => $category->getName(),
7297
            ]);
7298
        }
7299
7300
        return $form;
7301
    }
7302
7303
    private static function assignCategoriesToWiki(CWiki $wiki, array $categoriesIdList)
7304
    {
7305
        if (true !== api_get_configuration_value('wiki_categories_enabled')) {
7306
            return;
7307
        }
7308
7309
        $em = Database::getManager();
7310
7311
        foreach ($categoriesIdList as $categoryId) {
7312
            $category = $em->find(CWikiCategory::class, $categoryId);
7313
            $wiki->addCategory($category);
7314
        }
7315
7316
        $em->flush();
7317
    }
7318
}
7319