Test Setup Failed
Push — master ( f71949...6c6bd7 )
by Julito
55:21
created

Wiki::getUserContributions()   D

Complexity

Conditions 9
Paths 24

Size

Total Lines 96
Code Lines 73

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 73
nc 24
nop 2
dl 0
loc 96
rs 4.9572
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(TABLE_WIKI_DISCUSS);
49
        $this->tbl_wiki_mailcue = Database::get_course_table(TABLE_WIKI_MAILCUE);
50
        $this->tbl_wiki_conf = Database::get_course_table(TABLE_WIKI_CONF);
51
52
        $this->session_id = api_get_session_id();
53
        $this->condition_session = api_get_session_condition($this->session_id);
54
        $this->course_id = api_get_course_int_id();
55
        $this->group_id = api_get_group_id();
56
57
        if (!empty($this->group_id)) {
58
            $this->groupfilter = ' group_id="'.$this->group_id.'"';
59
        }
60
        $this->courseInfo = api_get_course_info();
61
        $this->url = api_get_path(WEB_CODE_PATH).'wiki/index.php?'.api_get_cidreq();
62
    }
63
64
    /**
65
     * Check whether this title is already used
66
     * @param string $link
67
     *
68
     *
69
     * @return bool  False if title is already taken
70
     * @author Patrick Cool <[email protected]>, Ghent University
71
     **/
72 View Code Duplication
    public function checktitle($link)
73
    {
74
        $tbl_wiki = $this->tbl_wiki;
75
        $condition_session = $this->condition_session;
76
        $course_id = $this->course_id;
77
        $groupfilter = $this->groupfilter;
78
79
        $sql = 'SELECT * FROM '.$tbl_wiki.'
80
                WHERE
81
                    c_id = '.$course_id.' AND
82
                    reflink="'.Database::escape_string($link).'" AND
83
                    '.$groupfilter.$condition_session.'';
84
        $result = Database::query($sql);
85
        $numberofresults = Database::num_rows($result);
86
        // the value has not been found and is this available
87
        if ($numberofresults == 0) {
88
            return true;
89
        } else {
90
            // the value has been found
91
            return false;
92
        }
93
    }
94
95
    /**
96
     * check wikilinks that has a page
97
     * @author Juan Carlos Raña <[email protected]>
98
     * @param string $input
99
     *
100
     * @return string
101
     **/
102
    public function links_to($input)
103
    {
104
        $input_array = preg_split("/(\[\[|\]\])/", $input, -1, PREG_SPLIT_DELIM_CAPTURE);
105
        $all_links = array();
106
107
        foreach ($input_array as $key => $value) {
108
            if (isset($input_array[$key - 1]) && $input_array[$key - 1] == '[[' &&
109
                isset($input_array[$key + 1]) && $input_array[$key + 1] == ']]'
110
            ) {
111 View Code Duplication
                if (api_strpos($value, "|") !== false) {
112
                    $full_link_array = explode("|", $value);
113
                    $link = trim($full_link_array[0]);
114
                    $title = trim($full_link_array[1]);
115
                } else {
116
                    $link = trim($value);
117
                    $title = trim($value);
118
                }
119
                unset($input_array[$key - 1]);
120
                unset($input_array[$key + 1]);
121
                //replace blank spaces by _ within the links. But to remove links at the end add a blank space
122
                $all_links[] = Database::escape_string(str_replace(' ', '_', $link)).' ';
123
            }
124
        }
125
        $output = implode($all_links);
126
127
        return $output;
128
    }
129
130
    /**
131
     * detect and add style to external links
132
     * @author Juan Carlos Raña Trabado
133
     **/
134
    public function detect_external_link($input)
135
    {
136
        $exlink = 'href=';
137
        $exlinkStyle = 'class="wiki_link_ext" href=';
138
        $output = str_replace($exlink, $exlinkStyle, $input);
139
140
        return $output;
141
    }
142
143
    /**
144
     * detect and add style to anchor links
145
     * @author Juan Carlos Raña Trabado
146
     **/
147
    public function detect_anchor_link($input)
148
    {
149
        $anchorlink = 'href="#';
150
        $anchorlinkStyle = 'class="wiki_anchor_link" href="#';
151
        $output = str_replace($anchorlink, $anchorlinkStyle, $input);
152
153
        return $output;
154
    }
155
156
    /**
157
     * detect and add style to mail links
158
     * author Juan Carlos Raña Trabado
159
     **/
160
    public function detect_mail_link($input)
161
    {
162
        $maillink = 'href="mailto';
163
        $maillinkStyle = 'class="wiki_mail_link" href="mailto';
164
        $output = str_replace($maillink, $maillinkStyle, $input);
165
166
        return $output;
167
    }
168
169
    /**
170
     * detect and add style to ftp links
171
     * @author Juan Carlos Raña Trabado
172
     **/
173
    public function detect_ftp_link($input)
174
    {
175
        $ftplink = 'href="ftp';
176
        $ftplinkStyle = 'class="wiki_ftp_link" href="ftp';
177
        $output = str_replace($ftplink, $ftplinkStyle, $input);
178
179
        return $output;
180
    }
181
182
    /**
183
     * detect and add style to news links
184
     * @author Juan Carlos Raña Trabado
185
     **/
186
    public function detect_news_link($input)
187
    {
188
        $newslink = 'href="news';
189
        $newslinkStyle = 'class="wiki_news_link" href="news';
190
        $output = str_replace($newslink, $newslinkStyle, $input);
191
192
        return $output;
193
    }
194
195
    /**
196
     * detect and add style to irc links
197
     * @author Juan Carlos Raña Trabado
198
     **/
199
    public function detect_irc_link($input)
200
    {
201
        $irclink = 'href="irc';
202
        $irclinkStyle = 'class="wiki_irc_link" href="irc';
203
        $output = str_replace($irclink, $irclinkStyle, $input);
204
205
        return $output;
206
    }
207
208
    /**
209
     * This function allows users to have [link to a title]-style links like in most regular wikis.
210
     * It is true that the adding of links is probably the most anoying part of Wiki for the people
211
     * who know something about the wiki syntax.
212
     * @author Patrick Cool <[email protected]>, Ghent University
213
     * Improvements [[]] and [[ | ]]by Juan Carlos Raña
214
     * Improvements internal wiki style and mark group by Juan Carlos Raña
215
     **/
216
    public function make_wiki_link_clickable($input)
217
    {
218
        $groupId = api_get_group_id();
219
        //now doubles brackets
220
        $input_array = preg_split("/(\[\[|\]\])/", $input, -1, PREG_SPLIT_DELIM_CAPTURE);
221
222
        foreach ($input_array as $key => $value) {
223
            //now doubles brackets
224
            if (isset($input_array[$key - 1]) &&
225
                $input_array[$key - 1] == '[[' && $input_array[$key + 1] == ']]'
226
            ) {
227
                // now full wikilink
228 View Code Duplication
                if (api_strpos($value, "|") !== false) {
229
                    $full_link_array = explode("|", $value);
230
                    $link = trim(strip_tags($full_link_array[0]));
231
                    $title = trim($full_link_array[1]);
232
                } else {
233
                    $link = trim(strip_tags($value));
234
                    $title = trim($value);
235
                }
236
237
                //if wikilink is homepage
238
                if ($link == 'index') {
239
                    $title = get_lang('DefaultTitle');
240
                }
241
                if ($link == get_lang('DefaultTitle')) {
242
                    $link = 'index';
243
                }
244
245
                // 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
246
                if (self::checktitle(strtolower(str_replace(' ', '_', $link)))) {
247
                    $link = api_html_entity_decode($link);
248
                    $input_array[$key] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?'.api_get_cidreq().'&action=addnew&amp;title='.Security::remove_XSS($link).'&group_id='.$groupId.'" class="new_wiki_link">'.$title.'</a>';
249
                } else {
250
                    $input_array[$key] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?'.api_get_cidreq().'&action=showpage&amp;title='.urlencode(strtolower(str_replace(' ', '_', $link))).'&group_id='.$groupId.'" class="wiki_link">'.$title.'</a>';
251
                }
252
                unset($input_array[$key - 1]);
253
                unset($input_array[$key + 1]);
254
            }
255
        }
256
        $output = implode('', $input_array);
257
258
        return $output;
259
    }
260
261
    /**
262
     * This function saves a change in a wiki page
263
     * @author Patrick Cool <[email protected]>, Ghent University
264
     * @param array $values
265
     * @return language string saying that the changes are stored
266
     **/
267
    public function save_wiki($values)
268
    {
269
        $tbl_wiki = $this->tbl_wiki;
270
        $tbl_wiki_conf = $this->tbl_wiki_conf;
271
272
        $_course = $this->courseInfo;
273
        $time = api_get_utc_datetime();
274
        $session_id = api_get_session_id();
275
        $groupId = api_get_group_id();
276
        $userId = api_get_user_id();
277
        $groupInfo = GroupManager::get_group_properties($groupId);
278
        $course_id = api_get_course_int_id();
279
280
        $_clean = array(
281
            'task' => '',
282
            'feedback1' => '',
283
            'feedback2' => '',
284
            'feedback3' => '',
285
            'fprogress1' => '',
286
            'fprogress2' => '',
287
            'fprogress3' => '',
288
            'max_text' => 0,
289
            'max_version' => 0,
290
            'delayedsubmit' => '',
291
            'assignment' => 0
292
        );
293
294
        $pageId = intval($values['page_id']);
295
296
        // NOTE: visibility, visibility_disc and ratinglock_disc changes
297
        // are not made here, but through the interce buttons
298
299
        // cleaning the variables
300
        if (api_get_setting('htmlpurifier_wiki') == 'true') {
301
            //$purifier = new HTMLPurifier();
302
            $values['content'] = Security::remove_XSS($values['content']);
303
        }
304
        $version = intval($values['version']) + 1;
305
        $linkTo = self::links_to($values['content']); //and check links content
306
307
        //cleaning config variables
308
        if (!empty($values['task'])) {
309
            $_clean['task'] = $values['task'];
310
        }
311
312
        if (!empty($values['feedback1']) || !empty($values['feedback2']) || !empty($values['feedback3'])) {
313
            $_clean['feedback1'] = $values['feedback1'];
314
            $_clean['feedback2'] = $values['feedback2'];
315
            $_clean['feedback3'] = $values['feedback3'];
316
            $_clean['fprogress1'] = $values['fprogress1'];
317
            $_clean['fprogress2'] = $values['fprogress2'];
318
            $_clean['fprogress3'] = $values['fprogress3'];
319
        }
320
321 View Code Duplication
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
322
            $_clean['startdate_assig'] = $values['startdate_assig'];
323
        } else {
324
            $_clean['startdate_assig'] = null;
325
        }
326
327 View Code Duplication
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
328
            $_clean['enddate_assig'] = $values['enddate_assig'];
329
        } else {
330
            $_clean['enddate_assig'] = null;
331
        }
332
333
        if (isset($values['delayedsubmit'])) {
334
            $_clean['delayedsubmit'] = $values['delayedsubmit'];
335
        }
336
337
        if (!empty($values['max_text']) || !empty($values['max_version'])) {
338
            $_clean['max_text'] = $values['max_text'];
339
            $_clean['max_version'] = $values['max_version'];
340
        }
341
342
        $values['assignment'] = isset($values['assignment']) ? $values['assignment'] : 0;
343
        $values['page_id'] = isset($values['page_id']) ? $values['page_id'] : 0;
344
345
        $params = [
346
            'c_id' => $course_id,
347
            'addlock' => 1,
348
            'visibility' => 1,
349
            'visibility_disc' => 1,
350
            'addlock_disc' => 1,
351
            'ratinglock_disc' => 1,
352
            'page_id' => $pageId,
353
            'reflink' => trim($values['reflink']),
354
            'title' => trim($values['title']),
355
            'content' => $values['content'],
356
            'user_id' => $userId,
357
            'group_id' => $groupId,
358
            'dtime' => $time,
359
            'assignment' => $values['assignment'],
360
            'comment' => $values['comment'],
361
            'progress' => $values['progress'],
362
            'version' => $version,
363
            'linksto' => $linkTo,
364
            'user_ip' => $_SERVER['REMOTE_ADDR'],
365
            'session_id' => $session_id,
366
            'page_id' => $values['page_id'],
367
            'editlock' => 0,
368
            'is_editing' => 0,
369
            'time_edit' => $time,
370
            'tag' => ''
371
        ];
372
373
        $id = Database::insert($tbl_wiki, $params);
374
375
        if ($id > 0) {
376
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
377
            Database::query($sql);
378
379
            // insert into item_property
380
            api_item_property_update(
381
                $_course,
382
                TOOL_WIKI,
383
                $id,
384
                'WikiAdded',
385
                $userId,
386
                $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 277 can also be of type null; however, api_item_property_update() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
387
            );
388
389 View Code Duplication
            if ($values['page_id'] == 0) {
390
                $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
391
                        WHERE c_id = '.$course_id.' AND iid ="'.$id.'"';
392
                Database::query($sql);
393
            }
394
        }
395
396
        // Update wiki config
397
        if ($values['reflink'] == 'index' && $version == 1) {
398
            $params = [
399
                'c_id' => $course_id,
400
                'page_id' => $id,
401
                'task' => $_clean['task'],
402
                'feedback1' => $_clean['feedback1'],
403
                'feedback2' => $_clean['feedback2'],
404
                'feedback3' => $_clean['feedback3'],
405
                'fprogress1' => $_clean['fprogress1'],
406
                'fprogress2' => $_clean['fprogress2'],
407
                'fprogress3' => $_clean['fprogress3'],
408
                'max_text' => intval($_clean['max_text']),
409
                'max_version' => intval($_clean['max_version']),
410
                'startdate_assig' => $_clean['startdate_assig'],
411
                'enddate_assig' => $_clean['enddate_assig'],
412
                'delayedsubmit' => $_clean['delayedsubmit']
413
            ];
414
            Database::insert($tbl_wiki_conf, $params);
415
        } else {
416
            $params = [
417
                'task' => $_clean['task'],
418
                'feedback1' => $_clean['feedback1'],
419
                'feedback2' => $_clean['feedback2'],
420
                'feedback3' => $_clean['feedback3'],
421
                'fprogress1' => $_clean['fprogress1'],
422
                'fprogress2' => $_clean['fprogress2'],
423
                'fprogress3' => $_clean['fprogress3'],
424
                'max_text' => intval($_clean['max_text']),
425
                'max_version' => intval($_clean['max_version']),
426
                'startdate_assig' => $_clean['startdate_assig'],
427
                'enddate_assig' => $_clean['enddate_assig'],
428
                'delayedsubmit' => $_clean['delayedsubmit']
429
            ];
430
            Database::update(
431
                $tbl_wiki_conf,
432
                $params,
433
                ['page_id = ? AND c_id = ?' => [$pageId, $course_id]]
434
            );
435
        }
436
437
        api_item_property_update(
438
            $_course,
439
            'wiki',
440
            $id,
441
            'WikiAdded',
442
            $userId,
443
            $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 277 can also be of type null; however, api_item_property_update() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
444
        );
445
        self::check_emailcue($_clean['reflink'], 'P', $time, $userId);
0 ignored issues
show
Bug introduced by
It seems like $time defined by api_get_utc_datetime() on line 273 can also be of type null or object<DateTime>; however, Wiki::check_emailcue() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
446
        $this->setWikiData($id);
0 ignored issues
show
Bug introduced by
It seems like $id defined by \Database::insert($tbl_wiki, $params) on line 373 can also be of type string; however, Wiki::setWikiData() does only seem to accept integer|boolean, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
447
448
        return get_lang('Saved');
449
    }
450
451
    /**
452
     * This function restore a wikipage
453
     * @author Juan Carlos Raña <[email protected]>
454
     * @return string Message of success (to be printed on screen)
455
     **/
456
    public function restore_wikipage(
457
        $r_page_id,
458
        $r_reflink,
459
        $r_title,
460
        $r_content,
461
        $r_group_id,
462
        $r_assignment,
463
        $r_progress,
464
        $c_version,
465
        $r_version,
466
        $r_linksto
467
    ) {
468
        $tbl_wiki = $this->tbl_wiki;
469
        $_course = $this->courseInfo;
470
        $r_user_id = api_get_user_id();
471
        $r_dtime = api_get_utc_datetime();
472
        $r_version = $r_version + 1;
473
        $r_comment = get_lang('RestoredFromVersion').': '.$c_version;
474
        $session_id = api_get_session_id();
475
        $course_id = api_get_course_int_id();
476
        $groupInfo = GroupManager::get_group_properties($r_group_id);
477
478
        $params = [
479
            'c_id' => $course_id,
480
            'page_id' => $r_page_id,
481
            'reflink' => $r_reflink,
482
            'title' => $r_title,
483
            'content' => $r_content,
484
            'user_id' => $r_user_id,
485
            'group_id' => $r_group_id,
486
            'dtime' => $r_dtime,
487
            'assignment' => $r_assignment,
488
            'comment' => $r_comment,
489
            'progress' => $r_progress,
490
            'version' => $r_version,
491
            'linksto' => $r_linksto,
492
            'user_ip' => $_SERVER['REMOTE_ADDR'],
493
            'session_id' => $session_id,
494
        ];
495
        $id = Database::insert($tbl_wiki, $params);
496
497 View Code Duplication
        if ($id) {
498
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
499
            Database::query($sql);
500
501
            api_item_property_update(
502
                $_course,
503
                'wiki',
504
                $id,
505
                'WikiAdded',
506
                api_get_user_id(),
507
                $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($r_group_id) on line 476 can also be of type null; however, api_item_property_update() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
508
            );
509
            self::check_emailcue($r_reflink, 'P', $r_dtime, $r_user_id);
0 ignored issues
show
Bug introduced by
It seems like $r_dtime defined by api_get_utc_datetime() on line 471 can also be of type null or object<DateTime>; however, Wiki::check_emailcue() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
510
        }
511
512
        return get_lang('PageRestored');
513
    }
514
515
    /**
516
     * This function delete a wiki
517
     * @author Juan Carlos Raña <[email protected]>
518
     * @return   string  Message of success (to be printed)
519
     **/
520
    public function delete_wiki()
521
    {
522
        $tbl_wiki = $this->tbl_wiki;
523
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
524
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
525
        $tbl_wiki_conf = $this->tbl_wiki_conf;
526
        $conditionSession = $this->condition_session;
527
        $groupFilter = $this->groupfilter;
528
        $course_id = $this->course_id;
529
530
        $sql = "SELECT page_id FROM $tbl_wiki
531
                WHERE c_id = $course_id AND $groupFilter $conditionSession
532
                ORDER BY id DESC";
533
534
        $result = Database::query($sql);
535
        $pageList = Database::store_result($result);
536
        if ($pageList) {
537
            foreach ($pageList as $pageData) {
538
                $pageId = $pageData['page_id'];
539
                $sql = "DELETE FROM $tbl_wiki_conf
540
                        WHERE c_id = $course_id AND page_id = $pageId";
541
                Database::query($sql);
542
543
                $sql = "DELETE FROM $tbl_wiki_discuss
544
                        WHERE c_id = $course_id AND publication_id = $pageId";
545
                Database::query($sql);
546
            }
547
        }
548
549
        $sql = "DELETE FROM $tbl_wiki_mailcue
550
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
551
        Database::query($sql);
552
553
        $sql = "DELETE FROM $tbl_wiki
554
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
555
        Database::query($sql);
556
557
        return get_lang('WikiDeleted');
558
    }
559
560
    /**
561
     * This function saves a new wiki page.
562
     * @author Patrick Cool <[email protected]>, Ghent University
563
     * @todo consider merging this with the function save_wiki into one single function.
564
     * @return string Message of success
565
     **/
566
    public function save_new_wiki($values)
567
    {
568
        $tbl_wiki = $this->tbl_wiki;
569
        $tbl_wiki_conf = $this->tbl_wiki_conf;
570
        $assig_user_id = $this->assig_user_id;
571
        $_clean = array();
572
573
        // cleaning the variables
574
        $_clean['assignment'] = '';
575
        if (isset($values['assignment'])) {
576
            $_clean['assignment'] = $values['assignment'];
577
        }
578
579
        // session_id
580
        $session_id = api_get_session_id();
581
        // Unlike ordinary pages of pages of assignments.
582
        // Allow create a ordinary page although there is a assignment with the same name
583
        if ($_clean['assignment'] == 2 || $_clean['assignment'] == 1) {
584
            $page = str_replace(' ', '_', $values['title']."_uass".$assig_user_id);
585
        } else {
586
            $page = str_replace(' ', '_', $values['title']);
587
        }
588
        $_clean['reflink'] = $page;
589
        $_clean['title']   = trim($values['title']);
590
        $_clean['content'] = $values['content'];
591
592
        if (api_get_setting('htmlpurifier_wiki') === 'true') {
593
            $purifier = new HTMLPurifier();
594
            $_clean['content'] = $purifier->purify($_clean['content']);
595
        }
596
597
        //re-check after strip_tags if the title is empty
598
        if (empty($_clean['title']) || empty($_clean['reflink'])) {
599
            return false;
600
        }
601
602
        if ($_clean['assignment'] == 2) {
603
            //config by default for individual assignment (students)
604
            //Identifies the user as a creator, not the teacher who created
605
            $_clean['user_id'] = intval($assig_user_id);
606
            $_clean['visibility'] = 0;
607
            $_clean['visibility_disc'] = 0;
608
            $_clean['ratinglock_disc'] = 0;
609
        } else {
610
            $_clean['user_id'] = api_get_user_id();
611
            $_clean['visibility'] = 1;
612
            $_clean['visibility_disc'] = 1;
613
            $_clean['ratinglock_disc'] = 1;
614
        }
615
616
        $_clean['comment'] = $values['comment'];
617
        $_clean['progress'] = $values['progress'];
618
        $_clean['version'] = 1;
619
620
        $groupId = api_get_group_id();
621
        $groupInfo = GroupManager::get_group_properties($groupId);
622
623
        //check wikilinks
624
        $_clean['linksto'] = self::links_to($_clean['content']);
625
626
        // cleaning config variables
627
        $_clean['task'] = isset($values['task']) ? $values['task'] : '';
628
        $_clean['feedback1'] = isset($values['feedback1']) ? $values['feedback1'] : '';
629
        $_clean['feedback2'] = isset($values['feedback2']) ? $values['feedback2'] : '';
630
        $_clean['feedback3'] = isset($values['feedback3']) ? $values['feedback3'] : '';
631
        $_clean['fprogress1'] = isset($values['fprogress1']) ? $values['fprogress1'] : '';
632
        $_clean['fprogress2'] = isset($values['fprogress2']) ? $values['fprogress2'] : '';
633
        $_clean['fprogress3'] = isset($values['fprogress3']) ? $values['fprogress3'] : '';
634
635 View Code Duplication
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
636
            $_clean['startdate_assig'] = $values['startdate_assig'];
637
        } else {
638
            $_clean['startdate_assig'] = null;
639
        }
640
641 View Code Duplication
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
642
            $_clean['enddate_assig'] = $values['enddate_assig'];
643
        } else {
644
            $_clean['enddate_assig'] = null;
645
        }
646
647
        $_clean['delayedsubmit'] = isset($values['delayedsubmit']) ? $values['delayedsubmit'] : '';
648
        $_clean['max_text'] = isset($values['max_text']) ? $values['max_text'] : '';
649
        $_clean['max_version'] = isset($values['max_version']) ? $values['max_version'] : '';
650
651
        $course_id = api_get_course_int_id();
652
653
        // Filter no _uass
654
        if (api_strtoupper(trim($values['title'])) === 'INDEX') {
655
            Display::addFlash(Display::return_message(get_lang('GoAndEditMainPage'), 'warning', false));
656
        } else {
657
            $var = $_clean['reflink'];
658
            $group_id = intval($_GET['group_id']);
659
            if (!self::checktitle($var)) {
660
                return get_lang('WikiPageTitleExist').
661
                '<a href="index.php?action=edit&amp;title='.$var.'&group_id='.$group_id.'">'.
662
                $values['title'].'</a>';
663
            } else {
664
                $dtime = api_get_utc_datetime();
665
666
                $params = [
667
                    'c_id' => $course_id,
668
                    'reflink' => $_clean['reflink'],
669
                    'title' => $_clean['title'],
670
                    'content' => $_clean['content'],
671
                    'user_id' => $_clean['user_id'],
672
                    'group_id' => $groupId,
673
                    'dtime' => $dtime,
674
                    'visibility' => $_clean['visibility'],
675
                    'visibility_disc' => $_clean['visibility_disc'],
676
                    'ratinglock_disc' => $_clean['ratinglock_disc'],
677
                    'assignment' => $_clean['assignment'],
678
                    'comment' => $_clean['comment'],
679
                    'progress' => $_clean['progress'],
680
                    'version' => $_clean['version'],
681
                    'linksto' => $_clean['linksto'],
682
                    'user_ip' => $_SERVER['REMOTE_ADDR'],
683
                    'session_id' => $session_id,
684
                    'addlock_disc' => 1
685
                ];
686
                $id = Database::insert($tbl_wiki, $params);
687
                if ($id > 0) {
688
                    $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
689
                    Database::query($sql);
690
691
                    //insert into item_property
692
                    api_item_property_update(
693
                        api_get_course_info(),
694
                        TOOL_WIKI,
695
                        $id,
696
                        'WikiAdded',
697
                        api_get_user_id(),
698
                        $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 621 can also be of type null; however, api_item_property_update() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
699
                    );
700
701
                    $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
702
                            WHERE c_id = '.$course_id.' AND id = "'.$id.'"';
703
                    Database::query($sql);
704
705
                    // insert wiki config
706
                    $params = [
707
                        'c_id' => $course_id,
708
                        'page_id' => $id,
709
                        'task' => $_clean['task'],
710
                        'feedback1' => $_clean['feedback1'],
711
                        'feedback2' => $_clean['feedback2'],
712
                        'feedback3' => $_clean['feedback3'],
713
                        'fprogress1' => $_clean['fprogress1'],
714
                        'fprogress2' => $_clean['fprogress2'],
715
                        'fprogress3' => $_clean['fprogress3'],
716
                        'max_text' => $_clean['max_text'],
717
                        'max_version' => $_clean['max_version'],
718
                        'startdate_assig' => $_clean['startdate_assig'],
719
                        'enddate_assig' => $_clean['enddate_assig'],
720
                        'delayedsubmit' => $_clean['delayedsubmit']
721
                    ];
722
723
                    Database::insert($tbl_wiki_conf, $params);
724
725
                    $this->setWikiData($id);
0 ignored issues
show
Bug introduced by
It seems like $id defined by \Database::insert($tbl_wiki, $params) on line 686 can also be of type string; however, Wiki::setWikiData() does only seem to accept integer|boolean, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
726
                    self::check_emailcue(0, 'A');
727
                    return get_lang('NewWikiSaved');
728
                }
729
            }
730
        }
731
    }
732
733
    /**
734
     * @param FormValidator $form
735
     * @param array $row
736
     */
737
    public function setForm($form, $row = array())
738
    {
739
        $toolBar = api_is_allowed_to_edit(null, true)
740
            ? array('ToolbarSet' => 'Wiki', 'Width' => '100%', 'Height' => '400')
741
            : array('ToolbarSet' => 'WikiStudent', 'Width' => '100%', 'Height' => '400', 'UserStatus' => 'student');
742
743
        $form->addHtmlEditor('content', get_lang('Content'), false, false, $toolBar);
744
        //$content
745
        $form->addElement('text', 'comment', get_lang('Comments'));
746
        $progress = array('', 10, 20, 30, 40, 50, 60, 70, 80, 90, 100);
747
748
        $form->addElement('select', 'progress', get_lang('Progress'), $progress);
749
750
        if ((api_is_allowed_to_edit(false, true) ||
751
            api_is_platform_admin()) &&
752
            isset($row['reflink']) && $row['reflink'] != 'index'
753
        ) {
754
            $form->addElement('advanced_settings', 'advanced_params', get_lang('AdvancedParameters'));
755
            $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
756
757
            $form->addHtmlEditor(
758
                'task',
759
                get_lang('DescriptionOfTheTask'),
760
                false,
761
                false,
762
                array(
763
                    'ToolbarSet' => 'wiki_task',
764
                    'Width' => '100%',
765
                    'Height' => '200',
766
                )
767
            );
768
769
            $form->addElement('label', null, get_lang('AddFeedback'));
770
            $form->addElement('textarea', 'feedback1', get_lang('Feedback1'));
771
            $form->addElement('select', 'fprogress1', get_lang('FProgress'), $progress);
772
773
            $form->addElement('textarea', 'feedback2', get_lang('Feedback2'));
774
            $form->addElement('select', 'fprogress2', get_lang('FProgress'), $progress);
775
776
            $form->addElement('textarea', 'feedback3', get_lang('Feedback3'));
777
            $form->addElement('select', 'fprogress3', get_lang('FProgress'), $progress);
778
779
            $form->addElement('checkbox', 'initstartdate', null, get_lang('StartDate'), array('id' => 'start_date_toggle'));
780
781
            $style = "display:block";
782
            $row['initstartdate'] = 1;
783
            if (empty($row['startdate_assig'])) {
784
                $style = "display:none";
785
                $row['initstartdate'] = null;
786
            }
787
788
            $form->addElement('html', '<div id="start_date" style="'.$style.'">');
789
            $form->addDatePicker('startdate_assig', '');
790
            $form->addElement('html', '</div>');
791
            $form->addElement('checkbox', 'initenddate', null, get_lang('EndDate'), array('id' => 'end_date_toggle'));
792
793
            $style = "display:block";
794
            $row['initenddate'] = 1;
795
            if (empty($row['enddate_assig'])) {
796
                $style = "display:none";
797
                $row['initenddate'] = null;
798
            }
799
800
            $form->addElement('html', '<div id="end_date" style="'.$style.'">');
801
            $form->addDatePicker('enddate_assig', '');
802
            $form->addElement('html', '</div>');
803
            $form->addElement('checkbox', 'delayedsubmit', null, get_lang('AllowLaterSends'));
804
            $form->addElement('text', 'max_text', get_lang('NMaxWords'));
805
            $form->addElement('text', 'max_version', get_lang('NMaxVersion'));
806
            $form->addElement('checkbox', 'assignment', null, get_lang('CreateAssignmentPage'));
807
            $form->addElement('html', '</div>');
808
        }
809
810
        $form->addElement('hidden', 'page_id');
811
        $form->addElement('hidden', 'reflink');
812
//        $form->addElement('hidden', 'assignment');
813
        $form->addElement('hidden', 'version');
814
        $form->addElement('hidden', 'wpost_id', api_get_unique_id());
815
    }
816
817
    /**
818
     * This function displays the form for adding a new wiki page.
819
     * @author Patrick Cool <[email protected]>, Ghent University
820
     * @return html code
821
     **/
822
    public function display_new_wiki_form()
823
    {
824
        $url = api_get_self().'?'.api_get_cidreq().'&action=addnew&group_id='.api_get_group_id();
825
        $form = new FormValidator('wiki_new', 'post', $url);
826
        $form->addElement('text', 'title', get_lang('Title'));
827
        $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
828
        self::setForm($form);
829
        $title = isset($_GET['title']) ? Security::remove_XSS($_GET['title']) : '';
830
        $form->setDefaults(['title' => $title]);
831
        $form->addElement('button', 'SaveWikiNew', get_lang('Save'));
832
        $form->display();
833
834
        if ($form->validate()) {
835
            $values = $form->exportValues();
836
            if (isset($values['startdate_assig']) &&
837
                isset($values['enddate_assig']) &&
838
                strtotime($values['startdate_assig']) > strtotime($values['enddate_assig'])
839
            ) {
840
                Display::addFlash(
841
                    Display::return_message(
842
                        get_lang("EndDateCannotBeBeforeTheStartDate"),
843
                        'error',
844
                        false
845
                    )
846
                );
847
            } 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...
848
                //double post
849
850
            } else {
851
                if (isset($values['assignment']) && $values['assignment'] == 1) {
852
                    self::auto_add_page_users($values);
853
                }
854
855
                $return_message = self::save_new_wiki($values);
856
857 View Code Duplication
                if ($return_message == false) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $return_message of type false|null|string against false; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
858
                    Display::addFlash(Display::return_message(get_lang('NoWikiPageTitle'), 'error', false));
859
                } else {
860
                    Display::addFlash(Display::return_message($return_message, 'confirmation', false));
861
                }
862
863
                $wikiData = self::getWikiData();
864
                $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq();
865
                header('Location: '.$redirectUrl);
866
                exit;
867
            }
868
        }
869
    }
870
871
    /**
872
     * This function displays a wiki entry
873
     * @author Patrick Cool <[email protected]>, Ghent University
874
     * @author Juan Carlos Raña Trabado
875
     * @param string $newtitle
876
     * @return string html code
877
     **/
878
    public function display_wiki_entry($newtitle)
879
    {
880
        $tbl_wiki = $this->tbl_wiki;
881
        $tbl_wiki_conf = $this->tbl_wiki_conf;
882
        $condition_session = $this->condition_session;
883
        $groupfilter = $this->groupfilter;
884
        $page = $this->page;
885
886
        $session_id = api_get_session_id();
887
        $course_id = api_get_course_int_id();
888
889
        if ($newtitle) {
890
            $pageMIX = $newtitle; //display the page after it is created
891
        } else {
892
            $pageMIX = $page; //display current page
893
        }
894
895
        $filter = null;
896
        if (isset($_GET['view']) && $_GET['view']) {
897
            $_clean['view'] = Database::escape_string($_GET['view']);
898
            $filter = ' AND w.id="'.$_clean['view'].'"';
899
        }
900
901
        // First, check page visibility in the first page version
902
        $sql = 'SELECT * FROM '.$tbl_wiki.'
903
                WHERE
904
                    c_id = '.$course_id.' AND
905
                    reflink="'.Database::escape_string($pageMIX).'" AND
906
                   '.$groupfilter.$condition_session.'
907
                ORDER BY id ASC';
908
        $result = Database::query($sql);
909
        $row = Database::fetch_array($result, 'ASSOC');
910
911
        $KeyVisibility = $row['visibility'];
912
913
        // second, show the last version
914
        $sql = 'SELECT * FROM '.$tbl_wiki.' w
915
                INNER JOIN '.$tbl_wiki_conf.' wc
916
                ON (wc.page_id = w.page_id AND wc.c_id = w.c_id)
917
                WHERE
918
                    w.c_id 		  = '.$course_id.' AND
919
                    w.reflink	  = "'.Database::escape_string($pageMIX).'" AND
920
                    w.session_id  = '.$session_id.' AND
921
                    w.'.$groupfilter.'  '.$filter.'
922
                ORDER BY id DESC';
923
924
        $result = Database::query($sql);
925
        // we do not need a while loop since we are always displaying the last version
926
        $row = Database::fetch_array($result, 'ASSOC');
927
928
        //log users access to wiki (page_id)
929
        if (!empty($row['page_id'])) {
930
            Event::addEvent(LOG_WIKI_ACCESS, LOG_WIKI_PAGE_ID, $row['page_id']);
931
        }
932
        //update visits
933 View Code Duplication
        if ($row['id']) {
934
            $sql = 'UPDATE '.$tbl_wiki.' SET hits=(hits+1)
935
                    WHERE c_id = '.$course_id.' AND id='.$row['id'].'';
936
            Database::query($sql);
937
        }
938
939
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
940
941
        // if both are empty and we are displaying the index page then we display the default text.
942
        if ($row['content'] == '' && $row['title'] == '' && $page == 'index') {
943
            if (api_is_allowed_to_edit(false, true) ||
944
                api_is_platform_admin() ||
945
                GroupManager::is_user_in_group(api_get_user_id(), $groupInfo) ||
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group...ies(api_get_group_id()) on line 939 can also be of type null; however, GroupManager::is_user_in_group() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
946
                api_is_allowed_in_course()
947
            ) {
948
                //Table structure for better export to pdf
949
                $default_table_for_content_Start = '<table align="center" border="0"><tr><td align="center">';
950
                $default_table_for_content_End = '</td></tr></table>';
951
                $content = $default_table_for_content_Start.
952
                    sprintf(get_lang('DefaultContent'), api_get_path(WEB_IMG_PATH)).
953
                    $default_table_for_content_End;
954
                $title = get_lang('DefaultTitle');
955
            } else {
956
                return Display::addFlash(Display::return_message(get_lang('WikiStandBy'), 'normal', false));
957
            }
958
        } else {
959
            $content = Security::remove_XSS($row['content']);
960
            $title = Security::remove_XSS($row['title']);
961
        }
962
963
        //assignment mode: identify page type
964
        $icon_assignment = null;
965 View Code Duplication
        if ($row['assignment'] == 1) {
966
            $icon_assignment = Display::return_icon(
967
                'wiki_assignment.png',
968
                get_lang('AssignmentDescExtra'),
969
                '',
970
                ICON_SIZE_SMALL
971
            );
972
        } elseif ($row['assignment'] == 2) {
973
            $icon_assignment = Display::return_icon(
974
                'wiki_work.png',
975
                get_lang('AssignmentWork'),
976
                '',
977
                ICON_SIZE_SMALL
978
            );
979
        }
980
981
        // task mode
982
        $icon_task = null;
983
        if (!empty($row['task'])) {
984
            $icon_task = Display::return_icon(
985
                'wiki_task.png',
986
                get_lang('StandardTask'),
987
                '',
988
                ICON_SIZE_SMALL
989
            );
990
        }
991
992
        // Show page. Show page to all users if isn't hide page. Mode assignments: if student is the author, can view
993
        if ($KeyVisibility == "1" ||
994
            api_is_allowed_to_edit(false, true) ||
995
            api_is_platform_admin() ||
996
            ($row['assignment'] == 2 && $KeyVisibility == "0" && (api_get_user_id() == $row['user_id'])) ||
997
            api_is_allowed_in_course()
998
        ) {
999
            $actionsLeft = '';
1000
            // menu edit page
1001
            $editLink = '<a href="index.php?'.api_get_cidreq().'&action=edit&title='.api_htmlentities(urlencode($page)).'"'.self::is_active_navigation_tab('edit').'>'.
1002
                Display::return_icon('edit.png', get_lang('EditThisPage'), '', ICON_SIZE_MEDIUM).'</a>';
1003
1004
            if (api_is_allowed_to_edit(false, true)) {
1005
                $actionsLeft .= $editLink;
1006
            } else {
1007
                if ((api_is_allowed_in_course() ||
1008
                    GroupManager::is_user_in_group(api_get_user_id(), $groupInfo))
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group...ies(api_get_group_id()) on line 939 can also be of type null; however, GroupManager::is_user_in_group() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1009
                ) {
1010
                    $actionsLeft .= $editLink;
1011
                } else {
1012
                    $actionsLeft .= '';
1013
                }
1014
            }
1015
1016
            $actionsRight = '';
1017
1018
            $protect_page = null;
1019
            $lock_unlock_protect = null;
1020
            // page action: protecting (locking) the page
1021 View Code Duplication
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1022
                if (self::check_protect_page() == 1) {
1023
                    $protect_page = Display::return_icon('lock.png', get_lang('PageLockedExtra'), '', ICON_SIZE_MEDIUM);
1024
                    $lock_unlock_protect = 'unlock';
1025
                } else {
1026
                    $protect_page = Display::return_icon('unlock.png', get_lang('PageUnlockedExtra'), '', ICON_SIZE_MEDIUM);
1027
                    $lock_unlock_protect = 'lock';
1028
                }
1029
            }
1030
1031 View Code Duplication
            if ($row['id']) {
1032
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_protect.'&title='.api_htmlentities(urlencode($page)).'">'.
1033
                        $protect_page.'</a>';
1034
            }
1035
1036
            $visibility_page = null;
1037
            $lock_unlock_visibility = null;
1038
            //page action: visibility
1039 View Code Duplication
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1040
                if (self::check_visibility_page() == 1) {
1041
                    $visibility_page = Display::return_icon('visible.png', get_lang('ShowPageExtra'), '', ICON_SIZE_MEDIUM);
1042
                    $lock_unlock_visibility = 'invisible';
1043
1044
                } else {
1045
                    $visibility_page = Display::return_icon('invisible.png', get_lang('HidePageExtra'), '', ICON_SIZE_MEDIUM);
1046
                    $lock_unlock_visibility = 'visible';
1047
                }
1048
            }
1049
1050 View Code Duplication
            if ($row['id']) {
1051
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_visibility.'&title='.api_htmlentities(urlencode($page)).'">'.
1052
                    $visibility_page.'</a>';
1053
            }
1054
1055
            //page action: notification
1056 View Code Duplication
            if (api_is_allowed_to_session_edit()) {
1057
                if (self::check_notify_page($page) == 1) {
1058
                    $notify_page = Display::return_icon('messagebox_info.png', get_lang('NotifyByEmail'), '', ICON_SIZE_MEDIUM);
1059
                    $lock_unlock_notify_page = 'unlocknotify';
1060
                } else {
1061
                    $notify_page = Display::return_icon('mail.png', get_lang('CancelNotifyByEmail'), '', ICON_SIZE_MEDIUM);
1062
                    $lock_unlock_notify_page = 'locknotify';
1063
                }
1064
            }
1065
1066
            // Only available if row['id'] is set
1067
            if ($row['id']) {
1068 View Code Duplication
                if (api_is_allowed_to_session_edit(false, true) && api_is_allowed_to_edit() ||
1069
                    GroupManager::is_user_in_group(api_get_user_id(), $groupInfo)
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group...ies(api_get_group_id()) on line 939 can also be of type null; however, GroupManager::is_user_in_group() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1070
                ) {
1071
                    // menu discuss page
1072
                    $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=discuss&title='.api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('discuss').'>'.
1073
                        Display::return_icon('discuss.png', get_lang('DiscussThisPage'), '', ICON_SIZE_MEDIUM).'</a>';
1074
                }
1075
1076
                //menu history
1077
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=history&title='.api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('history').'>'.
1078
                    Display::return_icon('history.png', get_lang('ShowPageHistory'), '', ICON_SIZE_MEDIUM).'</a>';
1079
                //menu linkspages
1080
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'action=links&title='.api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('links').'>'.
1081
                    Display::return_icon('what_link_here.png', get_lang('LinksPages'), '', ICON_SIZE_MEDIUM).'</a>';
1082
1083
                //menu delete wikipage
1084 View Code Duplication
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1085
                    $actionsRight .= '<a href="index.php?action=delete&'.api_get_cidreq().'&title='.api_htmlentities(urlencode($page)).'"'.self::is_active_navigation_tab('delete').'>'.
1086
                        Display::return_icon('delete.png', get_lang('DeleteThisPage'), '', ICON_SIZE_MEDIUM).'</a>';
1087
                }
1088
1089
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_notify_page.'&title='.api_htmlentities(urlencode($page)).'">'.
1090
                    $notify_page.'</a>';
1091
1092
                // Page action: copy last version to doc area
1093
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1094
                    $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export2doc&wiki_id='.$row['id'].'">'.
1095
                        Display::return_icon('export_to_documents.png', get_lang('ExportToDocArea'), '', ICON_SIZE_MEDIUM).'</a>';
1096
                }
1097
1098
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export_to_pdf&wiki_id='.$row['id'].'">'.
1099
                    Display::return_icon('pdf.png', get_lang('ExportToPDF'), '', ICON_SIZE_MEDIUM).'</a>';
1100
1101
                $unoconv = api_get_configuration_value('unoconv.binaries');
1102 View Code Duplication
                if ($unoconv) {
1103
                    $actionsRight .= '<a href="'.api_get_path(WEB_CODE_PATH).'wiki/index.php?action=export_to_doc_file&id='.$row['id'].'&'.api_get_cidreq().'">'.
1104
                        Display::return_icon('export_doc.png', get_lang('ExportToDoc'), array(), ICON_SIZE_MEDIUM).'</a>';
1105
                }
1106
1107
                //export to print
1108
                ?>
1109
                <script>
1110
                    function goprint() {
1111
                        var a = window.open('','','width=800,height=600');
1112
                        a.document.open("text/html");
1113
                        a.document.write(document.getElementById('wikicontent').innerHTML);
1114
                        a.document.close();
1115
                        a.print();
1116
                    }
1117
                </script>
1118
                <?php
1119
                $actionsRight .= Display::url(
1120
                    Display::return_icon('printer.png', get_lang('Print'), '', ICON_SIZE_MEDIUM),
1121
                    '#',
1122
                    array('onclick' => "javascript: goprint();")
1123
                );
1124
            }
1125
1126
            echo Display::toolbarAction('toolbar-wikistudent', [$actionsLeft, $actionsRight]);
1127
1128
            if (empty($title)) {
1129
                $pageTitle = get_lang('DefaultTitle');
1130
            }
1131
1132
            if (self::wiki_exist($title)) {
1133
                $pageTitle = $icon_assignment.'&nbsp;'.$icon_task.'&nbsp;'.api_htmlentities($title);
1134
            } else {
1135
                $pageTitle = api_htmlentities($title);
1136
            }
1137
1138
            $pageWiki = self::make_wiki_link_clickable(
1139
                self::detect_external_link(
1140
                    self::detect_anchor_link(
1141
                        self::detect_mail_link(
1142
                            self::detect_ftp_link(
1143
                                self::detect_irc_link(
1144
                                    self::detect_news_link($content)
1145
                                )
1146
                            )
1147
                        )
1148
                    )
1149
                )
1150
            );
1151
1152
            $footerWiki = get_lang('Progress').': '.($row['progress'] * 10).'%&nbsp;&nbsp;&nbsp;'.get_lang('Rating').': '.$row['score'].'&nbsp;&nbsp;&nbsp;'.get_lang('Words').': '.self::word_count($content);
1153
1154
            echo Display::panel($pageWiki, $pageTitle, $footerWiki);
1155
        } //end filter visibility
1156
    }
1157
1158
    /**
1159
     * This function counted the words in a document. Thanks Adeel Khan
1160
     * @param   string  Document's text
1161
     * @return  int     Number of words
1162
     */
1163
    public function word_count($document)
1164
    {
1165
        $search = array(
1166
            '@<script[^>]*?>.*?</script>@si',
1167
            '@<style[^>]*?>.*?</style>@siU',
1168
            '@<div id="player.[^>]*?>.*?</div>@',
1169
            '@<![\s\S]*?--[ \t\n\r]*>@'
1170
        );
1171
1172
        $document = preg_replace($search, '', $document);
1173
1174
        # strip all html tags
1175
        $wc = strip_tags($document);
1176
        $wc = html_entity_decode($wc, ENT_NOQUOTES, 'UTF-8'); // TODO:test also old html_entity_decode(utf8_encode($wc))
1177
1178
        # remove 'words' that don't consist of alphanumerical characters or punctuation. And fix accents and some letters
1179
        $pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@|á|é|í|ó|ú|à|è|ì|ò|ù|ä|ë|ï|ö|ü|Á|É|Í|Ó|Ú|À|È|Ò|Ù|Ä|Ë|Ï|Ö|Ü|â|ê|î|ô|û|Â|Ê|Î|Ô|Û|ñ|Ñ|ç|Ç)]+#";
1180
        $wc = trim(preg_replace($pattern, " ", $wc));
1181
1182
        # remove one-letter 'words' that consist only of punctuation
1183
        $wc = trim(preg_replace("#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#", " ", $wc));
1184
1185
        # remove superfluous whitespace
1186
        $wc = preg_replace("/\s\s+/", " ", $wc);
1187
1188
        # split string into an array of words
1189
        $wc = explode(" ", $wc);
1190
1191
        # remove empty elements
1192
        $wc = array_filter($wc);
1193
1194
        # return the number of words
1195
        return count($wc);
1196
    }
1197
1198
    /**
1199
     * This function checks if wiki title exist
1200
     */
1201 View Code Duplication
    public function wiki_exist($title)
1202
    {
1203
        $tbl_wiki = $this->tbl_wiki;
1204
        $groupfilter = $this->groupfilter;
1205
        $condition_session = $this->condition_session;
1206
        $course_id = api_get_course_int_id();
1207
1208
        $sql = 'SELECT id FROM '.$tbl_wiki.'
1209
              WHERE
1210
                c_id = '.$course_id.' AND
1211
                title="'.Database::escape_string($title).'" AND
1212
                '.$groupfilter.$condition_session.'
1213
              ORDER BY id ASC';
1214
        $result = Database::query($sql);
1215
        $cant = Database::num_rows($result);
1216
        if ($cant > 0) {
1217
            return true;
1218
        } else {
1219
            return false;
1220
        }
1221
    }
1222
1223
    /**
1224
     * Checks if this navigation tab has to be set to active
1225
     * @author Patrick Cool <[email protected]>, Ghent University
1226
     *
1227
     * @return string html code
1228
     */
1229
    public function is_active_navigation_tab($paramwk)
1230
    {
1231
        if (isset($_GET['action']) && $_GET['action'] == $paramwk) {
1232
            return ' class="active"';
1233
        }
1234
    }
1235
1236
    /**
1237
     * Lock add pages
1238
     * @author Juan Carlos Raña <[email protected]>
1239
     * return current database status of protect page and change it if get action
1240
     */
1241
    public function check_addnewpagelock()
1242
    {
1243
        $tbl_wiki = $this->tbl_wiki;
1244
        $condition_session = $this->condition_session;
1245
        $groupfilter = $this->groupfilter;
1246
        $course_id = api_get_course_int_id();
1247
1248
        $sql = 'SELECT *
1249
                FROM '.$tbl_wiki.'
1250
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1251
                ORDER BY id ASC';
1252
1253
        $result = Database::query($sql);
1254
        $row = Database::fetch_array($result);
1255
1256
        $status_addlock = $row['addlock'];
1257
1258
        // Change status
1259
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1260
            if (isset($_GET['actionpage'])) {
1261
                if ($_GET['actionpage'] == 'lockaddnew' && $status_addlock == 1) {
1262
                    $status_addlock = 0;
1263
                }
1264
                if ($_GET['actionpage'] == 'unlockaddnew' && $status_addlock == 0) {
1265
                    $status_addlock = 1;
1266
                }
1267
                $sql = 'UPDATE '.$tbl_wiki.' SET
1268
                            addlock="'.Database::escape_string($status_addlock).'"
1269
                        WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session;
1270
                Database::query($sql);
1271
            }
1272
1273
            $sql = 'SELECT *
1274
                    FROM '.$tbl_wiki.'
1275
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1276
                    ORDER BY id ASC';
1277
            $result = Database::query($sql);
1278
            $row = Database::fetch_array($result);
1279
        }
1280
1281
        return $row['addlock'];
1282
1283
    }
1284
1285
    /**
1286
     * Protect page
1287
     * @author Juan Carlos Raña <[email protected]>
1288
     * return current database status of protect page and change it if get action
1289
     */
1290
    public function check_protect_page()
1291
    {
1292
        $tbl_wiki = $this->tbl_wiki;
1293
        $condition_session = $this->condition_session;
1294
        $groupfilter = $this->groupfilter;
1295
        $page = $this->page;
1296
1297
        $course_id = api_get_course_int_id();
1298
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1299
              WHERE
1300
                c_id = '.$course_id.' AND
1301
                reflink="'.Database::escape_string($page).'" AND
1302
                '.$groupfilter.$condition_session.'
1303
              ORDER BY id ASC';
1304
1305
        $result = Database::query($sql);
1306
        $row = Database::fetch_array($result);
1307
        $status_editlock = $row['editlock'];
1308
        $id = $row['page_id'];
1309
1310
        // Change status
1311
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1312
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'lock' && $status_editlock == 0) {
1313
                $status_editlock = 1;
1314
            }
1315
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlock' && $status_editlock == 1) {
1316
                $status_editlock = 0;
1317
            }
1318
1319
            $sql = 'UPDATE '.$tbl_wiki.' SET editlock="'.Database::escape_string($status_editlock).'"
1320
                    WHERE c_id = '.$course_id.' AND page_id="'.$id.'"';
1321
            Database::query($sql);
1322
1323
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1324
                  WHERE
1325
                    c_id = '.$course_id.' AND
1326
                    reflink="'.Database::escape_string($page).'" AND
1327
                    '.$groupfilter.$condition_session.'
1328
                  ORDER BY id ASC';
1329
            $result = Database::query($sql);
1330
            $row = Database::fetch_array($result);
1331
        }
1332
1333
        //show status
1334
        return $row['editlock'];
1335
    }
1336
1337
    /**
1338
     * Visibility page
1339
     * @author Juan Carlos Raña <[email protected]>
1340
     * return current database status of visibility and change it if get action
1341
     */
1342
    public function check_visibility_page()
1343
    {
1344
        $tbl_wiki = $this->tbl_wiki;
1345
        $page = $this->page;
1346
        $condition_session = $this->condition_session;
1347
        $groupfilter = $this->groupfilter;
1348
        $course_id = api_get_course_int_id();
1349
1350
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1351
                WHERE
1352
                    c_id = '.$course_id.' AND
1353
                    reflink="'.Database::escape_string($page).'" AND
1354
                    '.$groupfilter.$condition_session.'
1355
                ORDER BY id ASC';
1356
        $result = Database::query($sql);
1357
        $row = Database::fetch_array($result);
1358
        $status_visibility = $row['visibility'];
1359
        //change status
1360
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1361
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'visible' && $status_visibility == 0) {
1362
                $status_visibility = 1;
1363
1364
            }
1365
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'invisible' && $status_visibility == 1) {
1366
                $status_visibility = 0;
1367
            }
1368
1369
            $sql = 'UPDATE '.$tbl_wiki.' SET 
1370
                    visibility = "'.Database::escape_string($status_visibility).'"
1371
                    WHERE 
1372
                        c_id = '.$course_id.' AND 
1373
                        reflink="'.Database::escape_string($page).'" AND 
1374
                        '.$groupfilter.$condition_session;
1375
            Database::query($sql);
1376
1377
            // Although the value now is assigned to all (not only the first),
1378
            // these three lines remain necessary.
1379
            // They do that by changing the page state is
1380
            // made when you press the button and not have to wait to change his page
1381
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1382
                    WHERE
1383
                        c_id = '.$course_id.' AND
1384
                        reflink="'.Database::escape_string($page).'" AND
1385
                        '.$groupfilter.$condition_session.'
1386
                    ORDER BY id ASC';
1387
            $result = Database::query($sql);
1388
            $row = Database::fetch_array($result);
1389
        }
1390
1391
        if (empty($row['id'])) {
1392
            $row['visibility'] = 1;
1393
        }
1394
1395
        //show status
1396
        return $row['visibility'];
1397
    }
1398
1399
    /**
1400
     * Visibility discussion
1401
     * @author Juan Carlos Raña <[email protected]>
1402
     * @return int current database status of discuss visibility and change it if get action page
1403
     */
1404 View Code Duplication
    public function check_visibility_discuss()
1405
    {
1406
        $tbl_wiki = $this->tbl_wiki;
1407
        $page = $this->page;
1408
        $condition_session = $this->condition_session;
1409
        $groupfilter = $this->groupfilter;
1410
        $course_id = api_get_course_int_id();
1411
1412
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1413
                WHERE
1414
                    c_id = '.$course_id.' AND
1415
                    reflink="'.Database::escape_string($page).'" AND
1416
                    '.$groupfilter.$condition_session.'
1417
                ORDER BY id ASC';
1418
        $result = Database::query($sql);
1419
        $row = Database::fetch_array($result);
1420
1421
        $status_visibility_disc = $row['visibility_disc'];
1422
1423
        //change status
1424
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1425
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'showdisc' && $status_visibility_disc == 0) {
1426
                $status_visibility_disc = 1;
1427
            }
1428
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'hidedisc' && $status_visibility_disc == 1) {
1429
                $status_visibility_disc = 0;
1430
            }
1431
1432
            $sql = 'UPDATE '.$tbl_wiki.' SET visibility_disc="'.Database::escape_string($status_visibility_disc).'"
1433
                    WHERE
1434
                        c_id = '.$course_id.' AND
1435
                        reflink="'.Database::escape_string($page).'" AND
1436
                        '.$groupfilter.$condition_session;
1437
            Database::query($sql);
1438
1439
            // Although the value now is assigned to all (not only the first),
1440
            // these three lines remain necessary.
1441
            // They do that by changing the page state is made when you press
1442
            // the button and not have to wait to change his page
1443
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1444
                    WHERE
1445
                        c_id = '.$course_id.' AND
1446
                        reflink="'.Database::escape_string($page).'" AND
1447
                        '.$groupfilter.$condition_session.'
1448
                    ORDER BY id ASC';
1449
            $result = Database::query($sql);
1450
            $row = Database::fetch_array($result);
1451
        }
1452
1453
        return $row['visibility_disc'];
1454
    }
1455
1456
    /**
1457
     * Lock add discussion
1458
     * @author Juan Carlos Raña <[email protected]>
1459
     * @return int current database status of lock dicuss and change if get action
1460
     */
1461 View Code Duplication
    public function check_addlock_discuss()
1462
    {
1463
        $tbl_wiki = $this->tbl_wiki;
1464
        $page = $this->page;
1465
        $condition_session = $this->condition_session;
1466
        $groupfilter = $this->groupfilter;
1467
        $course_id = api_get_course_int_id();
1468
1469
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1470
                WHERE
1471
                    c_id = '.$course_id.' AND
1472
                    reflink="'.Database::escape_string($page).'" AND
1473
                    '.$groupfilter.$condition_session.'
1474
                ORDER BY id ASC';
1475
        $result = Database::query($sql);
1476
        $row = Database::fetch_array($result);
1477
1478
        $status_addlock_disc = $row['addlock_disc'];
1479
1480
        //change status
1481
        if (api_is_allowed_to_edit() || api_is_platform_admin()) {
1482
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'lockdisc' && $status_addlock_disc == 0) {
1483
                $status_addlock_disc = 1;
1484
            }
1485
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlockdisc' && $status_addlock_disc == 1) {
1486
                $status_addlock_disc = 0;
1487
            }
1488
1489
            $sql = 'UPDATE '.$tbl_wiki.' SET
1490
                    addlock_disc="'.Database::escape_string($status_addlock_disc).'"
1491
                    WHERE
1492
                        c_id = '.$course_id.' AND
1493
                        reflink = "'.Database::escape_string($page).'" AND
1494
                         '.$groupfilter.$condition_session;
1495
            Database::query($sql);
1496
1497
            // Although the value now is assigned to all (not only the first),
1498
            // these three lines remain necessary.
1499
            // They do that by changing the page state is made when you press
1500
            // the button and not have to wait to change his page
1501
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1502
                    WHERE
1503
                        c_id = '.$course_id.' AND
1504
                        reflink="'.Database::escape_string($page).'" AND
1505
                        '.$groupfilter.$condition_session.'
1506
                    ORDER BY id ASC';
1507
            $result = Database::query($sql);
1508
            $row = Database::fetch_array($result);
1509
        }
1510
1511
        return $row['addlock_disc'];
1512
    }
1513
1514
    /**
1515
     * Lock rating discussion
1516
     * @author Juan Carlos Raña <[email protected]>
1517
     * @return  int  current database status of rating discuss and change it if get action
1518
     */
1519 View Code Duplication
    public function check_ratinglock_discuss()
1520
    {
1521
        $tbl_wiki = $this->tbl_wiki;
1522
        $page = $this->page;
1523
        $condition_session = $this->condition_session;
1524
        $groupfilter = $this->groupfilter;
1525
        $course_id = api_get_course_int_id();
1526
1527
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1528
                WHERE
1529
                    c_id = '.$course_id.' AND
1530
                    reflink="'.Database::escape_string($page).'" AND
1531
                    '.$groupfilter.$condition_session.'
1532
                ORDER BY id ASC';
1533
        $result = Database::query($sql);
1534
        $row = Database::fetch_array($result);
1535
        $status_ratinglock_disc = $row['ratinglock_disc'];
1536
1537
        //change status
1538
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1539
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'lockrating' && $status_ratinglock_disc == 0) {
1540
                $status_ratinglock_disc = 1;
1541
            }
1542
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlockrating' && $status_ratinglock_disc == 1) {
1543
                $status_ratinglock_disc = 0;
1544
            }
1545
1546
            $sql = 'UPDATE '.$tbl_wiki.'
1547
                    SET ratinglock_disc="'.Database::escape_string($status_ratinglock_disc).'"
1548
                    WHERE
1549
                        c_id = '.$course_id.' AND
1550
                        reflink="'.Database::escape_string($page).'" AND
1551
                        '.$groupfilter.$condition_session;
1552
            //Visibility. Value to all,not only for the first
1553
            Database::query($sql);
1554
1555
            // Although the value now is assigned to all (not only the first),
1556
            // these three lines remain necessary. They do that by changing the
1557
            // page state is made when you press the button and not have to wait
1558
            // to change his page
1559
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1560
                  WHERE
1561
                    c_id = '.$course_id.' AND
1562
                    reflink="'.Database::escape_string($page).'" AND
1563
                    '.$groupfilter.$condition_session.'
1564
                  ORDER BY id ASC';
1565
            $result = Database::query($sql);
1566
            $row = Database::fetch_array($result);
1567
        }
1568
1569
        return $row['ratinglock_disc'];
1570
    }
1571
1572
    /**
1573
     * Notify page changes
1574
     * @author Juan Carlos Raña <[email protected]>
1575
     * @return int the current notification status
1576
     */
1577
    public function check_notify_page($reflink)
1578
    {
1579
        $tbl_wiki = $this->tbl_wiki;
1580
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1581
        $condition_session = $this->condition_session;
1582
        $groupfilter = $this->groupfilter;
1583
        $groupId = api_get_group_id();
1584
        $session_id = api_get_session_id();
1585
        $course_id = api_get_course_int_id();
1586
        $userId = api_get_user_id();
1587
1588
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1589
                WHERE c_id = '.$course_id.' AND reflink="'.$reflink.'" AND '.$groupfilter.$condition_session.'
1590
                ORDER BY id ASC';
1591
        $result = Database::query($sql);
1592
        $row = Database::fetch_array($result);
1593
        $id = $row['id'];
1594
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1595
              WHERE c_id = '.$course_id.' AND id="'.$id.'" AND user_id="'.api_get_user_id().'" AND type="P"';
1596
        $result = Database::query($sql);
1597
        $row = Database::fetch_array($result);
1598
        $idm = $row['id'];
1599
        if (empty($idm)) {
1600
            $status_notify = 0;
1601
        } else {
1602
            $status_notify = 1;
1603
        }
1604
1605
        // Change status
1606
        if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'locknotify' && $status_notify == 0) {
1607
            $sql = "SELECT id FROM $tbl_wiki_mailcue
1608
                    WHERE c_id = $course_id AND id = $id AND user_id = $userId";
1609
            $result = Database::query($sql);
1610
            $exist = false;
1611
            if (Database::num_rows($result)) {
1612
                $exist = true;
1613
            }
1614
            if ($exist == false) {
1615
                $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1616
                ($course_id, '".$id."','".api_get_user_id()."','P','".$groupId."','".$session_id."')";
1617
                Database::query($sql);
1618
            }
1619
            $status_notify = 1;
1620
        }
1621
1622
        if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlocknotify' && $status_notify == 1) {
1623
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1624
                    WHERE id="'.$id.'" AND user_id="'.api_get_user_id().'" AND type="P" AND c_id = '.$course_id;
1625
            Database::query($sql);
1626
            $status_notify = 0;
1627
        }
1628
1629
        return $status_notify;
1630
    }
1631
1632
    /**
1633
     * Notify discussion changes
1634
     * @author Juan Carlos Raña <[email protected]>
1635
     * @param string $reflink
1636
     * @return int current database status of rating discuss and change it if get action
1637
     */
1638
    public function check_notify_discuss($reflink)
1639
    {
1640
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1641
        $tbl_wiki = $this->tbl_wiki;
1642
        $condition_session = $this->condition_session;
1643
        $groupfilter = $this->groupfilter;
1644
1645
        $course_id = api_get_course_int_id();
1646
        $groupId = api_get_group_id();
1647
        $session_id = api_get_session_id();
1648
1649
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1650
                WHERE c_id = '.$course_id.' AND reflink="'.$reflink.'" AND '.$groupfilter.$condition_session.'
1651
                ORDER BY id ASC';
1652
        $result = Database::query($sql);
1653
        $row = Database::fetch_array($result);
1654
        $id = $row['id'];
1655
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1656
                WHERE c_id = '.$course_id.' AND id="'.$id.'" AND user_id="'.api_get_user_id().'" AND type="D"';
1657
        $result = Database::query($sql);
1658
        $row = Database::fetch_array($result);
1659
        $idm = $row['id'];
1660
1661
        if (empty($idm)) {
1662
            $status_notify_disc = 0;
1663
        } else {
1664
            $status_notify_disc = 1;
1665
        }
1666
1667
        //change status
1668 View Code Duplication
        if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'locknotifydisc' && $status_notify_disc == 0) {
1669
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1670
            ($course_id, '".$id."','".api_get_user_id()."','D','".$groupId."','".$session_id."')";
1671
            Database::query($sql);
1672
            $status_notify_disc = 1;
1673
        }
1674 View Code Duplication
        if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlocknotifydisc' && $status_notify_disc == 1) {
1675
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1676
                    WHERE c_id = '.$course_id.' AND id="'.$id.'" AND user_id="'.api_get_user_id().'" AND type="D" AND c_id = '.$course_id;
1677
            Database::query($sql);
1678
            $status_notify_disc = 0;
1679
        }
1680
1681
        return $status_notify_disc;
1682
    }
1683
1684
    /**
1685
     * Notify all changes
1686
     * @author Juan Carlos Raña <[email protected]>
1687
     */
1688
    public function check_notify_all()
1689
    {
1690
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1691
        $course_id = api_get_course_int_id();
1692
        $groupId = api_get_group_id();
1693
        $session_id = api_get_session_id();
1694
1695
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1696
                WHERE
1697
                    c_id = '.$course_id.' AND
1698
                    user_id="'.api_get_user_id().'" AND
1699
                    type="F" AND
1700
                    group_id="'.$groupId.'" AND
1701
                    session_id="'.$session_id.'"';
1702
        $result = Database::query($sql);
1703
        $row = Database::fetch_array($result);
1704
1705
        $idm = $row['user_id'];
1706
1707
        if (empty($idm)) {
1708
            $status_notify_all = 0;
1709
        } else {
1710
            $status_notify_all = 1;
1711
        }
1712
1713
        //change status
1714 View Code Duplication
        if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'locknotifyall' && $status_notify_all == 0) {
1715
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, user_id, type, group_id, session_id) VALUES
1716
            ($course_id, '".api_get_user_id()."','F','".$groupId."','".$session_id."')";
1717
            Database::query($sql);
1718
            $status_notify_all = 1;
1719
        }
1720
1721 View Code Duplication
        if (isset($_GET['actionpage']) &&
1722
            isset($_GET['actionpage']) &&
1723
            $_GET['actionpage'] == 'unlocknotifyall' &&
1724
            $status_notify_all == 1
1725
        ) {
1726
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1727
                   WHERE
1728
                    c_id = '.$course_id.' AND
1729
                    user_id="'.api_get_user_id().'" AND
1730
                    type="F" AND
1731
                    group_id="'.$groupId.'" AND
1732
                    session_id="'.$session_id.'" AND
1733
                    c_id = '.$course_id;
1734
            Database::query($sql);
1735
            $status_notify_all = 0;
1736
        }
1737
1738
        //show status
1739
        return $status_notify_all;
1740
    }
1741
1742
    /**
1743
     * Sends pending e-mails
1744
     */
1745
    public function check_emailcue($id_or_ref, $type, $lastime = '', $lastuser = '')
1746
    {
1747
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1748
        $tbl_wiki = $this->tbl_wiki;
1749
        $condition_session = $this->condition_session;
1750
        $groupfilter = $this->groupfilter;
1751
        $_course = $this->courseInfo;
1752
        $groupId = api_get_group_id();
1753
        $session_id = api_get_session_id();
1754
        $course_id = api_get_course_int_id();
1755
        $group_properties = GroupManager::get_group_properties($groupId);
1756
        $group_name = $group_properties['name'];
1757
        $allow_send_mail = false; //define the variable to below
1758
        $email_assignment = null;
1759
        if ($type == 'P') {
1760
            //if modifying a wiki page
1761
            //first, current author and time
1762
            //Who is the author?
1763
            $userinfo = api_get_user_info($lastuser);
1764
            $email_user_author = get_lang('EditedBy').': '.$userinfo['complete_name'];
1765
1766
            //When ?
1767
            $year = substr($lastime, 0, 4);
1768
            $month = substr($lastime, 5, 2);
1769
            $day = substr($lastime, 8, 2);
1770
            $hours = substr($lastime, 11, 2);
1771
            $minutes = substr($lastime, 14, 2);
1772
            $seconds = substr($lastime, 17, 2);
1773
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
1774
1775
            //second, extract data from first reg
1776
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1777
                    WHERE  c_id = '.$course_id.' AND reflink="'.$id_or_ref.'" AND '.$groupfilter.$condition_session.'
1778
                    ORDER BY id ASC';
1779
            $result = Database::query($sql);
1780
            $row = Database::fetch_array($result);
1781
            $id = $row['id'];
1782
            $email_page_name = $row['title'];
1783 View Code Duplication
            if ($row['visibility'] == 1) {
1784
                $allow_send_mail = true; //if visibility off - notify off
1785
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1786
                        WHERE
1787
                            c_id = '.$course_id.' AND
1788
                            id="'.$id.'" AND
1789
                            type="'.$type.'" OR
1790
                            type="F" AND
1791
                            group_id="'.$groupId.'" AND
1792
                            session_id="'.$session_id.'"';
1793
                //type: P=page, D=discuss, F=full.
1794
                $result = Database::query($sql);
1795
                $emailtext = get_lang('EmailWikipageModified').' <strong>'.$email_page_name.'</strong> '.get_lang('Wiki');
1796
            }
1797
        } elseif ($type == 'D') {
1798
            //if added a post to discuss
1799
            //first, current author and time
1800
            //Who is the author of last message?
1801
            $userinfo = api_get_user_info($lastuser);
1802
            $email_user_author = get_lang('AddedBy').': '.$userinfo['complete_name'];
1803
1804
            //When ?
1805
            $year = substr($lastime, 0, 4);
1806
            $month = substr($lastime, 5, 2);
1807
            $day = substr($lastime, 8, 2);
1808
            $hours = substr($lastime, 11, 2);
1809
            $minutes = substr($lastime, 14, 2);
1810
            $seconds = substr($lastime, 17, 2);
1811
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
1812
            //second, extract data from first reg
1813
            $id = $id_or_ref; //$id_or_ref is id from tblwiki
1814
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1815
                    WHERE c_id = '.$course_id.' AND id="'.$id.'"
1816
                    ORDER BY id ASC';
1817
1818
            $result = Database::query($sql);
1819
            $row = Database::fetch_array($result);
1820
1821
            $email_page_name = $row['title'];
1822 View Code Duplication
            if ($row['visibility_disc'] == 1) {
1823
                $allow_send_mail = true; //if visibility off - notify off
1824
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1825
                        WHERE
1826
                            c_id = '.$course_id.' AND
1827
                            id="'.$id.'" AND
1828
                            type="'.$type.'" OR
1829
                            type="F" AND
1830
                            group_id="'.$groupId.'" AND
1831
                            session_id="'.$session_id.'"';
1832
                //type: P=page, D=discuss, F=full
1833
                $result = Database::query($sql);
1834
                $emailtext = get_lang('EmailWikiPageDiscAdded').' <strong>'.$email_page_name.'</strong> '.get_lang('Wiki');
1835
            }
1836
        } elseif ($type == 'A') {
1837
            //for added pages
1838
            $id = 0; //for tbl_wiki_mailcue
1839
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1840
                    WHERE c_id = '.$course_id.'
1841
                    ORDER BY id DESC'; //the added is always the last
1842
1843
            $result = Database::query($sql);
1844
            $row = Database::fetch_array($result);
1845
            $email_page_name = $row['title'];
1846
1847
            //Who is the author?
1848
            $userinfo = api_get_user_info($row['user_id']);
1849
            $email_user_author = get_lang('AddedBy').': '.$userinfo['complete_name'];
1850
1851
            //When ?
1852
            $year = substr($row['dtime'], 0, 4);
1853
            $month = substr($row['dtime'], 5, 2);
1854
            $day = substr($row['dtime'], 8, 2);
1855
            $hours = substr($row['dtime'], 11, 2);
1856
            $minutes = substr($row['dtime'], 14, 2);
1857
            $seconds = substr($row['dtime'], 17, 2);
1858
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
1859
1860
            if ($row['assignment'] == 0) {
1861
                $allow_send_mail = true;
1862
            } elseif ($row['assignment'] == 1) {
1863
                $email_assignment = get_lang('AssignmentDescExtra').' ('.get_lang('AssignmentMode').')';
1864
                $allow_send_mail = true;
1865
            } elseif ($row['assignment'] == 2) {
1866
                $allow_send_mail = false; //Mode tasks: avoids notifications to all users about all users
1867
            }
1868
1869
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1870
                    WHERE c_id = '.$course_id.' AND  id="'.$id.'" AND type="F" AND group_id="'.$groupId.'" AND session_id="'.$session_id.'"';
1871
            //type: P=page, D=discuss, F=full
1872
            $result = Database::query($sql);
1873
1874
            $emailtext = get_lang('EmailWikiPageAdded').' <strong>'.$email_page_name.'</strong> '.get_lang('In').' '.get_lang('Wiki');
1875
        } elseif ($type == 'E') {
1876
            $id = 0;
1877
            $allow_send_mail = true;
1878
            // Who is the author?
1879
            $userinfo = api_get_user_info(api_get_user_id()); //current user
1880
            $email_user_author = get_lang('DeletedBy').': '.$userinfo['complete_name'];
1881
            //When ?
1882
            $today = date('r'); //current time
1883
            $email_date_changes = $today;
1884
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1885
                    WHERE
1886
                        c_id = '.$course_id.' AND
1887
                        id="'.$id.'" AND type="F" AND
1888
                        group_id="'.$groupId.'" AND
1889
                        session_id="'.$session_id.'"'; //type: P=page, D=discuss, F=wiki
1890
            $result = Database::query($sql);
1891
            $emailtext = get_lang('EmailWikipageDedeleted');
1892
        }
1893
        ///make and send email
1894
        if ($allow_send_mail) {
1895
            while ($row = Database::fetch_array($result)) {
1896
                $userinfo = api_get_user_info($row['user_id']); //$row['user_id'] obtained from tbl_wiki_mailcue
1897
                $name_to = $userinfo['complete_name'];
1898
                $email_to = $userinfo['email'];
1899
                $sender_name = api_get_setting('emailAdministrator');
1900
                $sender_email = api_get_setting('emailAdministrator');
1901
                $email_subject = get_lang('EmailWikiChanges').' - '.$_course['official_code'];
1902
                $email_body = get_lang('DearUser').' '.api_get_person_name($userinfo['firstname'], $userinfo['lastname']).',<br /><br />';
1903
                if ($session_id == 0) {
1904
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' - '.$group_name.'</strong><br /><br /><br />';
1905
                } else {
1906
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' ('.api_get_session_name(api_get_session_id()).') - '.$group_name.'</strong><br /><br /><br />';
1907
                }
1908
                $email_body .= $email_user_author.' ('.$email_date_changes.')<br /><br /><br />';
1909
                $email_body .= $email_assignment.'<br /><br /><br />';
1910
                $email_body .= '<font size="-2">'.get_lang('EmailWikiChangesExt_1').': <strong>'.get_lang('NotifyChanges').'</strong><br />';
1911
                $email_body .= get_lang('EmailWikiChangesExt_2').': <strong>'.get_lang('NotNotifyChanges').'</strong></font><br />';
1912
                @api_mail_html(
1913
                    $name_to,
1914
                    $email_to,
1915
                    $email_subject,
1916
                    $email_body,
1917
                    $sender_name,
1918
                    $sender_email
1919
                );
1920
            }
1921
        }
1922
    }
1923
1924
    /**
1925
     * Function export last wiki page version to document area
1926
     * @param int $doc_id wiki page id
1927
     * @return mixed
1928
     * @author Juan Carlos Raña <[email protected]>
1929
     */
1930
    public function export2doc($doc_id)
1931
    {
1932
        $_course = $this->courseInfo;
1933
        $groupId = api_get_group_id();
1934
        $groupInfo = GroupManager::get_group_properties($groupId);
1935
        $data = self::getWikiDataFromDb($doc_id);
1936
1937
        if (empty($data)) {
1938
            return false;
1939
        }
1940
1941
        $wikiTitle = $data['title'];
1942
        $wikiContents = $data['content'];
1943
1944
        $template =
1945
            '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1946
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{LANGUAGE}" lang="{LANGUAGE}">
1947
            <head>
1948
            <title>{TITLE}</title>
1949
            <meta http-equiv="Content-Type" content="text/html; charset={ENCODING}" />
1950
            <style type="text/css" media="screen, projection">
1951
            /*<![CDATA[*/
1952
            {CSS}
1953
            /*]]>*/
1954
            </style>
1955
            {ASCIIMATHML_SCRIPT}</head>
1956
            <body dir="{TEXT_DIRECTION}">
1957
            {CONTENT}
1958
            </body>
1959
            </html>';
1960
1961
        $css_file = api_get_path(SYS_CSS_PATH).'themes/'.api_get_setting('stylesheets').'/default.css';
1962
        if (file_exists($css_file)) {
1963
            $css = @file_get_contents($css_file);
1964
        } else {
1965
            $css = '';
1966
        }
1967
        // Fixing some bugs in css files.
1968
        $root_rel = api_get_path(REL_PATH);
1969
        $css_path = 'main/css/';
1970
        $theme = api_get_setting('stylesheets').'/';
1971
        $css = str_replace('behavior:url("/main/css/csshover3.htc");', '', $css);
1972
        $css = str_replace('main/', $root_rel.'main/', $css);
1973
        $css = str_replace('images/', $root_rel.$css_path.$theme.'images/', $css);
1974
        $css = str_replace('../../img/', $root_rel.'main/img/', $css);
1975
        $asciimathmal_script = (api_contains_asciimathml($wikiContents) || api_contains_asciisvg($wikiContents))
1976
            ? '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'asciimath/ASCIIMathML.js" type="text/javascript"></script>'."\n" : '';
1977
1978
        $template = str_replace(array('{LANGUAGE}', '{ENCODING}', '{TEXT_DIRECTION}', '{TITLE}', '{CSS}', '{ASCIIMATHML_SCRIPT}'),
1979
            array(api_get_language_isocode(), api_get_system_encoding(), api_get_text_direction(), $wikiTitle, $css, $asciimathmal_script),
1980
            $template);
1981
1982
        if (0 != $groupId) {
1983
            $groupPart = '_group'.$groupId; // and add groupId to put the same document title in different groups
1984
            $group_properties = GroupManager::get_group_properties($groupId);
1985
            $groupPath = $group_properties['directory'];
1986
        } else {
1987
            $groupPart = '';
1988
            $groupPath = '';
1989
        }
1990
1991
        $exportDir = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/document'.$groupPath;
1992
        $exportFile = api_replace_dangerous_char($wikiTitle).$groupPart;
1993
        $wikiContents = trim(preg_replace("/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/", "$1", $wikiContents));
1994
        //TODO: put link instead of title
1995
1996
        $wikiContents = str_replace('{CONTENT}', $wikiContents, $template);
1997
1998
        // replace relative path by absolute path for courses, so you can see items into this page wiki (images, mp3, etc..) exported in documents
1999
        if (api_strpos($wikiContents, '../..'.api_get_path(REL_COURSE_PATH)) !== false) {
2000
            $web_course_path = api_get_path(WEB_COURSE_PATH);
2001
            $wikiContents = str_replace('../..'.api_get_path(REL_COURSE_PATH), $web_course_path, $wikiContents);
2002
        }
2003
2004
        $i = 1;
2005
        //only export last version, but in new export new version in document area
2006
        while (file_exists($exportDir.'/'.$exportFile.'_'.$i.'.html')) {
2007
            $i++;
2008
        }
2009
2010
        $wikiFileName = $exportFile.'_'.$i.'.html';
2011
        $exportPath = $exportDir.'/'.$wikiFileName;
2012
2013
        file_put_contents($exportPath, $wikiContents);
2014
        $doc_id = add_document(
2015
            $_course,
2016
            $groupPath.'/'.$wikiFileName,
2017
            'file',
2018
            filesize($exportPath),
2019
            $wikiTitle
2020
        );
2021
2022
        api_item_property_update(
2023
            $_course,
2024
            TOOL_DOCUMENT,
2025
            $doc_id,
2026
            'DocumentAdded',
2027
            api_get_user_id(),
2028
            $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 1934 can also be of type null; however, api_item_property_update() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
2029
        );
2030
2031
        return $doc_id;
2032
    }
2033
2034
    /**
2035
     * Exports the wiki page to PDF
2036
     */
2037
    public function export_to_pdf($id, $course_code)
2038
    {
2039
        if (!api_is_platform_admin()) {
2040
            if (api_get_setting('students_export2pdf') !== 'true') {
2041
                Display::addFlash(
2042
                    Display::return_message(
2043
                        get_lang('PDFDownloadNotAllowedForStudents'),
2044
                        'error',
2045
                        false
2046
                    )
2047
                );
2048
                return false;
2049
            }
2050
        }
2051
2052
        $data = self::getWikiDataFromDb($id);
2053
        $content_pdf = api_html_entity_decode($data['content'], ENT_QUOTES, api_get_system_encoding());
2054
2055
        //clean wiki links
2056
        $content_pdf = trim(preg_replace("/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/", "$1", $content_pdf));
2057
        //TODO: It should be better to display the link insted of the tile but it is hard for [[title]] links
2058
2059
        $title_pdf = api_html_entity_decode($data['title'], ENT_QUOTES, api_get_system_encoding());
2060
        $title_pdf = api_utf8_encode($title_pdf, api_get_system_encoding());
2061
        $content_pdf = api_utf8_encode($content_pdf, api_get_system_encoding());
2062
2063
        $html = '
2064
        <!-- defines the headers/footers - this must occur before the headers/footers are set -->
2065
2066
        <!--mpdf
2067
        <pageheader name="odds" content-left="'.$title_pdf.'"  header-style-left="color: #880000; font-style: italic;"  line="1" />
2068
        <pagefooter name="odds" content-right="{PAGENO}/{nb}" line="1" />
2069
2070
        <!-- set the headers/footers - they will occur from here on in the document -->
2071
        <!--mpdf
2072
        <setpageheader name="odds" page="odd" value="on" show-this-page="1" />
2073
        <setpagefooter name="odds" page="O" value="on" />
2074
2075
        mpdf-->'.$content_pdf;
2076
2077
        $css_file = api_get_path(SYS_CSS_PATH).'themes/'.api_get_setting('stylesheets').'/print.css';
2078
        if (file_exists($css_file)) {
2079
            $css = @file_get_contents($css_file);
2080
        } else {
2081
            $css = '';
2082
        }
2083
2084
        $pdf = new PDF();
2085
        $pdf->content_to_pdf($html, $css, $title_pdf, $course_code);
2086
        exit;
2087
    }
2088
2089
    /**
2090
     * Function prevent double post (reload or F5)
2091
     *
2092
     */
2093
    public function double_post($wpost_id)
2094
    {
2095
        $postId = Session::read('wpost_id');
2096
        if (!empty($postId)) {
2097
            if ($wpost_id == $postId) {
2098
                return false;
2099
            } else {
2100
                Session::write('wpost_id', $wpost_id);
2101
2102
                return true;
2103
            }
2104
        } else {
2105
            Session::write('wpost_id', $wpost_id);
2106
2107
            return true;
2108
        }
2109
    }
2110
2111
    /**
2112
     * Function wizard individual assignment
2113
     * @author Juan Carlos Raña <[email protected]>
2114
     */
2115
    public function auto_add_page_users($values)
2116
    {
2117
        $assignment_type = $values['assignment'];
2118
        $session_id = $this->session_id;
2119
        $groupId = api_get_group_id();
2120
        $groupInfo = GroupManager::get_group_properties($groupId);
2121
        if ($groupId == 0) {
2122
            //extract course members
2123
            if (!empty($session_id)) {
2124
                $a_users_to_add = CourseManager::get_user_list_from_course_code(api_get_course_id(), $session_id);
2125
            } else {
2126
                $a_users_to_add = CourseManager::get_user_list_from_course_code(api_get_course_id(), 0);
2127
            }
2128
        } else {
2129
            //extract group members
2130
            $subscribed_users = GroupManager::get_subscribed_users($groupInfo);
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 2120 can also be of type null; however, GroupManager::get_subscribed_users() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
2131
            $subscribed_tutors = GroupManager::get_subscribed_tutors($groupInfo);
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 2120 can also be of type null; however, GroupManager::get_subscribed_tutors() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
2132
            $a_users_to_add_with_duplicates = array_merge($subscribed_users, $subscribed_tutors);
2133
            //remove duplicates
2134
            $a_users_to_add = $a_users_to_add_with_duplicates;
2135
            //array_walk($a_users_to_add, create_function('&$value,$key', '$value = json_encode($value);'));
2136
            $a_users_to_add = array_unique($a_users_to_add);
2137
            //array_walk($a_users_to_add, create_function('&$value,$key', '$value = json_decode($value, true);'));
2138
        }
2139
2140
        $all_students_pages = array();
2141
        // Data about teacher
2142
        $userId = api_get_user_id();
2143
        $userinfo = api_get_user_info($userId);
2144
        $username = api_htmlentities(sprintf(get_lang('LoginX'), $userinfo['username'], ENT_QUOTES));
2145
        $name = $userinfo['complete_name']." - ".$username;
2146
        $photo = '<img src="'.$userinfo['avatar'].'" alt="'.$name.'"  width="40" height="50" align="top" title="'.$name.'"  />';
2147
2148
        // teacher assignment title
2149
        $title_orig = $values['title'];
2150
2151
        // teacher assignment reflink
2152
        $link2teacher = $values['title'] = $title_orig."_uass".$userId;
2153
2154
        // first: teacher name, photo, and assignment description (original content)
2155
        $content_orig_A = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2156
        <table border="0">
2157
            <tr><td style="font-size:24px">'.get_lang('AssignmentDesc').'</td></tr>
2158
            <tr><td>'.$photo.'<br />'.Display::tag('span', api_get_person_name($userinfo['firstname'], $userinfo['lastname']), array('title'=>$username)).'</td></tr>
2159
        </table></div>';
2160
2161
        $content_orig_B = '<br/><div align="center" style="font-size:24px">'.
2162
            get_lang('AssignmentDescription').': '.
2163
            $title_orig.'</div><br/>'.Security::remove_XSS($_POST['content']);
2164
2165
        //Second: student list (names, photo and links to their works).
2166
        //Third: Create Students work pages.
2167
        foreach ($a_users_to_add as $o_user_to_add) {
0 ignored issues
show
Bug introduced by
The expression $a_users_to_add of type array|integer is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
2168
            if ($o_user_to_add['user_id'] != $userId) {
2169
                // except that puts the task
2170
                $assig_user_id = $o_user_to_add['user_id'];
2171
                // identifies each page as created by the student, not by teacher
2172
2173
                $userPicture = UserManager::getUserPicture($assig_user_id);
2174
                $username = api_htmlentities(sprintf(get_lang('LoginX'), $o_user_to_add['username'], ENT_QUOTES));
2175
                $name = api_get_person_name($o_user_to_add['firstname'], $o_user_to_add['lastname'])." . ".$username;
2176
                $photo = '<img src="'.$userPicture.'" alt="'.$name.'"  width="40" height="50" align="bottom" title="'.$name.'"  />';
2177
2178
                $is_tutor_of_group = GroupManager::is_tutor_of_group($assig_user_id, $groupInfo); //student is tutor
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 2120 can also be of type null; however, GroupManager::is_tutor_of_group() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
2179
                $is_tutor_and_member = GroupManager::is_tutor_of_group($assig_user_id, $groupInfo) &&
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 2120 can also be of type null; however, GroupManager::is_tutor_of_group() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
2180
                    GroupManager::is_subscribed($assig_user_id, $groupInfo);
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 2120 can also be of type null; however, GroupManager::is_subscribed() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
2181
                // student is tutor and member
2182
                if ($is_tutor_and_member) {
2183
                    $status_in_group = get_lang('GroupTutorAndMember');
2184
                } else {
2185
                    if ($is_tutor_of_group) {
2186
                        $status_in_group = get_lang('GroupTutor');
2187
                    } else {
2188
                        $status_in_group = " "; //get_lang('GroupStandardMember')
2189
                    }
2190
                }
2191
2192
                if ($assignment_type == 1) {
2193
                    $values['title'] = $title_orig;
2194
                    $values['content'] = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2195
                    <table border="0">
2196
                    <tr><td style="font-size:24px">'.get_lang('AssignmentWork').'</td></tr>
2197
                    <tr><td>'.$photo.'<br />'.$name.'</td></tr></table>
2198
                    </div>[['.$link2teacher.' | '.get_lang('AssignmentLinktoTeacherPage').']] ';
2199
                    //If $content_orig_B is added here, the task written by the professor was copied to the page of each student. TODO: config options
2200
2201
                    // AssignmentLinktoTeacherPage
2202
                    $all_students_pages[] = '<li>'.
2203
                        Display::tag(
2204
                            'span',
2205
                            strtoupper($o_user_to_add['lastname']).', '.$o_user_to_add['firstname'], array('title'=>$username)
2206
                        ).
2207
                        ' [['.Security::remove_XSS($_POST['title'])."_uass".$assig_user_id.' | '.$photo.']] '.$status_in_group.'</li>';
2208
                    //don't change this line without guaranteeing that users will be ordered by last names in the following format (surname, name)
2209
                    $values['assignment'] = 2;
2210
                }
2211
                $this->assig_user_id = $assig_user_id;
2212
                self::save_new_wiki($values);
2213
            }
2214
        }
2215
2216
        foreach ($a_users_to_add as $o_user_to_add) {
0 ignored issues
show
Bug introduced by
The expression $a_users_to_add of type array|integer is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
2217
            if ($o_user_to_add['user_id'] == $userId) {
2218
                $assig_user_id = $o_user_to_add['user_id'];
2219
                if ($assignment_type == 1) {
2220
                    $values['title'] = $title_orig;
2221
                    $values['comment'] = get_lang('AssignmentDesc');
2222
                    sort($all_students_pages);
2223
                    $values['content'] = $content_orig_A.$content_orig_B.'<br/>
2224
                    <div align="center" style="font-size:18px; background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2225
                    '.get_lang('AssignmentLinkstoStudentsPage').'
2226
                    </div><br/>
2227
                    <div style="background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2228
                    <ol>'.implode($all_students_pages).'</ol>
2229
                    </div>
2230
                    <br/>';
2231
                    $values['assignment'] = 1;
2232
                }
2233
                $this->assig_user_id = $assig_user_id;
2234
                self::save_new_wiki($values);
2235
            }
2236
        }
2237
    }
2238
2239
    /**
2240
     * Displays the results of a wiki search
2241
     * @param   string  Search term
2242
     * @param   int     Whether to search the contents (1) or just the titles (0)
2243
     * @param int
2244
     */
2245
    public function display_wiki_search_results($search_term, $search_content = 0, $all_vers = 0)
2246
    {
2247
        $tbl_wiki = $this->tbl_wiki;
2248
        $condition_session = $this->condition_session;
2249
        $groupfilter = $this->groupfilter;
2250
        $_course = $this->courseInfo;
2251
        $course_id = api_get_course_int_id();
2252
        echo '<legend>'.get_lang('WikiSearchResults').': '.Security::remove_XSS($search_term);
2253
        echo '</legend>';
2254
2255
        //only by professors when page is hidden
2256
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
2257 View Code Duplication
            if ($all_vers == '1') {
2258
                if ($search_content == '1') {
2259
                    $sql = "SELECT * FROM ".$tbl_wiki."
2260
                            WHERE
2261
                                c_id = $course_id AND
2262
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2263
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2264
                                ".$groupfilter.$condition_session."";
2265
                    //search all pages and all versions
2266
                } else {
2267
                    $sql = "SELECT * FROM ".$tbl_wiki."
2268
                            WHERE
2269
                                c_id = $course_id AND
2270
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2271
                                ".$groupfilter.$condition_session."";
2272
                    //search all pages and all versions
2273
                }
2274
            } else {
2275
                if ($search_content == '1') {
2276
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2277
                            WHERE
2278
                                s1.c_id = $course_id AND
2279
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2280
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2281
                                id=(
2282
                                    SELECT MAX(s2.id)
2283
                                    FROM ".$tbl_wiki." s2
2284
                                    WHERE
2285
                                        s2.c_id = $course_id AND
2286
                                        s1.reflink = s2.reflink AND
2287
                                        ".$groupfilter.$condition_session.")";
2288
                    // warning don't use group by reflink because don't return the last version
2289
                } else {
2290
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2291
                            WHERE
2292
                                s1.c_id = $course_id AND
2293
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2294
                                id = (
2295
                                    SELECT MAX(s2.id)
2296
                                    FROM ".$tbl_wiki." s2
2297
                                    WHERE
2298
                                        s2.c_id = $course_id AND
2299
                                        s1.reflink = s2.reflink AND
2300
                                        ".$groupfilter.$condition_session.")";
2301
                    // warning don't use group by reflink because don't return the last version
2302
                }
2303
            }
2304 View Code Duplication
        } else {
2305
            if ($all_vers == '1') {
2306
                if ($search_content == '1') {
2307
                    $sql = "SELECT * FROM ".$tbl_wiki."
2308
                            WHERE
2309
                                c_id = $course_id AND
2310
                                visibility=1 AND
2311
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2312
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2313
                                ".$groupfilter.$condition_session."";
2314
                    //search all pages and all versions
2315
                } else {
2316
                    $sql = "SELECT * FROM ".$tbl_wiki."
2317
                            WHERE
2318
                                c_id = $course_id AND
2319
                                visibility=1 AND
2320
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2321
                                ".$groupfilter.$condition_session."";
2322
                    //search all pages and all versions
2323
                }
2324
            } else {
2325
                if ($search_content == '1') {
2326
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2327
                            WHERE
2328
                                s1.c_id = $course_id AND
2329
                                visibility=1 AND
2330
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2331
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2332
                                id=(
2333
                                    SELECT MAX(s2.id)
2334
                                    FROM ".$tbl_wiki." s2
2335
                                    WHERE s2.c_id = $course_id AND
2336
                                    s1.reflink = s2.reflink AND
2337
                                    ".$groupfilter.$condition_session.")";
2338
                    // warning don't use group by reflink because don't return the last version
2339
                } else {
2340
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2341
                            WHERE
2342
                                s1.c_id = $course_id AND
2343
                                visibility=1 AND
2344
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2345
                            id = (
2346
                                SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
2347
                                WHERE s2.c_id = $course_id AND
2348
                                s1.reflink = s2.reflink AND
2349
                                ".$groupfilter.$condition_session.")";
2350
                    // warning don't use group by reflink because don't return the last version
2351
                }
2352
            }
2353
        }
2354
2355
        $result = Database::query($sql);
2356
2357
        //show table
2358
        $rows = array();
2359
        if (Database::num_rows($result) > 0) {
2360
            while ($obj = Database::fetch_object($result)) {
2361
                //get author
2362
                $userinfo = api_get_user_info($obj->user_id);
2363
2364
                //get time
2365
                $year = substr($obj->dtime, 0, 4);
2366
                $month = substr($obj->dtime, 5, 2);
2367
                $day = substr($obj->dtime, 8, 2);
2368
                $hours = substr($obj->dtime, 11, 2);
2369
                $minutes = substr($obj->dtime, 14, 2);
2370
                $seconds = substr($obj->dtime, 17, 2);
2371
2372
                //get type assignment icon
2373
                if ($obj->assignment == 1) {
2374
                    $ShowAssignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'), '', ICON_SIZE_SMALL);
2375
                } elseif ($obj->assignment == 2) {
2376
                    $ShowAssignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'), '', ICON_SIZE_SMALL);
2377
                } elseif ($obj->assignment == 0) {
2378
                    $ShowAssignment = Display::return_icon('px_transparent.gif');
2379
                }
2380
                $row = array();
2381
                $row[] = $ShowAssignment;
2382
2383
                if ($all_vers == '1') {
2384
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&view='.$obj->id.'&session_id='.api_htmlentities(urlencode($_GET['$session_id'])).'&group_id='.api_htmlentities(urlencode($_GET['group_id'])).'">'.
2385
                        api_htmlentities($obj->title).'</a>';
2386
                } else {
2387
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2388
                        $obj->title.'</a>';
2389
                }
2390
2391
                $row[] = ($obj->user_id != 0 && $userinfo !== false) ? UserManager::getUserProfileLink($userinfo) : get_lang('Anonymous').' ('.$obj->user_ip.')';
2392
                $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
2393
2394
                if ($all_vers == '1') {
2395
                    $row[] = $obj->version;
2396
                } else {
2397
                    $showdelete = '';
2398
                    if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
2399
                        $showdelete = ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=delete&title='.api_htmlentities(urlencode($obj->reflink)).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2400
                            Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
2401
                    }
2402
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit&title='.api_htmlentities(urlencode($obj->reflink)).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2403
                        Display::return_icon('edit.png', get_lang('EditPage'), '', ICON_SIZE_SMALL).'</a>
2404
                        <a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=discuss&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2405
                        Display::return_icon('discuss.png', get_lang('Discuss'), '', ICON_SIZE_SMALL).'</a>
2406
                        <a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=history&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2407
                        Display::return_icon('history.png', get_lang('History'), '', ICON_SIZE_SMALL).'</a> <a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=links&title='.api_htmlentities(urlencode($obj->reflink)).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2408
                        Display::return_icon('what_link_here.png', get_lang('LinksPages'), '', ICON_SIZE_SMALL).'</a>'.$showdelete;
2409
                }
2410
                $rows[] = $row;
2411
            }
2412
2413
            $table = new SortableTableFromArrayConfig(
2414
                $rows,
2415
                1,
2416
                10,
2417
                'SearchPages_table',
2418
                '',
2419
                '',
2420
                'ASC'
2421
            );
2422
            $table->set_additional_parameters(
2423
                array(
2424
                    'cidReq' => $_GET['cidReq'],
2425
                    'action' => $_GET['action'],
2426
                    'group_id' => intval($_GET['group_id']),
2427
                    'mode_table' => 'yes2',
2428
                    'search_term' => $search_term,
2429
                    'search_content' => $search_content,
2430
                    'all_vers' => $all_vers,
2431
                )
2432
            );
2433
            $table->set_header(0, get_lang('Type'), true, array('style' => 'width:30px;'));
2434
            $table->set_header(1, get_lang('Title'), true);
2435
            if ($all_vers == '1') {
2436
                $table->set_header(2, get_lang('Author'), true);
2437
                $table->set_header(3, get_lang('Date'), true);
2438
                $table->set_header(4, get_lang('Version'), true);
2439
            } else {
2440
                $table->set_header(2, get_lang('Author').' ('.get_lang('LastVersion').')', true);
2441
                $table->set_header(3, get_lang('Date').' ('.get_lang('LastVersion').')', true);
2442
                $table->set_header(4, get_lang('Actions'), false, array('style' => 'width:130px;'));
2443
            }
2444
            $table->display();
2445
        } else {
2446
            echo get_lang('NoSearchResults');
2447
        }
2448
    }
2449
2450
    /**
2451
     * Returns a date picker
2452
     * @todo replace this function with the formvalidator datepicker
2453
     *
2454
     */
2455
    public function draw_date_picker($prefix, $default = '')
2456
    {
2457
        if (empty($default)) {
2458
            $default = date('Y-m-d H:i:s');
2459
        }
2460
        $parts = explode(' ', $default);
2461
        list($d_year, $d_month, $d_day) = explode('-', $parts[0]);
2462
        list($d_hour, $d_minute) = explode(':', $parts[1]);
2463
2464
        $month_list = array(
2465
            1 => get_lang('JanuaryLong'),
2466
            2 => get_lang('FebruaryLong'),
2467
            3 => get_lang('MarchLong'),
2468
            4 => get_lang('AprilLong'),
2469
            5 => get_lang('MayLong'),
2470
            6 => get_lang('JuneLong'),
2471
            7 => get_lang('JulyLong'),
2472
            8 => get_lang('AugustLong'),
2473
            9 => get_lang('SeptemberLong'),
2474
            10 => get_lang('OctoberLong'),
2475
            11 => get_lang('NovemberLong'),
2476
            12 => get_lang('DecemberLong'),
2477
        );
2478
2479
        $minute = range(10, 59);
2480
        array_unshift($minute, '00', '01', '02', '03', '04', '05', '06', '07', '08', '09');
2481
        $date_form = self::make_select($prefix.'_day', array_combine(range(1, 31), range(1, 31)), $d_day);
2482
        $date_form .= self::make_select($prefix.'_month', $month_list, $d_month);
2483
        $date_form .= self::make_select(
2484
                $prefix.'_year',
2485
                array(
2486
                    $d_year - 2 => $d_year - 2,
2487
                    $d_year - 1 => $d_year - 1,
2488
                    $d_year => $d_year,
2489
                    $d_year + 1 => $d_year + 1,
2490
                    $d_year + 2 => $d_year + 2,
2491
                ),
2492
                $d_year
2493
            ).'&nbsp;&nbsp;&nbsp;&nbsp;';
2494
        $date_form .= self::make_select($prefix.'_hour', array_combine(range(0, 23), range(0, 23)), $d_hour).' : ';
2495
        $date_form .= self::make_select($prefix.'_minute', $minute, $d_minute);
2496
2497
        return $date_form;
2498
    }
2499
2500
    /**
2501
     * Draws an HTML form select with the given options
2502
     *
2503
     */
2504
    public function make_select($name, $values, $checked = '')
2505
    {
2506
        $output = '<select name="'.$name.'" id="'.$name.'">';
2507
        foreach ($values as $key => $value) {
2508
            $output .= '<option value="'.$key.'" '.(($checked == $key) ? 'selected="selected"' : '').'>'.$value.'</option>';
2509
        }
2510
        $output .= '</select>';
2511
        return $output;
2512
    }
2513
2514
    /**
2515
     * Translates a form date into a more usable format
2516
     *
2517
     */
2518
    public function get_date_from_select($prefix)
2519
    {
2520
        return $_POST[$prefix.'_year'].'-'.
2521
        self::two_digits($_POST[$prefix.'_month']).'-'.
2522
        self::two_digits($_POST[$prefix.'_day']).' '.
2523
        self::two_digits($_POST[$prefix.'_hour']).':'.
2524
        self::two_digits($_POST[$prefix.'_minute']).':00';
2525
    }
2526
2527
    /**
2528
     * Converts 1-9 to 01-09
2529
     */
2530
    public function two_digits($number)
2531
    {
2532
        $number = (int) $number;
2533
        return ($number < 10) ? '0'.$number : $number;
2534
    }
2535
2536
    /**
2537
     * Get wiki information
2538
     * @param   int|bool     wiki id
2539
     * @return  array   wiki data
2540
     */
2541
    public function getWikiDataFromDb($id)
2542
    {
2543
        $tbl_wiki = $this->tbl_wiki;
2544
        $course_id = api_get_course_int_id();
2545
        if ($id === false) {
2546
            return array();
2547
        }
2548
        $id = intval($id);
2549
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2550
                WHERE c_id = '.$course_id.' AND id = '.$id.' ';
2551
        $result = Database::query($sql);
2552
        $data = array();
2553
        while ($row = Database::fetch_array($result, 'ASSOC')) {
2554
            $data = $row;
2555
        }
2556
        return $data;
2557
    }
2558
2559
    /**
2560
     * @param string $refLink
2561
     * @return array
2562
     */
2563
    public function getLastWikiData($refLink)
2564
    {
2565
        $tbl_wiki = $this->tbl_wiki;
2566
        $groupfilter = $this->groupfilter;
2567
        $condition_session = $this->condition_session;
2568
        $course_id = api_get_course_int_id();
2569
2570
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2571
                WHERE
2572
                    c_id = '.$course_id.' AND
2573
                    reflink="'.Database::escape_string($refLink).'" AND
2574
                    '.$groupfilter.$condition_session.'
2575
                ORDER BY id DESC';
2576
2577
        $result = Database::query($sql);
2578
2579
        return Database::fetch_array($result);
2580
    }
2581
2582
    /**
2583
     * Get wiki information
2584
     * @param   string     wiki id
2585
     * @param int $courseId
2586
     * @return  array   wiki data
2587
     */
2588
    public function getPageByTitle($title, $courseId = null)
2589
    {
2590
        $tbl_wiki = $this->tbl_wiki;
2591
        if (empty($courseId)) {
2592
            $courseId = api_get_course_int_id();
2593
        } else {
2594
            $courseId = intval($courseId);
2595
        }
2596
2597
        if (empty($title) || empty($courseId)) {
2598
            return array();
2599
        }
2600
2601
        $title = Database::escape_string($title);
2602
        $sql = "SELECT * FROM $tbl_wiki
2603
                WHERE c_id = $courseId AND reflink = '$title'";
2604
        $result = Database::query($sql);
2605
        $data = array();
2606
        if (Database::num_rows($result)) {
2607
            $data = Database::fetch_array($result, 'ASSOC');
2608
        }
2609
2610
        return $data;
2611
    }
2612
2613
    /**
2614
     * @param string $title
2615
     * @param int $courseId
2616
     * @param string
2617
     * @param string
2618
     * @return bool
2619
     */
2620
    public function deletePage($title, $courseId, $groupfilter = null, $condition_session = null)
2621
    {
2622
        $tbl_wiki = $this->tbl_wiki;
2623
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
2624
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
2625
        $tbl_wiki_conf = $this->tbl_wiki_conf;
2626
2627
        $pageInfo = self::getPageByTitle($title, $courseId);
2628
        if (!empty($pageInfo)) {
2629
            $pageId = $pageInfo['id'];
2630
            $sql = "DELETE FROM $tbl_wiki_conf
2631
                    WHERE c_id = $courseId AND page_id = $pageId";
2632
            Database::query($sql);
2633
2634
            $sql = 'DELETE FROM '.$tbl_wiki_discuss.'
2635
                    WHERE c_id = '.$courseId.' AND publication_id = '.$pageId;
2636
            Database::query($sql);
2637
2638
            $sql = 'DELETE FROM  '.$tbl_wiki_mailcue.'
2639
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
2640
            Database::query($sql);
2641
2642
            $sql = 'DELETE FROM '.$tbl_wiki.'
2643
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
2644
            Database::query($sql);
2645
            self::check_emailcue(0, 'E');
2646
2647
            return true;
2648
        }
2649
2650
        return false;
2651
    }
2652
2653
    /**
2654
     * @return array
2655
     */
2656
    public function getAllWiki()
2657
    {
2658
        $tbl_wiki = $this->tbl_wiki;
2659
        $course_id = $this->course_id;
2660
        $condition_session = $this->condition_session;
2661
2662
        $sql = "SELECT * FROM $tbl_wiki
2663
                WHERE
2664
                    c_id = $course_id AND
2665
                    is_editing != '0' ".$condition_session;
2666
        $result = Database::query($sql);
2667
2668
        return Database::store_result($result, 'ASSOC');
2669
    }
2670
2671
    /**
2672
     * @param int $isEditing
2673
     */
2674
    public function updateWikiIsEditing($isEditing)
2675
    {
2676
        $tbl_wiki = $this->tbl_wiki;
2677
        $course_id = $this->course_id;
2678
        $condition_session = $this->condition_session;
2679
        $isEditing = Database::escape_string($isEditing);
2680
2681
        $sql = 'UPDATE '.$tbl_wiki.' SET
2682
                is_editing = "0",
2683
                time_edit = NULL
2684
                WHERE
2685
                    c_id = '.$course_id.' AND
2686
                    is_editing="'.$isEditing.'" '.
2687
            $condition_session;
2688
        Database::query($sql);
2689
    }
2690
2691
    /**
2692
     * Release of blocked pages to prevent concurrent editions
2693
     * @param int $userId
2694
     * @param string $action
2695
     */
2696
    public function blockConcurrentEditions($userId, $action = null)
2697
    {
2698
        $result = self::getAllWiki();
2699
        if (!empty($result)) {
2700
            foreach ($result  as $is_editing_block) {
2701
                $max_edit_time = 1200; // 20 minutes
2702
                $timestamp_edit = strtotime($is_editing_block['time_edit']);
2703
                $time_editing = time() - $timestamp_edit;
2704
2705
                // First prevent concurrent users and double version
2706
                if ($is_editing_block['is_editing'] == $userId) {
2707
                    Session::write('_version', $is_editing_block['version']);
2708
                } else {
2709
                    Session::erase('_version');
2710
                }
2711
                // Second checks if has exceeded the time that a page may be available or if a page was edited and saved by its author
2712
                if ($time_editing > $max_edit_time || ($is_editing_block['is_editing'] == $userId && $action != 'edit')) {
2713
                    self::updateWikiIsEditing($is_editing_block['is_editing']);
2714
                }
2715
            }
2716
        }
2717
    }
2718
2719
    /**
2720
     * Showing wiki stats
2721
     */
2722
    public function getStats()
2723
    {
2724
        if (!api_is_allowed_to_edit(false, true)) {
2725
            return false;
2726
        }
2727
2728
        $tbl_wiki = $this->tbl_wiki;
2729
        $course_id = $this->course_id;
2730
        $condition_session = $this->condition_session;
2731
        $groupfilter = $this->groupfilter;
2732
        $session_id = $this->session_id;
2733
        $tbl_wiki_conf = $this->tbl_wiki_conf;
2734
2735
        echo '<div class="actions">'.get_lang('Statistics').'</div>';
2736
2737
        // Check all versions of all pages
2738
        $total_words = 0;
2739
        $total_links = 0;
2740
        $total_links_anchors = 0;
2741
        $total_links_mail = 0;
2742
        $total_links_ftp = 0;
2743
        $total_links_irc = 0;
2744
        $total_links_news = 0;
2745
        $total_wlinks = 0;
2746
        $total_images = 0;
2747
        $clean_total_flash = 0;
2748
        $total_flash = 0;
2749
        $total_mp3 = 0;
2750
        $total_flv_p = 0;
2751
        $total_flv = 0;
2752
        $total_youtube = 0;
2753
        $total_multimedia = 0;
2754
        $total_tables = 0;
2755
2756
        $sql = "SELECT *, COUNT(*) AS TOTAL_VERS, SUM(hits) AS TOTAL_VISITS
2757
                FROM ".$tbl_wiki."
2758
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
2759
2760
        $allpages = Database::query($sql);
2761
        while ($row = Database::fetch_array($allpages)) {
2762
            $total_versions = $row['TOTAL_VERS'];
2763
            $total_visits = intval($row['TOTAL_VISITS']);
2764
        }
2765
2766
        $sql = "SELECT * FROM ".$tbl_wiki."
2767
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
2768
        $allpages = Database::query($sql);
2769
2770 View Code Duplication
        while ($row = Database::fetch_array($allpages)) {
2771
            $total_words = $total_words + self::word_count($row['content']);
2772
            $total_links = $total_links + substr_count($row['content'], "href=");
2773
            $total_links_anchors = $total_links_anchors + substr_count($row['content'], 'href="#');
2774
            $total_links_mail = $total_links_mail + substr_count($row['content'], 'href="mailto');
2775
            $total_links_ftp = $total_links_ftp + substr_count($row['content'], 'href="ftp');
2776
            $total_links_irc = $total_links_irc + substr_count($row['content'], 'href="irc');
2777
            $total_links_news = $total_links_news + substr_count($row['content'], 'href="news');
2778
            $total_wlinks = $total_wlinks + substr_count($row['content'], "[[");
2779
            $total_images = $total_images + substr_count($row['content'], "<img");
2780
            $clean_total_flash = preg_replace('/player.swf/', ' ', $row['content']);
2781
            $total_flash = $total_flash + substr_count($clean_total_flash, '.swf"');
2782
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
2783
            $total_mp3 = $total_mp3 + substr_count($row['content'], ".mp3");
2784
            $total_flv_p = $total_flv_p + substr_count($row['content'], ".flv");
2785
            $total_flv = $total_flv_p / 5;
2786
            $total_youtube = $total_youtube + substr_count($row['content'], "http://www.youtube.com");
2787
            $total_multimedia = $total_multimedia + substr_count($row['content'], "video/x-msvideo");
2788
            $total_tables = $total_tables + substr_count($row['content'], "<table");
2789
        }
2790
2791
        // Check only last version of all pages (current page)
2792
        $sql = ' SELECT *, COUNT(*) AS TOTAL_PAGES, SUM(hits) AS TOTAL_VISITS_LV
2793
                FROM  '.$tbl_wiki.' s1
2794
                WHERE s1.c_id = '.$course_id.' AND id=(
2795
                    SELECT MAX(s2.id)
2796
                    FROM '.$tbl_wiki.' s2
2797
                    WHERE
2798
                        s2.c_id = '.$course_id.' AND
2799
                        s1.reflink = s2.reflink AND
2800
                        '.$groupfilter.' AND
2801
                        session_id='.$session_id.')';
2802
        $allpages = Database::query($sql);
2803
        while ($row = Database::fetch_array($allpages)) {
2804
            $total_pages = $row['TOTAL_PAGES'];
2805
            $total_visits_lv = intval($row['TOTAL_VISITS_LV']);
2806
        }
2807
2808
        $total_words_lv = 0;
2809
        $total_links_lv = 0;
2810
        $total_links_anchors_lv = 0;
2811
        $total_links_mail_lv = 0;
2812
        $total_links_ftp_lv = 0;
2813
        $total_links_irc_lv = 0;
2814
        $total_links_news_lv = 0;
2815
        $total_wlinks_lv = 0;
2816
        $total_images_lv = 0;
2817
        $clean_total_flash_lv = 0;
2818
        $total_flash_lv = 0;
2819
        $total_mp3_lv = 0;
2820
        $total_flv_p_lv = 0;
2821
        $total_flv_lv = 0;
2822
        $total_youtube_lv = 0;
2823
        $total_multimedia_lv = 0;
2824
        $total_tables_lv = 0;
2825
2826
        $sql = 'SELECT * FROM  '.$tbl_wiki.' s1
2827
                WHERE s1.c_id = '.$course_id.' AND id=(
2828
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
2829
                    WHERE
2830
                        s2.c_id = '.$course_id.' AND
2831
                        s1.reflink = s2.reflink AND
2832
                        '.$groupfilter.' AND
2833
                        session_id='.$session_id.'
2834
                )';
2835
        $allpages = Database::query($sql);
2836
2837 View Code Duplication
        while ($row = Database::fetch_array($allpages)) {
2838
            $total_words_lv = $total_words_lv + self::word_count($row['content']);
2839
            $total_links_lv = $total_links_lv + substr_count($row['content'], "href=");
2840
            $total_links_anchors_lv = $total_links_anchors_lv + substr_count($row['content'], 'href="#');
2841
            $total_links_mail_lv = $total_links_mail_lv + substr_count($row['content'], 'href="mailto');
2842
            $total_links_ftp_lv = $total_links_ftp_lv + substr_count($row['content'], 'href="ftp');
2843
            $total_links_irc_lv = $total_links_irc_lv + substr_count($row['content'], 'href="irc');
2844
            $total_links_news_lv = $total_links_news_lv + substr_count($row['content'], 'href="news');
2845
            $total_wlinks_lv = $total_wlinks_lv + substr_count($row['content'], "[[");
2846
            $total_images_lv = $total_images_lv + substr_count($row['content'], "<img");
2847
            $clean_total_flash_lv = preg_replace('/player.swf/', ' ', $row['content']);
2848
            $total_flash_lv = $total_flash_lv + substr_count($clean_total_flash_lv, '.swf"');
2849
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
2850
            $total_mp3_lv = $total_mp3_lv + substr_count($row['content'], ".mp3");
2851
            $total_flv_p_lv = $total_flv_p_lv + substr_count($row['content'], ".flv");
2852
            $total_flv_lv = $total_flv_p_lv / 5;
2853
            $total_youtube_lv = $total_youtube_lv + substr_count($row['content'], "http://www.youtube.com");
2854
            $total_multimedia_lv = $total_multimedia_lv + substr_count($row['content'], "video/x-msvideo");
2855
            $total_tables_lv = $total_tables_lv + substr_count($row['content'], "<table");
2856
        }
2857
2858
        //Total pages edited at this time
2859
        $total_editing_now = 0;
2860
        $sql = 'SELECT *, COUNT(*) AS TOTAL_EDITING_NOW
2861
                FROM  '.$tbl_wiki.' s1
2862
                WHERE is_editing!=0 AND s1.c_id = '.$course_id.' AND
2863
                id=(
2864
                    SELECT MAX(s2.id)
2865
                    FROM '.$tbl_wiki.' s2
2866
                    WHERE
2867
                        s2.c_id = '.$course_id.' AND
2868
                        s1.reflink = s2.reflink AND
2869
                        '.$groupfilter.' AND
2870
                        session_id='.$session_id.'
2871
        )';
2872
2873
        // Can not use group by because the mark is set in the latest version
2874
        $allpages = Database::query($sql);
2875
        while ($row = Database::fetch_array($allpages)) {
2876
            $total_editing_now = $row['TOTAL_EDITING_NOW'];
2877
        }
2878
2879
        // Total hidden pages
2880
        $total_hidden = 0;
2881
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2882
                WHERE  
2883
                    c_id = '.$course_id.' AND 
2884
                    visibility = 0 AND 
2885
                    '.$groupfilter.$condition_session.'
2886
                GROUP BY reflink';
2887
        // or group by page_id. As the mark of hidden places it in all versions of the page, I can use group by to see the first
2888
        $allpages = Database::query($sql);
2889
        while ($row = Database::fetch_array($allpages)) {
2890
            $total_hidden = $total_hidden + 1;
2891
        }
2892
2893
        //Total protect pages
2894
        $total_protected = 0;
2895
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2896
                WHERE  c_id = '.$course_id.' AND editlock=1 AND '.$groupfilter.$condition_session.'
2897
                GROUP BY reflink';
2898
        // or group by page_id. As the mark of protected page is the first version of the page, I can use group by
2899
2900
        $allpages = Database::query($sql);
2901
        while ($row = Database::fetch_array($allpages)) {
2902
            $total_protected = $total_protected + 1;
2903
        }
2904
2905
        // Total empty versions.
2906
        $total_empty_content = 0;
2907
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2908
                WHERE
2909
                    c_id = '.$course_id.' AND
2910
                    content="" AND
2911
                    '.$groupfilter.$condition_session.'';
2912
        $allpages = Database::query($sql);
2913
        while ($row = Database::fetch_array($allpages)) {
2914
            $total_empty_content = $total_empty_content + 1;
2915
        }
2916
2917
        //Total empty pages (last version)
2918
2919
        $total_empty_content_lv = 0;
2920
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
2921
                WHERE s1.c_id = '.$course_id.' AND content="" AND id=(
2922
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
2923
                    WHERE 
2924
                        s1.c_id = '.$course_id.' AND 
2925
                        s1.reflink = s2.reflink AND 
2926
                        '.$groupfilter.' AND 
2927
                        session_id='.$session_id.'
2928
                )';
2929
        $allpages = Database::query($sql);
2930
        while ($row = Database::fetch_array($allpages)) {
2931
            $total_empty_content_lv = $total_empty_content_lv + 1;
2932
        }
2933
2934
        // Total locked discuss pages
2935
        $total_lock_disc = 0;
2936
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2937
                WHERE c_id = '.$course_id.' AND addlock_disc=0 AND '.$groupfilter.$condition_session.'
2938
                GROUP BY reflink';//group by because mark lock in all vers, then always is ok
2939
        $allpages = Database::query($sql);
2940
        while ($row = Database::fetch_array($allpages)) {
2941
            $total_lock_disc = $total_lock_disc + 1;
2942
        }
2943
2944
        // Total hidden discuss pages.
2945
        $total_hidden_disc = 0;
2946
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2947
                WHERE c_id = '.$course_id.' AND visibility_disc=0 AND '.$groupfilter.$condition_session.'
2948
                GROUP BY reflink';
2949
        //group by because mark lock in all vers, then always is ok
2950
        $allpages = Database::query($sql);
2951
        while ($row = Database::fetch_array($allpages)) {
2952
            $total_hidden_disc = $total_hidden_disc + 1;
2953
        }
2954
2955
        // Total versions with any short comment by user or system
2956
        $total_comment_version = 0;
2957
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2958
                WHERE c_id = '.$course_id.' AND comment!="" AND '.$groupfilter.$condition_session.'';
2959
        $allpages = Database::query($sql);
2960
        while ($row = Database::fetch_array($allpages)) {
2961
            $total_comment_version = $total_comment_version + 1;
2962
        }
2963
2964
        // Total pages that can only be scored by teachers.
2965
        $total_only_teachers_rating = 0;
2966
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2967
                WHERE c_id = '.$course_id.' AND
2968
                ratinglock_disc = 0 AND
2969
                '.$groupfilter.$condition_session.'
2970
                GROUP BY reflink';//group by because mark lock in all vers, then always is ok
2971
        $allpages = Database::query($sql);
2972
        while ($row = Database::fetch_array($allpages)) {
2973
            $total_only_teachers_rating = $total_only_teachers_rating + 1;
2974
        }
2975
2976
        // Total pages scored by peers
2977
        // put always this line alfter check num all pages and num pages rated by teachers
2978
        $total_rating_by_peers = $total_pages - $total_only_teachers_rating;
2979
2980
        //Total pages identified as standard task
2981
        $total_task = 0;
2982
        $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
2983
              WHERE '.$tbl_wiki_conf.'.c_id = '.$course_id.' AND
2984
               '.$tbl_wiki_conf.'.task!="" AND
2985
               '.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
2986
                '.$tbl_wiki.'.'.$groupfilter.$condition_session;
2987
        $allpages = Database::query($sql);
2988
        while ($row = Database::fetch_array($allpages)) {
2989
            $total_task = $total_task + 1;
2990
        }
2991
2992
        //Total pages identified as teacher page (wiki portfolio mode - individual assignment)
2993
        $total_teacher_assignment = 0;
2994
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
2995
                WHERE s1.c_id = '.$course_id.' AND assignment=1 AND id=(
2996
                    SELECT MAX(s2.id)
2997
                    FROM '.$tbl_wiki.' s2
2998
                    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.' AND session_id='.$session_id.'
2999
                )';
3000
        //mark all versions, but do not use group by reflink because y want the pages not versions
3001
        $allpages = Database::query($sql);
3002
        while ($row = Database::fetch_array($allpages)) {
3003
            $total_teacher_assignment = $total_teacher_assignment + 1;
3004
        }
3005
3006
        //Total pages identifies as student page (wiki portfolio mode - individual assignment)
3007
        $total_student_assignment = 0;
3008
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3009
                WHERE s1.c_id = '.$course_id.' AND assignment=2 AND
3010
                id=(SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3011
                WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.' AND session_id='.$session_id.')';
3012
        //mark all versions, but do not use group by reflink because y want the pages not versions
3013
        $allpages = Database::query($sql);
3014
        while ($row = Database::fetch_array($allpages)) {
3015
            $total_student_assignment = $total_student_assignment + 1;
3016
        }
3017
3018
        //Current Wiki status add new pages
3019
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3020
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3021
                GROUP BY addlock';//group by because mark 0 in all vers, then always is ok
3022
        $allpages = Database::query($sql);
3023
        $wiki_add_lock = null;
3024
        while ($row = Database::fetch_array($allpages)) {
3025
            $wiki_add_lock = $row['addlock'];
3026
        }
3027
3028
        if ($wiki_add_lock == 1) {
3029
            $status_add_new_pag = get_lang('Yes');
3030
        } else {
3031
            $status_add_new_pag = get_lang('No');
3032
        }
3033
3034
        //Creation date of the oldest wiki page and version
3035
3036
        $first_wiki_date = null;
3037
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3038
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3039
                ORDER BY dtime ASC 
3040
                LIMIT 1';
3041
        $allpages = Database::query($sql);
3042
        while ($row = Database::fetch_array($allpages)) {
3043
            $first_wiki_date = $row['dtime'];
3044
        }
3045
3046
        // Date of publication of the latest wiki version.
3047
3048
        $last_wiki_date = null;
3049
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3050
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3051
                ORDER BY dtime DESC 
3052
                LIMIT 1';
3053
        $allpages = Database::query($sql);
3054
        while ($row = Database::fetch_array($allpages)) {
3055
            $last_wiki_date = $row['dtime'];
3056
        }
3057
3058
        // Average score of all wiki pages. (If a page has not scored zero rated)
3059
        $media_score = 0;
3060
        $sql = "SELECT *, SUM(score) AS TOTAL_SCORE FROM ".$tbl_wiki."
3061
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."
3062
                GROUP BY reflink ";
3063
        //group by because mark in all versions, then always is ok.
3064
        // Do not use "count" because using "group by", would give a wrong value
3065
        $allpages = Database::query($sql);
3066
        $total_score = 0;
3067
        while ($row = Database::fetch_array($allpages)) {
3068
            $total_score = $total_score + $row['TOTAL_SCORE'];
3069
        }
3070
3071
        if (!empty($total_pages)) {
3072
            $media_score = $total_score / $total_pages;
3073
            //put always this line alfter check num all pages
3074
        }
3075
3076
        // Average user progress in his pages.
3077
        $media_progress = 0;
3078
        $sql = 'SELECT  *, SUM(progress) AS TOTAL_PROGRESS
3079
                FROM  '.$tbl_wiki.' s1
3080
                WHERE s1.c_id = '.$course_id.' AND id=
3081
                (
3082
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3083
                    WHERE
3084
                        s2.c_id = '.$course_id.' AND
3085
                        s1.reflink = s2.reflink AND
3086
                        '.$groupfilter.' AND
3087
                        session_id='.$session_id.')';
3088
        // As the value is only the latest version I can not use group by
3089
        $allpages = Database::query($sql);
3090
        while ($row = Database::fetch_array($allpages)) {
3091
            $total_progress = $row['TOTAL_PROGRESS'];
3092
        }
3093
3094
        if (!empty($total_pages)) {
3095
            $media_progress = $total_progress / $total_pages;
3096
            //put always this line alfter check num all pages
3097
        }
3098
3099
        // Total users that have participated in the Wiki
3100
        $total_users = 0;
3101
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3102
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3103
                GROUP BY user_id';
3104
        //as the mark of user it in all versions of the page, I can use group by to see the first
3105
        $allpages = Database::query($sql);
3106
        while ($row = Database::fetch_array($allpages)) {
3107
            $total_users = $total_users + 1;
3108
        }
3109
3110
        // Total of different IP addresses that have participated in the wiki
3111
        $total_ip = 0;
3112
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3113
              WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3114
              GROUP BY user_ip';
3115
        $allpages = Database::query($sql);
3116
        while ($row = Database::fetch_array($allpages)) {
3117
            $total_ip = $total_ip + 1;
3118
        }
3119
3120
        echo '<table class="data_table">';
3121
        echo '<thead>';
3122
        echo '<tr>';
3123
        echo '<th colspan="2">'.get_lang('General').'</th>';
3124
        echo '</tr>';
3125
        echo '</thead>';
3126
        echo '<tr>';
3127
        echo '<td>'.get_lang('StudentAddNewPages').'</td>';
3128
        echo '<td>'.$status_add_new_pag.'</td>';
3129
        echo '</tr>';
3130
        echo '<tr>';
3131
        echo '<td>'.get_lang('DateCreateOldestWikiPage').'</td>';
3132
        echo '<td>'.$first_wiki_date.'</td>';
3133
        echo '</tr>';
3134
        echo '<tr>';
3135
        echo '<td>'.get_lang('DateEditLatestWikiVersion').'</td>';
3136
        echo '<td>'.$last_wiki_date.'</td>';
3137
        echo '</tr>';
3138
        echo '<tr>';
3139
        echo '<td>'.get_lang('AverageScoreAllPages').'</td>';
3140
        echo '<td>'.$media_score.' %</td>';
3141
        echo '</tr>';
3142
        echo '<tr>';
3143
        echo '<td>'.get_lang('AverageMediaUserProgress').'</td>';
3144
        echo '<td>'.$media_progress.' %</td>';
3145
        echo '</tr>';
3146
        echo '<tr>';
3147
        echo '<td>'.get_lang('TotalWikiUsers').'</td>';
3148
        echo '<td>'.$total_users.'</td>';
3149
        echo '</tr>';
3150
        echo '<tr>';
3151
        echo '<td>'.get_lang('TotalIpAdress').'</td>';
3152
        echo '<td>'.$total_ip.'</td>';
3153
        echo '</tr>';
3154
        echo '</table>';
3155
        echo '<br/>';
3156
3157
        echo '<table class="data_table">';
3158
        echo '<thead>';
3159
        echo '<tr>';
3160
        echo '<th colspan="2">'.get_lang('Pages').' '.get_lang('And').' '.get_lang('Versions').'</th>';
3161
        echo '</tr>';
3162
        echo '</thead>';
3163
        echo '<tr>';
3164
        echo '<td>'.get_lang('Pages').' - '.get_lang('NumContributions').'</td>';
3165
        echo '<td>'.$total_pages.' ('.get_lang('Versions').': '.$total_versions.')</td>';
3166
        echo '</tr>';
3167
        echo '<tr>';
3168
        echo '<td>'.get_lang('EmptyPages').'</td>';
3169
        echo '<td>'.$total_empty_content_lv.' ('.get_lang('Versions').': '.$total_empty_content.')</td>';
3170
        echo '</tr>';
3171
        echo '<tr>';
3172
        echo '<td>'.get_lang('NumAccess').'</td>';
3173
        echo '<td>'.$total_visits_lv.' ('.get_lang('Versions').': '.$total_visits.')</td>';
3174
        echo '</tr>';
3175
        echo '<tr>';
3176
        echo '<td>'.get_lang('TotalPagesEditedAtThisTime').'</td>';
3177
        echo '<td>'.$total_editing_now.'</td>';
3178
        echo '</tr>';
3179
        echo '<tr>';
3180
        echo '<td>'.get_lang('TotalHiddenPages').'</td>';
3181
        echo '<td>'.$total_hidden.'</td>';
3182
        echo '</tr>';
3183
        echo '<tr>';
3184
        echo '<td>'.get_lang('NumProtectedPages').'</td>';
3185
        echo '<td>'.$total_protected.'</td>';
3186
        echo '</tr>';
3187
        echo '<tr>';
3188
        echo '<td>'.get_lang('LockedDiscussPages').'</td>';
3189
        echo '<td>'.$total_lock_disc.'</td>';
3190
        echo '</tr>';
3191
        echo '<tr>';
3192
        echo '<td>'.get_lang('HiddenDiscussPages').'</td>';
3193
        echo '<td>'.$total_hidden_disc.'</td>';
3194
        echo '</tr>';
3195
        echo '<tr>';
3196
        echo '<td>'.get_lang('TotalComments').'</td>';
3197
        echo '<td>'.$total_comment_version.'</td>';
3198
        echo '</tr>';
3199
        echo '<tr>';
3200
        echo '<td>'.get_lang('TotalOnlyRatingByTeacher').'</td>';
3201
        echo '<td>'.$total_only_teachers_rating.'</td>';
3202
        echo '</tr>';
3203
        echo '<tr>';
3204
        echo '<td>'.get_lang('TotalRatingPeers').'</td>';
3205
        echo '<td>'.$total_rating_by_peers.'</td>';
3206
        echo '</tr>';
3207
        echo '<tr>';
3208
        echo '<td>'.get_lang('TotalTeacherAssignments').' - '.get_lang('PortfolioMode').'</td>';
3209
        echo '<td>'.$total_teacher_assignment.'</td>';
3210
        echo '</tr>';
3211
        echo '<tr>';
3212
        echo '<td>'.get_lang('TotalStudentAssignments').' - '.get_lang('PortfolioMode').'</td>';
3213
        echo '<td>'.$total_student_assignment.'</td>';
3214
        echo '</tr>';
3215
        echo '<tr>';
3216
        echo '<td>'.get_lang('TotalTask').' - '.get_lang('StandardMode').'</td>';
3217
        echo '<td>'.$total_task.'</td>';
3218
        echo '</tr>';
3219
        echo '</table>';
3220
        echo '<br/>';
3221
3222
        echo '<table class="data_table">';
3223
        echo '<thead>';
3224
        echo '<tr>';
3225
        echo '<th colspan="3">'.get_lang('ContentPagesInfo').'</th>';
3226
        echo '</tr>';
3227
        echo '<tr>';
3228
        echo '<td></td>';
3229
        echo '<td>'.get_lang('InTheLastVersion').'</td>';
3230
        echo '<td>'.get_lang('InAllVersions').'</td>';
3231
        echo '</tr>';
3232
        echo '</thead>';
3233
        echo '<tr>';
3234
        echo '<td>'.get_lang('NumWords').'</td>';
3235
        echo '<td>'.$total_words_lv.'</td>';
3236
        echo '<td>'.$total_words.'</td>';
3237
        echo '</tr>';
3238
        echo '<tr>';
3239
        echo '<td>'.get_lang('NumlinksHtmlImagMedia').'</td>';
3240
        echo '<td>'.$total_links_lv.' ('.get_lang('Anchors').':'.$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>';
3241
        echo '<td>'.$total_links.' ('.get_lang('Anchors').':'.$total_links_anchors.', Mail:'.$total_links_mail.', FTP:'.$total_links_ftp.', IRC:'.$total_links_irc.', News:'.$total_links_news.', ... ) </td>';
3242
        echo '</tr>';
3243
        echo '<tr>';
3244
        echo '<td>'.get_lang('NumWikilinks').'</td>';
3245
        echo '<td>'.$total_wlinks_lv.'</td>';
3246
        echo '<td>'.$total_wlinks.'</td>';
3247
        echo '</tr>';
3248
        echo '<tr>';
3249
        echo '<td>'.get_lang('NumImages').'</td>';
3250
        echo '<td>'.$total_images_lv.'</td>';
3251
        echo '<td>'.$total_images.'</td>';
3252
        echo '</tr>';
3253
        echo '<tr>';
3254
        echo '<td>'.get_lang('NumFlash').'</td>';
3255
        echo '<td>'.$total_flash_lv.'</td>';
3256
        echo '<td>'.$total_flash.'</td>';
3257
        echo '</tr>';
3258
        echo '<tr>';
3259
        echo '<td>'.get_lang('NumMp3').'</td>';
3260
        echo '<td>'.$total_mp3_lv.'</td>';
3261
        echo '<td>'.$total_mp3.'</td>';
3262
        echo '</tr>';
3263
        echo '<tr>';
3264
        echo '<td>'.get_lang('NumFlvVideo').'</td>';
3265
        echo '<td>'.$total_flv_lv.'</td>';
3266
        echo '<td>'.$total_flv.'</td>';
3267
        echo '</tr>';
3268
        echo '<tr>';
3269
        echo '<td>'.get_lang('NumYoutubeVideo').'</td>';
3270
        echo '<td>'.$total_youtube_lv.'</td>';
3271
        echo '<td>'.$total_youtube.'</td>';
3272
        echo '</tr>';
3273
        echo '<tr>';
3274
        echo '<td>'.get_lang('NumOtherAudioVideo').'</td>';
3275
        echo '<td>'.$total_multimedia_lv.'</td>';
3276
        echo '<td>'.$total_multimedia.'</td>';
3277
        echo '</tr>';
3278
        echo '<tr>';
3279
        echo '<td>'.get_lang('NumTables').'</td>';
3280
        echo '<td>'.$total_tables_lv.'</td>';
3281
        echo '<td>'.$total_tables.'</td>';
3282
        echo '</tr>';
3283
        echo '</table>';
3284
    }
3285
3286
    /**
3287
     * @param string $action
3288
     */
3289
    public function getActiveUsers($action)
3290
    {
3291
        $tbl_wiki = $this->tbl_wiki;
3292
        $course_id = $this->course_id;
3293
        $condition_session = $this->condition_session;
3294
        $groupfilter = $this->groupfilter;
3295
        $_course = $this->courseInfo;
3296
3297
        echo '<div class="actions">'.get_lang('MostActiveUsers').'</div>';
3298
        $sql = 'SELECT *, COUNT(*) AS NUM_EDIT FROM '.$tbl_wiki.'
3299
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3300
                GROUP BY user_id';
3301
        $allpages = Database::query($sql);
3302
3303
        //show table
3304
        if (Database::num_rows($allpages) > 0) {
3305
            while ($obj = Database::fetch_object($allpages)) {
3306
                $userinfo = api_get_user_info($obj->user_id);
3307
                $row = array();
3308
                if ($obj->user_id != 0 && $userinfo !== false) {
3309
                    $row[] = UserManager::getUserProfileLink($userinfo).'
3310
                            <a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode($obj->user_id).
3311
                        '&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'"></a>';
3312
                } else {
3313
                    $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
3314
                }
3315
                $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode($obj->user_id).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.$obj->NUM_EDIT.'</a>';
3316
                $rows[] = $row;
3317
            }
3318
3319
            $table = new SortableTableFromArrayConfig($rows, 1, 10, 'MostActiveUsersA_table', '', '', 'DESC');
3320
            $table->set_additional_parameters(
3321
                array(
3322
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
3323
                    'action' => Security::remove_XSS($action),
3324
                    'session_id' => Security::remove_XSS($_GET['session_id']),
3325
                    'group_id' => Security::remove_XSS($_GET['group_id'])
3326
                )
3327
            );
3328
            $table->set_header(0, get_lang('Author'), true);
3329
            $table->set_header(1, get_lang('Contributions'), true, array('style' => 'width:30px;'));
3330
            $table->display();
3331
        }
3332
    }
3333
3334
    /**
3335
     * @param string $page
3336
     */
3337
    public function getDiscuss($page)
3338
    {
3339
        $tbl_wiki = $this->tbl_wiki;
3340
        $course_id = $this->course_id;
3341
        $condition_session = $this->condition_session;
3342
        $groupfilter = $this->groupfilter;
3343
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
3344
3345 View Code Duplication
        if (api_get_session_id() != 0 &&
3346
            api_is_allowed_to_session_edit(false, true) == false
3347
        ) {
3348
            api_not_allowed();
3349
        }
3350
3351 View Code Duplication
        if (!$_GET['title']) {
3352
            Display::addFlash(Display::return_message(get_lang("MustSelectPage"), 'error', false));
3353
            return;
3354
        }
3355
3356
        // First extract the date of last version
3357
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3358
                WHERE
3359
                    c_id = '.$course_id.' AND
3360
                    reflink = "'.Database::escape_string($page).'" AND
3361
                    '.$groupfilter.$condition_session.'
3362
                ORDER BY id DESC';
3363
        $result = Database::query($sql);
3364
        $row = Database::fetch_array($result);
3365
        $lastversiondate = api_get_local_time($row['dtime']);
3366
        $lastuserinfo = api_get_user_info($row['user_id']);
3367
3368
        // Select page to discuss
3369
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3370
                WHERE
3371
                    c_id = '.$course_id.' AND
3372
                    reflink="'.Database::escape_string($page).'" AND
3373
                    '.$groupfilter.$condition_session.'
3374
                ORDER BY id ASC';
3375
        $result = Database::query($sql);
3376
        $row = Database::fetch_array($result);
3377
        $id = $row['id'];
3378
        $firstuserid = $row['user_id'];
3379
3380
        if (isset($_POST['Submit']) && self::double_post($_POST['wpost_id'])) {
3381
            $dtime = api_get_utc_datetime();
3382
            $message_author = api_get_user_id();
3383
3384
            $params = [
3385
                'c_id' => $course_id,
3386
                'publication_id' => $id,
3387
                'userc_id' => $message_author,
3388
                'comment' => $_POST['comment'],
3389
                'p_score' => $_POST['rating'],
3390
                'dtime' => $dtime
3391
            ];
3392
            $discussId = Database::insert($tbl_wiki_discuss, $params);
3393
            if ($discussId) {
3394
                $sql = "UPDATE $tbl_wiki_discuss SET id = iid WHERE iid = $discussId";
3395
                Database::query($sql);
3396
            }
3397
3398
            self::check_emailcue($id, 'D', $dtime, $message_author);
0 ignored issues
show
Bug introduced by
It seems like $dtime defined by api_get_utc_datetime() on line 3381 can also be of type null or object<DateTime>; however, Wiki::check_emailcue() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
3399
3400
            header('Location: index.php?action=discuss&title='.api_htmlentities(urlencode($page)).'&'.api_get_cidreq());
3401
            exit;
3402
        }
3403
3404
        //mode assignment: previous to show  page type
3405
        $icon_assignment = null;
3406 View Code Duplication
        if ($row['assignment'] == 1) {
3407
            $icon_assignment = Display::return_icon(
3408
                'wiki_assignment.png',
3409
                get_lang('AssignmentDescExtra'),
3410
                '',
3411
                ICON_SIZE_SMALL
3412
            );
3413
        } elseif ($row['assignment'] == 2) {
3414
            $icon_assignment = Display::return_icon(
3415
                'wiki_work.png',
3416
                get_lang('AssignmentWorkExtra'),
3417
                '',
3418
                ICON_SIZE_SMALL
3419
            );
3420
        }
3421
3422
        $countWPost = null;
3423
        $avg_WPost_score = null;
3424
3425
3426
        // Show title and form to discuss if page exist
3427
        if ($id != '') {
3428
            // Show discussion to students if isn't hidden.
3429
            // Show page to all teachers if is hidden.
3430
            // Mode assignments: If is hidden, show pages to student only if student is the author
3431
            if ($row['visibility_disc'] == 1 ||
3432
                api_is_allowed_to_edit(false, true) ||
3433
                api_is_platform_admin() ||
3434
                ($row['assignment'] == 2 && $row['visibility_disc'] == 0 && (api_get_user_id() == $row['user_id']))
3435
            ) {
3436
                echo '<div id="wikititle">';
3437
                // discussion action: protecting (locking) the discussion
3438
                $addlock_disc = null;
3439
                $lock_unlock_disc = null;
3440 View Code Duplication
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3441
                    if (self::check_addlock_discuss() == 1) {
3442
                        $addlock_disc = Display::return_icon(
3443
                            'unlock.png',
3444
                            get_lang('UnlockDiscussExtra'),
3445
                            '',
3446
                            ICON_SIZE_SMALL
3447
                        );
3448
                        $lock_unlock_disc = 'unlockdisc';
3449
                    } else {
3450
                        $addlock_disc = Display::return_icon(
3451
                            'lock.png',
3452
                            get_lang('LockDiscussExtra'),
3453
                            '',
3454
                            ICON_SIZE_SMALL
3455
                        );
3456
                        $lock_unlock_disc = 'lockdisc';
3457
                    }
3458
                }
3459
                echo '<span style="float:right">';
3460
                echo '<a href="index.php?action=discuss&actionpage='.$lock_unlock_disc.'&title='.api_htmlentities(urlencode($page)).'">'.$addlock_disc.'</a>';
3461
                echo '</span>';
3462
3463
                // discussion action: visibility.  Show discussion to students if isn't hidden. Show page to all teachers if is hidden.
3464
                $visibility_disc = null;
3465
                $hide_show_disc = null;
3466 View Code Duplication
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3467
                    if (self::check_visibility_discuss() == 1) {
3468
                        /// TODO: 	Fix Mode assignments: If is hidden, show discussion to student only if student is the author
3469
                        $visibility_disc = Display::return_icon('visible.png', get_lang('ShowDiscussExtra'), '', ICON_SIZE_SMALL);
3470
                        $hide_show_disc = 'hidedisc';
3471
                    } else {
3472
                        $visibility_disc = Display::return_icon('invisible.png', get_lang('HideDiscussExtra'), '', ICON_SIZE_SMALL);
3473
                        $hide_show_disc = 'showdisc';
3474
                    }
3475
                }
3476
                echo '<span style="float:right">';
3477
                echo '<a href="index.php?action=discuss&amp;actionpage='.$hide_show_disc.'&amp;title='.api_htmlentities(urlencode($page)).'">'.$visibility_disc.'</a>';
3478
                echo '</span>';
3479
3480
                //discussion action: check add rating lock. Show/Hide list to rating for all student
3481
                $lock_unlock_rating_disc = null;
3482
                $ratinglock_disc = null;
3483 View Code Duplication
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3484
                    if (self::check_ratinglock_discuss() == 1) {
3485
                        $ratinglock_disc = Display::return_icon('star.png', get_lang('UnlockRatingDiscussExtra'), '', ICON_SIZE_SMALL);
3486
                        $lock_unlock_rating_disc = 'unlockrating';
3487
                    } else {
3488
                        $ratinglock_disc = Display::return_icon('star_na.png', get_lang('LockRatingDiscussExtra'), '', ICON_SIZE_SMALL);
3489
                        $lock_unlock_rating_disc = 'lockrating';
3490
                    }
3491
                }
3492
3493
                echo '<span style="float:right">';
3494
                echo '<a href="index.php?action=discuss&actionpage='.$lock_unlock_rating_disc.'&title='.api_htmlentities(urlencode($page)).'">'.$ratinglock_disc.'</a>';
3495
                echo '</span>';
3496
3497
                //discussion action: email notification
3498
                if (self::check_notify_discuss($page) == 1) {
3499
                    $notify_disc = Display::return_icon(
3500
                        'messagebox_info.png',
3501
                        get_lang('NotifyDiscussByEmail'),
3502
                        '',
3503
                        ICON_SIZE_SMALL
3504
                    );
3505
                    $lock_unlock_notify_disc = 'unlocknotifydisc';
3506
                } else {
3507
                    $notify_disc = Display::return_icon(
3508
                        'mail.png',
3509
                        get_lang('CancelNotifyDiscussByEmail'),
3510
                        '',
3511
                        ICON_SIZE_SMALL
3512
                    );
3513
                    $lock_unlock_notify_disc = 'locknotifydisc';
3514
                }
3515
                echo '<span style="float:right">';
3516
                echo '<a href="index.php?action=discuss&amp;actionpage='.$lock_unlock_notify_disc.'&amp;title='.api_htmlentities(urlencode($page)).'">'.$notify_disc.'</a>';
3517
                echo '</span>';
3518
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities($row['title']);
3519
                if ($lastuserinfo !== false) {
3520
                    echo ' ('.get_lang('MostRecentVersionBy').' '.UserManager::getUserProfileLink($lastuserinfo).' '.$lastversiondate.$countWPost.')'.$avg_WPost_score.' '; //TODO: read average score
3521
                }
3522
3523
                echo '</div>';
3524
                if ($row['addlock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3525
                    //show comments but students can't add theirs
3526
                    ?>
3527
                <div class="panel panel-default">
3528
                    <div class="panel-body">
3529
                    <form name="form1" method="post" action="" class="form-horizontal">
3530
                        <div class="form-group">
3531
                            <label class="col-sm-2 control-label"><?php echo get_lang('Comments'); ?>:</label>
3532
                            <div class="col-sm-10">
3533
                                <?php  echo '<input type="hidden" name="wpost_id" value="'.md5(uniqid(rand(), true)).'">'; //prevent double post ?>
3534
                                <textarea class="form-control" name="comment" cols="80" rows="5" id="comment"></textarea>
3535
                            </div>
3536
                        </div>
3537
                        <div class="form-group">
3538
                             <?php
3539
                                //check if rating is allowed
3540
                                if ($row['ratinglock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3541
                                    ?>
3542
                            <label class="col-sm-2 control-label"><?php echo get_lang('Rating'); ?>:</label>
3543
                            <div class="col-sm-10">
3544
                                <select name="rating" id="rating" class="selectpicker">
3545
                                    <option value="-" selected>-</option>
3546
                                    <option value="0">0</option>
3547
                                    <option value="1">1</option>
3548
                                    <option value="2">2</option>
3549
                                    <option value="3">3</option>
3550
                                    <option value="4">4</option>
3551
                                    <option value="5">5</option>
3552
                                    <option value="6">6</option>
3553
                                    <option value="7">7</option>
3554
                                    <option value="8">8</option>
3555
                                    <option value="9">9</option>
3556
                                    <option value="10">10</option>
3557
                                </select>
3558
                            </div>
3559
                            <?php
3560
                                } else {
3561
                                    echo '<input type=hidden name="rating" value="-">'; // must pass a default value to avoid rate automatically
3562
                                }
3563
                                ?>
3564
3565
                          </div>
3566
                        <div class="form-group">
3567
                                <div class="col-sm-offset-2 col-sm-10">
3568
                                  <?php  echo '<button class="btn btn-default" type="submit" name="Submit"> '.get_lang('Send').'</button>'; ?>
3569
                                </div>
3570
                            </div>
3571
                        </div>
3572
                        </div>
3573
                    </form>
3574
3575
                    <?php
3576
3577
                }//end discuss lock
3578
3579
                echo '<hr noshade size="1">';
3580
                $user_table = Database::get_main_table(TABLE_MAIN_USER);
3581
3582
                $sql = "SELECT *
3583
                        FROM $tbl_wiki_discuss reviews, $user_table user
3584
                        WHERE
3585
                            reviews.c_id = $course_id AND
3586
                            reviews.publication_id='".$id."' AND
3587
                            user.user_id='".$firstuserid."'
3588
                        ORDER BY reviews.id DESC";
3589
                $result = Database::query($sql);
3590
3591
                $countWPost = Database::num_rows($result);
3592
                echo get_lang('NumComments').": ".$countWPost; //comment's numbers
3593
3594
                $sql = "SELECT SUM(p_score) as sumWPost
3595
                        FROM $tbl_wiki_discuss
3596
                        WHERE c_id = $course_id AND publication_id = '".$id."' AND NOT p_score='-'
3597
                        ORDER BY id DESC";
3598
                $result2 = Database::query($sql);
3599
                $row2 = Database::fetch_array($result2);
3600
3601
                $sql = "SELECT * FROM $tbl_wiki_discuss
3602
                        WHERE c_id = $course_id AND publication_id='".$id."' AND NOT p_score='-'";
3603
                $result3 = Database::query($sql);
3604
                $countWPost_score = Database::num_rows($result3);
3605
3606
                echo ' - '.get_lang('NumCommentsScore').': '.$countWPost_score; //
3607
3608
                if ($countWPost_score != 0) {
3609
                    $avg_WPost_score = round($row2['sumWPost'] / $countWPost_score, 2).' / 10';
3610
                } else {
3611
                    $avg_WPost_score = $countWPost_score;
3612
                }
3613
3614
                echo ' - '.get_lang('RatingMedia').': '.$avg_WPost_score; // average rating
3615
3616
                $sql = 'UPDATE '.$tbl_wiki.' SET
3617
                        score="'.Database::escape_string($avg_WPost_score).'"
3618
                        WHERE
3619
                            c_id = '.$course_id.' AND
3620
                            reflink="'.Database::escape_string($page).'" AND
3621
                            '.$groupfilter.$condition_session;
3622
                // check if work ok. TODO:
3623
                Database::query($sql);
3624
3625
                echo '<hr noshade size="1">';
3626
3627
                while ($row = Database::fetch_array($result)) {
3628
                    $userinfo = api_get_user_info($row['userc_id']);
3629
                    if (($userinfo['status']) == "5") {
3630
                        $author_status = get_lang('Student');
3631
                    } else {
3632
                        $author_status = get_lang('Teacher');
3633
                    }
3634
3635
                    $name = $userinfo['complete_name'];
3636
                    $author_photo = '<img src="'.$userinfo['avatar'].'" alt="'.api_htmlentities($name).'"  width="40" height="50" align="top"  title="'.api_htmlentities($name).'"  />';
3637
3638
                    //stars
3639
                    $p_score = $row['p_score'];
3640
                    switch ($p_score) {
3641
                        case  0:
3642
                            $imagerating = Display::return_icon('rating/stars_0.gif');
3643
                            break;
3644
                        case  1:
3645
                            $imagerating = Display::return_icon('rating/stars_5.gif');
3646
                            break;
3647
                        case  2:
3648
                            $imagerating = Display::return_icon('rating/stars_10.gif');
3649
                            break;
3650
                        case  3:
3651
                            $imagerating = Display::return_icon('rating/stars_15.gif');
3652
                            break;
3653
                        case  4:
3654
                            $imagerating = Display::return_icon('rating/stars_20.gif');
3655
                            break;
3656
                        case  5:
3657
                            $imagerating = Display::return_icon('rating/stars_25.gif');
3658
                            break;
3659
                        case  6:
3660
                            $imagerating = Display::return_icon('rating/stars_30.gif');
3661
                            break;
3662
                        case  7:
3663
                            $imagerating = Display::return_icon('rating/stars_35.gif');
3664
                            break;
3665
                        case  8:
3666
                            $imagerating = Display::return_icon('rating/stars_40.gif');
3667
                            break;
3668
                        case  9:
3669
                            $imagerating = Display::return_icon('rating/stars_45.gif');
3670
                            break;
3671
                        case  10:
3672
                            $imagerating = Display::return_icon('rating/stars_50.gif');
3673
                            break;
3674
                    }
3675
                    echo '<p><table>';
3676
                    echo '<tr>';
3677
                    echo '<td rowspan="2">'.$author_photo.'</td>';
3678
                    $userProfile = '';
3679
                    if ($userinfo !== false) {
3680
                        $userProfile = UserManager::getUserProfileLink($userinfo);
3681
                    }
3682
                    echo '<td style=" color:#999999">'.$userProfile.' ('.$author_status.') '.
3683
                        api_get_local_time($row['dtime'], null, date_default_timezone_get()).
3684
                        ' - '.get_lang('Rating').': '.$row['p_score'].' '.$imagerating.' </td>';
3685
                    echo '</tr>';
3686
                    echo '<tr>';
3687
                    echo '<td>'.api_htmlentities($row['comment']).'</td>';
3688
                    echo '</tr>';
3689
                    echo "</table>";
3690
                }
3691
            } else {
3692
                Display::addFlash(Display::return_message(get_lang('LockByTeacher'), 'warning', false));
3693
            }
3694
        } else {
3695
            Display::addFlash(Display::return_message(get_lang('DiscussNotAvailable'), 'normal', false));
3696
        }
3697
    }
3698
3699
    /**
3700
     * Show all pages
3701
     */
3702
    public function allPages($action)
3703
    {
3704
        $tbl_wiki = $this->tbl_wiki;
3705
        $course_id = $this->course_id;
3706
        $session_id = $this->session_id;
3707
        $groupfilter = $this->groupfilter;
3708
        $_course = $this->courseInfo;
3709
3710
        echo '<div class="actions">'.get_lang('AllPages');
3711
3712
        // menu delete all wiki
3713 View Code Duplication
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3714
            echo ' <a href="index.php?action=deletewiki&'.api_get_cidreq().'">'.
3715
                Display::return_icon('delete.png', get_lang('DeleteWiki'), '', ICON_SIZE_MEDIUM).'</a>';
3716
        }
3717
        echo '</div>';
3718
3719
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) { //only by professors if page is hidden
3720
            $sql = 'SELECT  *
3721
                    FROM  '.$tbl_wiki.' s1
3722
        		    WHERE s1.c_id = '.$course_id.' AND id=(
3723
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3724
                    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.' AND session_id='.$session_id.')';
3725
            // warning don't use group by reflink because does not return the last version
3726
3727
        } else {
3728
            $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1
3729
				    WHERE visibility=1 AND s1.c_id = '.$course_id.' AND id=(
3730
                        SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3731
                        WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.' AND session_id='.$session_id.')';
3732
            // warning don't use group by reflink because does not return the last version
3733
        }
3734
3735
        $allpages = Database::query($sql);
3736
3737
        //show table
3738
        if (Database::num_rows($allpages) > 0) {
3739
            while ($obj = Database::fetch_object($allpages)) {
3740
                //get author
3741
                $userinfo = api_get_user_info($obj->user_id);
3742
                $username = api_htmlentities(sprintf(get_lang('LoginX'), $userinfo['username']), ENT_QUOTES);
3743
3744
                //get type assignment icon
3745
                if ($obj->assignment == 1) {
3746
                    $ShowAssignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'), '', ICON_SIZE_SMALL);
3747
                } elseif ($obj->assignment == 2) {
3748
                    $ShowAssignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'), '', ICON_SIZE_SMALL);
3749
                } elseif ($obj->assignment == 0) {
3750
                    $ShowAssignment = Display::return_icon('px_transparent.gif');
3751
                }
3752
3753
                //get icon task
3754
                if (!empty($obj->task)) {
3755
                    $icon_task = Display::return_icon('wiki_task.png', get_lang('StandardTask'), '', ICON_SIZE_SMALL);
3756
                } else {
3757
                    $icon_task = Display::return_icon('px_transparent.gif');
3758
                }
3759
3760
                $row = array();
3761
                $row[] = $ShowAssignment.$icon_task;
3762
                $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">
3763
                '.api_htmlentities($obj->title).'</a>';
3764 View Code Duplication
                if ($userinfo !== false) {
3765
                    $row[] = UserManager::getUserProfileLink($userinfo);
3766
                }
3767
                else {
3768
                    $row[] = get_lang('Anonymous').' ('.api_htmlentities($obj->user_ip).')';
3769
                }
3770
                $row[] = api_get_local_time($obj->dtime, null, date_default_timezone_get());
3771
                $showdelete = '';
3772
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3773
                    $showdelete = ' <a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=delete&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
3774
                        Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
3775
                }
3776
                if (api_is_allowed_to_session_edit(false, true)) {
3777
                    $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=edit&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
3778
                        Display::return_icon('edit.png', get_lang('EditPage'), '', ICON_SIZE_SMALL).'</a> <a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=discuss&title='.api_htmlentities(urlencode($obj->reflink)).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
3779
                        Display::return_icon('discuss.png', get_lang('Discuss'), '', ICON_SIZE_SMALL).'</a> <a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=history&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
3780
                        Display::return_icon('history.png', get_lang('History'), '', ICON_SIZE_SMALL).'</a>
3781
                        <a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=links&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
3782
                        Display::return_icon('what_link_here.png', get_lang('LinksPages'), '', ICON_SIZE_SMALL).'</a>'.$showdelete;
3783
                }
3784
                $rows[] = $row;
3785
            }
3786
3787
            $table = new SortableTableFromArrayConfig($rows, 1, 10, 'AllPages_table', '', '', 'ASC');
3788
            $table->set_additional_parameters(array('cidReq' =>Security::remove_XSS($_GET['cidReq']), 'action'=>Security::remove_XSS($action), 'group_id'=>Security::remove_XSS($_GET['group_id'])));
3789
            $table->set_header(0, get_lang('Type'), true, array('style' => 'width:30px;'));
3790
            $table->set_header(1, get_lang('Title'), true);
3791
            $table->set_header(2, get_lang('Author').' ('.get_lang('LastVersion').')', true);
3792
            $table->set_header(3, get_lang('Date').' ('.get_lang('LastVersion').')', true);
3793
            if (api_is_allowed_to_session_edit(false, true)) {
3794
                $table->set_header(4, get_lang('Actions'), true, array('style' => 'width:130px;'));
3795
            }
3796
            $table->display();
3797
        }
3798
    }
3799
3800
    /**
3801
     * Get recent changes
3802
     * @param string $page
3803
     * @param string $action
3804
     *
3805
     */
3806
    public function recentChanges($page, $action)
3807
    {
3808
        $tbl_wiki = $this->tbl_wiki;
3809
        $course_id = $this->course_id;
3810
        $condition_session = $this->condition_session;
3811
        $groupfilter = $this->groupfilter;
3812
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3813
3814
        if (api_is_allowed_to_session_edit(false, true)) {
3815
            if (self::check_notify_all() == 1) {
3816
                $notify_all = Display::return_icon(
3817
                        'messagebox_info.png',
3818
                        get_lang('NotifyByEmail'),
3819
                        '',
3820
                        ICON_SIZE_SMALL
3821
                    ).' '.get_lang('NotNotifyChanges');
3822
                $lock_unlock_notify_all = 'unlocknotifyall';
3823
            } else {
3824
                $notify_all = Display::return_icon(
3825
                        'mail.png',
3826
                        get_lang('CancelNotifyByEmail'),
3827
                        '',
3828
                        ICON_SIZE_SMALL
3829
                    ).' '.get_lang('NotifyChanges');
3830
                $lock_unlock_notify_all = 'locknotifyall';
3831
            }
3832
        }
3833
3834
        echo '<div class="actions"><span style="float: right;">';
3835
        echo '<a href="index.php?action=recentchanges&amp;actionpage='.$lock_unlock_notify_all.'&amp;title='.api_htmlentities(urlencode($page)).'">'.$notify_all.'</a>';
3836
        echo '</span>'.get_lang('RecentChanges').'</div>';
3837
3838
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) { //only by professors if page is hidden
3839
            $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
3840
        		WHERE 	'.$tbl_wiki_conf.'.c_id= '.$course_id.' AND
3841
        				'.$tbl_wiki.'.c_id= '.$course_id.' AND
3842
        				'.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
3843
        				'.$tbl_wiki.'.'.$groupfilter.$condition_session.'
3844
        		ORDER BY dtime DESC'; // new version
3845
        } else {
3846
            $sql = 'SELECT *
3847
                FROM '.$tbl_wiki.'
3848
                WHERE
3849
                    c_id = '.$course_id.' AND
3850
                    '.$groupfilter.$condition_session.' AND
3851
                    visibility=1
3852
                ORDER BY dtime DESC';
3853
            // old version TODO: Replace by the bottom line
3854
        }
3855
3856
        $allpages = Database::query($sql);
3857
3858
        //show table
3859
        if (Database::num_rows($allpages) > 0) {
3860
            $rows = array();
3861
            while ($obj = Database::fetch_object($allpages)) {
3862
                //get author
3863
                $userinfo = api_get_user_info($obj->user_id);
3864
3865
                //get type assignment icon
3866
                if ($obj->assignment == 1) {
3867
                    $ShowAssignment = Display::return_icon(
3868
                        'wiki_assignment.png',
3869
                        get_lang('AssignmentDesc'),
3870
                        '',
3871
                        ICON_SIZE_SMALL
3872
                    );
3873
                } elseif ($obj->assignment == 2) {
3874
                    $ShowAssignment = Display::return_icon(
3875
                        'wiki_work.png',
3876
                        get_lang('AssignmentWork'),
3877
                        '',
3878
                        ICON_SIZE_SMALL
3879
                    );
3880
                } elseif ($obj->assignment == 0) {
3881
                    $ShowAssignment = Display::return_icon(
3882
                        'px_transparent.gif'
3883
                    );
3884
                }
3885
3886
                // Get icon task
3887
                if (!empty($obj->task)) {
3888
                    $icon_task = Display::return_icon(
3889
                        'wiki_task.png',
3890
                        get_lang('StandardTask'),
3891
                        '',
3892
                        ICON_SIZE_SMALL
3893
                    );
3894
                } else {
3895
                    $icon_task = Display::return_icon('px_transparent.gif');
3896
                }
3897
3898
                $row = array();
3899
                $row[] = api_get_local_time($obj->dtime, null, date_default_timezone_get());
3900
                $row[] = $ShowAssignment.$icon_task;
3901
                $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&amp;view='.$obj->id.'&session_id='.api_get_session_id().'&group_id='.api_get_group_id().'">'.
3902
                    api_htmlentities($obj->title).'</a>';
3903
                $row[] = $obj->version > 1 ? get_lang('EditedBy') : get_lang('AddedBy');
3904 View Code Duplication
                if ($userinfo !== false) {
3905
                    $row[] = UserManager::getUserProfileLink($userinfo);
3906
                } else {
3907
                    $row[] = get_lang('Anonymous').' ('.api_htmlentities($obj->user_ip).')';
3908
                }
3909
                $rows[] = $row;
3910
            }
3911
3912
            $table = new SortableTableFromArrayConfig(
3913
                $rows,
3914
                0,
3915
                10,
3916
                'RecentPages_table',
3917
                '',
3918
                '',
3919
                'DESC'
3920
            );
3921
            $table->set_additional_parameters(
3922
                array(
3923
                    'cidReq' =>api_get_course_id(),
3924
                    'action'=>Security::remove_XSS($action),
3925
                    'session_id' => api_get_session_id(),
3926
                    'group_id' => api_get_group_id()
3927
                )
3928
            );
3929
            $table->set_header(0, get_lang('Date'), true, array('style' => 'width:200px;'));
3930
            $table->set_header(1, get_lang('Type'), true, array('style' => 'width:30px;'));
3931
            $table->set_header(2, get_lang('Title'), true);
3932
            $table->set_header(3, get_lang('Actions'), true, array('style' => 'width:80px;'));
3933
            $table->set_header(4, get_lang('Author'), true);
3934
            $table->display();
3935
        }
3936
    }
3937
3938
    /**
3939
     * What links here. Show pages that have linked this page
3940
     *
3941
     * @param string $page
3942
     */
3943
    public function getLinks($page)
3944
    {
3945
        $tbl_wiki = $this->tbl_wiki;
3946
        $course_id = $this->course_id;
3947
        $condition_session = $this->condition_session;
3948
        $groupfilter = $this->groupfilter;
3949
        $_course = $this->courseInfo;
3950
        $action = $this->action;
3951
3952
        if (!$_GET['title']) {
3953
            Display::addFlash(Display::return_message(get_lang("MustSelectPage"), 'error', false));
3954
        } else {
3955
            $sql = 'SELECT * FROM '.$tbl_wiki.'
3956
                    WHERE
3957
                        c_id = '.$course_id.' AND
3958
                        reflink="'.Database::escape_string($page).'" AND
3959
                        '.$groupfilter.$condition_session;
3960
            $result = Database::query($sql);
3961
            $row = Database::fetch_array($result);
3962
3963
            //get type assignment icon
3964
            $ShowAssignment = '';
3965 View Code Duplication
            if ($row['assignment'] == 1) {
3966
                $ShowAssignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'), '', ICON_SIZE_SMALL);
3967
            } elseif ($row['assignment'] == 2) {
3968
                $ShowAssignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'), '', ICON_SIZE_SMALL);
3969
            } elseif ($row['assignment'] == 0) {
3970
                $ShowAssignment = Display::return_icon('px_transparent.gif');
3971
            }
3972
3973
            //fix Title to reflink (link Main Page)
3974
            if ($page == get_lang('DefaultTitle')) {
3975
                $page = 'index';
3976
            }
3977
3978
            echo '<div id="wikititle">';
3979
            echo get_lang('LinksPagesFrom').': '.$ShowAssignment.' <a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(urlencode($page)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
3980
                api_htmlentities($row['title']).'</a>';
3981
            echo '</div>';
3982
3983
            //fix index to title Main page into linksto
3984
3985
            if ($page == 'index') {
3986
                $page = str_replace(' ', '_', get_lang('DefaultTitle'));
3987
            }
3988
3989
            //table
3990
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3991
                //only by professors if page is hidden
3992
                $sql = "SELECT * FROM ".$tbl_wiki." s1
3993
                        WHERE s1.c_id = $course_id AND linksto LIKE '%".Database::escape_string($page)."%' AND id=(
3994
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
3995
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
3996
                //add blank space after like '%" " %' to identify each word
3997
            } else {
3998
                $sql = "SELECT * FROM ".$tbl_wiki." s1
3999
                        WHERE s1.c_id = $course_id AND visibility=1 AND linksto LIKE '%".Database::escape_string($page)."%' AND id=(
4000
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4001
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4002
                //add blank space after like '%" " %' to identify each word
4003
            }
4004
4005
            $allpages = Database::query($sql);
4006
4007
            //show table
4008
            if (Database::num_rows($allpages) > 0) {
4009
                $rows = array();
4010
                while ($obj = Database::fetch_object($allpages)) {
4011
                    //get author
4012
                    $userinfo = api_get_user_info($obj->user_id);
4013
4014
                    //get time
4015
                    $year = substr($obj->dtime, 0, 4);
4016
                    $month = substr($obj->dtime, 5, 2);
4017
                    $day = substr($obj->dtime, 8, 2);
4018
                    $hours = substr($obj->dtime, 11, 2);
4019
                    $minutes = substr($obj->dtime, 14, 2);
4020
                    $seconds = substr($obj->dtime, 17, 2);
4021
4022
                    //get type assignment icon
4023
                    if ($obj->assignment == 1) {
4024
                        $ShowAssignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'), '', ICON_SIZE_SMALL);
4025
                    } elseif ($obj->assignment == 2) {
4026
                        $ShowAssignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'), '', ICON_SIZE_SMALL);
4027
                    } elseif ($obj->assignment == 0) {
4028
                        $ShowAssignment = Display::return_icon('px_transparent.gif');
4029
                    }
4030
4031
                    $row = array();
4032
                    $row[] = $ShowAssignment;
4033
                    $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4034
                        api_htmlentities($obj->title).'</a>';
4035 View Code Duplication
                    if ($userinfo !== false) {
4036
                        $row[] = UserManager::getUserProfileLink($userinfo);
4037
                    }
4038
                    else {
4039
                        $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
4040
                    }
4041
                    $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
4042
                    $rows[] = $row;
4043
                }
4044
4045
                $table = new SortableTableFromArrayConfig(
4046
                    $rows,
4047
                    1,
4048
                    10,
4049
                    'AllPages_table',
4050
                    '',
4051
                    '',
4052
                    'ASC'
4053
                );
4054
                $table->set_additional_parameters(
4055
                    array(
4056
                        'cidReq' => Security::remove_XSS($_GET['cidReq']),
4057
                        'action' => Security::remove_XSS($action),
4058
                        'group_id' => intval($_GET['group_id']),
4059
                    )
4060
                );
4061
                $table->set_header(
4062
                    0,
4063
                    get_lang('Type'),
4064
                    true,
4065
                    array('style' => 'width:30px;')
4066
                );
4067
                $table->set_header(1, get_lang('Title'), true);
4068
                $table->set_header(2, get_lang('Author'), true);
4069
                $table->set_header(3, get_lang('Date'), true);
4070
                $table->display();
4071
            }
4072
        }
4073
    }
4074
4075
    /**
4076
     * @param string $action
4077
     */
4078
    public function getSearchPages($action)
4079
    {
4080
        echo '<div class="actions">'.get_lang('SearchPages').'</div>';
4081
        if (isset($_GET['mode_table'])) {
4082
            if (!isset($_GET['SearchPages_table_page_nr'])) {
4083
                $_GET['search_term'] = isset($_POST['search_term']) ? $_POST['search_term'] : '';
4084
                $_GET['search_content'] = isset($_POST['search_content']) ? $_POST['search_content'] : '';
4085
                $_GET['all_vers'] = isset($_POST['all_vers']) ? $_POST['all_vers'] : '';
4086
            }
4087
            self::display_wiki_search_results(
4088
                $_GET['search_term'],
4089
                $_GET['search_content'],
4090
                $_GET['all_vers']
4091
            );
4092
        } else {
4093
4094
            // initiate the object
4095
            $form = new FormValidator('wiki_search',
4096
                'post',
4097
                api_get_self().'?cidReq='.api_get_course_id().'&action='.api_htmlentities($action).'&session_id='.api_get_session_id().'&group_id='.api_get_group_id().'&mode_table=yes1'
4098
            );
4099
4100
            // Setting the form elements
4101
4102
            $form->addText('search_term', get_lang('SearchTerm'), true, array('autofocus' => 'autofocus'));
4103
            $form->addElement('checkbox', 'search_content', null, get_lang('AlsoSearchContent'));
4104
            $form->addElement('checkbox', 'all_vers', null, get_lang('IncludeAllVersions'));
4105
            $form->addButtonSearch(get_lang('Search'), 'SubmitWikiSearch');
4106
4107
            // setting the rules
4108
            $form->addRule('search_term', get_lang('TooShort'), 'minlength', 3); //TODO: before fixing the pagination rules worked, not now
4109
4110
            if ($form->validate()) {
4111
                $form->display();
4112
                $values = $form->exportValues();
4113
                self::display_wiki_search_results(
4114
                    $values['search_term'],
4115
                    $values['search_content'],
4116
                    $values['all_vers']
4117
                );
4118
            } else {
4119
                $form->display();
4120
            }
4121
        }
4122
    }
4123
4124
    /**
4125
     * @param int $userId
4126
     * @param string $action
4127
     */
4128
    public function getUserContributions($userId, $action)
4129
    {
4130
        $_course = $this->courseInfo;
4131
        $tbl_wiki = $this->tbl_wiki;
4132
        $course_id = $this->course_id;
4133
        $condition_session = $this->condition_session;
4134
        $groupfilter = $this->groupfilter;
4135
        $userId = intval($userId);
4136
        $userinfo = api_get_user_info($userId);
4137
        if ($userinfo !== false) {
4138
            echo '<div class="actions">'.get_lang('UserContributions').': '.UserManager::getUserProfileLink($userinfo).
4139
                '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.$userId.
4140
                '&session_id='.$this->session_id.'&group_id='.$this->group_id.'">'.
4141
                '</a></div>';
4142
        }
4143
4144
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4145
            //only by professors if page is hidden
4146
            $sql = 'SELECT * FROM '.$tbl_wiki.'
4147
                    WHERE
4148
                        c_id = '.$course_id.' AND
4149
                        '.$groupfilter.$condition_session.' AND
4150
                        user_id="'.$userId.'"';
4151
        } else {
4152
            $sql = 'SELECT * FROM '.$tbl_wiki.'
4153
                    WHERE
4154
                        c_id = '.$course_id.' AND
4155
                        '.$groupfilter.$condition_session.' AND
4156
                        user_id="'.$userId.'" AND
4157
                        visibility=1';
4158
        }
4159
4160
        $allpages = Database::query($sql);
4161
4162
        //show table
4163
        if (Database::num_rows($allpages) > 0) {
4164
            $rows = array();
4165
            while ($obj = Database::fetch_object($allpages)) {
4166
                // Get time
4167
                $year = substr($obj->dtime, 0, 4);
4168
                $month = substr($obj->dtime, 5, 2);
4169
                $day = substr($obj->dtime, 8, 2);
4170
                $hours = substr($obj->dtime, 11, 2);
4171
                $minutes = substr($obj->dtime, 14, 2);
4172
                $seconds = substr($obj->dtime, 17, 2);
4173
4174
                //get type assignment icon
4175
                $ShowAssignment = '';
4176
                if ($obj->assignment == 1) {
4177
                    $ShowAssignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'), '', ICON_SIZE_SMALL);
4178
                } elseif ($obj->assignment == 2) {
4179
                    $ShowAssignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'), '', ICON_SIZE_SMALL);
4180
                } elseif ($obj->assignment == 0) {
4181
                    $ShowAssignment = Display::return_icon('px_transparent.gif');
4182
                }
4183
4184
                $row = array();
4185
                $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
4186
                $row[] = $ShowAssignment;
4187
                $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&view='.$obj->id.'&session_id='.api_get_session_id().'&group_id='.api_get_group_id().'">'.
4188
                    api_htmlentities($obj->title).'</a>';
4189
                $row[] = Security::remove_XSS($obj->version);
4190
                $row[] = Security::remove_XSS($obj->comment);
4191
                $row[] = Security::remove_XSS($obj->progress).' %';
4192
                $row[] = Security::remove_XSS($obj->score);
4193
                $rows[] = $row;
4194
            }
4195
4196
            $table = new SortableTableFromArrayConfig(
4197
                $rows,
4198
                2,
4199
                10,
4200
                'UsersContributions_table',
4201
                '',
4202
                '',
4203
                'ASC'
4204
            );
4205
            $table->set_additional_parameters(
4206
                array(
4207
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
4208
                    'action' => Security::remove_XSS($action),
4209
                    'user_id' => intval($userId),
4210
                    'session_id' => intval($_GET['session_id']),
4211
                    'group_id' => intval($_GET['group_id']),
4212
                )
4213
            );
4214
            $table->set_header(0, get_lang('Date'), true, array('style' => 'width:200px;'));
4215
            $table->set_header(1, get_lang('Type'), true, array('style' => 'width:30px;'));
4216
            $table->set_header(2, get_lang('Title'), true, array('style' => 'width:200px;'));
4217
            $table->set_header(3, get_lang('Version'), true, array('style' => 'width:30px;'));
4218
            $table->set_header(4, get_lang('Comment'), true, array('style' => 'width:200px;'));
4219
            $table->set_header(5, get_lang('Progress'), true, array('style' => 'width:30px;'));
4220
            $table->set_header(6, get_lang('Rating'), true, array('style' => 'width:30px;'));
4221
            $table->display();
4222
        }
4223
    }
4224
4225
    /**
4226
     * @param string $action
4227
     */
4228 View Code Duplication
    public function getMostChangedPages($action)
4229
    {
4230
        $_course = $this->courseInfo;
4231
        $tbl_wiki = $this->tbl_wiki;
4232
        $course_id = $this->course_id;
4233
        $condition_session = $this->condition_session;
4234
        $groupfilter = $this->groupfilter;
4235
4236
        echo '<div class="actions">'.get_lang('MostChangedPages').'</div>';
4237
4238
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) { //only by professors if page is hidden
4239
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
4240
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
4241
                    GROUP BY reflink';//TODO:check MAX and group by return last version
4242
        } else {
4243
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
4244
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND visibility=1
4245
                    GROUP BY reflink'; //TODO:check MAX and group by return last version
4246
        }
4247
4248
        $allpages = Database::query($sql);
4249
4250
        //show table
4251
        if (Database::num_rows($allpages) > 0) {
4252
            $rows = array();
4253
            while ($obj = Database::fetch_object($allpages)) {
4254
                //get type assignment icon
4255
                $ShowAssignment = '';
4256
                if ($obj->assignment == 1) {
4257
                    $ShowAssignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'), '', ICON_SIZE_SMALL);
4258
                } elseif ($obj->assignment == 2) {
4259
                    $ShowAssignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'), '', ICON_SIZE_SMALL);
4260
                } elseif ($obj->assignment == 0) {
4261
                    $ShowAssignment = Display::return_icon('px_transparent.gif');
4262
                }
4263
4264
                $row = array();
4265
                $row[] = $ShowAssignment;
4266
                $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4267
                    api_htmlentities($obj->title).'</a>';
4268
                $row[] = $obj->MAX;
4269
                $rows[] = $row;
4270
            }
4271
4272
            $table = new SortableTableFromArrayConfig(
4273
                $rows,
4274
                2,
4275
                10,
4276
                'MostChangedPages_table',
4277
                '',
4278
                '',
4279
                'DESC'
4280
            );
4281
            $table->set_additional_parameters(
4282
                array(
4283
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
4284
                    'action' => Security::remove_XSS($action),
4285
                    'session_id' => intval($_GET['session_id']),
4286
                    'group_id' => intval($_GET['group_id']),
4287
                )
4288
            );
4289
            $table->set_header(0, get_lang('Type'), true, array('style' => 'width:30px;'));
4290
            $table->set_header(1, get_lang('Title'), true);
4291
            $table->set_header(2, get_lang('Changes'), true);
4292
            $table->display();
4293
        }
4294
    }
4295
4296
    /**
4297
     * Restore page
4298
     * @return bool
4299
     */
4300
    public function restorePage()
4301
    {
4302
        $userId = api_get_user_id();
4303
        $_course = $this->courseInfo;
4304
        $current_row = $this->getWikiData();
4305
        $last_row = $this->getLastWikiData($this->page);
4306
4307
        if (empty($last_row)) {
4308
            return false;
4309
        }
4310
4311
        $PassEdit = false;
4312
4313
        /* Only teachers and platform admin can edit the index page.
4314
        Only teachers and platform admin can edit an assignment teacher*/
4315
        if (($current_row['reflink'] == 'index' || $current_row['reflink'] == '' || $current_row['assignment'] == 1) &&
4316
            (!api_is_allowed_to_edit(false, true) && $this->group_id == 0)
4317
        ) {
4318
            Display::addFlash(
4319
                Display::return_message(get_lang('OnlyEditPagesCourseManager'), 'normal', false)
4320
            );
4321
        } else {
4322
4323
            // check if is a wiki group
4324
            if ($current_row['group_id'] != 0) {
4325
                $groupInfo = GroupManager::get_group_properties($this->group_id);
4326
                //Only teacher, platform admin and group members can edit a wiki group
4327 View Code Duplication
                if (api_is_allowed_to_edit(false, true) ||
4328
                    api_is_platform_admin() ||
4329
                    GroupManager::is_user_in_group($userId, $groupInfo) ||
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group...erties($this->group_id) on line 4325 can also be of type null; however, GroupManager::is_user_in_group() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
4330
                    api_is_allowed_in_course()
4331
                ) {
4332
                    $PassEdit = true;
4333
                } else {
4334
                    Display::addFlash(
4335
                        Display::return_message(get_lang('OnlyEditPagesGroupMembers'), 'normal', false)
4336
                    );
4337
                }
4338
            } else {
4339
                $PassEdit = true;
4340
            }
4341
4342
            // check if is an assignment
4343
            //$icon_assignment = null;
4344
            if ($current_row['assignment'] == 1) {
4345
                Display::addFlash(Display::return_message(get_lang('EditAssignmentWarning'), 'normal', false));
4346
            } elseif ($current_row['assignment'] == 2) {
4347 View Code Duplication
                if (($userId == $current_row['user_id']) == false) {
4348
                    if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4349
                        $PassEdit = true;
4350
                    } else {
4351
                        Display::addFlash(Display::return_message(get_lang('LockByTeacher'), 'normal', false));
4352
                        $PassEdit = false;
4353
                    }
4354
                } else {
4355
                    $PassEdit = true;
4356
                }
4357
            }
4358
4359
            //show editor if edit is allowed
4360
            if ($PassEdit) {
4361
                if ($current_row['editlock'] == 1 &&
4362
                    (api_is_allowed_to_edit(false, true) == false || api_is_platform_admin() == false)
4363
                ) {
4364
                    Display::addFlash(Display::return_message(get_lang('PageLockedExtra'), 'normal', false));
4365
                } else {
4366
                    if ($last_row['is_editing'] != 0 && $last_row['is_editing'] != $userId) {
4367
                        // Checking for concurrent users
4368
                        $timestamp_edit = strtotime($last_row['time_edit']);
4369
                        $time_editing = time() - $timestamp_edit;
4370
                        $max_edit_time = 1200; // 20 minutes
4371
                        $rest_time = $max_edit_time - $time_editing;
4372
                        $userinfo = api_get_user_info($last_row['is_editing']);
4373
                        $is_being_edited = get_lang('ThisPageisBeginEditedBy').' <a href='.$userinfo['profile_url'].'>'.
4374
                            Display::tag('span', $userinfo['complete_name_with_username']).
4375
                            get_lang('ThisPageisBeginEditedTryLater').' '.date("i", $rest_time).' '.get_lang('MinMinutes');
4376
                        Display::addFlash(Display::return_message($is_being_edited, 'normal', false));
4377
                    } else {
4378
                        Display::addFlash(Display::return_message(
4379
                            self::restore_wikipage(
4380
                                $current_row['page_id'],
4381
                                $current_row['reflink'],
4382
                                $current_row['title'],
4383
                                $current_row['content'],
4384
                                $current_row['group_id'],
4385
                                $current_row['assignment'],
4386
                                $current_row['progress'],
4387
                                $current_row['version'],
4388
                                $last_row['version'],
4389
                                $current_row['linksto']
4390
                            ).': <a href="index.php?cidReq='.$_course['code'].'&action=showpage&amp;title='.api_htmlentities(urlencode($last_row['reflink'])).'&session_id='.$last_row['session_id'].'&group_id='.$last_row['group_id'].'">'.
4391
                            api_htmlentities($last_row['title']).'</a>',
4392
                            'confirmation',
4393
                            false
4394
                        ));
4395
                    }
4396
                }
4397
            }
4398
        }
4399
    }
4400
4401
    /**
4402
     * @param int|bool $wikiId
4403
     */
4404
    public function setWikiData($wikiId)
4405
    {
4406
        $this->wikiData = self::getWikiDataFromDb($wikiId);
4407
    }
4408
4409
    /**
4410
     * @return array
4411
     */
4412
    public function getWikiData()
4413
    {
4414
        return $this->wikiData;
4415
    }
4416
4417
    /**
4418
     * Check last version
4419
     * @param int $view
4420
     */
4421
    public function checkLastVersion($view)
4422
    {
4423
        $tbl_wiki = $this->tbl_wiki;
4424
        $course_id = $this->course_id;
4425
        $condition_session = $this->condition_session;
4426
        $groupfilter = $this->groupfilter;
4427
        $page = $this->page;
4428
        $_course = $this->courseInfo;
4429
4430
        if (empty($view)) {
4431
            return false;
4432
        }
4433
4434
        $current_row = $this->getWikiData();
4435
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4436
                WHERE
4437
                    c_id = '.$course_id.' AND
4438
                    reflink = "'.Database::escape_string($page).'" AND
4439
                    '.$groupfilter.$condition_session.'
4440
                ORDER BY id DESC'; //last version
4441
        $result = Database::query($sql);
4442
        $last_row = Database::fetch_array($result);
4443
4444
        if ($view < $last_row['id']) {
4445
            $message = '<center>'.get_lang('NoAreSeeingTheLastVersion').'<br />
4446
            '.get_lang("Version").' (
4447
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&amp;title='.api_htmlentities(urlencode($current_row['reflink'])).'&group_id='.$current_row['group_id'].'&session_id='.$current_row['session_id'].'&view='.api_htmlentities($_GET['view']).'" title="'.get_lang('CurrentVersion').'">
4448
            '.$current_row['version'].'
4449
            </a> /
4450
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&amp;title='.api_htmlentities(urlencode($last_row['reflink'])).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'" title="'.get_lang('LastVersion').'">
4451
            '.$last_row['version'].'
4452
            </a>) <br />'.get_lang("ConvertToLastVersion").':
4453
            <a href="index.php?cidReq='.$_course['id'].'&action=restorepage&amp;title='.api_htmlentities(urlencode($last_row['reflink'])).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'&view='.api_htmlentities($_GET['view']).'">'.
4454
                get_lang("Restore").'</a></center>';
4455
            Display::addFlash(Display::return_message($message, 'warning', false));
4456
        }
4457
    }
4458
4459
    /**
4460
     *  Get most linked pages
4461
     */
4462
    public function getMostLinked()
4463
    {
4464
        $tbl_wiki = $this->tbl_wiki;
4465
        $course_id = $this->course_id;
4466
        $groupfilter = $this->groupfilter;
4467
        $condition_session = $this->condition_session;
4468
        $_course = $this->courseInfo;
4469
4470
        echo '<div class="actions">'.get_lang('MostLinkedPages').'</div>';
4471
        $pages = array();
4472
        $linked = array();
4473
4474
        // Get name pages
4475
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4476
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
4477
                GROUP BY reflink
4478
                ORDER BY reflink ASC';
4479
        $allpages = Database::query($sql);
4480 View Code Duplication
        while ($row = Database::fetch_array($allpages)) {
4481
            if ($row['reflink'] == 'index') {
4482
                $row['reflink'] = str_replace(' ', '_', get_lang('DefaultTitle'));
4483
            }
4484
            $pages[] = $row['reflink'];
4485
        }
4486
4487
        // Get name refs in last pages
4488
        $sql = 'SELECT *
4489
                FROM '.$tbl_wiki.' s1
4490
                WHERE s1.c_id = '.$course_id.' AND id=(
4491
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
4492
                    WHERE
4493
                        s2.c_id = '.$course_id.' AND
4494
                        s1.reflink = s2.reflink AND
4495
                        '.$groupfilter.$condition_session.'
4496
                )';
4497
4498
        $allpages = Database::query($sql);
4499
4500
        while ($row = Database::fetch_array($allpages)) {
4501
            //remove self reference
4502
            $row['linksto'] = str_replace($row["reflink"], " ", trim($row["linksto"]));
4503
            $refs = explode(" ", trim($row["linksto"]));
4504
4505
            // Find linksto into reflink. If found ->page is linked
4506
            foreach ($refs as $v) {
4507
                if (in_array($v, $pages)) {
4508
                    if (trim($v) != "") {
4509
                        $linked[] = $v;
4510
                    }
4511
                }
4512
            }
4513
        }
4514
4515
        $linked = array_unique($linked);
4516
        //make a unique list. TODO:delete this line and count how many for each page
4517
        //show table
4518
        $rows = array();
4519
        foreach ($linked as $linked_show) {
4520
            $row = array();
4521
            $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(urlencode(str_replace('_', ' ', $linked_show))).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4522
                str_replace('_', ' ', $linked_show).'</a>';
4523
            $rows[] = $row;
4524
        }
4525
4526
        $table = new SortableTableFromArrayConfig(
4527
            $rows,
4528
            0,
4529
            10,
4530
            'LinkedPages_table',
4531
            '',
4532
            '',
4533
            'DESC'
4534
        );
4535
        $table->set_additional_parameters(
4536
            array(
4537
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
4538
                'action' => Security::remove_XSS($this->action),
4539
                'session_id' => intval($_GET['session_id']),
4540
                'group_id' => intval($_GET['group_id']),
4541
            )
4542
        );
4543
        $table->set_header(0, get_lang('Title'), true);
4544
        $table->display();
4545
    }
4546
4547
    /**
4548
     * Get orphan pages
4549
     */
4550
    public function getOrphaned()
4551
    {
4552
        $tbl_wiki = $this->tbl_wiki;
4553
        $course_id = $this->course_id;
4554
        $groupfilter = $this->groupfilter;
4555
        $condition_session = $this->condition_session;
4556
        $_course = $this->courseInfo;
4557
4558
        echo '<div class="actions">'.get_lang('OrphanedPages').'</div>';
4559
4560
        $pages = array();
4561
        $orphaned = array();
4562
4563
        //get name pages
4564
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4565
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
4566
                GROUP BY reflink
4567
                ORDER BY reflink ASC';
4568
        $allpages = Database::query($sql);
4569
        while ($row = Database::fetch_array($allpages)) {
4570
            $pages[] = $row['reflink'];
4571
        }
4572
4573
        //get name refs in last pages and make a unique list
4574
        $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1
4575
                WHERE s1.c_id = '.$course_id.' AND id=(
4576
                SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
4577
                WHERE
4578
                    s2.c_id = '.$course_id.' AND
4579
                    s1.reflink = s2.reflink AND
4580
                    '.$groupfilter.$condition_session.'
4581
                )';
4582
        $allpages = Database::query($sql);
4583
        $array_refs_linked = array();
4584
        while ($row = Database::fetch_array($allpages)) {
4585
            $row['linksto'] = str_replace($row["reflink"], " ", trim($row["linksto"])); //remove self reference
4586
            $refs = explode(" ", trim($row["linksto"]));
4587
            foreach ($refs as $ref_linked) {
4588
                if ($ref_linked == str_replace(' ', '_', get_lang('DefaultTitle'))) {
4589
                    $ref_linked = 'index';
4590
                }
4591
                $array_refs_linked[] = $ref_linked;
4592
            }
4593
        }
4594
4595
        $array_refs_linked = array_unique($array_refs_linked);
4596
4597
        //search each name of list linksto into list reflink
4598
        foreach ($pages as $v) {
4599
            if (!in_array($v, $array_refs_linked)) {
4600
                $orphaned[] = $v;
4601
            }
4602
        }
4603
        $rows = array();
4604
        foreach ($orphaned as $orphaned_show) {
4605
            // get visibility status and title
4606
            $sql = 'SELECT *
4607
                    FROM  '.$tbl_wiki.'
4608
		            WHERE
4609
		                c_id = '.$course_id.' AND
4610
		                '.$groupfilter.$condition_session.' AND
4611
		                reflink="'.Database::escape_string($orphaned_show).'"
4612
                    GROUP BY reflink';
4613
            $allpages = Database::query($sql);
4614
            while ($row = Database::fetch_array($allpages)) {
4615
                $orphaned_title = $row['title'];
4616
                $orphaned_visibility = $row['visibility'];
4617 View Code Duplication
                if ($row['assignment'] == 1) {
4618
                    $ShowAssignment = Display::return_icon('wiki_assignment.png', '', '', ICON_SIZE_SMALL);
4619
                } elseif ($row['assignment'] == 2) {
4620
                    $ShowAssignment = Display::return_icon('wiki_work.png', '', '', ICON_SIZE_SMALL);
4621
                } elseif ($row['assignment'] == 0) {
4622
                    $ShowAssignment = Display::return_icon('px_transparent.gif');
4623
                }
4624
            }
4625
4626
            if (!api_is_allowed_to_edit(false, true) || !api_is_platform_admin() && $orphaned_visibility == 0) {
4627
                continue;
4628
            }
4629
4630
            //show table
4631
            $row = array();
4632
            $row[] = $ShowAssignment;
4633
            $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(urlencode($orphaned_show)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4634
                api_htmlentities($orphaned_title).'</a>';
4635
            $rows[] = $row;
4636
        }
4637
4638
        $table = new SortableTableFromArrayConfig(
4639
            $rows,
4640
            1,
4641
            10,
4642
            'OrphanedPages_table',
4643
            '',
4644
            '',
4645
            'DESC'
4646
        );
4647
        $table->set_additional_parameters(
4648
            array(
4649
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
4650
                'action' => Security::remove_XSS($this->action),
4651
                'session_id' => intval($_GET['session_id']),
4652
                'group_id' => intval($_GET['group_id']),
4653
            )
4654
        );
4655
        $table->set_header(0, get_lang('Type'), true, array('style' => 'width:30px;'));
4656
        $table->set_header(1, get_lang('Title'), true);
4657
        $table->display();
4658
    }
4659
4660
    /**
4661
     * Get wanted pages
4662
     */
4663
    public function getWantedPages()
4664
    {
4665
        $tbl_wiki = $this->tbl_wiki;
4666
        $course_id = $this->course_id;
4667
        $groupfilter = $this->groupfilter;
4668
        $condition_session = $this->condition_session;
4669
4670
        echo '<div class="actions">'.get_lang('WantedPages').'</div>';
4671
        $pages = array();
4672
        $wanted = array();
4673
        //get name pages
4674
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4675
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
4676
                GROUP BY reflink
4677
                ORDER BY reflink ASC';
4678
        $allpages = Database::query($sql);
4679
4680 View Code Duplication
        while ($row = Database::fetch_array($allpages)) {
4681
            if ($row['reflink'] == 'index') {
4682
                $row['reflink'] = str_replace(' ', '_', get_lang('DefaultTitle'));
4683
            }
4684
            $pages[] = $row['reflink'];
4685
        }
4686
4687
        //get name refs in last pages
4688
        $sql = 'SELECT * FROM   '.$tbl_wiki.' s1
4689
                WHERE s1.c_id = '.$course_id.' AND id=(
4690
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
4691
                    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.$condition_session.'
4692
                )';
4693
4694
        $allpages = Database::query($sql);
4695
4696
        while ($row = Database::fetch_array($allpages)) {
4697
            $refs = explode(" ", trim($row["linksto"]));
4698
            // Find linksto into reflink. If not found ->page is wanted
4699
            foreach ($refs as $v) {
4700
                if (!in_array($v, $pages)) {
4701
                    if (trim($v) != "") {
4702
                        $wanted[] = $v;
4703
                    }
4704
                }
4705
            }
4706
        }
4707
4708
        $wanted = array_unique($wanted); //make a unique list
4709
4710
        //show table
4711
        $rows = array();
4712
        foreach ($wanted as $wanted_show) {
4713
            $row = array();
4714
            $wanted_show = Security::remove_XSS($wanted_show);
4715
            $row[] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?cidReq=&action=addnew&title='.str_replace('_', ' ', $wanted_show).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'" class="new_wiki_link">'.str_replace('_', ' ', $wanted_show).'</a>'; //meter un remove xss en lugar de htmlentities
4716
            $rows[] = $row;
4717
        }
4718
4719
        $table = new SortableTableFromArrayConfig(
4720
            $rows,
4721
            0,
4722
            10,
4723
            'WantedPages_table',
4724
            '',
4725
            '',
4726
            'DESC'
4727
        );
4728
        $table->set_additional_parameters(
4729
            array(
4730
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
4731
                'action' => Security::remove_XSS($this->action),
4732
                'session_id' => intval($_GET['session_id']),
4733
                'group_id' => intval($_GET['group_id']),
4734
            )
4735
        );
4736
        $table->set_header(0, get_lang('Title'), true);
4737
        $table->display();
4738
    }
4739
4740
    /**
4741
     * Most visited
4742
     */
4743 View Code Duplication
    public function getMostVisited()
4744
    {
4745
        $tbl_wiki = $this->tbl_wiki;
4746
        $course_id = $this->course_id;
4747
        $groupfilter = $this->groupfilter;
4748
        $condition_session = $this->condition_session;
4749
        $_course = $this->courseInfo;
4750
4751
        echo '<div class="actions">'.get_lang('MostVisitedPages').'</div>';
4752
4753
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) { //only by professors if page is hidden
4754
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
4755
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
4756
                    GROUP BY reflink';
4757
        } else {
4758
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
4759
                    WHERE
4760
                        c_id = '.$course_id.' AND
4761
                        '.$groupfilter.$condition_session.' AND
4762
                        visibility=1
4763
                    GROUP BY reflink';
4764
        }
4765
4766
        $allpages = Database::query($sql);
4767
4768
        //show table
4769
        if (Database::num_rows($allpages) > 0) {
4770
            $rows = array();
4771
            while ($obj = Database::fetch_object($allpages)) {
4772
                //get type assignment icon
4773
                $ShowAssignment = '';
4774
                if ($obj->assignment == 1) {
4775
                    $ShowAssignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'), '', ICON_SIZE_SMALL);
4776
                } elseif ($obj->assignment == 2) {
4777
                    $ShowAssignment = $ShowAssignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'), '', ICON_SIZE_SMALL);
4778
                } elseif ($obj->assignment == 0) {
4779
                    $ShowAssignment = Display::return_icon('px_transparent.gif');
4780
                }
4781
4782
                $row = array();
4783
                $row[] = $ShowAssignment;
4784
                $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4785
                    api_htmlentities($obj->title).'</a>';
4786
                $row[] = $obj->tsum;
4787
                $rows[] = $row;
4788
            }
4789
4790
            $table = new SortableTableFromArrayConfig(
4791
                $rows,
4792
                2,
4793
                10,
4794
                'MostVisitedPages_table',
4795
                '',
4796
                '',
4797
                'DESC'
4798
            );
4799
            $table->set_additional_parameters(
4800
                array(
4801
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
4802
                    'action' => Security::remove_XSS($this->action),
4803
                    'session_id' => intval($_GET['session_id']),
4804
                    'group_id' => intval($_GET['group_id']),
4805
                )
4806
            );
4807
            $table->set_header(0, get_lang('Type'), true, array('style' => 'width:30px;'));
4808
            $table->set_header(1, get_lang('Title'), true);
4809
            $table->set_header(2, get_lang('Visits'), true);
4810
            $table->display();
4811
        }
4812
    }
4813
4814
    /**
4815
     * Get actions bar
4816
     * @return string
4817
     */
4818
    public function showActionBar()
4819
    {
4820
        $_course = $this->courseInfo;
4821
        $session_id = $this->session_id;
4822
        $groupId = $this->group_id;
4823
        $page = $this->page;
4824
        $actionsLeft = '';
4825
        $actionsLeft .= '<a href="index.php?action=showpage&title=index&cidReq='.$_course['id'].'&session_id='.$session_id.'&group_id='.$groupId.'">'.
4826
            Display::return_icon('home.png', get_lang('Home'), '', ICON_SIZE_MEDIUM).'</a>';
4827
4828
        if (api_is_allowed_to_session_edit(false, true) && api_is_allowed_to_edit()) {
4829
            // menu add page
4830
            $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=addnew&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab('addnew').'>'
4831
            . Display::return_icon('add.png', get_lang('AddNew'), '', ICON_SIZE_MEDIUM).'</a>';
4832
        }
4833
4834
        $lock_unlock_addnew = null;
4835
        $protect_addnewpage = null;
4836
4837 View Code Duplication
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4838
            // page action: enable or disable the adding of new pages
4839
            if (self::check_addnewpagelock() == 0) {
4840
                $protect_addnewpage = Display::return_icon('off.png', get_lang('AddOptionProtected'));
4841
                $lock_unlock_addnew = 'unlockaddnew';
4842
            } else {
4843
                $protect_addnewpage = Display::return_icon('on.png', get_lang('AddOptionUnprotected'));
4844
                $lock_unlock_addnew = 'lockaddnew';
4845
            }
4846
        }
4847
4848
        // menu find
4849
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab('searchpages').'>'.
4850
            Display::return_icon('search.png', get_lang('SearchPages'), '', ICON_SIZE_MEDIUM).'</a></li>';
4851
        ///menu more
4852
        $actionsLeft .= '<a href="index.php?action=more&amp;title='.api_htmlentities(urlencode($page)).'"'.self::is_active_navigation_tab('more').'>'.
4853
            Display::return_icon('stats.png', get_lang('Statistics'), '', ICON_SIZE_MEDIUM).'</a></li>';
4854
4855
        // menu all pages
4856
        $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('allpages').'>'.
4857
            get_lang('AllPages').'</a>';
4858
        // menu recent changes
4859
        $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('recentchanges').'>'.
4860
            get_lang('RecentChanges').'</a>';
4861
        echo Display::toolbarAction('toolbar-wiki', [$actionsLeft]);
4862
    }
4863
4864
    /**
4865
     * Showing warning
4866
     */
4867
    public function deletePageWarning()
4868
    {
4869
        $page = $this->page;
4870
        $course_id = $this->course_id;
4871
        $groupfilter = $this->groupfilter;
4872
        $condition_session = $this->condition_session;
4873
4874 View Code Duplication
        if (!$_GET['title']) {
4875
            Display::addFlash(Display::return_message(get_lang('MustSelectPage'), 'error', false));
4876
            return;
4877
        }
4878
4879
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4880
            Display::addFlash('<div id="wikititle">'.get_lang('DeletePageHistory').'</div>');
4881
            if ($page == "index") {
4882
                Display::addFlash(Display::return_message(get_lang('WarningDeleteMainPage'), 'warning', false));
4883
            }
4884
            $message = get_lang('ConfirmDeletePage')."
4885
                <a href=\"index.php?".api_get_cidreq()."\">".get_lang("No")."</a>
4886
                <a href=\"".api_get_self()."?".api_get_cidreq()."&action=delete&title=".api_htmlentities(urlencode($page))."&delete=yes\">".
4887
                get_lang("Yes")."</a>";
4888
4889
            if (!isset($_GET['delete'])) {
4890
                Display::addFlash(Display::return_message($message, 'warning', false));
4891
            }
4892
4893
            if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
4894
                $result = self::deletePage($page, $course_id, $groupfilter, $condition_session);
4895
                if ($result) {
4896
                    Display::addFlash(Display::return_message(get_lang('WikiPageDeleted'), 'confirmation', false));
4897
                }
4898
            }
4899
        } else {
4900
            Display::addFlash(
4901
                Display::return_message(
4902
                    get_lang('OnlyAdminDeletePageWiki'),
4903
                    'normal',
4904
                    false
4905
                )
4906
            );
4907
        }
4908
    }
4909
4910
    /**
4911
     * Edit page
4912
     */
4913
    public function editPage()
4914
    {
4915
        $tbl_wiki = $this->tbl_wiki;
4916
        $tbl_wiki_conf = $this->tbl_wiki_conf;
4917
        $condition_session = $this->condition_session;
4918
        $groupfilter = $this->groupfilter;
4919
        $page = $this->page;
4920
        $course_id = $this->course_id;
4921
        $groupId = $this->group_id;
4922
        $userId = api_get_user_id();
4923
4924 View Code Duplication
        if (api_get_session_id() != 0 &&
4925
            api_is_allowed_to_session_edit(false, true) == false
4926
        ) {
4927
            api_not_allowed();
4928
        }
4929
4930
        $sql = 'SELECT *
4931
                FROM '.$tbl_wiki.' w INNER JOIN '.$tbl_wiki_conf.' c
4932
                ON  (w.c_id = c.c_id AND w.page_id = c.page_id)
4933
                WHERE
4934
    		        w.c_id = '.$course_id.' AND
4935
                    w.reflink= "'.Database::escape_string($page).'" AND
4936
                    w.'.$groupfilter.$condition_session.'
4937
                ORDER BY id DESC';
4938
        $result = Database::query($sql);
4939
        $row = Database::fetch_array($result);
4940
4941
        // we do not need a while loop since we are always displaying the last version
4942
        if ($row['content'] == '' && $row['title'] == '' && $page == '') {
4943
            Display::addFlash(
4944
                Display::return_message(get_lang('MustSelectPage'), 'error', false)
4945
            );
4946
            return;
4947
        } elseif ($row['content'] == '' && $row['title'] == '' && $page == 'index') {
4948
4949
            // Table structure for better export to pdf
4950
            $default_table_for_content_Start = '<table align="center" border="0"><tr><td align="center">';
4951
            $default_table_for_content_End = '</td></tr></table>';
4952
            $content = $default_table_for_content_Start.sprintf(get_lang('DefaultContent'), api_get_path(WEB_IMG_PATH)).$default_table_for_content_End;
4953
            $title = get_lang('DefaultTitle');
4954
            $page_id = 0;
4955
        } else {
4956
            $content = api_html_entity_decode($row['content']);
4957
            $title = api_html_entity_decode($row['title']);
4958
            $page_id = $row['page_id'];
4959
        }
4960
4961
        // Only teachers and platform admin can edit the index page.
4962
        // Only teachers and platform admin can edit an assignment teacher.
4963
        // And users in groups
4964
4965
        if (($row['reflink'] == 'index' || $row['reflink'] == '' || $row['assignment'] == 1) &&
4966
            (!api_is_allowed_to_edit(false, true) && $groupId == 0) && !api_is_allowed_in_course()
4967
        ) {
4968
            Display::addFlash(
4969
                Display::return_message(get_lang('OnlyEditPagesCourseManager')),
4970
                'error'
4971
            );
4972
        } else {
4973
            $PassEdit = false;
4974
4975
            // Check if is a wiki group
4976
            if (!empty($groupId)) {
4977
                $groupInfo = GroupManager::get_group_properties($groupId);
4978
                //Only teacher, platform admin and group members can edit a wiki group
4979 View Code Duplication
                if (api_is_allowed_to_edit(false, true) ||
4980
                    api_is_platform_admin() ||
4981
                    GroupManager::is_user_in_group($userId, $groupInfo)
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 4977 can also be of type null; however, GroupManager::is_user_in_group() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
4982
                ) {
4983
                    $PassEdit = true;
4984
                } else {
4985
                    Display::addFlash(
4986
                        Display::return_message(
4987
                            get_lang('OnlyEditPagesGroupMembers')
4988
                        )
4989
                    );
4990
                }
4991
            } else {
4992
                $PassEdit = true;
4993
            }
4994
4995
            $icon_assignment = null;
4996
            // check if is a assignment
4997
            if ($row['assignment'] == 1) {
4998
                Display::addFlash(
4999
                    Display::return_message(get_lang('EditAssignmentWarning'))
5000
                );
5001
5002
                $icon_assignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'), '', ICON_SIZE_SMALL);
5003
            } elseif ($row['assignment'] == 2) {
5004
                $icon_assignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWorkExtra'), '', ICON_SIZE_SMALL);
5005 View Code Duplication
                if (($userId == $row['user_id']) == false) {
5006
                    if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5007
                        $PassEdit = true;
5008
                    } else {
5009
                        Display::addFlash(
5010
                            Display::return_message(
5011
                                get_lang('LockByTeacher'),
5012
                                'warning'
5013
                            )
5014
                        );
5015
                        $PassEdit = false;
5016
                    }
5017
                } else {
5018
                    $PassEdit = true;
5019
                }
5020
            }
5021
5022
            if ($PassEdit) {
5023
                //show editor if edit is allowed <<<<<
5024
                if ($row['editlock'] == 1 &&
5025
                    (api_is_allowed_to_edit(false, true) == false || api_is_platform_admin() == false)
5026
                ) {
5027
                    Display::addFlash(
5028
                        Display::return_message(
5029
                            get_lang('PageLockedExtra')
5030
                        )
5031
                    );
5032
                } else {
5033
                    // Check tasks
5034
5035
                    if (!empty($row['startdate_assig']) && time() < api_strtotime($row['startdate_assig'])
5036
                    ) {
5037
                        $message = get_lang('TheTaskDoesNotBeginUntil').': '.api_get_local_time($row['startdate_assig']);
5038
5039
                        Display::addFlash(
5040
                            Display::return_message(
5041
                                $message,
5042
                                'warning'
5043
                            )
5044
                        );
5045
5046
                        if (!api_is_allowed_to_edit(false, true)) {
5047
                            $this->redirectHome();
5048
                        }
5049
                    }
5050
5051
                    if (!empty($row['enddate_assig']) &&
5052
                        time() > strtotime($row['enddate_assig']) &&
5053
                        $row['delayedsubmit'] == 0
5054
                    ) {
5055
                        $message = get_lang('TheDeadlineHasBeenCompleted').': '.api_get_local_time($row['enddate_assig']);
5056
                        Display::addFlash(
5057
                            Display::return_message(
5058
                                $message,
5059
                                'warning'
5060
                            )
5061
                        );
5062
                        if (!api_is_allowed_to_edit(false, true)) {
5063
                            $this->redirectHome();
5064
                        }
5065
                    }
5066
5067 View Code Duplication
                    if (!empty($row['max_version']) && $row['version'] >= $row['max_version']) {
5068
                        $message = get_lang('HasReachedMaxiNumVersions');
5069
                        Display::addFlash(
5070
                            Display::return_message(
5071
                                $message,
5072
                                'warning'
5073
                            )
5074
                        );
5075
                        if (!api_is_allowed_to_edit(false, true)) {
5076
                            $this->redirectHome();
5077
                        }
5078
                    }
5079
5080 View Code Duplication
                    if (!empty($row['max_text']) && $row['max_text'] <= self::word_count($row['content'])) {
5081
                        $message = get_lang('HasReachedMaxNumWords');
5082
                        Display::addFlash(
5083
                            Display::return_message(
5084
                                $message,
5085
                                'warning'
5086
                            )
5087
                        );
5088
                        if (!api_is_allowed_to_edit(false, true)) {
5089
                            $this->redirectHome();
5090
                        }
5091
                    }
5092
5093
                    if (!empty($row['task'])) {
5094
                        //previous change 0 by text
5095 View Code Duplication
                        if (!empty($row['startdate_assig'])) {
5096
                            $message_task_startdate = get_lang('No');
5097
                        } else {
5098
                            $message_task_startdate = api_get_local_time($row['startdate_assig']);
5099
                        }
5100
5101 View Code Duplication
                        if (!empty($row['enddate_assig'])) {
5102
                            $message_task_enddate = get_lang('No');
5103
                        } else {
5104
                            $message_task_enddate = api_get_local_time($row['enddate_assig']);
5105
                        }
5106
5107
                        if ($row['delayedsubmit'] == 0) {
5108
                            $message_task_delayedsubmit = get_lang('No');
5109
                        } else {
5110
                            $message_task_delayedsubmit = get_lang('Yes');
5111
                        }
5112
5113
                        if ($row['max_version'] == 0) {
5114
                            $message_task_max_version = get_lang('No');
5115
                        } else {
5116
                            $message_task_max_version = $row['max_version'];
5117
                        }
5118
5119
                        if ($row['max_text'] == 0) {
5120
                            $message_task_max_text = get_lang('No');
5121
                        } else {
5122
                            $message_task_max_text = $row['max_text'];
5123
                        }
5124
5125
                        // Comp message
5126
                        $message_task = '<b>'.get_lang('DescriptionOfTheTask').'</b><p>'.$row['task'].'</p><hr>';
5127
                        $message_task .= '<p>'.get_lang('StartDate').': '.$message_task_startdate.'</p>';
5128
                        $message_task .= '<p>'.get_lang('EndDate').': '.$message_task_enddate;
5129
                        $message_task .= ' ('.get_lang('AllowLaterSends').') '.$message_task_delayedsubmit.'</p>';
5130
                        $message_task .= '<p>'.get_lang('OtherSettings').': '.get_lang('NMaxVersion').': '.$message_task_max_version;
5131
                        $message_task .= ' '.get_lang('NMaxWords').': '.$message_task_max_text;
5132
                        // Display message
5133
                        Display::addFlash(
5134
                            Display::return_message(
5135
                                $message_task
5136
                            )
5137
                        );
5138
                    }
5139
5140
                    $feedback_message = '';
5141
                    if ($row['progress'] == $row['fprogress1'] && !empty($row['fprogress1'])) {
5142
                        $feedback_message = '<b>'.get_lang('Feedback').'</b><p>'.api_htmlentities($row['feedback1']).'</p>';
5143
                    } elseif ($row['progress'] == $row['fprogress2'] && !empty($row['fprogress2'])) {
5144
                        $feedback_message = '<b>'.get_lang('Feedback').'</b><p>'.api_htmlentities($row['feedback2']).'</p>';
5145
                    } elseif ($row['progress'] == $row['fprogress3'] && !empty($row['fprogress3'])) {
5146
                        $feedback_message = '<b>'.get_lang('Feedback').'</b><p>'.api_htmlentities($row['feedback3']).'</p>';
5147
                    }
5148
5149
                    if (!empty($feedback_message)) {
5150
                        Display::addFlash(
5151
                            Display::return_message(
5152
                                $feedback_message
5153
                            )
5154
                        );
5155
                    }
5156
5157
                    // Previous checking for concurrent editions
5158
                    if ($row['is_editing'] == 0) {
5159
                        Display::addFlash(
5160
                            Display::return_message(
5161
                                get_lang('WarningMaxEditingTime')
5162
                            )
5163
                        );
5164
                        $time_edit = api_get_utc_datetime();
5165
                        $sql = 'UPDATE '.$tbl_wiki.' SET
5166
                                is_editing = "'.$userId.'",
5167
                                time_edit = "'.$time_edit.'"
5168
                                WHERE c_id = '.$course_id.' AND id="'.$row['id'].'"';
5169
                        Database::query($sql);
5170
                    } elseif ($row['is_editing'] != $userId) {
5171
                        $timestamp_edit = strtotime($row['time_edit']);
5172
                        $time_editing = time() - $timestamp_edit;
5173
                        $max_edit_time = 1200; // 20 minutes
5174
                        $rest_time = $max_edit_time - $time_editing;
5175
5176
                        $userinfo = api_get_user_info($row['is_editing']);
5177
                        if ($userinfo !== false) {
5178
                            $is_being_edited = get_lang('ThisPageisBeginEditedBy').' '.UserManager::getUserProfileLink($userinfo).'
5179
                            ' . get_lang('ThisPageisBeginEditedTryLater').' '.date("i", $rest_time).' '.get_lang('MinMinutes').'';
5180
                        }
5181
5182
                        Display::addFlash(
5183
                            Display::return_message(
5184
                                $is_being_edited,
5185
                                'normal',
5186
                                false
5187
                            )
5188
                        );
5189
5190
                        $this->redirectHome();
5191
                    }
5192
5193
                    // Form.
5194
                    $url = api_get_self().'?action=edit&title='.urlencode($page).'&session_id='.api_get_session_id().'&group_id='.api_get_group_id().'&'.api_get_cidreq();
5195
                    $form = new FormValidator('wiki', 'post', $url);
5196
                    $form->addElement('header', $icon_assignment.str_repeat('&nbsp;', 3).api_htmlentities($title));
5197
                    self::setForm($form, $row);
5198
                    $form->addElement('hidden', 'title');
5199
                    $form->addButtonSave(get_lang('Save'), 'SaveWikiChange');
5200
                    $row['title'] = $title;
5201
                    $row['page_id'] = $page_id;
5202
                    $row['reflink'] = $page;
5203
                    $row['content'] = $content;
5204
5205
                    $form->setDefaults($row);
5206
                    $form->display();
5207
5208
                    // Saving a change
5209
                    if ($form->validate()) {
5210
                        $versionFromSession = Session::read('_version');
5211
                        if (empty($_POST['title'])) {
5212
                            Display::addFlash(
5213
                                Display::return_message(
5214
                                    get_lang("NoWikiPageTitle"),
5215
                                    'error'
5216
                                )
5217
                            );
5218
                        } 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...
5219
                            //double post
5220
                        } elseif ($_POST['version'] != '' && $versionFromSession != 0 && $_POST['version'] != $versionFromSession) {
5221
                            //prevent concurrent users and double version
5222
                            Display::addFlash(
5223
                                Display::return_message(
5224
                                    get_lang("EditedByAnotherUser"),
5225
                                    'error'
5226
                                )
5227
                            );
5228
                        } else {
5229
                            $returnMessage = self::save_wiki($form->exportValues());
5230
                            Display::addFlash(
5231
                                Display::return_message(
5232
                                    $returnMessage,
5233
                                    'confirmation'
5234
                                )
5235
                            );
5236
                        }
5237
                        $wikiData = self::getWikiData();
5238
                        $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq();
5239
                        header('Location: '.$redirectUrl);
5240
                        exit;
5241
                    }
5242
                }
5243
            }
5244
        }
5245
    }
5246
5247
    /**
5248
     * Get history
5249
     */
5250
    public function getHistory()
5251
    {
5252
        $tbl_wiki = $this->tbl_wiki;
5253
        $condition_session = $this->condition_session;
5254
        $groupfilter = $this->groupfilter;
5255
        $page = $this->page;
5256
        $course_id = $this->course_id;
5257
        $session_id = $this->session_id;
5258
        $userId = api_get_user_id();
5259
5260 View Code Duplication
        if (!$_GET['title']) {
5261
            Display::addFlash(Display::return_message(get_lang("MustSelectPage"), 'error', false));
5262
            return;
5263
        }
5264
5265
        /* First, see the property visibility that is at the last register and
5266
        therefore we should select descending order.
5267
        But to give ownership to each record,
5268
        this is no longer necessary except for the title. TODO: check this*/
5269
5270
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5271
                WHERE
5272
                    c_id = '.$course_id.' AND
5273
                    reflink="'.Database::escape_string($page).'" AND
5274
                    '.$groupfilter.$condition_session.'
5275
                ORDER BY id DESC';
5276
        $result = Database::query($sql);
5277
5278
        $KeyVisibility = null;
5279
        $KeyAssignment = null;
5280
        $KeyTitle = null;
5281
        $KeyUserId = null;
5282
        while ($row = Database::fetch_array($result)) {
5283
            $KeyVisibility = $row['visibility'];
5284
            $KeyAssignment = $row['assignment'];
5285
            $KeyTitle = $row['title'];
5286
            $KeyUserId = $row['user_id'];
5287
        }
5288
        $icon_assignment = null;
5289
        if ($KeyAssignment == 1) {
5290
            $icon_assignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'), '', ICON_SIZE_SMALL);
5291
        } elseif ($KeyAssignment == 2) {
5292
            $icon_assignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWorkExtra'), '', ICON_SIZE_SMALL);
5293
        }
5294
5295
        // Second, show
5296
5297
        //if the page is hidden and is a job only sees its author and professor
5298
        if ($KeyVisibility == 1 ||
5299
            api_is_allowed_to_edit(false, true) ||
5300
            api_is_platform_admin() ||
5301
            (
5302
                $KeyAssignment == 2 && $KeyVisibility == 0 &&
5303
                ($userId == $KeyUserId)
5304
            )
5305
        ) {
5306
            // We show the complete history
5307
            if (!isset($_POST['HistoryDifferences']) && !isset($_POST['HistoryDifferences2'])) {
5308
                $sql = 'SELECT * FROM '.$tbl_wiki.'
5309
                        WHERE
5310
                            c_id = '.$course_id.' AND
5311
                            reflink="'.Database::escape_string($page).'" AND
5312
                            '.$groupfilter.$condition_session.'
5313
                        ORDER BY id DESC';
5314
                $result = Database::query($sql);
5315
                $title = $_GET['title'];
5316
                $group_id = api_get_group_id();
5317
5318
                echo '<div id="wikititle">';
5319
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities($KeyTitle);
5320
                echo '</div>';
5321
5322
                echo '<form id="differences" method="POST" action="index.php?'.api_get_cidreq().'&action=history&title='.api_htmlentities(urlencode($title)).'&session_id='.api_htmlentities($session_id).'&group_id='.api_htmlentities($group_id).'">';
5323
5324
                echo '<ul style="list-style-type: none;">';
5325
                echo '<br/>';
5326
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.
5327
                    get_lang('ShowDifferences').' '.get_lang('LinesDiff').'</button>';
5328
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.
5329
                    get_lang('ShowDifferences').' '.get_lang('WordsDiff').'</button>';
5330
                echo '<br/><br/>';
5331
5332
                $counter = 0;
5333
                $total_versions = Database::num_rows($result);
5334
5335
                while ($row = Database::fetch_array($result)) {
5336
                    $userinfo = api_get_user_info($row['user_id']);
5337
                    $username = api_htmlentities(sprintf(get_lang('LoginX'), $userinfo['username']), ENT_QUOTES);
5338
5339
                    echo '<li style="margin-bottom: 5px;">';
5340
                    ($counter == 0) ? $oldstyle = 'style="visibility: hidden;"' : $oldstyle = '';
5341
                    ($counter == 0) ? $newchecked = ' checked' : $newchecked = '';
5342
                    ($counter == $total_versions - 1) ? $newstyle = 'style="visibility: hidden;"' : $newstyle = '';
5343
                    ($counter == 1) ? $oldchecked = ' checked' : $oldchecked = '';
5344
                    echo '<input name="old" value="'.$row['id'].'" type="radio" '.$oldstyle.' '.$oldchecked.'/> ';
5345
                    echo '<input name="new" value="'.$row['id'].'" type="radio" '.$newstyle.' '.$newchecked.'/> ';
5346
                    echo '<a href="'.api_get_self().'?action=showpage&amp;title='.api_htmlentities(urlencode($page)).'&amp;view='.$row['id'].'">';
5347
                    echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=showpage&title='.api_htmlentities(urlencode($page)).'&view='.$row['id'].'">';
5348
                    echo api_get_local_time($row['dtime'], null, date_default_timezone_get());
5349
                    echo '</a>';
5350
                    echo ' ('.get_lang('Version').' '.$row['version'].')';
5351
                    echo ' '.get_lang('By').' ';
5352
                    if ($userinfo !== false) {
5353
                        echo UserManager::getUserProfileLink($userinfo);
5354
                    } else {
5355
                        echo get_lang('Anonymous').' ('.api_htmlentities($row['user_ip']).')';
5356
                    }
5357
                    echo ' ( '.get_lang('Progress').': '.api_htmlentities($row['progress']).'%, ';
5358
                    $comment = $row['comment'];
5359
                    if (!empty($comment)) {
5360
                        $comment = api_substr($comment, 0, 100);
5361
                        if ($comment !== false) {
5362
                            $comment = api_htmlentities($comment);
5363
                            echo get_lang('Comments').': '.$comment;
5364
                            if (api_strlen($row['comment']) > 100) {
5365
                                echo '... ';
5366
                            }
5367
                        }
5368
                    } else {
5369
                        echo get_lang('Comments').':  ---';
5370
                    }
5371
                    echo ' ) </li>';
5372
                    $counter++;
5373
                } //end while
5374
5375
                echo '<br/>';
5376
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.get_lang('ShowDifferences').' '.get_lang('LinesDiff').'</button>';
5377
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.get_lang('ShowDifferences').' '.get_lang('WordsDiff').'</button>';
5378
                echo '</ul></form>';
5379
            } else { // We show the differences between two versions
5380
                $version_old = array();
5381 View Code Duplication
                if (isset($_POST['old'])) {
5382
                    $sql_old = "SELECT * FROM $tbl_wiki
5383
                                WHERE c_id = $course_id AND id='".Database::escape_string($_POST['old'])."'";
5384
                    $result_old = Database::query($sql_old);
5385
                    $version_old = Database::fetch_array($result_old);
5386
                }
5387
5388
                $sql_new = "SELECT * FROM $tbl_wiki
5389
                            WHERE c_id = $course_id AND id='".Database::escape_string($_POST['new'])."'";
5390
                $result_new = Database::query($sql_new);
5391
                $version_new = Database::fetch_array($result_new);
5392
                $oldTime = isset($version_old['dtime']) ? $version_old['dtime'] : null;
5393
                $oldContent = isset($version_old['content']) ? $version_old['content'] : null;
5394
5395
                if (isset($_POST['HistoryDifferences'])) {
5396
                    include 'diff.inc.php';
5397
                    //title
5398
                    echo '<div id="wikititle">'.api_htmlentities($version_new['title']).'
5399
                            <font size="-2"><i>('.get_lang('DifferencesNew').'</i>
5400
                            <font style="background-color:#aaaaaa">'.$version_new['dtime'].'</font>
5401
                            <i>'.get_lang('DifferencesOld').'</i>
5402
                            <font style="background-color:#aaaaaa">'.$oldTime.'</font>
5403
                ) '.get_lang('Legend').':  <span class="diffAdded" >'.get_lang('WikiDiffAddedLine').'</span>
5404
                <span class="diffDeleted" >'.get_lang('WikiDiffDeletedLine').'</span> <span class="diffMoved">'.get_lang('WikiDiffMovedLine').'</span></font>
5405
                </div>';
5406
                }
5407
                if (isset($_POST['HistoryDifferences2'])) {
5408
                    //title
5409
                    echo '<div id="wikititle">'.api_htmlentities($version_new['title']).'
5410
                        <font size="-2"><i>('.get_lang('DifferencesNew').'</i> <font style="background-color:#aaaaaa">'.$version_new['dtime'].'</font>
5411
                        <i>'.get_lang('DifferencesOld').'</i> <font style="background-color:#aaaaaa">'.$oldTime.'</font>)
5412
                        '.get_lang('Legend').':  <span class="diffAddedTex" >'.get_lang('WikiDiffAddedTex').'</span>
5413
                        <span class="diffDeletedTex" >'.get_lang('WikiDiffDeletedTex').'</span></font></div>';
5414
                }
5415
5416
5417
                if (isset($_POST['HistoryDifferences'])) {
5418
                    echo '<table>'.diff($oldContent, $version_new['content'], true, 'format_table_line').'</table>'; // format_line mode is better for words
5419
                    echo '<br />';
5420
                    echo '<strong>'.get_lang('Legend').'</strong><div class="diff">'."\n";
5421
                    echo '<table><tr>';
5422
                    echo  '<td>';
5423
                    echo '</td><td>';
5424
                    echo '<span class="diffEqual" >'.get_lang('WikiDiffUnchangedLine').'</span><br />';
5425
                    echo '<span class="diffAdded" >'.get_lang('WikiDiffAddedLine').'</span><br />';
5426
                    echo '<span class="diffDeleted" >'.get_lang('WikiDiffDeletedLine').'</span><br />';
5427
                    echo '<span class="diffMoved" >'.get_lang('WikiDiffMovedLine').'</span><br />';
5428
                    echo '</td>';
5429
                    echo '</tr></table>';
5430
                }
5431
5432
                if (isset($_POST['HistoryDifferences2'])) {
5433
                    $lines1 = array(strip_tags($oldContent)); //without <> tags
5434
                    $lines2 = array(strip_tags($version_new['content'])); //without <> tags
5435
                    $diff = new Text_Diff($lines1, $lines2);
5436
                    $renderer = new Text_Diff_Renderer_inline();
5437
                    echo '<style>del{background:#fcc}ins{background:#cfc}</style>'.$renderer->render($diff); // Code inline
5438
                    echo '<br />';
5439
                    echo '<strong>'.get_lang('Legend').'</strong><div class="diff">'."\n";
5440
                    echo '<table><tr>';
5441
                    echo  '<td>';
5442
                    echo '</td><td>';
5443
                    echo '<span class="diffAddedTex" >'.get_lang('WikiDiffAddedTex').'</span><br />';
5444
                    echo '<span class="diffDeletedTex" >'.get_lang('WikiDiffDeletedTex').'</span><br />';
5445
                    echo '</td>';
5446
                    echo '</tr></table>';
5447
                }
5448
            }
5449
        }
5450
    }
5451
5452
    /**
5453
     * Get stat tables
5454
     */
5455
    public function getStatsTable()
5456
    {
5457
        $_course = $this->courseInfo;
5458
        $session_id = $this->session_id;
5459
        $groupId = $this->group_id;
5460
5461
        echo '<div class="actions">'.get_lang('More').'</div>';
5462
        echo '<table border="0">';
5463
        echo '  <tr>';
5464
        echo '    <td>';
5465
        echo '      <ul>';
5466
        //Submenu Most active users
5467
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mactiveusers&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostActiveUsers').'</a></li>';
5468
        //Submenu Most visited pages
5469
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mvisited&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostVisitedPages').'</a></li>';
5470
        //Submenu Most changed pages
5471
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mostchanged&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostChangedPages').'</a></li>';
5472
        echo '      </ul>';
5473
        echo '    </td>';
5474
        echo '    <td>';
5475
        echo '      <ul>';
5476
        // Submenu Orphaned pages
5477
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=orphaned&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('OrphanedPages').'</a></li>';
5478
        // Submenu Wanted pages
5479
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=wanted&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('WantedPages').'</a></li>';
5480
        // Submenu Most linked pages
5481
        echo '<li><a href="index.php?cidReq='.$_course['code'].'&action=mostlinked&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostLinkedPages').'</a></li>';
5482
        echo '</ul>';
5483
        echo '</td>';
5484
        echo '<td style="vertical-align:top">';
5485
        echo '<ul>';
5486
        // Submenu Statistics
5487
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5488
            echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=statistics&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('Statistics').'</a></li>';
5489
        }
5490
        echo '      </ul>';
5491
        echo'    </td>';
5492
        echo '  </tr>';
5493
        echo '</table>';
5494
    }
5495
5496
    /**
5497
     * Kind of controller
5498
     * @param string $action
5499
     */
5500
    public function handleAction($action)
5501
    {
5502
        $page = $this->page;
5503
        switch ($action) {
5504
            case 'export_to_pdf':
5505
                if (isset($_GET['wiki_id'])) {
5506
                    self::export_to_pdf($_GET['wiki_id'], api_get_course_id());
5507
                    break;
5508
                }
5509
                break;
5510
            case 'export2doc':
5511
                if (isset($_GET['wiki_id'])) {
5512
                    $export2doc = self::export2doc($_GET['wiki_id']);
5513
                    if ($export2doc) {
5514
                        Display::addFlash(
5515
                            Display::return_message(
5516
                                get_lang('ThePageHasBeenExportedToDocArea'),
5517
                                'confirmation',
5518
                                false
5519
                            )
5520
                        );
5521
                    }
5522
                }
5523
                break;
5524
            case 'restorepage':
5525
                self::restorePage();
5526
                break;
5527
            case 'more':
5528
                self::getStatsTable();
5529
                break;
5530
            case 'statistics':
5531
                self::getStats();
5532
                break;
5533
            case 'mactiveusers':
5534
                self::getActiveUsers($action);
5535
                break;
5536
            case 'usercontrib':
5537
                self::getUserContributions($_GET['user_id'], $action);
5538
                break;
5539
            case 'mostchanged':
5540
                $this->getMostChangedPages($action);
5541
                break;
5542
            case 'mvisited':
5543
                self::getMostVisited();
5544
                break;
5545
            case 'wanted':
5546
                $this->getWantedPages();
5547
                break;
5548
            case 'orphaned':
5549
                self::getOrphaned();
5550
                break;
5551
            case 'mostlinked':
5552
                self::getMostLinked();
5553
                break;
5554
            case 'delete':
5555
                self::deletePageWarning($page);
5556
                break;
5557
            case 'deletewiki':
5558
                $title = '<div class="actions">'.get_lang('DeleteWiki').'</div>';
5559
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5560
                    $message = get_lang('ConfirmDeleteWiki');
5561
                    $message .= '<p>
5562
                        <a href="index.php?'.api_get_cidreq().'">'.get_lang('No').'</a>
5563
                        &nbsp;&nbsp;|&nbsp;&nbsp;
5564
                        <a href="'.api_get_self().'?'.api_get_cidreq().'&action=deletewiki&delete=yes">'.
5565
                        get_lang('Yes').'</a>
5566
                    </p>';
5567
5568 View Code Duplication
                    if (!isset($_GET['delete'])) {
5569
                        Display::addFlash($title.Display::return_message($message, 'warning', false));
5570
                    }
5571
                } else {
5572
                    Display::addFlash(Display::return_message(get_lang("OnlyAdminDeleteWiki"), 'normal', false));
5573
                }
5574
5575
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5576
                    if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
5577
                        $return_message = self::delete_wiki();
5578
                        Display::addFlash(Display::return_message($return_message, 'confirmation', false));
5579
                        $this->redirectHome();
5580
                    }
5581
                }
5582
                break;
5583
            case 'searchpages':
5584
                self::getSearchPages($action);
5585
                break;
5586
            case 'links':
5587
                self::getLinks($page);
5588
                break;
5589
            case 'addnew':
5590 View Code Duplication
                if (api_get_session_id() != 0 && api_is_allowed_to_session_edit(false, true) == false) {
5591
                    api_not_allowed();
5592
                }
5593
                $groupInfo = GroupManager::get_group_properties(api_get_group_id());
5594
                echo '<div class="actions">'.get_lang('AddNew').'</div>';
5595
                echo '<br/>';
5596
                //first, check if page index was created. chektitle=false
5597
                if (self::checktitle('index')) {
5598
                    if (api_is_allowed_to_edit(false, true) ||
5599
                        api_is_platform_admin() ||
5600
                        GroupManager::is_user_in_group(api_get_user_id(), $groupInfo) ||
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group...ies(api_get_group_id()) on line 5593 can also be of type null; however, GroupManager::is_user_in_group() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
5601
                        api_is_allowed_in_course()
5602
                    ) {
5603
                        Display::addFlash(Display::return_message(get_lang('GoAndEditMainPage'), 'normal', false));
5604
                    } else {
5605
                        Display::addFlash(Display::return_message(get_lang('WikiStandBy'), 'normal', false));
5606
                    }
5607
                } elseif (self::check_addnewpagelock() == 0 && (api_is_allowed_to_edit(false, true) == false || api_is_platform_admin() == false)) {
5608
                    Display::addFlash(Display::return_message(get_lang('AddPagesLocked'), 'error', false));
5609
                } else {
5610
                    $groupInfo = GroupManager::get_group_properties(api_get_group_id());
5611
                    if (api_is_allowed_to_edit(false, true) ||
5612
                        api_is_platform_admin() ||
5613
                        GroupManager::is_user_in_group(api_get_user_id(), $groupInfo) ||
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group...ies(api_get_group_id()) on line 5610 can also be of type null; however, GroupManager::is_user_in_group() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
5614
                        $_GET['group_id'] == 0
5615
                    ) {
5616
                        self::display_new_wiki_form();
5617
                    } else {
5618
                        Display::addFlash(Display::return_message(get_lang('OnlyAddPagesGroupMembers'), 'normal', false));
5619
                    }
5620
                }
5621
                break;
5622
            case 'show':
5623
                self::display_wiki_entry($page);
5624
                break;
5625
            case 'showpage':
5626
                self::display_wiki_entry($page);
5627
                break;
5628
            case 'edit':
5629
                self::editPage();
5630
                break;
5631
            case 'history':
5632
                self::getHistory();
5633
                break;
5634
            case 'recentchanges':
5635
                self::recentChanges($page, $action);
5636
                break;
5637
            case 'allpages':
5638
                self::allPages($action);
5639
                break;
5640
            case 'discuss':
5641
                self::getDiscuss($page);
5642
                break;
5643
            case 'export_to_doc_file':
5644
                self::exportTo($_GET['id'], 'odt');
5645
                exit;
5646
                break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
5647
        }
5648
    }
5649
5650
    /**
5651
     * Redirect to home
5652
     */
5653
    public function redirectHome()
5654
    {
5655
        $redirectUrl = $this->url.'&action=showpage&title=index';
5656
        header('Location: '.$redirectUrl.'&'.api_get_cidreq());
5657
        exit;
5658
    }
5659
5660
    /**
5661
     * Export wiki content in a ODF
5662
     * @param int $id
5663
     * @param string int
5664
     * @return bool
5665
     */
5666
    public function exportTo($id, $format = 'doc')
5667
    {
5668
        $data = self::getWikiDataFromDb($id);
5669
5670
        if (isset($data['content']) && !empty($data['content'])) {
5671
            Export::htmlToOdt($data['content'], $data['reflink'], $format);
5672
        }
5673
5674
        return false;
5675
    }
5676
}
5677