Completed
Push — master ( 9b8b24...6e1754 )
by Julito
58:58
created

Wiki::deletePageWarning()   C

Complexity

Conditions 9
Paths 14

Size

Total Lines 69
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 48
nc 14
nop 0
dl 0
loc 69
rs 6.2192
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/* 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 = array();
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 = array();
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 = array(
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 = array();
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 = array())
770
    {
771
        $toolBar = api_is_allowed_to_edit(null, true)
772
            ? array(
773
                'ToolbarSet' => 'Wiki',
774
                'Width' => '100%',
775
                'Height' => '400'
776
            )
777
            : array(
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 = array('', 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
                array(
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
                array('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
                array('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
1194
                } else {
1195
                    $visibility_page = Display::return_icon(
1196
                        'invisible.png',
1197
                        get_lang('HidePageExtra'),
1198
                        '',
1199
                        ICON_SIZE_MEDIUM
1200
                    );
1201
                    $lock_unlock_visibility = 'visible';
1202
                }
1203
            }
1204
1205
            if ($row['id']) {
1206
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_visibility.'&title='.api_htmlentities(urlencode($page)).'">'.
1207
                    $visibility_page.'</a>';
1208
            }
1209
1210
            //page action: notification
1211
            if (api_is_allowed_to_session_edit()) {
1212
                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

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

1355
            if (self::/** @scrutinizer ignore-call */ wiki_exist($title)) {
Loading history...
1356
                $pageTitle = $icon_assignment.'&nbsp;'.
1357
                    $icon_task.'&nbsp;'.api_htmlentities($title);
1358
            } else {
1359
                $pageTitle = api_htmlentities($title);
1360
            }
1361
1362
            $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

1362
            /** @scrutinizer ignore-call */ 
1363
            $pageWiki = self::make_wiki_link_clickable(
Loading history...
1363
                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

1363
                self::/** @scrutinizer ignore-call */ 
1364
                      detect_external_link(
Loading history...
1364
                    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

1364
                    self::/** @scrutinizer ignore-call */ 
1365
                          detect_anchor_link(
Loading history...
1365
                        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

1365
                        self::/** @scrutinizer ignore-call */ 
1366
                              detect_mail_link(
Loading history...
1366
                            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

1366
                            self::/** @scrutinizer ignore-call */ 
1367
                                  detect_ftp_link(
Loading history...
1367
                                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

1367
                                self::/** @scrutinizer ignore-call */ 
1368
                                      detect_irc_link(
Loading history...
1368
                                    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

1368
                                    self::/** @scrutinizer ignore-call */ 
1369
                                          detect_news_link($content)
Loading history...
1369
                                )
1370
                            )
1371
                        )
1372
                    )
1373
                )
1374
            );
1375
1376
            $footerWiki =
1377
                get_lang('Progress').': '.($row['progress'] * 10).'%&nbsp;&nbsp;&nbsp;'.
1378
                get_lang('Rating').': '.$row['score'].'&nbsp;&nbsp;&nbsp;'.
1379
                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

1379
                get_lang('Words').': '.self::/** @scrutinizer ignore-call */ word_count($content);
Loading history...
1380
            // wikicontent require to print wiki document
1381
            echo '<div id="wikicontent">'.Display::panel($pageWiki, $pageTitle, $footerWiki).'</div>';
1382
        } //end filter visibility
1383
    }
1384
1385
    /**
1386
     * This function counted the words in a document. Thanks Adeel Khan
1387
     * @param   string  Document's text
1388
     * @return  int     Number of words
1389
     */
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...
1390
    public function word_count($document)
1391
    {
1392
        $search = array(
1393
            '@<script[^>]*?>.*?</script>@si',
1394
            '@<style[^>]*?>.*?</style>@siU',
1395
            '@<div id="player.[^>]*?>.*?</div>@',
1396
            '@<![\s\S]*?--[ \t\n\r]*>@'
1397
        );
1398
1399
        $document = preg_replace($search, '', $document);
1400
1401
        # strip all html tags
1402
        $wc = strip_tags($document);
1403
        $wc = html_entity_decode(
1404
            $wc,
1405
            ENT_NOQUOTES,
1406
            'UTF-8'
1407
        ); // TODO:test also old html_entity_decode(utf8_encode($wc))
1408
1409
        # remove 'words' that don't consist of alphanumerical characters or punctuation. And fix accents and some letters
1410
        $pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@|á|é|í|ó|ú|à|è|ì|ò|ù|ä|ë|ï|ö|ü|Á|É|Í|Ó|Ú|À|È|Ò|Ù|Ä|Ë|Ï|Ö|Ü|â|ê|î|ô|û|Â|Ê|Î|Ô|Û|ñ|Ñ|ç|Ç)]+#";
1411
        $wc = trim(preg_replace($pattern, " ", $wc));
1412
1413
        # remove one-letter 'words' that consist only of punctuation
1414
        $wc = trim(
1415
            preg_replace(
1416
                "#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#",
1417
                " ",
1418
                $wc
1419
            )
1420
        );
1421
1422
        # remove superfluous whitespace
1423
        $wc = preg_replace("/\s\s+/", " ", $wc);
1424
1425
        # split string into an array of words
1426
        $wc = explode(" ", $wc);
1427
1428
        # remove empty elements
1429
        $wc = array_filter($wc);
1430
1431
        # return the number of words
1432
        return count($wc);
1433
    }
1434
1435
    /**
1436
     * This function checks if wiki title exist
1437
     */
1438
    public function wiki_exist($title)
1439
    {
1440
        $tbl_wiki = $this->tbl_wiki;
1441
        $groupfilter = $this->groupfilter;
1442
        $condition_session = $this->condition_session;
1443
        $course_id = api_get_course_int_id();
1444
1445
        $sql = 'SELECT id FROM '.$tbl_wiki.'
1446
              WHERE
1447
                c_id = '.$course_id.' AND
1448
                title="'.Database::escape_string($title).'" AND
1449
                '.$groupfilter.$condition_session.'
1450
              ORDER BY id ASC';
1451
        $result = Database::query($sql);
1452
        $cant = Database::num_rows($result);
1453
        if ($cant > 0) {
1454
            return true;
1455
        } else {
1456
            return false;
1457
        }
1458
    }
1459
1460
    /**
1461
     * Checks if this navigation tab has to be set to active
1462
     * @author Patrick Cool <[email protected]>, Ghent University
1463
     *
1464
     * @return string html code
1465
     */
1466
    public function is_active_navigation_tab($paramwk)
1467
    {
1468
        if (isset($_GET['action']) && $_GET['action'] == $paramwk) {
1469
            return ' class="active"';
1470
        }
1471
    }
1472
1473
    /**
1474
     * Lock add pages
1475
     * @author Juan Carlos Raña <[email protected]>
1476
     * return current database status of protect page and change it if get action
1477
     */
1478
    public function check_addnewpagelock()
1479
    {
1480
        $tbl_wiki = $this->tbl_wiki;
1481
        $condition_session = $this->condition_session;
1482
        $groupfilter = $this->groupfilter;
1483
        $course_id = api_get_course_int_id();
1484
1485
        $sql = 'SELECT *
1486
                FROM '.$tbl_wiki.'
1487
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1488
                ORDER BY id ASC';
1489
1490
        $result = Database::query($sql);
1491
        $row = Database::fetch_array($result);
1492
1493
        $status_addlock = $row['addlock'];
1494
1495
        // Change status
1496
        if (api_is_allowed_to_edit(false, true) ||
1497
            api_is_platform_admin()
1498
        ) {
1499
            if (isset($_GET['actionpage'])) {
1500
                if ($_GET['actionpage'] == 'lockaddnew' && $status_addlock == 1) {
1501
                    $status_addlock = 0;
1502
                }
1503
                if ($_GET['actionpage'] == 'unlockaddnew' && $status_addlock == 0) {
1504
                    $status_addlock = 1;
1505
                }
1506
                $sql = 'UPDATE '.$tbl_wiki.' SET
1507
                            addlock="'.Database::escape_string($status_addlock).'"
1508
                        WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session;
1509
                Database::query($sql);
1510
            }
1511
1512
            $sql = 'SELECT *
1513
                    FROM '.$tbl_wiki.'
1514
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1515
                    ORDER BY id ASC';
1516
            $result = Database::query($sql);
1517
            $row = Database::fetch_array($result);
1518
        }
1519
1520
        return $row['addlock'];
1521
    }
1522
1523
    /**
1524
     * Protect page
1525
     * @author Juan Carlos Raña <[email protected]>
1526
     * return current database status of protect page and change it if get action
1527
     */
1528
    public function check_protect_page()
1529
    {
1530
        $tbl_wiki = $this->tbl_wiki;
1531
        $condition_session = $this->condition_session;
1532
        $groupfilter = $this->groupfilter;
1533
        $page = $this->page;
1534
1535
        $course_id = api_get_course_int_id();
1536
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1537
              WHERE
1538
                c_id = '.$course_id.' AND
1539
                reflink="'.Database::escape_string($page).'" AND
1540
                '.$groupfilter.$condition_session.'
1541
              ORDER BY id ASC';
1542
1543
        $result = Database::query($sql);
1544
        $row = Database::fetch_array($result);
1545
        $status_editlock = $row['editlock'];
1546
        $id = $row['page_id'];
1547
1548
        // Change status
1549
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1550
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'lock' && $status_editlock == 0) {
1551
                $status_editlock = 1;
1552
            }
1553
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlock' && $status_editlock == 1) {
1554
                $status_editlock = 0;
1555
            }
1556
1557
            $sql = 'UPDATE '.$tbl_wiki.' SET 
1558
                    editlock="'.Database::escape_string($status_editlock).'"
1559
                    WHERE c_id = '.$course_id.' AND page_id="'.$id.'"';
1560
            Database::query($sql);
1561
1562
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1563
                    WHERE
1564
                        c_id = '.$course_id.' AND
1565
                        reflink="'.Database::escape_string($page).'" AND
1566
                    '.$groupfilter.$condition_session.'
1567
                  ORDER BY id ASC';
1568
            $result = Database::query($sql);
1569
            $row = Database::fetch_array($result);
1570
        }
1571
1572
        //show status
1573
        return $row['editlock'];
1574
    }
1575
1576
    /**
1577
     * Visibility page
1578
     * @author Juan Carlos Raña <[email protected]>
1579
     * return current database status of visibility and change it if get action
1580
     */
1581
    public function check_visibility_page()
1582
    {
1583
        $tbl_wiki = $this->tbl_wiki;
1584
        $page = $this->page;
1585
        $condition_session = $this->condition_session;
1586
        $groupfilter = $this->groupfilter;
1587
        $course_id = api_get_course_int_id();
1588
1589
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1590
                WHERE
1591
                    c_id = '.$course_id.' AND
1592
                    reflink="'.Database::escape_string($page).'" AND
1593
                    '.$groupfilter.$condition_session.'
1594
                ORDER BY id ASC';
1595
        $result = Database::query($sql);
1596
        $row = Database::fetch_array($result);
1597
        $status_visibility = $row['visibility'];
1598
        //change status
1599
        if (api_is_allowed_to_edit(false, true) ||
1600
            api_is_platform_admin()
1601
        ) {
1602
            if (isset($_GET['actionpage']) &&
1603
                $_GET['actionpage'] == 'visible' &&
1604
                $status_visibility == 0
1605
            ) {
1606
                $status_visibility = 1;
1607
1608
            }
1609
            if (isset($_GET['actionpage']) &&
1610
                $_GET['actionpage'] == 'invisible' &&
1611
                $status_visibility == 1
1612
            ) {
1613
                $status_visibility = 0;
1614
            }
1615
1616
            $sql = 'UPDATE '.$tbl_wiki.' SET 
1617
                    visibility = "'.Database::escape_string($status_visibility).'"
1618
                    WHERE 
1619
                        c_id = '.$course_id.' AND 
1620
                        reflink="'.Database::escape_string($page).'" AND 
1621
                        '.$groupfilter.$condition_session;
1622
            Database::query($sql);
1623
1624
            // Although the value now is assigned to all (not only the first),
1625
            // these three lines remain necessary.
1626
            // They do that by changing the page state is
1627
            // made when you press the button and not have to wait to change his page
1628
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1629
                    WHERE
1630
                        c_id = '.$course_id.' AND
1631
                        reflink="'.Database::escape_string($page).'" AND
1632
                        '.$groupfilter.$condition_session.'
1633
                    ORDER BY id ASC';
1634
            $result = Database::query($sql);
1635
            $row = Database::fetch_array($result);
1636
        }
1637
1638
        if (empty($row['id'])) {
1639
            $row['visibility'] = 1;
1640
        }
1641
1642
        //show status
1643
        return $row['visibility'];
1644
    }
1645
1646
    /**
1647
     * Visibility discussion
1648
     * @author Juan Carlos Raña <[email protected]>
1649
     * @return int current database status of discuss visibility
1650
     * and change it if get action page
1651
     */
1652
    public function check_visibility_discuss()
1653
    {
1654
        $tbl_wiki = $this->tbl_wiki;
1655
        $page = $this->page;
1656
        $condition_session = $this->condition_session;
1657
        $groupfilter = $this->groupfilter;
1658
        $course_id = api_get_course_int_id();
1659
1660
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1661
                WHERE
1662
                    c_id = '.$course_id.' AND
1663
                    reflink="'.Database::escape_string($page).'" AND
1664
                    '.$groupfilter.$condition_session.'
1665
                ORDER BY id ASC';
1666
        $result = Database::query($sql);
1667
        $row = Database::fetch_array($result);
1668
1669
        $status_visibility_disc = $row['visibility_disc'];
1670
1671
        //change status
1672
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1673
            if (isset($_GET['actionpage']) &&
1674
                $_GET['actionpage'] == 'showdisc' &&
1675
                $status_visibility_disc == 0
1676
            ) {
1677
                $status_visibility_disc = 1;
1678
            }
1679
            if (isset($_GET['actionpage']) &&
1680
                $_GET['actionpage'] == 'hidedisc' &&
1681
                $status_visibility_disc == 1
1682
            ) {
1683
                $status_visibility_disc = 0;
1684
            }
1685
1686
            $sql = 'UPDATE '.$tbl_wiki.' SET 
1687
                    visibility_disc="'.Database::escape_string($status_visibility_disc).'"
1688
                    WHERE
1689
                        c_id = '.$course_id.' AND
1690
                        reflink="'.Database::escape_string($page).'" AND
1691
                        '.$groupfilter.$condition_session;
1692
            Database::query($sql);
1693
1694
            // Although the value now is assigned to all (not only the first),
1695
            // these three lines remain necessary.
1696
            // They do that by changing the page state is made when you press
1697
            // the button and not have to wait to change his page
1698
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1699
                    WHERE
1700
                        c_id = '.$course_id.' AND
1701
                        reflink="'.Database::escape_string($page).'" AND
1702
                        '.$groupfilter.$condition_session.'
1703
                    ORDER BY id ASC';
1704
            $result = Database::query($sql);
1705
            $row = Database::fetch_array($result);
1706
        }
1707
1708
        return $row['visibility_disc'];
1709
    }
1710
1711
    /**
1712
     * Lock add discussion
1713
     * @author Juan Carlos Raña <[email protected]>
1714
     * @return int current database status of lock dicuss and change if get action
1715
     */
1716
    public function check_addlock_discuss()
1717
    {
1718
        $tbl_wiki = $this->tbl_wiki;
1719
        $page = $this->page;
1720
        $condition_session = $this->condition_session;
1721
        $groupfilter = $this->groupfilter;
1722
        $course_id = api_get_course_int_id();
1723
1724
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1725
                WHERE
1726
                    c_id = '.$course_id.' AND
1727
                    reflink="'.Database::escape_string($page).'" AND
1728
                    '.$groupfilter.$condition_session.'
1729
                ORDER BY id ASC';
1730
        $result = Database::query($sql);
1731
        $row = Database::fetch_array($result);
1732
1733
        $status_addlock_disc = $row['addlock_disc'];
1734
1735
        //change status
1736
        if (api_is_allowed_to_edit() || api_is_platform_admin()) {
1737
            if (isset($_GET['actionpage']) &&
1738
                $_GET['actionpage'] == 'lockdisc' &&
1739
                $status_addlock_disc == 0
1740
            ) {
1741
                $status_addlock_disc = 1;
1742
            }
1743
            if (isset($_GET['actionpage']) &&
1744
                $_GET['actionpage'] == 'unlockdisc' &&
1745
                $status_addlock_disc == 1
1746
            ) {
1747
                $status_addlock_disc = 0;
1748
            }
1749
1750
            $sql = 'UPDATE '.$tbl_wiki.' SET
1751
                    addlock_disc="'.Database::escape_string($status_addlock_disc).'"
1752
                    WHERE
1753
                        c_id = '.$course_id.' AND
1754
                        reflink = "'.Database::escape_string($page).'" AND
1755
                         '.$groupfilter.$condition_session;
1756
            Database::query($sql);
1757
1758
            // Although the value now is assigned to all (not only the first),
1759
            // these three lines remain necessary.
1760
            // They do that by changing the page state is made when you press
1761
            // the button and not have to wait to change his page
1762
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1763
                    WHERE
1764
                        c_id = '.$course_id.' AND
1765
                        reflink="'.Database::escape_string($page).'" AND
1766
                        '.$groupfilter.$condition_session.'
1767
                    ORDER BY id ASC';
1768
            $result = Database::query($sql);
1769
            $row = Database::fetch_array($result);
1770
        }
1771
1772
        return $row['addlock_disc'];
1773
    }
1774
1775
    /**
1776
     * Lock rating discussion
1777
     * @author Juan Carlos Raña <[email protected]>
1778
     * @return  int  current database status of rating discuss and change it if get action
1779
     */
1780
    public function check_ratinglock_discuss()
1781
    {
1782
        $tbl_wiki = $this->tbl_wiki;
1783
        $page = $this->page;
1784
        $condition_session = $this->condition_session;
1785
        $groupfilter = $this->groupfilter;
1786
        $course_id = api_get_course_int_id();
1787
1788
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1789
                WHERE
1790
                    c_id = '.$course_id.' AND
1791
                    reflink="'.Database::escape_string($page).'" AND
1792
                    '.$groupfilter.$condition_session.'
1793
                ORDER BY id ASC';
1794
        $result = Database::query($sql);
1795
        $row = Database::fetch_array($result);
1796
        $status_ratinglock_disc = $row['ratinglock_disc'];
1797
1798
        //change status
1799
        if (api_is_allowed_to_edit(false, true) ||
1800
            api_is_platform_admin()
1801
        ) {
1802
            if (isset($_GET['actionpage']) &&
1803
                $_GET['actionpage'] == 'lockrating' &&
1804
                $status_ratinglock_disc == 0
1805
            ) {
1806
                $status_ratinglock_disc = 1;
1807
            }
1808
            if (isset($_GET['actionpage']) &&
1809
                $_GET['actionpage'] == 'unlockrating' &&
1810
                $status_ratinglock_disc == 1
1811
            ) {
1812
                $status_ratinglock_disc = 0;
1813
            }
1814
1815
            $sql = 'UPDATE '.$tbl_wiki.'
1816
                    SET ratinglock_disc="'.Database::escape_string($status_ratinglock_disc).'"
1817
                    WHERE
1818
                        c_id = '.$course_id.' AND
1819
                        reflink="'.Database::escape_string($page).'" AND
1820
                        '.$groupfilter.$condition_session;
1821
            // Visibility. Value to all,not only for the first
1822
            Database::query($sql);
1823
1824
            // Although the value now is assigned to all (not only the first),
1825
            // these three lines remain necessary. They do that by changing the
1826
            // page state is made when you press the button and not have to wait
1827
            // to change his page
1828
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1829
                    WHERE
1830
                        c_id = '.$course_id.' AND
1831
                        reflink="'.Database::escape_string($page).'" AND
1832
                    '.$groupfilter.$condition_session.'
1833
                  ORDER BY id ASC';
1834
            $result = Database::query($sql);
1835
            $row = Database::fetch_array($result);
1836
        }
1837
1838
        return $row['ratinglock_disc'];
1839
    }
1840
1841
    /**
1842
     * Notify page changes
1843
     * @author Juan Carlos Raña <[email protected]>
1844
     * @return int the current notification status
1845
     */
1846
    public function check_notify_page($reflink)
1847
    {
1848
        $tbl_wiki = $this->tbl_wiki;
1849
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1850
        $condition_session = $this->condition_session;
1851
        $groupfilter = $this->groupfilter;
1852
        $groupId = api_get_group_id();
1853
        $session_id = api_get_session_id();
1854
        $course_id = api_get_course_int_id();
1855
        $userId = api_get_user_id();
1856
1857
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1858
                WHERE 
1859
                    c_id = '.$course_id.' AND 
1860
                    reflink="'.$reflink.'" AND 
1861
                    '.$groupfilter.$condition_session.'
1862
                ORDER BY id ASC';
1863
        $result = Database::query($sql);
1864
        $row = Database::fetch_array($result);
1865
        $id = $row['id'];
1866
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1867
                WHERE
1868
                    c_id = '.$course_id.' AND 
1869
                    id="'.$id.'" AND 
1870
                    user_id="'.api_get_user_id().'" AND 
1871
                    type="P"';
1872
        $result = Database::query($sql);
1873
        $row = Database::fetch_array($result);
1874
        $idm = $row['id'];
1875
        if (empty($idm)) {
1876
            $status_notify = 0;
1877
        } else {
1878
            $status_notify = 1;
1879
        }
1880
1881
        // Change status
1882
        if (isset($_GET['actionpage']) &&
1883
            $_GET['actionpage'] == 'locknotify' &&
1884
            $status_notify == 0
1885
        ) {
1886
            $sql = "SELECT id FROM $tbl_wiki_mailcue
1887
                    WHERE c_id = $course_id AND id = $id AND user_id = $userId";
1888
            $result = Database::query($sql);
1889
            $exist = false;
1890
            if (Database::num_rows($result)) {
1891
                $exist = true;
1892
            }
1893
            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...
1894
                $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1895
                ($course_id, '".$id."','".api_get_user_id(
1896
                    )."','P','".$groupId."','".$session_id."')";
1897
                Database::query($sql);
1898
            }
1899
            $status_notify = 1;
1900
        }
1901
1902
        if (isset($_GET['actionpage']) &&
1903
            $_GET['actionpage'] == 'unlocknotify' &&
1904
            $status_notify == 1
1905
        ) {
1906
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1907
                    WHERE 
1908
                        id="'.$id.'" AND 
1909
                        user_id="'.api_get_user_id().'" AND 
1910
                        type="P" AND 
1911
                        c_id = '.$course_id;
1912
            Database::query($sql);
1913
            $status_notify = 0;
1914
        }
1915
1916
        return $status_notify;
1917
    }
1918
1919
    /**
1920
     * Notify discussion changes
1921
     * @author Juan Carlos Raña <[email protected]>
1922
     * @param string $reflink
1923
     * @return int current database status of rating discuss and change it if get action
1924
     */
1925
    public function check_notify_discuss($reflink)
1926
    {
1927
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1928
        $tbl_wiki = $this->tbl_wiki;
1929
        $condition_session = $this->condition_session;
1930
        $groupfilter = $this->groupfilter;
1931
1932
        $course_id = api_get_course_int_id();
1933
        $groupId = api_get_group_id();
1934
        $session_id = api_get_session_id();
1935
1936
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1937
                WHERE 
1938
                    c_id = '.$course_id.' AND 
1939
                    reflink="'.$reflink.'" AND 
1940
                    '.$groupfilter.$condition_session.'
1941
                ORDER BY id ASC';
1942
        $result = Database::query($sql);
1943
        $row = Database::fetch_array($result);
1944
        $id = $row['id'];
1945
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1946
                WHERE 
1947
                    c_id = '.$course_id.' AND id="'.$id.'" AND user_id="'.api_get_user_id(
1948
            ).'" AND type="D"';
1949
        $result = Database::query($sql);
1950
        $row = Database::fetch_array($result);
1951
        $idm = $row['id'];
1952
1953
        if (empty($idm)) {
1954
            $status_notify_disc = 0;
1955
        } else {
1956
            $status_notify_disc = 1;
1957
        }
1958
1959
        // change status
1960
        if (isset($_GET['actionpage']) &&
1961
            $_GET['actionpage'] == 'locknotifydisc' &&
1962
            $status_notify_disc == 0
1963
        ) {
1964
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1965
            ($course_id, '".$id."','".api_get_user_id()."','D','".$groupId."','".$session_id."')";
1966
            Database::query($sql);
1967
            $status_notify_disc = 1;
1968
        }
1969
        if (isset($_GET['actionpage']) &&
1970
            $_GET['actionpage'] == 'unlocknotifydisc' &&
1971
            $status_notify_disc == 1
1972
        ) {
1973
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1974
                    WHERE 
1975
                        c_id = '.$course_id.' AND 
1976
                        id="'.$id.'" AND 
1977
                        user_id="'.api_get_user_id().'" AND 
1978
                        type="D" AND 
1979
                        c_id = '.$course_id;
1980
            Database::query($sql);
1981
            $status_notify_disc = 0;
1982
        }
1983
1984
        return $status_notify_disc;
1985
    }
1986
1987
    /**
1988
     * Notify all changes
1989
     * @author Juan Carlos Raña <[email protected]>
1990
     */
1991
    public function check_notify_all()
1992
    {
1993
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1994
        $course_id = api_get_course_int_id();
1995
        $groupId = api_get_group_id();
1996
        $session_id = api_get_session_id();
1997
1998
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1999
                WHERE
2000
                    c_id = '.$course_id.' AND
2001
                    user_id="'.api_get_user_id().'" AND
2002
                    type="F" AND
2003
                    group_id="'.$groupId.'" AND
2004
                    session_id="'.$session_id.'"';
2005
        $result = Database::query($sql);
2006
        $row = Database::fetch_array($result);
2007
2008
        $idm = $row['user_id'];
2009
2010
        if (empty($idm)) {
2011
            $status_notify_all = 0;
2012
        } else {
2013
            $status_notify_all = 1;
2014
        }
2015
2016
        //change status
2017
        if (isset($_GET['actionpage']) &&
2018
            $_GET['actionpage'] == 'locknotifyall' &&
2019
            $status_notify_all == 0
2020
        ) {
2021
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, user_id, type, group_id, session_id) VALUES
2022
            ($course_id, '".api_get_user_id(
2023
                )."','F','".$groupId."','".$session_id."')";
2024
            Database::query($sql);
2025
            $status_notify_all = 1;
2026
        }
2027
2028
        if (isset($_GET['actionpage']) &&
2029
            isset($_GET['actionpage']) &&
2030
            $_GET['actionpage'] == 'unlocknotifyall' &&
2031
            $status_notify_all == 1
2032
        ) {
2033
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
2034
                   WHERE
2035
                    c_id = '.$course_id.' AND
2036
                    user_id="'.api_get_user_id().'" AND
2037
                    type="F" AND
2038
                    group_id="'.$groupId.'" AND
2039
                    session_id="'.$session_id.'" AND
2040
                    c_id = '.$course_id;
2041
            Database::query($sql);
2042
            $status_notify_all = 0;
2043
        }
2044
2045
        //show status
2046
        return $status_notify_all;
2047
    }
2048
2049
    /**
2050
     * Sends pending e-mails
2051
     */
2052
    public function check_emailcue(
2053
        $id_or_ref,
2054
        $type,
2055
        $lastime = '',
2056
        $lastuser = ''
2057
    ) {
2058
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
2059
        $tbl_wiki = $this->tbl_wiki;
2060
        $condition_session = $this->condition_session;
2061
        $groupfilter = $this->groupfilter;
2062
        $_course = $this->courseInfo;
2063
        $groupId = api_get_group_id();
2064
        $session_id = api_get_session_id();
2065
        $course_id = api_get_course_int_id();
2066
        $group_properties = GroupManager::get_group_properties($groupId);
2067
        $group_name = $group_properties['name'];
2068
        $allow_send_mail = false; //define the variable to below
2069
        $email_assignment = null;
2070
        if ($type == 'P') {
2071
            //if modifying a wiki page
2072
            //first, current author and time
2073
            //Who is the author?
2074
            $userinfo = api_get_user_info($lastuser);
2075
            $email_user_author = get_lang(
2076
                    'EditedBy'
2077
                ).': '.$userinfo['complete_name'];
2078
2079
            //When ?
2080
            $year = substr($lastime, 0, 4);
2081
            $month = substr($lastime, 5, 2);
2082
            $day = substr($lastime, 8, 2);
2083
            $hours = substr($lastime, 11, 2);
2084
            $minutes = substr($lastime, 14, 2);
2085
            $seconds = substr($lastime, 17, 2);
2086
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2087
2088
            //second, extract data from first reg
2089
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2090
                    WHERE 
2091
                        c_id = '.$course_id.' AND 
2092
                        reflink="'.$id_or_ref.'" AND 
2093
                        '.$groupfilter.$condition_session.'
2094
                    ORDER BY id ASC';
2095
            $result = Database::query($sql);
2096
            $row = Database::fetch_array($result);
2097
            $id = $row['id'];
2098
            $email_page_name = $row['title'];
2099
            if ($row['visibility'] == 1) {
2100
                $allow_send_mail = true; //if visibility off - notify off
2101
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2102
                        WHERE
2103
                            c_id = '.$course_id.' AND
2104
                            id="'.$id.'" AND
2105
                            type="'.$type.'" OR
2106
                            type="F" AND
2107
                            group_id="'.$groupId.'" AND
2108
                            session_id="'.$session_id.'"';
2109
                //type: P=page, D=discuss, F=full.
2110
                $result = Database::query($sql);
2111
                $emailtext = get_lang('EmailWikipageModified').
2112
                    '<strong>'.$email_page_name.'</strong> '.
2113
                    get_lang('Wiki');
2114
            }
2115
        } elseif ($type == 'D') {
2116
            //if added a post to discuss
2117
            //first, current author and time
2118
            //Who is the author of last message?
2119
            $userinfo = api_get_user_info($lastuser);
2120
            $email_user_author = get_lang(
2121
                    'AddedBy'
2122
                ).': '.$userinfo['complete_name'];
2123
2124
            //When ?
2125
            $year = substr($lastime, 0, 4);
2126
            $month = substr($lastime, 5, 2);
2127
            $day = substr($lastime, 8, 2);
2128
            $hours = substr($lastime, 11, 2);
2129
            $minutes = substr($lastime, 14, 2);
2130
            $seconds = substr($lastime, 17, 2);
2131
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2132
            //second, extract data from first reg
2133
            $id = $id_or_ref; //$id_or_ref is id from tblwiki
2134
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2135
                    WHERE c_id = '.$course_id.' AND id="'.$id.'"
2136
                    ORDER BY id ASC';
2137
2138
            $result = Database::query($sql);
2139
            $row = Database::fetch_array($result);
2140
2141
            $email_page_name = $row['title'];
2142
            if ($row['visibility_disc'] == 1) {
2143
                $allow_send_mail = true; //if visibility off - notify off
2144
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2145
                        WHERE
2146
                            c_id = '.$course_id.' AND
2147
                            id="'.$id.'" AND
2148
                            type="'.$type.'" OR
2149
                            type="F" AND
2150
                            group_id="'.$groupId.'" AND
2151
                            session_id="'.$session_id.'"';
2152
                //type: P=page, D=discuss, F=full
2153
                $result = Database::query($sql);
2154
                $emailtext = get_lang(
2155
                        'EmailWikiPageDiscAdded'
2156
                    ).' <strong>'.$email_page_name.'</strong> '.get_lang(
2157
                        'Wiki'
2158
                    );
2159
            }
2160
        } elseif ($type == 'A') {
2161
            //for added pages
2162
            $id = 0; //for tbl_wiki_mailcue
2163
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2164
                    WHERE c_id = '.$course_id.'
2165
                    ORDER BY id DESC'; //the added is always the last
2166
2167
            $result = Database::query($sql);
2168
            $row = Database::fetch_array($result);
2169
            $email_page_name = $row['title'];
2170
2171
            //Who is the author?
2172
            $userinfo = api_get_user_info($row['user_id']);
2173
            $email_user_author = get_lang(
2174
                    'AddedBy'
2175
                ).': '.$userinfo['complete_name'];
2176
2177
            //When ?
2178
            $year = substr($row['dtime'], 0, 4);
2179
            $month = substr($row['dtime'], 5, 2);
2180
            $day = substr($row['dtime'], 8, 2);
2181
            $hours = substr($row['dtime'], 11, 2);
2182
            $minutes = substr($row['dtime'], 14, 2);
2183
            $seconds = substr($row['dtime'], 17, 2);
2184
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2185
2186
            if ($row['assignment'] == 0) {
2187
                $allow_send_mail = true;
2188
            } elseif ($row['assignment'] == 1) {
2189
                $email_assignment = get_lang(
2190
                        'AssignmentDescExtra'
2191
                    ).' ('.get_lang('AssignmentMode').')';
2192
                $allow_send_mail = true;
2193
            } elseif ($row['assignment'] == 2) {
2194
                $allow_send_mail = false; //Mode tasks: avoids notifications to all users about all users
2195
            }
2196
2197
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2198
                    WHERE
2199
                        c_id = '.$course_id.' AND  
2200
                        id="'.$id.'" AND 
2201
                        type="F" AND 
2202
                        group_id="'.$groupId.'" AND 
2203
                        session_id="'.$session_id.'"';
2204
2205
            //type: P=page, D=discuss, F=full
2206
            $result = Database::query($sql);
2207
2208
            $emailtext = get_lang(
2209
                    'EmailWikiPageAdded'
2210
                ).' <strong>'.$email_page_name.'</strong> '.get_lang(
2211
                    'In'
2212
                ).' '.get_lang('Wiki');
2213
        } elseif ($type == 'E') {
2214
            $id = 0;
2215
            $allow_send_mail = true;
2216
            // Who is the author?
2217
            $userinfo = api_get_user_info(api_get_user_id()); //current user
2218
            $email_user_author = get_lang('DeletedBy').': '.$userinfo['complete_name'];
2219
            //When ?
2220
            $today = date('r'); //current time
2221
            $email_date_changes = $today;
2222
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2223
                    WHERE
2224
                        c_id = '.$course_id.' AND
2225
                        id="'.$id.'" AND type="F" AND
2226
                        group_id="'.$groupId.'" AND
2227
                        session_id="'.$session_id.'"'; //type: P=page, D=discuss, F=wiki
2228
            $result = Database::query($sql);
2229
            $emailtext = get_lang('EmailWikipageDedeleted');
2230
        }
2231
        ///make and send email
2232
        if ($allow_send_mail) {
2233
            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...
2234
                $userinfo = api_get_user_info(
2235
                    $row['user_id']
2236
                ); //$row['user_id'] obtained from tbl_wiki_mailcue
2237
                $name_to = $userinfo['complete_name'];
2238
                $email_to = $userinfo['email'];
2239
                $sender_name = api_get_setting('emailAdministrator');
2240
                $sender_email = api_get_setting('emailAdministrator');
2241
                $email_subject = get_lang(
2242
                        'EmailWikiChanges'
2243
                    ).' - '.$_course['official_code'];
2244
                $email_body = get_lang('DearUser').' '.api_get_person_name(
2245
                        $userinfo['firstname'],
2246
                        $userinfo['lastname']
2247
                    ).',<br /><br />';
2248
                if ($session_id == 0) {
2249
                    $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...
2250
                } else {
2251
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' ('.api_get_session_name(
2252
                            api_get_session_id()
2253
                        ).') - '.$group_name.'</strong><br /><br /><br />';
2254
                }
2255
                $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...
2256
                $email_body .= $email_assignment.'<br /><br /><br />';
2257
                $email_body .= '<font size="-2">'.get_lang(
2258
                        'EmailWikiChangesExt_1'
2259
                    ).': <strong>'.get_lang('NotifyChanges').'</strong><br />';
2260
                $email_body .= get_lang(
2261
                        'EmailWikiChangesExt_2'
2262
                    ).': <strong>'.get_lang(
2263
                        'NotNotifyChanges'
2264
                    ).'</strong></font><br />';
2265
                @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

2265
                /** @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...
2266
                    $name_to,
2267
                    $email_to,
2268
                    $email_subject,
2269
                    $email_body,
2270
                    $sender_name,
2271
                    $sender_email
2272
                );
2273
            }
2274
        }
2275
    }
2276
2277
    /**
2278
     * Function export last wiki page version to document area
2279
     * @param int $doc_id wiki page id
2280
     * @return mixed
2281
     * @author Juan Carlos Raña <[email protected]>
2282
     */
2283
    public function export2doc($doc_id)
2284
    {
2285
        $_course = $this->courseInfo;
2286
        $groupId = api_get_group_id();
2287
        $groupInfo = GroupManager::get_group_properties($groupId);
2288
        $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

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

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

2666
                self::/** @scrutinizer ignore-call */ 
2667
                      save_new_wiki($values);
Loading history...
2667
            }
2668
        }
2669
2670
        foreach ($a_users_to_add as $o_user_to_add) {
2671
            if ($o_user_to_add['user_id'] == $userId) {
2672
                $assig_user_id = $o_user_to_add['user_id'];
2673
                if ($assignment_type == 1) {
2674
                    $values['title'] = $title_orig;
2675
                    $values['comment'] = get_lang('AssignmentDesc');
2676
                    sort($all_students_pages);
2677
                    $values['content'] = $content_orig_A.$content_orig_B.'<br/>
2678
                    <div align="center" style="font-size:18px; background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2679
                    '.get_lang('AssignmentLinkstoStudentsPage').'
2680
                    </div><br/>
2681
                    <div style="background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2682
                    <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

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

3123
        /** @scrutinizer ignore-call */ 
3124
        $pageInfo = self::getPageByTitle($title, $courseId);
Loading history...
3124
        if (!empty($pageInfo)) {
3125
            $pageId = $pageInfo['id'];
3126
            $sql = "DELETE FROM $tbl_wiki_conf
3127
                    WHERE c_id = $courseId AND page_id = $pageId";
3128
            Database::query($sql);
3129
3130
            $sql = 'DELETE FROM '.$tbl_wiki_discuss.'
3131
                    WHERE c_id = '.$courseId.' AND publication_id = '.$pageId;
3132
            Database::query($sql);
3133
3134
            $sql = 'DELETE FROM  '.$tbl_wiki_mailcue.'
3135
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3136
            Database::query($sql);
3137
3138
            $sql = 'DELETE FROM '.$tbl_wiki.'
3139
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3140
            Database::query($sql);
3141
            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

3141
            self::/** @scrutinizer ignore-call */ 
3142
                  check_emailcue(0, 'E');
Loading history...
3142
3143
            return true;
3144
        }
3145
3146
        return false;
3147
    }
3148
3149
    /**
3150
     * @return array
3151
     */
3152
    public function getAllWiki()
3153
    {
3154
        $tbl_wiki = $this->tbl_wiki;
3155
        $course_id = $this->course_id;
3156
        $condition_session = $this->condition_session;
3157
3158
        $sql = "SELECT * FROM $tbl_wiki
3159
                WHERE
3160
                    c_id = $course_id AND
3161
                    is_editing != '0' ".$condition_session;
3162
        $result = Database::query($sql);
3163
3164
        return Database::store_result($result, 'ASSOC');
3165
    }
3166
3167
    /**
3168
     * @param int $isEditing
3169
     */
3170
    public function updateWikiIsEditing($isEditing)
3171
    {
3172
        $tbl_wiki = $this->tbl_wiki;
3173
        $course_id = $this->course_id;
3174
        $condition_session = $this->condition_session;
3175
        $isEditing = Database::escape_string($isEditing);
3176
3177
        $sql = 'UPDATE '.$tbl_wiki.' SET
3178
                is_editing = "0",
3179
                time_edit = NULL
3180
                WHERE
3181
                    c_id = '.$course_id.' AND
3182
                    is_editing="'.$isEditing.'" '.
3183
            $condition_session;
3184
        Database::query($sql);
3185
    }
3186
3187
    /**
3188
     * Release of blocked pages to prevent concurrent editions
3189
     * @param int $userId
3190
     * @param string $action
3191
     */
3192
    public function blockConcurrentEditions($userId, $action = null)
3193
    {
3194
        $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

3194
        /** @scrutinizer ignore-call */ 
3195
        $result = self::getAllWiki();
Loading history...
3195
        if (!empty($result)) {
3196
            foreach ($result as $is_editing_block) {
3197
                $max_edit_time = 1200; // 20 minutes
3198
                $timestamp_edit = strtotime($is_editing_block['time_edit']);
3199
                $time_editing = time() - $timestamp_edit;
3200
3201
                // First prevent concurrent users and double version
3202
                if ($is_editing_block['is_editing'] == $userId) {
3203
                    Session::write('_version', $is_editing_block['version']);
3204
                } else {
3205
                    Session::erase('_version');
3206
                }
3207
                // Second checks if has exceeded the time that a page may
3208
                // be available or if a page was edited and saved by its author
3209
                if ($time_editing > $max_edit_time ||
3210
                    ($is_editing_block['is_editing'] == $userId &&
3211
                        $action != 'edit')
3212
                ) {
3213
                    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

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

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

4032
        if (isset($_POST['Submit']) && self::/** @scrutinizer ignore-call */ double_post($_POST['wpost_id'])) {
Loading history...
4033
            $dtime = api_get_utc_datetime();
4034
            $message_author = api_get_user_id();
4035
4036
            $params = [
4037
                'c_id' => $course_id,
4038
                'publication_id' => $id,
4039
                'userc_id' => $message_author,
4040
                'comment' => $_POST['comment'],
4041
                'p_score' => $_POST['rating'],
4042
                'dtime' => $dtime
4043
            ];
4044
            $discussId = Database::insert($tbl_wiki_discuss, $params);
4045
            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...
4046
                $sql = "UPDATE $tbl_wiki_discuss SET id = iid WHERE iid = $discussId";
4047
                Database::query($sql);
4048
            }
4049
4050
            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

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

4094
                    if (self::/** @scrutinizer ignore-call */ check_addlock_discuss() == 1) {
Loading history...
4095
                        $addlock_disc = Display::return_icon(
4096
                            'unlock.png',
4097
                            get_lang('UnlockDiscussExtra'),
4098
                            '',
4099
                            ICON_SIZE_SMALL
4100
                        );
4101
                        $lock_unlock_disc = 'unlockdisc';
4102
                    } else {
4103
                        $addlock_disc = Display::return_icon(
4104
                            'lock.png',
4105
                            get_lang('LockDiscussExtra'),
4106
                            '',
4107
                            ICON_SIZE_SMALL
4108
                        );
4109
                        $lock_unlock_disc = 'lockdisc';
4110
                    }
4111
                }
4112
                echo '<span style="float:right">';
4113
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_disc.'&title='.api_htmlentities(
4114
                        urlencode($page)
4115
                    ).'">'.$addlock_disc.'</a>';
4116
                echo '</span>';
4117
4118
                // discussion action: visibility.  Show discussion to students if isn't hidden. Show page to all teachers if is hidden.
4119
                $visibility_disc = null;
4120
                $hide_show_disc = null;
4121
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4122
                    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

4122
                    if (self::/** @scrutinizer ignore-call */ check_visibility_discuss() == 1) {
Loading history...
4123
                        /// TODO: 	Fix Mode assignments: If is hidden, show discussion to student only if student is the author
4124
                        $visibility_disc = Display::return_icon(
4125
                            'visible.png',
4126
                            get_lang('ShowDiscussExtra'),
4127
                            '',
4128
                            ICON_SIZE_SMALL
4129
                        );
4130
                        $hide_show_disc = 'hidedisc';
4131
                    } else {
4132
                        $visibility_disc = Display::return_icon(
4133
                            'invisible.png',
4134
                            get_lang('HideDiscussExtra'),
4135
                            '',
4136
                            ICON_SIZE_SMALL
4137
                        );
4138
                        $hide_show_disc = 'showdisc';
4139
                    }
4140
                }
4141
                echo '<span style="float:right">';
4142
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$hide_show_disc.'&title='.api_htmlentities(
4143
                        urlencode($page)
4144
                    ).'">'.$visibility_disc.'</a>';
4145
                echo '</span>';
4146
4147
                // discussion action: check add rating lock. Show/Hide list to rating for all student
4148
                $lock_unlock_rating_disc = null;
4149
                $ratinglock_disc = null;
4150
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4151
                    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

4151
                    if (self::/** @scrutinizer ignore-call */ check_ratinglock_discuss() == 1) {
Loading history...
4152
                        $ratinglock_disc = Display::return_icon(
4153
                            'star.png',
4154
                            get_lang('UnlockRatingDiscussExtra'),
4155
                            '',
4156
                            ICON_SIZE_SMALL
4157
                        );
4158
                        $lock_unlock_rating_disc = 'unlockrating';
4159
                    } else {
4160
                        $ratinglock_disc = Display::return_icon(
4161
                            'star_na.png',
4162
                            get_lang('LockRatingDiscussExtra'),
4163
                            '',
4164
                            ICON_SIZE_SMALL
4165
                        );
4166
                        $lock_unlock_rating_disc = 'lockrating';
4167
                    }
4168
                }
4169
4170
                echo '<span style="float:right">';
4171
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_rating_disc.'&title='.api_htmlentities(
4172
                        urlencode($page)
4173
                    ).'">'.$ratinglock_disc.'</a>';
4174
                echo '</span>';
4175
4176
                // discussion action: email notification
4177
                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

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

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

4672
            if (self::/** @scrutinizer ignore-call */ check_notify_all() == 1) {
Loading history...
4673
                $notify_all = Display::return_icon(
4674
                        'messagebox_info.png',
4675
                        get_lang('NotifyByEmail'),
4676
                        '',
4677
                        ICON_SIZE_SMALL
4678
                    ).' '.get_lang('NotNotifyChanges');
4679
                $lock_unlock_notify_all = 'unlocknotifyall';
4680
            } else {
4681
                $notify_all = Display::return_icon(
4682
                        'mail.png',
4683
                        get_lang('CancelNotifyByEmail'),
4684
                        '',
4685
                        ICON_SIZE_SMALL
4686
                    ).' '.get_lang('NotifyChanges');
4687
                $lock_unlock_notify_all = 'locknotifyall';
4688
            }
4689
        }
4690
4691
        echo '<div class="actions"><span style="float: right;">';
4692
        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...
4693
                urlencode($page)
4694
            ).'">'.$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...
4695
        echo '</span>'.get_lang('RecentChanges').'</div>';
4696
4697
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4698
            //only by professors if page is hidden
4699
            $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
4700
        		WHERE 	'.$tbl_wiki_conf.'.c_id= '.$course_id.' AND
4701
        				'.$tbl_wiki.'.c_id= '.$course_id.' AND
4702
        				'.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
4703
        				'.$tbl_wiki.'.'.$groupfilter.$condition_session.'
4704
        		ORDER BY dtime DESC'; // new version
4705
        } else {
4706
            $sql = 'SELECT *
4707
                FROM '.$tbl_wiki.'
4708
                WHERE
4709
                    c_id = '.$course_id.' AND
4710
                    '.$groupfilter.$condition_session.' AND
4711
                    visibility=1
4712
                ORDER BY dtime DESC';
4713
            // old version TODO: Replace by the bottom line
4714
        }
4715
4716
        $allpages = Database::query($sql);
4717
4718
        //show table
4719
        if (Database::num_rows($allpages) > 0) {
4720
            $rows = array();
4721
            while ($obj = Database::fetch_object($allpages)) {
4722
                //get author
4723
                $userinfo = api_get_user_info($obj->user_id);
4724
4725
                //get type assignment icon
4726
                if ($obj->assignment == 1) {
4727
                    $ShowAssignment = Display::return_icon(
4728
                        'wiki_assignment.png',
4729
                        get_lang('AssignmentDesc'),
4730
                        '',
4731
                        ICON_SIZE_SMALL
4732
                    );
4733
                } elseif ($obj->assignment == 2) {
4734
                    $ShowAssignment = Display::return_icon(
4735
                        'wiki_work.png',
4736
                        get_lang('AssignmentWork'),
4737
                        '',
4738
                        ICON_SIZE_SMALL
4739
                    );
4740
                } elseif ($obj->assignment == 0) {
4741
                    $ShowAssignment = Display::return_icon(
4742
                        'px_transparent.gif'
4743
                    );
4744
                }
4745
4746
                // Get icon task
4747
                if (!empty($obj->task)) {
4748
                    $icon_task = Display::return_icon(
4749
                        'wiki_task.png',
4750
                        get_lang('StandardTask'),
4751
                        '',
4752
                        ICON_SIZE_SMALL
4753
                    );
4754
                } else {
4755
                    $icon_task = Display::return_icon('px_transparent.gif');
4756
                }
4757
4758
                $row = array();
4759
                $row[] = api_get_local_time(
4760
                    $obj->dtime
4761
                );
4762
                $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...
4763
                $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
4764
                    ).'&action=showpage&title='.api_htmlentities(
4765
                        urlencode($obj->reflink)
4766
                    ).'&view='.$obj->id.'&session_id='.api_get_session_id(
4767
                    ).'&group_id='.api_get_group_id().'">'.
4768
                    api_htmlentities($obj->title).'</a>';
4769
                $row[] = $obj->version > 1 ? get_lang('EditedBy') : get_lang(
4770
                    'AddedBy'
4771
                );
4772
                if ($userinfo !== false) {
4773
                    $row[] = UserManager::getUserProfileLink($userinfo);
4774
                } else {
4775
                    $row[] = get_lang('Anonymous').' ('.api_htmlentities(
4776
                            $obj->user_ip
4777
                        ).')';
4778
                }
4779
                $rows[] = $row;
4780
            }
4781
4782
            $table = new SortableTableFromArrayConfig(
4783
                $rows,
4784
                0,
4785
                10,
4786
                'RecentPages_table',
4787
                '',
4788
                '',
4789
                'DESC'
4790
            );
4791
            $table->set_additional_parameters(
4792
                array(
4793
                    'cidReq' => api_get_course_id(),
4794
                    'action' => Security::remove_XSS($action),
4795
                    'session_id' => api_get_session_id(),
4796
                    'group_id' => api_get_group_id()
4797
                )
4798
            );
4799
            $table->set_header(
4800
                0,
4801
                get_lang('Date'),
4802
                true,
4803
                array('style' => 'width:200px;')
4804
            );
4805
            $table->set_header(
4806
                1,
4807
                get_lang('Type'),
4808
                true,
4809
                array('style' => 'width:30px;')
4810
            );
4811
            $table->set_header(2, get_lang('Title'), true);
4812
            $table->set_header(
4813
                3,
4814
                get_lang('Actions'),
4815
                true,
4816
                array('style' => 'width:80px;')
4817
            );
4818
            $table->set_header(4, get_lang('Author'), true);
4819
            $table->display();
4820
        }
4821
    }
4822
4823
    /**
4824
     * What links here. Show pages that have linked this page
4825
     *
4826
     * @param string $page
4827
     */
4828
    public function getLinks($page)
4829
    {
4830
        $tbl_wiki = $this->tbl_wiki;
4831
        $course_id = $this->course_id;
4832
        $condition_session = $this->condition_session;
4833
        $groupfilter = $this->groupfilter;
4834
        $_course = $this->courseInfo;
4835
        $action = $this->action;
4836
4837
        if (!$_GET['title']) {
4838
            Display::addFlash(
4839
                Display::return_message(
4840
                    get_lang("MustSelectPage"),
4841
                    'error',
4842
                    false
4843
                )
4844
            );
4845
        } else {
4846
            $sql = 'SELECT * FROM '.$tbl_wiki.'
4847
                    WHERE
4848
                        c_id = '.$course_id.' AND
4849
                        reflink="'.Database::escape_string($page).'" AND
4850
                        '.$groupfilter.$condition_session;
4851
            $result = Database::query($sql);
4852
            $row = Database::fetch_array($result);
4853
4854
            //get type assignment icon
4855
            $ShowAssignment = '';
4856
            if ($row['assignment'] == 1) {
4857
                $ShowAssignment = Display::return_icon(
4858
                    'wiki_assignment.png',
4859
                    get_lang('AssignmentDesc'),
4860
                    '',
4861
                    ICON_SIZE_SMALL
4862
                );
4863
            } elseif ($row['assignment'] == 2) {
4864
                $ShowAssignment = Display::return_icon(
4865
                    'wiki_work.png',
4866
                    get_lang('AssignmentWork'),
4867
                    '',
4868
                    ICON_SIZE_SMALL
4869
                );
4870
            } elseif ($row['assignment'] == 0) {
4871
                $ShowAssignment = Display::return_icon('px_transparent.gif');
4872
            }
4873
4874
            //fix Title to reflink (link Main Page)
4875
            if ($page == get_lang('DefaultTitle')) {
4876
                $page = 'index';
4877
            }
4878
4879
            echo '<div id="wikititle">';
4880
            echo get_lang(
4881
                    'LinksPagesFrom'
4882
                ).': '.$ShowAssignment.' <a href="'.api_get_self(
4883
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4884
                    urlencode($page)
4885
                ).'&session_id='.api_htmlentities(
4886
                    $_GET['session_id']
4887
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4888
                api_htmlentities($row['title']).'</a>';
4889
            echo '</div>';
4890
4891
            //fix index to title Main page into linksto
4892
4893
            if ($page == 'index') {
4894
                $page = str_replace(' ', '_', get_lang('DefaultTitle'));
4895
            }
4896
4897
            //table
4898
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin(
4899
                )) {
4900
                //only by professors if page is hidden
4901
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4902
                        WHERE s1.c_id = $course_id AND linksto LIKE '%".Database::escape_string(
4903
                        $page
4904
                    )."%' AND id=(
4905
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4906
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4907
                //add blank space after like '%" " %' to identify each word
4908
            } else {
4909
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4910
                        WHERE s1.c_id = $course_id AND visibility=1 AND linksto LIKE '%".Database::escape_string(
4911
                        $page
4912
                    )."%' AND id=(
4913
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4914
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4915
                //add blank space after like '%" " %' to identify each word
4916
            }
4917
4918
            $allpages = Database::query($sql);
4919
4920
            //show table
4921
            if (Database::num_rows($allpages) > 0) {
4922
                $rows = array();
4923
                while ($obj = Database::fetch_object($allpages)) {
4924
                    //get author
4925
                    $userinfo = api_get_user_info($obj->user_id);
4926
4927
                    //get time
4928
                    $year = substr($obj->dtime, 0, 4);
4929
                    $month = substr($obj->dtime, 5, 2);
4930
                    $day = substr($obj->dtime, 8, 2);
4931
                    $hours = substr($obj->dtime, 11, 2);
4932
                    $minutes = substr($obj->dtime, 14, 2);
4933
                    $seconds = substr($obj->dtime, 17, 2);
4934
4935
                    //get type assignment icon
4936
                    if ($obj->assignment == 1) {
4937
                        $ShowAssignment = Display::return_icon(
4938
                            'wiki_assignment.png',
4939
                            get_lang('AssignmentDesc'),
4940
                            '',
4941
                            ICON_SIZE_SMALL
4942
                        );
4943
                    } elseif ($obj->assignment == 2) {
4944
                        $ShowAssignment = Display::return_icon(
4945
                            'wiki_work.png',
4946
                            get_lang('AssignmentWork'),
4947
                            '',
4948
                            ICON_SIZE_SMALL
4949
                        );
4950
                    } elseif ($obj->assignment == 0) {
4951
                        $ShowAssignment = Display::return_icon(
4952
                            'px_transparent.gif'
4953
                        );
4954
                    }
4955
4956
                    $row = array();
4957
                    $row[] = $ShowAssignment;
4958
                    $row[] = '<a href="'.api_get_self(
4959
                        ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4960
                            urlencode($obj->reflink)
4961
                        ).'&session_id='.api_htmlentities(
4962
                            $_GET['session_id']
4963
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4964
                        api_htmlentities($obj->title).'</a>';
4965
                    if ($userinfo !== false) {
4966
                        $row[] = UserManager::getUserProfileLink($userinfo);
4967
                    } else {
4968
                        $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
4969
                    }
4970
                    $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
4971
                    $rows[] = $row;
4972
                }
4973
4974
                $table = new SortableTableFromArrayConfig(
4975
                    $rows,
4976
                    1,
4977
                    10,
4978
                    'AllPages_table',
4979
                    '',
4980
                    '',
4981
                    'ASC'
4982
                );
4983
                $table->set_additional_parameters(
4984
                    array(
4985
                        'cidReq' => Security::remove_XSS($_GET['cidReq']),
4986
                        'action' => Security::remove_XSS($action),
4987
                        'group_id' => intval($_GET['group_id']),
4988
                    )
4989
                );
4990
                $table->set_header(
4991
                    0,
4992
                    get_lang('Type'),
4993
                    true,
4994
                    array('style' => 'width:30px;')
4995
                );
4996
                $table->set_header(1, get_lang('Title'), true);
4997
                $table->set_header(2, get_lang('Author'), true);
4998
                $table->set_header(3, get_lang('Date'), true);
4999
                $table->display();
5000
            }
5001
        }
5002
    }
5003
5004
    /**
5005
     * @param string $action
5006
     */
5007
    public function getSearchPages($action)
5008
    {
5009
        echo '<div class="actions">'.get_lang('SearchPages').'</div>';
5010
        if (isset($_GET['mode_table'])) {
5011
            if (!isset($_GET['SearchPages_table_page_nr'])) {
5012
                $_GET['search_term'] = isset($_POST['search_term']) ? $_POST['search_term'] : '';
5013
                $_GET['search_content'] = isset($_POST['search_content']) ? $_POST['search_content'] : '';
5014
                $_GET['all_vers'] = isset($_POST['all_vers']) ? $_POST['all_vers'] : '';
5015
            }
5016
            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

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

5451
                                self::/** @scrutinizer ignore-call */ 
5452
                                      restore_wikipage(
Loading history...
5452
                                    $current_row['page_id'],
5453
                                    $current_row['reflink'],
5454
                                    $current_row['title'],
5455
                                    $current_row['content'],
5456
                                    $current_row['group_id'],
5457
                                    $current_row['assignment'],
5458
                                    $current_row['progress'],
5459
                                    $current_row['version'],
5460
                                    $last_row['version'],
5461
                                    $current_row['linksto']
5462
                                ).': <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5463
                                    urlencode($last_row['reflink'])
5464
                                ).'&session_id='.$last_row['session_id'].'&group_id='.$last_row['group_id'].'">'.
5465
                                api_htmlentities($last_row['title']).'</a>',
5466
                                'confirmation',
5467
                                false
5468
                            )
5469
                        );
5470
                    }
5471
                }
5472
            }
5473
        }
5474
    }
5475
5476
    /**
5477
     * @param int|bool $wikiId
5478
     */
5479
    public function setWikiData($wikiId)
5480
    {
5481
        $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

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

6013
            $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...
6014
                    'addnew'
6015
                ).'>'
6016
                .Display::return_icon(
6017
                    'add.png',
6018
                    get_lang('AddNew'),
6019
                    '',
6020
                    ICON_SIZE_MEDIUM
6021
                ).'</a>';
6022
        }
6023
6024
        $lock_unlock_addnew = null;
6025
        $protect_addnewpage = null;
6026
6027
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6028
            // page action: enable or disable the adding of new pages
6029
            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

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

6128
                /** @scrutinizer ignore-call */ 
6129
                $result = self::deletePage(
Loading history...
6129
                    $page,
6130
                    $course_id,
6131
                    $groupfilter,
6132
                    $condition_session
6133
                );
6134
                if ($result) {
6135
                    Display::addFlash(
6136
                        Display::return_message(
6137
                            get_lang('WikiPageDeleted'),
6138
                            'confirmation',
6139
                            false
6140
                        )
6141
                    );
6142
                }
6143
            }
6144
        } else {
6145
            Display::addFlash(
6146
                Display::return_message(
6147
                    get_lang('OnlyAdminDeletePageWiki'),
6148
                    'normal',
6149
                    false
6150
                )
6151
            );
6152
        }
6153
    }
6154
6155
    /**
6156
     * Edit page
6157
     */
6158
    public function editPage()
6159
    {
6160
        $tbl_wiki = $this->tbl_wiki;
6161
        $tbl_wiki_conf = $this->tbl_wiki_conf;
6162
        $condition_session = $this->condition_session;
6163
        $groupfilter = $this->groupfilter;
6164
        $page = $this->page;
6165
        $course_id = $this->course_id;
6166
        $groupId = $this->group_id;
6167
        $userId = api_get_user_id();
6168
6169
        if (api_get_session_id() != 0 &&
6170
            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...
6171
        ) {
6172
            api_not_allowed();
6173
        }
6174
6175
        $sql = 'SELECT *
6176
                FROM '.$tbl_wiki.' w INNER JOIN '.$tbl_wiki_conf.' c
6177
                ON  (w.c_id = c.c_id AND w.page_id = c.page_id)
6178
                WHERE
6179
    		        w.c_id = '.$course_id.' AND
6180
                    w.reflink= "'.Database::escape_string($page).'" AND
6181
                    w.'.$groupfilter.$condition_session.'
6182
                ORDER BY id DESC';
6183
        $result = Database::query($sql);
6184
        $row = Database::fetch_array($result);
6185
6186
        // we do not need a while loop since we are always displaying the last version
6187
        if ($row['content'] == '' && $row['title'] == '' && $page == '') {
6188
            Display::addFlash(
6189
                Display::return_message(
6190
                    get_lang('MustSelectPage'),
6191
                    'error',
6192
                    false
6193
                )
6194
            );
6195
6196
            return;
6197
        } elseif ($row['content'] == '' && $row['title'] == '' && $page == 'index') {
6198
6199
            // Table structure for better export to pdf
6200
            $default_table_for_content_Start = '<table align="center" border="0"><tr><td align="center">';
6201
            $default_table_for_content_End = '</td></tr></table>';
6202
            $content = $default_table_for_content_Start.sprintf(
6203
                    get_lang('DefaultContent'),
6204
                    api_get_path(WEB_IMG_PATH)
6205
                ).$default_table_for_content_End;
6206
            $title = get_lang('DefaultTitle');
6207
            $page_id = 0;
6208
        } else {
6209
            $content = api_html_entity_decode($row['content']);
6210
            $title = api_html_entity_decode($row['title']);
6211
            $page_id = $row['page_id'];
6212
        }
6213
6214
        // Only teachers and platform admin can edit the index page.
6215
        // Only teachers and platform admin can edit an assignment teacher.
6216
        // And users in groups
6217
6218
        if (($row['reflink'] == 'index' || $row['reflink'] == '' || $row['assignment'] == 1) &&
6219
            (!api_is_allowed_to_edit(
6220
                    false,
6221
                    true
6222
                ) && $groupId == 0) && !api_is_allowed_in_course()
6223
        ) {
6224
            Display::addFlash(
6225
                Display::return_message(
6226
                    get_lang('OnlyEditPagesCourseManager'),
6227
                    'error'
6228
                )
6229
            );
6230
        } else {
6231
            $PassEdit = false;
6232
            // Check if is a wiki group
6233
            if (!empty($groupId)) {
6234
                $groupInfo = GroupManager::get_group_properties($groupId);
6235
                //Only teacher, platform admin and group members can edit a wiki group
6236
                if (api_is_allowed_to_edit(false, true) ||
6237
                    api_is_platform_admin() ||
6238
                    GroupManager::is_user_in_group($userId, $groupInfo)
6239
                ) {
6240
                    $PassEdit = true;
6241
                } else {
6242
                    Display::addFlash(
6243
                        Display::return_message(
6244
                            get_lang('OnlyEditPagesGroupMembers')
6245
                        )
6246
                    );
6247
                }
6248
            } else {
6249
                $PassEdit = true;
6250
            }
6251
6252
            $icon_assignment = null;
6253
            // check if is a assignment
6254
            if ($row['assignment'] == 1) {
6255
                Display::addFlash(
6256
                    Display::return_message(get_lang('EditAssignmentWarning'))
6257
                );
6258
6259
                $icon_assignment = Display::return_icon(
6260
                    'wiki_assignment.png',
6261
                    get_lang('AssignmentDescExtra'),
6262
                    '',
6263
                    ICON_SIZE_SMALL
6264
                );
6265
            } elseif ($row['assignment'] == 2) {
6266
                $icon_assignment = Display::return_icon(
6267
                    'wiki_work.png',
6268
                    get_lang('AssignmentWorkExtra'),
6269
                    '',
6270
                    ICON_SIZE_SMALL
6271
                );
6272
                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...
6273
                    if (api_is_allowed_to_edit(
6274
                            false,
6275
                            true
6276
                        ) || api_is_platform_admin()) {
6277
                        $PassEdit = true;
6278
                    } else {
6279
                        Display::addFlash(
6280
                            Display::return_message(
6281
                                get_lang('LockByTeacher'),
6282
                                'warning'
6283
                            )
6284
                        );
6285
                        $PassEdit = false;
6286
                    }
6287
                } else {
6288
                    $PassEdit = true;
6289
                }
6290
            }
6291
6292
            if ($PassEdit) {
6293
                //show editor if edit is allowed <<<<<
6294
                if ($row['editlock'] == 1 &&
6295
                    (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...
6296
                        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...
6297
                ) {
6298
                    Display::addFlash(
6299
                        Display::return_message(
6300
                            get_lang('PageLockedExtra')
6301
                        )
6302
                    );
6303
                } else {
6304
                    // Check tasks
6305
                    if (!empty($row['startdate_assig']) && time() <
6306
                        api_strtotime($row['startdate_assig'])
6307
                    ) {
6308
                        $message = get_lang(
6309
                                'TheTaskDoesNotBeginUntil'
6310
                            ).': '.api_get_local_time($row['startdate_assig']);
6311
6312
                        Display::addFlash(
6313
                            Display::return_message(
6314
                                $message,
6315
                                'warning'
6316
                            )
6317
                        );
6318
6319
                        if (!api_is_allowed_to_edit(false, true)) {
6320
                            $this->redirectHome();
6321
                        }
6322
                    }
6323
6324
                    if (!empty($row['enddate_assig']) &&
6325
                        time() > strtotime($row['enddate_assig']) &&
6326
                        $row['delayedsubmit'] == 0
6327
                    ) {
6328
                        $message = get_lang(
6329
                                'TheDeadlineHasBeenCompleted'
6330
                            ).': '.api_get_local_time($row['enddate_assig']);
6331
                        Display::addFlash(
6332
                            Display::return_message(
6333
                                $message,
6334
                                'warning'
6335
                            )
6336
                        );
6337
                        if (!api_is_allowed_to_edit(false, true)) {
6338
                            $this->redirectHome();
6339
                        }
6340
                    }
6341
6342
                    if (!empty($row['max_version']) && $row['version'] >= $row['max_version']) {
6343
                        $message = get_lang('HasReachedMaxiNumVersions');
6344
                        Display::addFlash(
6345
                            Display::return_message(
6346
                                $message,
6347
                                'warning'
6348
                            )
6349
                        );
6350
                        if (!api_is_allowed_to_edit(false, true)) {
6351
                            $this->redirectHome();
6352
                        }
6353
                    }
6354
6355
                    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

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

6521
                    self::/** @scrutinizer ignore-call */ 
6522
                          setForm($form, $row);
Loading history...
6522
                    $form->addElement('hidden', 'title');
6523
                    $form->addButtonSave(get_lang('Save'), 'SaveWikiChange');
6524
                    $row['title'] = $title;
6525
                    $row['page_id'] = $page_id;
6526
                    $row['reflink'] = $page;
6527
                    $row['content'] = $content;
6528
6529
                    $form->setDefaults($row);
6530
                    $form->display();
6531
6532
                    // Saving a change
6533
                    if ($form->validate()) {
6534
                        $versionFromSession = Session::read('_version');
6535
                        if (empty($_POST['title'])) {
6536
                            Display::addFlash(
6537
                                Display::return_message(
6538
                                    get_lang("NoWikiPageTitle"),
6539
                                    'error'
6540
                                )
6541
                            );
6542
                        } 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

6542
                        } elseif (!self::/** @scrutinizer ignore-call */ double_post($_POST['wpost_id'])) {
Loading history...
6543
                            //double post
6544
                        } 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...
6545
                            //prevent concurrent users and double version
6546
                            Display::addFlash(
6547
                                Display::return_message(
6548
                                    get_lang("EditedByAnotherUser"),
6549
                                    'error'
6550
                                )
6551
                            );
6552
                        } else {
6553
                            $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

6553
                            /** @scrutinizer ignore-call */ 
6554
                            $returnMessage = self::save_wiki(
Loading history...
6554
                                $form->exportValues()
6555
                            );
6556
                            Display::addFlash(
6557
                                Display::return_message(
6558
                                    $returnMessage,
6559
                                    'confirmation'
6560
                                )
6561
                            );
6562
                        }
6563
                        $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

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

6946
                    self::/** @scrutinizer ignore-call */ 
6947
                          export_to_pdf($_GET['wiki_id'], api_get_course_id());
Loading history...
6947
                    break;
6948
                }
6949
                break;
6950
            case 'export2doc':
6951
                if (isset($_GET['wiki_id'])) {
6952
                    $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

6952
                    /** @scrutinizer ignore-call */ 
6953
                    $export2doc = self::export2doc($_GET['wiki_id']);
Loading history...
6953
                    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...
6954
                        Display::addFlash(
6955
                            Display::return_message(
6956
                                get_lang('ThePageHasBeenExportedToDocArea'),
6957
                                'confirmation',
6958
                                false
6959
                            )
6960
                        );
6961
                    }
6962
                }
6963
                break;
6964
            case 'restorepage':
6965
                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

6965
                self::/** @scrutinizer ignore-call */ 
6966
                      restorePage();
Loading history...
6966
                break;
6967
            case 'more':
6968
                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

6968
                self::/** @scrutinizer ignore-call */ 
6969
                      getStatsTable();
Loading history...
6969
                break;
6970
            case 'statistics':
6971
                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

6971
                self::/** @scrutinizer ignore-call */ 
6972
                      getStats();
Loading history...
6972
                break;
6973
            case 'mactiveusers':
6974
                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

6974
                self::/** @scrutinizer ignore-call */ 
6975
                      getActiveUsers($action);
Loading history...
6975
                break;
6976
            case 'usercontrib':
6977
                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

6977
                self::/** @scrutinizer ignore-call */ 
6978
                      getUserContributions($_GET['user_id'], $action);
Loading history...
6978
                break;
6979
            case 'mostchanged':
6980
                $this->getMostChangedPages($action);
6981
                break;
6982
            case 'mvisited':
6983
                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

6983
                self::/** @scrutinizer ignore-call */ 
6984
                      getMostVisited();
Loading history...
6984
                break;
6985
            case 'wanted':
6986
                $this->getWantedPages();
6987
                break;
6988
            case 'orphaned':
6989
                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

6989
                self::/** @scrutinizer ignore-call */ 
6990
                      getOrphaned();
Loading history...
6990
                break;
6991
            case 'mostlinked':
6992
                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

6992
                self::/** @scrutinizer ignore-call */ 
6993
                      getMostLinked();
Loading history...
6993
                break;
6994
            case 'delete':
6995
                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

6995
                self::/** @scrutinizer ignore-call */ 
6996
                      deletePageWarning($page);
Loading history...
6996
                break;
6997
            case 'deletewiki':
6998
                $title = '<div class="actions">'.get_lang(
6999
                        'DeleteWiki'
7000
                    ).'</div>';
7001
                if (api_is_allowed_to_edit(
7002
                        false,
7003
                        true
7004
                    ) || api_is_platform_admin()) {
7005
                    $message = get_lang('ConfirmDeleteWiki');
7006
                    $message .= '<p>
7007
                        <a href="index.php?'.api_get_cidreq().'">'.get_lang(
7008
                            'No'
7009
                        ).'</a>
7010
                        &nbsp;&nbsp;|&nbsp;&nbsp;
7011
                        <a href="'.api_get_self().'?'.api_get_cidreq(
7012
                        ).'&action=deletewiki&delete=yes">'.
7013
                        get_lang('Yes').'</a>
7014
                    </p>';
7015
7016
                    if (!isset($_GET['delete'])) {
7017
                        Display::addFlash(
7018
                            $title.Display::return_message(
7019
                                $message,
7020
                                'warning',
7021
                                false
7022
                            )
7023
                        );
7024
                    }
7025
                } else {
7026
                    Display::addFlash(
7027
                        Display::return_message(
7028
                            get_lang("OnlyAdminDeleteWiki"),
7029
                            'normal',
7030
                            false
7031
                        )
7032
                    );
7033
                }
7034
7035
                if (api_is_allowed_to_edit(
7036
                        false,
7037
                        true
7038
                    ) || api_is_platform_admin()) {
7039
                    if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
7040
                        $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

7040
                        /** @scrutinizer ignore-call */ 
7041
                        $return_message = self::delete_wiki();
Loading history...
7041
                        Display::addFlash(
7042
                            Display::return_message(
7043
                                $return_message,
7044
                                'confirmation',
7045
                                false
7046
                            )
7047
                        );
7048
                        $this->redirectHome();
7049
                    }
7050
                }
7051
                break;
7052
            case 'searchpages':
7053
                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

7053
                self::/** @scrutinizer ignore-call */ 
7054
                      getSearchPages($action);
Loading history...
7054
                break;
7055
            case 'links':
7056
                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

7056
                self::/** @scrutinizer ignore-call */ 
7057
                      getLinks($page);
Loading history...
7057
                break;
7058
            case 'addnew':
7059
                if (api_get_session_id() != 0 && api_is_allowed_to_session_edit(
7060
                        false,
7061
                        true
7062
                    ) == 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...
7063
                    api_not_allowed();
7064
                }
7065
                $groupInfo = GroupManager::get_group_properties(
7066
                    api_get_group_id()
7067
                );
7068
                echo '<div class="actions">'.get_lang('AddNew').'</div>';
7069
                echo '<br/>';
7070
                //first, check if page index was created. chektitle=false
7071
                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

7071
                if (self::/** @scrutinizer ignore-call */ checktitle('index')) {
Loading history...
7072
                    if (api_is_allowed_to_edit(false, true) ||
7073
                        api_is_platform_admin() ||
7074
                        GroupManager::is_user_in_group(
7075
                            api_get_user_id(),
7076
                            $groupInfo
7077
                        ) ||
7078
                        api_is_allowed_in_course()
7079
                    ) {
7080
                        Display::addFlash(
7081
                            Display::return_message(
7082
                                get_lang('GoAndEditMainPage'),
7083
                                'normal',
7084
                                false
7085
                            )
7086
                        );
7087
                    } else {
7088
                        Display::addFlash(
7089
                            Display::return_message(
7090
                                get_lang('WikiStandBy'),
7091
                                'normal',
7092
                                false
7093
                            )
7094
                        );
7095
                    }
7096
                } 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

7096
                } elseif (self::/** @scrutinizer ignore-call */ check_addnewpagelock(
Loading history...
7097
                    ) == 0 && (api_is_allowed_to_edit(
7098
                            false,
7099
                            true
7100
                        ) == 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...
7101
                    Display::addFlash(
7102
                        Display::return_message(
7103
                            get_lang('AddPagesLocked'),
7104
                            'error',
7105
                            false
7106
                        )
7107
                    );
7108
                } else {
7109
                    $groupInfo = GroupManager::get_group_properties(
7110
                        api_get_group_id()
7111
                    );
7112
                    if (api_is_allowed_to_edit(false, true) ||
7113
                        api_is_platform_admin() ||
7114
                        GroupManager::is_user_in_group(
7115
                            api_get_user_id(),
7116
                            $groupInfo
7117
                        ) ||
7118
                        $_GET['group_id'] == 0
7119
                    ) {
7120
                        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

7120
                        self::/** @scrutinizer ignore-call */ 
7121
                              display_new_wiki_form();
Loading history...
7121
                    } else {
7122
                        Display::addFlash(
7123
                            Display::return_message(
7124
                                get_lang('OnlyAddPagesGroupMembers'),
7125
                                'normal',
7126
                                false
7127
                            )
7128
                        );
7129
                    }
7130
                }
7131
                break;
7132
            case 'show':
7133
                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

7133
                self::/** @scrutinizer ignore-call */ 
7134
                      display_wiki_entry($page);
Loading history...
7134
                break;
7135
            case 'showpage':
7136
                self::display_wiki_entry($page);
7137
                break;
7138
            case 'edit':
7139
                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

7139
                self::/** @scrutinizer ignore-call */ 
7140
                      editPage();
Loading history...
7140
                break;
7141
            case 'history':
7142
                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

7142
                self::/** @scrutinizer ignore-call */ 
7143
                      getHistory();
Loading history...
7143
                break;
7144
            case 'recentchanges':
7145
                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

7145
                self::/** @scrutinizer ignore-call */ 
7146
                      recentChanges($page, $action);
Loading history...
7146
                break;
7147
            case 'allpages':
7148
                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

7148
                self::/** @scrutinizer ignore-call */ 
7149
                      allPages($action);
Loading history...
7149
                break;
7150
            case 'discuss':
7151
                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

7151
                self::/** @scrutinizer ignore-call */ 
7152
                      getDiscuss($page);
Loading history...
7152
                break;
7153
            case 'export_to_doc_file':
7154
                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

7154
                self::/** @scrutinizer ignore-call */ 
7155
                      exportTo($_GET['id'], 'odt');
Loading history...
7155
                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...
7156
                break;
7157
        }
7158
    }
7159
7160
    /**
7161
     * Redirect to home
7162
     */
7163
    public function redirectHome()
7164
    {
7165
        $redirectUrl = $this->url.'&action=showpage&title=index';
7166
        header('Location: '.$redirectUrl.'&'.api_get_cidreq());
7167
        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...
7168
    }
7169
7170
    /**
7171
     * Export wiki content in a ODF
7172
     * @param int $id
7173
     * @param string int
7174
     * @return bool
7175
     */
7176
    public function exportTo($id, $format = 'doc')
7177
    {
7178
        $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

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