Completed
Push — master ( 27e209...a08afa )
by Julito
186:04 queued 150:53
created

Wiki::display_wiki_search_results()   F

Complexity

Conditions 21
Paths 1560

Size

Total Lines 325
Code Lines 249

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 249
nc 1560
nop 3
dl 0
loc 325
rs 2
c 0
b 0
f 0

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
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Component\Editor\Connector;
5
use Chamilo\CoreBundle\Component\Filesystem\Data;
6
use ChamiloSession as Session;
7
use MediaAlchemyst\Alchemyst;
8
use MediaAlchemyst\DriversContainer;
9
use Neutron\TemporaryFilesystem\Manager;
10
use Neutron\TemporaryFilesystem\TemporaryFilesystem;
11
use Symfony\Component\Filesystem\Filesystem;
12
13
/**
14
 * Class Wiki
15
 * Functions library for the wiki tool
16
 * @author Juan Carlos Raña <[email protected]>
17
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
18
 * @author Julio Montoya <[email protected]> using the pdf.lib.php library
19
 *
20
 * @package chamilo.wiki
21
 */
22
class Wiki
23
{
24
    public $tbl_wiki;
25
    public $tbl_wiki_discuss;
26
    public $tbl_wiki_mailcue;
27
    public $tbl_wiki_conf;
28
    public $session_id = null;
29
    public $course_id = null;
30
    public $condition_session = null;
31
    public $group_id;
32
    public $assig_user_id;
33
    public $groupfilter = 'group_id=0';
34
    public $courseInfo;
35
    public $charset;
36
    public $page;
37
    public $action;
38
    public $wikiData = [];
39
    public $url;
40
41
    /**
42
     * Constructor
43
     */
44
    public function __construct()
45
    {
46
        // Database table definition
47
        $this->tbl_wiki = Database::get_course_table(TABLE_WIKI);
48
        $this->tbl_wiki_discuss = Database::get_course_table(
49
            TABLE_WIKI_DISCUSS
50
        );
51
        $this->tbl_wiki_mailcue = Database::get_course_table(
52
            TABLE_WIKI_MAILCUE
53
        );
54
        $this->tbl_wiki_conf = Database::get_course_table(TABLE_WIKI_CONF);
55
56
        $this->session_id = api_get_session_id();
57
        $this->condition_session = api_get_session_condition($this->session_id);
58
        $this->course_id = api_get_course_int_id();
59
        $this->group_id = api_get_group_id();
60
61
        if (!empty($this->group_id)) {
62
            $this->groupfilter = ' group_id="'.$this->group_id.'"';
63
        }
64
        $this->courseInfo = api_get_course_info();
65
        $this->url = api_get_path(WEB_CODE_PATH).'wiki/index.php?'.api_get_cidreq();
66
    }
67
68
    /**
69
     * Check whether this title is already used
70
     * @param string $link
71
     *
72
     *
73
     * @return bool  False if title is already taken
74
     * @author Patrick Cool <[email protected]>, Ghent University
75
     **/
76
    public function checktitle($link)
77
    {
78
        $tbl_wiki = $this->tbl_wiki;
79
        $condition_session = $this->condition_session;
80
        $course_id = $this->course_id;
81
        $groupfilter = $this->groupfilter;
82
83
        $sql = 'SELECT * FROM '.$tbl_wiki.'
84
                WHERE
85
                    c_id = '.$course_id.' AND
86
                    reflink="'.Database::escape_string($link).'" AND
87
                    '.$groupfilter.$condition_session.'';
88
        $result = Database::query($sql);
89
        $num = Database::num_rows($result);
90
        // the value has not been found and is this available
91
        if ($num == 0) {
92
            return true;
93
        } else {
94
            // the value has been found
95
            return false;
96
        }
97
    }
98
99
    /**
100
     * check wikilinks that has a page
101
     * @author Juan Carlos Raña <[email protected]>
102
     * @param string $input
103
     *
104
     * @return string
105
     **/
106
    public function links_to($input)
107
    {
108
        $input_array = preg_split(
109
            "/(\[\[|\]\])/",
110
            $input,
111
            -1,
112
            PREG_SPLIT_DELIM_CAPTURE
113
        );
114
        $all_links = [];
115
116
        foreach ($input_array as $key => $value) {
117
            if (isset($input_array[$key - 1]) && $input_array[$key - 1] == '[[' &&
118
                isset($input_array[$key + 1]) && $input_array[$key + 1] == ']]'
119
            ) {
120
                if (api_strpos($value, "|") !== false) {
121
                    $full_link_array = explode("|", $value);
122
                    $link = trim($full_link_array[0]);
123
                    $title = trim($full_link_array[1]);
124
                } else {
125
                    $link = trim($value);
126
                    $title = trim($value);
127
                }
128
                unset($input_array[$key - 1]);
129
                unset($input_array[$key + 1]);
130
                //replace blank spaces by _ within the links. But to remove links at the end add a blank space
131
                $all_links[] = Database::escape_string(
132
                    str_replace(' ', '_', $link)
133
                ).' ';
134
            }
135
        }
136
        $output = implode($all_links);
0 ignored issues
show
Bug introduced by
The call to implode() has too few arguments starting with pieces. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

136
        $output = /** @scrutinizer ignore-call */ implode($all_links);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
137
138
        return $output;
139
    }
140
141
    /**
142
     * detect and add style to external links
143
     * @author Juan Carlos Raña Trabado
144
     **/
145
    public function detect_external_link($input)
146
    {
147
        $exlink = 'href=';
148
        $exlinkStyle = 'class="wiki_link_ext" href=';
149
        $output = str_replace($exlink, $exlinkStyle, $input);
150
151
        return $output;
152
    }
153
154
    /**
155
     * detect and add style to anchor links
156
     * @author Juan Carlos Raña Trabado
157
     **/
158
    public function detect_anchor_link($input)
159
    {
160
        $anchorlink = 'href="#';
161
        $anchorlinkStyle = 'class="wiki_anchor_link" href="#';
162
        $output = str_replace($anchorlink, $anchorlinkStyle, $input);
163
164
        return $output;
165
    }
166
167
    /**
168
     * detect and add style to mail links
169
     * author Juan Carlos Raña Trabado
170
     **/
171
    public function detect_mail_link($input)
172
    {
173
        $maillink = 'href="mailto';
174
        $maillinkStyle = 'class="wiki_mail_link" href="mailto';
175
        $output = str_replace($maillink, $maillinkStyle, $input);
176
177
        return $output;
178
    }
179
180
    /**
181
     * detect and add style to ftp links
182
     * @author Juan Carlos Raña Trabado
183
     **/
184
    public function detect_ftp_link($input)
185
    {
186
        $ftplink = 'href="ftp';
187
        $ftplinkStyle = 'class="wiki_ftp_link" href="ftp';
188
        $output = str_replace($ftplink, $ftplinkStyle, $input);
189
190
        return $output;
191
    }
192
193
    /**
194
     * detect and add style to news links
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
     * @author Juan Carlos Raña Trabado
209
     **/
210
    public function detect_irc_link($input)
211
    {
212
        $irclink = 'href="irc';
213
        $irclinkStyle = 'class="wiki_irc_link" href="irc';
214
        $output = str_replace($irclink, $irclinkStyle, $input);
215
216
        return $output;
217
    }
218
219
    /**
220
     * This function allows users to have [link to a title]-style links like in most regular wikis.
221
     * It is true that the adding of links is probably the most anoying part of Wiki for the people
222
     * who know something about the wiki syntax.
223
     * @author Patrick Cool <[email protected]>, Ghent University
224
     * Improvements [[]] and [[ | ]]by Juan Carlos Raña
225
     * Improvements internal wiki style and mark group by Juan Carlos Raña
226
     **/
227
    public function make_wiki_link_clickable($input)
228
    {
229
        $groupId = api_get_group_id();
230
        //now doubles brackets
231
        $input_array = preg_split(
232
            "/(\[\[|\]\])/",
233
            $input,
234
            -1,
235
            PREG_SPLIT_DELIM_CAPTURE
236
        );
237
238
        foreach ($input_array as $key => $value) {
239
            //now doubles brackets
240
            if (isset($input_array[$key - 1]) &&
241
                $input_array[$key - 1] == '[[' && $input_array[$key + 1] == ']]'
242
            ) {
243
                // now full wikilink
244
                if (api_strpos($value, "|") !== false) {
245
                    $full_link_array = explode("|", $value);
246
                    $link = trim(strip_tags($full_link_array[0]));
247
                    $title = trim($full_link_array[1]);
248
                } else {
249
                    $link = trim(strip_tags($value));
250
                    $title = trim($value);
251
                }
252
253
                //if wikilink is homepage
254
                if ($link == 'index') {
255
                    $title = get_lang('DefaultTitle');
256
                }
257
                if ($link == get_lang('DefaultTitle')) {
258
                    $link = 'index';
259
                }
260
261
                // note: checkreflink checks if the link is still free. If it is not used then it returns true, if it is used, then it returns false. Now the title may be different
262
                if (self::checktitle(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::checktitle() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

262
                if (self::/** @scrutinizer ignore-call */ checktitle(
Loading history...
263
                    strtolower(str_replace(' ', '_', $link))
264
                )) {
265
                    $link = api_html_entity_decode($link);
266
                    $input_array[$key] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?'.api_get_cidreq().'&action=addnew&title='.Security::remove_XSS($link).'&group_id='.$groupId.'" class="new_wiki_link">'.$title.'</a>';
267
                } else {
268
                    $input_array[$key] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?'.api_get_cidreq().'&action=showpage&title='.urlencode(strtolower(str_replace(' ', '_', $link))).'&group_id='.$groupId.'" class="wiki_link">'.$title.'</a>';
269
                }
270
                unset($input_array[$key - 1]);
271
                unset($input_array[$key + 1]);
272
            }
273
        }
274
        $output = implode('', $input_array);
0 ignored issues
show
Bug introduced by
It seems like $input_array can also be of type false; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

274
        $output = implode('', /** @scrutinizer ignore-type */ $input_array);
Loading history...
275
276
        return $output;
277
    }
278
279
    /**
280
     * This function saves a change in a wiki page
281
     * @author Patrick Cool <[email protected]>, Ghent University
282
     * @param array $values
283
     * @return language string saying that the changes are stored
284
     **/
285
    public function save_wiki($values)
286
    {
287
        $tbl_wiki = $this->tbl_wiki;
288
        $tbl_wiki_conf = $this->tbl_wiki_conf;
289
290
        $_course = $this->courseInfo;
291
        $time = api_get_utc_datetime();
292
        $session_id = api_get_session_id();
293
        $groupId = api_get_group_id();
294
        $userId = api_get_user_id();
295
        $groupInfo = GroupManager::get_group_properties($groupId);
296
        $course_id = api_get_course_int_id();
297
298
        $_clean = [
299
            'task' => '',
300
            'feedback1' => '',
301
            'feedback2' => '',
302
            'feedback3' => '',
303
            'fprogress1' => '',
304
            'fprogress2' => '',
305
            'fprogress3' => '',
306
            'max_text' => 0,
307
            'max_version' => 0,
308
            'delayedsubmit' => '',
309
            'assignment' => 0
310
        ];
311
312
        $pageId = intval($values['page_id']);
313
314
        // NOTE: visibility, visibility_disc and ratinglock_disc changes
315
        // are not made here, but through the interce buttons
316
317
        // cleaning the variables
318
        if (api_get_setting('htmlpurifier_wiki') == 'true') {
319
            //$purifier = new HTMLPurifier();
320
            $values['content'] = Security::remove_XSS($values['content']);
321
        }
322
        $version = intval($values['version']) + 1;
323
        $linkTo = self::links_to($values['content']); //and check links content
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::links_to() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

323
        /** @scrutinizer ignore-call */ 
324
        $linkTo = self::links_to($values['content']); //and check links content
Loading history...
324
325
        //cleaning config variables
326
        if (!empty($values['task'])) {
327
            $_clean['task'] = $values['task'];
328
        }
329
330
        if (!empty($values['feedback1']) ||
331
            !empty($values['feedback2']) ||
332
            !empty($values['feedback3'])
333
        ) {
334
            $_clean['feedback1'] = $values['feedback1'];
335
            $_clean['feedback2'] = $values['feedback2'];
336
            $_clean['feedback3'] = $values['feedback3'];
337
            $_clean['fprogress1'] = $values['fprogress1'];
338
            $_clean['fprogress2'] = $values['fprogress2'];
339
            $_clean['fprogress3'] = $values['fprogress3'];
340
        }
341
342
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
343
            $_clean['startdate_assig'] = $values['startdate_assig'];
344
        } else {
345
            $_clean['startdate_assig'] = null;
346
        }
347
348
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
349
            $_clean['enddate_assig'] = $values['enddate_assig'];
350
        } else {
351
            $_clean['enddate_assig'] = null;
352
        }
353
354
        if (isset($values['delayedsubmit'])) {
355
            $_clean['delayedsubmit'] = $values['delayedsubmit'];
356
        }
357
358
        if (!empty($values['max_text']) || !empty($values['max_version'])) {
359
            $_clean['max_text'] = $values['max_text'];
360
            $_clean['max_version'] = $values['max_version'];
361
        }
362
363
        $values['assignment'] = isset($values['assignment']) ? $values['assignment'] : 0;
364
        $values['page_id'] = isset($values['page_id']) ? $values['page_id'] : 0;
365
366
        $params = [
367
            'c_id' => $course_id,
368
            'addlock' => 1,
369
            'visibility' => 1,
370
            'visibility_disc' => 1,
371
            'addlock_disc' => 1,
372
            'ratinglock_disc' => 1,
373
            'page_id' => $pageId,
374
            'reflink' => trim($values['reflink']),
375
            'title' => trim($values['title']),
376
            'content' => $values['content'],
377
            'user_id' => $userId,
378
            'group_id' => $groupId,
379
            'dtime' => $time,
380
            'assignment' => $values['assignment'],
381
            'comment' => $values['comment'],
382
            'progress' => $values['progress'],
383
            'version' => $version,
384
            'linksto' => $linkTo,
385
            'user_ip' => $_SERVER['REMOTE_ADDR'],
386
            'session_id' => $session_id,
387
            'page_id' => $values['page_id'],
388
            'editlock' => 0,
389
            'is_editing' => 0,
390
            'time_edit' => $time,
391
            'tag' => ''
392
        ];
393
394
        $id = Database::insert($tbl_wiki, $params);
395
396
        if ($id > 0) {
397
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
398
            Database::query($sql);
399
400
            // insert into item_property
401
            api_item_property_update(
402
                $_course,
403
                TOOL_WIKI,
404
                $id,
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type false; however, parameter $item_id of api_item_property_update() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

404
                /** @scrutinizer ignore-type */ $id,
Loading history...
405
                'WikiAdded',
406
                $userId,
407
                $groupInfo
408
            );
409
410
            if ($values['page_id'] == 0) {
411
                $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
0 ignored issues
show
Bug introduced by
Are you sure $id of type integer|false can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

411
                $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'./** @scrutinizer ignore-type */ $id.'"
Loading history...
412
                        WHERE c_id = '.$course_id.' AND iid ="'.$id.'"';
413
                Database::query($sql);
414
            }
415
        }
416
417
        // Update wiki config
418
        if ($values['reflink'] == 'index' && $version == 1) {
419
            $params = [
420
                'c_id' => $course_id,
421
                'page_id' => $id,
422
                'task' => $_clean['task'],
423
                'feedback1' => $_clean['feedback1'],
424
                'feedback2' => $_clean['feedback2'],
425
                'feedback3' => $_clean['feedback3'],
426
                'fprogress1' => $_clean['fprogress1'],
427
                'fprogress2' => $_clean['fprogress2'],
428
                'fprogress3' => $_clean['fprogress3'],
429
                'max_text' => intval($_clean['max_text']),
430
                'max_version' => intval($_clean['max_version']),
431
                'startdate_assig' => $_clean['startdate_assig'],
432
                'enddate_assig' => $_clean['enddate_assig'],
433
                'delayedsubmit' => $_clean['delayedsubmit']
434
            ];
435
            Database::insert($tbl_wiki_conf, $params);
436
        } else {
437
            $params = [
438
                'task' => $_clean['task'],
439
                'feedback1' => $_clean['feedback1'],
440
                'feedback2' => $_clean['feedback2'],
441
                'feedback3' => $_clean['feedback3'],
442
                'fprogress1' => $_clean['fprogress1'],
443
                'fprogress2' => $_clean['fprogress2'],
444
                'fprogress3' => $_clean['fprogress3'],
445
                'max_text' => intval($_clean['max_text']),
446
                'max_version' => intval($_clean['max_version']),
447
                'startdate_assig' => $_clean['startdate_assig'],
448
                'enddate_assig' => $_clean['enddate_assig'],
449
                'delayedsubmit' => $_clean['delayedsubmit']
450
            ];
451
            Database::update(
452
                $tbl_wiki_conf,
453
                $params,
454
                ['page_id = ? AND c_id = ?' => [$pageId, $course_id]]
455
            );
456
        }
457
458
        api_item_property_update(
459
            $_course,
460
            'wiki',
461
            $id,
462
            'WikiAdded',
463
            $userId,
464
            $groupInfo
465
        );
466
        self::check_emailcue($_clean['reflink'], 'P', $time, $userId);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_emailcue() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

466
        self::/** @scrutinizer ignore-call */ 
467
              check_emailcue($_clean['reflink'], 'P', $time, $userId);
Loading history...
467
        $this->setWikiData($id);
468
469
        return get_lang('Saved');
0 ignored issues
show
Bug Best Practice introduced by
The expression return get_lang('Saved') returns the type string which is incompatible with the documented return type language.
Loading history...
470
    }
471
472
    /**
473
     * This function restore a wikipage
474
     * @author Juan Carlos Raña <[email protected]>
475
     * @return string Message of success (to be printed on screen)
476
     **/
477
    public function restore_wikipage(
478
        $r_page_id,
479
        $r_reflink,
480
        $r_title,
481
        $r_content,
482
        $r_group_id,
483
        $r_assignment,
484
        $r_progress,
485
        $c_version,
486
        $r_version,
487
        $r_linksto
488
    ) {
489
        $tbl_wiki = $this->tbl_wiki;
490
        $_course = $this->courseInfo;
491
        $r_user_id = api_get_user_id();
492
        $r_dtime = api_get_utc_datetime();
493
        $r_version = $r_version + 1;
494
        $r_comment = get_lang('RestoredFromVersion').': '.$c_version;
495
        $session_id = api_get_session_id();
496
        $course_id = api_get_course_int_id();
497
        $groupInfo = GroupManager::get_group_properties($r_group_id);
498
499
        $params = [
500
            'c_id' => $course_id,
501
            'page_id' => $r_page_id,
502
            'reflink' => $r_reflink,
503
            'title' => $r_title,
504
            'content' => $r_content,
505
            'user_id' => $r_user_id,
506
            'group_id' => $r_group_id,
507
            'dtime' => $r_dtime,
508
            'assignment' => $r_assignment,
509
            'comment' => $r_comment,
510
            'progress' => $r_progress,
511
            'version' => $r_version,
512
            'linksto' => $r_linksto,
513
            'user_ip' => $_SERVER['REMOTE_ADDR'],
514
            'session_id' => $session_id,
515
        ];
516
        $id = Database::insert($tbl_wiki, $params);
517
518
        if ($id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
519
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
520
            Database::query($sql);
521
522
            api_item_property_update(
523
                $_course,
524
                'wiki',
525
                $id,
526
                'WikiAdded',
527
                api_get_user_id(),
528
                $groupInfo
529
            );
530
            self::check_emailcue($r_reflink, 'P', $r_dtime, $r_user_id);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_emailcue() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

530
            self::/** @scrutinizer ignore-call */ 
531
                  check_emailcue($r_reflink, 'P', $r_dtime, $r_user_id);
Loading history...
531
        }
532
533
        return get_lang('PageRestored');
534
    }
535
536
    /**
537
     * This function delete a wiki
538
     * @author Juan Carlos Raña <[email protected]>
539
     * @return   string  Message of success (to be printed)
540
     **/
541
    public function delete_wiki()
542
    {
543
        $tbl_wiki = $this->tbl_wiki;
544
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
545
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
546
        $tbl_wiki_conf = $this->tbl_wiki_conf;
547
        $conditionSession = $this->condition_session;
548
        $groupFilter = $this->groupfilter;
549
        $course_id = $this->course_id;
550
551
        $sql = "SELECT page_id FROM $tbl_wiki
552
                WHERE c_id = $course_id AND $groupFilter $conditionSession
553
                ORDER BY id DESC";
554
555
        $result = Database::query($sql);
556
        $pageList = Database::store_result($result);
557
        if ($pageList) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $pageList of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
558
            foreach ($pageList as $pageData) {
559
                $pageId = $pageData['page_id'];
560
                $sql = "DELETE FROM $tbl_wiki_conf
561
                        WHERE c_id = $course_id AND page_id = $pageId";
562
                Database::query($sql);
563
564
                $sql = "DELETE FROM $tbl_wiki_discuss
565
                        WHERE c_id = $course_id AND publication_id = $pageId";
566
                Database::query($sql);
567
            }
568
        }
569
570
        $sql = "DELETE FROM $tbl_wiki_mailcue
571
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
572
        Database::query($sql);
573
574
        $sql = "DELETE FROM $tbl_wiki
575
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
576
        Database::query($sql);
577
578
        return get_lang('WikiDeleted');
579
    }
580
581
    /**
582
     * This function saves a new wiki page.
583
     * @author Patrick Cool <[email protected]>, Ghent University
584
     * @todo consider merging this with the function save_wiki into one single function.
585
     * @return string Message of success
586
     **/
587
    public function save_new_wiki($values)
588
    {
589
        $tbl_wiki = $this->tbl_wiki;
590
        $tbl_wiki_conf = $this->tbl_wiki_conf;
591
        $assig_user_id = $this->assig_user_id;
592
        $_clean = [];
593
594
        // cleaning the variables
595
        $_clean['assignment'] = '';
596
        if (isset($values['assignment'])) {
597
            $_clean['assignment'] = $values['assignment'];
598
        }
599
600
        // session_id
601
        $session_id = api_get_session_id();
602
        // Unlike ordinary pages of pages of assignments.
603
        // Allow create a ordinary page although there is a assignment with the same name
604
        if ($_clean['assignment'] == 2 || $_clean['assignment'] == 1) {
605
            $page = str_replace(
606
                ' ',
607
                '_',
608
                $values['title']."_uass".$assig_user_id
609
            );
610
        } else {
611
            $page = str_replace(' ', '_', $values['title']);
612
        }
613
        $_clean['reflink'] = $page;
614
        $_clean['title'] = trim($values['title']);
615
        $_clean['content'] = $values['content'];
616
617
        if (api_get_setting('htmlpurifier_wiki') === 'true') {
618
            $purifier = new HTMLPurifier();
619
            $_clean['content'] = $purifier->purify($_clean['content']);
620
        }
621
622
        //re-check after strip_tags if the title is empty
623
        if (empty($_clean['title']) || empty($_clean['reflink'])) {
624
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
625
        }
626
627
        if ($_clean['assignment'] == 2) {
628
            //config by default for individual assignment (students)
629
            //Identifies the user as a creator, not the teacher who created
630
            $_clean['user_id'] = intval($assig_user_id);
631
            $_clean['visibility'] = 0;
632
            $_clean['visibility_disc'] = 0;
633
            $_clean['ratinglock_disc'] = 0;
634
        } else {
635
            $_clean['user_id'] = api_get_user_id();
636
            $_clean['visibility'] = 1;
637
            $_clean['visibility_disc'] = 1;
638
            $_clean['ratinglock_disc'] = 1;
639
        }
640
641
        $_clean['comment'] = $values['comment'];
642
        $_clean['progress'] = $values['progress'];
643
        $_clean['version'] = 1;
644
645
        $groupId = api_get_group_id();
646
        $groupInfo = GroupManager::get_group_properties($groupId);
647
648
        //check wikilinks
649
        $_clean['linksto'] = self::links_to($_clean['content']);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::links_to() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

649
        /** @scrutinizer ignore-call */ 
650
        $_clean['linksto'] = self::links_to($_clean['content']);
Loading history...
650
651
        // cleaning config variables
652
        $_clean['task'] = isset($values['task']) ? $values['task'] : '';
653
        $_clean['feedback1'] = isset($values['feedback1']) ? $values['feedback1'] : '';
654
        $_clean['feedback2'] = isset($values['feedback2']) ? $values['feedback2'] : '';
655
        $_clean['feedback3'] = isset($values['feedback3']) ? $values['feedback3'] : '';
656
        $_clean['fprogress1'] = isset($values['fprogress1']) ? $values['fprogress1'] : '';
657
        $_clean['fprogress2'] = isset($values['fprogress2']) ? $values['fprogress2'] : '';
658
        $_clean['fprogress3'] = isset($values['fprogress3']) ? $values['fprogress3'] : '';
659
660
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
661
            $_clean['startdate_assig'] = $values['startdate_assig'];
662
        } else {
663
            $_clean['startdate_assig'] = null;
664
        }
665
666
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
667
            $_clean['enddate_assig'] = $values['enddate_assig'];
668
        } else {
669
            $_clean['enddate_assig'] = null;
670
        }
671
672
        $_clean['delayedsubmit'] = isset($values['delayedsubmit']) ? $values['delayedsubmit'] : '';
673
        $_clean['max_text'] = isset($values['max_text']) ? $values['max_text'] : '';
674
        $_clean['max_version'] = isset($values['max_version']) ? $values['max_version'] : '';
675
676
        $course_id = api_get_course_int_id();
677
678
        // Filter no _uass
679
        if (api_strtoupper(trim($values['title'])) === 'INDEX') {
680
            Display::addFlash(
681
                Display::return_message(
682
                    get_lang('GoAndEditMainPage'),
683
                    'warning',
684
                    false
685
                )
686
            );
687
        } else {
688
            $var = $_clean['reflink'];
689
            $group_id = intval($_GET['group_id']);
690
            if (!self::checktitle($var)) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::checktitle() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

690
            if (!self::/** @scrutinizer ignore-call */ checktitle($var)) {
Loading history...
691
                return get_lang('WikiPageTitleExist').
692
                    '<a href="index.php?action=edit&title='.$var.'&group_id='.$group_id.'">'.
693
                    $values['title'].'</a>';
694
            } else {
695
                $dtime = api_get_utc_datetime();
696
697
                $params = [
698
                    'c_id' => $course_id,
699
                    'reflink' => $_clean['reflink'],
700
                    'title' => $_clean['title'],
701
                    'content' => $_clean['content'],
702
                    'user_id' => $_clean['user_id'],
703
                    'group_id' => $groupId,
704
                    'dtime' => $dtime,
705
                    'visibility' => $_clean['visibility'],
706
                    'visibility_disc' => $_clean['visibility_disc'],
707
                    'ratinglock_disc' => $_clean['ratinglock_disc'],
708
                    'assignment' => $_clean['assignment'],
709
                    'comment' => $_clean['comment'],
710
                    'progress' => $_clean['progress'],
711
                    'version' => $_clean['version'],
712
                    'linksto' => $_clean['linksto'],
713
                    'user_ip' => $_SERVER['REMOTE_ADDR'],
714
                    'session_id' => $session_id,
715
                    'addlock_disc' => 1
716
                ];
717
                $id = Database::insert($tbl_wiki, $params);
718
                if ($id > 0) {
719
                    $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
720
                    Database::query($sql);
721
722
                    //insert into item_property
723
                    api_item_property_update(
724
                        api_get_course_info(),
725
                        TOOL_WIKI,
726
                        $id,
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type false; however, parameter $item_id of api_item_property_update() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

726
                        /** @scrutinizer ignore-type */ $id,
Loading history...
727
                        'WikiAdded',
728
                        api_get_user_id(),
729
                        $groupInfo
730
                    );
731
732
                    $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
0 ignored issues
show
Bug introduced by
Are you sure $id of type integer|false can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

732
                    $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'./** @scrutinizer ignore-type */ $id.'"
Loading history...
733
                            WHERE c_id = '.$course_id.' AND id = "'.$id.'"';
734
                    Database::query($sql);
735
736
                    // insert wiki config
737
                    $params = [
738
                        'c_id' => $course_id,
739
                        'page_id' => $id,
740
                        'task' => $_clean['task'],
741
                        'feedback1' => $_clean['feedback1'],
742
                        'feedback2' => $_clean['feedback2'],
743
                        'feedback3' => $_clean['feedback3'],
744
                        'fprogress1' => $_clean['fprogress1'],
745
                        'fprogress2' => $_clean['fprogress2'],
746
                        'fprogress3' => $_clean['fprogress3'],
747
                        'max_text' => $_clean['max_text'],
748
                        'max_version' => $_clean['max_version'],
749
                        'startdate_assig' => $_clean['startdate_assig'],
750
                        'enddate_assig' => $_clean['enddate_assig'],
751
                        'delayedsubmit' => $_clean['delayedsubmit']
752
                    ];
753
754
                    Database::insert($tbl_wiki_conf, $params);
755
756
                    $this->setWikiData($id);
757
                    self::check_emailcue(0, 'A');
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_emailcue() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

757
                    self::/** @scrutinizer ignore-call */ 
758
                          check_emailcue(0, 'A');
Loading history...
758
759
                    return get_lang('NewWikiSaved');
760
                }
761
            }
762
        }
763
    }
764
765
    /**
766
     * @param FormValidator $form
767
     * @param array $row
768
     */
769
    public function setForm($form, $row = [])
770
    {
771
        $toolBar = api_is_allowed_to_edit(null, true)
772
            ? [
773
                'ToolbarSet' => 'Wiki',
774
                'Width' => '100%',
775
                'Height' => '400'
776
            ]
777
            : [
778
                'ToolbarSet' => 'WikiStudent',
779
                'Width' => '100%',
780
                'Height' => '400',
781
                'UserStatus' => 'student'
782
            ];
783
784
        $form->addHtmlEditor(
785
            'content',
786
            get_lang('Content'),
787
            false,
788
            false,
789
            $toolBar
790
        );
791
        //$content
792
        $form->addElement('text', 'comment', get_lang('Comments'));
793
        $progress = ['', 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
794
795
        $form->addElement(
796
            'select',
797
            'progress',
798
            get_lang('Progress'),
799
            $progress
800
        );
801
802
        if ((api_is_allowed_to_edit(false, true) ||
803
            api_is_platform_admin()) &&
804
            isset($row['reflink']) && $row['reflink'] != 'index'
805
        ) {
806
            $form->addElement(
807
                'advanced_settings',
808
                'advanced_params',
809
                get_lang('AdvancedParameters')
810
            );
811
            $form->addElement(
812
                'html',
813
                '<div id="advanced_params_options" style="display:none">'
814
            );
815
816
            $form->addHtmlEditor(
817
                'task',
818
                get_lang('DescriptionOfTheTask'),
819
                false,
820
                false,
821
                [
822
                    'ToolbarSet' => 'wiki_task',
823
                    'Width' => '100%',
824
                    'Height' => '200',
825
                ]
826
            );
827
828
            $form->addElement('label', null, get_lang('AddFeedback'));
829
            $form->addElement('textarea', 'feedback1', get_lang('Feedback1'));
830
            $form->addElement(
831
                'select',
832
                'fprogress1',
833
                get_lang('FProgress'),
834
                $progress
835
            );
836
837
            $form->addElement('textarea', 'feedback2', get_lang('Feedback2'));
838
            $form->addElement(
839
                'select',
840
                'fprogress2',
841
                get_lang('FProgress'),
842
                $progress
843
            );
844
845
            $form->addElement('textarea', 'feedback3', get_lang('Feedback3'));
846
            $form->addElement(
847
                'select',
848
                'fprogress3',
849
                get_lang('FProgress'),
850
                $progress
851
            );
852
853
            $form->addElement(
854
                'checkbox',
855
                'initstartdate',
856
                null,
857
                get_lang('StartDate'),
858
                ['id' => 'start_date_toggle']
859
            );
860
861
            $style = "display:block";
862
            $row['initstartdate'] = 1;
863
            if (empty($row['startdate_assig'])) {
864
                $style = "display:none";
865
                $row['initstartdate'] = null;
866
            }
867
868
            $form->addElement(
869
                'html',
870
                '<div id="start_date" style="'.$style.'">'
871
            );
872
            $form->addDatePicker('startdate_assig', '');
873
            $form->addElement('html', '</div>');
874
            $form->addElement(
875
                'checkbox',
876
                'initenddate',
877
                null,
878
                get_lang('EndDate'),
879
                ['id' => 'end_date_toggle']
880
            );
881
882
            $style = "display:block";
883
            $row['initenddate'] = 1;
884
            if (empty($row['enddate_assig'])) {
885
                $style = "display:none";
886
                $row['initenddate'] = null;
887
            }
888
889
            $form->addHtml('<div id="end_date" style="'.$style.'">');
890
            $form->addDatePicker('enddate_assig', '');
891
            $form->addHtml('</div>');
892
            $form->addElement(
893
                'checkbox',
894
                'delayedsubmit',
895
                null,
896
                get_lang('AllowLaterSends')
897
            );
898
            $form->addElement('text', 'max_text', get_lang('NMaxWords'));
899
            $form->addElement('text', 'max_version', get_lang('NMaxVersion'));
900
            $form->addElement(
901
                'checkbox',
902
                'assignment',
903
                null,
904
                get_lang('CreateAssignmentPage')
905
            );
906
            $form->addElement('html', '</div>');
907
        }
908
909
        $form->addElement('hidden', 'page_id');
910
        $form->addElement('hidden', 'reflink');
911
        $form->addElement('hidden', 'version');
912
        $form->addElement('hidden', 'wpost_id', api_get_unique_id());
913
    }
914
915
    /**
916
     * This function displays the form for adding a new wiki page.
917
     * @author Patrick Cool <[email protected]>, Ghent University
918
     * @return string html code
919
     **/
920
    public function display_new_wiki_form()
921
    {
922
        $url = api_get_self().'?'.api_get_cidreq(
923
            ).'&action=addnew&group_id='.api_get_group_id();
924
        $form = new FormValidator('wiki_new', 'post', $url);
925
        $form->addElement('text', 'title', get_lang('Title'));
926
        $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
927
        self::setForm($form);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::setForm() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

927
        self::/** @scrutinizer ignore-call */ 
928
              setForm($form);
Loading history...
928
        $title = isset($_GET['title']) ? Security::remove_XSS(
929
            $_GET['title']
930
        ) : '';
931
        $form->setDefaults(['title' => $title]);
932
        $form->addElement('button', 'SaveWikiNew', get_lang('Save'));
933
        $form->display();
934
935
        if ($form->validate()) {
936
            $values = $form->exportValues();
937
            if (isset($values['startdate_assig']) &&
938
                isset($values['enddate_assig']) &&
939
                strtotime($values['startdate_assig']) > strtotime(
940
                    $values['enddate_assig']
941
                )
942
            ) {
943
                Display::addFlash(
944
                    Display::return_message(
945
                        get_lang("EndDateCannotBeBeforeTheStartDate"),
946
                        'error',
947
                        false
948
                    )
949
                );
950
            } elseif (!self::double_post($_POST['wpost_id'])) {
0 ignored issues
show
Unused Code introduced by
This elseif statement is empty, and could be removed.

This check looks for the bodies of elseif statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These elseif bodies can be removed. If you have an empty elseif but statements in the else branch, consider inverting the condition.

Loading history...
Bug Best Practice introduced by
The method Wiki::double_post() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

950
            } elseif (!self::/** @scrutinizer ignore-call */ double_post($_POST['wpost_id'])) {
Loading history...
951
                //double post
952
            } else {
953
                if (isset($values['assignment']) && $values['assignment'] == 1) {
954
                    self::auto_add_page_users($values);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::auto_add_page_users() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

954
                    self::/** @scrutinizer ignore-call */ 
955
                          auto_add_page_users($values);
Loading history...
955
                }
956
957
                $return_message = self::save_new_wiki($values);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::save_new_wiki() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

957
                /** @scrutinizer ignore-call */ 
958
                $return_message = self::save_new_wiki($values);
Loading history...
958
959
                if ($return_message == false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $return_message of type string to the boolean false. If you are specifically checking for an empty string, consider using the more explicit === '' instead.
Loading history...
960
                    Display::addFlash(
961
                        Display::return_message(
962
                            get_lang('NoWikiPageTitle'),
963
                            'error',
964
                            false
965
                        )
966
                    );
967
                } else {
968
                    Display::addFlash(
969
                        Display::return_message(
970
                            $return_message,
971
                            'confirmation',
972
                            false
973
                        )
974
                    );
975
                }
976
977
                $wikiData = self::getWikiData();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getWikiData() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

977
                /** @scrutinizer ignore-call */ 
978
                $wikiData = self::getWikiData();
Loading history...
978
                $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq();
979
                header('Location: '.$redirectUrl);
980
                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...
981
            }
982
        }
983
    }
984
985
    /**
986
     * This function displays a wiki entry
987
     * @author Patrick Cool <[email protected]>, Ghent University
988
     * @author Juan Carlos Raña Trabado
989
     * @param string $newtitle
990
     * @return string html code
991
     **/
992
    public function display_wiki_entry($newtitle)
993
    {
994
        $tbl_wiki = $this->tbl_wiki;
995
        $tbl_wiki_conf = $this->tbl_wiki_conf;
996
        $condition_session = $this->condition_session;
997
        $groupfilter = $this->groupfilter;
998
        $page = $this->page;
999
1000
        $session_id = api_get_session_id();
1001
        $course_id = api_get_course_int_id();
1002
1003
        if ($newtitle) {
1004
            $pageMIX = $newtitle; //display the page after it is created
1005
        } else {
1006
            $pageMIX = $page; //display current page
1007
        }
1008
1009
        $filter = null;
1010
        if (isset($_GET['view']) && $_GET['view']) {
1011
            $_clean['view'] = Database::escape_string($_GET['view']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
$_clean was never initialized. Although not strictly required by PHP, it is generally a good practice to add $_clean = array(); before regardless.
Loading history...
1012
            $filter = ' AND w.id="'.$_clean['view'].'"';
1013
        }
1014
1015
        // First, check page visibility in the first page version
1016
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1017
                WHERE
1018
                    c_id = '.$course_id.' AND
1019
                    reflink="'.Database::escape_string($pageMIX).'" AND
1020
                   '.$groupfilter.$condition_session.'
1021
                ORDER BY id ASC';
1022
        $result = Database::query($sql);
1023
        $row = Database::fetch_array($result, 'ASSOC');
1024
1025
        $KeyVisibility = $row['visibility'];
1026
1027
        // second, show the last version
1028
        $sql = 'SELECT * FROM '.$tbl_wiki.' w
1029
                INNER JOIN '.$tbl_wiki_conf.' wc
1030
                ON (wc.page_id = w.page_id AND wc.c_id = w.c_id)
1031
                WHERE
1032
                    w.c_id 		  = '.$course_id.' AND
1033
                    w.reflink	  = "'.Database::escape_string($pageMIX).'" AND
1034
                    w.session_id  = '.$session_id.' AND
1035
                    w.'.$groupfilter.'  '.$filter.'
1036
                ORDER BY id DESC';
1037
1038
        $result = Database::query($sql);
1039
        // we do not need a while loop since we are always displaying the last version
1040
        $row = Database::fetch_array($result, 'ASSOC');
1041
1042
        //log users access to wiki (page_id)
1043
        if (!empty($row['page_id'])) {
1044
            Event::addEvent(LOG_WIKI_ACCESS, LOG_WIKI_PAGE_ID, $row['page_id']);
1045
        }
1046
        //update visits
1047
        if ($row['id']) {
1048
            $sql = 'UPDATE '.$tbl_wiki.' SET hits=(hits+1)
1049
                    WHERE c_id = '.$course_id.' AND id='.$row['id'].'';
1050
            Database::query($sql);
1051
        }
1052
1053
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1054
1055
        // if both are empty and we are displaying the index page then we display the default text.
1056
        if ($row['content'] == '' && $row['title'] == '' && $page == 'index') {
1057
            if (api_is_allowed_to_edit(false, true) ||
1058
                api_is_platform_admin() ||
1059
                GroupManager::is_user_in_group(api_get_user_id(), $groupInfo) ||
1060
                api_is_allowed_in_course()
1061
            ) {
1062
                //Table structure for better export to pdf
1063
                $default_table_for_content_Start = '<table align="center" border="0"><tr><td align="center">';
1064
                $default_table_for_content_End = '</td></tr></table>';
1065
                $content = $default_table_for_content_Start.
1066
                    sprintf(
1067
                        get_lang('DefaultContent'),
1068
                        api_get_path(WEB_IMG_PATH)
1069
                    ).
1070
                    $default_table_for_content_End;
1071
                $title = get_lang('DefaultTitle');
1072
            } else {
1073
                return Display::addFlash(
0 ignored issues
show
Bug introduced by
Are you sure the usage of Display::addFlash(Displa...By'), 'normal', false)) targeting Display::addFlash() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1074
                    Display::return_message(
1075
                        get_lang('WikiStandBy'),
1076
                        'normal',
1077
                        false
1078
                    )
1079
                );
1080
            }
1081
        } else {
1082
            $content = Security::remove_XSS($row['content']);
1083
            $title = Security::remove_XSS($row['title']);
1084
        }
1085
1086
        //assignment mode: identify page type
1087
        $icon_assignment = null;
1088
        if ($row['assignment'] == 1) {
1089
            $icon_assignment = Display::return_icon(
1090
                'wiki_assignment.png',
1091
                get_lang('AssignmentDescExtra'),
1092
                '',
1093
                ICON_SIZE_SMALL
1094
            );
1095
        } elseif ($row['assignment'] == 2) {
1096
            $icon_assignment = Display::return_icon(
1097
                'wiki_work.png',
1098
                get_lang('AssignmentWork'),
1099
                '',
1100
                ICON_SIZE_SMALL
1101
            );
1102
        }
1103
1104
        // task mode
1105
        $icon_task = null;
1106
        if (!empty($row['task'])) {
1107
            $icon_task = Display::return_icon(
1108
                'wiki_task.png',
1109
                get_lang('StandardTask'),
1110
                '',
1111
                ICON_SIZE_SMALL
1112
            );
1113
        }
1114
1115
        // Show page. Show page to all users if isn't hide page. Mode assignments: if student is the author, can view
1116
        if ($KeyVisibility == "1" ||
1117
            api_is_allowed_to_edit(false, true) ||
1118
            api_is_platform_admin() ||
1119
            ($row['assignment'] == 2 && $KeyVisibility == "0" && (api_get_user_id() == $row['user_id'])) ||
1120
            api_is_allowed_in_course()
1121
        ) {
1122
            $actionsLeft = '';
1123
            // menu edit page
1124
            $editLink = '<a href="index.php?'.api_get_cidreq().'&action=edit&title='.api_htmlentities(urlencode($page)).'"'.self::is_active_navigation_tab('edit').'>'.
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::is_active_navigation_tab() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1124
            $editLink = '<a href="index.php?'.api_get_cidreq().'&action=edit&title='.api_htmlentities(urlencode($page)).'"'.self::/** @scrutinizer ignore-call */ is_active_navigation_tab('edit').'>'.
Loading history...
1125
                Display::return_icon(
1126
                    'edit.png',
1127
                    get_lang('EditThisPage'),
1128
                    '',
1129
                    ICON_SIZE_MEDIUM
1130
                ).'</a>';
1131
1132
            if (api_is_allowed_to_edit(false, true)) {
1133
                $actionsLeft .= $editLink;
1134
            } else {
1135
                if ((api_is_allowed_in_course() ||
1136
                    GroupManager::is_user_in_group(
1137
                        api_get_user_id(),
1138
                        $groupInfo
1139
                    ))
1140
                ) {
1141
                    $actionsLeft .= $editLink;
1142
                } else {
1143
                    $actionsLeft .= '';
1144
                }
1145
            }
1146
1147
            $actionsRight = '';
1148
1149
            $protect_page = null;
1150
            $lock_unlock_protect = null;
1151
            // page action: protecting (locking) the page
1152
            if (api_is_allowed_to_edit(false, true) ||
1153
                api_is_platform_admin()
1154
            ) {
1155
                if (self::check_protect_page() == 1) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_protect_page() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1155
                if (self::/** @scrutinizer ignore-call */ check_protect_page() == 1) {
Loading history...
1156
                    $protect_page = Display::return_icon(
1157
                        'lock.png',
1158
                        get_lang('PageLockedExtra'),
1159
                        '',
1160
                        ICON_SIZE_MEDIUM
1161
                    );
1162
                    $lock_unlock_protect = 'unlock';
1163
                } else {
1164
                    $protect_page = Display::return_icon(
1165
                        'unlock.png',
1166
                        get_lang('PageUnlockedExtra'),
1167
                        '',
1168
                        ICON_SIZE_MEDIUM
1169
                    );
1170
                    $lock_unlock_protect = 'lock';
1171
                }
1172
            }
1173
1174
            if ($row['id']) {
1175
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_protect.'&title='.api_htmlentities(urlencode($page)).'">'.
1176
                $protect_page.'</a>';
1177
            }
1178
1179
            $visibility_page = null;
1180
            $lock_unlock_visibility = null;
1181
            //page action: visibility
1182
            if (api_is_allowed_to_edit(false, true) ||
1183
                api_is_platform_admin()
1184
            ) {
1185
                if (self::check_visibility_page() == 1) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_visibility_page() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1185
                if (self::/** @scrutinizer ignore-call */ check_visibility_page() == 1) {
Loading history...
1186
                    $visibility_page = Display::return_icon(
1187
                        'visible.png',
1188
                        get_lang('ShowPageExtra'),
1189
                        '',
1190
                        ICON_SIZE_MEDIUM
1191
                    );
1192
                    $lock_unlock_visibility = 'invisible';
1193
                } else {
1194
                    $visibility_page = Display::return_icon(
1195
                        'invisible.png',
1196
                        get_lang('HidePageExtra'),
1197
                        '',
1198
                        ICON_SIZE_MEDIUM
1199
                    );
1200
                    $lock_unlock_visibility = 'visible';
1201
                }
1202
            }
1203
1204
            if ($row['id']) {
1205
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_visibility.'&title='.api_htmlentities(urlencode($page)).'">'.
1206
                    $visibility_page.'</a>';
1207
            }
1208
1209
            //page action: notification
1210
            if (api_is_allowed_to_session_edit()) {
1211
                if (self::check_notify_page($page) == 1) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_notify_page() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1211
                if (self::/** @scrutinizer ignore-call */ check_notify_page($page) == 1) {
Loading history...
1212
                    $notify_page = Display::return_icon(
1213
                        'messagebox_info.png',
1214
                        get_lang('NotifyByEmail'),
1215
                        '',
1216
                        ICON_SIZE_MEDIUM
1217
                    );
1218
                    $lock_unlock_notify_page = 'unlocknotify';
1219
                } else {
1220
                    $notify_page = Display::return_icon(
1221
                        'mail.png',
1222
                        get_lang('CancelNotifyByEmail'),
1223
                        '',
1224
                        ICON_SIZE_MEDIUM
1225
                    );
1226
                    $lock_unlock_notify_page = 'locknotify';
1227
                }
1228
            }
1229
1230
            // Only available if row['id'] is set
1231
            if ($row['id']) {
1232
                if (api_is_allowed_to_session_edit(false, true) &&
1233
                    api_is_allowed_to_edit() ||
1234
                    GroupManager::is_user_in_group(
1235
                        api_get_user_id(),
1236
                        $groupInfo
1237
                    )
1238
                ) {
1239
                    // menu discuss page
1240
                    $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=discuss&title='.api_htmlentities(
1241
                            urlencode($page)
1242
                        ).'" '.self::is_active_navigation_tab('discuss').'>'.
1243
                        Display::return_icon(
1244
                            'discuss.png',
1245
                            get_lang('DiscussThisPage'),
1246
                            '',
1247
                            ICON_SIZE_MEDIUM
1248
                        ).'</a>';
1249
                }
1250
1251
                //menu history
1252
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=history&title='.api_htmlentities(
1253
                        urlencode($page)
1254
                    ).'" '.self::is_active_navigation_tab('history').'>'.
1255
                    Display::return_icon(
1256
                        'history.png',
1257
                        get_lang('ShowPageHistory'),
1258
                        '',
1259
                        ICON_SIZE_MEDIUM
1260
                    ).'</a>';
1261
                //menu linkspages
1262
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'action=links&title='.api_htmlentities(
1263
                        urlencode($page)
1264
                    ).'" '.self::is_active_navigation_tab('links').'>'.
1265
                    Display::return_icon(
1266
                        'what_link_here.png',
1267
                        get_lang('LinksPages'),
1268
                        '',
1269
                        ICON_SIZE_MEDIUM
1270
                    ).'</a>';
1271
1272
                //menu delete wikipage
1273
                if (api_is_allowed_to_edit(false, true) ||
1274
                    api_is_platform_admin()
1275
                ) {
1276
                    $actionsRight .= '<a href="index.php?action=delete&'.api_get_cidreq().'&title='.api_htmlentities(
1277
                            urlencode($page)
1278
                        ).'"'.self::is_active_navigation_tab('delete').'>'.
1279
                        Display::return_icon(
1280
                            'delete.png',
1281
                            get_lang('DeleteThisPage'),
1282
                            '',
1283
                            ICON_SIZE_MEDIUM
1284
                        ).'</a>';
1285
                }
1286
1287
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_notify_page.'&title='.api_htmlentities(
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $lock_unlock_notify_page does not seem to be defined for all execution paths leading up to this point.
Loading history...
1288
                        urlencode($page)
1289
                    ).'">'.
1290
                    $notify_page.'</a>';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $notify_page does not seem to be defined for all execution paths leading up to this point.
Loading history...
1291
1292
                // Page action: copy last version to doc area
1293
                if (api_is_allowed_to_edit(false, true) ||
1294
                    api_is_platform_admin()
1295
                ) {
1296
                    $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export2doc&wiki_id='.$row['id'].'">'.
1297
                        Display::return_icon(
1298
                            'export_to_documents.png',
1299
                            get_lang('ExportToDocArea'),
1300
                            '',
1301
                            ICON_SIZE_MEDIUM
1302
                        ).'</a>';
1303
                }
1304
1305
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export_to_pdf&wiki_id='.$row['id'].'">'.
1306
                    Display::return_icon(
1307
                        'pdf.png',
1308
                        get_lang('ExportToPDF'),
1309
                        '',
1310
                        ICON_SIZE_MEDIUM
1311
                    ).'</a>';
1312
1313
                $unoconv = api_get_configuration_value('unoconv.binaries');
1314
                if ($unoconv) {
1315
                    $actionsRight .= '<a href="'.api_get_path(WEB_CODE_PATH).'wiki/index.php?action=export_to_doc_file&id='.$row['id'].'&'.api_get_cidreq().'">'.
1316
                        Display::return_icon(
1317
                            'export_doc.png',
1318
                            get_lang('ExportToDoc'),
1319
                            [],
1320
                            ICON_SIZE_MEDIUM
1321
                        ).'</a>';
1322
                }
1323
1324
                //export to print?>
1325
                <script>
1326
                    function goprint() {
1327
                        var a = window.open('', '', 'width=800,height=600');
1328
                        a.document.open("text/html");
1329
                        a.document.write($('#wikicontent .panel-heading').html());
1330
                        a.document.write($('#wikicontent .panel-body').html());
1331
                        a.document.close();
1332
                        a.print();
1333
                    }
1334
                </script>
1335
                <?php
1336
                $actionsRight .= Display::url(
1337
                    Display::return_icon(
1338
                        'printer.png',
1339
                        get_lang('Print'),
1340
                        '',
1341
                        ICON_SIZE_MEDIUM
1342
                    ),
1343
                    '#',
1344
                    ['onclick' => "javascript: goprint();"]
1345
                );
1346
            }
1347
1348
            echo Display::toolbarAction(
1349
                'toolbar-wikistudent',
1350
                [$actionsLeft, $actionsRight]
1351
            );
1352
1353
            if (self::wiki_exist($title)) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::wiki_exist() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1353
            if (self::/** @scrutinizer ignore-call */ wiki_exist($title)) {
Loading history...
1354
                $pageTitle = $icon_assignment.'&nbsp;'.
1355
                    $icon_task.'&nbsp;'.api_htmlentities($title);
1356
            } else {
1357
                $pageTitle = api_htmlentities($title);
1358
            }
1359
1360
            $pageWiki = self::make_wiki_link_clickable(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::make_wiki_link_clickable() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1360
            /** @scrutinizer ignore-call */ 
1361
            $pageWiki = self::make_wiki_link_clickable(
Loading history...
1361
                self::detect_external_link(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::detect_external_link() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1361
                self::/** @scrutinizer ignore-call */ 
1362
                      detect_external_link(
Loading history...
1362
                    self::detect_anchor_link(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::detect_anchor_link() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1362
                    self::/** @scrutinizer ignore-call */ 
1363
                          detect_anchor_link(
Loading history...
1363
                        self::detect_mail_link(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::detect_mail_link() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1363
                        self::/** @scrutinizer ignore-call */ 
1364
                              detect_mail_link(
Loading history...
1364
                            self::detect_ftp_link(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::detect_ftp_link() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1364
                            self::/** @scrutinizer ignore-call */ 
1365
                                  detect_ftp_link(
Loading history...
1365
                                self::detect_irc_link(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::detect_irc_link() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1365
                                self::/** @scrutinizer ignore-call */ 
1366
                                      detect_irc_link(
Loading history...
1366
                                    self::detect_news_link($content)
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::detect_news_link() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1366
                                    self::/** @scrutinizer ignore-call */ 
1367
                                          detect_news_link($content)
Loading history...
1367
                                )
1368
                            )
1369
                        )
1370
                    )
1371
                )
1372
            );
1373
1374
            $footerWiki =
1375
                get_lang('Progress').': '.($row['progress'] * 10).'%&nbsp;&nbsp;&nbsp;'.
1376
                get_lang('Rating').': '.$row['score'].'&nbsp;&nbsp;&nbsp;'.
1377
                get_lang('Words').': '.self::word_count($content);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::word_count() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1377
                get_lang('Words').': '.self::/** @scrutinizer ignore-call */ word_count($content);
Loading history...
1378
            // wikicontent require to print wiki document
1379
            echo '<div id="wikicontent">'.Display::panel($pageWiki, $pageTitle, $footerWiki).'</div>';
1380
        } //end filter visibility
1381
    }
1382
1383
    /**
1384
     * This function counted the words in a document. Thanks Adeel Khan
1385
     * @param   string  Document's text
1386
     * @return  int     Number of words
1387
     */
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...
1388
    public function word_count($document)
1389
    {
1390
        $search = [
1391
            '@<script[^>]*?>.*?</script>@si',
1392
            '@<style[^>]*?>.*?</style>@siU',
1393
            '@<div id="player.[^>]*?>.*?</div>@',
1394
            '@<![\s\S]*?--[ \t\n\r]*>@'
1395
        ];
1396
1397
        $document = preg_replace($search, '', $document);
1398
1399
        # strip all html tags
1400
        $wc = strip_tags($document);
1401
        $wc = html_entity_decode(
1402
            $wc,
1403
            ENT_NOQUOTES,
1404
            'UTF-8'
1405
        ); // TODO:test also old html_entity_decode(utf8_encode($wc))
1406
1407
        # remove 'words' that don't consist of alphanumerical characters or punctuation. And fix accents and some letters
1408
        $pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@|á|é|í|ó|ú|à|è|ì|ò|ù|ä|ë|ï|ö|ü|Á|É|Í|Ó|Ú|À|È|Ò|Ù|Ä|Ë|Ï|Ö|Ü|â|ê|î|ô|û|Â|Ê|Î|Ô|Û|ñ|Ñ|ç|Ç)]+#";
1409
        $wc = trim(preg_replace($pattern, " ", $wc));
1410
1411
        # remove one-letter 'words' that consist only of punctuation
1412
        $wc = trim(
1413
            preg_replace(
1414
                "#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#",
1415
                " ",
1416
                $wc
1417
            )
1418
        );
1419
1420
        # remove superfluous whitespace
1421
        $wc = preg_replace("/\s\s+/", " ", $wc);
1422
1423
        # split string into an array of words
1424
        $wc = explode(" ", $wc);
1425
1426
        # remove empty elements
1427
        $wc = array_filter($wc);
1428
1429
        # return the number of words
1430
        return count($wc);
1431
    }
1432
1433
    /**
1434
     * This function checks if wiki title exist
1435
     */
1436
    public function wiki_exist($title)
1437
    {
1438
        $tbl_wiki = $this->tbl_wiki;
1439
        $groupfilter = $this->groupfilter;
1440
        $condition_session = $this->condition_session;
1441
        $course_id = api_get_course_int_id();
1442
1443
        $sql = 'SELECT id FROM '.$tbl_wiki.'
1444
              WHERE
1445
                c_id = '.$course_id.' AND
1446
                title="'.Database::escape_string($title).'" AND
1447
                '.$groupfilter.$condition_session.'
1448
              ORDER BY id ASC';
1449
        $result = Database::query($sql);
1450
        $cant = Database::num_rows($result);
1451
        if ($cant > 0) {
1452
            return true;
1453
        } else {
1454
            return false;
1455
        }
1456
    }
1457
1458
    /**
1459
     * Checks if this navigation tab has to be set to active
1460
     * @author Patrick Cool <[email protected]>, Ghent University
1461
     *
1462
     * @return string html code
1463
     */
1464
    public function is_active_navigation_tab($paramwk)
1465
    {
1466
        if (isset($_GET['action']) && $_GET['action'] == $paramwk) {
1467
            return ' class="active"';
1468
        }
1469
    }
1470
1471
    /**
1472
     * Lock add pages
1473
     * @author Juan Carlos Raña <[email protected]>
1474
     * return current database status of protect page and change it if get action
1475
     */
1476
    public function check_addnewpagelock()
1477
    {
1478
        $tbl_wiki = $this->tbl_wiki;
1479
        $condition_session = $this->condition_session;
1480
        $groupfilter = $this->groupfilter;
1481
        $course_id = api_get_course_int_id();
1482
1483
        $sql = 'SELECT *
1484
                FROM '.$tbl_wiki.'
1485
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1486
                ORDER BY id ASC';
1487
1488
        $result = Database::query($sql);
1489
        $row = Database::fetch_array($result);
1490
1491
        $status_addlock = $row['addlock'];
1492
1493
        // Change status
1494
        if (api_is_allowed_to_edit(false, true) ||
1495
            api_is_platform_admin()
1496
        ) {
1497
            if (isset($_GET['actionpage'])) {
1498
                if ($_GET['actionpage'] == 'lockaddnew' && $status_addlock == 1) {
1499
                    $status_addlock = 0;
1500
                }
1501
                if ($_GET['actionpage'] == 'unlockaddnew' && $status_addlock == 0) {
1502
                    $status_addlock = 1;
1503
                }
1504
                $sql = 'UPDATE '.$tbl_wiki.' SET
1505
                            addlock="'.Database::escape_string($status_addlock).'"
1506
                        WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session;
1507
                Database::query($sql);
1508
            }
1509
1510
            $sql = 'SELECT *
1511
                    FROM '.$tbl_wiki.'
1512
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1513
                    ORDER BY id ASC';
1514
            $result = Database::query($sql);
1515
            $row = Database::fetch_array($result);
1516
        }
1517
1518
        return $row['addlock'];
1519
    }
1520
1521
    /**
1522
     * Protect page
1523
     * @author Juan Carlos Raña <[email protected]>
1524
     * return current database status of protect page and change it if get action
1525
     */
1526
    public function check_protect_page()
1527
    {
1528
        $tbl_wiki = $this->tbl_wiki;
1529
        $condition_session = $this->condition_session;
1530
        $groupfilter = $this->groupfilter;
1531
        $page = $this->page;
1532
1533
        $course_id = api_get_course_int_id();
1534
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1535
              WHERE
1536
                c_id = '.$course_id.' AND
1537
                reflink="'.Database::escape_string($page).'" AND
1538
                '.$groupfilter.$condition_session.'
1539
              ORDER BY id ASC';
1540
1541
        $result = Database::query($sql);
1542
        $row = Database::fetch_array($result);
1543
        $status_editlock = $row['editlock'];
1544
        $id = $row['page_id'];
1545
1546
        // Change status
1547
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1548
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'lock' && $status_editlock == 0) {
1549
                $status_editlock = 1;
1550
            }
1551
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlock' && $status_editlock == 1) {
1552
                $status_editlock = 0;
1553
            }
1554
1555
            $sql = 'UPDATE '.$tbl_wiki.' SET 
1556
                    editlock="'.Database::escape_string($status_editlock).'"
1557
                    WHERE c_id = '.$course_id.' AND page_id="'.$id.'"';
1558
            Database::query($sql);
1559
1560
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1561
                    WHERE
1562
                        c_id = '.$course_id.' AND
1563
                        reflink="'.Database::escape_string($page).'" AND
1564
                    '.$groupfilter.$condition_session.'
1565
                  ORDER BY id ASC';
1566
            $result = Database::query($sql);
1567
            $row = Database::fetch_array($result);
1568
        }
1569
1570
        //show status
1571
        return $row['editlock'];
1572
    }
1573
1574
    /**
1575
     * Visibility page
1576
     * @author Juan Carlos Raña <[email protected]>
1577
     * return current database status of visibility and change it if get action
1578
     */
1579
    public function check_visibility_page()
1580
    {
1581
        $tbl_wiki = $this->tbl_wiki;
1582
        $page = $this->page;
1583
        $condition_session = $this->condition_session;
1584
        $groupfilter = $this->groupfilter;
1585
        $course_id = api_get_course_int_id();
1586
1587
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1588
                WHERE
1589
                    c_id = '.$course_id.' AND
1590
                    reflink="'.Database::escape_string($page).'" AND
1591
                    '.$groupfilter.$condition_session.'
1592
                ORDER BY id ASC';
1593
        $result = Database::query($sql);
1594
        $row = Database::fetch_array($result);
1595
        $status_visibility = $row['visibility'];
1596
        //change status
1597
        if (api_is_allowed_to_edit(false, true) ||
1598
            api_is_platform_admin()
1599
        ) {
1600
            if (isset($_GET['actionpage']) &&
1601
                $_GET['actionpage'] == 'visible' &&
1602
                $status_visibility == 0
1603
            ) {
1604
                $status_visibility = 1;
1605
            }
1606
            if (isset($_GET['actionpage']) &&
1607
                $_GET['actionpage'] == 'invisible' &&
1608
                $status_visibility == 1
1609
            ) {
1610
                $status_visibility = 0;
1611
            }
1612
1613
            $sql = 'UPDATE '.$tbl_wiki.' SET 
1614
                    visibility = "'.Database::escape_string($status_visibility).'"
1615
                    WHERE 
1616
                        c_id = '.$course_id.' AND 
1617
                        reflink="'.Database::escape_string($page).'" AND 
1618
                        '.$groupfilter.$condition_session;
1619
            Database::query($sql);
1620
1621
            // Although the value now is assigned to all (not only the first),
1622
            // these three lines remain necessary.
1623
            // They do that by changing the page state is
1624
            // made when you press the button and not have to wait to change his page
1625
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1626
                    WHERE
1627
                        c_id = '.$course_id.' AND
1628
                        reflink="'.Database::escape_string($page).'" AND
1629
                        '.$groupfilter.$condition_session.'
1630
                    ORDER BY id ASC';
1631
            $result = Database::query($sql);
1632
            $row = Database::fetch_array($result);
1633
        }
1634
1635
        if (empty($row['id'])) {
1636
            $row['visibility'] = 1;
1637
        }
1638
1639
        //show status
1640
        return $row['visibility'];
1641
    }
1642
1643
    /**
1644
     * Visibility discussion
1645
     * @author Juan Carlos Raña <[email protected]>
1646
     * @return int current database status of discuss visibility
1647
     * and change it if get action page
1648
     */
1649
    public function check_visibility_discuss()
1650
    {
1651
        $tbl_wiki = $this->tbl_wiki;
1652
        $page = $this->page;
1653
        $condition_session = $this->condition_session;
1654
        $groupfilter = $this->groupfilter;
1655
        $course_id = api_get_course_int_id();
1656
1657
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1658
                WHERE
1659
                    c_id = '.$course_id.' AND
1660
                    reflink="'.Database::escape_string($page).'" AND
1661
                    '.$groupfilter.$condition_session.'
1662
                ORDER BY id ASC';
1663
        $result = Database::query($sql);
1664
        $row = Database::fetch_array($result);
1665
1666
        $status_visibility_disc = $row['visibility_disc'];
1667
1668
        //change status
1669
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1670
            if (isset($_GET['actionpage']) &&
1671
                $_GET['actionpage'] == 'showdisc' &&
1672
                $status_visibility_disc == 0
1673
            ) {
1674
                $status_visibility_disc = 1;
1675
            }
1676
            if (isset($_GET['actionpage']) &&
1677
                $_GET['actionpage'] == 'hidedisc' &&
1678
                $status_visibility_disc == 1
1679
            ) {
1680
                $status_visibility_disc = 0;
1681
            }
1682
1683
            $sql = 'UPDATE '.$tbl_wiki.' SET 
1684
                    visibility_disc="'.Database::escape_string($status_visibility_disc).'"
1685
                    WHERE
1686
                        c_id = '.$course_id.' AND
1687
                        reflink="'.Database::escape_string($page).'" AND
1688
                        '.$groupfilter.$condition_session;
1689
            Database::query($sql);
1690
1691
            // Although the value now is assigned to all (not only the first),
1692
            // these three lines remain necessary.
1693
            // They do that by changing the page state is made when you press
1694
            // the button and not have to wait to change his page
1695
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1696
                    WHERE
1697
                        c_id = '.$course_id.' AND
1698
                        reflink="'.Database::escape_string($page).'" AND
1699
                        '.$groupfilter.$condition_session.'
1700
                    ORDER BY id ASC';
1701
            $result = Database::query($sql);
1702
            $row = Database::fetch_array($result);
1703
        }
1704
1705
        return $row['visibility_disc'];
1706
    }
1707
1708
    /**
1709
     * Lock add discussion
1710
     * @author Juan Carlos Raña <[email protected]>
1711
     * @return int current database status of lock dicuss and change if get action
1712
     */
1713
    public function check_addlock_discuss()
1714
    {
1715
        $tbl_wiki = $this->tbl_wiki;
1716
        $page = $this->page;
1717
        $condition_session = $this->condition_session;
1718
        $groupfilter = $this->groupfilter;
1719
        $course_id = api_get_course_int_id();
1720
1721
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1722
                WHERE
1723
                    c_id = '.$course_id.' AND
1724
                    reflink="'.Database::escape_string($page).'" AND
1725
                    '.$groupfilter.$condition_session.'
1726
                ORDER BY id ASC';
1727
        $result = Database::query($sql);
1728
        $row = Database::fetch_array($result);
1729
1730
        $status_addlock_disc = $row['addlock_disc'];
1731
1732
        //change status
1733
        if (api_is_allowed_to_edit() || api_is_platform_admin()) {
1734
            if (isset($_GET['actionpage']) &&
1735
                $_GET['actionpage'] == 'lockdisc' &&
1736
                $status_addlock_disc == 0
1737
            ) {
1738
                $status_addlock_disc = 1;
1739
            }
1740
            if (isset($_GET['actionpage']) &&
1741
                $_GET['actionpage'] == 'unlockdisc' &&
1742
                $status_addlock_disc == 1
1743
            ) {
1744
                $status_addlock_disc = 0;
1745
            }
1746
1747
            $sql = 'UPDATE '.$tbl_wiki.' SET
1748
                    addlock_disc="'.Database::escape_string($status_addlock_disc).'"
1749
                    WHERE
1750
                        c_id = '.$course_id.' AND
1751
                        reflink = "'.Database::escape_string($page).'" AND
1752
                         '.$groupfilter.$condition_session;
1753
            Database::query($sql);
1754
1755
            // Although the value now is assigned to all (not only the first),
1756
            // these three lines remain necessary.
1757
            // They do that by changing the page state is made when you press
1758
            // the button and not have to wait to change his page
1759
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1760
                    WHERE
1761
                        c_id = '.$course_id.' AND
1762
                        reflink="'.Database::escape_string($page).'" AND
1763
                        '.$groupfilter.$condition_session.'
1764
                    ORDER BY id ASC';
1765
            $result = Database::query($sql);
1766
            $row = Database::fetch_array($result);
1767
        }
1768
1769
        return $row['addlock_disc'];
1770
    }
1771
1772
    /**
1773
     * Lock rating discussion
1774
     * @author Juan Carlos Raña <[email protected]>
1775
     * @return  int  current database status of rating discuss and change it if get action
1776
     */
1777
    public function check_ratinglock_discuss()
1778
    {
1779
        $tbl_wiki = $this->tbl_wiki;
1780
        $page = $this->page;
1781
        $condition_session = $this->condition_session;
1782
        $groupfilter = $this->groupfilter;
1783
        $course_id = api_get_course_int_id();
1784
1785
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1786
                WHERE
1787
                    c_id = '.$course_id.' AND
1788
                    reflink="'.Database::escape_string($page).'" AND
1789
                    '.$groupfilter.$condition_session.'
1790
                ORDER BY id ASC';
1791
        $result = Database::query($sql);
1792
        $row = Database::fetch_array($result);
1793
        $status_ratinglock_disc = $row['ratinglock_disc'];
1794
1795
        //change status
1796
        if (api_is_allowed_to_edit(false, true) ||
1797
            api_is_platform_admin()
1798
        ) {
1799
            if (isset($_GET['actionpage']) &&
1800
                $_GET['actionpage'] == 'lockrating' &&
1801
                $status_ratinglock_disc == 0
1802
            ) {
1803
                $status_ratinglock_disc = 1;
1804
            }
1805
            if (isset($_GET['actionpage']) &&
1806
                $_GET['actionpage'] == 'unlockrating' &&
1807
                $status_ratinglock_disc == 1
1808
            ) {
1809
                $status_ratinglock_disc = 0;
1810
            }
1811
1812
            $sql = 'UPDATE '.$tbl_wiki.'
1813
                    SET ratinglock_disc="'.Database::escape_string($status_ratinglock_disc).'"
1814
                    WHERE
1815
                        c_id = '.$course_id.' AND
1816
                        reflink="'.Database::escape_string($page).'" AND
1817
                        '.$groupfilter.$condition_session;
1818
            // Visibility. Value to all,not only for the first
1819
            Database::query($sql);
1820
1821
            // Although the value now is assigned to all (not only the first),
1822
            // these three lines remain necessary. They do that by changing the
1823
            // page state is made when you press the button and not have to wait
1824
            // to change his page
1825
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1826
                    WHERE
1827
                        c_id = '.$course_id.' AND
1828
                        reflink="'.Database::escape_string($page).'" AND
1829
                    '.$groupfilter.$condition_session.'
1830
                  ORDER BY id ASC';
1831
            $result = Database::query($sql);
1832
            $row = Database::fetch_array($result);
1833
        }
1834
1835
        return $row['ratinglock_disc'];
1836
    }
1837
1838
    /**
1839
     * Notify page changes
1840
     * @author Juan Carlos Raña <[email protected]>
1841
     * @return int the current notification status
1842
     */
1843
    public function check_notify_page($reflink)
1844
    {
1845
        $tbl_wiki = $this->tbl_wiki;
1846
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1847
        $condition_session = $this->condition_session;
1848
        $groupfilter = $this->groupfilter;
1849
        $groupId = api_get_group_id();
1850
        $session_id = api_get_session_id();
1851
        $course_id = api_get_course_int_id();
1852
        $userId = api_get_user_id();
1853
1854
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1855
                WHERE 
1856
                    c_id = '.$course_id.' AND 
1857
                    reflink="'.$reflink.'" AND 
1858
                    '.$groupfilter.$condition_session.'
1859
                ORDER BY id ASC';
1860
        $result = Database::query($sql);
1861
        $row = Database::fetch_array($result);
1862
        $id = $row['id'];
1863
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1864
                WHERE
1865
                    c_id = '.$course_id.' AND 
1866
                    id="'.$id.'" AND 
1867
                    user_id="'.api_get_user_id().'" AND 
1868
                    type="P"';
1869
        $result = Database::query($sql);
1870
        $row = Database::fetch_array($result);
1871
        $idm = $row['id'];
1872
        if (empty($idm)) {
1873
            $status_notify = 0;
1874
        } else {
1875
            $status_notify = 1;
1876
        }
1877
1878
        // Change status
1879
        if (isset($_GET['actionpage']) &&
1880
            $_GET['actionpage'] == 'locknotify' &&
1881
            $status_notify == 0
1882
        ) {
1883
            $sql = "SELECT id FROM $tbl_wiki_mailcue
1884
                    WHERE c_id = $course_id AND id = $id AND user_id = $userId";
1885
            $result = Database::query($sql);
1886
            $exist = false;
1887
            if (Database::num_rows($result)) {
1888
                $exist = true;
1889
            }
1890
            if ($exist == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1891
                $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1892
                ($course_id, '".$id."','".api_get_user_id(
1893
                    )."','P','".$groupId."','".$session_id."')";
1894
                Database::query($sql);
1895
            }
1896
            $status_notify = 1;
1897
        }
1898
1899
        if (isset($_GET['actionpage']) &&
1900
            $_GET['actionpage'] == 'unlocknotify' &&
1901
            $status_notify == 1
1902
        ) {
1903
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1904
                    WHERE 
1905
                        id="'.$id.'" AND 
1906
                        user_id="'.api_get_user_id().'" AND 
1907
                        type="P" AND 
1908
                        c_id = '.$course_id;
1909
            Database::query($sql);
1910
            $status_notify = 0;
1911
        }
1912
1913
        return $status_notify;
1914
    }
1915
1916
    /**
1917
     * Notify discussion changes
1918
     * @author Juan Carlos Raña <[email protected]>
1919
     * @param string $reflink
1920
     * @return int current database status of rating discuss and change it if get action
1921
     */
1922
    public function check_notify_discuss($reflink)
1923
    {
1924
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1925
        $tbl_wiki = $this->tbl_wiki;
1926
        $condition_session = $this->condition_session;
1927
        $groupfilter = $this->groupfilter;
1928
1929
        $course_id = api_get_course_int_id();
1930
        $groupId = api_get_group_id();
1931
        $session_id = api_get_session_id();
1932
1933
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1934
                WHERE 
1935
                    c_id = '.$course_id.' AND 
1936
                    reflink="'.$reflink.'" AND 
1937
                    '.$groupfilter.$condition_session.'
1938
                ORDER BY id ASC';
1939
        $result = Database::query($sql);
1940
        $row = Database::fetch_array($result);
1941
        $id = $row['id'];
1942
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1943
                WHERE 
1944
                    c_id = '.$course_id.' AND id="'.$id.'" AND user_id="'.api_get_user_id(
1945
            ).'" AND type="D"';
1946
        $result = Database::query($sql);
1947
        $row = Database::fetch_array($result);
1948
        $idm = $row['id'];
1949
1950
        if (empty($idm)) {
1951
            $status_notify_disc = 0;
1952
        } else {
1953
            $status_notify_disc = 1;
1954
        }
1955
1956
        // change status
1957
        if (isset($_GET['actionpage']) &&
1958
            $_GET['actionpage'] == 'locknotifydisc' &&
1959
            $status_notify_disc == 0
1960
        ) {
1961
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1962
            ($course_id, '".$id."','".api_get_user_id()."','D','".$groupId."','".$session_id."')";
1963
            Database::query($sql);
1964
            $status_notify_disc = 1;
1965
        }
1966
        if (isset($_GET['actionpage']) &&
1967
            $_GET['actionpage'] == 'unlocknotifydisc' &&
1968
            $status_notify_disc == 1
1969
        ) {
1970
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1971
                    WHERE 
1972
                        c_id = '.$course_id.' AND 
1973
                        id="'.$id.'" AND 
1974
                        user_id="'.api_get_user_id().'" AND 
1975
                        type="D" AND 
1976
                        c_id = '.$course_id;
1977
            Database::query($sql);
1978
            $status_notify_disc = 0;
1979
        }
1980
1981
        return $status_notify_disc;
1982
    }
1983
1984
    /**
1985
     * Notify all changes
1986
     * @author Juan Carlos Raña <[email protected]>
1987
     */
1988
    public function check_notify_all()
1989
    {
1990
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1991
        $course_id = api_get_course_int_id();
1992
        $groupId = api_get_group_id();
1993
        $session_id = api_get_session_id();
1994
1995
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1996
                WHERE
1997
                    c_id = '.$course_id.' AND
1998
                    user_id="'.api_get_user_id().'" AND
1999
                    type="F" AND
2000
                    group_id="'.$groupId.'" AND
2001
                    session_id="'.$session_id.'"';
2002
        $result = Database::query($sql);
2003
        $row = Database::fetch_array($result);
2004
2005
        $idm = $row['user_id'];
2006
2007
        if (empty($idm)) {
2008
            $status_notify_all = 0;
2009
        } else {
2010
            $status_notify_all = 1;
2011
        }
2012
2013
        //change status
2014
        if (isset($_GET['actionpage']) &&
2015
            $_GET['actionpage'] == 'locknotifyall' &&
2016
            $status_notify_all == 0
2017
        ) {
2018
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, user_id, type, group_id, session_id) VALUES
2019
            ($course_id, '".api_get_user_id(
2020
                )."','F','".$groupId."','".$session_id."')";
2021
            Database::query($sql);
2022
            $status_notify_all = 1;
2023
        }
2024
2025
        if (isset($_GET['actionpage']) &&
2026
            isset($_GET['actionpage']) &&
2027
            $_GET['actionpage'] == 'unlocknotifyall' &&
2028
            $status_notify_all == 1
2029
        ) {
2030
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
2031
                   WHERE
2032
                    c_id = '.$course_id.' AND
2033
                    user_id="'.api_get_user_id().'" AND
2034
                    type="F" AND
2035
                    group_id="'.$groupId.'" AND
2036
                    session_id="'.$session_id.'" AND
2037
                    c_id = '.$course_id;
2038
            Database::query($sql);
2039
            $status_notify_all = 0;
2040
        }
2041
2042
        //show status
2043
        return $status_notify_all;
2044
    }
2045
2046
    /**
2047
     * Sends pending e-mails
2048
     */
2049
    public function check_emailcue(
2050
        $id_or_ref,
2051
        $type,
2052
        $lastime = '',
2053
        $lastuser = ''
2054
    ) {
2055
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
2056
        $tbl_wiki = $this->tbl_wiki;
2057
        $condition_session = $this->condition_session;
2058
        $groupfilter = $this->groupfilter;
2059
        $_course = $this->courseInfo;
2060
        $groupId = api_get_group_id();
2061
        $session_id = api_get_session_id();
2062
        $course_id = api_get_course_int_id();
2063
        $group_properties = GroupManager::get_group_properties($groupId);
2064
        $group_name = $group_properties['name'];
2065
        $allow_send_mail = false; //define the variable to below
2066
        $email_assignment = null;
2067
        if ($type == 'P') {
2068
            //if modifying a wiki page
2069
            //first, current author and time
2070
            //Who is the author?
2071
            $userinfo = api_get_user_info($lastuser);
2072
            $email_user_author = get_lang(
2073
                    'EditedBy'
2074
                ).': '.$userinfo['complete_name'];
2075
2076
            //When ?
2077
            $year = substr($lastime, 0, 4);
2078
            $month = substr($lastime, 5, 2);
2079
            $day = substr($lastime, 8, 2);
2080
            $hours = substr($lastime, 11, 2);
2081
            $minutes = substr($lastime, 14, 2);
2082
            $seconds = substr($lastime, 17, 2);
2083
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2084
2085
            //second, extract data from first reg
2086
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2087
                    WHERE 
2088
                        c_id = '.$course_id.' AND 
2089
                        reflink="'.$id_or_ref.'" AND 
2090
                        '.$groupfilter.$condition_session.'
2091
                    ORDER BY id ASC';
2092
            $result = Database::query($sql);
2093
            $row = Database::fetch_array($result);
2094
            $id = $row['id'];
2095
            $email_page_name = $row['title'];
2096
            if ($row['visibility'] == 1) {
2097
                $allow_send_mail = true; //if visibility off - notify off
2098
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2099
                        WHERE
2100
                            c_id = '.$course_id.' AND
2101
                            id="'.$id.'" AND
2102
                            type="'.$type.'" OR
2103
                            type="F" AND
2104
                            group_id="'.$groupId.'" AND
2105
                            session_id="'.$session_id.'"';
2106
                //type: P=page, D=discuss, F=full.
2107
                $result = Database::query($sql);
2108
                $emailtext = get_lang('EmailWikipageModified').
2109
                    '<strong>'.$email_page_name.'</strong> '.
2110
                    get_lang('Wiki');
2111
            }
2112
        } elseif ($type == 'D') {
2113
            //if added a post to discuss
2114
            //first, current author and time
2115
            //Who is the author of last message?
2116
            $userinfo = api_get_user_info($lastuser);
2117
            $email_user_author = get_lang(
2118
                    'AddedBy'
2119
                ).': '.$userinfo['complete_name'];
2120
2121
            //When ?
2122
            $year = substr($lastime, 0, 4);
2123
            $month = substr($lastime, 5, 2);
2124
            $day = substr($lastime, 8, 2);
2125
            $hours = substr($lastime, 11, 2);
2126
            $minutes = substr($lastime, 14, 2);
2127
            $seconds = substr($lastime, 17, 2);
2128
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2129
            //second, extract data from first reg
2130
            $id = $id_or_ref; //$id_or_ref is id from tblwiki
2131
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2132
                    WHERE c_id = '.$course_id.' AND id="'.$id.'"
2133
                    ORDER BY id ASC';
2134
2135
            $result = Database::query($sql);
2136
            $row = Database::fetch_array($result);
2137
2138
            $email_page_name = $row['title'];
2139
            if ($row['visibility_disc'] == 1) {
2140
                $allow_send_mail = true; //if visibility off - notify off
2141
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2142
                        WHERE
2143
                            c_id = '.$course_id.' AND
2144
                            id="'.$id.'" AND
2145
                            type="'.$type.'" OR
2146
                            type="F" AND
2147
                            group_id="'.$groupId.'" AND
2148
                            session_id="'.$session_id.'"';
2149
                //type: P=page, D=discuss, F=full
2150
                $result = Database::query($sql);
2151
                $emailtext = get_lang(
2152
                        'EmailWikiPageDiscAdded'
2153
                    ).' <strong>'.$email_page_name.'</strong> '.get_lang(
2154
                        'Wiki'
2155
                    );
2156
            }
2157
        } elseif ($type == 'A') {
2158
            //for added pages
2159
            $id = 0; //for tbl_wiki_mailcue
2160
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2161
                    WHERE c_id = '.$course_id.'
2162
                    ORDER BY id DESC'; //the added is always the last
2163
2164
            $result = Database::query($sql);
2165
            $row = Database::fetch_array($result);
2166
            $email_page_name = $row['title'];
2167
2168
            //Who is the author?
2169
            $userinfo = api_get_user_info($row['user_id']);
2170
            $email_user_author = get_lang(
2171
                    'AddedBy'
2172
                ).': '.$userinfo['complete_name'];
2173
2174
            //When ?
2175
            $year = substr($row['dtime'], 0, 4);
2176
            $month = substr($row['dtime'], 5, 2);
2177
            $day = substr($row['dtime'], 8, 2);
2178
            $hours = substr($row['dtime'], 11, 2);
2179
            $minutes = substr($row['dtime'], 14, 2);
2180
            $seconds = substr($row['dtime'], 17, 2);
2181
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2182
2183
            if ($row['assignment'] == 0) {
2184
                $allow_send_mail = true;
2185
            } elseif ($row['assignment'] == 1) {
2186
                $email_assignment = get_lang(
2187
                        'AssignmentDescExtra'
2188
                    ).' ('.get_lang('AssignmentMode').')';
2189
                $allow_send_mail = true;
2190
            } elseif ($row['assignment'] == 2) {
2191
                $allow_send_mail = false; //Mode tasks: avoids notifications to all users about all users
2192
            }
2193
2194
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2195
                    WHERE
2196
                        c_id = '.$course_id.' AND  
2197
                        id="'.$id.'" AND 
2198
                        type="F" AND 
2199
                        group_id="'.$groupId.'" AND 
2200
                        session_id="'.$session_id.'"';
2201
2202
            //type: P=page, D=discuss, F=full
2203
            $result = Database::query($sql);
2204
2205
            $emailtext = get_lang(
2206
                    'EmailWikiPageAdded'
2207
                ).' <strong>'.$email_page_name.'</strong> '.get_lang(
2208
                    'In'
2209
                ).' '.get_lang('Wiki');
2210
        } elseif ($type == 'E') {
2211
            $id = 0;
2212
            $allow_send_mail = true;
2213
            // Who is the author?
2214
            $userinfo = api_get_user_info(api_get_user_id()); //current user
2215
            $email_user_author = get_lang('DeletedBy').': '.$userinfo['complete_name'];
2216
            //When ?
2217
            $today = date('r'); //current time
2218
            $email_date_changes = $today;
2219
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2220
                    WHERE
2221
                        c_id = '.$course_id.' AND
2222
                        id="'.$id.'" AND type="F" AND
2223
                        group_id="'.$groupId.'" AND
2224
                        session_id="'.$session_id.'"'; //type: P=page, D=discuss, F=wiki
2225
            $result = Database::query($sql);
2226
            $emailtext = get_lang('EmailWikipageDedeleted');
2227
        }
2228
        ///make and send email
2229
        if ($allow_send_mail) {
2230
            while ($row = Database::fetch_array($result)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.
Loading history...
2231
                $userinfo = api_get_user_info(
2232
                    $row['user_id']
2233
                ); //$row['user_id'] obtained from tbl_wiki_mailcue
2234
                $name_to = $userinfo['complete_name'];
2235
                $email_to = $userinfo['email'];
2236
                $sender_name = api_get_setting('emailAdministrator');
2237
                $sender_email = api_get_setting('emailAdministrator');
2238
                $email_subject = get_lang(
2239
                        'EmailWikiChanges'
2240
                    ).' - '.$_course['official_code'];
2241
                $email_body = get_lang('DearUser').' '.api_get_person_name(
2242
                        $userinfo['firstname'],
2243
                        $userinfo['lastname']
2244
                    ).',<br /><br />';
2245
                if ($session_id == 0) {
2246
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' - '.$group_name.'</strong><br /><br /><br />';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $emailtext does not seem to be defined for all execution paths leading up to this point.
Loading history...
2247
                } else {
2248
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' ('.api_get_session_name(
2249
                            api_get_session_id()
2250
                        ).') - '.$group_name.'</strong><br /><br /><br />';
2251
                }
2252
                $email_body .= $email_user_author.' ('.$email_date_changes.')<br /><br /><br />';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $email_date_changes does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $email_user_author does not seem to be defined for all execution paths leading up to this point.
Loading history...
2253
                $email_body .= $email_assignment.'<br /><br /><br />';
2254
                $email_body .= '<font size="-2">'.get_lang(
2255
                        'EmailWikiChangesExt_1'
2256
                    ).': <strong>'.get_lang('NotifyChanges').'</strong><br />';
2257
                $email_body .= get_lang(
2258
                        'EmailWikiChangesExt_2'
2259
                    ).': <strong>'.get_lang(
2260
                        'NotNotifyChanges'
2261
                    ).'</strong></font><br />';
2262
                @api_mail_html(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for api_mail_html(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

2262
                /** @scrutinizer ignore-unhandled */ @api_mail_html(

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2263
                    $name_to,
2264
                    $email_to,
2265
                    $email_subject,
2266
                    $email_body,
2267
                    $sender_name,
2268
                    $sender_email
2269
                );
2270
            }
2271
        }
2272
    }
2273
2274
    /**
2275
     * Function export last wiki page version to document area
2276
     * @param int $doc_id wiki page id
2277
     * @return mixed
2278
     * @author Juan Carlos Raña <[email protected]>
2279
     */
2280
    public function export2doc($doc_id)
2281
    {
2282
        $_course = $this->courseInfo;
2283
        $groupId = api_get_group_id();
2284
        $groupInfo = GroupManager::get_group_properties($groupId);
2285
        $data = self::getWikiDataFromDb($doc_id);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getWikiDataFromDb() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2285
        /** @scrutinizer ignore-call */ 
2286
        $data = self::getWikiDataFromDb($doc_id);
Loading history...
2286
2287
        if (empty($data)) {
2288
            return false;
2289
        }
2290
2291
        $wikiTitle = $data['title'];
2292
        $wikiContents = $data['content'];
2293
2294
        $template =
2295
            '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2296
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{LANGUAGE}" lang="{LANGUAGE}">
2297
            <head>
2298
            <title>{TITLE}</title>
2299
            <meta http-equiv="Content-Type" content="text/html; charset={ENCODING}" />
2300
            <style type="text/css" media="screen, projection">
2301
            /*<![CDATA[*/
2302
            {CSS}
2303
            /*]]>*/
2304
            </style>
2305
            {ASCIIMATHML_SCRIPT}</head>
2306
            <body dir="{TEXT_DIRECTION}">
2307
            {CONTENT}
2308
            </body>
2309
            </html>';
2310
2311
        $css_file = api_get_path(SYS_CSS_PATH).'themes/'.api_get_setting(
2312
                'stylesheets'
2313
            ).'/default.css';
2314
        if (file_exists($css_file)) {
2315
            $css = @file_get_contents($css_file);
2316
        } else {
2317
            $css = '';
2318
        }
2319
        // Fixing some bugs in css files.
2320
        $root_rel = api_get_path(REL_PATH);
2321
        $css_path = 'main/css/';
2322
        $theme = api_get_setting('stylesheets').'/';
2323
        $css = str_replace(
2324
            'behavior:url("/main/css/csshover3.htc");',
2325
            '',
2326
            $css
2327
        );
2328
        $css = str_replace('main/', $root_rel.'main/', $css);
2329
        $css = str_replace(
2330
            'images/',
2331
            $root_rel.$css_path.$theme.'images/',
2332
            $css
2333
        );
2334
        $css = str_replace('../../img/', $root_rel.'main/img/', $css);
2335
        $asciimathmal_script = (api_contains_asciimathml(
2336
                $wikiContents
2337
            ) || api_contains_asciisvg($wikiContents))
2338
            ? '<script src="'.api_get_path(
2339
                WEB_CODE_PATH
2340
            ).'inc/lib/javascript/asciimath/ASCIIMathML.js" type="text/javascript"></script>'."\n" : '';
2341
2342
        $template = str_replace(
2343
            [
2344
                '{LANGUAGE}',
2345
                '{ENCODING}',
2346
                '{TEXT_DIRECTION}',
2347
                '{TITLE}',
2348
                '{CSS}',
2349
                '{ASCIIMATHML_SCRIPT}'
2350
            ],
2351
            [
2352
                api_get_language_isocode(),
2353
                api_get_system_encoding(),
2354
                api_get_text_direction(),
2355
                $wikiTitle,
2356
                $css,
2357
                $asciimathmal_script
2358
            ],
2359
            $template
2360
        );
2361
2362
        if (0 != $groupId) {
2363
            $groupPart = '_group'.$groupId; // and add groupId to put the same document title in different groups
2364
            $group_properties = GroupManager::get_group_properties($groupId);
2365
            $groupPath = $group_properties['directory'];
2366
        } else {
2367
            $groupPart = '';
2368
            $groupPath = '';
2369
        }
2370
2371
        $exportDir = api_get_path(SYS_COURSE_PATH).api_get_course_path(
2372
            ).'/document'.$groupPath;
2373
        $exportFile = api_replace_dangerous_char($wikiTitle).$groupPart;
2374
        $wikiContents = trim(
2375
            preg_replace(
2376
                "/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/",
2377
                "$1",
2378
                $wikiContents
2379
            )
2380
        );
2381
        //TODO: put link instead of title
2382
        $wikiContents = str_replace('{CONTENT}', $wikiContents, $template);
2383
        // replace relative path by absolute path for courses, so you can see
2384
        // items into this page wiki (images, mp3, etc..) exported in documents
2385
        if (api_strpos(
2386
                $wikiContents,
2387
                '../..'.api_get_path(REL_COURSE_PATH)
2388
            ) !== false) {
2389
            $web_course_path = api_get_path(WEB_COURSE_PATH);
2390
            $wikiContents = str_replace(
2391
                '../..'.api_get_path(REL_COURSE_PATH),
2392
                $web_course_path,
2393
                $wikiContents
2394
            );
2395
        }
2396
2397
        $i = 1;
2398
        //only export last version, but in new export new version in document area
2399
        while (file_exists($exportDir.'/'.$exportFile.'_'.$i.'.html')) {
2400
            $i++;
2401
        }
2402
2403
        $wikiFileName = $exportFile.'_'.$i.'.html';
2404
        $exportPath = $exportDir.'/'.$wikiFileName;
2405
2406
        file_put_contents($exportPath, $wikiContents);
2407
        $doc_id = add_document(
2408
            $_course,
2409
            $groupPath.'/'.$wikiFileName,
2410
            'file',
2411
            filesize($exportPath),
2412
            $wikiTitle
2413
        );
2414
2415
        api_item_property_update(
2416
            $_course,
2417
            TOOL_DOCUMENT,
2418
            $doc_id,
2419
            'DocumentAdded',
2420
            api_get_user_id(),
2421
            $groupInfo
2422
        );
2423
2424
        return $doc_id;
2425
    }
2426
2427
    /**
2428
     * Exports the wiki page to PDF
2429
     */
2430
    public function export_to_pdf($id, $course_code)
2431
    {
2432
        if (!api_is_platform_admin()) {
2433
            if (api_get_setting('students_export2pdf') !== 'true') {
2434
                Display::addFlash(
2435
                    Display::return_message(
2436
                        get_lang('PDFDownloadNotAllowedForStudents'),
2437
                        'error',
2438
                        false
2439
                    )
2440
                );
2441
2442
                return false;
2443
            }
2444
        }
2445
2446
        $data = self::getWikiDataFromDb($id);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getWikiDataFromDb() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2446
        /** @scrutinizer ignore-call */ 
2447
        $data = self::getWikiDataFromDb($id);
Loading history...
2447
        $content_pdf = api_html_entity_decode(
2448
            $data['content'],
2449
            ENT_QUOTES,
2450
            api_get_system_encoding()
2451
        );
2452
2453
        //clean wiki links
2454
        $content_pdf = trim(
2455
            preg_replace(
2456
                "/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/",
2457
                "$1",
2458
                $content_pdf
2459
            )
2460
        );
2461
        //TODO: It should be better to display the link insted of the tile but it is hard for [[title]] links
2462
2463
        $title_pdf = api_html_entity_decode(
2464
            $data['title'],
2465
            ENT_QUOTES,
2466
            api_get_system_encoding()
2467
        );
2468
        $title_pdf = api_utf8_encode($title_pdf, api_get_system_encoding());
2469
        $content_pdf = api_utf8_encode($content_pdf, api_get_system_encoding());
2470
2471
        $html = '
2472
        <!-- defines the headers/footers - this must occur before the headers/footers are set -->
2473
2474
        <!--mpdf
2475
        <pageheader name="odds" content-left="'.$title_pdf.'"  header-style-left="color: #880000; font-style: italic;"  line="1" />
2476
        <pagefooter name="odds" content-right="{PAGENO}/{nb}" line="1" />
2477
2478
        <!-- set the headers/footers - they will occur from here on in the document -->
2479
        <!--mpdf
2480
        <setpageheader name="odds" page="odd" value="on" show-this-page="1" />
2481
        <setpagefooter name="odds" page="O" value="on" />
2482
2483
        mpdf-->'.$content_pdf;
2484
2485
        $css_file = api_get_path(SYS_CSS_PATH).'themes/'.api_get_setting('stylesheets').'/print.css';
2486
        if (file_exists($css_file)) {
2487
            $css = @file_get_contents($css_file);
2488
        } else {
2489
            $css = '';
2490
        }
2491
2492
        $pdf = new PDF();
2493
        $pdf->content_to_pdf($html, $css, $title_pdf, $course_code);
2494
        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...
2495
    }
2496
2497
    /**
2498
     * Function prevent double post (reload or F5)
2499
     *
2500
     */
2501
    public function double_post($wpost_id)
2502
    {
2503
        $postId = Session::read('wpost_id');
2504
        if (!empty($postId)) {
2505
            if ($wpost_id == $postId) {
2506
                return false;
2507
            } else {
2508
                Session::write('wpost_id', $wpost_id);
2509
2510
                return true;
2511
            }
2512
        } else {
2513
            Session::write('wpost_id', $wpost_id);
2514
2515
            return true;
2516
        }
2517
    }
2518
2519
    /**
2520
     * Function wizard individual assignment
2521
     * @author Juan Carlos Raña <[email protected]>
2522
     */
2523
    public function auto_add_page_users($values)
2524
    {
2525
        $assignment_type = $values['assignment'];
2526
        $session_id = $this->session_id;
2527
        $groupId = api_get_group_id();
2528
        $groupInfo = GroupManager::get_group_properties($groupId);
2529
        if ($groupId == 0) {
2530
            //extract course members
2531
            if (!empty($session_id)) {
2532
                $a_users_to_add = CourseManager::get_user_list_from_course_code(
2533
                    api_get_course_id(),
2534
                    $session_id
2535
                );
2536
            } else {
2537
                $a_users_to_add = CourseManager::get_user_list_from_course_code(
2538
                    api_get_course_id(),
2539
                    0
2540
                );
2541
            }
2542
        } else {
2543
            //extract group members
2544
            $subscribed_users = GroupManager::get_subscribed_users($groupInfo);
2545
            $subscribed_tutors = GroupManager::get_subscribed_tutors(
2546
                $groupInfo
2547
            );
2548
            $a_users_to_add_with_duplicates = array_merge(
2549
                $subscribed_users,
2550
                $subscribed_tutors
2551
            );
2552
            //remove duplicates
2553
            $a_users_to_add = $a_users_to_add_with_duplicates;
2554
            $a_users_to_add = array_unique($a_users_to_add);
2555
        }
2556
2557
        $all_students_pages = [];
2558
        // Data about teacher
2559
        $userId = api_get_user_id();
2560
        $userinfo = api_get_user_info($userId);
2561
        $username = api_htmlentities(
2562
            sprintf(get_lang('LoginX'), $userinfo['username'], ENT_QUOTES)
2563
        );
2564
        $name = $userinfo['complete_name']." - ".$username;
2565
        $photo = '<img src="'.$userinfo['avatar'].'" alt="'.$name.'"  width="40" height="50" align="top" title="'.$name.'"  />';
2566
2567
        // teacher assignment title
2568
        $title_orig = $values['title'];
2569
2570
        // teacher assignment reflink
2571
        $link2teacher = $values['title'] = $title_orig."_uass".$userId;
2572
2573
        // first: teacher name, photo, and assignment description (original content)
2574
        $content_orig_A = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2575
        <table border="0">
2576
            <tr><td style="font-size:24px">'.get_lang('AssignmentDesc').'</td></tr>
2577
            <tr><td>'.$photo.'<br />'.Display::tag(
2578
                'span',
2579
                api_get_person_name(
2580
                    $userinfo['firstname'],
2581
                    $userinfo['lastname']
2582
                ),
2583
                ['title' => $username]
2584
            ).'</td></tr>
2585
        </table></div>';
2586
2587
        $content_orig_B = '<br/><div align="center" style="font-size:24px">'.
2588
            get_lang('AssignmentDescription').': '.
2589
            $title_orig.'</div><br/>'.Security::remove_XSS($_POST['content']);
2590
2591
        //Second: student list (names, photo and links to their works).
2592
        //Third: Create Students work pages.
2593
        foreach ($a_users_to_add as $o_user_to_add) {
2594
            if ($o_user_to_add['user_id'] != $userId) {
2595
                // except that puts the task
2596
                $assig_user_id = $o_user_to_add['user_id'];
2597
                // identifies each page as created by the student, not by teacher
2598
2599
                $userPicture = UserManager::getUserPicture($assig_user_id);
2600
                $username = api_htmlentities(
2601
                    sprintf(
2602
                        get_lang('LoginX'),
2603
                        $o_user_to_add['username'],
2604
                        ENT_QUOTES
2605
                    )
2606
                );
2607
                $name = api_get_person_name(
2608
                        $o_user_to_add['firstname'],
2609
                        $o_user_to_add['lastname']
2610
                    )." . ".$username;
2611
                $photo = '<img src="'.$userPicture.'" alt="'.$name.'"  width="40" height="50" align="bottom" title="'.$name.'"  />';
2612
2613
                $is_tutor_of_group = GroupManager::is_tutor_of_group(
2614
                    $assig_user_id,
2615
                    $groupInfo
2616
                ); //student is tutor
2617
                $is_tutor_and_member = GroupManager::is_tutor_of_group(
2618
                        $assig_user_id,
2619
                        $groupInfo
2620
                    ) &&
2621
                    GroupManager::is_subscribed($assig_user_id, $groupInfo);
2622
                // student is tutor and member
2623
                if ($is_tutor_and_member) {
2624
                    $status_in_group = get_lang('GroupTutorAndMember');
2625
                } else {
2626
                    if ($is_tutor_of_group) {
2627
                        $status_in_group = get_lang('GroupTutor');
2628
                    } else {
2629
                        $status_in_group = " "; //get_lang('GroupStandardMember')
2630
                    }
2631
                }
2632
2633
                if ($assignment_type == 1) {
2634
                    $values['title'] = $title_orig;
2635
                    $values['content'] = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2636
                    <table border="0">
2637
                    <tr><td style="font-size:24px">'.get_lang('AssignmentWork').'</td></tr>
2638
                    <tr><td>'.$photo.'<br />'.$name.'</td></tr></table>
2639
                    </div>[['.$link2teacher.' | '.get_lang(
2640
                            'AssignmentLinktoTeacherPage'
2641
                        ).']] ';
2642
                    //If $content_orig_B is added here, the task written by
2643
                    // the professor was copied to the page of each student.
2644
                    // TODO: config options
2645
                    // AssignmentLinktoTeacherPage
2646
                    $all_students_pages[] = '<li>'.
2647
                        Display::tag(
2648
                            'span',
2649
                            strtoupper(
2650
                                $o_user_to_add['lastname']
2651
                            ).', '.$o_user_to_add['firstname'],
2652
                            ['title' => $username]
2653
                        ).
2654
                        ' [['.Security::remove_XSS(
2655
                            $_POST['title']
2656
                        )."_uass".$assig_user_id.' | '.$photo.']] '.$status_in_group.'</li>';
2657
                    // don't change this line without guaranteeing
2658
                    // that users will be ordered by last names in the
2659
                    // following format (surname, name)
2660
                    $values['assignment'] = 2;
2661
                }
2662
                $this->assig_user_id = $assig_user_id;
2663
                self::save_new_wiki($values);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::save_new_wiki() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2663
                self::/** @scrutinizer ignore-call */ 
2664
                      save_new_wiki($values);
Loading history...
2664
            }
2665
        }
2666
2667
        foreach ($a_users_to_add as $o_user_to_add) {
2668
            if ($o_user_to_add['user_id'] == $userId) {
2669
                $assig_user_id = $o_user_to_add['user_id'];
2670
                if ($assignment_type == 1) {
2671
                    $values['title'] = $title_orig;
2672
                    $values['comment'] = get_lang('AssignmentDesc');
2673
                    sort($all_students_pages);
2674
                    $values['content'] = $content_orig_A.$content_orig_B.'<br/>
2675
                    <div align="center" style="font-size:18px; background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2676
                    '.get_lang('AssignmentLinkstoStudentsPage').'
2677
                    </div><br/>
2678
                    <div style="background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2679
                    <ol>'.implode($all_students_pages).'</ol>
0 ignored issues
show
Bug introduced by
The call to implode() has too few arguments starting with pieces. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2679
                    <ol>'./** @scrutinizer ignore-call */ implode($all_students_pages).'</ol>

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
2680
                    </div>
2681
                    <br/>';
2682
                    $values['assignment'] = 1;
2683
                }
2684
                $this->assig_user_id = $assig_user_id;
2685
                self::save_new_wiki($values);
2686
            }
2687
        }
2688
    }
2689
2690
    /**
2691
     * Displays the results of a wiki search
2692
     * @param   string  Search term
2693
     * @param   int     Whether to search the contents (1) or just the titles (0)
2694
     * @param int
2695
     */
2696
    public function display_wiki_search_results(
2697
        $search_term,
2698
        $search_content = 0,
2699
        $all_vers = 0
2700
    ) {
2701
        $tbl_wiki = $this->tbl_wiki;
2702
        $condition_session = $this->condition_session;
2703
        $groupfilter = $this->groupfilter;
2704
        $_course = $this->courseInfo;
2705
        $course_id = api_get_course_int_id();
2706
        echo '<legend>'.get_lang('WikiSearchResults').': '.Security::remove_XSS(
2707
                $search_term
2708
            );
2709
        echo '</legend>';
2710
2711
        //only by professors when page is hidden
2712
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
2713
            if ($all_vers == '1') {
2714
                if ($search_content == '1') {
2715
                    $sql = "SELECT * FROM ".$tbl_wiki."
2716
                            WHERE
2717
                                c_id = $course_id AND
2718
                                title LIKE '%".Database::escape_string(
2719
                            $search_term
2720
                        )."%' OR
2721
                                content LIKE '%".Database::escape_string(
2722
                            $search_term
2723
                        )."%' AND
2724
                                ".$groupfilter.$condition_session."";
2725
                    //search all pages and all versions
2726
                } else {
2727
                    $sql = "SELECT * FROM ".$tbl_wiki."
2728
                            WHERE
2729
                                c_id = $course_id AND
2730
                                title LIKE '%".Database::escape_string(
2731
                            $search_term
2732
                        )."%' AND
2733
                                ".$groupfilter.$condition_session."";
2734
                    //search all pages and all versions
2735
                }
2736
            } else {
2737
                if ($search_content == '1') {
2738
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2739
                            WHERE
2740
                                s1.c_id = $course_id AND
2741
                                title LIKE '%".Database::escape_string(
2742
                            $search_term
2743
                        )."%' OR
2744
                                content LIKE '%".Database::escape_string(
2745
                            $search_term
2746
                        )."%' AND
2747
                                id=(
2748
                                    SELECT MAX(s2.id)
2749
                                    FROM ".$tbl_wiki." s2
2750
                                    WHERE
2751
                                        s2.c_id = $course_id AND
2752
                                        s1.reflink = s2.reflink AND
2753
                                        ".$groupfilter.$condition_session.")";
2754
                    // warning don't use group by reflink because don't return the last version
2755
                } else {
2756
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2757
                            WHERE
2758
                                s1.c_id = $course_id AND
2759
                                title LIKE '%".Database::escape_string(
2760
                            $search_term
2761
                        )."%' AND
2762
                                id = (
2763
                                    SELECT MAX(s2.id)
2764
                                    FROM ".$tbl_wiki." s2
2765
                                    WHERE
2766
                                        s2.c_id = $course_id AND
2767
                                        s1.reflink = s2.reflink AND
2768
                                        ".$groupfilter.$condition_session.")";
2769
                    // warning don't use group by reflink because don't return the last version
2770
                }
2771
            }
2772
        } else {
2773
            if ($all_vers == '1') {
2774
                if ($search_content == '1') {
2775
                    $sql = "SELECT * FROM ".$tbl_wiki."
2776
                            WHERE
2777
                                c_id = $course_id AND
2778
                                visibility=1 AND
2779
                                title LIKE '%".Database::escape_string(
2780
                            $search_term
2781
                        )."%' OR
2782
                                content LIKE '%".Database::escape_string(
2783
                            $search_term
2784
                        )."%' AND
2785
                                ".$groupfilter.$condition_session."";
2786
                    //search all pages and all versions
2787
                } else {
2788
                    $sql = "SELECT * FROM ".$tbl_wiki."
2789
                            WHERE
2790
                                c_id = $course_id AND
2791
                                visibility=1 AND
2792
                                title LIKE '%".Database::escape_string(
2793
                            $search_term
2794
                        )."%' AND
2795
                                ".$groupfilter.$condition_session."";
2796
                    //search all pages and all versions
2797
                }
2798
            } else {
2799
                if ($search_content == '1') {
2800
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2801
                            WHERE
2802
                                s1.c_id = $course_id AND
2803
                                visibility=1 AND
2804
                                title LIKE '%".Database::escape_string(
2805
                            $search_term
2806
                        )."%' OR
2807
                                content LIKE '%".Database::escape_string(
2808
                            $search_term
2809
                        )."%' AND
2810
                                id=(
2811
                                    SELECT MAX(s2.id)
2812
                                    FROM ".$tbl_wiki." s2
2813
                                    WHERE s2.c_id = $course_id AND
2814
                                    s1.reflink = s2.reflink AND
2815
                                    ".$groupfilter.$condition_session.")";
2816
                    // warning don't use group by reflink because don't return the last version
2817
                } else {
2818
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2819
                            WHERE
2820
                                s1.c_id = $course_id AND
2821
                                visibility=1 AND
2822
                                title LIKE '%".Database::escape_string(
2823
                            $search_term
2824
                        )."%' AND
2825
                            id = (
2826
                                SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
2827
                                WHERE s2.c_id = $course_id AND
2828
                                s1.reflink = s2.reflink AND
2829
                                ".$groupfilter.$condition_session.")";
2830
                    // warning don't use group by reflink because don't return the last version
2831
                }
2832
            }
2833
        }
2834
2835
        $result = Database::query($sql);
2836
2837
        //show table
2838
        $rows = [];
2839
        if (Database::num_rows($result) > 0) {
2840
            while ($obj = Database::fetch_object($result)) {
2841
                //get author
2842
                $userinfo = api_get_user_info($obj->user_id);
2843
2844
                //get time
2845
                $year = substr($obj->dtime, 0, 4);
2846
                $month = substr($obj->dtime, 5, 2);
2847
                $day = substr($obj->dtime, 8, 2);
2848
                $hours = substr($obj->dtime, 11, 2);
2849
                $minutes = substr($obj->dtime, 14, 2);
2850
                $seconds = substr($obj->dtime, 17, 2);
2851
2852
                //get type assignment icon
2853
                if ($obj->assignment == 1) {
2854
                    $ShowAssignment = Display::return_icon(
2855
                        'wiki_assignment.png',
2856
                        get_lang('AssignmentDesc'),
2857
                        '',
2858
                        ICON_SIZE_SMALL
2859
                    );
2860
                } elseif ($obj->assignment == 2) {
2861
                    $ShowAssignment = Display::return_icon(
2862
                        'wiki_work.png',
2863
                        get_lang('AssignmentWork'),
2864
                        '',
2865
                        ICON_SIZE_SMALL
2866
                    );
2867
                } elseif ($obj->assignment == 0) {
2868
                    $ShowAssignment = Display::return_icon(
2869
                        'px_transparent.gif'
2870
                    );
2871
                }
2872
                $row = [];
2873
                $row[] = $ShowAssignment;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ShowAssignment does not seem to be defined for all execution paths leading up to this point.
Loading history...
2874
2875
                if ($all_vers == '1') {
2876
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2877
                        ).'&action=showpage&title='.api_htmlentities(
2878
                            urlencode($obj->reflink)
2879
                        ).'&view='.$obj->id.'&session_id='.api_htmlentities(
2880
                            urlencode($_GET['$session_id'])
2881
                        ).'&group_id='.api_htmlentities(
2882
                            urlencode($_GET['group_id'])
2883
                        ).'">'.
2884
                        api_htmlentities($obj->title).'</a>';
2885
                } else {
2886
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2887
                        ).'&action=showpage&title='.api_htmlentities(
2888
                            urlencode($obj->reflink)
2889
                        ).'&session_id='.api_htmlentities(
2890
                            $_GET['session_id']
2891
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2892
                        $obj->title.'</a>';
2893
                }
2894
2895
                $row[] = ($obj->user_id != 0 && $userinfo !== false) ? UserManager::getUserProfileLink(
2896
                    $userinfo
2897
                ) : get_lang('Anonymous').' ('.$obj->user_ip.')';
2898
                $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
2899
2900
                if ($all_vers == '1') {
2901
                    $row[] = $obj->version;
2902
                } else {
2903
                    $showdelete = '';
2904
                    if (api_is_allowed_to_edit(
2905
                            false,
2906
                            true
2907
                        ) || api_is_platform_admin()) {
2908
                        $showdelete = ' <a href="'.api_get_self(
2909
                            ).'?'.api_get_cidreq(
2910
                            ).'&action=delete&title='.api_htmlentities(
2911
                                urlencode($obj->reflink)
2912
                            ).'&group_id='.api_htmlentities(
2913
                                $_GET['group_id']
2914
                            ).'">'.
2915
                            Display::return_icon(
2916
                                'delete.png',
2917
                                get_lang('Delete'),
2918
                                '',
2919
                                ICON_SIZE_SMALL
2920
                            );
2921
                    }
2922
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2923
                        ).'&action=edit&title='.api_htmlentities(
2924
                            urlencode($obj->reflink)
2925
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2926
                        Display::return_icon(
2927
                            'edit.png',
2928
                            get_lang('EditPage'),
2929
                            '',
2930
                            ICON_SIZE_SMALL
2931
                        ).'</a>
2932
                        <a href="'.api_get_self(
2933
                        ).'?cidReq='.$_course['code'].'&action=discuss&title='.api_htmlentities(
2934
                            urlencode($obj->reflink)
2935
                        ).'&session_id='.api_htmlentities(
2936
                            $_GET['session_id']
2937
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2938
                        Display::return_icon(
2939
                            'discuss.png',
2940
                            get_lang('Discuss'),
2941
                            '',
2942
                            ICON_SIZE_SMALL
2943
                        ).'</a>
2944
                        <a href="'.api_get_self(
2945
                        ).'?cidReq='.$_course['code'].'&action=history&title='.api_htmlentities(
2946
                            urlencode($obj->reflink)
2947
                        ).'&session_id='.api_htmlentities(
2948
                            $_GET['session_id']
2949
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2950
                        Display::return_icon(
2951
                            'history.png',
2952
                            get_lang('History'),
2953
                            '',
2954
                            ICON_SIZE_SMALL
2955
                        ).'</a> <a href="'.api_get_self(
2956
                        ).'?cidReq='.$_course['code'].'&action=links&title='.api_htmlentities(
2957
                            urlencode($obj->reflink)
2958
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2959
                        Display::return_icon(
2960
                            'what_link_here.png',
2961
                            get_lang('LinksPages'),
2962
                            '',
2963
                            ICON_SIZE_SMALL
2964
                        ).'</a>'.$showdelete;
2965
                }
2966
                $rows[] = $row;
2967
            }
2968
2969
            $table = new SortableTableFromArrayConfig(
2970
                $rows,
2971
                1,
2972
                10,
2973
                'SearchPages_table',
2974
                '',
2975
                '',
2976
                'ASC'
2977
            );
2978
            $table->set_additional_parameters(
2979
                [
2980
                    'cidReq' => $_GET['cidReq'],
2981
                    'action' => $_GET['action'],
2982
                    'group_id' => intval($_GET['group_id']),
2983
                    'mode_table' => 'yes2',
2984
                    'search_term' => $search_term,
2985
                    'search_content' => $search_content,
2986
                    'all_vers' => $all_vers,
2987
                ]
2988
            );
2989
            $table->set_header(
2990
                0,
2991
                get_lang('Type'),
2992
                true,
2993
                ['style' => 'width:30px;']
2994
            );
2995
            $table->set_header(1, get_lang('Title'), true);
2996
            if ($all_vers == '1') {
2997
                $table->set_header(2, get_lang('Author'), true);
2998
                $table->set_header(3, get_lang('Date'), true);
2999
                $table->set_header(4, get_lang('Version'), true);
3000
            } else {
3001
                $table->set_header(
3002
                    2,
3003
                    get_lang('Author').' ('.get_lang('LastVersion').')',
3004
                    true
3005
                );
3006
                $table->set_header(
3007
                    3,
3008
                    get_lang('Date').' ('.get_lang('LastVersion').')',
3009
                    true
3010
                );
3011
                $table->set_header(
3012
                    4,
3013
                    get_lang('Actions'),
3014
                    false,
3015
                    ['style' => 'width:130px;']
3016
                );
3017
            }
3018
            $table->display();
3019
        } else {
3020
            echo get_lang('NoSearchResults');
3021
        }
3022
    }
3023
3024
    /**
3025
     * Get wiki information
3026
     * @param   int|bool wiki id
3027
     * @return  array   wiki data
3028
     */
3029
    public function getWikiDataFromDb($id)
3030
    {
3031
        $tbl_wiki = $this->tbl_wiki;
3032
        $course_id = api_get_course_int_id();
3033
        if ($id === false) {
3034
            return [];
3035
        }
3036
        $id = intval($id);
3037
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3038
                WHERE c_id = '.$course_id.' AND id = '.$id.' ';
3039
        $result = Database::query($sql);
3040
        $data = [];
3041
        while ($row = Database::fetch_array($result, 'ASSOC')) {
3042
            $data = $row;
3043
        }
3044
3045
        return $data;
3046
    }
3047
3048
    /**
3049
     * @param string $refLink
3050
     * @return array
3051
     */
3052
    public function getLastWikiData($refLink)
3053
    {
3054
        $tbl_wiki = $this->tbl_wiki;
3055
        $groupfilter = $this->groupfilter;
3056
        $condition_session = $this->condition_session;
3057
        $course_id = api_get_course_int_id();
3058
3059
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3060
                WHERE
3061
                    c_id = '.$course_id.' AND
3062
                    reflink="'.Database::escape_string($refLink).'" AND
3063
                    '.$groupfilter.$condition_session.'
3064
                ORDER BY id DESC';
3065
3066
        $result = Database::query($sql);
3067
3068
        return Database::fetch_array($result);
3069
    }
3070
3071
    /**
3072
     * Get wiki information
3073
     * @param   string     wiki id
3074
     * @param int $courseId
3075
     * @return  array   wiki data
3076
     */
3077
    public function getPageByTitle($title, $courseId = null)
3078
    {
3079
        $tbl_wiki = $this->tbl_wiki;
3080
        if (empty($courseId)) {
3081
            $courseId = api_get_course_int_id();
3082
        } else {
3083
            $courseId = intval($courseId);
3084
        }
3085
3086
        if (empty($title) || empty($courseId)) {
3087
            return [];
3088
        }
3089
3090
        $title = Database::escape_string($title);
3091
        $sql = "SELECT * FROM $tbl_wiki
3092
                WHERE c_id = $courseId AND reflink = '$title'";
3093
        $result = Database::query($sql);
3094
        $data = [];
3095
        if (Database::num_rows($result)) {
3096
            $data = Database::fetch_array($result, 'ASSOC');
3097
        }
3098
3099
        return $data;
3100
    }
3101
3102
    /**
3103
     * @param string $title
3104
     * @param int $courseId
3105
     * @param string
3106
     * @param string
3107
     * @return bool
3108
     */
3109
    public function deletePage(
3110
        $title,
3111
        $courseId,
3112
        $groupfilter = null,
3113
        $condition_session = null
3114
    ) {
3115
        $tbl_wiki = $this->tbl_wiki;
3116
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
3117
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
3118
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3119
3120
        $pageInfo = self::getPageByTitle($title, $courseId);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getPageByTitle() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

3120
        /** @scrutinizer ignore-call */ 
3121
        $pageInfo = self::getPageByTitle($title, $courseId);
Loading history...
3121
        if (!empty($pageInfo)) {
3122
            $pageId = $pageInfo['id'];
3123
            $sql = "DELETE FROM $tbl_wiki_conf
3124
                    WHERE c_id = $courseId AND page_id = $pageId";
3125
            Database::query($sql);
3126
3127
            $sql = 'DELETE FROM '.$tbl_wiki_discuss.'
3128
                    WHERE c_id = '.$courseId.' AND publication_id = '.$pageId;
3129
            Database::query($sql);
3130
3131
            $sql = 'DELETE FROM  '.$tbl_wiki_mailcue.'
3132
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3133
            Database::query($sql);
3134
3135
            $sql = 'DELETE FROM '.$tbl_wiki.'
3136
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3137
            Database::query($sql);
3138
            self::check_emailcue(0, 'E');
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_emailcue() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

3138
            self::/** @scrutinizer ignore-call */ 
3139
                  check_emailcue(0, 'E');
Loading history...
3139
3140
            return true;
3141
        }
3142
3143
        return false;
3144
    }
3145
3146
    /**
3147
     * @return array
3148
     */
3149
    public function getAllWiki()
3150
    {
3151
        $tbl_wiki = $this->tbl_wiki;
3152
        $course_id = $this->course_id;
3153
        $condition_session = $this->condition_session;
3154
3155
        $sql = "SELECT * FROM $tbl_wiki
3156
                WHERE
3157
                    c_id = $course_id AND
3158
                    is_editing != '0' ".$condition_session;
3159
        $result = Database::query($sql);
3160
3161
        return Database::store_result($result, 'ASSOC');
3162
    }
3163
3164
    /**
3165
     * @param int $isEditing
3166
     */
3167
    public function updateWikiIsEditing($isEditing)
3168
    {
3169
        $tbl_wiki = $this->tbl_wiki;
3170
        $course_id = $this->course_id;
3171
        $condition_session = $this->condition_session;
3172
        $isEditing = Database::escape_string($isEditing);
3173
3174
        $sql = 'UPDATE '.$tbl_wiki.' SET
3175
                is_editing = "0",
3176
                time_edit = NULL
3177
                WHERE
3178
                    c_id = '.$course_id.' AND
3179
                    is_editing="'.$isEditing.'" '.
3180
            $condition_session;
3181
        Database::query($sql);
3182
    }
3183
3184
    /**
3185
     * Release of blocked pages to prevent concurrent editions
3186
     * @param int $userId
3187
     * @param string $action
3188
     */
3189
    public function blockConcurrentEditions($userId, $action = null)
3190
    {
3191
        $result = self::getAllWiki();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getAllWiki() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

3191
        /** @scrutinizer ignore-call */ 
3192
        $result = self::getAllWiki();
Loading history...
3192
        if (!empty($result)) {
3193
            foreach ($result as $is_editing_block) {
3194
                $max_edit_time = 1200; // 20 minutes
3195
                $timestamp_edit = strtotime($is_editing_block['time_edit']);
3196
                $time_editing = time() - $timestamp_edit;
3197
3198
                // First prevent concurrent users and double version
3199
                if ($is_editing_block['is_editing'] == $userId) {
3200
                    Session::write('_version', $is_editing_block['version']);
3201
                } else {
3202
                    Session::erase('_version');
3203
                }
3204
                // Second checks if has exceeded the time that a page may
3205
                // be available or if a page was edited and saved by its author
3206
                if ($time_editing > $max_edit_time ||
3207
                    ($is_editing_block['is_editing'] == $userId &&
3208
                        $action != 'edit')
3209
                ) {
3210
                    self::updateWikiIsEditing($is_editing_block['is_editing']);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::updateWikiIsEditing() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

3210
                    self::/** @scrutinizer ignore-call */ 
3211
                          updateWikiIsEditing($is_editing_block['is_editing']);
Loading history...
3211
                }
3212
            }
3213
        }
3214
    }
3215
3216
    /**
3217
     * Showing wiki stats
3218
     */
3219
    public function getStats()
3220
    {
3221
        if (!api_is_allowed_to_edit(false, true)) {
3222
            return false;
3223
        }
3224
3225
        $tbl_wiki = $this->tbl_wiki;
3226
        $course_id = $this->course_id;
3227
        $condition_session = $this->condition_session;
3228
        $groupfilter = $this->groupfilter;
3229
        $session_id = $this->session_id;
3230
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3231
3232
        echo '<div class="actions">'.get_lang('Statistics').'</div>';
3233
3234
        // Check all versions of all pages
3235
        $total_words = 0;
3236
        $total_links = 0;
3237
        $total_links_anchors = 0;
3238
        $total_links_mail = 0;
3239
        $total_links_ftp = 0;
3240
        $total_links_irc = 0;
3241
        $total_links_news = 0;
3242
        $total_wlinks = 0;
3243
        $total_images = 0;
3244
        $clean_total_flash = 0;
3245
        $total_flash = 0;
3246
        $total_mp3 = 0;
3247
        $total_flv_p = 0;
3248
        $total_flv = 0;
3249
        $total_youtube = 0;
3250
        $total_multimedia = 0;
3251
        $total_tables = 0;
3252
3253
        $sql = "SELECT *, COUNT(*) AS TOTAL_VERS, SUM(hits) AS TOTAL_VISITS
3254
                FROM ".$tbl_wiki."
3255
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3256
3257
        $allpages = Database::query($sql);
3258
        while ($row = Database::fetch_array($allpages)) {
3259
            $total_versions = $row['TOTAL_VERS'];
3260
            $total_visits = intval($row['TOTAL_VISITS']);
3261
        }
3262
3263
        $sql = "SELECT * FROM ".$tbl_wiki."
3264
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3265
        $allpages = Database::query($sql);
3266
3267
        while ($row = Database::fetch_array($allpages)) {
3268
            $total_words = $total_words + self::word_count($row['content']);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::word_count() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

3268
            $total_words = $total_words + self::/** @scrutinizer ignore-call */ word_count($row['content']);
Loading history...
3269
            $total_links = $total_links + substr_count(
3270
                $row['content'],
3271
                "href="
3272
            );
3273
            $total_links_anchors = $total_links_anchors + substr_count(
3274
                $row['content'],
3275
                'href="#'
3276
            );
3277
            $total_links_mail = $total_links_mail + substr_count(
3278
                $row['content'],
3279
                'href="mailto'
3280
            );
3281
            $total_links_ftp = $total_links_ftp + substr_count(
3282
                $row['content'],
3283
                'href="ftp'
3284
            );
3285
            $total_links_irc = $total_links_irc + substr_count(
3286
                $row['content'],
3287
                'href="irc'
3288
            );
3289
            $total_links_news = $total_links_news + substr_count(
3290
                $row['content'],
3291
                'href="news'
3292
            );
3293
            $total_wlinks = $total_wlinks + substr_count($row['content'], "[[");
3294
            $total_images = $total_images + substr_count(
3295
                $row['content'],
3296
                "<img"
3297
            );
3298
            $clean_total_flash = preg_replace(
3299
                '/player.swf/',
3300
                ' ',
3301
                $row['content']
3302
            );
3303
            $total_flash = $total_flash + substr_count(
3304
                $clean_total_flash,
3305
                '.swf"'
3306
            );
3307
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3308
            $total_mp3 = $total_mp3 + substr_count($row['content'], ".mp3");
3309
            $total_flv_p = $total_flv_p + substr_count($row['content'], ".flv");
3310
            $total_flv = $total_flv_p / 5;
3311
            $total_youtube = $total_youtube + substr_count(
3312
                $row['content'],
3313
                "http://www.youtube.com"
3314
            );
3315
            $total_multimedia = $total_multimedia + substr_count(
3316
                $row['content'],
3317
                "video/x-msvideo"
3318
            );
3319
            $total_tables = $total_tables + substr_count(
3320
                $row['content'],
3321
                "<table"
3322
            );
3323
        }
3324
3325
        // Check only last version of all pages (current page)
3326
        $sql = ' SELECT *, COUNT(*) AS TOTAL_PAGES, SUM(hits) AS TOTAL_VISITS_LV
3327
                FROM  '.$tbl_wiki.' s1
3328
                WHERE s1.c_id = '.$course_id.' AND id=(
3329
                    SELECT MAX(s2.id)
3330
                    FROM '.$tbl_wiki.' s2
3331
                    WHERE
3332
                        s2.c_id = '.$course_id.' AND
3333
                        s1.reflink = s2.reflink AND
3334
                        '.$groupfilter.' AND
3335
                        session_id='.$session_id.')';
3336
        $allpages = Database::query($sql);
3337
        while ($row = Database::fetch_array($allpages)) {
3338
            $total_pages = $row['TOTAL_PAGES'];
3339
            $total_visits_lv = intval($row['TOTAL_VISITS_LV']);
3340
        }
3341
3342
        $total_words_lv = 0;
3343
        $total_links_lv = 0;
3344
        $total_links_anchors_lv = 0;
3345
        $total_links_mail_lv = 0;
3346
        $total_links_ftp_lv = 0;
3347
        $total_links_irc_lv = 0;
3348
        $total_links_news_lv = 0;
3349
        $total_wlinks_lv = 0;
3350
        $total_images_lv = 0;
3351
        $clean_total_flash_lv = 0;
3352
        $total_flash_lv = 0;
3353
        $total_mp3_lv = 0;
3354
        $total_flv_p_lv = 0;
3355
        $total_flv_lv = 0;
3356
        $total_youtube_lv = 0;
3357
        $total_multimedia_lv = 0;
3358
        $total_tables_lv = 0;
3359
3360
        $sql = 'SELECT * FROM  '.$tbl_wiki.' s1
3361
                WHERE s1.c_id = '.$course_id.' AND id=(
3362
                    SELECT MAX(s2.id) 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
                )';
3369
        $allpages = Database::query($sql);
3370
3371
        while ($row = Database::fetch_array($allpages)) {
3372
            $total_words_lv = $total_words_lv + self::word_count(
3373
                $row['content']
3374
            );
3375
            $total_links_lv = $total_links_lv + substr_count(
3376
                $row['content'],
3377
                "href="
3378
            );
3379
            $total_links_anchors_lv = $total_links_anchors_lv + substr_count(
3380
                $row['content'],
3381
                'href="#'
3382
            );
3383
            $total_links_mail_lv = $total_links_mail_lv + substr_count(
3384
                $row['content'],
3385
                'href="mailto'
3386
            );
3387
            $total_links_ftp_lv = $total_links_ftp_lv + substr_count(
3388
                $row['content'],
3389
                'href="ftp'
3390
            );
3391
            $total_links_irc_lv = $total_links_irc_lv + substr_count(
3392
                $row['content'],
3393
                'href="irc'
3394
            );
3395
            $total_links_news_lv = $total_links_news_lv + substr_count(
3396
                $row['content'],
3397
                'href="news'
3398
            );
3399
            $total_wlinks_lv = $total_wlinks_lv + substr_count(
3400
                $row['content'],
3401
                "[["
3402
            );
3403
            $total_images_lv = $total_images_lv + substr_count(
3404
                $row['content'],
3405
                "<img"
3406
            );
3407
            $clean_total_flash_lv = preg_replace(
3408
                '/player.swf/',
3409
                ' ',
3410
                $row['content']
3411
            );
3412
            $total_flash_lv = $total_flash_lv + substr_count(
3413
                $clean_total_flash_lv,
3414
                '.swf"'
3415
            );
3416
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3417
            $total_mp3_lv = $total_mp3_lv + substr_count(
3418
                $row['content'],
3419
                ".mp3"
3420
            );
3421
            $total_flv_p_lv = $total_flv_p_lv + substr_count(
3422
                $row['content'],
3423
                ".flv"
3424
            );
3425
            $total_flv_lv = $total_flv_p_lv / 5;
3426
            $total_youtube_lv = $total_youtube_lv + substr_count(
3427
                $row['content'],
3428
                "http://www.youtube.com"
3429
            );
3430
            $total_multimedia_lv = $total_multimedia_lv + substr_count(
3431
                $row['content'],
3432
                "video/x-msvideo"
3433
            );
3434
            $total_tables_lv = $total_tables_lv + substr_count(
3435
                $row['content'],
3436
                "<table"
3437
            );
3438
        }
3439
3440
        //Total pages edited at this time
3441
        $total_editing_now = 0;
3442
        $sql = 'SELECT *, COUNT(*) AS TOTAL_EDITING_NOW
3443
                FROM  '.$tbl_wiki.' s1
3444
                WHERE is_editing!=0 AND s1.c_id = '.$course_id.' AND
3445
                id=(
3446
                    SELECT MAX(s2.id)
3447
                    FROM '.$tbl_wiki.' s2
3448
                    WHERE
3449
                        s2.c_id = '.$course_id.' AND
3450
                        s1.reflink = s2.reflink AND
3451
                        '.$groupfilter.' AND
3452
                        session_id='.$session_id.'
3453
        )';
3454
3455
        // Can not use group by because the mark is set in the latest version
3456
        $allpages = Database::query($sql);
3457
        while ($row = Database::fetch_array($allpages)) {
3458
            $total_editing_now = $row['TOTAL_EDITING_NOW'];
3459
        }
3460
3461
        // Total hidden pages
3462
        $total_hidden = 0;
3463
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3464
                WHERE  
3465
                    c_id = '.$course_id.' AND 
3466
                    visibility = 0 AND 
3467
                    '.$groupfilter.$condition_session.'
3468
                GROUP BY reflink';
3469
        // or group by page_id. As the mark of hidden places it in all
3470
        // versions of the page, I can use group by to see the first
3471
        $allpages = Database::query($sql);
3472
        while ($row = Database::fetch_array($allpages)) {
3473
            $total_hidden = $total_hidden + 1;
3474
        }
3475
3476
        //Total protect pages
3477
        $total_protected = 0;
3478
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3479
                WHERE  
3480
                    c_id = '.$course_id.' AND 
3481
                    editlock = 1 AND
3482
                     '.$groupfilter.$condition_session.'
3483
                GROUP BY reflink';
3484
        // or group by page_id. As the mark of protected page is the
3485
        // first version of the page, I can use group by
3486
        $allpages = Database::query($sql);
3487
        while ($row = Database::fetch_array($allpages)) {
3488
            $total_protected = $total_protected + 1;
3489
        }
3490
3491
        // Total empty versions.
3492
        $total_empty_content = 0;
3493
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3494
                WHERE
3495
                    c_id = '.$course_id.' AND
3496
                    content="" AND
3497
                    '.$groupfilter.$condition_session.'';
3498
        $allpages = Database::query($sql);
3499
        while ($row = Database::fetch_array($allpages)) {
3500
            $total_empty_content = $total_empty_content + 1;
3501
        }
3502
3503
        //Total empty pages (last version)
3504
3505
        $total_empty_content_lv = 0;
3506
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3507
                WHERE s1.c_id = '.$course_id.' AND content="" AND id=(
3508
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3509
                    WHERE 
3510
                        s1.c_id = '.$course_id.' AND 
3511
                        s1.reflink = s2.reflink AND 
3512
                        '.$groupfilter.' AND 
3513
                        session_id='.$session_id.'
3514
                )';
3515
        $allpages = Database::query($sql);
3516
        while ($row = Database::fetch_array($allpages)) {
3517
            $total_empty_content_lv = $total_empty_content_lv + 1;
3518
        }
3519
3520
        // Total locked discuss pages
3521
        $total_lock_disc = 0;
3522
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3523
                WHERE c_id = '.$course_id.' AND addlock_disc=0 AND '.$groupfilter.$condition_session.'
3524
                GROUP BY reflink';//group by because mark lock in all vers, then always is ok
3525
        $allpages = Database::query($sql);
3526
        while ($row = Database::fetch_array($allpages)) {
3527
            $total_lock_disc = $total_lock_disc + 1;
3528
        }
3529
3530
        // Total hidden discuss pages.
3531
        $total_hidden_disc = 0;
3532
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3533
                WHERE c_id = '.$course_id.' AND visibility_disc=0 AND '.$groupfilter.$condition_session.'
3534
                GROUP BY reflink';
3535
        //group by because mark lock in all vers, then always is ok
3536
        $allpages = Database::query($sql);
3537
        while ($row = Database::fetch_array($allpages)) {
3538
            $total_hidden_disc = $total_hidden_disc + 1;
3539
        }
3540
3541
        // Total versions with any short comment by user or system
3542
        $total_comment_version = 0;
3543
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3544
                WHERE c_id = '.$course_id.' AND comment!="" AND '.$groupfilter.$condition_session.'';
3545
        $allpages = Database::query($sql);
3546
        while ($row = Database::fetch_array($allpages)) {
3547
            $total_comment_version = $total_comment_version + 1;
3548
        }
3549
3550
        // Total pages that can only be scored by teachers.
3551
        $total_only_teachers_rating = 0;
3552
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3553
                WHERE c_id = '.$course_id.' AND
3554
                ratinglock_disc = 0 AND
3555
                '.$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_only_teachers_rating = $total_only_teachers_rating + 1;
3560
        }
3561
3562
        // Total pages scored by peers
3563
        // put always this line alfter check num all pages and num pages rated by teachers
3564
        $total_rating_by_peers = $total_pages - $total_only_teachers_rating;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $total_pages does not seem to be defined for all execution paths leading up to this point.
Loading history...
3565
3566
        //Total pages identified as standard task
3567
        $total_task = 0;
3568
        $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
3569
              WHERE '.$tbl_wiki_conf.'.c_id = '.$course_id.' AND
3570
               '.$tbl_wiki_conf.'.task!="" AND
3571
               '.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
3572
                '.$tbl_wiki.'.'.$groupfilter.$condition_session;
3573
        $allpages = Database::query($sql);
3574
        while ($row = Database::fetch_array($allpages)) {
3575
            $total_task = $total_task + 1;
3576
        }
3577
3578
        //Total pages identified as teacher page (wiki portfolio mode - individual assignment)
3579
        $total_teacher_assignment = 0;
3580
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3581
                WHERE s1.c_id = '.$course_id.' AND assignment=1 AND id=(
3582
                    SELECT MAX(s2.id)
3583
                    FROM '.$tbl_wiki.' s2
3584
                    WHERE 
3585
                        s2.c_id = '.$course_id.' AND
3586
                        s1.reflink = s2.reflink AND 
3587
                        '.$groupfilter.' AND
3588
                         session_id='.$session_id.'
3589
                )';
3590
        //mark all versions, but do not use group by reflink because y want the pages not versions
3591
        $allpages = Database::query($sql);
3592
        while ($row = Database::fetch_array($allpages)) {
3593
            $total_teacher_assignment = $total_teacher_assignment + 1;
3594
        }
3595
3596
        //Total pages identifies as student page (wiki portfolio mode - individual assignment)
3597
        $total_student_assignment = 0;
3598
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3599
                WHERE s1.c_id = '.$course_id.' AND assignment=2 AND
3600
                id = (SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3601
                WHERE 
3602
                    s2.c_id = '.$course_id.' AND 
3603
                    s1.reflink = s2.reflink AND 
3604
                    '.$groupfilter.' AND 
3605
                    session_id='.$session_id.'
3606
                )';
3607
        //mark all versions, but do not use group by reflink because y want the pages not versions
3608
        $allpages = Database::query($sql);
3609
        while ($row = Database::fetch_array($allpages)) {
3610
            $total_student_assignment = $total_student_assignment + 1;
3611
        }
3612
3613
        //Current Wiki status add new pages
3614
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3615
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3616
                GROUP BY addlock';//group by because mark 0 in all vers, then always is ok
3617
        $allpages = Database::query($sql);
3618
        $wiki_add_lock = null;
3619
        while ($row = Database::fetch_array($allpages)) {
3620
            $wiki_add_lock = $row['addlock'];
3621
        }
3622
3623
        if ($wiki_add_lock == 1) {
3624
            $status_add_new_pag = get_lang('Yes');
3625
        } else {
3626
            $status_add_new_pag = get_lang('No');
3627
        }
3628
3629
        // Creation date of the oldest wiki page and version
3630
        $first_wiki_date = null;
3631
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3632
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3633
                ORDER BY dtime ASC 
3634
                LIMIT 1';
3635
        $allpages = Database::query($sql);
3636
        while ($row = Database::fetch_array($allpages)) {
3637
            $first_wiki_date = api_get_local_time($row['dtime']);
3638
        }
3639
3640
        // Date of publication of the latest wiki version.
3641
3642
        $last_wiki_date = null;
3643
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3644
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3645
                ORDER BY dtime DESC 
3646
                LIMIT 1';
3647
        $allpages = Database::query($sql);
3648
        while ($row = Database::fetch_array($allpages)) {
3649
            $last_wiki_date = api_get_local_time($row['dtime']);
3650
        }
3651
3652
        // Average score of all wiki pages. (If a page has not scored zero rated)
3653
        $media_score = 0;
3654
        $sql = "SELECT *, SUM(score) AS TOTAL_SCORE FROM ".$tbl_wiki."
3655
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."
3656
                GROUP BY reflink ";
3657
        //group by because mark in all versions, then always is ok.
3658
        // Do not use "count" because using "group by", would give a wrong value
3659
        $allpages = Database::query($sql);
3660
        $total_score = 0;
3661
        while ($row = Database::fetch_array($allpages)) {
3662
            $total_score = $total_score + $row['TOTAL_SCORE'];
3663
        }
3664
3665
        if (!empty($total_pages)) {
3666
            $media_score = $total_score / $total_pages;
3667
            //put always this line alfter check num all pages
3668
        }
3669
3670
        // Average user progress in his pages.
3671
        $media_progress = 0;
3672
        $sql = 'SELECT  *, SUM(progress) AS TOTAL_PROGRESS
3673
                FROM  '.$tbl_wiki.' s1
3674
                WHERE s1.c_id = '.$course_id.' AND id=
3675
                (
3676
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3677
                    WHERE
3678
                        s2.c_id = '.$course_id.' AND
3679
                        s1.reflink = s2.reflink AND
3680
                        '.$groupfilter.' AND
3681
                        session_id='.$session_id.'
3682
                )';
3683
        // As the value is only the latest version I can not use group by
3684
        $allpages = Database::query($sql);
3685
        while ($row = Database::fetch_array($allpages)) {
3686
            $total_progress = $row['TOTAL_PROGRESS'];
3687
        }
3688
3689
        if (!empty($total_pages)) {
3690
            $media_progress = $total_progress / $total_pages;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $total_progress does not seem to be defined for all execution paths leading up to this point.
Loading history...
3691
            //put always this line alfter check num all pages
3692
        }
3693
3694
        // Total users that have participated in the Wiki
3695
        $total_users = 0;
3696
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3697
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3698
                GROUP BY user_id';
3699
        //as the mark of user it in all versions of the page, I can use group by to see the first
3700
        $allpages = Database::query($sql);
3701
        while ($row = Database::fetch_array($allpages)) {
3702
            $total_users = $total_users + 1;
3703
        }
3704
3705
        // Total of different IP addresses that have participated in the wiki
3706
        $total_ip = 0;
3707
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3708
              WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3709
              GROUP BY user_ip';
3710
        $allpages = Database::query($sql);
3711
        while ($row = Database::fetch_array($allpages)) {
3712
            $total_ip = $total_ip + 1;
3713
        }
3714
3715
        echo '<table class="data_table">';
3716
        echo '<thead>';
3717
        echo '<tr>';
3718
        echo '<th colspan="2">'.get_lang('General').'</th>';
3719
        echo '</tr>';
3720
        echo '</thead>';
3721
        echo '<tr>';
3722
        echo '<td>'.get_lang('StudentAddNewPages').'</td>';
3723
        echo '<td>'.$status_add_new_pag.'</td>';
3724
        echo '</tr>';
3725
        echo '<tr>';
3726
        echo '<td>'.get_lang('DateCreateOldestWikiPage').'</td>';
3727
        echo '<td>'.$first_wiki_date.'</td>';
3728
        echo '</tr>';
3729
        echo '<tr>';
3730
        echo '<td>'.get_lang('DateEditLatestWikiVersion').'</td>';
3731
        echo '<td>'.$last_wiki_date.'</td>';
3732
        echo '</tr>';
3733
        echo '<tr>';
3734
        echo '<td>'.get_lang('AverageScoreAllPages').'</td>';
3735
        echo '<td>'.$media_score.' %</td>';
3736
        echo '</tr>';
3737
        echo '<tr>';
3738
        echo '<td>'.get_lang('AverageMediaUserProgress').'</td>';
3739
        echo '<td>'.$media_progress.' %</td>';
3740
        echo '</tr>';
3741
        echo '<tr>';
3742
        echo '<td>'.get_lang('TotalWikiUsers').'</td>';
3743
        echo '<td>'.$total_users.'</td>';
3744
        echo '</tr>';
3745
        echo '<tr>';
3746
        echo '<td>'.get_lang('TotalIpAdress').'</td>';
3747
        echo '<td>'.$total_ip.'</td>';
3748
        echo '</tr>';
3749
        echo '</table>';
3750
        echo '<br/>';
3751
3752
        echo '<table class="data_table">';
3753
        echo '<thead>';
3754
        echo '<tr>';
3755
        echo '<th colspan="2">'.get_lang('Pages').' '.get_lang(
3756
                'And'
3757
            ).' '.get_lang('Versions').'</th>';
3758
        echo '</tr>';
3759
        echo '</thead>';
3760
        echo '<tr>';
3761
        echo '<td>'.get_lang('Pages').' - '.get_lang(
3762
                'NumContributions'
3763
            ).'</td>';
3764
        echo '<td>'.$total_pages.' ('.get_lang(
3765
                'Versions'
3766
            ).': '.$total_versions.')</td>';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $total_versions does not seem to be defined for all execution paths leading up to this point.
Loading history...
3767
        echo '</tr>';
3768
        echo '<tr>';
3769
        echo '<td>'.get_lang('EmptyPages').'</td>';
3770
        echo '<td>'.$total_empty_content_lv.' ('.get_lang(
3771
                'Versions'
3772
            ).': '.$total_empty_content.')</td>';
3773
        echo '</tr>';
3774
        echo '<tr>';
3775
        echo '<td>'.get_lang('NumAccess').'</td>';
3776
        echo '<td>'.$total_visits_lv.' ('.get_lang(
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $total_visits_lv does not seem to be defined for all execution paths leading up to this point.
Loading history...
3777
                'Versions'
3778
            ).': '.$total_visits.')</td>';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $total_visits does not seem to be defined for all execution paths leading up to this point.
Loading history...
3779
        echo '</tr>';
3780
        echo '<tr>';
3781
        echo '<td>'.get_lang('TotalPagesEditedAtThisTime').'</td>';
3782
        echo '<td>'.$total_editing_now.'</td>';
3783
        echo '</tr>';
3784
        echo '<tr>';
3785
        echo '<td>'.get_lang('TotalHiddenPages').'</td>';
3786
        echo '<td>'.$total_hidden.'</td>';
3787
        echo '</tr>';
3788
        echo '<tr>';
3789
        echo '<td>'.get_lang('NumProtectedPages').'</td>';
3790
        echo '<td>'.$total_protected.'</td>';
3791
        echo '</tr>';
3792
        echo '<tr>';
3793
        echo '<td>'.get_lang('LockedDiscussPages').'</td>';
3794
        echo '<td>'.$total_lock_disc.'</td>';
3795
        echo '</tr>';
3796
        echo '<tr>';
3797
        echo '<td>'.get_lang('HiddenDiscussPages').'</td>';
3798
        echo '<td>'.$total_hidden_disc.'</td>';
3799
        echo '</tr>';
3800
        echo '<tr>';
3801
        echo '<td>'.get_lang('TotalComments').'</td>';
3802
        echo '<td>'.$total_comment_version.'</td>';
3803
        echo '</tr>';
3804
        echo '<tr>';
3805
        echo '<td>'.get_lang('TotalOnlyRatingByTeacher').'</td>';
3806
        echo '<td>'.$total_only_teachers_rating.'</td>';
3807
        echo '</tr>';
3808
        echo '<tr>';
3809
        echo '<td>'.get_lang('TotalRatingPeers').'</td>';
3810
        echo '<td>'.$total_rating_by_peers.'</td>';
3811
        echo '</tr>';
3812
        echo '<tr>';
3813
        echo '<td>'.get_lang('TotalTeacherAssignments').' - '.get_lang(
3814
                'PortfolioMode'
3815
            ).'</td>';
3816
        echo '<td>'.$total_teacher_assignment.'</td>';
3817
        echo '</tr>';
3818
        echo '<tr>';
3819
        echo '<td>'.get_lang('TotalStudentAssignments').' - '.get_lang(
3820
                'PortfolioMode'
3821
            ).'</td>';
3822
        echo '<td>'.$total_student_assignment.'</td>';
3823
        echo '</tr>';
3824
        echo '<tr>';
3825
        echo '<td>'.get_lang('TotalTask').' - '.get_lang(
3826
                'StandardMode'
3827
            ).'</td>';
3828
        echo '<td>'.$total_task.'</td>';
3829
        echo '</tr>';
3830
        echo '</table>';
3831
        echo '<br/>';
3832
3833
        echo '<table class="data_table">';
3834
        echo '<thead>';
3835
        echo '<tr>';
3836
        echo '<th colspan="3">'.get_lang('ContentPagesInfo').'</th>';
3837
        echo '</tr>';
3838
        echo '<tr>';
3839
        echo '<td></td>';
3840
        echo '<td>'.get_lang('InTheLastVersion').'</td>';
3841
        echo '<td>'.get_lang('InAllVersions').'</td>';
3842
        echo '</tr>';
3843
        echo '</thead>';
3844
        echo '<tr>';
3845
        echo '<td>'.get_lang('NumWords').'</td>';
3846
        echo '<td>'.$total_words_lv.'</td>';
3847
        echo '<td>'.$total_words.'</td>';
3848
        echo '</tr>';
3849
        echo '<tr>';
3850
        echo '<td>'.get_lang('NumlinksHtmlImagMedia').'</td>';
3851
        echo '<td>'.$total_links_lv.' ('.get_lang(
3852
                'Anchors'
3853
            ).':'.$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>';
3854
        echo '<td>'.$total_links.' ('.get_lang(
3855
                'Anchors'
3856
            ).':'.$total_links_anchors.', Mail:'.$total_links_mail.', FTP:'.$total_links_ftp.', IRC:'.$total_links_irc.', News:'.$total_links_news.', ... ) </td>';
3857
        echo '</tr>';
3858
        echo '<tr>';
3859
        echo '<td>'.get_lang('NumWikilinks').'</td>';
3860
        echo '<td>'.$total_wlinks_lv.'</td>';
3861
        echo '<td>'.$total_wlinks.'</td>';
3862
        echo '</tr>';
3863
        echo '<tr>';
3864
        echo '<td>'.get_lang('NumImages').'</td>';
3865
        echo '<td>'.$total_images_lv.'</td>';
3866
        echo '<td>'.$total_images.'</td>';
3867
        echo '</tr>';
3868
        echo '<tr>';
3869
        echo '<td>'.get_lang('NumFlash').'</td>';
3870
        echo '<td>'.$total_flash_lv.'</td>';
3871
        echo '<td>'.$total_flash.'</td>';
3872
        echo '</tr>';
3873
        echo '<tr>';
3874
        echo '<td>'.get_lang('NumMp3').'</td>';
3875
        echo '<td>'.$total_mp3_lv.'</td>';
3876
        echo '<td>'.$total_mp3.'</td>';
3877
        echo '</tr>';
3878
        echo '<tr>';
3879
        echo '<td>'.get_lang('NumFlvVideo').'</td>';
3880
        echo '<td>'.$total_flv_lv.'</td>';
3881
        echo '<td>'.$total_flv.'</td>';
3882
        echo '</tr>';
3883
        echo '<tr>';
3884
        echo '<td>'.get_lang('NumYoutubeVideo').'</td>';
3885
        echo '<td>'.$total_youtube_lv.'</td>';
3886
        echo '<td>'.$total_youtube.'</td>';
3887
        echo '</tr>';
3888
        echo '<tr>';
3889
        echo '<td>'.get_lang('NumOtherAudioVideo').'</td>';
3890
        echo '<td>'.$total_multimedia_lv.'</td>';
3891
        echo '<td>'.$total_multimedia.'</td>';
3892
        echo '</tr>';
3893
        echo '<tr>';
3894
        echo '<td>'.get_lang('NumTables').'</td>';
3895
        echo '<td>'.$total_tables_lv.'</td>';
3896
        echo '<td>'.$total_tables.'</td>';
3897
        echo '</tr>';
3898
        echo '</table>';
3899
    }
3900
3901
    /**
3902
     * @param string $action
3903
     */
3904
    public function getActiveUsers($action)
3905
    {
3906
        $tbl_wiki = $this->tbl_wiki;
3907
        $course_id = $this->course_id;
3908
        $condition_session = $this->condition_session;
3909
        $groupfilter = $this->groupfilter;
3910
        $_course = $this->courseInfo;
3911
3912
        echo '<div class="actions">'.get_lang('MostActiveUsers').'</div>';
3913
        $sql = 'SELECT *, COUNT(*) AS NUM_EDIT FROM '.$tbl_wiki.'
3914
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3915
                GROUP BY user_id';
3916
        $allpages = Database::query($sql);
3917
3918
        //show table
3919
        if (Database::num_rows($allpages) > 0) {
3920
            while ($obj = Database::fetch_object($allpages)) {
3921
                $userinfo = api_get_user_info($obj->user_id);
3922
                $row = [];
3923
                if ($obj->user_id != 0 && $userinfo !== false) {
3924
                    $row[] = UserManager::getUserProfileLink($userinfo).'
3925
                            <a href="'.api_get_self(
3926
                        ).'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode(
3927
                            $obj->user_id
3928
                        ).
3929
                        '&session_id='.api_htmlentities(
3930
                            $_GET['session_id']
3931
                        ).'&group_id='.api_htmlentities(
3932
                            $_GET['group_id']
3933
                        ).'"></a>';
3934
                } else {
3935
                    $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
3936
                }
3937
                $row[] = '<a href="'.api_get_self(
3938
                    ).'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode(
3939
                        $obj->user_id
3940
                    ).'&session_id='.api_htmlentities(
3941
                        $_GET['session_id']
3942
                    ).'&group_id='.api_htmlentities(
3943
                        $_GET['group_id']
3944
                    ).'">'.$obj->NUM_EDIT.'</a>';
3945
                $rows[] = $row;
3946
            }
3947
3948
            $table = new SortableTableFromArrayConfig(
3949
                $rows,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $rows does not seem to be defined for all execution paths leading up to this point.
Loading history...
3950
                1,
3951
                10,
3952
                'MostActiveUsersA_table',
3953
                '',
3954
                '',
3955
                'DESC'
3956
            );
3957
            $table->set_additional_parameters(
3958
                [
3959
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
3960
                    'action' => Security::remove_XSS($action),
3961
                    'session_id' => Security::remove_XSS($_GET['session_id']),
3962
                    'group_id' => Security::remove_XSS($_GET['group_id'])
3963
                ]
3964
            );
3965
            $table->set_header(0, get_lang('Author'), true);
3966
            $table->set_header(
3967
                1,
3968
                get_lang('Contributions'),
3969
                true,
3970
                ['style' => 'width:30px;']
3971
            );
3972
            $table->display();
3973
        }
3974
    }
3975
3976
    /**
3977
     * @param string $page
3978
     */
3979
    public function getDiscuss($page)
3980
    {
3981
        $tbl_wiki = $this->tbl_wiki;
3982
        $course_id = $this->course_id;
3983
        $condition_session = $this->condition_session;
3984
        $groupfilter = $this->groupfilter;
3985
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
3986
3987
        if (api_get_session_id() != 0 &&
3988
            api_is_allowed_to_session_edit(false, true) == false
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
3989
        ) {
3990
            api_not_allowed();
3991
        }
3992
3993
        if (!$_GET['title']) {
3994
            Display::addFlash(
3995
                Display::return_message(
3996
                    get_lang("MustSelectPage"),
3997
                    'error',
3998
                    false
3999
                )
4000
            );
4001
4002
            return;
4003
        }
4004
4005
        // First extract the date of last version
4006
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4007
                WHERE
4008
                    c_id = '.$course_id.' AND
4009
                    reflink = "'.Database::escape_string($page).'" AND
4010
                    '.$groupfilter.$condition_session.'
4011
                ORDER BY id DESC';
4012
        $result = Database::query($sql);
4013
        $row = Database::fetch_array($result);
4014
        $lastversiondate = api_get_local_time($row['dtime']);
4015
        $lastuserinfo = api_get_user_info($row['user_id']);
4016
4017
        // Select page to discuss
4018
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4019
                WHERE
4020
                    c_id = '.$course_id.' AND
4021
                    reflink="'.Database::escape_string($page).'" AND
4022
                    '.$groupfilter.$condition_session.'
4023
                ORDER BY id ASC';
4024
        $result = Database::query($sql);
4025
        $row = Database::fetch_array($result);
4026
        $id = $row['id'];
4027
        $firstuserid = $row['user_id'];
4028
4029
        if (isset($_POST['Submit']) && self::double_post($_POST['wpost_id'])) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::double_post() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

4029
        if (isset($_POST['Submit']) && self::/** @scrutinizer ignore-call */ double_post($_POST['wpost_id'])) {
Loading history...
4030
            $dtime = api_get_utc_datetime();
4031
            $message_author = api_get_user_id();
4032
4033
            $params = [
4034
                'c_id' => $course_id,
4035
                'publication_id' => $id,
4036
                'userc_id' => $message_author,
4037
                'comment' => $_POST['comment'],
4038
                'p_score' => $_POST['rating'],
4039
                'dtime' => $dtime
4040
            ];
4041
            $discussId = Database::insert($tbl_wiki_discuss, $params);
4042
            if ($discussId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $discussId of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
4043
                $sql = "UPDATE $tbl_wiki_discuss SET id = iid WHERE iid = $discussId";
4044
                Database::query($sql);
4045
            }
4046
4047
            self::check_emailcue($id, 'D', $dtime, $message_author);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_emailcue() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

4047
            self::/** @scrutinizer ignore-call */ 
4048
                  check_emailcue($id, 'D', $dtime, $message_author);
Loading history...
4048
4049
            header(
4050
                'Location: index.php?action=discuss&title='.api_htmlentities(urlencode($page)).'&'.api_get_cidreq()
4051
            );
4052
            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...
4053
        }
4054
4055
        // mode assignment: previous to show  page type
4056
        $icon_assignment = null;
4057
        if ($row['assignment'] == 1) {
4058
            $icon_assignment = Display::return_icon(
4059
                'wiki_assignment.png',
4060
                get_lang('AssignmentDescExtra'),
4061
                '',
4062
                ICON_SIZE_SMALL
4063
            );
4064
        } elseif ($row['assignment'] == 2) {
4065
            $icon_assignment = Display::return_icon(
4066
                'wiki_work.png',
4067
                get_lang('AssignmentWorkExtra'),
4068
                '',
4069
                ICON_SIZE_SMALL
4070
            );
4071
        }
4072
4073
        $countWPost = null;
4074
        $avg_WPost_score = null;
4075
4076
        // Show title and form to discuss if page exist
4077
        if ($id != '') {
4078
            // Show discussion to students if isn't hidden.
4079
            // Show page to all teachers if is hidden.
4080
            // Mode assignments: If is hidden, show pages to student only if student is the author
4081
            if ($row['visibility_disc'] == 1 ||
4082
                api_is_allowed_to_edit(false, true) ||
4083
                api_is_platform_admin() ||
4084
                ($row['assignment'] == 2 && $row['visibility_disc'] == 0 && (api_get_user_id() == $row['user_id']))
4085
            ) {
4086
                echo '<div id="wikititle">';
4087
                // discussion action: protecting (locking) the discussion
4088
                $addlock_disc = null;
4089
                $lock_unlock_disc = null;
4090
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4091
                    if (self::check_addlock_discuss() == 1) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_addlock_discuss() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

4091
                    if (self::/** @scrutinizer ignore-call */ check_addlock_discuss() == 1) {
Loading history...
4092
                        $addlock_disc = Display::return_icon(
4093
                            'unlock.png',
4094
                            get_lang('UnlockDiscussExtra'),
4095
                            '',
4096
                            ICON_SIZE_SMALL
4097
                        );
4098
                        $lock_unlock_disc = 'unlockdisc';
4099
                    } else {
4100
                        $addlock_disc = Display::return_icon(
4101
                            'lock.png',
4102
                            get_lang('LockDiscussExtra'),
4103
                            '',
4104
                            ICON_SIZE_SMALL
4105
                        );
4106
                        $lock_unlock_disc = 'lockdisc';
4107
                    }
4108
                }
4109
                echo '<span style="float:right">';
4110
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_disc.'&title='.api_htmlentities(
4111
                        urlencode($page)
4112
                    ).'">'.$addlock_disc.'</a>';
4113
                echo '</span>';
4114
4115
                // discussion action: visibility.  Show discussion to students if isn't hidden. Show page to all teachers if is hidden.
4116
                $visibility_disc = null;
4117
                $hide_show_disc = null;
4118
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4119
                    if (self::check_visibility_discuss() == 1) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_visibility_discuss() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

4119
                    if (self::/** @scrutinizer ignore-call */ check_visibility_discuss() == 1) {
Loading history...
4120
                        /// TODO: 	Fix Mode assignments: If is hidden, show discussion to student only if student is the author
4121
                        $visibility_disc = Display::return_icon(
4122
                            'visible.png',
4123
                            get_lang('ShowDiscussExtra'),
4124
                            '',
4125
                            ICON_SIZE_SMALL
4126
                        );
4127
                        $hide_show_disc = 'hidedisc';
4128
                    } else {
4129
                        $visibility_disc = Display::return_icon(
4130
                            'invisible.png',
4131
                            get_lang('HideDiscussExtra'),
4132
                            '',
4133
                            ICON_SIZE_SMALL
4134
                        );
4135
                        $hide_show_disc = 'showdisc';
4136
                    }
4137
                }
4138
                echo '<span style="float:right">';
4139
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$hide_show_disc.'&title='.api_htmlentities(
4140
                        urlencode($page)
4141
                    ).'">'.$visibility_disc.'</a>';
4142
                echo '</span>';
4143
4144
                // discussion action: check add rating lock. Show/Hide list to rating for all student
4145
                $lock_unlock_rating_disc = null;
4146
                $ratinglock_disc = null;
4147
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4148
                    if (self::check_ratinglock_discuss() == 1) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_ratinglock_discuss() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

4148
                    if (self::/** @scrutinizer ignore-call */ check_ratinglock_discuss() == 1) {
Loading history...
4149
                        $ratinglock_disc = Display::return_icon(
4150
                            'star.png',
4151
                            get_lang('UnlockRatingDiscussExtra'),
4152
                            '',
4153
                            ICON_SIZE_SMALL
4154
                        );
4155
                        $lock_unlock_rating_disc = 'unlockrating';
4156
                    } else {
4157
                        $ratinglock_disc = Display::return_icon(
4158
                            'star_na.png',
4159
                            get_lang('LockRatingDiscussExtra'),
4160
                            '',
4161
                            ICON_SIZE_SMALL
4162
                        );
4163
                        $lock_unlock_rating_disc = 'lockrating';
4164
                    }
4165
                }
4166
4167
                echo '<span style="float:right">';
4168
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_rating_disc.'&title='.api_htmlentities(
4169
                        urlencode($page)
4170
                    ).'">'.$ratinglock_disc.'</a>';
4171
                echo '</span>';
4172
4173
                // discussion action: email notification
4174
                if (self::check_notify_discuss($page) == 1) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_notify_discuss() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

4174
                if (self::/** @scrutinizer ignore-call */ check_notify_discuss($page) == 1) {
Loading history...
4175
                    $notify_disc = Display::return_icon(
4176
                        'messagebox_info.png',
4177
                        get_lang('NotifyDiscussByEmail'),
4178
                        '',
4179
                        ICON_SIZE_SMALL
4180
                    );
4181
                    $lock_unlock_notify_disc = 'unlocknotifydisc';
4182
                } else {
4183
                    $notify_disc = Display::return_icon(
4184
                        'mail.png',
4185
                        get_lang('CancelNotifyDiscussByEmail'),
4186
                        '',
4187
                        ICON_SIZE_SMALL
4188
                    );
4189
                    $lock_unlock_notify_disc = 'locknotifydisc';
4190
                }
4191
                echo '<span style="float:right">';
4192
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_notify_disc.'&title='.api_htmlentities(
4193
                        urlencode($page)
4194
                    ).'">'.$notify_disc.'</a>';
4195
                echo '</span>';
4196
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities(
4197
                        $row['title']
4198
                    );
4199
                if ($lastuserinfo !== false) {
4200
                    echo ' ('.get_lang('MostRecentVersionBy').' '.
4201
                        UserManager::getUserProfileLink($lastuserinfo).' '.$lastversiondate.$countWPost.')'.$avg_WPost_score.' '; //TODO: read average score
4202
                }
4203
4204
                echo '</div>';
4205
                if ($row['addlock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4206
                    //show comments but students can't add theirs
4207
                    ?>
4208
                    <div class="panel panel-default">
4209
                        <div class="panel-body">
4210
                            <form name="form1" method="post" action=""
4211
                                  class="form-horizontal">
4212
                                <div class="form-group">
4213
                                    <label
4214
                                        class="col-sm-2 control-label">
4215
                                        <?php echo get_lang('Comments'); ?>:</label>
4216
                                    <div class="col-sm-10">
4217
                                        <?php echo '<input type="hidden" name="wpost_id" value="'.md5(uniqid(rand(), true)).'">'; //prevent double post?>
0 ignored issues
show
Bug introduced by
The call to rand() has too few arguments starting with min. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

4217
                                        <?php echo '<input type="hidden" name="wpost_id" value="'.md5(uniqid(/** @scrutinizer ignore-call */ rand(), true)).'">'; //prevent double post?>

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
4218
                                        <textarea class="form-control"
4219
                                                  name="comment" cols="80"
4220
                                                  rows="5"
4221
                                                  id="comment">
4222
                                        </textarea>
4223
                                    </div>
4224
                                </div>
4225
                                <div class="form-group">
4226
                                    <?php
4227
                                    //check if rating is allowed
4228
                                    if ($row['ratinglock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4229
                                        ?>
4230
                                        <label
4231
                                            class="col-sm-2 control-label"><?php echo get_lang('Rating'); ?>:</label>
4232
                                        <div class="col-sm-10">
4233
                                            <select name="rating" id="rating" class="selectpicker">
4234
                                                <option value="-" selected>-</option>
4235
                                                <option value="0">0</option>
4236
                                                <option value="1">1</option>
4237
                                                <option value="2">2</option>
4238
                                                <option value="3">3</option>
4239
                                                <option value="4">4</option>
4240
                                                <option value="5">5</option>
4241
                                                <option value="6">6</option>
4242
                                                <option value="7">7</option>
4243
                                                <option value="8">8</option>
4244
                                                <option value="9">9</option>
4245
                                                <option value="10">10</option>
4246
                                            </select>
4247
                                        </div>
4248
                                        <?php
4249
                                    } else {
4250
                                        echo '<input type=hidden name="rating" value="-">';
4251
                                        // must pass a default value to avoid rate automatically
4252
                                    } ?>
4253
4254
                                </div>
4255
                                <div class="form-group">
4256
                                    <div class="col-sm-offset-2 col-sm-10">
4257
                                        <?php echo '<button class="btn btn-default" type="submit" name="Submit"> '.
4258
                                            get_lang('Send').'</button>'; ?>
4259
                                    </div>
4260
                                </div>
4261
                        </div>
4262
                    </div>
4263
                    </form>
4264
                    <?php
4265
                }
4266
                // end discuss lock
4267
4268
                echo '<hr noshade size="1">';
4269
                $user_table = Database::get_main_table(TABLE_MAIN_USER);
4270
4271
                $sql = "SELECT *
4272
                        FROM $tbl_wiki_discuss reviews, $user_table user
4273
                        WHERE
4274
                            reviews.c_id = $course_id AND
4275
                            reviews.publication_id='".$id."' AND
4276
                            user.user_id='".$firstuserid."'
4277
                        ORDER BY reviews.id DESC";
4278
                $result = Database::query($sql);
4279
4280
                $countWPost = Database::num_rows($result);
4281
                echo get_lang('NumComments').": ".$countWPost; //comment's numbers
4282
4283
                $sql = "SELECT SUM(p_score) as sumWPost
4284
                        FROM $tbl_wiki_discuss
4285
                        WHERE c_id = $course_id AND publication_id = '".$id."' AND NOT p_score='-'
4286
                        ORDER BY id DESC";
4287
                $result2 = Database::query($sql);
4288
                $row2 = Database::fetch_array($result2);
4289
4290
                $sql = "SELECT * FROM $tbl_wiki_discuss
4291
                        WHERE c_id = $course_id AND publication_id='".$id."' AND NOT p_score='-'";
4292
                $result3 = Database::query($sql);
4293
                $countWPost_score = Database::num_rows($result3);
4294
4295
                echo ' - '.get_lang('NumCommentsScore').': '.$countWPost_score;
4296
4297
                if ($countWPost_score != 0) {
4298
                    $avg_WPost_score = round($row2['sumWPost'] / $countWPost_score, 2).' / 10';
4299
                } else {
4300
                    $avg_WPost_score = $countWPost_score;
4301
                }
4302
4303
                echo ' - '.get_lang('RatingMedia').': '.$avg_WPost_score; // average rating
4304
4305
                $sql = 'UPDATE '.$tbl_wiki.' SET
4306
                        score = "'.Database::escape_string($avg_WPost_score).'"
4307
                        WHERE
4308
                            c_id = '.$course_id.' AND
4309
                            reflink="'.Database::escape_string($page).'" AND
4310
                            '.$groupfilter.$condition_session;
4311
                // check if work ok. TODO:
4312
                Database::query($sql);
4313
4314
                echo '<hr noshade size="1">';
4315
                while ($row = Database::fetch_array($result)) {
4316
                    $userinfo = api_get_user_info($row['userc_id']);
4317
                    if (($userinfo['status']) == "5") {
4318
                        $author_status = get_lang('Student');
4319
                    } else {
4320
                        $author_status = get_lang('Teacher');
4321
                    }
4322
4323
                    $name = $userinfo['complete_name'];
4324
                    $author_photo = '<img src="'.$userinfo['avatar'].'" alt="'.api_htmlentities($name).'"  width="40" height="50" align="top"  title="'.api_htmlentities($name).'"  />';
4325
4326
                    // stars
4327
                    $p_score = $row['p_score'];
4328
                    switch ($p_score) {
4329
                        case  0:
4330
                            $imagerating = Display::return_icon(
4331
                                'rating/stars_0.gif'
4332
                            );
4333
                            break;
4334
                        case  1:
4335
                            $imagerating = Display::return_icon(
4336
                                'rating/stars_5.gif'
4337
                            );
4338
                            break;
4339
                        case  2:
4340
                            $imagerating = Display::return_icon(
4341
                                'rating/stars_10.gif'
4342
                            );
4343
                            break;
4344
                        case  3:
4345
                            $imagerating = Display::return_icon(
4346
                                'rating/stars_15.gif'
4347
                            );
4348
                            break;
4349
                        case  4:
4350
                            $imagerating = Display::return_icon(
4351
                                'rating/stars_20.gif'
4352
                            );
4353
                            break;
4354
                        case  5:
4355
                            $imagerating = Display::return_icon(
4356
                                'rating/stars_25.gif'
4357
                            );
4358
                            break;
4359
                        case  6:
4360
                            $imagerating = Display::return_icon(
4361
                                'rating/stars_30.gif'
4362
                            );
4363
                            break;
4364
                        case  7:
4365
                            $imagerating = Display::return_icon(
4366
                                'rating/stars_35.gif'
4367
                            );
4368
                            break;
4369
                        case  8:
4370
                            $imagerating = Display::return_icon(
4371
                                'rating/stars_40.gif'
4372
                            );
4373
                            break;
4374
                        case  9:
4375
                            $imagerating = Display::return_icon(
4376
                                'rating/stars_45.gif'
4377
                            );
4378
                            break;
4379
                        case  10:
4380
                            $imagerating = Display::return_icon(
4381
                                'rating/stars_50.gif'
4382
                            );
4383
                            break;
4384
                    }
4385
                    echo '<p><table>';
4386
                    echo '<tr>';
4387
                    echo '<td rowspan="2">'.$author_photo.'</td>';
4388
                    $userProfile = '';
4389
                    if ($userinfo !== false) {
4390
                        $userProfile = UserManager::getUserProfileLink(
4391
                            $userinfo
4392
                        );
4393
                    }
4394
                    echo '<td style=" color:#999999">'.$userProfile.' ('.$author_status.') '.
4395
                        api_get_local_time(
4396
                            $row['dtime']
4397
                        ).
4398
                        ' - '.get_lang(
4399
                            'Rating'
4400
                        ).': '.$row['p_score'].' '.$imagerating.' </td>';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $imagerating does not seem to be defined for all execution paths leading up to this point.
Loading history...
4401
                    echo '</tr>';
4402
                    echo '<tr>';
4403
                    echo '<td>'.api_htmlentities($row['comment']).'</td>';
4404
                    echo '</tr>';
4405
                    echo "</table>";
4406
                }
4407
            } else {
4408
                Display::addFlash(
4409
                    Display::return_message(
4410
                        get_lang('LockByTeacher'),
4411
                        'warning',
4412
                        false
4413
                    )
4414
                );
4415
            }
4416
        } else {
4417
            Display::addFlash(
4418
                Display::return_message(
4419
                    get_lang('DiscussNotAvailable'),
4420
                    'normal',
4421
                    false
4422
                )
4423
            );
4424
        }
4425
    }
4426
4427
    /**
4428
     * Show all pages
4429
     */
4430
    public function allPages($action)
4431
    {
4432
        $tbl_wiki = $this->tbl_wiki;
4433
        $course_id = $this->course_id;
4434
        $session_id = $this->session_id;
4435
        $groupfilter = $this->groupfilter;
4436
        $_course = $this->courseInfo;
4437
4438
        echo '<div class="actions">'.get_lang('AllPages');
4439
4440
        // menu delete all wiki
4441
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4442
            echo ' <a href="index.php?action=deletewiki&'.api_get_cidreq().'">'.
4443
                Display::return_icon(
4444
                    'delete.png',
4445
                    get_lang('DeleteWiki'),
4446
                    '',
4447
                    ICON_SIZE_MEDIUM
4448
                ).'</a>';
4449
        }
4450
        echo '</div>';
4451
4452
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin(
4453
            )) { //only by professors if page is hidden
4454
            $sql = 'SELECT  *
4455
                    FROM  '.$tbl_wiki.' s1
4456
        		    WHERE s1.c_id = '.$course_id.' AND id=(
4457
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
4458
                    WHERE
4459
                        s2.c_id = '.$course_id.' AND 
4460
                        s1.reflink = s2.reflink AND 
4461
                        '.$groupfilter.' AND 
4462
                        session_id='.$session_id.')';
4463
            // warning don't use group by reflink because does not return the last version
4464
        } else {
4465
            $sql = 'SELECT  *  FROM '.$tbl_wiki.' s1
4466
				    WHERE visibility=1 AND s1.c_id = '.$course_id.' AND id=(
4467
                        SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
4468
                        WHERE 
4469
                            s2.c_id = '.$course_id.' AND 
4470
                            s1.reflink = s2.reflink AND
4471
                             '.$groupfilter.' AND 
4472
                             session_id='.$session_id.')';
4473
            // warning don't use group by reflink because does not return the last version
4474
        }
4475
4476
        $allpages = Database::query($sql);
4477
4478
        //show table
4479
        if (Database::num_rows($allpages) > 0) {
4480
            while ($obj = Database::fetch_object($allpages)) {
4481
                //get author
4482
                $userinfo = api_get_user_info($obj->user_id);
4483
                $username = api_htmlentities(
4484
                    sprintf(get_lang('LoginX'), $userinfo['username']),
4485
                    ENT_QUOTES
4486
                );
4487
4488
                //get type assignment icon
4489
                if ($obj->assignment == 1) {
4490
                    $ShowAssignment = Display::return_icon(
4491
                        'wiki_assignment.png',
4492
                        get_lang('AssignmentDesc'),
4493
                        '',
4494
                        ICON_SIZE_SMALL
4495
                    );
4496
                } elseif ($obj->assignment == 2) {
4497
                    $ShowAssignment = Display::return_icon(
4498
                        'wiki_work.png',
4499
                        get_lang('AssignmentWork'),
4500
                        '',
4501
                        ICON_SIZE_SMALL
4502
                    );
4503
                } elseif ($obj->assignment == 0) {
4504
                    $ShowAssignment = Display::return_icon(
4505
                        'px_transparent.gif'
4506
                    );
4507
                }
4508
4509
                //get icon task
4510
                if (!empty($obj->task)) {
4511
                    $icon_task = Display::return_icon(
4512
                        'wiki_task.png',
4513
                        get_lang('StandardTask'),
4514
                        '',
4515
                        ICON_SIZE_SMALL
4516
                    );
4517
                } else {
4518
                    $icon_task = Display::return_icon('px_transparent.gif');
4519
                }
4520
4521
                $row = [];
4522
                $row[] = $ShowAssignment.$icon_task;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ShowAssignment does not seem to be defined for all execution paths leading up to this point.
Loading history...
4523
                $row[] = '<a href="'.api_get_self(
4524
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4525
                        urlencode($obj->reflink)
4526
                    ).'&session_id='.api_htmlentities(
4527
                        $_GET['session_id']
4528
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">
4529
                '.api_htmlentities($obj->title).'</a>';
4530
                if ($userinfo !== false) {
4531
                    $row[] = UserManager::getUserProfileLink($userinfo);
4532
                } else {
4533
                    $row[] = get_lang('Anonymous').' ('.api_htmlentities(
4534
                            $obj->user_ip
4535
                        ).')';
4536
                }
4537
                $row[] = api_get_local_time(
4538
                    $obj->dtime
4539
                );
4540
                $showdelete = '';
4541
                if (api_is_allowed_to_edit(
4542
                        false,
4543
                        true
4544
                    ) || api_is_platform_admin()) {
4545
                    $showdelete = ' <a href="'.api_get_self(
4546
                        ).'?cidReq='.$_course['code'].'&action=delete&title='.api_htmlentities(
4547
                            urlencode($obj->reflink)
4548
                        ).'&session_id='.api_htmlentities(
4549
                            $_GET['session_id']
4550
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4551
                        Display::return_icon(
4552
                            'delete.png',
4553
                            get_lang('Delete'),
4554
                            '',
4555
                            ICON_SIZE_SMALL
4556
                        );
4557
                }
4558
                if (api_is_allowed_to_session_edit(false, true)) {
4559
                    $row[] = '<a href="'.api_get_self(
4560
                        ).'?cidReq='.$_course['code'].'&action=edit&title='.api_htmlentities(
4561
                            urlencode($obj->reflink)
4562
                        ).'&session_id='.api_htmlentities(
4563
                            $_GET['session_id']
4564
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4565
                        Display::return_icon(
4566
                            'edit.png',
4567
                            get_lang('EditPage'),
4568
                            '',
4569
                            ICON_SIZE_SMALL
4570
                        ).'</a> <a href="'.api_get_self(
4571
                        ).'?cidReq='.$_course['code'].'&action=discuss&title='.api_htmlentities(
4572
                            urlencode($obj->reflink)
4573
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4574
                        Display::return_icon(
4575
                            'discuss.png',
4576
                            get_lang('Discuss'),
4577
                            '',
4578
                            ICON_SIZE_SMALL
4579
                        ).'</a> <a href="'.api_get_self(
4580
                        ).'?cidReq='.$_course['code'].'&action=history&title='.api_htmlentities(
4581
                            urlencode($obj->reflink)
4582
                        ).'&session_id='.api_htmlentities(
4583
                            $_GET['session_id']
4584
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4585
                        Display::return_icon(
4586
                            'history.png',
4587
                            get_lang('History'),
4588
                            '',
4589
                            ICON_SIZE_SMALL
4590
                        ).'</a>
4591
                        <a href="'.api_get_self(
4592
                        ).'?cidReq='.$_course['code'].'&action=links&title='.api_htmlentities(
4593
                            urlencode($obj->reflink)
4594
                        ).'&session_id='.api_htmlentities(
4595
                            $_GET['session_id']
4596
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4597
                        Display::return_icon(
4598
                            'what_link_here.png',
4599
                            get_lang('LinksPages'),
4600
                            '',
4601
                            ICON_SIZE_SMALL
4602
                        ).'</a>'.$showdelete;
4603
                }
4604
                $rows[] = $row;
4605
            }
4606
4607
            $table = new SortableTableFromArrayConfig(
4608
                $rows,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $rows does not seem to be defined for all execution paths leading up to this point.
Loading history...
4609
                1,
4610
                10,
4611
                'AllPages_table',
4612
                '',
4613
                '',
4614
                'ASC'
4615
            );
4616
            $table->set_additional_parameters(
4617
                [
4618
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
4619
                    'action' => Security::remove_XSS($action),
4620
                    'group_id' => Security::remove_XSS($_GET['group_id'])
4621
                ]
4622
            );
4623
            $table->set_header(
4624
                0,
4625
                get_lang('Type'),
4626
                true,
4627
                ['style' => 'width:30px;']
4628
            );
4629
            $table->set_header(1, get_lang('Title'), true);
4630
            $table->set_header(
4631
                2,
4632
                get_lang('Author').' ('.get_lang('LastVersion').')',
4633
                true
4634
            );
4635
            $table->set_header(
4636
                3,
4637
                get_lang('Date').' ('.get_lang('LastVersion').')',
4638
                true
4639
            );
4640
            if (api_is_allowed_to_session_edit(false, true)) {
4641
                $table->set_header(
4642
                    4,
4643
                    get_lang('Actions'),
4644
                    true,
4645
                    ['style' => 'width:130px;']
4646
                );
4647
            }
4648
            $table->display();
4649
        }
4650
    }
4651
4652
    /**
4653
     * Get recent changes
4654
     * @param string $page
4655
     * @param string $action
4656
     *
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) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_notify_all() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

4667
            if (self::/** @scrutinizer ignore-call */ check_notify_all() == 1) {
Loading history...
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(
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $lock_unlock_notify_all does not seem to be defined for all execution paths leading up to this point.
Loading history...
4688
                urlencode($page)
4689
            ).'">'.$notify_all.'</a>';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $notify_all does not seem to be defined for all execution paths leading up to this point.
Loading history...
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;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ShowAssignment does not seem to be defined for all execution paths leading up to this point.
Loading history...
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
            //table
4893
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin(
4894
                )) {
4895
                //only by professors if page is hidden
4896
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4897
                        WHERE s1.c_id = $course_id AND linksto LIKE '%".Database::escape_string(
4898
                        $page
4899
                    )."%' AND id=(
4900
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4901
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4902
                //add blank space after like '%" " %' to identify each word
4903
            } else {
4904
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4905
                        WHERE s1.c_id = $course_id AND visibility=1 AND linksto LIKE '%".Database::escape_string(
4906
                        $page
4907
                    )."%' AND id=(
4908
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4909
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4910
                //add blank space after like '%" " %' to identify each word
4911
            }
4912
4913
            $allpages = Database::query($sql);
4914
4915
            //show table
4916
            if (Database::num_rows($allpages) > 0) {
4917
                $rows = [];
4918
                while ($obj = Database::fetch_object($allpages)) {
4919
                    //get author
4920
                    $userinfo = api_get_user_info($obj->user_id);
4921
4922
                    //get time
4923
                    $year = substr($obj->dtime, 0, 4);
4924
                    $month = substr($obj->dtime, 5, 2);
4925
                    $day = substr($obj->dtime, 8, 2);
4926
                    $hours = substr($obj->dtime, 11, 2);
4927
                    $minutes = substr($obj->dtime, 14, 2);
4928
                    $seconds = substr($obj->dtime, 17, 2);
4929
4930
                    //get type assignment icon
4931
                    if ($obj->assignment == 1) {
4932
                        $ShowAssignment = Display::return_icon(
4933
                            'wiki_assignment.png',
4934
                            get_lang('AssignmentDesc'),
4935
                            '',
4936
                            ICON_SIZE_SMALL
4937
                        );
4938
                    } elseif ($obj->assignment == 2) {
4939
                        $ShowAssignment = Display::return_icon(
4940
                            'wiki_work.png',
4941
                            get_lang('AssignmentWork'),
4942
                            '',
4943
                            ICON_SIZE_SMALL
4944
                        );
4945
                    } elseif ($obj->assignment == 0) {
4946
                        $ShowAssignment = Display::return_icon(
4947
                            'px_transparent.gif'
4948
                        );
4949
                    }
4950
4951
                    $row = [];
4952
                    $row[] = $ShowAssignment;
4953
                    $row[] = '<a href="'.api_get_self(
4954
                        ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4955
                            urlencode($obj->reflink)
4956
                        ).'&session_id='.api_htmlentities(
4957
                            $_GET['session_id']
4958
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4959
                        api_htmlentities($obj->title).'</a>';
4960
                    if ($userinfo !== false) {
4961
                        $row[] = UserManager::getUserProfileLink($userinfo);
4962
                    } else {
4963
                        $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
4964
                    }
4965
                    $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
4966
                    $rows[] = $row;
4967
                }
4968
4969
                $table = new SortableTableFromArrayConfig(
4970
                    $rows,
4971
                    1,
4972
                    10,
4973
                    'AllPages_table',
4974
                    '',
4975
                    '',
4976
                    'ASC'
4977
                );
4978
                $table->set_additional_parameters(
4979
                    [
4980
                        'cidReq' => Security::remove_XSS($_GET['cidReq']),
4981
                        'action' => Security::remove_XSS($action),
4982
                        'group_id' => intval($_GET['group_id']),
4983
                    ]
4984
                );
4985
                $table->set_header(
4986
                    0,
4987
                    get_lang('Type'),
4988
                    true,
4989
                    ['style' => 'width:30px;']
4990
                );
4991
                $table->set_header(1, get_lang('Title'), true);
4992
                $table->set_header(2, get_lang('Author'), true);
4993
                $table->set_header(3, get_lang('Date'), true);
4994
                $table->display();
4995
            }
4996
        }
4997
    }
4998
4999
    /**
5000
     * @param string $action
5001
     */
5002
    public function getSearchPages($action)
5003
    {
5004
        echo '<div class="actions">'.get_lang('SearchPages').'</div>';
5005
        if (isset($_GET['mode_table'])) {
5006
            if (!isset($_GET['SearchPages_table_page_nr'])) {
5007
                $_GET['search_term'] = isset($_POST['search_term']) ? $_POST['search_term'] : '';
5008
                $_GET['search_content'] = isset($_POST['search_content']) ? $_POST['search_content'] : '';
5009
                $_GET['all_vers'] = isset($_POST['all_vers']) ? $_POST['all_vers'] : '';
5010
            }
5011
            self::display_wiki_search_results(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::display_wiki_search_results() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

5011
            self::/** @scrutinizer ignore-call */ 
5012
                  display_wiki_search_results(
Loading history...
5012
                $_GET['search_term'],
5013
                $_GET['search_content'],
5014
                $_GET['all_vers']
5015
            );
5016
        } else {
5017
5018
            // initiate the object
5019
            $form = new FormValidator(
5020
                'wiki_search',
5021
                'post',
5022
                api_get_self().'?cidReq='.api_get_course_id(
5023
                ).'&action='.api_htmlentities(
5024
                    $action
5025
                ).'&session_id='.api_get_session_id(
5026
                ).'&group_id='.api_get_group_id().'&mode_table=yes1'
5027
            );
5028
5029
            // Setting the form elements
5030
5031
            $form->addText(
5032
                'search_term',
5033
                get_lang('SearchTerm'),
5034
                true,
5035
                ['autofocus' => 'autofocus']
5036
            );
5037
            $form->addElement(
5038
                'checkbox',
5039
                'search_content',
5040
                null,
5041
                get_lang('AlsoSearchContent')
5042
            );
5043
            $form->addElement(
5044
                'checkbox',
5045
                'all_vers',
5046
                null,
5047
                get_lang('IncludeAllVersions')
5048
            );
5049
            $form->addButtonSearch(get_lang('Search'), 'SubmitWikiSearch');
5050
5051
            // setting the rules
5052
            $form->addRule(
5053
                'search_term',
5054
                get_lang('TooShort'),
5055
                'minlength',
5056
                3
5057
            ); //TODO: before fixing the pagination rules worked, not now
5058
5059
            if ($form->validate()) {
5060
                $form->display();
5061
                $values = $form->exportValues();
5062
                self::display_wiki_search_results(
5063
                    $values['search_term'],
5064
                    $values['search_content'],
5065
                    $values['all_vers']
5066
                );
5067
            } else {
5068
                $form->display();
5069
            }
5070
        }
5071
    }
5072
5073
    /**
5074
     * @param int $userId
5075
     * @param string $action
5076
     */
5077
    public function getUserContributions($userId, $action)
5078
    {
5079
        $_course = $this->courseInfo;
5080
        $tbl_wiki = $this->tbl_wiki;
5081
        $course_id = $this->course_id;
5082
        $condition_session = $this->condition_session;
5083
        $groupfilter = $this->groupfilter;
5084
        $userId = intval($userId);
5085
        $userinfo = api_get_user_info($userId);
5086
        if ($userinfo !== false) {
5087
            echo '<div class="actions">'.
5088
                get_lang('UserContributions').': '.UserManager::getUserProfileLink($userinfo).
5089
                '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.$userId.
5090
                '&session_id='.$this->session_id.'&group_id='.$this->group_id.'">'.
5091
                '</a></div>';
5092
        }
5093
5094
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5095
            //only by professors if page is hidden
5096
            $sql = 'SELECT * FROM '.$tbl_wiki.'
5097
                    WHERE
5098
                        c_id = '.$course_id.' AND
5099
                        '.$groupfilter.$condition_session.' AND
5100
                        user_id="'.$userId.'"';
5101
        } else {
5102
            $sql = 'SELECT * FROM '.$tbl_wiki.'
5103
                    WHERE
5104
                        c_id = '.$course_id.' AND
5105
                        '.$groupfilter.$condition_session.' AND
5106
                        user_id="'.$userId.'" AND
5107
                        visibility=1';
5108
        }
5109
5110
        $allpages = Database::query($sql);
5111
5112
        //show table
5113
        if (Database::num_rows($allpages) > 0) {
5114
            $rows = [];
5115
            while ($obj = Database::fetch_object($allpages)) {
5116
                //get type assignment icon
5117
                $ShowAssignment = '';
5118
                if ($obj->assignment == 1) {
5119
                    $ShowAssignment = Display::return_icon(
5120
                        'wiki_assignment.png',
5121
                        get_lang('AssignmentDescExtra'),
5122
                        '',
5123
                        ICON_SIZE_SMALL
5124
                    );
5125
                } elseif ($obj->assignment == 2) {
5126
                    $ShowAssignment = Display::return_icon(
5127
                        'wiki_work.png',
5128
                        get_lang('AssignmentWork'),
5129
                        '',
5130
                        ICON_SIZE_SMALL
5131
                    );
5132
                } elseif ($obj->assignment == 0) {
5133
                    $ShowAssignment = Display::return_icon(
5134
                        'px_transparent.gif'
5135
                    );
5136
                }
5137
5138
                $row = [];
5139
                $row[] = api_get_local_time($obj->dtime);
5140
                $row[] = $ShowAssignment;
5141
                $row[] = '<a href="'.api_get_self(
5142
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5143
                        urlencode($obj->reflink)
5144
                    ).'&view='.$obj->id.'&session_id='.api_get_session_id(
5145
                    ).'&group_id='.api_get_group_id().'">'.
5146
                    api_htmlentities($obj->title).'</a>';
5147
                $row[] = Security::remove_XSS($obj->version);
5148
                $row[] = Security::remove_XSS($obj->comment);
5149
                $row[] = Security::remove_XSS($obj->progress).' %';
5150
                $row[] = Security::remove_XSS($obj->score);
5151
                $rows[] = $row;
5152
            }
5153
5154
            $table = new SortableTableFromArrayConfig(
5155
                $rows,
5156
                2,
5157
                10,
5158
                'UsersContributions_table',
5159
                '',
5160
                '',
5161
                'ASC'
5162
            );
5163
            $table->set_additional_parameters(
5164
                [
5165
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5166
                    'action' => Security::remove_XSS($action),
5167
                    'user_id' => intval($userId),
5168
                    'session_id' => intval($_GET['session_id']),
5169
                    'group_id' => intval($_GET['group_id']),
5170
                ]
5171
            );
5172
            $table->set_header(
5173
                0,
5174
                get_lang('Date'),
5175
                true,
5176
                ['style' => 'width:200px;']
5177
            );
5178
            $table->set_header(
5179
                1,
5180
                get_lang('Type'),
5181
                true,
5182
                ['style' => 'width:30px;']
5183
            );
5184
            $table->set_header(
5185
                2,
5186
                get_lang('Title'),
5187
                true,
5188
                ['style' => 'width:200px;']
5189
            );
5190
            $table->set_header(
5191
                3,
5192
                get_lang('Version'),
5193
                true,
5194
                ['style' => 'width:30px;']
5195
            );
5196
            $table->set_header(
5197
                4,
5198
                get_lang('Comment'),
5199
                true,
5200
                ['style' => 'width:200px;']
5201
            );
5202
            $table->set_header(
5203
                5,
5204
                get_lang('Progress'),
5205
                true,
5206
                ['style' => 'width:30px;']
5207
            );
5208
            $table->set_header(
5209
                6,
5210
                get_lang('Rating'),
5211
                true,
5212
                ['style' => 'width:30px;']
5213
            );
5214
            $table->display();
5215
        }
5216
    }
5217
5218
    /**
5219
     * @param string $action
5220
     */
5221
    public function getMostChangedPages($action)
5222
    {
5223
        $_course = $this->courseInfo;
5224
        $tbl_wiki = $this->tbl_wiki;
5225
        $course_id = $this->course_id;
5226
        $condition_session = $this->condition_session;
5227
        $groupfilter = $this->groupfilter;
5228
5229
        echo '<div class="actions">'.get_lang('MostChangedPages').'</div>';
5230
5231
        if (api_is_allowed_to_edit(false, true) ||
5232
            api_is_platform_admin()
5233
        ) { //only by professors if page is hidden
5234
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
5235
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5236
                    GROUP BY reflink';//TODO:check MAX and group by return last version
5237
        } else {
5238
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
5239
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND visibility=1
5240
                    GROUP BY reflink'; //TODO:check MAX and group by return last version
5241
        }
5242
5243
        $allpages = Database::query($sql);
5244
5245
        //show table
5246
        if (Database::num_rows($allpages) > 0) {
5247
            $rows = [];
5248
            while ($obj = Database::fetch_object($allpages)) {
5249
                //get type assignment icon
5250
                $ShowAssignment = '';
5251
                if ($obj->assignment == 1) {
5252
                    $ShowAssignment = Display::return_icon(
5253
                        'wiki_assignment.png',
5254
                        get_lang('AssignmentDesc'),
5255
                        '',
5256
                        ICON_SIZE_SMALL
5257
                    );
5258
                } elseif ($obj->assignment == 2) {
5259
                    $ShowAssignment = Display::return_icon(
5260
                        'wiki_work.png',
5261
                        get_lang('AssignmentWork'),
5262
                        '',
5263
                        ICON_SIZE_SMALL
5264
                    );
5265
                } elseif ($obj->assignment == 0) {
5266
                    $ShowAssignment = Display::return_icon(
5267
                        'px_transparent.gif'
5268
                    );
5269
                }
5270
5271
                $row = [];
5272
                $row[] = $ShowAssignment;
5273
                $row[] = '<a href="'.api_get_self(
5274
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5275
                        urlencode($obj->reflink)
5276
                    ).'&session_id='.api_htmlentities(
5277
                        $_GET['session_id']
5278
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5279
                    api_htmlentities($obj->title).'</a>';
5280
                $row[] = $obj->MAX;
5281
                $rows[] = $row;
5282
            }
5283
5284
            $table = new SortableTableFromArrayConfig(
5285
                $rows,
5286
                2,
5287
                10,
5288
                'MostChangedPages_table',
5289
                '',
5290
                '',
5291
                'DESC'
5292
            );
5293
            $table->set_additional_parameters(
5294
                [
5295
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5296
                    'action' => Security::remove_XSS($action),
5297
                    'session_id' => intval($_GET['session_id']),
5298
                    'group_id' => intval($_GET['group_id']),
5299
                ]
5300
            );
5301
            $table->set_header(
5302
                0,
5303
                get_lang('Type'),
5304
                true,
5305
                ['style' => 'width:30px;']
5306
            );
5307
            $table->set_header(1, get_lang('Title'), true);
5308
            $table->set_header(2, get_lang('Changes'), true);
5309
            $table->display();
5310
        }
5311
    }
5312
5313
    /**
5314
     * Restore page
5315
     * @return bool
5316
     */
5317
    public function restorePage()
5318
    {
5319
        $userId = api_get_user_id();
5320
        $_course = $this->courseInfo;
5321
        $current_row = $this->getWikiData();
5322
        $last_row = $this->getLastWikiData($this->page);
5323
5324
        if (empty($last_row)) {
5325
            return false;
5326
        }
5327
5328
        $PassEdit = false;
5329
5330
        /* Only teachers and platform admin can edit the index page.
5331
        Only teachers and platform admin can edit an assignment teacher*/
5332
        if (($current_row['reflink'] == 'index' ||
5333
                $current_row['reflink'] == '' ||
5334
                $current_row['assignment'] == 1) &&
5335
            (!api_is_allowed_to_edit(false, true) &&
5336
                $this->group_id == 0)
5337
        ) {
5338
            Display::addFlash(
5339
                Display::return_message(
5340
                    get_lang('OnlyEditPagesCourseManager'),
5341
                    'normal',
5342
                    false
5343
                )
5344
            );
5345
        } else {
5346
5347
            // check if is a wiki group
5348
            if ($current_row['group_id'] != 0) {
5349
                $groupInfo = GroupManager::get_group_properties(
5350
                    $this->group_id
5351
                );
5352
                //Only teacher, platform admin and group members can edit a wiki group
5353
                if (api_is_allowed_to_edit(false, true) ||
5354
                    api_is_platform_admin() ||
5355
                    GroupManager::is_user_in_group($userId, $groupInfo) ||
5356
                    api_is_allowed_in_course()
5357
                ) {
5358
                    $PassEdit = true;
5359
                } else {
5360
                    Display::addFlash(
5361
                        Display::return_message(
5362
                            get_lang('OnlyEditPagesGroupMembers'),
5363
                            'normal',
5364
                            false
5365
                        )
5366
                    );
5367
                }
5368
            } else {
5369
                $PassEdit = true;
5370
            }
5371
5372
            // check if is an assignment
5373
            //$icon_assignment = null;
5374
            if ($current_row['assignment'] == 1) {
5375
                Display::addFlash(
5376
                    Display::return_message(
5377
                        get_lang('EditAssignmentWarning'),
5378
                        'normal',
5379
                        false
5380
                    )
5381
                );
5382
            } elseif ($current_row['assignment'] == 2) {
5383
                if (($userId == $current_row['user_id']) == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
5384
                    if (api_is_allowed_to_edit(
5385
                            false,
5386
                            true
5387
                        ) || api_is_platform_admin()) {
5388
                        $PassEdit = true;
5389
                    } else {
5390
                        Display::addFlash(
5391
                            Display::return_message(
5392
                                get_lang('LockByTeacher'),
5393
                                'normal',
5394
                                false
5395
                            )
5396
                        );
5397
                        $PassEdit = false;
5398
                    }
5399
                } else {
5400
                    $PassEdit = true;
5401
                }
5402
            }
5403
5404
            //show editor if edit is allowed
5405
            if ($PassEdit) {
5406
                if ($current_row['editlock'] == 1 &&
5407
                    (api_is_allowed_to_edit(false, true) == false ||
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
5408
                        api_is_platform_admin() == false)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
5409
                ) {
5410
                    Display::addFlash(
5411
                        Display::return_message(
5412
                            get_lang('PageLockedExtra'),
5413
                            'normal',
5414
                            false
5415
                        )
5416
                    );
5417
                } else {
5418
                    if ($last_row['is_editing'] != 0 && $last_row['is_editing'] != $userId) {
5419
                        // Checking for concurrent users
5420
                        $timestamp_edit = strtotime($last_row['time_edit']);
5421
                        $time_editing = time() - $timestamp_edit;
5422
                        $max_edit_time = 1200; // 20 minutes
5423
                        $rest_time = $max_edit_time - $time_editing;
5424
                        $userinfo = api_get_user_info($last_row['is_editing']);
5425
                        $is_being_edited = get_lang(
5426
                                'ThisPageisBeginEditedBy'
5427
                            ).' <a href='.$userinfo['profile_url'].'>'.
5428
                            Display::tag(
5429
                                'span',
5430
                                $userinfo['complete_name_with_username']
5431
                            ).
5432
                            get_lang('ThisPageisBeginEditedTryLater').' '.date(
5433
                                "i",
5434
                                $rest_time
5435
                            ).' '.get_lang('MinMinutes');
5436
                        Display::addFlash(
5437
                            Display::return_message(
5438
                                $is_being_edited,
5439
                                'normal',
5440
                                false
5441
                            )
5442
                        );
5443
                    } else {
5444
                        Display::addFlash(
5445
                            Display::return_message(
5446
                                self::restore_wikipage(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::restore_wikipage() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

5446
                                self::/** @scrutinizer ignore-call */ 
5447
                                      restore_wikipage(
Loading history...
5447
                                    $current_row['page_id'],
5448
                                    $current_row['reflink'],
5449
                                    $current_row['title'],
5450
                                    $current_row['content'],
5451
                                    $current_row['group_id'],
5452
                                    $current_row['assignment'],
5453
                                    $current_row['progress'],
5454
                                    $current_row['version'],
5455
                                    $last_row['version'],
5456
                                    $current_row['linksto']
5457
                                ).': <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5458
                                    urlencode($last_row['reflink'])
5459
                                ).'&session_id='.$last_row['session_id'].'&group_id='.$last_row['group_id'].'">'.
5460
                                api_htmlentities($last_row['title']).'</a>',
5461
                                'confirmation',
5462
                                false
5463
                            )
5464
                        );
5465
                    }
5466
                }
5467
            }
5468
        }
5469
    }
5470
5471
    /**
5472
     * @param int|bool $wikiId
5473
     */
5474
    public function setWikiData($wikiId)
5475
    {
5476
        $this->wikiData = self::getWikiDataFromDb($wikiId);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getWikiDataFromDb() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

5476
        /** @scrutinizer ignore-call */ 
5477
        $this->wikiData = self::getWikiDataFromDb($wikiId);
Loading history...
5477
    }
5478
5479
    /**
5480
     * @return array
5481
     */
5482
    public function getWikiData()
5483
    {
5484
        return $this->wikiData;
5485
    }
5486
5487
    /**
5488
     * Check last version
5489
     * @param int $view
5490
     * @return bool
5491
     */
5492
    public function checkLastVersion($view)
5493
    {
5494
        $tbl_wiki = $this->tbl_wiki;
5495
        $course_id = $this->course_id;
5496
        $condition_session = $this->condition_session;
5497
        $groupfilter = $this->groupfilter;
5498
        $page = $this->page;
5499
        $_course = $this->courseInfo;
5500
5501
        if (empty($view)) {
5502
            return false;
5503
        }
5504
5505
        $current_row = $this->getWikiData();
5506
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5507
                WHERE
5508
                    c_id = '.$course_id.' AND
5509
                    reflink = "'.Database::escape_string($page).'" AND
5510
                    '.$groupfilter.$condition_session.'
5511
                ORDER BY id DESC'; //last version
5512
        $result = Database::query($sql);
5513
        $last_row = Database::fetch_array($result);
5514
5515
        if ($view < $last_row['id']) {
5516
            $message = '<center>'.get_lang('NoAreSeeingTheLastVersion').'<br />
5517
            '.get_lang("Version").' (
5518
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5519
                    urlencode($current_row['reflink'])
5520
                ).'&group_id='.$current_row['group_id'].'&session_id='.$current_row['session_id'].'&view='.api_htmlentities(
5521
                    $_GET['view']
5522
                ).'" title="'.get_lang('CurrentVersion').'">
5523
            '.$current_row['version'].'
5524
            </a> /
5525
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5526
                    urlencode($last_row['reflink'])
5527
                ).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'" title="'.get_lang(
5528
                    'LastVersion'
5529
                ).'">
5530
            '.$last_row['version'].'
5531
            </a>) <br />'.get_lang("ConvertToLastVersion").':
5532
            <a href="index.php?cidReq='.$_course['id'].'&action=restorepage&title='.api_htmlentities(
5533
                    urlencode($last_row['reflink'])
5534
                ).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'&view='.api_htmlentities(
5535
                    $_GET['view']
5536
                ).'">'.
5537
                get_lang("Restore").'</a></center>';
5538
            Display::addFlash(
5539
                Display::return_message($message, 'warning', false)
5540
            );
5541
        }
5542
    }
5543
5544
    /**
5545
     *  Get most linked pages
5546
     */
5547
    public function getMostLinked()
5548
    {
5549
        $tbl_wiki = $this->tbl_wiki;
5550
        $course_id = $this->course_id;
5551
        $groupfilter = $this->groupfilter;
5552
        $condition_session = $this->condition_session;
5553
        $_course = $this->courseInfo;
5554
5555
        echo '<div class="actions">'.get_lang('MostLinkedPages').'</div>';
5556
        $pages = [];
5557
        $linked = [];
5558
5559
        // Get name pages
5560
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5561
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5562
                GROUP BY reflink
5563
                ORDER BY reflink ASC';
5564
        $allpages = Database::query($sql);
5565
        while ($row = Database::fetch_array($allpages)) {
5566
            if ($row['reflink'] == 'index') {
5567
                $row['reflink'] = str_replace(
5568
                    ' ',
5569
                    '_',
5570
                    get_lang('DefaultTitle')
5571
                );
5572
            }
5573
            $pages[] = $row['reflink'];
5574
        }
5575
5576
        // Get name refs in last pages
5577
        $sql = 'SELECT *
5578
                FROM '.$tbl_wiki.' s1
5579
                WHERE s1.c_id = '.$course_id.' AND id=(
5580
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5581
                    WHERE
5582
                        s2.c_id = '.$course_id.' AND
5583
                        s1.reflink = s2.reflink AND
5584
                        '.$groupfilter.$condition_session.'
5585
                )';
5586
5587
        $allpages = Database::query($sql);
5588
5589
        while ($row = Database::fetch_array($allpages)) {
5590
            //remove self reference
5591
            $row['linksto'] = str_replace(
5592
                $row["reflink"],
5593
                " ",
5594
                trim($row["linksto"])
5595
            );
5596
            $refs = explode(" ", trim($row["linksto"]));
5597
5598
            // Find linksto into reflink. If found ->page is linked
5599
            foreach ($refs as $v) {
5600
                if (in_array($v, $pages)) {
5601
                    if (trim($v) != "") {
5602
                        $linked[] = $v;
5603
                    }
5604
                }
5605
            }
5606
        }
5607
5608
        $linked = array_unique($linked);
5609
        //make a unique list. TODO:delete this line and count how many for each page
5610
        //show table
5611
        $rows = [];
5612
        foreach ($linked as $linked_show) {
5613
            $row = [];
5614
            $row[] = '<a href="'.api_get_self(
5615
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5616
                    urlencode(str_replace('_', ' ', $linked_show))
5617
                ).'&session_id='.api_htmlentities(
5618
                    $_GET['session_id']
5619
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5620
                str_replace('_', ' ', $linked_show).'</a>';
5621
            $rows[] = $row;
5622
        }
5623
5624
        $table = new SortableTableFromArrayConfig(
5625
            $rows,
5626
            0,
5627
            10,
5628
            'LinkedPages_table',
5629
            '',
5630
            '',
5631
            'DESC'
5632
        );
5633
        $table->set_additional_parameters(
5634
            [
5635
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5636
                'action' => Security::remove_XSS($this->action),
5637
                'session_id' => intval($_GET['session_id']),
5638
                'group_id' => intval($_GET['group_id']),
5639
            ]
5640
        );
5641
        $table->set_header(0, get_lang('Title'), true);
5642
        $table->display();
5643
    }
5644
5645
    /**
5646
     * Get orphan pages
5647
     */
5648
    public function getOrphaned()
5649
    {
5650
        $tbl_wiki = $this->tbl_wiki;
5651
        $course_id = $this->course_id;
5652
        $groupfilter = $this->groupfilter;
5653
        $condition_session = $this->condition_session;
5654
        $_course = $this->courseInfo;
5655
5656
        echo '<div class="actions">'.get_lang('OrphanedPages').'</div>';
5657
5658
        $pages = [];
5659
        $orphaned = [];
5660
5661
        //get name pages
5662
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5663
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5664
                GROUP BY reflink
5665
                ORDER BY reflink ASC';
5666
        $allpages = Database::query($sql);
5667
        while ($row = Database::fetch_array($allpages)) {
5668
            $pages[] = $row['reflink'];
5669
        }
5670
5671
        //get name refs in last pages and make a unique list
5672
        $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1
5673
                WHERE s1.c_id = '.$course_id.' AND id=(
5674
                SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5675
                WHERE
5676
                    s2.c_id = '.$course_id.' AND
5677
                    s1.reflink = s2.reflink AND
5678
                    '.$groupfilter.$condition_session.'
5679
                )';
5680
        $allpages = Database::query($sql);
5681
        $array_refs_linked = [];
5682
        while ($row = Database::fetch_array($allpages)) {
5683
            $row['linksto'] = str_replace(
5684
                $row["reflink"],
5685
                " ",
5686
                trim($row["linksto"])
5687
            ); //remove self reference
5688
            $refs = explode(" ", trim($row["linksto"]));
5689
            foreach ($refs as $ref_linked) {
5690
                if ($ref_linked == str_replace(
5691
                        ' ',
5692
                        '_',
5693
                        get_lang('DefaultTitle')
5694
                    )) {
5695
                    $ref_linked = 'index';
5696
                }
5697
                $array_refs_linked[] = $ref_linked;
5698
            }
5699
        }
5700
5701
        $array_refs_linked = array_unique($array_refs_linked);
5702
5703
        //search each name of list linksto into list reflink
5704
        foreach ($pages as $v) {
5705
            if (!in_array($v, $array_refs_linked)) {
5706
                $orphaned[] = $v;
5707
            }
5708
        }
5709
        $rows = [];
5710
        foreach ($orphaned as $orphaned_show) {
5711
            // get visibility status and title
5712
            $sql = 'SELECT *
5713
                    FROM  '.$tbl_wiki.'
5714
		            WHERE
5715
		                c_id = '.$course_id.' AND
5716
		                '.$groupfilter.$condition_session.' AND
5717
		                reflink="'.Database::escape_string($orphaned_show).'"
5718
                    GROUP BY reflink';
5719
            $allpages = Database::query($sql);
5720
            while ($row = Database::fetch_array($allpages)) {
5721
                $orphaned_title = $row['title'];
5722
                $orphaned_visibility = $row['visibility'];
5723
                if ($row['assignment'] == 1) {
5724
                    $ShowAssignment = Display::return_icon(
5725
                        'wiki_assignment.png',
5726
                        '',
5727
                        '',
5728
                        ICON_SIZE_SMALL
5729
                    );
5730
                } elseif ($row['assignment'] == 2) {
5731
                    $ShowAssignment = Display::return_icon(
5732
                        'wiki_work.png',
5733
                        '',
5734
                        '',
5735
                        ICON_SIZE_SMALL
5736
                    );
5737
                } elseif ($row['assignment'] == 0) {
5738
                    $ShowAssignment = Display::return_icon(
5739
                        'px_transparent.gif'
5740
                    );
5741
                }
5742
            }
5743
5744
            if (!api_is_allowed_to_edit(false, true) || !api_is_platform_admin(
5745
                ) && $orphaned_visibility == 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $orphaned_visibility does not seem to be defined for all execution paths leading up to this point.
Loading history...
5746
                continue;
5747
            }
5748
5749
            //show table
5750
            $row = [];
5751
            $row[] = $ShowAssignment;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ShowAssignment does not seem to be defined for all execution paths leading up to this point.
Loading history...
5752
            $row[] = '<a href="'.api_get_self(
5753
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5754
                    urlencode($orphaned_show)
5755
                ).'&session_id='.api_htmlentities(
5756
                    $_GET['session_id']
5757
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5758
                api_htmlentities($orphaned_title).'</a>';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $orphaned_title does not seem to be defined for all execution paths leading up to this point.
Loading history...
5759
            $rows[] = $row;
5760
        }
5761
5762
        $table = new SortableTableFromArrayConfig(
5763
            $rows,
5764
            1,
5765
            10,
5766
            'OrphanedPages_table',
5767
            '',
5768
            '',
5769
            'DESC'
5770
        );
5771
        $table->set_additional_parameters(
5772
            [
5773
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5774
                'action' => Security::remove_XSS($this->action),
5775
                'session_id' => intval($_GET['session_id']),
5776
                'group_id' => intval($_GET['group_id']),
5777
            ]
5778
        );
5779
        $table->set_header(
5780
            0,
5781
            get_lang('Type'),
5782
            true,
5783
            ['style' => 'width:30px;']
5784
        );
5785
        $table->set_header(1, get_lang('Title'), true);
5786
        $table->display();
5787
    }
5788
5789
    /**
5790
     * Get wanted pages
5791
     */
5792
    public function getWantedPages()
5793
    {
5794
        $tbl_wiki = $this->tbl_wiki;
5795
        $course_id = $this->course_id;
5796
        $groupfilter = $this->groupfilter;
5797
        $condition_session = $this->condition_session;
5798
5799
        echo '<div class="actions">'.get_lang('WantedPages').'</div>';
5800
        $pages = [];
5801
        $wanted = [];
5802
        //get name pages
5803
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5804
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5805
                GROUP BY reflink
5806
                ORDER BY reflink ASC';
5807
        $allpages = Database::query($sql);
5808
5809
        while ($row = Database::fetch_array($allpages)) {
5810
            if ($row['reflink'] == 'index') {
5811
                $row['reflink'] = str_replace(
5812
                    ' ',
5813
                    '_',
5814
                    get_lang('DefaultTitle')
5815
                );
5816
            }
5817
            $pages[] = $row['reflink'];
5818
        }
5819
5820
        //get name refs in last pages
5821
        $sql = 'SELECT * FROM   '.$tbl_wiki.' s1
5822
                WHERE s1.c_id = '.$course_id.' AND id=(
5823
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5824
                    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.$condition_session.'
5825
                )';
5826
5827
        $allpages = Database::query($sql);
5828
5829
        while ($row = Database::fetch_array($allpages)) {
5830
            $refs = explode(" ", trim($row["linksto"]));
5831
            // Find linksto into reflink. If not found ->page is wanted
5832
            foreach ($refs as $v) {
5833
                if (!in_array($v, $pages)) {
5834
                    if (trim($v) != "") {
5835
                        $wanted[] = $v;
5836
                    }
5837
                }
5838
            }
5839
        }
5840
5841
        $wanted = array_unique($wanted); //make a unique list
5842
5843
        //show table
5844
        $rows = [];
5845
        foreach ($wanted as $wanted_show) {
5846
            $row = [];
5847
            $wanted_show = Security::remove_XSS($wanted_show);
5848
            $row[] = '<a href="'.api_get_path(
5849
                    WEB_PATH
5850
                ).'main/wiki/index.php?cidReq=&action=addnew&title='.str_replace(
5851
                    '_',
5852
                    ' ',
5853
                    $wanted_show
5854
                ).'&session_id='.api_htmlentities(
5855
                    $_GET['session_id']
5856
                ).'&group_id='.api_htmlentities(
5857
                    $_GET['group_id']
5858
                ).'" class="new_wiki_link">'.str_replace(
5859
                    '_',
5860
                    ' ',
5861
                    $wanted_show
5862
                ).'</a>'; //meter un remove xss en lugar de htmlentities
5863
            $rows[] = $row;
5864
        }
5865
5866
        $table = new SortableTableFromArrayConfig(
5867
            $rows,
5868
            0,
5869
            10,
5870
            'WantedPages_table',
5871
            '',
5872
            '',
5873
            'DESC'
5874
        );
5875
        $table->set_additional_parameters(
5876
            [
5877
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5878
                'action' => Security::remove_XSS($this->action),
5879
                'session_id' => intval($_GET['session_id']),
5880
                'group_id' => intval($_GET['group_id']),
5881
            ]
5882
        );
5883
        $table->set_header(0, get_lang('Title'), true);
5884
        $table->display();
5885
    }
5886
5887
    /**
5888
     * Most visited
5889
     */
5890
    public function getMostVisited()
5891
    {
5892
        $tbl_wiki = $this->tbl_wiki;
5893
        $course_id = $this->course_id;
5894
        $groupfilter = $this->groupfilter;
5895
        $condition_session = $this->condition_session;
5896
        $_course = $this->courseInfo;
5897
5898
        echo '<div class="actions">'.get_lang('MostVisitedPages').'</div>';
5899
5900
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin(
5901
            )) { //only by professors if page is hidden
5902
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5903
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5904
                    GROUP BY reflink';
5905
        } else {
5906
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5907
                    WHERE
5908
                        c_id = '.$course_id.' AND
5909
                        '.$groupfilter.$condition_session.' AND
5910
                        visibility=1
5911
                    GROUP BY reflink';
5912
        }
5913
5914
        $allpages = Database::query($sql);
5915
5916
        //show table
5917
        if (Database::num_rows($allpages) > 0) {
5918
            $rows = [];
5919
            while ($obj = Database::fetch_object($allpages)) {
5920
                //get type assignment icon
5921
                $ShowAssignment = '';
5922
                if ($obj->assignment == 1) {
5923
                    $ShowAssignment = Display::return_icon(
5924
                        'wiki_assignment.png',
5925
                        get_lang('AssignmentDesc'),
5926
                        '',
5927
                        ICON_SIZE_SMALL
5928
                    );
5929
                } elseif ($obj->assignment == 2) {
5930
                    $ShowAssignment = $ShowAssignment = Display::return_icon(
5931
                        'wiki_work.png',
5932
                        get_lang('AssignmentWork'),
5933
                        '',
5934
                        ICON_SIZE_SMALL
5935
                    );
5936
                } elseif ($obj->assignment == 0) {
5937
                    $ShowAssignment = Display::return_icon(
5938
                        'px_transparent.gif'
5939
                    );
5940
                }
5941
5942
                $row = [];
5943
                $row[] = $ShowAssignment;
5944
                $row[] = '<a href="'.api_get_self(
5945
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5946
                        urlencode($obj->reflink)
5947
                    ).'&session_id='.api_htmlentities(
5948
                        $_GET['session_id']
5949
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5950
                    api_htmlentities($obj->title).'</a>';
5951
                $row[] = $obj->tsum;
5952
                $rows[] = $row;
5953
            }
5954
5955
            $table = new SortableTableFromArrayConfig(
5956
                $rows,
5957
                2,
5958
                10,
5959
                'MostVisitedPages_table',
5960
                '',
5961
                '',
5962
                'DESC'
5963
            );
5964
            $table->set_additional_parameters(
5965
                [
5966
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5967
                    'action' => Security::remove_XSS($this->action),
5968
                    'session_id' => intval($_GET['session_id']),
5969
                    'group_id' => intval($_GET['group_id']),
5970
                ]
5971
            );
5972
            $table->set_header(
5973
                0,
5974
                get_lang('Type'),
5975
                true,
5976
                ['style' => 'width:30px;']
5977
            );
5978
            $table->set_header(1, get_lang('Title'), true);
5979
            $table->set_header(2, get_lang('Visits'), true);
5980
            $table->display();
5981
        }
5982
    }
5983
5984
    /**
5985
     * Get actions bar
5986
     * @return string
5987
     */
5988
    public function showActionBar()
5989
    {
5990
        $_course = $this->courseInfo;
5991
        $session_id = $this->session_id;
5992
        $groupId = $this->group_id;
5993
        $page = $this->page;
5994
        $actionsLeft = '';
5995
        $actionsLeft .= '<a href="index.php?action=showpage&title=index&cidReq='.$_course['id'].'&session_id='.$session_id.'&group_id='.$groupId.'">'.
5996
            Display::return_icon(
5997
                'home.png',
5998
                get_lang('Home'),
5999
                '',
6000
                ICON_SIZE_MEDIUM
6001
            ).'</a>';
6002
6003
        if (api_is_allowed_to_session_edit(
6004
                false,
6005
                true
6006
            ) && api_is_allowed_to_edit()) {
6007
            // menu add page
6008
            $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=addnew&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::is_active_navigation_tab() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6008
            $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=addnew&session_id='.$session_id.'&group_id='.$groupId.'"'.self::/** @scrutinizer ignore-call */ is_active_navigation_tab(
Loading history...
6009
                    'addnew'
6010
                ).'>'
6011
                .Display::return_icon(
6012
                    'add.png',
6013
                    get_lang('AddNew'),
6014
                    '',
6015
                    ICON_SIZE_MEDIUM
6016
                ).'</a>';
6017
        }
6018
6019
        $lock_unlock_addnew = null;
6020
        $protect_addnewpage = null;
6021
6022
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6023
            // page action: enable or disable the adding of new pages
6024
            if (self::check_addnewpagelock() == 0) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_addnewpagelock() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6024
            if (self::/** @scrutinizer ignore-call */ check_addnewpagelock() == 0) {
Loading history...
6025
                $protect_addnewpage = Display::return_icon(
6026
                    'off.png',
6027
                    get_lang('AddOptionProtected')
6028
                );
6029
                $lock_unlock_addnew = 'unlockaddnew';
6030
            } else {
6031
                $protect_addnewpage = Display::return_icon(
6032
                    'on.png',
6033
                    get_lang('AddOptionUnprotected')
6034
                );
6035
                $lock_unlock_addnew = 'lockaddnew';
6036
            }
6037
        }
6038
6039
        // menu find
6040
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6041
                'searchpages'
6042
            ).'>'.
6043
            Display::return_icon(
6044
                'search.png',
6045
                get_lang('SearchPages'),
6046
                '',
6047
                ICON_SIZE_MEDIUM
6048
            ).'</a></li>';
6049
        ///menu more
6050
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'&action=more&title='.api_htmlentities(
6051
                urlencode($page)
6052
            ).'"'.self::is_active_navigation_tab('more').'>'.
6053
            Display::return_icon(
6054
                'stats.png',
6055
                get_lang('Statistics'),
6056
                '',
6057
                ICON_SIZE_MEDIUM
6058
            ).'</a></li>';
6059
6060
        // menu all pages
6061
        $actionsLeft .= '<a class="btn btn-default" href="index.php?cidReq='.$_course['id'].'&action=allpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6062
                'allpages'
6063
            ).'>'.
6064
            get_lang('AllPages').'</a>';
6065
        // menu recent changes
6066
        $actionsLeft .= '<a class="btn btn-default" href="index.php?cidReq='.$_course['id'].'&action=recentchanges&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6067
                'recentchanges'
6068
            ).'>'.
6069
            get_lang('RecentChanges').'</a>';
6070
        echo Display::toolbarAction('toolbar-wiki', [$actionsLeft]);
6071
    }
6072
6073
    /**
6074
     * Showing warning
6075
     */
6076
    public function deletePageWarning()
6077
    {
6078
        $page = $this->page;
6079
        $course_id = $this->course_id;
6080
        $groupfilter = $this->groupfilter;
6081
        $condition_session = $this->condition_session;
6082
6083
        if (!$_GET['title']) {
6084
            Display::addFlash(
6085
                Display::return_message(
6086
                    get_lang('MustSelectPage'),
6087
                    'error',
6088
                    false
6089
                )
6090
            );
6091
6092
            return;
6093
        }
6094
6095
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6096
            Display::addFlash(
6097
                '<div id="wikititle">'.get_lang('DeletePageHistory').'</div>'
6098
            );
6099
            if ($page == "index") {
6100
                Display::addFlash(
6101
                    Display::return_message(
6102
                        get_lang('WarningDeleteMainPage'),
6103
                        'warning',
6104
                        false
6105
                    )
6106
                );
6107
            }
6108
            $message = get_lang('ConfirmDeletePage')."
6109
                <a href=\"index.php?".api_get_cidreq()."\">".get_lang("No")."</a>
6110
                <a href=\"".api_get_self()."?".api_get_cidreq(
6111
                )."&action=delete&title=".api_htmlentities(
6112
                    urlencode($page)
6113
                )."&delete=yes\">".
6114
                get_lang("Yes")."</a>";
6115
6116
            if (!isset($_GET['delete'])) {
6117
                Display::addFlash(
6118
                    Display::return_message($message, 'warning', false)
6119
                );
6120
            }
6121
6122
            if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
6123
                $result = self::deletePage(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::deletePage() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6123
                /** @scrutinizer ignore-call */ 
6124
                $result = self::deletePage(
Loading history...
6124
                    $page,
6125
                    $course_id,
6126
                    $groupfilter,
6127
                    $condition_session
6128
                );
6129
                if ($result) {
6130
                    Display::addFlash(
6131
                        Display::return_message(
6132
                            get_lang('WikiPageDeleted'),
6133
                            'confirmation',
6134
                            false
6135
                        )
6136
                    );
6137
                }
6138
            }
6139
        } else {
6140
            Display::addFlash(
6141
                Display::return_message(
6142
                    get_lang('OnlyAdminDeletePageWiki'),
6143
                    'normal',
6144
                    false
6145
                )
6146
            );
6147
        }
6148
    }
6149
6150
    /**
6151
     * Edit page
6152
     */
6153
    public function editPage()
6154
    {
6155
        $tbl_wiki = $this->tbl_wiki;
6156
        $tbl_wiki_conf = $this->tbl_wiki_conf;
6157
        $condition_session = $this->condition_session;
6158
        $groupfilter = $this->groupfilter;
6159
        $page = $this->page;
6160
        $course_id = $this->course_id;
6161
        $groupId = $this->group_id;
6162
        $userId = api_get_user_id();
6163
6164
        if (api_get_session_id() != 0 &&
6165
            api_is_allowed_to_session_edit(false, true) == false
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
6166
        ) {
6167
            api_not_allowed();
6168
        }
6169
6170
        $sql = 'SELECT *
6171
                FROM '.$tbl_wiki.' w INNER JOIN '.$tbl_wiki_conf.' c
6172
                ON  (w.c_id = c.c_id AND w.page_id = c.page_id)
6173
                WHERE
6174
    		        w.c_id = '.$course_id.' AND
6175
                    w.reflink= "'.Database::escape_string($page).'" AND
6176
                    w.'.$groupfilter.$condition_session.'
6177
                ORDER BY id DESC';
6178
        $result = Database::query($sql);
6179
        $row = Database::fetch_array($result);
6180
6181
        // we do not need a while loop since we are always displaying the last version
6182
        if ($row['content'] == '' && $row['title'] == '' && $page == '') {
6183
            Display::addFlash(
6184
                Display::return_message(
6185
                    get_lang('MustSelectPage'),
6186
                    'error',
6187
                    false
6188
                )
6189
            );
6190
6191
            return;
6192
        } elseif ($row['content'] == '' && $row['title'] == '' && $page == 'index') {
6193
6194
            // Table structure for better export to pdf
6195
            $default_table_for_content_Start = '<table align="center" border="0"><tr><td align="center">';
6196
            $default_table_for_content_End = '</td></tr></table>';
6197
            $content = $default_table_for_content_Start.sprintf(
6198
                    get_lang('DefaultContent'),
6199
                    api_get_path(WEB_IMG_PATH)
6200
                ).$default_table_for_content_End;
6201
            $title = get_lang('DefaultTitle');
6202
            $page_id = 0;
6203
        } else {
6204
            $content = api_html_entity_decode($row['content']);
6205
            $title = api_html_entity_decode($row['title']);
6206
            $page_id = $row['page_id'];
6207
        }
6208
6209
        // Only teachers and platform admin can edit the index page.
6210
        // Only teachers and platform admin can edit an assignment teacher.
6211
        // And users in groups
6212
6213
        if (($row['reflink'] == 'index' || $row['reflink'] == '' || $row['assignment'] == 1) &&
6214
            (!api_is_allowed_to_edit(
6215
                    false,
6216
                    true
6217
                ) && $groupId == 0) && !api_is_allowed_in_course()
6218
        ) {
6219
            Display::addFlash(
6220
                Display::return_message(
6221
                    get_lang('OnlyEditPagesCourseManager'),
6222
                    'error'
6223
                )
6224
            );
6225
        } else {
6226
            $PassEdit = false;
6227
            // Check if is a wiki group
6228
            if (!empty($groupId)) {
6229
                $groupInfo = GroupManager::get_group_properties($groupId);
6230
                //Only teacher, platform admin and group members can edit a wiki group
6231
                if (api_is_allowed_to_edit(false, true) ||
6232
                    api_is_platform_admin() ||
6233
                    GroupManager::is_user_in_group($userId, $groupInfo)
6234
                ) {
6235
                    $PassEdit = true;
6236
                } else {
6237
                    Display::addFlash(
6238
                        Display::return_message(
6239
                            get_lang('OnlyEditPagesGroupMembers')
6240
                        )
6241
                    );
6242
                }
6243
            } else {
6244
                $PassEdit = true;
6245
            }
6246
6247
            $icon_assignment = null;
6248
            // check if is a assignment
6249
            if ($row['assignment'] == 1) {
6250
                Display::addFlash(
6251
                    Display::return_message(get_lang('EditAssignmentWarning'))
6252
                );
6253
6254
                $icon_assignment = Display::return_icon(
6255
                    'wiki_assignment.png',
6256
                    get_lang('AssignmentDescExtra'),
6257
                    '',
6258
                    ICON_SIZE_SMALL
6259
                );
6260
            } elseif ($row['assignment'] == 2) {
6261
                $icon_assignment = Display::return_icon(
6262
                    'wiki_work.png',
6263
                    get_lang('AssignmentWorkExtra'),
6264
                    '',
6265
                    ICON_SIZE_SMALL
6266
                );
6267
                if (($userId == $row['user_id']) == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
6268
                    if (api_is_allowed_to_edit(
6269
                            false,
6270
                            true
6271
                        ) || api_is_platform_admin()) {
6272
                        $PassEdit = true;
6273
                    } else {
6274
                        Display::addFlash(
6275
                            Display::return_message(
6276
                                get_lang('LockByTeacher'),
6277
                                'warning'
6278
                            )
6279
                        );
6280
                        $PassEdit = false;
6281
                    }
6282
                } else {
6283
                    $PassEdit = true;
6284
                }
6285
            }
6286
6287
            if ($PassEdit) {
6288
                //show editor if edit is allowed <<<<<
6289
                if ($row['editlock'] == 1 &&
6290
                    (api_is_allowed_to_edit(false, true) == false ||
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
6291
                        api_is_platform_admin() == false)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
6292
                ) {
6293
                    Display::addFlash(
6294
                        Display::return_message(
6295
                            get_lang('PageLockedExtra')
6296
                        )
6297
                    );
6298
                } else {
6299
                    // Check tasks
6300
                    if (!empty($row['startdate_assig']) && time() <
6301
                        api_strtotime($row['startdate_assig'])
6302
                    ) {
6303
                        $message = get_lang(
6304
                                'TheTaskDoesNotBeginUntil'
6305
                            ).': '.api_get_local_time($row['startdate_assig']);
6306
6307
                        Display::addFlash(
6308
                            Display::return_message(
6309
                                $message,
6310
                                'warning'
6311
                            )
6312
                        );
6313
6314
                        if (!api_is_allowed_to_edit(false, true)) {
6315
                            $this->redirectHome();
6316
                        }
6317
                    }
6318
6319
                    if (!empty($row['enddate_assig']) &&
6320
                        time() > strtotime($row['enddate_assig']) &&
6321
                        $row['delayedsubmit'] == 0
6322
                    ) {
6323
                        $message = get_lang(
6324
                                'TheDeadlineHasBeenCompleted'
6325
                            ).': '.api_get_local_time($row['enddate_assig']);
6326
                        Display::addFlash(
6327
                            Display::return_message(
6328
                                $message,
6329
                                'warning'
6330
                            )
6331
                        );
6332
                        if (!api_is_allowed_to_edit(false, true)) {
6333
                            $this->redirectHome();
6334
                        }
6335
                    }
6336
6337
                    if (!empty($row['max_version']) && $row['version'] >= $row['max_version']) {
6338
                        $message = get_lang('HasReachedMaxiNumVersions');
6339
                        Display::addFlash(
6340
                            Display::return_message(
6341
                                $message,
6342
                                'warning'
6343
                            )
6344
                        );
6345
                        if (!api_is_allowed_to_edit(false, true)) {
6346
                            $this->redirectHome();
6347
                        }
6348
                    }
6349
6350
                    if (!empty($row['max_text']) && $row['max_text'] <= self::word_count(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::word_count() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6350
                    if (!empty($row['max_text']) && $row['max_text'] <= self::/** @scrutinizer ignore-call */ word_count(
Loading history...
6351
                            $row['content']
6352
                        )) {
6353
                        $message = get_lang('HasReachedMaxNumWords');
6354
                        Display::addFlash(
6355
                            Display::return_message(
6356
                                $message,
6357
                                'warning'
6358
                            )
6359
                        );
6360
                        if (!api_is_allowed_to_edit(false, true)) {
6361
                            $this->redirectHome();
6362
                        }
6363
                    }
6364
6365
                    if (!empty($row['task'])) {
6366
                        //previous change 0 by text
6367
                        if (!empty($row['startdate_assig'])) {
6368
                            $message_task_startdate = get_lang('No');
6369
                        } else {
6370
                            $message_task_startdate = api_get_local_time(
6371
                                $row['startdate_assig']
6372
                            );
6373
                        }
6374
6375
                        if (!empty($row['enddate_assig'])) {
6376
                            $message_task_enddate = get_lang('No');
6377
                        } else {
6378
                            $message_task_enddate = api_get_local_time(
6379
                                $row['enddate_assig']
6380
                            );
6381
                        }
6382
6383
                        if ($row['delayedsubmit'] == 0) {
6384
                            $message_task_delayedsubmit = get_lang('No');
6385
                        } else {
6386
                            $message_task_delayedsubmit = get_lang('Yes');
6387
                        }
6388
6389
                        if ($row['max_version'] == 0) {
6390
                            $message_task_max_version = get_lang('No');
6391
                        } else {
6392
                            $message_task_max_version = $row['max_version'];
6393
                        }
6394
6395
                        if ($row['max_text'] == 0) {
6396
                            $message_task_max_text = get_lang('No');
6397
                        } else {
6398
                            $message_task_max_text = $row['max_text'];
6399
                        }
6400
6401
                        // Comp message
6402
                        $message_task = '<b>'.get_lang(
6403
                                'DescriptionOfTheTask'
6404
                            ).'</b><p>'.$row['task'].'</p><hr>';
6405
                        $message_task .= '<p>'.get_lang(
6406
                                'StartDate'
6407
                            ).': '.$message_task_startdate.'</p>';
6408
                        $message_task .= '<p>'.get_lang(
6409
                                'EndDate'
6410
                            ).': '.$message_task_enddate;
6411
                        $message_task .= ' ('.get_lang(
6412
                                'AllowLaterSends'
6413
                            ).') '.$message_task_delayedsubmit.'</p>';
6414
                        $message_task .= '<p>'.get_lang(
6415
                                'OtherSettings'
6416
                            ).': '.get_lang(
6417
                                'NMaxVersion'
6418
                            ).': '.$message_task_max_version;
6419
                        $message_task .= ' '.get_lang(
6420
                                'NMaxWords'
6421
                            ).': '.$message_task_max_text;
6422
                        // Display message
6423
                        Display::addFlash(
6424
                            Display::return_message(
6425
                                $message_task
6426
                            )
6427
                        );
6428
                    }
6429
6430
                    $feedback_message = '';
6431
                    if ($row['progress'] == $row['fprogress1'] && !empty($row['fprogress1'])) {
6432
                        $feedback_message = '<b>'.get_lang(
6433
                                'Feedback'
6434
                            ).'</b><p>'.api_htmlentities(
6435
                                $row['feedback1']
6436
                            ).'</p>';
6437
                    } elseif ($row['progress'] == $row['fprogress2'] && !empty($row['fprogress2'])) {
6438
                        $feedback_message = '<b>'.get_lang(
6439
                                'Feedback'
6440
                            ).'</b><p>'.api_htmlentities(
6441
                                $row['feedback2']
6442
                            ).'</p>';
6443
                    } elseif ($row['progress'] == $row['fprogress3'] && !empty($row['fprogress3'])) {
6444
                        $feedback_message = '<b>'.get_lang(
6445
                                'Feedback'
6446
                            ).'</b><p>'.api_htmlentities(
6447
                                $row['feedback3']
6448
                            ).'</p>';
6449
                    }
6450
6451
                    if (!empty($feedback_message)) {
6452
                        Display::addFlash(
6453
                            Display::return_message(
6454
                                $feedback_message
6455
                            )
6456
                        );
6457
                    }
6458
6459
                    // Previous checking for concurrent editions
6460
                    if ($row['is_editing'] == 0) {
6461
                        Display::addFlash(
6462
                            Display::return_message(
6463
                                get_lang('WarningMaxEditingTime')
6464
                            )
6465
                        );
6466
                        $time_edit = api_get_utc_datetime();
6467
                        $sql = 'UPDATE '.$tbl_wiki.' SET
6468
                                is_editing = "'.$userId.'",
6469
                                time_edit = "'.$time_edit.'"
6470
                                WHERE c_id = '.$course_id.' AND id="'.$row['id'].'"';
6471
                        Database::query($sql);
6472
                    } elseif ($row['is_editing'] != $userId) {
6473
                        $timestamp_edit = strtotime($row['time_edit']);
6474
                        $time_editing = time() - $timestamp_edit;
6475
                        $max_edit_time = 1200; // 20 minutes
6476
                        $rest_time = $max_edit_time - $time_editing;
6477
6478
                        $userinfo = api_get_user_info($row['is_editing']);
6479
                        if ($userinfo !== false) {
6480
                            $is_being_edited = get_lang(
6481
                                    'ThisPageisBeginEditedBy'
6482
                                ).' '.UserManager::getUserProfileLink(
6483
                                    $userinfo
6484
                                ).'
6485
                            '.get_lang(
6486
                                    'ThisPageisBeginEditedTryLater'
6487
                                ).' '.date("i", $rest_time).' '.get_lang(
6488
                                    'MinMinutes'
6489
                                ).'';
6490
                        }
6491
6492
                        Display::addFlash(
6493
                            Display::return_message(
6494
                                $is_being_edited,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $is_being_edited does not seem to be defined for all execution paths leading up to this point.
Loading history...
6495
                                'normal',
6496
                                false
6497
                            )
6498
                        );
6499
6500
                        $this->redirectHome();
6501
                    }
6502
6503
                    // Form.
6504
                    $url = api_get_self().'?action=edit&title='.urlencode(
6505
                            $page
6506
                        ).'&session_id='.api_get_session_id(
6507
                        ).'&group_id='.api_get_group_id().'&'.api_get_cidreq();
6508
                    $form = new FormValidator('wiki', 'post', $url);
6509
                    $form->addElement(
6510
                        'header',
6511
                        $icon_assignment.str_repeat(
6512
                            '&nbsp;',
6513
                            3
6514
                        ).api_htmlentities($title)
6515
                    );
6516
                    self::setForm($form, $row);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::setForm() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6516
                    self::/** @scrutinizer ignore-call */ 
6517
                          setForm($form, $row);
Loading history...
6517
                    $form->addElement('hidden', 'title');
6518
                    $form->addButtonSave(get_lang('Save'), 'SaveWikiChange');
6519
                    $row['title'] = $title;
6520
                    $row['page_id'] = $page_id;
6521
                    $row['reflink'] = $page;
6522
                    $row['content'] = $content;
6523
6524
                    $form->setDefaults($row);
6525
                    $form->display();
6526
6527
                    // Saving a change
6528
                    if ($form->validate()) {
6529
                        $versionFromSession = Session::read('_version');
6530
                        if (empty($_POST['title'])) {
6531
                            Display::addFlash(
6532
                                Display::return_message(
6533
                                    get_lang("NoWikiPageTitle"),
6534
                                    'error'
6535
                                )
6536
                            );
6537
                        } elseif (!self::double_post($_POST['wpost_id'])) {
0 ignored issues
show
Unused Code introduced by
This elseif statement is empty, and could be removed.

This check looks for the bodies of elseif statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These elseif bodies can be removed. If you have an empty elseif but statements in the else branch, consider inverting the condition.

Loading history...
Bug Best Practice introduced by
The method Wiki::double_post() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6537
                        } elseif (!self::/** @scrutinizer ignore-call */ double_post($_POST['wpost_id'])) {
Loading history...
6538
                            //double post
6539
                        } elseif ($_POST['version'] != '' && $versionFromSession != 0 && $_POST['version'] != $versionFromSession) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $versionFromSession of type null|mixed to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
6540
                            //prevent concurrent users and double version
6541
                            Display::addFlash(
6542
                                Display::return_message(
6543
                                    get_lang("EditedByAnotherUser"),
6544
                                    'error'
6545
                                )
6546
                            );
6547
                        } else {
6548
                            $returnMessage = self::save_wiki(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::save_wiki() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6548
                            /** @scrutinizer ignore-call */ 
6549
                            $returnMessage = self::save_wiki(
Loading history...
6549
                                $form->exportValues()
6550
                            );
6551
                            Display::addFlash(
6552
                                Display::return_message(
6553
                                    $returnMessage,
6554
                                    'confirmation'
6555
                                )
6556
                            );
6557
                        }
6558
                        $wikiData = self::getWikiData();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getWikiData() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6558
                        /** @scrutinizer ignore-call */ 
6559
                        $wikiData = self::getWikiData();
Loading history...
6559
                        $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq(
6560
                            );
6561
                        header('Location: '.$redirectUrl);
6562
                        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...
6563
                    }
6564
                }
6565
            }
6566
        }
6567
    }
6568
6569
    /**
6570
     * Get history
6571
     */
6572
    public function getHistory()
6573
    {
6574
        $tbl_wiki = $this->tbl_wiki;
6575
        $condition_session = $this->condition_session;
6576
        $groupfilter = $this->groupfilter;
6577
        $page = $this->page;
6578
        $course_id = $this->course_id;
6579
        $session_id = $this->session_id;
6580
        $userId = api_get_user_id();
6581
6582
        if (!$_GET['title']) {
6583
            Display::addFlash(
6584
                Display::return_message(
6585
                    get_lang("MustSelectPage"),
6586
                    'error',
6587
                    false
6588
                )
6589
            );
6590
6591
            return;
6592
        }
6593
6594
        /* First, see the property visibility that is at the last register and
6595
        therefore we should select descending order.
6596
        But to give ownership to each record,
6597
        this is no longer necessary except for the title. TODO: check this*/
6598
6599
        $sql = 'SELECT * FROM '.$tbl_wiki.'
6600
                WHERE
6601
                    c_id = '.$course_id.' AND
6602
                    reflink="'.Database::escape_string($page).'" AND
6603
                    '.$groupfilter.$condition_session.'
6604
                ORDER BY id DESC';
6605
        $result = Database::query($sql);
6606
6607
        $KeyVisibility = null;
6608
        $KeyAssignment = null;
6609
        $KeyTitle = null;
6610
        $KeyUserId = null;
6611
        while ($row = Database::fetch_array($result)) {
6612
            $KeyVisibility = $row['visibility'];
6613
            $KeyAssignment = $row['assignment'];
6614
            $KeyTitle = $row['title'];
6615
            $KeyUserId = $row['user_id'];
6616
        }
6617
        $icon_assignment = null;
6618
        if ($KeyAssignment == 1) {
6619
            $icon_assignment = Display::return_icon(
6620
                'wiki_assignment.png',
6621
                get_lang('AssignmentDescExtra'),
6622
                '',
6623
                ICON_SIZE_SMALL
6624
            );
6625
        } elseif ($KeyAssignment == 2) {
6626
            $icon_assignment = Display::return_icon(
6627
                'wiki_work.png',
6628
                get_lang('AssignmentWorkExtra'),
6629
                '',
6630
                ICON_SIZE_SMALL
6631
            );
6632
        }
6633
6634
        // Second, show
6635
        //if the page is hidden and is a job only sees its author and professor
6636
        if ($KeyVisibility == 1 ||
6637
            api_is_allowed_to_edit(false, true) ||
6638
            api_is_platform_admin() ||
6639
            (
6640
                $KeyAssignment == 2 && $KeyVisibility == 0 &&
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $KeyVisibility of type null|mixed to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
6641
                ($userId == $KeyUserId)
6642
            )
6643
        ) {
6644
            // We show the complete history
6645
            if (!isset($_POST['HistoryDifferences']) &&
6646
                !isset($_POST['HistoryDifferences2'])
6647
            ) {
6648
                $sql = 'SELECT * FROM '.$tbl_wiki.'
6649
                        WHERE
6650
                            c_id = '.$course_id.' AND
6651
                            reflink="'.Database::escape_string($page).'" AND
6652
                            '.$groupfilter.$condition_session.'
6653
                        ORDER BY id DESC';
6654
                $result = Database::query($sql);
6655
                $title = $_GET['title'];
6656
                $group_id = api_get_group_id();
6657
6658
                echo '<div id="wikititle">';
6659
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities(
6660
                        $KeyTitle
6661
                    );
6662
                echo '</div>';
6663
6664
                echo '<form id="differences" method="POST" action="index.php?'.api_get_cidreq(
6665
                    ).'&action=history&title='.api_htmlentities(
6666
                        urlencode($title)
6667
                    ).'&session_id='.api_htmlentities(
6668
                        $session_id
6669
                    ).'&group_id='.api_htmlentities($group_id).'">';
6670
6671
                echo '<ul style="list-style-type: none;">';
6672
                echo '<br/>';
6673
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.
6674
                    get_lang('ShowDifferences').' '.get_lang(
6675
                        'LinesDiff'
6676
                    ).'</button>';
6677
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.
6678
                    get_lang('ShowDifferences').' '.get_lang(
6679
                        'WordsDiff'
6680
                    ).'</button>';
6681
                echo '<br/><br/>';
6682
6683
                $counter = 0;
6684
                $total_versions = Database::num_rows($result);
6685
6686
                while ($row = Database::fetch_array($result)) {
6687
                    $userinfo = api_get_user_info($row['user_id']);
6688
                    $username = api_htmlentities(
6689
                        sprintf(get_lang('LoginX'), $userinfo['username']),
6690
                        ENT_QUOTES
6691
                    );
6692
6693
                    echo '<li style="margin-bottom: 5px;">';
6694
                    ($counter == 0) ? $oldstyle = 'style="visibility: hidden;"' : $oldstyle = '';
6695
                    ($counter == 0) ? $newchecked = ' checked' : $newchecked = '';
6696
                    ($counter == $total_versions - 1) ? $newstyle = 'style="visibility: hidden;"' : $newstyle = '';
6697
                    ($counter == 1) ? $oldchecked = ' checked' : $oldchecked = '';
6698
                    echo '<input name="old" value="'.$row['id'].'" type="radio" '.$oldstyle.' '.$oldchecked.'/> ';
6699
                    echo '<input name="new" value="'.$row['id'].'" type="radio" '.$newstyle.' '.$newchecked.'/> ';
6700
                    echo '<a href="'.api_get_self(
6701
                        ).'?action=showpage&title='.api_htmlentities(
6702
                            urlencode($page)
6703
                        ).'&view='.$row['id'].'">';
6704
                    echo '<a href="'.api_get_self().'?'.api_get_cidreq(
6705
                        ).'&action=showpage&title='.api_htmlentities(
6706
                            urlencode($page)
6707
                        ).'&view='.$row['id'].'">';
6708
                    echo api_get_local_time(
6709
                        $row['dtime']
6710
                    );
6711
                    echo '</a>';
6712
                    echo ' ('.get_lang('Version').' '.$row['version'].')';
6713
                    echo ' '.get_lang('By').' ';
6714
                    if ($userinfo !== false) {
6715
                        echo UserManager::getUserProfileLink($userinfo);
6716
                    } else {
6717
                        echo get_lang('Anonymous').' ('.api_htmlentities(
6718
                                $row['user_ip']
6719
                            ).')';
6720
                    }
6721
                    echo ' ( '.get_lang('Progress').': '.api_htmlentities(
6722
                            $row['progress']
6723
                        ).'%, ';
6724
                    $comment = $row['comment'];
6725
                    if (!empty($comment)) {
6726
                        $comment = api_substr($comment, 0, 100);
6727
                        if ($comment !== false) {
6728
                            $comment = api_htmlentities($comment);
6729
                            echo get_lang('Comments').': '.$comment;
6730
                            if (api_strlen($row['comment']) > 100) {
6731
                                echo '... ';
6732
                            }
6733
                        }
6734
                    } else {
6735
                        echo get_lang('Comments').':  ---';
6736
                    }
6737
                    echo ' ) </li>';
6738
                    $counter++;
6739
                } //end while
6740
6741
                echo '<br/>';
6742
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.get_lang(
6743
                        'ShowDifferences'
6744
                    ).' '.get_lang('LinesDiff').'</button>';
6745
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.get_lang(
6746
                        'ShowDifferences'
6747
                    ).' '.get_lang('WordsDiff').'</button>';
6748
                echo '</ul></form>';
6749
            } else { // We show the differences between two versions
6750
                $version_old = [];
6751
                if (isset($_POST['old'])) {
6752
                    $sql_old = "SELECT * FROM $tbl_wiki
6753
                                WHERE c_id = $course_id AND id='".Database::escape_string(
6754
                            $_POST['old']
6755
                        )."'";
6756
                    $result_old = Database::query($sql_old);
6757
                    $version_old = Database::fetch_array($result_old);
6758
                }
6759
6760
                $sql_new = "SELECT * FROM $tbl_wiki
6761
                            WHERE 
6762
                              c_id = $course_id AND 
6763
                              id = '".Database::escape_string($_POST['new'])."'";
6764
                $result_new = Database::query($sql_new);
6765
                $version_new = Database::fetch_array($result_new);
6766
                $oldTime = isset($version_old['dtime']) ? api_get_local_time($version_old['dtime']) : null;
6767
                $oldContent = isset($version_old['content']) ? $version_old['content'] : null;
6768
6769
                if (isset($_POST['HistoryDifferences'])) {
6770
                    include 'diff.inc.php';
6771
                    //title
6772
                    echo '<div id="wikititle">'.api_htmlentities(
6773
                            $version_new['title']
6774
                        ).'
6775
                            <font size="-2"><i>('.get_lang('DifferencesNew').'</i>
6776
                            <font style="background-color:#aaaaaa">'.api_get_local_time($version_new['dtime']).'</font>
6777
                            <i>'.get_lang('DifferencesOld').'</i>
6778
                            <font style="background-color:#aaaaaa">'.$oldTime.'</font>
6779
                ) '.get_lang('Legend').':  <span class="diffAdded" >'.get_lang(
6780
                            'WikiDiffAddedLine'
6781
                        ).'</span>
6782
                <span class="diffDeleted" >'.get_lang(
6783
                            'WikiDiffDeletedLine'
6784
                        ).'</span> <span class="diffMoved">'.get_lang(
6785
                            'WikiDiffMovedLine'
6786
                        ).'</span></font>
6787
                </div>';
6788
                }
6789
                if (isset($_POST['HistoryDifferences2'])) {
6790
                    //title
6791
                    echo '<div id="wikititle">'.api_htmlentities(
6792
                            $version_new['title']
6793
                        ).'
6794
                        <font size="-2"><i>('.get_lang(
6795
                            'DifferencesNew'
6796
                        ).'</i> <font style="background-color:#aaaaaa">'.api_get_local_time($version_new['dtime']).'</font>
6797
                        <i>'.get_lang(
6798
                            'DifferencesOld'
6799
                        ).'</i> <font style="background-color:#aaaaaa">'.$oldTime.'</font>)
6800
                        '.get_lang(
6801
                            'Legend'
6802
                        ).':  <span class="diffAddedTex" >'.get_lang(
6803
                            'WikiDiffAddedTex'
6804
                        ).'</span>
6805
                        <span class="diffDeletedTex" >'.get_lang(
6806
                            'WikiDiffDeletedTex'
6807
                        ).'</span></font></div>';
6808
                }
6809
6810
6811
                if (isset($_POST['HistoryDifferences'])) {
6812
                    echo '<table>'.diff(
6813
                            $oldContent,
6814
                            $version_new['content'],
6815
                            true,
6816
                            'format_table_line'
6817
                        ).'</table>'; // format_line mode is better for words
6818
                    echo '<br />';
6819
                    echo '<strong>'.get_lang(
6820
                            'Legend'
6821
                        ).'</strong><div class="diff">'."\n";
6822
                    echo '<table><tr>';
6823
                    echo '<td>';
6824
                    echo '</td><td>';
6825
                    echo '<span class="diffEqual" >'.get_lang(
6826
                            'WikiDiffUnchangedLine'
6827
                        ).'</span><br />';
6828
                    echo '<span class="diffAdded" >'.get_lang(
6829
                            'WikiDiffAddedLine'
6830
                        ).'</span><br />';
6831
                    echo '<span class="diffDeleted" >'.get_lang(
6832
                            'WikiDiffDeletedLine'
6833
                        ).'</span><br />';
6834
                    echo '<span class="diffMoved" >'.get_lang(
6835
                            'WikiDiffMovedLine'
6836
                        ).'</span><br />';
6837
                    echo '</td>';
6838
                    echo '</tr></table>';
6839
                }
6840
6841
                if (isset($_POST['HistoryDifferences2'])) {
6842
                    $lines1 = [strip_tags($oldContent)]; //without <> tags
6843
                    $lines2 = [
6844
                        strip_tags(
6845
                            $version_new['content']
6846
                        )
6847
                    ]; //without <> tags
6848
                    $diff = new Text_Diff($lines1, $lines2);
6849
                    $renderer = new Text_Diff_Renderer_inline();
6850
                    echo '<style>del{background:#fcc}ins{background:#cfc}</style>'.$renderer->render(
6851
                            $diff
6852
                        ); // Code inline
6853
                    echo '<br />';
6854
                    echo '<strong>'.get_lang(
6855
                            'Legend'
6856
                        ).'</strong><div class="diff">'."\n";
6857
                    echo '<table><tr>';
6858
                    echo '<td>';
6859
                    echo '</td><td>';
6860
                    echo '<span class="diffAddedTex" >'.get_lang(
6861
                            'WikiDiffAddedTex'
6862
                        ).'</span><br />';
6863
                    echo '<span class="diffDeletedTex" >'.get_lang(
6864
                            'WikiDiffDeletedTex'
6865
                        ).'</span><br />';
6866
                    echo '</td>';
6867
                    echo '</tr></table>';
6868
                }
6869
            }
6870
        }
6871
    }
6872
6873
    /**
6874
     * Get stat tables
6875
     */
6876
    public function getStatsTable()
6877
    {
6878
        $_course = $this->courseInfo;
6879
        $session_id = $this->session_id;
6880
        $groupId = $this->group_id;
6881
6882
        echo '<div class="actions">'.get_lang('More').'</div>';
6883
        echo '<table border="0">';
6884
        echo '  <tr>';
6885
        echo '    <td>';
6886
        echo '      <ul>';
6887
        //Submenu Most active users
6888
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mactiveusers&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6889
                'MostActiveUsers'
6890
            ).'</a></li>';
6891
        //Submenu Most visited pages
6892
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mvisited&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6893
                'MostVisitedPages'
6894
            ).'</a></li>';
6895
        //Submenu Most changed pages
6896
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mostchanged&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6897
                'MostChangedPages'
6898
            ).'</a></li>';
6899
        echo '      </ul>';
6900
        echo '    </td>';
6901
        echo '    <td>';
6902
        echo '      <ul>';
6903
        // Submenu Orphaned pages
6904
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=orphaned&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6905
                'OrphanedPages'
6906
            ).'</a></li>';
6907
        // Submenu Wanted pages
6908
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=wanted&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6909
                'WantedPages'
6910
            ).'</a></li>';
6911
        // Submenu Most linked pages
6912
        echo '<li><a href="index.php?cidReq='.$_course['code'].'&action=mostlinked&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6913
                'MostLinkedPages'
6914
            ).'</a></li>';
6915
        echo '</ul>';
6916
        echo '</td>';
6917
        echo '<td style="vertical-align:top">';
6918
        echo '<ul>';
6919
        // Submenu Statistics
6920
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6921
            echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=statistics&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6922
                    'Statistics'
6923
                ).'</a></li>';
6924
        }
6925
        echo '      </ul>';
6926
        echo '    </td>';
6927
        echo '  </tr>';
6928
        echo '</table>';
6929
    }
6930
6931
    /**
6932
     * Kind of controller
6933
     * @param string $action
6934
     */
6935
    public function handleAction($action)
6936
    {
6937
        $page = $this->page;
6938
        switch ($action) {
6939
            case 'export_to_pdf':
6940
                if (isset($_GET['wiki_id'])) {
6941
                    self::export_to_pdf($_GET['wiki_id'], api_get_course_id());
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::export_to_pdf() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6941
                    self::/** @scrutinizer ignore-call */ 
6942
                          export_to_pdf($_GET['wiki_id'], api_get_course_id());
Loading history...
6942
                    break;
6943
                }
6944
                break;
6945
            case 'export2doc':
6946
                if (isset($_GET['wiki_id'])) {
6947
                    $export2doc = self::export2doc($_GET['wiki_id']);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::export2doc() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6947
                    /** @scrutinizer ignore-call */ 
6948
                    $export2doc = self::export2doc($_GET['wiki_id']);
Loading history...
6948
                    if ($export2doc) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $export2doc of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
6949
                        Display::addFlash(
6950
                            Display::return_message(
6951
                                get_lang('ThePageHasBeenExportedToDocArea'),
6952
                                'confirmation',
6953
                                false
6954
                            )
6955
                        );
6956
                    }
6957
                }
6958
                break;
6959
            case 'restorepage':
6960
                self::restorePage();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::restorePage() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6960
                self::/** @scrutinizer ignore-call */ 
6961
                      restorePage();
Loading history...
6961
                break;
6962
            case 'more':
6963
                self::getStatsTable();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getStatsTable() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6963
                self::/** @scrutinizer ignore-call */ 
6964
                      getStatsTable();
Loading history...
6964
                break;
6965
            case 'statistics':
6966
                self::getStats();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getStats() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6966
                self::/** @scrutinizer ignore-call */ 
6967
                      getStats();
Loading history...
6967
                break;
6968
            case 'mactiveusers':
6969
                self::getActiveUsers($action);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getActiveUsers() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6969
                self::/** @scrutinizer ignore-call */ 
6970
                      getActiveUsers($action);
Loading history...
6970
                break;
6971
            case 'usercontrib':
6972
                self::getUserContributions($_GET['user_id'], $action);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getUserContributions() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6972
                self::/** @scrutinizer ignore-call */ 
6973
                      getUserContributions($_GET['user_id'], $action);
Loading history...
6973
                break;
6974
            case 'mostchanged':
6975
                $this->getMostChangedPages($action);
6976
                break;
6977
            case 'mvisited':
6978
                self::getMostVisited();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getMostVisited() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6978
                self::/** @scrutinizer ignore-call */ 
6979
                      getMostVisited();
Loading history...
6979
                break;
6980
            case 'wanted':
6981
                $this->getWantedPages();
6982
                break;
6983
            case 'orphaned':
6984
                self::getOrphaned();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getOrphaned() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6984
                self::/** @scrutinizer ignore-call */ 
6985
                      getOrphaned();
Loading history...
6985
                break;
6986
            case 'mostlinked':
6987
                self::getMostLinked();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getMostLinked() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6987
                self::/** @scrutinizer ignore-call */ 
6988
                      getMostLinked();
Loading history...
6988
                break;
6989
            case 'delete':
6990
                self::deletePageWarning($page);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::deletePageWarning() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

6990
                self::/** @scrutinizer ignore-call */ 
6991
                      deletePageWarning($page);
Loading history...
6991
                break;
6992
            case 'deletewiki':
6993
                $title = '<div class="actions">'.get_lang(
6994
                        'DeleteWiki'
6995
                    ).'</div>';
6996
                if (api_is_allowed_to_edit(
6997
                        false,
6998
                        true
6999
                    ) || api_is_platform_admin()) {
7000
                    $message = get_lang('ConfirmDeleteWiki');
7001
                    $message .= '<p>
7002
                        <a href="index.php?'.api_get_cidreq().'">'.get_lang(
7003
                            'No'
7004
                        ).'</a>
7005
                        &nbsp;&nbsp;|&nbsp;&nbsp;
7006
                        <a href="'.api_get_self().'?'.api_get_cidreq(
7007
                        ).'&action=deletewiki&delete=yes">'.
7008
                        get_lang('Yes').'</a>
7009
                    </p>';
7010
7011
                    if (!isset($_GET['delete'])) {
7012
                        Display::addFlash(
7013
                            $title.Display::return_message(
7014
                                $message,
7015
                                'warning',
7016
                                false
7017
                            )
7018
                        );
7019
                    }
7020
                } else {
7021
                    Display::addFlash(
7022
                        Display::return_message(
7023
                            get_lang("OnlyAdminDeleteWiki"),
7024
                            'normal',
7025
                            false
7026
                        )
7027
                    );
7028
                }
7029
7030
                if (api_is_allowed_to_edit(
7031
                        false,
7032
                        true
7033
                    ) || api_is_platform_admin()) {
7034
                    if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
7035
                        $return_message = self::delete_wiki();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::delete_wiki() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7035
                        /** @scrutinizer ignore-call */ 
7036
                        $return_message = self::delete_wiki();
Loading history...
7036
                        Display::addFlash(
7037
                            Display::return_message(
7038
                                $return_message,
7039
                                'confirmation',
7040
                                false
7041
                            )
7042
                        );
7043
                        $this->redirectHome();
7044
                    }
7045
                }
7046
                break;
7047
            case 'searchpages':
7048
                self::getSearchPages($action);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getSearchPages() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7048
                self::/** @scrutinizer ignore-call */ 
7049
                      getSearchPages($action);
Loading history...
7049
                break;
7050
            case 'links':
7051
                self::getLinks($page);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getLinks() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7051
                self::/** @scrutinizer ignore-call */ 
7052
                      getLinks($page);
Loading history...
7052
                break;
7053
            case 'addnew':
7054
                if (api_get_session_id() != 0 && api_is_allowed_to_session_edit(
7055
                        false,
7056
                        true
7057
                    ) == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
7058
                    api_not_allowed();
7059
                }
7060
                $groupInfo = GroupManager::get_group_properties(
7061
                    api_get_group_id()
7062
                );
7063
                echo '<div class="actions">'.get_lang('AddNew').'</div>';
7064
                echo '<br/>';
7065
                //first, check if page index was created. chektitle=false
7066
                if (self::checktitle('index')) {
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::checktitle() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7066
                if (self::/** @scrutinizer ignore-call */ checktitle('index')) {
Loading history...
7067
                    if (api_is_allowed_to_edit(false, true) ||
7068
                        api_is_platform_admin() ||
7069
                        GroupManager::is_user_in_group(
7070
                            api_get_user_id(),
7071
                            $groupInfo
7072
                        ) ||
7073
                        api_is_allowed_in_course()
7074
                    ) {
7075
                        Display::addFlash(
7076
                            Display::return_message(
7077
                                get_lang('GoAndEditMainPage'),
7078
                                'normal',
7079
                                false
7080
                            )
7081
                        );
7082
                    } else {
7083
                        Display::addFlash(
7084
                            Display::return_message(
7085
                                get_lang('WikiStandBy'),
7086
                                'normal',
7087
                                false
7088
                            )
7089
                        );
7090
                    }
7091
                } elseif (self::check_addnewpagelock(
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::check_addnewpagelock() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7091
                } elseif (self::/** @scrutinizer ignore-call */ check_addnewpagelock(
Loading history...
7092
                    ) == 0 && (api_is_allowed_to_edit(
7093
                            false,
7094
                            true
7095
                        ) == false || api_is_platform_admin() == false)) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
7096
                    Display::addFlash(
7097
                        Display::return_message(
7098
                            get_lang('AddPagesLocked'),
7099
                            'error',
7100
                            false
7101
                        )
7102
                    );
7103
                } else {
7104
                    $groupInfo = GroupManager::get_group_properties(
7105
                        api_get_group_id()
7106
                    );
7107
                    if (api_is_allowed_to_edit(false, true) ||
7108
                        api_is_platform_admin() ||
7109
                        GroupManager::is_user_in_group(
7110
                            api_get_user_id(),
7111
                            $groupInfo
7112
                        ) ||
7113
                        $_GET['group_id'] == 0
7114
                    ) {
7115
                        self::display_new_wiki_form();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::display_new_wiki_form() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7115
                        self::/** @scrutinizer ignore-call */ 
7116
                              display_new_wiki_form();
Loading history...
7116
                    } else {
7117
                        Display::addFlash(
7118
                            Display::return_message(
7119
                                get_lang('OnlyAddPagesGroupMembers'),
7120
                                'normal',
7121
                                false
7122
                            )
7123
                        );
7124
                    }
7125
                }
7126
                break;
7127
            case 'show':
7128
                self::display_wiki_entry($page);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::display_wiki_entry() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7128
                self::/** @scrutinizer ignore-call */ 
7129
                      display_wiki_entry($page);
Loading history...
7129
                break;
7130
            case 'showpage':
7131
                self::display_wiki_entry($page);
7132
                break;
7133
            case 'edit':
7134
                self::editPage();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::editPage() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7134
                self::/** @scrutinizer ignore-call */ 
7135
                      editPage();
Loading history...
7135
                break;
7136
            case 'history':
7137
                self::getHistory();
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getHistory() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7137
                self::/** @scrutinizer ignore-call */ 
7138
                      getHistory();
Loading history...
7138
                break;
7139
            case 'recentchanges':
7140
                self::recentChanges($page, $action);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::recentChanges() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7140
                self::/** @scrutinizer ignore-call */ 
7141
                      recentChanges($page, $action);
Loading history...
7141
                break;
7142
            case 'allpages':
7143
                self::allPages($action);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::allPages() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7143
                self::/** @scrutinizer ignore-call */ 
7144
                      allPages($action);
Loading history...
7144
                break;
7145
            case 'discuss':
7146
                self::getDiscuss($page);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getDiscuss() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7146
                self::/** @scrutinizer ignore-call */ 
7147
                      getDiscuss($page);
Loading history...
7147
                break;
7148
            case 'export_to_doc_file':
7149
                self::exportTo($_GET['id'], 'odt');
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::exportTo() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7149
                self::/** @scrutinizer ignore-call */ 
7150
                      exportTo($_GET['id'], 'odt');
Loading history...
7150
                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...
7151
                break;
7152
        }
7153
    }
7154
7155
    /**
7156
     * Redirect to home
7157
     */
7158
    public function redirectHome()
7159
    {
7160
        $redirectUrl = $this->url.'&action=showpage&title=index';
7161
        header('Location: '.$redirectUrl.'&'.api_get_cidreq());
7162
        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...
7163
    }
7164
7165
    /**
7166
     * Export wiki content in a ODF
7167
     * @param int $id
7168
     * @param string int
7169
     * @return bool
7170
     */
7171
    public function exportTo($id, $format = 'doc')
7172
    {
7173
        $data = self::getWikiDataFromDb($id);
0 ignored issues
show
Bug Best Practice introduced by
The method Wiki::getWikiDataFromDb() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

7173
        /** @scrutinizer ignore-call */ 
7174
        $data = self::getWikiDataFromDb($id);
Loading history...
7174
7175
        if (isset($data['content']) && !empty($data['content'])) {
7176
            Export::htmlToOdt($data['content'], $data['reflink'], $format);
7177
        }
7178
7179
        return false;
7180
    }
7181
}
7182