Test Setup Failed
Push — master ( 4e700f...c7183e )
by Julito
63:12
created

Wiki::draw_date_picker()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 68
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 57
nc 2
nop 2
dl 0
loc 68
rs 9.2447
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(
105
            "/(\[\[|\]\])/",
106
            $input,
107
            -1,
108
            PREG_SPLIT_DELIM_CAPTURE
109
        );
110
        $all_links = array();
111
112
        foreach ($input_array as $key => $value) {
113
            if (isset($input_array[$key - 1]) && $input_array[$key - 1] == '[[' &&
114
                isset($input_array[$key + 1]) && $input_array[$key + 1] == ']]'
115
            ) {
116 View Code Duplication
                if (api_strpos($value, "|") !== false) {
117
                    $full_link_array = explode("|", $value);
118
                    $link = trim($full_link_array[0]);
119
                    $title = trim($full_link_array[1]);
120
                } else {
121
                    $link = trim($value);
122
                    $title = trim($value);
123
                }
124
                unset($input_array[$key - 1]);
125
                unset($input_array[$key + 1]);
126
                //replace blank spaces by _ within the links. But to remove links at the end add a blank space
127
                $all_links[] = Database::escape_string(
128
                        str_replace(' ', '_', $link)
129
                    ).' ';
130
            }
131
        }
132
        $output = implode($all_links);
133
134
        return $output;
135
    }
136
137
    /**
138
     * detect and add style to external links
139
     * @author Juan Carlos Raña Trabado
140
     **/
141
    public function detect_external_link($input)
142
    {
143
        $exlink = 'href=';
144
        $exlinkStyle = 'class="wiki_link_ext" href=';
145
        $output = str_replace($exlink, $exlinkStyle, $input);
146
147
        return $output;
148
    }
149
150
    /**
151
     * detect and add style to anchor links
152
     * @author Juan Carlos Raña Trabado
153
     **/
154
    public function detect_anchor_link($input)
155
    {
156
        $anchorlink = 'href="#';
157
        $anchorlinkStyle = 'class="wiki_anchor_link" href="#';
158
        $output = str_replace($anchorlink, $anchorlinkStyle, $input);
159
160
        return $output;
161
    }
162
163
    /**
164
     * detect and add style to mail links
165
     * author Juan Carlos Raña Trabado
166
     **/
167
    public function detect_mail_link($input)
168
    {
169
        $maillink = 'href="mailto';
170
        $maillinkStyle = 'class="wiki_mail_link" href="mailto';
171
        $output = str_replace($maillink, $maillinkStyle, $input);
172
173
        return $output;
174
    }
175
176
    /**
177
     * detect and add style to ftp links
178
     * @author Juan Carlos Raña Trabado
179
     **/
180
    public function detect_ftp_link($input)
181
    {
182
        $ftplink = 'href="ftp';
183
        $ftplinkStyle = 'class="wiki_ftp_link" href="ftp';
184
        $output = str_replace($ftplink, $ftplinkStyle, $input);
185
186
        return $output;
187
    }
188
189
    /**
190
     * detect and add style to news links
191
     * @author Juan Carlos Raña Trabado
192
     **/
193
    public function detect_news_link($input)
194
    {
195
        $newslink = 'href="news';
196
        $newslinkStyle = 'class="wiki_news_link" href="news';
197
        $output = str_replace($newslink, $newslinkStyle, $input);
198
199
        return $output;
200
    }
201
202
    /**
203
     * detect and add style to irc links
204
     * @author Juan Carlos Raña Trabado
205
     **/
206
    public function detect_irc_link($input)
207
    {
208
        $irclink = 'href="irc';
209
        $irclinkStyle = 'class="wiki_irc_link" href="irc';
210
        $output = str_replace($irclink, $irclinkStyle, $input);
211
212
        return $output;
213
    }
214
215
    /**
216
     * This function allows users to have [link to a title]-style links like in most regular wikis.
217
     * It is true that the adding of links is probably the most anoying part of Wiki for the people
218
     * who know something about the wiki syntax.
219
     * @author Patrick Cool <[email protected]>, Ghent University
220
     * Improvements [[]] and [[ | ]]by Juan Carlos Raña
221
     * Improvements internal wiki style and mark group by Juan Carlos Raña
222
     **/
223
    public function make_wiki_link_clickable($input)
224
    {
225
        $groupId = api_get_group_id();
226
        //now doubles brackets
227
        $input_array = preg_split(
228
            "/(\[\[|\]\])/",
229
            $input,
230
            -1,
231
            PREG_SPLIT_DELIM_CAPTURE
232
        );
233
234
        foreach ($input_array as $key => $value) {
235
            //now doubles brackets
236
            if (isset($input_array[$key - 1]) &&
237
                $input_array[$key - 1] == '[[' && $input_array[$key + 1] == ']]'
238
            ) {
239
                // now full wikilink
240 View Code Duplication
                if (api_strpos($value, "|") !== false) {
241
                    $full_link_array = explode("|", $value);
242
                    $link = trim(strip_tags($full_link_array[0]));
243
                    $title = trim($full_link_array[1]);
244
                } else {
245
                    $link = trim(strip_tags($value));
246
                    $title = trim($value);
247
                }
248
249
                //if wikilink is homepage
250
                if ($link == 'index') {
251
                    $title = get_lang('DefaultTitle');
252
                }
253
                if ($link == get_lang('DefaultTitle')) {
254
                    $link = 'index';
255
                }
256
257
                // 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
258
                if (self::checktitle(strtolower(str_replace(' ', '_', $link)))) {
259
                    $link = api_html_entity_decode($link);
260
                    $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>';
261
                } else {
262
                    $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>';
263
                }
264
                unset($input_array[$key - 1]);
265
                unset($input_array[$key + 1]);
266
            }
267
        }
268
        $output = implode('', $input_array);
269
270
        return $output;
271
    }
272
273
    /**
274
     * This function saves a change in a wiki page
275
     * @author Patrick Cool <[email protected]>, Ghent University
276
     * @param array $values
277
     * @return language string saying that the changes are stored
278
     **/
279
    public function save_wiki($values)
280
    {
281
        $tbl_wiki = $this->tbl_wiki;
282
        $tbl_wiki_conf = $this->tbl_wiki_conf;
283
284
        $_course = $this->courseInfo;
285
        $time = api_get_utc_datetime();
286
        $session_id = api_get_session_id();
287
        $groupId = api_get_group_id();
288
        $userId = api_get_user_id();
289
        $groupInfo = GroupManager::get_group_properties($groupId);
290
        $course_id = api_get_course_int_id();
291
292
        $_clean = array(
293
            'task' => '',
294
            'feedback1' => '',
295
            'feedback2' => '',
296
            'feedback3' => '',
297
            'fprogress1' => '',
298
            'fprogress2' => '',
299
            'fprogress3' => '',
300
            'max_text' => 0,
301
            'max_version' => 0,
302
            'delayedsubmit' => '',
303
            'assignment' => 0
304
        );
305
306
        $pageId = intval($values['page_id']);
307
308
        // NOTE: visibility, visibility_disc and ratinglock_disc changes
309
        // are not made here, but through the interce buttons
310
311
        // cleaning the variables
312
        if (api_get_setting('htmlpurifier_wiki') == 'true') {
313
            //$purifier = new HTMLPurifier();
314
            $values['content'] = Security::remove_XSS($values['content']);
315
        }
316
        $version = intval($values['version']) + 1;
317
        $linkTo = self::links_to($values['content']); //and check links content
318
319
        //cleaning config variables
320
        if (!empty($values['task'])) {
321
            $_clean['task'] = $values['task'];
322
        }
323
324
        if (!empty($values['feedback1']) ||
325
            !empty($values['feedback2']) ||
326
            !empty($values['feedback3'])
327
        ) {
328
            $_clean['feedback1'] = $values['feedback1'];
329
            $_clean['feedback2'] = $values['feedback2'];
330
            $_clean['feedback3'] = $values['feedback3'];
331
            $_clean['fprogress1'] = $values['fprogress1'];
332
            $_clean['fprogress2'] = $values['fprogress2'];
333
            $_clean['fprogress3'] = $values['fprogress3'];
334
        }
335
336 View Code Duplication
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
337
            $_clean['startdate_assig'] = $values['startdate_assig'];
338
        } else {
339
            $_clean['startdate_assig'] = null;
340
        }
341
342 View Code Duplication
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
343
            $_clean['enddate_assig'] = $values['enddate_assig'];
344
        } else {
345
            $_clean['enddate_assig'] = null;
346
        }
347
348
        if (isset($values['delayedsubmit'])) {
349
            $_clean['delayedsubmit'] = $values['delayedsubmit'];
350
        }
351
352
        if (!empty($values['max_text']) || !empty($values['max_version'])) {
353
            $_clean['max_text'] = $values['max_text'];
354
            $_clean['max_version'] = $values['max_version'];
355
        }
356
357
        $values['assignment'] = isset($values['assignment']) ? $values['assignment'] : 0;
358
        $values['page_id'] = isset($values['page_id']) ? $values['page_id'] : 0;
359
360
        $params = [
361
            'c_id' => $course_id,
362
            'addlock' => 1,
363
            'visibility' => 1,
364
            'visibility_disc' => 1,
365
            'addlock_disc' => 1,
366
            'ratinglock_disc' => 1,
367
            'page_id' => $pageId,
368
            'reflink' => trim($values['reflink']),
369
            'title' => trim($values['title']),
370
            'content' => $values['content'],
371
            'user_id' => $userId,
372
            'group_id' => $groupId,
373
            'dtime' => $time,
374
            'assignment' => $values['assignment'],
375
            'comment' => $values['comment'],
376
            'progress' => $values['progress'],
377
            'version' => $version,
378
            'linksto' => $linkTo,
379
            'user_ip' => $_SERVER['REMOTE_ADDR'],
380
            'session_id' => $session_id,
381
            'page_id' => $values['page_id'],
382
            'editlock' => 0,
383
            'is_editing' => 0,
384
            'time_edit' => $time,
385
            'tag' => ''
386
        ];
387
388
        $id = Database::insert($tbl_wiki, $params);
389
390
        if ($id > 0) {
391
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
392
            Database::query($sql);
393
394
            // insert into item_property
395
            api_item_property_update(
396
                $_course,
397
                TOOL_WIKI,
398
                $id,
399
                'WikiAdded',
400
                $userId,
401
                $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 289 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...
402
            );
403
404 View Code Duplication
            if ($values['page_id'] == 0) {
405
                $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
406
                        WHERE c_id = '.$course_id.' AND iid ="'.$id.'"';
407
                Database::query($sql);
408
            }
409
        }
410
411
        // Update wiki config
412
        if ($values['reflink'] == 'index' && $version == 1) {
413
            $params = [
414
                'c_id' => $course_id,
415
                'page_id' => $id,
416
                'task' => $_clean['task'],
417
                'feedback1' => $_clean['feedback1'],
418
                'feedback2' => $_clean['feedback2'],
419
                'feedback3' => $_clean['feedback3'],
420
                'fprogress1' => $_clean['fprogress1'],
421
                'fprogress2' => $_clean['fprogress2'],
422
                'fprogress3' => $_clean['fprogress3'],
423
                'max_text' => intval($_clean['max_text']),
424
                'max_version' => intval($_clean['max_version']),
425
                'startdate_assig' => $_clean['startdate_assig'],
426
                'enddate_assig' => $_clean['enddate_assig'],
427
                'delayedsubmit' => $_clean['delayedsubmit']
428
            ];
429
            Database::insert($tbl_wiki_conf, $params);
430
        } else {
431
            $params = [
432
                'task' => $_clean['task'],
433
                'feedback1' => $_clean['feedback1'],
434
                'feedback2' => $_clean['feedback2'],
435
                'feedback3' => $_clean['feedback3'],
436
                'fprogress1' => $_clean['fprogress1'],
437
                'fprogress2' => $_clean['fprogress2'],
438
                'fprogress3' => $_clean['fprogress3'],
439
                'max_text' => intval($_clean['max_text']),
440
                'max_version' => intval($_clean['max_version']),
441
                'startdate_assig' => $_clean['startdate_assig'],
442
                'enddate_assig' => $_clean['enddate_assig'],
443
                'delayedsubmit' => $_clean['delayedsubmit']
444
            ];
445
            Database::update(
446
                $tbl_wiki_conf,
447
                $params,
448
                ['page_id = ? AND c_id = ?' => [$pageId, $course_id]]
449
            );
450
        }
451
452
        api_item_property_update(
453
            $_course,
454
            'wiki',
455
            $id,
456
            'WikiAdded',
457
            $userId,
458
            $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 289 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...
459
        );
460
        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 285 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...
461
        $this->setWikiData($id);
0 ignored issues
show
Bug introduced by
It seems like $id defined by \Database::insert($tbl_wiki, $params) on line 388 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...
462
463
        return get_lang('Saved');
464
    }
465
466
    /**
467
     * This function restore a wikipage
468
     * @author Juan Carlos Raña <[email protected]>
469
     * @return string Message of success (to be printed on screen)
470
     **/
471
    public function restore_wikipage(
472
        $r_page_id,
473
        $r_reflink,
474
        $r_title,
475
        $r_content,
476
        $r_group_id,
477
        $r_assignment,
478
        $r_progress,
479
        $c_version,
480
        $r_version,
481
        $r_linksto
482
    ) {
483
        $tbl_wiki = $this->tbl_wiki;
484
        $_course = $this->courseInfo;
485
        $r_user_id = api_get_user_id();
486
        $r_dtime = api_get_utc_datetime();
487
        $r_version = $r_version + 1;
488
        $r_comment = get_lang('RestoredFromVersion').': '.$c_version;
489
        $session_id = api_get_session_id();
490
        $course_id = api_get_course_int_id();
491
        $groupInfo = GroupManager::get_group_properties($r_group_id);
492
493
        $params = [
494
            'c_id' => $course_id,
495
            'page_id' => $r_page_id,
496
            'reflink' => $r_reflink,
497
            'title' => $r_title,
498
            'content' => $r_content,
499
            'user_id' => $r_user_id,
500
            'group_id' => $r_group_id,
501
            'dtime' => $r_dtime,
502
            'assignment' => $r_assignment,
503
            'comment' => $r_comment,
504
            'progress' => $r_progress,
505
            'version' => $r_version,
506
            'linksto' => $r_linksto,
507
            'user_ip' => $_SERVER['REMOTE_ADDR'],
508
            'session_id' => $session_id,
509
        ];
510
        $id = Database::insert($tbl_wiki, $params);
511
512 View Code Duplication
        if ($id) {
513
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
514
            Database::query($sql);
515
516
            api_item_property_update(
517
                $_course,
518
                'wiki',
519
                $id,
520
                'WikiAdded',
521
                api_get_user_id(),
522
                $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($r_group_id) on line 491 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...
523
            );
524
            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 486 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...
525
        }
526
527
        return get_lang('PageRestored');
528
    }
529
530
    /**
531
     * This function delete a wiki
532
     * @author Juan Carlos Raña <[email protected]>
533
     * @return   string  Message of success (to be printed)
534
     **/
535
    public function delete_wiki()
536
    {
537
        $tbl_wiki = $this->tbl_wiki;
538
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
539
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
540
        $tbl_wiki_conf = $this->tbl_wiki_conf;
541
        $conditionSession = $this->condition_session;
542
        $groupFilter = $this->groupfilter;
543
        $course_id = $this->course_id;
544
545
        $sql = "SELECT page_id FROM $tbl_wiki
546
                WHERE c_id = $course_id AND $groupFilter $conditionSession
547
                ORDER BY id DESC";
548
549
        $result = Database::query($sql);
550
        $pageList = Database::store_result($result);
551
        if ($pageList) {
552
            foreach ($pageList as $pageData) {
553
                $pageId = $pageData['page_id'];
554
                $sql = "DELETE FROM $tbl_wiki_conf
555
                        WHERE c_id = $course_id AND page_id = $pageId";
556
                Database::query($sql);
557
558
                $sql = "DELETE FROM $tbl_wiki_discuss
559
                        WHERE c_id = $course_id AND publication_id = $pageId";
560
                Database::query($sql);
561
            }
562
        }
563
564
        $sql = "DELETE FROM $tbl_wiki_mailcue
565
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
566
        Database::query($sql);
567
568
        $sql = "DELETE FROM $tbl_wiki
569
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
570
        Database::query($sql);
571
572
        return get_lang('WikiDeleted');
573
    }
574
575
    /**
576
     * This function saves a new wiki page.
577
     * @author Patrick Cool <[email protected]>, Ghent University
578
     * @todo consider merging this with the function save_wiki into one single function.
579
     * @return string Message of success
580
     **/
581
    public function save_new_wiki($values)
582
    {
583
        $tbl_wiki = $this->tbl_wiki;
584
        $tbl_wiki_conf = $this->tbl_wiki_conf;
585
        $assig_user_id = $this->assig_user_id;
586
        $_clean = array();
587
588
        // cleaning the variables
589
        $_clean['assignment'] = '';
590
        if (isset($values['assignment'])) {
591
            $_clean['assignment'] = $values['assignment'];
592
        }
593
594
        // session_id
595
        $session_id = api_get_session_id();
596
        // Unlike ordinary pages of pages of assignments.
597
        // Allow create a ordinary page although there is a assignment with the same name
598
        if ($_clean['assignment'] == 2 || $_clean['assignment'] == 1) {
599
            $page = str_replace(
600
                ' ',
601
                '_',
602
                $values['title']."_uass".$assig_user_id
603
            );
604
        } else {
605
            $page = str_replace(' ', '_', $values['title']);
606
        }
607
        $_clean['reflink'] = $page;
608
        $_clean['title'] = trim($values['title']);
609
        $_clean['content'] = $values['content'];
610
611
        if (api_get_setting('htmlpurifier_wiki') === 'true') {
612
            $purifier = new HTMLPurifier();
613
            $_clean['content'] = $purifier->purify($_clean['content']);
614
        }
615
616
        //re-check after strip_tags if the title is empty
617
        if (empty($_clean['title']) || empty($_clean['reflink'])) {
618
            return false;
619
        }
620
621
        if ($_clean['assignment'] == 2) {
622
            //config by default for individual assignment (students)
623
            //Identifies the user as a creator, not the teacher who created
624
            $_clean['user_id'] = intval($assig_user_id);
625
            $_clean['visibility'] = 0;
626
            $_clean['visibility_disc'] = 0;
627
            $_clean['ratinglock_disc'] = 0;
628
        } else {
629
            $_clean['user_id'] = api_get_user_id();
630
            $_clean['visibility'] = 1;
631
            $_clean['visibility_disc'] = 1;
632
            $_clean['ratinglock_disc'] = 1;
633
        }
634
635
        $_clean['comment'] = $values['comment'];
636
        $_clean['progress'] = $values['progress'];
637
        $_clean['version'] = 1;
638
639
        $groupId = api_get_group_id();
640
        $groupInfo = GroupManager::get_group_properties($groupId);
641
642
        //check wikilinks
643
        $_clean['linksto'] = self::links_to($_clean['content']);
644
645
        // cleaning config variables
646
        $_clean['task'] = isset($values['task']) ? $values['task'] : '';
647
        $_clean['feedback1'] = isset($values['feedback1']) ? $values['feedback1'] : '';
648
        $_clean['feedback2'] = isset($values['feedback2']) ? $values['feedback2'] : '';
649
        $_clean['feedback3'] = isset($values['feedback3']) ? $values['feedback3'] : '';
650
        $_clean['fprogress1'] = isset($values['fprogress1']) ? $values['fprogress1'] : '';
651
        $_clean['fprogress2'] = isset($values['fprogress2']) ? $values['fprogress2'] : '';
652
        $_clean['fprogress3'] = isset($values['fprogress3']) ? $values['fprogress3'] : '';
653
654 View Code Duplication
        if (isset($values['initstartdate']) && $values['initstartdate'] == 1) {
655
            $_clean['startdate_assig'] = $values['startdate_assig'];
656
        } else {
657
            $_clean['startdate_assig'] = null;
658
        }
659
660 View Code Duplication
        if (isset($values['initenddate']) && $values['initenddate'] == 1) {
661
            $_clean['enddate_assig'] = $values['enddate_assig'];
662
        } else {
663
            $_clean['enddate_assig'] = null;
664
        }
665
666
        $_clean['delayedsubmit'] = isset($values['delayedsubmit']) ? $values['delayedsubmit'] : '';
667
        $_clean['max_text'] = isset($values['max_text']) ? $values['max_text'] : '';
668
        $_clean['max_version'] = isset($values['max_version']) ? $values['max_version'] : '';
669
670
        $course_id = api_get_course_int_id();
671
672
        // Filter no _uass
673
        if (api_strtoupper(trim($values['title'])) === 'INDEX') {
674
            Display::addFlash(
675
                Display::return_message(
676
                    get_lang('GoAndEditMainPage'),
677
                    'warning',
678
                    false
679
                )
680
            );
681
        } else {
682
            $var = $_clean['reflink'];
683
            $group_id = intval($_GET['group_id']);
684
            if (!self::checktitle($var)) {
685
                return get_lang('WikiPageTitleExist').
686
                    '<a href="index.php?action=edit&amp;title='.$var.'&group_id='.$group_id.'">'.
687
                    $values['title'].'</a>';
688
            } else {
689
                $dtime = api_get_utc_datetime();
690
691
                $params = [
692
                    'c_id' => $course_id,
693
                    'reflink' => $_clean['reflink'],
694
                    'title' => $_clean['title'],
695
                    'content' => $_clean['content'],
696
                    'user_id' => $_clean['user_id'],
697
                    'group_id' => $groupId,
698
                    'dtime' => $dtime,
699
                    'visibility' => $_clean['visibility'],
700
                    'visibility_disc' => $_clean['visibility_disc'],
701
                    'ratinglock_disc' => $_clean['ratinglock_disc'],
702
                    'assignment' => $_clean['assignment'],
703
                    'comment' => $_clean['comment'],
704
                    'progress' => $_clean['progress'],
705
                    'version' => $_clean['version'],
706
                    'linksto' => $_clean['linksto'],
707
                    'user_ip' => $_SERVER['REMOTE_ADDR'],
708
                    'session_id' => $session_id,
709
                    'addlock_disc' => 1
710
                ];
711
                $id = Database::insert($tbl_wiki, $params);
712
                if ($id > 0) {
713
                    $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
714
                    Database::query($sql);
715
716
                    //insert into item_property
717
                    api_item_property_update(
718
                        api_get_course_info(),
719
                        TOOL_WIKI,
720
                        $id,
721
                        'WikiAdded',
722
                        api_get_user_id(),
723
                        $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 640 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...
724
                    );
725
726
                    $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
727
                            WHERE c_id = '.$course_id.' AND id = "'.$id.'"';
728
                    Database::query($sql);
729
730
                    // insert wiki config
731
                    $params = [
732
                        'c_id' => $course_id,
733
                        'page_id' => $id,
734
                        'task' => $_clean['task'],
735
                        'feedback1' => $_clean['feedback1'],
736
                        'feedback2' => $_clean['feedback2'],
737
                        'feedback3' => $_clean['feedback3'],
738
                        'fprogress1' => $_clean['fprogress1'],
739
                        'fprogress2' => $_clean['fprogress2'],
740
                        'fprogress3' => $_clean['fprogress3'],
741
                        'max_text' => $_clean['max_text'],
742
                        'max_version' => $_clean['max_version'],
743
                        'startdate_assig' => $_clean['startdate_assig'],
744
                        'enddate_assig' => $_clean['enddate_assig'],
745
                        'delayedsubmit' => $_clean['delayedsubmit']
746
                    ];
747
748
                    Database::insert($tbl_wiki_conf, $params);
749
750
                    $this->setWikiData($id);
0 ignored issues
show
Bug introduced by
It seems like $id defined by \Database::insert($tbl_wiki, $params) on line 711 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...
751
                    self::check_emailcue(0, 'A');
752
                    return get_lang('NewWikiSaved');
753
                }
754
            }
755
        }
756
    }
757
758
    /**
759
     * @param FormValidator $form
760
     * @param array $row
761
     */
762
    public function setForm($form, $row = array())
763
    {
764
        $toolBar = api_is_allowed_to_edit(null, true)
765
            ? array(
766
                'ToolbarSet' => 'Wiki',
767
                'Width' => '100%',
768
                'Height' => '400'
769
            )
770
            : array(
771
                'ToolbarSet' => 'WikiStudent',
772
                'Width' => '100%',
773
                'Height' => '400',
774
                'UserStatus' => 'student'
775
            );
776
777
        $form->addHtmlEditor(
778
            'content',
779
            get_lang('Content'),
780
            false,
781
            false,
782
            $toolBar
783
        );
784
        //$content
785
        $form->addElement('text', 'comment', get_lang('Comments'));
786
        $progress = array('', 10, 20, 30, 40, 50, 60, 70, 80, 90, 100);
787
788
        $form->addElement(
789
            'select',
790
            'progress',
791
            get_lang('Progress'),
792
            $progress
793
        );
794
795
        if ((api_is_allowed_to_edit(false, true) ||
796
                api_is_platform_admin()) &&
797
            isset($row['reflink']) && $row['reflink'] != 'index'
798
        ) {
799
            $form->addElement(
800
                'advanced_settings',
801
                'advanced_params',
802
                get_lang('AdvancedParameters')
803
            );
804
            $form->addElement(
805
                'html',
806
                '<div id="advanced_params_options" style="display:none">'
807
            );
808
809
            $form->addHtmlEditor(
810
                'task',
811
                get_lang('DescriptionOfTheTask'),
812
                false,
813
                false,
814
                array(
815
                    'ToolbarSet' => 'wiki_task',
816
                    'Width' => '100%',
817
                    'Height' => '200',
818
                )
819
            );
820
821
            $form->addElement('label', null, get_lang('AddFeedback'));
822
            $form->addElement('textarea', 'feedback1', get_lang('Feedback1'));
823
            $form->addElement(
824
                'select',
825
                'fprogress1',
826
                get_lang('FProgress'),
827
                $progress
828
            );
829
830
            $form->addElement('textarea', 'feedback2', get_lang('Feedback2'));
831
            $form->addElement(
832
                'select',
833
                'fprogress2',
834
                get_lang('FProgress'),
835
                $progress
836
            );
837
838
            $form->addElement('textarea', 'feedback3', get_lang('Feedback3'));
839
            $form->addElement(
840
                'select',
841
                'fprogress3',
842
                get_lang('FProgress'),
843
                $progress
844
            );
845
846
            $form->addElement(
847
                'checkbox',
848
                'initstartdate',
849
                null,
850
                get_lang('StartDate'),
851
                array('id' => 'start_date_toggle')
852
            );
853
854
            $style = "display:block";
855
            $row['initstartdate'] = 1;
856
            if (empty($row['startdate_assig'])) {
857
                $style = "display:none";
858
                $row['initstartdate'] = null;
859
            }
860
861
            $form->addElement(
862
                'html',
863
                '<div id="start_date" style="'.$style.'">'
864
            );
865
            $form->addDatePicker('startdate_assig', '');
866
            $form->addElement('html', '</div>');
867
            $form->addElement(
868
                'checkbox',
869
                'initenddate',
870
                null,
871
                get_lang('EndDate'),
872
                array('id' => 'end_date_toggle')
873
            );
874
875
            $style = "display:block";
876
            $row['initenddate'] = 1;
877
            if (empty($row['enddate_assig'])) {
878
                $style = "display:none";
879
                $row['initenddate'] = null;
880
            }
881
882
            $form->addElement('html', '<div id="end_date" style="'.$style.'">');
883
            $form->addDatePicker('enddate_assig', '');
884
            $form->addElement('html', '</div>');
885
            $form->addElement(
886
                'checkbox',
887
                'delayedsubmit',
888
                null,
889
                get_lang('AllowLaterSends')
890
            );
891
            $form->addElement('text', 'max_text', get_lang('NMaxWords'));
892
            $form->addElement('text', 'max_version', get_lang('NMaxVersion'));
893
            $form->addElement(
894
                'checkbox',
895
                'assignment',
896
                null,
897
                get_lang('CreateAssignmentPage')
898
            );
899
            $form->addElement('html', '</div>');
900
        }
901
902
        $form->addElement('hidden', 'page_id');
903
        $form->addElement('hidden', 'reflink');
904
        $form->addElement('hidden', 'version');
905
        $form->addElement('hidden', 'wpost_id', api_get_unique_id());
906
    }
907
908
    /**
909
     * This function displays the form for adding a new wiki page.
910
     * @author Patrick Cool <[email protected]>, Ghent University
911
     * @return string html code
912
     **/
913
    public function display_new_wiki_form()
914
    {
915
        $url = api_get_self().'?'.api_get_cidreq(
916
            ).'&action=addnew&group_id='.api_get_group_id();
917
        $form = new FormValidator('wiki_new', 'post', $url);
918
        $form->addElement('text', 'title', get_lang('Title'));
919
        $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
920
        self::setForm($form);
921
        $title = isset($_GET['title']) ? Security::remove_XSS(
922
            $_GET['title']
923
        ) : '';
924
        $form->setDefaults(['title' => $title]);
925
        $form->addElement('button', 'SaveWikiNew', get_lang('Save'));
926
        $form->display();
927
928
        if ($form->validate()) {
929
            $values = $form->exportValues();
930
            if (isset($values['startdate_assig']) &&
931
                isset($values['enddate_assig']) &&
932
                strtotime($values['startdate_assig']) > strtotime(
933
                    $values['enddate_assig']
934
                )
935
            ) {
936
                Display::addFlash(
937
                    Display::return_message(
938
                        get_lang("EndDateCannotBeBeforeTheStartDate"),
939
                        'error',
940
                        false
941
                    )
942
                );
943
            } 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...
944
                //double post
945
            } else {
946
                if (isset($values['assignment']) && $values['assignment'] == 1) {
947
                    self::auto_add_page_users($values);
948
                }
949
950
                $return_message = self::save_new_wiki($values);
951
952 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...
953
                    Display::addFlash(
954
                        Display::return_message(
955
                            get_lang('NoWikiPageTitle'),
956
                            'error',
957
                            false
958
                        )
959
                    );
960
                } else {
961
                    Display::addFlash(
962
                        Display::return_message(
963
                            $return_message,
964
                            'confirmation',
965
                            false
966
                        )
967
                    );
968
                }
969
970
                $wikiData = self::getWikiData();
971
                $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq(
972
                    );
973
                header('Location: '.$redirectUrl);
974
                exit;
975
            }
976
        }
977
    }
978
979
    /**
980
     * This function displays a wiki entry
981
     * @author Patrick Cool <[email protected]>, Ghent University
982
     * @author Juan Carlos Raña Trabado
983
     * @param string $newtitle
984
     * @return string html code
985
     **/
986
    public function display_wiki_entry($newtitle)
987
    {
988
        $tbl_wiki = $this->tbl_wiki;
989
        $tbl_wiki_conf = $this->tbl_wiki_conf;
990
        $condition_session = $this->condition_session;
991
        $groupfilter = $this->groupfilter;
992
        $page = $this->page;
993
994
        $session_id = api_get_session_id();
995
        $course_id = api_get_course_int_id();
996
997
        if ($newtitle) {
998
            $pageMIX = $newtitle; //display the page after it is created
999
        } else {
1000
            $pageMIX = $page; //display current page
1001
        }
1002
1003
        $filter = null;
1004
        if (isset($_GET['view']) && $_GET['view']) {
1005
            $_clean['view'] = Database::escape_string($_GET['view']);
1006
            $filter = ' AND w.id="'.$_clean['view'].'"';
1007
        }
1008
1009
        // First, check page visibility in the first page version
1010
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1011
                WHERE
1012
                    c_id = '.$course_id.' AND
1013
                    reflink="'.Database::escape_string($pageMIX).'" AND
1014
                   '.$groupfilter.$condition_session.'
1015
                ORDER BY id ASC';
1016
        $result = Database::query($sql);
1017
        $row = Database::fetch_array($result, 'ASSOC');
1018
1019
        $KeyVisibility = $row['visibility'];
1020
1021
        // second, show the last version
1022
        $sql = 'SELECT * FROM '.$tbl_wiki.' w
1023
                INNER JOIN '.$tbl_wiki_conf.' wc
1024
                ON (wc.page_id = w.page_id AND wc.c_id = w.c_id)
1025
                WHERE
1026
                    w.c_id 		  = '.$course_id.' AND
1027
                    w.reflink	  = "'.Database::escape_string($pageMIX).'" AND
1028
                    w.session_id  = '.$session_id.' AND
1029
                    w.'.$groupfilter.'  '.$filter.'
1030
                ORDER BY id DESC';
1031
1032
        $result = Database::query($sql);
1033
        // we do not need a while loop since we are always displaying the last version
1034
        $row = Database::fetch_array($result, 'ASSOC');
1035
1036
        //log users access to wiki (page_id)
1037
        if (!empty($row['page_id'])) {
1038
            Event::addEvent(LOG_WIKI_ACCESS, LOG_WIKI_PAGE_ID, $row['page_id']);
1039
        }
1040
        //update visits
1041 View Code Duplication
        if ($row['id']) {
1042
            $sql = 'UPDATE '.$tbl_wiki.' SET hits=(hits+1)
1043
                    WHERE c_id = '.$course_id.' AND id='.$row['id'].'';
1044
            Database::query($sql);
1045
        }
1046
1047
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1048
1049
        // if both are empty and we are displaying the index page then we display the default text.
1050
        if ($row['content'] == '' && $row['title'] == '' && $page == 'index') {
1051
            if (api_is_allowed_to_edit(false, true) ||
1052
                api_is_platform_admin() ||
1053
                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 1047 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...
1054
                api_is_allowed_in_course()
1055
            ) {
1056
                //Table structure for better export to pdf
1057
                $default_table_for_content_Start = '<table align="center" border="0"><tr><td align="center">';
1058
                $default_table_for_content_End = '</td></tr></table>';
1059
                $content = $default_table_for_content_Start.
1060
                    sprintf(
1061
                        get_lang('DefaultContent'),
1062
                        api_get_path(WEB_IMG_PATH)
1063
                    ).
1064
                    $default_table_for_content_End;
1065
                $title = get_lang('DefaultTitle');
1066
            } else {
1067
                return Display::addFlash(
1068
                    Display::return_message(
1069
                        get_lang('WikiStandBy'),
1070
                        'normal',
1071
                        false
1072
                    )
1073
                );
1074
            }
1075
        } else {
1076
            $content = Security::remove_XSS($row['content']);
1077
            $title = Security::remove_XSS($row['title']);
1078
        }
1079
1080
        //assignment mode: identify page type
1081
        $icon_assignment = null;
1082 View Code Duplication
        if ($row['assignment'] == 1) {
1083
            $icon_assignment = Display::return_icon(
1084
                'wiki_assignment.png',
1085
                get_lang('AssignmentDescExtra'),
1086
                '',
1087
                ICON_SIZE_SMALL
1088
            );
1089
        } elseif ($row['assignment'] == 2) {
1090
            $icon_assignment = Display::return_icon(
1091
                'wiki_work.png',
1092
                get_lang('AssignmentWork'),
1093
                '',
1094
                ICON_SIZE_SMALL
1095
            );
1096
        }
1097
1098
        // task mode
1099
        $icon_task = null;
1100 View Code Duplication
        if (!empty($row['task'])) {
1101
            $icon_task = Display::return_icon(
1102
                'wiki_task.png',
1103
                get_lang('StandardTask'),
1104
                '',
1105
                ICON_SIZE_SMALL
1106
            );
1107
        }
1108
1109
        // Show page. Show page to all users if isn't hide page. Mode assignments: if student is the author, can view
1110
        if ($KeyVisibility == "1" ||
1111
            api_is_allowed_to_edit(false, true) ||
1112
            api_is_platform_admin() ||
1113
            ($row['assignment'] == 2 && $KeyVisibility == "0" && (api_get_user_id() == $row['user_id'])) ||
1114
            api_is_allowed_in_course()
1115
        ) {
1116
            $actionsLeft = '';
1117
            // menu edit page
1118
            $editLink = '<a href="index.php?'.api_get_cidreq().'&action=edit&title='.api_htmlentities(urlencode($page)).'"'.self::is_active_navigation_tab('edit').'>'.
1119
                Display::return_icon('edit.png', get_lang('EditThisPage'), '', ICON_SIZE_MEDIUM).'</a>';
1120
1121
            if (api_is_allowed_to_edit(false, true)) {
1122
                $actionsLeft .= $editLink;
1123
            } else {
1124
                if ((api_is_allowed_in_course() ||
1125
                    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 1047 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...
1126
                ) {
1127
                    $actionsLeft .= $editLink;
1128
                } else {
1129
                    $actionsLeft .= '';
1130
                }
1131
            }
1132
1133
            $actionsRight = '';
1134
1135
            $protect_page = null;
1136
            $lock_unlock_protect = null;
1137
            // page action: protecting (locking) the page
1138 View Code Duplication
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1139
                if (self::check_protect_page() == 1) {
1140
                    $protect_page = Display::return_icon('lock.png', get_lang('PageLockedExtra'), '', ICON_SIZE_MEDIUM);
1141
                    $lock_unlock_protect = 'unlock';
1142
                } else {
1143
                    $protect_page = Display::return_icon('unlock.png', get_lang('PageUnlockedExtra'), '', ICON_SIZE_MEDIUM);
1144
                    $lock_unlock_protect = 'lock';
1145
                }
1146
            }
1147
1148 View Code Duplication
            if ($row['id']) {
1149
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_protect.'&title='.api_htmlentities(urlencode($page)).'">'.
1150
                        $protect_page.'</a>';
1151
            }
1152
1153
            $visibility_page = null;
1154
            $lock_unlock_visibility = null;
1155
            //page action: visibility
1156 View Code Duplication
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1157
                if (self::check_visibility_page() == 1) {
1158
                    $visibility_page = Display::return_icon(
1159
                        'visible.png',
1160
                        get_lang('ShowPageExtra'),
1161
                        '',
1162
                        ICON_SIZE_MEDIUM
1163
                    );
1164
                    $lock_unlock_visibility = 'invisible';
1165
1166
                } else {
1167
                    $visibility_page = Display::return_icon(
1168
                        'invisible.png',
1169
                        get_lang('HidePageExtra'),
1170
                        '',
1171
                        ICON_SIZE_MEDIUM
1172
                    );
1173
                    $lock_unlock_visibility = 'visible';
1174
                }
1175
            }
1176
1177 View Code Duplication
            if ($row['id']) {
1178
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_visibility.'&title='.api_htmlentities(urlencode($page)).'">'.
1179
                    $visibility_page.'</a>';
1180
            }
1181
1182
            //page action: notification
1183 View Code Duplication
            if (api_is_allowed_to_session_edit()) {
1184
                if (self::check_notify_page($page) == 1) {
1185
                    $notify_page = Display::return_icon('messagebox_info.png', get_lang('NotifyByEmail'), '', ICON_SIZE_MEDIUM);
1186
                    $lock_unlock_notify_page = 'unlocknotify';
1187
                } else {
1188
                    $notify_page = Display::return_icon('mail.png', get_lang('CancelNotifyByEmail'), '', ICON_SIZE_MEDIUM);
1189
                    $lock_unlock_notify_page = 'locknotify';
1190
                }
1191
            }
1192
1193
            // Only available if row['id'] is set
1194
            if ($row['id']) {
1195 View Code Duplication
                if (api_is_allowed_to_session_edit(false, true) && api_is_allowed_to_edit() ||
1196
                    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 1047 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...
1197
                ) {
1198
                    // menu discuss page
1199
                    $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=discuss&title='.api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('discuss').'>'.
1200
                        Display::return_icon('discuss.png', get_lang('DiscussThisPage'), '', ICON_SIZE_MEDIUM).'</a>';
1201
                }
1202
1203
                //menu history
1204
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=history&title='.api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('history').'>'.
1205
                    Display::return_icon('history.png', get_lang('ShowPageHistory'), '', ICON_SIZE_MEDIUM).'</a>';
1206
                //menu linkspages
1207
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'action=links&title='.api_htmlentities(urlencode($page)).'" '.self::is_active_navigation_tab('links').'>'.
1208
                    Display::return_icon('what_link_here.png', get_lang('LinksPages'), '', ICON_SIZE_MEDIUM).'</a>';
1209
1210
                //menu delete wikipage
1211 View Code Duplication
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1212
                    $actionsRight .= '<a href="index.php?action=delete&'.api_get_cidreq().'&title='.api_htmlentities(urlencode($page)).'"'.self::is_active_navigation_tab('delete').'>'.
1213
                        Display::return_icon('delete.png', get_lang('DeleteThisPage'), '', ICON_SIZE_MEDIUM).'</a>';
1214
                }
1215
1216
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_notify_page.'&title='.api_htmlentities(urlencode($page)).'">'.
1217
                    $notify_page.'</a>';
1218
1219
                // Page action: copy last version to doc area
1220 View Code Duplication
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1221
                    $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export2doc&wiki_id='.$row['id'].'">'.
1222
                        Display::return_icon('export_to_documents.png', get_lang('ExportToDocArea'), '', ICON_SIZE_MEDIUM).'</a>';
1223
                }
1224
1225
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export_to_pdf&wiki_id='.$row['id'].'">'.
1226
                    Display::return_icon('pdf.png', get_lang('ExportToPDF'), '', ICON_SIZE_MEDIUM).'</a>';
1227
1228
                $unoconv = api_get_configuration_value('unoconv.binaries');
1229 View Code Duplication
                if ($unoconv) {
1230
                    $actionsRight .= '<a href="'.api_get_path(WEB_CODE_PATH).'wiki/index.php?action=export_to_doc_file&id='.$row['id'].'&'.api_get_cidreq().'">'.
1231
                        Display::return_icon('export_doc.png', get_lang('ExportToDoc'), array(), ICON_SIZE_MEDIUM).'</a>';
1232
                }
1233
1234
                //export to print
1235
                ?>
1236
                <script>
1237
                    function goprint() {
1238
                        var a = window.open('', '', 'width=800,height=600');
1239
                        a.document.open("text/html");
1240
                        a.document.write(document.getElementById('wikicontent').innerHTML);
1241
                        a.document.close();
1242
                        a.print();
1243
                    }
1244
                </script>
1245
                <?php
1246
                $actionsRight .= Display::url(
1247
                    Display::return_icon(
1248
                        'printer.png',
1249
                        get_lang('Print'),
1250
                        '',
1251
                        ICON_SIZE_MEDIUM
1252
                    ),
1253
                    '#',
1254
                    array('onclick' => "javascript: goprint();")
1255
                );
1256
            }
1257
1258
            echo Display::toolbarAction(
1259
                'toolbar-wikistudent',
1260
                [$actionsLeft, $actionsRight]
1261
            );
1262
1263
            if (empty($title)) {
1264
                $pageTitle = get_lang('DefaultTitle');
1265
            }
1266
1267
            if (self::wiki_exist($title)) {
1268
                $pageTitle = $icon_assignment.'&nbsp;'.$icon_task.'&nbsp;'.api_htmlentities($title);
1269
            } else {
1270
                $pageTitle = api_htmlentities($title);
1271
            }
1272
1273
            $pageWiki = self::make_wiki_link_clickable(
1274
                self::detect_external_link(
1275
                    self::detect_anchor_link(
1276
                        self::detect_mail_link(
1277
                            self::detect_ftp_link(
1278
                                self::detect_irc_link(
1279
                                    self::detect_news_link($content)
1280
                                )
1281
                            )
1282
                        )
1283
                    )
1284
                )
1285
            );
1286
1287
            $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);
1288
1289
            echo Display::panel($pageWiki, $pageTitle, $footerWiki);
1290
        } //end filter visibility
1291
    }
1292
1293
    /**
1294
     * This function counted the words in a document. Thanks Adeel Khan
1295
     * @param   string  Document's text
1296
     * @return  int     Number of words
1297
     */
1298
    public function word_count($document)
1299
    {
1300
        $search = array(
1301
            '@<script[^>]*?>.*?</script>@si',
1302
            '@<style[^>]*?>.*?</style>@siU',
1303
            '@<div id="player.[^>]*?>.*?</div>@',
1304
            '@<![\s\S]*?--[ \t\n\r]*>@'
1305
        );
1306
1307
        $document = preg_replace($search, '', $document);
1308
1309
        # strip all html tags
1310
        $wc = strip_tags($document);
1311
        $wc = html_entity_decode(
1312
            $wc,
1313
            ENT_NOQUOTES,
1314
            'UTF-8'
1315
        ); // TODO:test also old html_entity_decode(utf8_encode($wc))
1316
1317
        # remove 'words' that don't consist of alphanumerical characters or punctuation. And fix accents and some letters
1318
        $pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@|á|é|í|ó|ú|à|è|ì|ò|ù|ä|ë|ï|ö|ü|Á|É|Í|Ó|Ú|À|È|Ò|Ù|Ä|Ë|Ï|Ö|Ü|â|ê|î|ô|û|Â|Ê|Î|Ô|Û|ñ|Ñ|ç|Ç)]+#";
1319
        $wc = trim(preg_replace($pattern, " ", $wc));
1320
1321
        # remove one-letter 'words' that consist only of punctuation
1322
        $wc = trim(
1323
            preg_replace(
1324
                "#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#",
1325
                " ",
1326
                $wc
1327
            )
1328
        );
1329
1330
        # remove superfluous whitespace
1331
        $wc = preg_replace("/\s\s+/", " ", $wc);
1332
1333
        # split string into an array of words
1334
        $wc = explode(" ", $wc);
1335
1336
        # remove empty elements
1337
        $wc = array_filter($wc);
1338
1339
        # return the number of words
1340
        return count($wc);
1341
    }
1342
1343
    /**
1344
     * This function checks if wiki title exist
1345
     */
1346 View Code Duplication
    public function wiki_exist($title)
1347
    {
1348
        $tbl_wiki = $this->tbl_wiki;
1349
        $groupfilter = $this->groupfilter;
1350
        $condition_session = $this->condition_session;
1351
        $course_id = api_get_course_int_id();
1352
1353
        $sql = 'SELECT id FROM '.$tbl_wiki.'
1354
              WHERE
1355
                c_id = '.$course_id.' AND
1356
                title="'.Database::escape_string($title).'" AND
1357
                '.$groupfilter.$condition_session.'
1358
              ORDER BY id ASC';
1359
        $result = Database::query($sql);
1360
        $cant = Database::num_rows($result);
1361
        if ($cant > 0) {
1362
            return true;
1363
        } else {
1364
            return false;
1365
        }
1366
    }
1367
1368
    /**
1369
     * Checks if this navigation tab has to be set to active
1370
     * @author Patrick Cool <[email protected]>, Ghent University
1371
     *
1372
     * @return string html code
1373
     */
1374
    public function is_active_navigation_tab($paramwk)
1375
    {
1376
        if (isset($_GET['action']) && $_GET['action'] == $paramwk) {
1377
            return ' class="active"';
1378
        }
1379
    }
1380
1381
    /**
1382
     * Lock add pages
1383
     * @author Juan Carlos Raña <[email protected]>
1384
     * return current database status of protect page and change it if get action
1385
     */
1386
    public function check_addnewpagelock()
1387
    {
1388
        $tbl_wiki = $this->tbl_wiki;
1389
        $condition_session = $this->condition_session;
1390
        $groupfilter = $this->groupfilter;
1391
        $course_id = api_get_course_int_id();
1392
1393
        $sql = 'SELECT *
1394
                FROM '.$tbl_wiki.'
1395
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1396
                ORDER BY id ASC';
1397
1398
        $result = Database::query($sql);
1399
        $row = Database::fetch_array($result);
1400
1401
        $status_addlock = $row['addlock'];
1402
1403
        // Change status
1404
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1405
            if (isset($_GET['actionpage'])) {
1406
                if ($_GET['actionpage'] == 'lockaddnew' && $status_addlock == 1) {
1407
                    $status_addlock = 0;
1408
                }
1409
                if ($_GET['actionpage'] == 'unlockaddnew' && $status_addlock == 0) {
1410
                    $status_addlock = 1;
1411
                }
1412
                $sql = 'UPDATE '.$tbl_wiki.' SET
1413
                            addlock="'.Database::escape_string($status_addlock).'"
1414
                        WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session;
1415
                Database::query($sql);
1416
            }
1417
1418
            $sql = 'SELECT *
1419
                    FROM '.$tbl_wiki.'
1420
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1421
                    ORDER BY id ASC';
1422
            $result = Database::query($sql);
1423
            $row = Database::fetch_array($result);
1424
        }
1425
1426
        return $row['addlock'];
1427
    }
1428
1429
    /**
1430
     * Protect page
1431
     * @author Juan Carlos Raña <[email protected]>
1432
     * return current database status of protect page and change it if get action
1433
     */
1434
    public function check_protect_page()
1435
    {
1436
        $tbl_wiki = $this->tbl_wiki;
1437
        $condition_session = $this->condition_session;
1438
        $groupfilter = $this->groupfilter;
1439
        $page = $this->page;
1440
1441
        $course_id = api_get_course_int_id();
1442
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1443
              WHERE
1444
                c_id = '.$course_id.' AND
1445
                reflink="'.Database::escape_string($page).'" AND
1446
                '.$groupfilter.$condition_session.'
1447
              ORDER BY id ASC';
1448
1449
        $result = Database::query($sql);
1450
        $row = Database::fetch_array($result);
1451
        $status_editlock = $row['editlock'];
1452
        $id = $row['page_id'];
1453
1454
        // Change status
1455
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1456
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'lock' && $status_editlock == 0) {
1457
                $status_editlock = 1;
1458
            }
1459
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlock' && $status_editlock == 1) {
1460
                $status_editlock = 0;
1461
            }
1462
1463
            $sql = 'UPDATE '.$tbl_wiki.' SET editlock="'.Database::escape_string($status_editlock).'"
1464
                    WHERE c_id = '.$course_id.' AND page_id="'.$id.'"';
1465
            Database::query($sql);
1466
1467
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1468
                  WHERE
1469
                    c_id = '.$course_id.' AND
1470
                    reflink="'.Database::escape_string($page).'" AND
1471
                    '.$groupfilter.$condition_session.'
1472
                  ORDER BY id ASC';
1473
            $result = Database::query($sql);
1474
            $row = Database::fetch_array($result);
1475
        }
1476
1477
        //show status
1478
        return $row['editlock'];
1479
    }
1480
1481
    /**
1482
     * Visibility page
1483
     * @author Juan Carlos Raña <[email protected]>
1484
     * return current database status of visibility and change it if get action
1485
     */
1486
    public function check_visibility_page()
1487
    {
1488
        $tbl_wiki = $this->tbl_wiki;
1489
        $page = $this->page;
1490
        $condition_session = $this->condition_session;
1491
        $groupfilter = $this->groupfilter;
1492
        $course_id = api_get_course_int_id();
1493
1494
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1495
                WHERE
1496
                    c_id = '.$course_id.' AND
1497
                    reflink="'.Database::escape_string($page).'" AND
1498
                    '.$groupfilter.$condition_session.'
1499
                ORDER BY id ASC';
1500
        $result = Database::query($sql);
1501
        $row = Database::fetch_array($result);
1502
        $status_visibility = $row['visibility'];
1503
        //change status
1504
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1505
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'visible' && $status_visibility == 0) {
1506
                $status_visibility = 1;
1507
1508
            }
1509
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'invisible' && $status_visibility == 1) {
1510
                $status_visibility = 0;
1511
            }
1512
1513
            $sql = 'UPDATE '.$tbl_wiki.' SET 
1514
                    visibility = "'.Database::escape_string($status_visibility).'"
1515
                    WHERE 
1516
                        c_id = '.$course_id.' AND 
1517
                        reflink="'.Database::escape_string($page).'" AND 
1518
                        '.$groupfilter.$condition_session;
1519
            Database::query($sql);
1520
1521
            // Although the value now is assigned to all (not only the first),
1522
            // these three lines remain necessary.
1523
            // They do that by changing the page state is
1524
            // made when you press the button and not have to wait to change his page
1525
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1526
                    WHERE
1527
                        c_id = '.$course_id.' AND
1528
                        reflink="'.Database::escape_string($page).'" AND
1529
                        '.$groupfilter.$condition_session.'
1530
                    ORDER BY id ASC';
1531
            $result = Database::query($sql);
1532
            $row = Database::fetch_array($result);
1533
        }
1534
1535
        if (empty($row['id'])) {
1536
            $row['visibility'] = 1;
1537
        }
1538
1539
        //show status
1540
        return $row['visibility'];
1541
    }
1542
1543
    /**
1544
     * Visibility discussion
1545
     * @author Juan Carlos Raña <[email protected]>
1546
     * @return int current database status of discuss visibility and change it if get action page
1547
     */
1548 View Code Duplication
    public function check_visibility_discuss()
1549
    {
1550
        $tbl_wiki = $this->tbl_wiki;
1551
        $page = $this->page;
1552
        $condition_session = $this->condition_session;
1553
        $groupfilter = $this->groupfilter;
1554
        $course_id = api_get_course_int_id();
1555
1556
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1557
                WHERE
1558
                    c_id = '.$course_id.' AND
1559
                    reflink="'.Database::escape_string($page).'" AND
1560
                    '.$groupfilter.$condition_session.'
1561
                ORDER BY id ASC';
1562
        $result = Database::query($sql);
1563
        $row = Database::fetch_array($result);
1564
1565
        $status_visibility_disc = $row['visibility_disc'];
1566
1567
        //change status
1568
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1569
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'showdisc' && $status_visibility_disc == 0) {
1570
                $status_visibility_disc = 1;
1571
            }
1572
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'hidedisc' && $status_visibility_disc == 1) {
1573
                $status_visibility_disc = 0;
1574
            }
1575
1576
            $sql = 'UPDATE '.$tbl_wiki.' SET visibility_disc="'.Database::escape_string($status_visibility_disc).'"
1577
                    WHERE
1578
                        c_id = '.$course_id.' AND
1579
                        reflink="'.Database::escape_string($page).'" AND
1580
                        '.$groupfilter.$condition_session;
1581
            Database::query($sql);
1582
1583
            // Although the value now is assigned to all (not only the first),
1584
            // these three lines remain necessary.
1585
            // They do that by changing the page state is made when you press
1586
            // the button and not have to wait to change his page
1587
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1588
                    WHERE
1589
                        c_id = '.$course_id.' AND
1590
                        reflink="'.Database::escape_string($page).'" AND
1591
                        '.$groupfilter.$condition_session.'
1592
                    ORDER BY id ASC';
1593
            $result = Database::query($sql);
1594
            $row = Database::fetch_array($result);
1595
        }
1596
1597
        return $row['visibility_disc'];
1598
    }
1599
1600
    /**
1601
     * Lock add discussion
1602
     * @author Juan Carlos Raña <[email protected]>
1603
     * @return int current database status of lock dicuss and change if get action
1604
     */
1605 View Code Duplication
    public function check_addlock_discuss()
1606
    {
1607
        $tbl_wiki = $this->tbl_wiki;
1608
        $page = $this->page;
1609
        $condition_session = $this->condition_session;
1610
        $groupfilter = $this->groupfilter;
1611
        $course_id = api_get_course_int_id();
1612
1613
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1614
                WHERE
1615
                    c_id = '.$course_id.' AND
1616
                    reflink="'.Database::escape_string($page).'" AND
1617
                    '.$groupfilter.$condition_session.'
1618
                ORDER BY id ASC';
1619
        $result = Database::query($sql);
1620
        $row = Database::fetch_array($result);
1621
1622
        $status_addlock_disc = $row['addlock_disc'];
1623
1624
        //change status
1625
        if (api_is_allowed_to_edit() || api_is_platform_admin()) {
1626
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'lockdisc' && $status_addlock_disc == 0) {
1627
                $status_addlock_disc = 1;
1628
            }
1629
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlockdisc' && $status_addlock_disc == 1) {
1630
                $status_addlock_disc = 0;
1631
            }
1632
1633
            $sql = 'UPDATE '.$tbl_wiki.' SET
1634
                    addlock_disc="'.Database::escape_string($status_addlock_disc).'"
1635
                    WHERE
1636
                        c_id = '.$course_id.' AND
1637
                        reflink = "'.Database::escape_string($page).'" AND
1638
                         '.$groupfilter.$condition_session;
1639
            Database::query($sql);
1640
1641
            // Although the value now is assigned to all (not only the first),
1642
            // these three lines remain necessary.
1643
            // They do that by changing the page state is made when you press
1644
            // the button and not have to wait to change his page
1645
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1646
                    WHERE
1647
                        c_id = '.$course_id.' AND
1648
                        reflink="'.Database::escape_string($page).'" AND
1649
                        '.$groupfilter.$condition_session.'
1650
                    ORDER BY id ASC';
1651
            $result = Database::query($sql);
1652
            $row = Database::fetch_array($result);
1653
        }
1654
1655
        return $row['addlock_disc'];
1656
    }
1657
1658
    /**
1659
     * Lock rating discussion
1660
     * @author Juan Carlos Raña <[email protected]>
1661
     * @return  int  current database status of rating discuss and change it if get action
1662
     */
1663 View Code Duplication
    public function check_ratinglock_discuss()
1664
    {
1665
        $tbl_wiki = $this->tbl_wiki;
1666
        $page = $this->page;
1667
        $condition_session = $this->condition_session;
1668
        $groupfilter = $this->groupfilter;
1669
        $course_id = api_get_course_int_id();
1670
1671
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1672
                WHERE
1673
                    c_id = '.$course_id.' AND
1674
                    reflink="'.Database::escape_string($page).'" AND
1675
                    '.$groupfilter.$condition_session.'
1676
                ORDER BY id ASC';
1677
        $result = Database::query($sql);
1678
        $row = Database::fetch_array($result);
1679
        $status_ratinglock_disc = $row['ratinglock_disc'];
1680
1681
        //change status
1682
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1683
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'lockrating' && $status_ratinglock_disc == 0) {
1684
                $status_ratinglock_disc = 1;
1685
            }
1686
            if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlockrating' && $status_ratinglock_disc == 1) {
1687
                $status_ratinglock_disc = 0;
1688
            }
1689
1690
            $sql = 'UPDATE '.$tbl_wiki.'
1691
                    SET ratinglock_disc="'.Database::escape_string($status_ratinglock_disc).'"
1692
                    WHERE
1693
                        c_id = '.$course_id.' AND
1694
                        reflink="'.Database::escape_string($page).'" AND
1695
                        '.$groupfilter.$condition_session;
1696
            //Visibility. Value to all,not only for the first
1697
            Database::query($sql);
1698
1699
            // Although the value now is assigned to all (not only the first),
1700
            // these three lines remain necessary. They do that by changing the
1701
            // page state is made when you press the button and not have to wait
1702
            // to change his page
1703
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1704
                  WHERE
1705
                    c_id = '.$course_id.' AND
1706
                    reflink="'.Database::escape_string($page).'" AND
1707
                    '.$groupfilter.$condition_session.'
1708
                  ORDER BY id ASC';
1709
            $result = Database::query($sql);
1710
            $row = Database::fetch_array($result);
1711
        }
1712
1713
        return $row['ratinglock_disc'];
1714
    }
1715
1716
    /**
1717
     * Notify page changes
1718
     * @author Juan Carlos Raña <[email protected]>
1719
     * @return int the current notification status
1720
     */
1721
    public function check_notify_page($reflink)
1722
    {
1723
        $tbl_wiki = $this->tbl_wiki;
1724
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1725
        $condition_session = $this->condition_session;
1726
        $groupfilter = $this->groupfilter;
1727
        $groupId = api_get_group_id();
1728
        $session_id = api_get_session_id();
1729
        $course_id = api_get_course_int_id();
1730
        $userId = api_get_user_id();
1731
1732
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1733
                WHERE c_id = '.$course_id.' AND reflink="'.$reflink.'" AND '.$groupfilter.$condition_session.'
1734
                ORDER BY id ASC';
1735
        $result = Database::query($sql);
1736
        $row = Database::fetch_array($result);
1737
        $id = $row['id'];
1738
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1739
                WHERE c_id = '.$course_id.' AND id="'.$id.'" AND user_id="'.api_get_user_id().'" AND type="P"';
1740
        $result = Database::query($sql);
1741
        $row = Database::fetch_array($result);
1742
        $idm = $row['id'];
1743
        if (empty($idm)) {
1744
            $status_notify = 0;
1745
        } else {
1746
            $status_notify = 1;
1747
        }
1748
1749
        // Change status
1750
        if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'locknotify' && $status_notify == 0) {
1751
            $sql = "SELECT id FROM $tbl_wiki_mailcue
1752
                    WHERE c_id = $course_id AND id = $id AND user_id = $userId";
1753
            $result = Database::query($sql);
1754
            $exist = false;
1755
            if (Database::num_rows($result)) {
1756
                $exist = true;
1757
            }
1758
            if ($exist == false) {
1759
                $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1760
                ($course_id, '".$id."','".api_get_user_id()."','P','".$groupId."','".$session_id."')";
1761
                Database::query($sql);
1762
            }
1763
            $status_notify = 1;
1764
        }
1765
1766
        if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlocknotify' && $status_notify == 1) {
1767
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1768
                    WHERE id="'.$id.'" AND user_id="'.api_get_user_id().'" AND type="P" AND c_id = '.$course_id;
1769
            Database::query($sql);
1770
            $status_notify = 0;
1771
        }
1772
1773
        return $status_notify;
1774
    }
1775
1776
    /**
1777
     * Notify discussion changes
1778
     * @author Juan Carlos Raña <[email protected]>
1779
     * @param string $reflink
1780
     * @return int current database status of rating discuss and change it if get action
1781
     */
1782
    public function check_notify_discuss($reflink)
1783
    {
1784
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1785
        $tbl_wiki = $this->tbl_wiki;
1786
        $condition_session = $this->condition_session;
1787
        $groupfilter = $this->groupfilter;
1788
1789
        $course_id = api_get_course_int_id();
1790
        $groupId = api_get_group_id();
1791
        $session_id = api_get_session_id();
1792
1793
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1794
                WHERE c_id = '.$course_id.' AND reflink="'.$reflink.'" AND '.$groupfilter.$condition_session.'
1795
                ORDER BY id ASC';
1796
        $result = Database::query($sql);
1797
        $row = Database::fetch_array($result);
1798
        $id = $row['id'];
1799
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1800
                WHERE c_id = '.$course_id.' AND id="'.$id.'" AND user_id="'.api_get_user_id().'" AND type="D"';
1801
        $result = Database::query($sql);
1802
        $row = Database::fetch_array($result);
1803
        $idm = $row['id'];
1804
1805
        if (empty($idm)) {
1806
            $status_notify_disc = 0;
1807
        } else {
1808
            $status_notify_disc = 1;
1809
        }
1810
1811
        //change status
1812 View Code Duplication
        if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'locknotifydisc' && $status_notify_disc == 0) {
1813
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1814
            ($course_id, '".$id."','".api_get_user_id()."','D','".$groupId."','".$session_id."')";
1815
            Database::query($sql);
1816
            $status_notify_disc = 1;
1817
        }
1818 View Code Duplication
        if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'unlocknotifydisc' && $status_notify_disc == 1) {
1819
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1820
                    WHERE c_id = '.$course_id.' AND id="'.$id.'" AND user_id="'.api_get_user_id().'" AND type="D" AND c_id = '.$course_id;
1821
            Database::query($sql);
1822
            $status_notify_disc = 0;
1823
        }
1824
1825
        return $status_notify_disc;
1826
    }
1827
1828
    /**
1829
     * Notify all changes
1830
     * @author Juan Carlos Raña <[email protected]>
1831
     */
1832
    public function check_notify_all()
1833
    {
1834
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1835
        $course_id = api_get_course_int_id();
1836
        $groupId = api_get_group_id();
1837
        $session_id = api_get_session_id();
1838
1839
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1840
                WHERE
1841
                    c_id = '.$course_id.' AND
1842
                    user_id="'.api_get_user_id().'" AND
1843
                    type="F" AND
1844
                    group_id="'.$groupId.'" AND
1845
                    session_id="'.$session_id.'"';
1846
        $result = Database::query($sql);
1847
        $row = Database::fetch_array($result);
1848
1849
        $idm = $row['user_id'];
1850
1851
        if (empty($idm)) {
1852
            $status_notify_all = 0;
1853
        } else {
1854
            $status_notify_all = 1;
1855
        }
1856
1857
        //change status
1858 View Code Duplication
        if (isset($_GET['actionpage']) && $_GET['actionpage'] == 'locknotifyall' && $status_notify_all == 0) {
1859
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, user_id, type, group_id, session_id) VALUES
1860
            ($course_id, '".api_get_user_id()."','F','".$groupId."','".$session_id."')";
1861
            Database::query($sql);
1862
            $status_notify_all = 1;
1863
        }
1864
1865 View Code Duplication
        if (isset($_GET['actionpage']) &&
1866
            isset($_GET['actionpage']) &&
1867
            $_GET['actionpage'] == 'unlocknotifyall' &&
1868
            $status_notify_all == 1
1869
        ) {
1870
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1871
                   WHERE
1872
                    c_id = '.$course_id.' AND
1873
                    user_id="'.api_get_user_id().'" AND
1874
                    type="F" AND
1875
                    group_id="'.$groupId.'" AND
1876
                    session_id="'.$session_id.'" AND
1877
                    c_id = '.$course_id;
1878
            Database::query($sql);
1879
            $status_notify_all = 0;
1880
        }
1881
1882
        //show status
1883
        return $status_notify_all;
1884
    }
1885
1886
    /**
1887
     * Sends pending e-mails
1888
     */
1889
    public function check_emailcue(
1890
        $id_or_ref,
1891
        $type,
1892
        $lastime = '',
1893
        $lastuser = ''
1894
    ) {
1895
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1896
        $tbl_wiki = $this->tbl_wiki;
1897
        $condition_session = $this->condition_session;
1898
        $groupfilter = $this->groupfilter;
1899
        $_course = $this->courseInfo;
1900
        $groupId = api_get_group_id();
1901
        $session_id = api_get_session_id();
1902
        $course_id = api_get_course_int_id();
1903
        $group_properties = GroupManager::get_group_properties($groupId);
1904
        $group_name = $group_properties['name'];
1905
        $allow_send_mail = false; //define the variable to below
1906
        $email_assignment = null;
1907
        if ($type == 'P') {
1908
            //if modifying a wiki page
1909
            //first, current author and time
1910
            //Who is the author?
1911
            $userinfo = api_get_user_info($lastuser);
1912
            $email_user_author = get_lang('EditedBy').': '.$userinfo['complete_name'];
1913
1914
            //When ?
1915
            $year = substr($lastime, 0, 4);
1916
            $month = substr($lastime, 5, 2);
1917
            $day = substr($lastime, 8, 2);
1918
            $hours = substr($lastime, 11, 2);
1919
            $minutes = substr($lastime, 14, 2);
1920
            $seconds = substr($lastime, 17, 2);
1921
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
1922
1923
            //second, extract data from first reg
1924
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1925
                    WHERE  c_id = '.$course_id.' AND reflink="'.$id_or_ref.'" AND '.$groupfilter.$condition_session.'
1926
                    ORDER BY id ASC';
1927
            $result = Database::query($sql);
1928
            $row = Database::fetch_array($result);
1929
            $id = $row['id'];
1930
            $email_page_name = $row['title'];
1931 View Code Duplication
            if ($row['visibility'] == 1) {
1932
                $allow_send_mail = true; //if visibility off - notify off
1933
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1934
                        WHERE
1935
                            c_id = '.$course_id.' AND
1936
                            id="'.$id.'" AND
1937
                            type="'.$type.'" OR
1938
                            type="F" AND
1939
                            group_id="'.$groupId.'" AND
1940
                            session_id="'.$session_id.'"';
1941
                //type: P=page, D=discuss, F=full.
1942
                $result = Database::query($sql);
1943
                $emailtext = get_lang(
1944
                        'EmailWikipageModified'
1945
                    ).' <strong>'.$email_page_name.'</strong> '.get_lang(
1946
                        'Wiki'
1947
                    );
1948
            }
1949
        } elseif ($type == 'D') {
1950
            //if added a post to discuss
1951
            //first, current author and time
1952
            //Who is the author of last message?
1953
            $userinfo = api_get_user_info($lastuser);
1954
            $email_user_author = get_lang('AddedBy').': '.$userinfo['complete_name'];
1955
1956
            //When ?
1957
            $year = substr($lastime, 0, 4);
1958
            $month = substr($lastime, 5, 2);
1959
            $day = substr($lastime, 8, 2);
1960
            $hours = substr($lastime, 11, 2);
1961
            $minutes = substr($lastime, 14, 2);
1962
            $seconds = substr($lastime, 17, 2);
1963
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
1964
            //second, extract data from first reg
1965
            $id = $id_or_ref; //$id_or_ref is id from tblwiki
1966
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1967
                    WHERE c_id = '.$course_id.' AND id="'.$id.'"
1968
                    ORDER BY id ASC';
1969
1970
            $result = Database::query($sql);
1971
            $row = Database::fetch_array($result);
1972
1973
            $email_page_name = $row['title'];
1974 View Code Duplication
            if ($row['visibility_disc'] == 1) {
1975
                $allow_send_mail = true; //if visibility off - notify off
1976
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1977
                        WHERE
1978
                            c_id = '.$course_id.' AND
1979
                            id="'.$id.'" AND
1980
                            type="'.$type.'" OR
1981
                            type="F" AND
1982
                            group_id="'.$groupId.'" AND
1983
                            session_id="'.$session_id.'"';
1984
                //type: P=page, D=discuss, F=full
1985
                $result = Database::query($sql);
1986
                $emailtext = get_lang('EmailWikiPageDiscAdded').' <strong>'.$email_page_name.'</strong> '.get_lang('Wiki');
1987
            }
1988
        } elseif ($type == 'A') {
1989
            //for added pages
1990
            $id = 0; //for tbl_wiki_mailcue
1991
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1992
                    WHERE c_id = '.$course_id.'
1993
                    ORDER BY id DESC'; //the added is always the last
1994
1995
            $result = Database::query($sql);
1996
            $row = Database::fetch_array($result);
1997
            $email_page_name = $row['title'];
1998
1999
            //Who is the author?
2000
            $userinfo = api_get_user_info($row['user_id']);
2001
            $email_user_author = get_lang('AddedBy').': '.$userinfo['complete_name'];
2002
2003
            //When ?
2004
            $year = substr($row['dtime'], 0, 4);
2005
            $month = substr($row['dtime'], 5, 2);
2006
            $day = substr($row['dtime'], 8, 2);
2007
            $hours = substr($row['dtime'], 11, 2);
2008
            $minutes = substr($row['dtime'], 14, 2);
2009
            $seconds = substr($row['dtime'], 17, 2);
2010
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2011
2012
            if ($row['assignment'] == 0) {
2013
                $allow_send_mail = true;
2014
            } elseif ($row['assignment'] == 1) {
2015
                $email_assignment = get_lang('AssignmentDescExtra').' ('.get_lang('AssignmentMode').')';
2016
                $allow_send_mail = true;
2017
            } elseif ($row['assignment'] == 2) {
2018
                $allow_send_mail = false; //Mode tasks: avoids notifications to all users about all users
2019
            }
2020
2021
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2022
                    WHERE c_id = '.$course_id.' AND  id="'.$id.'" AND type="F" AND group_id="'.$groupId.'" AND session_id="'.$session_id.'"';
2023
            //type: P=page, D=discuss, F=full
2024
            $result = Database::query($sql);
2025
2026
            $emailtext = get_lang('EmailWikiPageAdded').' <strong>'.$email_page_name.'</strong> '.get_lang('In').' '.get_lang('Wiki');
2027
        } elseif ($type == 'E') {
2028
            $id = 0;
2029
            $allow_send_mail = true;
2030
            // Who is the author?
2031
            $userinfo = api_get_user_info(api_get_user_id()); //current user
2032
            $email_user_author = get_lang('DeletedBy').': '.$userinfo['complete_name'];
2033
            //When ?
2034
            $today = date('r'); //current time
2035
            $email_date_changes = $today;
2036
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2037
                    WHERE
2038
                        c_id = '.$course_id.' AND
2039
                        id="'.$id.'" AND type="F" AND
2040
                        group_id="'.$groupId.'" AND
2041
                        session_id="'.$session_id.'"'; //type: P=page, D=discuss, F=wiki
2042
            $result = Database::query($sql);
2043
            $emailtext = get_lang('EmailWikipageDedeleted');
2044
        }
2045
        ///make and send email
2046
        if ($allow_send_mail) {
2047
            while ($row = Database::fetch_array($result)) {
2048
                $userinfo = api_get_user_info(
2049
                    $row['user_id']
2050
                ); //$row['user_id'] obtained from tbl_wiki_mailcue
2051
                $name_to = $userinfo['complete_name'];
2052
                $email_to = $userinfo['email'];
2053
                $sender_name = api_get_setting('emailAdministrator');
2054
                $sender_email = api_get_setting('emailAdministrator');
2055
                $email_subject = get_lang('EmailWikiChanges').' - '.$_course['official_code'];
2056
                $email_body = get_lang('DearUser').' '.api_get_person_name($userinfo['firstname'], $userinfo['lastname']).',<br /><br />';
2057
                if ($session_id == 0) {
2058
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' - '.$group_name.'</strong><br /><br /><br />';
2059
                } else {
2060
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' ('.api_get_session_name(api_get_session_id()).') - '.$group_name.'</strong><br /><br /><br />';
2061
                }
2062
                $email_body .= $email_user_author.' ('.$email_date_changes.')<br /><br /><br />';
2063
                $email_body .= $email_assignment.'<br /><br /><br />';
2064
                $email_body .= '<font size="-2">'.get_lang('EmailWikiChangesExt_1').': <strong>'.get_lang('NotifyChanges').'</strong><br />';
2065
                $email_body .= get_lang('EmailWikiChangesExt_2').': <strong>'.get_lang('NotNotifyChanges').'</strong></font><br />';
2066
                @api_mail_html(
2067
                    $name_to,
2068
                    $email_to,
2069
                    $email_subject,
2070
                    $email_body,
2071
                    $sender_name,
2072
                    $sender_email
2073
                );
2074
            }
2075
        }
2076
    }
2077
2078
    /**
2079
     * Function export last wiki page version to document area
2080
     * @param int $doc_id wiki page id
2081
     * @return mixed
2082
     * @author Juan Carlos Raña <[email protected]>
2083
     */
2084
    public function export2doc($doc_id)
2085
    {
2086
        $_course = $this->courseInfo;
2087
        $groupId = api_get_group_id();
2088
        $groupInfo = GroupManager::get_group_properties($groupId);
2089
        $data = self::getWikiDataFromDb($doc_id);
2090
2091
        if (empty($data)) {
2092
            return false;
2093
        }
2094
2095
        $wikiTitle = $data['title'];
2096
        $wikiContents = $data['content'];
2097
2098
        $template =
2099
            '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2100
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{LANGUAGE}" lang="{LANGUAGE}">
2101
            <head>
2102
            <title>{TITLE}</title>
2103
            <meta http-equiv="Content-Type" content="text/html; charset={ENCODING}" />
2104
            <style type="text/css" media="screen, projection">
2105
            /*<![CDATA[*/
2106
            {CSS}
2107
            /*]]>*/
2108
            </style>
2109
            {ASCIIMATHML_SCRIPT}</head>
2110
            <body dir="{TEXT_DIRECTION}">
2111
            {CONTENT}
2112
            </body>
2113
            </html>';
2114
2115
        $css_file = api_get_path(SYS_CSS_PATH).'themes/'.api_get_setting('stylesheets').'/default.css';
2116
        if (file_exists($css_file)) {
2117
            $css = @file_get_contents($css_file);
2118
        } else {
2119
            $css = '';
2120
        }
2121
        // Fixing some bugs in css files.
2122
        $root_rel = api_get_path(REL_PATH);
2123
        $css_path = 'main/css/';
2124
        $theme = api_get_setting('stylesheets').'/';
2125
        $css = str_replace('behavior:url("/main/css/csshover3.htc");', '', $css);
2126
        $css = str_replace('main/', $root_rel.'main/', $css);
2127
        $css = str_replace('images/', $root_rel.$css_path.$theme.'images/', $css);
2128
        $css = str_replace('../../img/', $root_rel.'main/img/', $css);
2129
        $asciimathmal_script = (api_contains_asciimathml($wikiContents) || api_contains_asciisvg($wikiContents))
2130
            ? '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'asciimath/ASCIIMathML.js" type="text/javascript"></script>'."\n" : '';
2131
2132
        $template = str_replace(array('{LANGUAGE}', '{ENCODING}', '{TEXT_DIRECTION}', '{TITLE}', '{CSS}', '{ASCIIMATHML_SCRIPT}'),
2133
            array(api_get_language_isocode(), api_get_system_encoding(), api_get_text_direction(), $wikiTitle, $css, $asciimathmal_script),
2134
            $template);
2135
2136
        if (0 != $groupId) {
2137
            $groupPart = '_group'.$groupId; // and add groupId to put the same document title in different groups
2138
            $group_properties = GroupManager::get_group_properties($groupId);
2139
            $groupPath = $group_properties['directory'];
2140
        } else {
2141
            $groupPart = '';
2142
            $groupPath = '';
2143
        }
2144
2145
        $exportDir = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/document'.$groupPath;
2146
        $exportFile = api_replace_dangerous_char($wikiTitle).$groupPart;
2147
        $wikiContents = trim(preg_replace("/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/", "$1", $wikiContents));
2148
        //TODO: put link instead of title
2149
2150
        $wikiContents = str_replace('{CONTENT}', $wikiContents, $template);
2151
2152
        // replace relative path by absolute path for courses, so you can see items into this page wiki (images, mp3, etc..) exported in documents
2153
        if (api_strpos($wikiContents, '../..'.api_get_path(REL_COURSE_PATH)) !== false) {
2154
            $web_course_path = api_get_path(WEB_COURSE_PATH);
2155
            $wikiContents = str_replace('../..'.api_get_path(REL_COURSE_PATH), $web_course_path, $wikiContents);
2156
        }
2157
2158
        $i = 1;
2159
        //only export last version, but in new export new version in document area
2160
        while (file_exists($exportDir.'/'.$exportFile.'_'.$i.'.html')) {
2161
            $i++;
2162
        }
2163
2164
        $wikiFileName = $exportFile.'_'.$i.'.html';
2165
        $exportPath = $exportDir.'/'.$wikiFileName;
2166
2167
        file_put_contents($exportPath, $wikiContents);
2168
        $doc_id = add_document(
2169
            $_course,
2170
            $groupPath.'/'.$wikiFileName,
2171
            'file',
2172
            filesize($exportPath),
2173
            $wikiTitle
2174
        );
2175
2176
        api_item_property_update(
2177
            $_course,
2178
            TOOL_DOCUMENT,
2179
            $doc_id,
2180
            'DocumentAdded',
2181
            api_get_user_id(),
2182
            $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 2088 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...
2183
        );
2184
2185
        return $doc_id;
2186
    }
2187
2188
    /**
2189
     * Exports the wiki page to PDF
2190
     */
2191
    public function export_to_pdf($id, $course_code)
2192
    {
2193
        if (!api_is_platform_admin()) {
2194
            if (api_get_setting('students_export2pdf') !== 'true') {
2195
                Display::addFlash(
2196
                    Display::return_message(
2197
                        get_lang('PDFDownloadNotAllowedForStudents'),
2198
                        'error',
2199
                        false
2200
                    )
2201
                );
2202
2203
                return false;
2204
            }
2205
        }
2206
2207
        $data = self::getWikiDataFromDb($id);
2208
        $content_pdf = api_html_entity_decode(
2209
            $data['content'],
2210
            ENT_QUOTES,
2211
            api_get_system_encoding()
2212
        );
2213
2214
        //clean wiki links
2215
        $content_pdf = trim(
2216
            preg_replace(
2217
                "/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/",
2218
                "$1",
2219
                $content_pdf
2220
            )
2221
        );
2222
        //TODO: It should be better to display the link insted of the tile but it is hard for [[title]] links
2223
2224
        $title_pdf = api_html_entity_decode(
2225
            $data['title'],
2226
            ENT_QUOTES,
2227
            api_get_system_encoding()
2228
        );
2229
        $title_pdf = api_utf8_encode($title_pdf, api_get_system_encoding());
2230
        $content_pdf = api_utf8_encode($content_pdf, api_get_system_encoding());
2231
2232
        $html = '
2233
        <!-- defines the headers/footers - this must occur before the headers/footers are set -->
2234
2235
        <!--mpdf
2236
        <pageheader name="odds" content-left="'.$title_pdf.'"  header-style-left="color: #880000; font-style: italic;"  line="1" />
2237
        <pagefooter name="odds" content-right="{PAGENO}/{nb}" line="1" />
2238
2239
        <!-- set the headers/footers - they will occur from here on in the document -->
2240
        <!--mpdf
2241
        <setpageheader name="odds" page="odd" value="on" show-this-page="1" />
2242
        <setpagefooter name="odds" page="O" value="on" />
2243
2244
        mpdf-->'.$content_pdf;
2245
2246
        $css_file = api_get_path(SYS_CSS_PATH).'themes/'.api_get_setting(
2247
                'stylesheets'
2248
            ).'/print.css';
2249
        if (file_exists($css_file)) {
2250
            $css = @file_get_contents($css_file);
2251
        } else {
2252
            $css = '';
2253
        }
2254
2255
        $pdf = new PDF();
2256
        $pdf->content_to_pdf($html, $css, $title_pdf, $course_code);
2257
        exit;
2258
    }
2259
2260
    /**
2261
     * Function prevent double post (reload or F5)
2262
     *
2263
     */
2264
    public function double_post($wpost_id)
2265
    {
2266
        $postId = Session::read('wpost_id');
2267
        if (!empty($postId)) {
2268
            if ($wpost_id == $postId) {
2269
                return false;
2270
            } else {
2271
                Session::write('wpost_id', $wpost_id);
2272
2273
                return true;
2274
            }
2275
        } else {
2276
            Session::write('wpost_id', $wpost_id);
2277
2278
            return true;
2279
        }
2280
    }
2281
2282
    /**
2283
     * Function wizard individual assignment
2284
     * @author Juan Carlos Raña <[email protected]>
2285
     */
2286
    public function auto_add_page_users($values)
2287
    {
2288
        $assignment_type = $values['assignment'];
2289
        $session_id = $this->session_id;
2290
        $groupId = api_get_group_id();
2291
        $groupInfo = GroupManager::get_group_properties($groupId);
2292
        if ($groupId == 0) {
2293
            //extract course members
2294
            if (!empty($session_id)) {
2295
                $a_users_to_add = CourseManager::get_user_list_from_course_code(
2296
                    api_get_course_id(),
2297
                    $session_id
2298
                );
2299
            } else {
2300
                $a_users_to_add = CourseManager::get_user_list_from_course_code(
2301
                    api_get_course_id(),
2302
                    0
2303
                );
2304
            }
2305
        } else {
2306
            //extract group members
2307
            $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 2291 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...
2308
            $subscribed_tutors = GroupManager::get_subscribed_tutors(
2309
                $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 2291 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...
2310
            );
2311
            $a_users_to_add_with_duplicates = array_merge(
2312
                $subscribed_users,
2313
                $subscribed_tutors
2314
            );
2315
            //remove duplicates
2316
            $a_users_to_add = $a_users_to_add_with_duplicates;
2317
            //array_walk($a_users_to_add, create_function('&$value,$key', '$value = json_encode($value);'));
2318
            $a_users_to_add = array_unique($a_users_to_add);
2319
            //array_walk($a_users_to_add, create_function('&$value,$key', '$value = json_decode($value, true);'));
2320
        }
2321
2322
        $all_students_pages = array();
2323
        // Data about teacher
2324
        $userId = api_get_user_id();
2325
        $userinfo = api_get_user_info($userId);
2326
        $username = api_htmlentities(
2327
            sprintf(get_lang('LoginX'), $userinfo['username'], ENT_QUOTES)
2328
        );
2329
        $name = $userinfo['complete_name']." - ".$username;
2330
        $photo = '<img src="'.$userinfo['avatar'].'" alt="'.$name.'"  width="40" height="50" align="top" title="'.$name.'"  />';
2331
2332
        // teacher assignment title
2333
        $title_orig = $values['title'];
2334
2335
        // teacher assignment reflink
2336
        $link2teacher = $values['title'] = $title_orig."_uass".$userId;
2337
2338
        // first: teacher name, photo, and assignment description (original content)
2339
        $content_orig_A = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2340
        <table border="0">
2341
            <tr><td style="font-size:24px">'.get_lang('AssignmentDesc').'</td></tr>
2342
            <tr><td>'.$photo.'<br />'.Display::tag(
2343
                'span',
2344
                api_get_person_name(
2345
                    $userinfo['firstname'],
2346
                    $userinfo['lastname']
2347
                ),
2348
                array('title' => $username)
2349
            ).'</td></tr>
2350
        </table></div>';
2351
2352
        $content_orig_B = '<br/><div align="center" style="font-size:24px">'.
2353
            get_lang('AssignmentDescription').': '.
2354
            $title_orig.'</div><br/>'.Security::remove_XSS($_POST['content']);
2355
2356
        //Second: student list (names, photo and links to their works).
2357
        //Third: Create Students work pages.
2358
        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...
2359
            if ($o_user_to_add['user_id'] != $userId) {
2360
                // except that puts the task
2361
                $assig_user_id = $o_user_to_add['user_id'];
2362
                // identifies each page as created by the student, not by teacher
2363
2364
                $userPicture = UserManager::getUserPicture($assig_user_id);
2365
                $username = api_htmlentities(
2366
                    sprintf(
2367
                        get_lang('LoginX'),
2368
                        $o_user_to_add['username'],
2369
                        ENT_QUOTES
2370
                    )
2371
                );
2372
                $name = api_get_person_name(
2373
                        $o_user_to_add['firstname'],
2374
                        $o_user_to_add['lastname']
2375
                    )." . ".$username;
2376
                $photo = '<img src="'.$userPicture.'" alt="'.$name.'"  width="40" height="50" align="bottom" title="'.$name.'"  />';
2377
2378
                $is_tutor_of_group = GroupManager::is_tutor_of_group(
2379
                    $assig_user_id,
2380
                    $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 2291 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...
2381
                ); //student is tutor
2382
                $is_tutor_and_member = GroupManager::is_tutor_of_group(
2383
                        $assig_user_id,
2384
                        $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group_properties($groupId) on line 2291 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...
2385
                    ) &&
2386
                    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 2291 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...
2387
                // student is tutor and member
2388
                if ($is_tutor_and_member) {
2389
                    $status_in_group = get_lang('GroupTutorAndMember');
2390
                } else {
2391
                    if ($is_tutor_of_group) {
2392
                        $status_in_group = get_lang('GroupTutor');
2393
                    } else {
2394
                        $status_in_group = " "; //get_lang('GroupStandardMember')
2395
                    }
2396
                }
2397
2398
                if ($assignment_type == 1) {
2399
                    $values['title'] = $title_orig;
2400
                    $values['content'] = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2401
                    <table border="0">
2402
                    <tr><td style="font-size:24px">'.get_lang('AssignmentWork').'</td></tr>
2403
                    <tr><td>'.$photo.'<br />'.$name.'</td></tr></table>
2404
                    </div>[['.$link2teacher.' | '.get_lang(
2405
                            'AssignmentLinktoTeacherPage'
2406
                        ).']] ';
2407
                    //If $content_orig_B is added here, the task written by the professor was copied to the page of each student. TODO: config options
2408
2409
                    // AssignmentLinktoTeacherPage
2410
                    $all_students_pages[] = '<li>'.
2411
                        Display::tag(
2412
                            'span',
2413
                            strtoupper(
2414
                                $o_user_to_add['lastname']
2415
                            ).', '.$o_user_to_add['firstname'],
2416
                            array('title' => $username)
2417
                        ).
2418
                        ' [['.Security::remove_XSS(
2419
                            $_POST['title']
2420
                        )."_uass".$assig_user_id.' | '.$photo.']] '.$status_in_group.'</li>';
2421
                    //don't change this line without guaranteeing that users will be ordered by last names in the following format (surname, name)
2422
                    $values['assignment'] = 2;
2423
                }
2424
                $this->assig_user_id = $assig_user_id;
2425
                self::save_new_wiki($values);
2426
            }
2427
        }
2428
2429
        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...
2430
            if ($o_user_to_add['user_id'] == $userId) {
2431
                $assig_user_id = $o_user_to_add['user_id'];
2432
                if ($assignment_type == 1) {
2433
                    $values['title'] = $title_orig;
2434
                    $values['comment'] = get_lang('AssignmentDesc');
2435
                    sort($all_students_pages);
2436
                    $values['content'] = $content_orig_A.$content_orig_B.'<br/>
2437
                    <div align="center" style="font-size:18px; background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2438
                    '.get_lang('AssignmentLinkstoStudentsPage').'
2439
                    </div><br/>
2440
                    <div style="background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2441
                    <ol>'.implode($all_students_pages).'</ol>
2442
                    </div>
2443
                    <br/>';
2444
                    $values['assignment'] = 1;
2445
                }
2446
                $this->assig_user_id = $assig_user_id;
2447
                self::save_new_wiki($values);
2448
            }
2449
        }
2450
    }
2451
2452
    /**
2453
     * Displays the results of a wiki search
2454
     * @param   string  Search term
2455
     * @param   int     Whether to search the contents (1) or just the titles (0)
2456
     * @param int
2457
     */
2458
    public function display_wiki_search_results(
2459
        $search_term,
2460
        $search_content = 0,
2461
        $all_vers = 0
2462
    ) {
2463
        $tbl_wiki = $this->tbl_wiki;
2464
        $condition_session = $this->condition_session;
2465
        $groupfilter = $this->groupfilter;
2466
        $_course = $this->courseInfo;
2467
        $course_id = api_get_course_int_id();
2468
        echo '<legend>'.get_lang('WikiSearchResults').': '.Security::remove_XSS(
2469
                $search_term
2470
            );
2471
        echo '</legend>';
2472
2473
        //only by professors when page is hidden
2474
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
2475 View Code Duplication
            if ($all_vers == '1') {
2476
                if ($search_content == '1') {
2477
                    $sql = "SELECT * FROM ".$tbl_wiki."
2478
                            WHERE
2479
                                c_id = $course_id AND
2480
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2481
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2482
                                ".$groupfilter.$condition_session."";
2483
                    //search all pages and all versions
2484
                } else {
2485
                    $sql = "SELECT * FROM ".$tbl_wiki."
2486
                            WHERE
2487
                                c_id = $course_id AND
2488
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2489
                                ".$groupfilter.$condition_session."";
2490
                    //search all pages and all versions
2491
                }
2492
            } else {
2493
                if ($search_content == '1') {
2494
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2495
                            WHERE
2496
                                s1.c_id = $course_id AND
2497
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2498
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2499
                                id=(
2500
                                    SELECT MAX(s2.id)
2501
                                    FROM ".$tbl_wiki." s2
2502
                                    WHERE
2503
                                        s2.c_id = $course_id AND
2504
                                        s1.reflink = s2.reflink AND
2505
                                        ".$groupfilter.$condition_session.")";
2506
                    // warning don't use group by reflink because don't return the last version
2507
                } else {
2508
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2509
                            WHERE
2510
                                s1.c_id = $course_id AND
2511
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2512
                                id = (
2513
                                    SELECT MAX(s2.id)
2514
                                    FROM ".$tbl_wiki." s2
2515
                                    WHERE
2516
                                        s2.c_id = $course_id AND
2517
                                        s1.reflink = s2.reflink AND
2518
                                        ".$groupfilter.$condition_session.")";
2519
                    // warning don't use group by reflink because don't return the last version
2520
                }
2521
            }
2522 View Code Duplication
        } else {
2523
            if ($all_vers == '1') {
2524
                if ($search_content == '1') {
2525
                    $sql = "SELECT * FROM ".$tbl_wiki."
2526
                            WHERE
2527
                                c_id = $course_id AND
2528
                                visibility=1 AND
2529
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2530
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2531
                                ".$groupfilter.$condition_session."";
2532
                    //search all pages and all versions
2533
                } else {
2534
                    $sql = "SELECT * FROM ".$tbl_wiki."
2535
                            WHERE
2536
                                c_id = $course_id AND
2537
                                visibility=1 AND
2538
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2539
                                ".$groupfilter.$condition_session."";
2540
                    //search all pages and all versions
2541
                }
2542
            } else {
2543
                if ($search_content == '1') {
2544
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2545
                            WHERE
2546
                                s1.c_id = $course_id AND
2547
                                visibility=1 AND
2548
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2549
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2550
                                id=(
2551
                                    SELECT MAX(s2.id)
2552
                                    FROM ".$tbl_wiki." s2
2553
                                    WHERE s2.c_id = $course_id AND
2554
                                    s1.reflink = s2.reflink AND
2555
                                    ".$groupfilter.$condition_session.")";
2556
                    // warning don't use group by reflink because don't return the last version
2557
                } else {
2558
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2559
                            WHERE
2560
                                s1.c_id = $course_id AND
2561
                                visibility=1 AND
2562
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2563
                            id = (
2564
                                SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
2565
                                WHERE s2.c_id = $course_id AND
2566
                                s1.reflink = s2.reflink AND
2567
                                ".$groupfilter.$condition_session.")";
2568
                    // warning don't use group by reflink because don't return the last version
2569
                }
2570
            }
2571
        }
2572
2573
        $result = Database::query($sql);
2574
2575
        //show table
2576
        $rows = array();
2577
        if (Database::num_rows($result) > 0) {
2578
            while ($obj = Database::fetch_object($result)) {
2579
                //get author
2580
                $userinfo = api_get_user_info($obj->user_id);
2581
2582
                //get time
2583
                $year = substr($obj->dtime, 0, 4);
2584
                $month = substr($obj->dtime, 5, 2);
2585
                $day = substr($obj->dtime, 8, 2);
2586
                $hours = substr($obj->dtime, 11, 2);
2587
                $minutes = substr($obj->dtime, 14, 2);
2588
                $seconds = substr($obj->dtime, 17, 2);
2589
2590
                //get type assignment icon
2591
                if ($obj->assignment == 1) {
2592
                    $ShowAssignment = Display::return_icon(
2593
                        'wiki_assignment.png',
2594
                        get_lang('AssignmentDesc'),
2595
                        '',
2596
                        ICON_SIZE_SMALL
2597
                    );
2598
                } elseif ($obj->assignment == 2) {
2599
                    $ShowAssignment = Display::return_icon(
2600
                        'wiki_work.png',
2601
                        get_lang('AssignmentWork'),
2602
                        '',
2603
                        ICON_SIZE_SMALL
2604
                    );
2605
                } elseif ($obj->assignment == 0) {
2606
                    $ShowAssignment = Display::return_icon(
2607
                        'px_transparent.gif'
2608
                    );
2609
                }
2610
                $row = array();
2611
                $row[] = $ShowAssignment;
2612
2613
                if ($all_vers == '1') {
2614
                    $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'])).'">'.
2615
                        api_htmlentities($obj->title).'</a>';
2616
                } else {
2617
                    $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']).'">'.
2618
                        $obj->title.'</a>';
2619
                }
2620
2621
                $row[] = ($obj->user_id != 0 && $userinfo !== false) ? UserManager::getUserProfileLink($userinfo) : get_lang('Anonymous').' ('.$obj->user_ip.')';
2622
                $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
2623
2624
                if ($all_vers == '1') {
2625
                    $row[] = $obj->version;
2626
                } else {
2627
                    $showdelete = '';
2628
                    if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
2629
                        $showdelete = ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=delete&title='.api_htmlentities(urlencode($obj->reflink)).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2630
                            Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
2631
                    }
2632
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit&title='.api_htmlentities(urlencode($obj->reflink)).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2633
                        Display::return_icon('edit.png', get_lang('EditPage'), '', ICON_SIZE_SMALL).'</a>
2634
                        <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']).'">'.
2635
                        Display::return_icon('discuss.png', get_lang('Discuss'), '', ICON_SIZE_SMALL).'</a>
2636
                        <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']).'">'.
2637
                        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']).'">'.
2638
                        Display::return_icon('what_link_here.png', get_lang('LinksPages'), '', ICON_SIZE_SMALL).'</a>'.$showdelete;
2639
                }
2640
                $rows[] = $row;
2641
            }
2642
2643
            $table = new SortableTableFromArrayConfig(
2644
                $rows,
2645
                1,
2646
                10,
2647
                'SearchPages_table',
2648
                '',
2649
                '',
2650
                'ASC'
2651
            );
2652
            $table->set_additional_parameters(
2653
                array(
2654
                    'cidReq' => $_GET['cidReq'],
2655
                    'action' => $_GET['action'],
2656
                    'group_id' => intval($_GET['group_id']),
2657
                    'mode_table' => 'yes2',
2658
                    'search_term' => $search_term,
2659
                    'search_content' => $search_content,
2660
                    'all_vers' => $all_vers,
2661
                )
2662
            );
2663
            $table->set_header(
2664
                0,
2665
                get_lang('Type'),
2666
                true,
2667
                array('style' => 'width:30px;')
2668
            );
2669
            $table->set_header(1, get_lang('Title'), true);
2670
            if ($all_vers == '1') {
2671
                $table->set_header(2, get_lang('Author'), true);
2672
                $table->set_header(3, get_lang('Date'), true);
2673
                $table->set_header(4, get_lang('Version'), true);
2674
            } else {
2675
                $table->set_header(
2676
                    2,
2677
                    get_lang('Author').' ('.get_lang('LastVersion').')',
2678
                    true
2679
                );
2680
                $table->set_header(
2681
                    3,
2682
                    get_lang('Date').' ('.get_lang('LastVersion').')',
2683
                    true
2684
                );
2685
                $table->set_header(
2686
                    4,
2687
                    get_lang('Actions'),
2688
                    false,
2689
                    array('style' => 'width:130px;')
2690
                );
2691
            }
2692
            $table->display();
2693
        } else {
2694
            echo get_lang('NoSearchResults');
2695
        }
2696
    }
2697
2698
    /**
2699
     * Returns a date picker
2700
     * @todo replace this function with the formvalidator datepicker
2701
     *
2702
     */
2703
    public function draw_date_picker($prefix, $default = '')
2704
    {
2705
        if (empty($default)) {
2706
            $default = date('Y-m-d H:i:s');
2707
        }
2708
        $parts = explode(' ', $default);
2709
        list($d_year, $d_month, $d_day) = explode('-', $parts[0]);
2710
        list($d_hour, $d_minute) = explode(':', $parts[1]);
2711
2712
        $month_list = array(
2713
            1 => get_lang('JanuaryLong'),
2714
            2 => get_lang('FebruaryLong'),
2715
            3 => get_lang('MarchLong'),
2716
            4 => get_lang('AprilLong'),
2717
            5 => get_lang('MayLong'),
2718
            6 => get_lang('JuneLong'),
2719
            7 => get_lang('JulyLong'),
2720
            8 => get_lang('AugustLong'),
2721
            9 => get_lang('SeptemberLong'),
2722
            10 => get_lang('OctoberLong'),
2723
            11 => get_lang('NovemberLong'),
2724
            12 => get_lang('DecemberLong'),
2725
        );
2726
2727
        $minute = range(10, 59);
2728
        array_unshift(
2729
            $minute,
2730
            '00',
2731
            '01',
2732
            '02',
2733
            '03',
2734
            '04',
2735
            '05',
2736
            '06',
2737
            '07',
2738
            '08',
2739
            '09'
2740
        );
2741
        $date_form = self::make_select(
2742
            $prefix.'_day',
2743
            array_combine(range(1, 31), range(1, 31)),
2744
            $d_day
2745
        );
2746
        $date_form .= self::make_select(
2747
            $prefix.'_month',
2748
            $month_list,
2749
            $d_month
2750
        );
2751
        $date_form .= self::make_select(
2752
                $prefix.'_year',
2753
                array(
2754
                    $d_year - 2 => $d_year - 2,
2755
                    $d_year - 1 => $d_year - 1,
2756
                    $d_year => $d_year,
2757
                    $d_year + 1 => $d_year + 1,
2758
                    $d_year + 2 => $d_year + 2,
2759
                ),
2760
                $d_year
2761
            ).'&nbsp;&nbsp;&nbsp;&nbsp;';
2762
        $date_form .= self::make_select(
2763
                $prefix.'_hour',
2764
                array_combine(range(0, 23), range(0, 23)),
2765
                $d_hour
2766
            ).' : ';
2767
        $date_form .= self::make_select($prefix.'_minute', $minute, $d_minute);
2768
2769
        return $date_form;
2770
    }
2771
2772
    /**
2773
     * Draws an HTML form select with the given options
2774
     *
2775
     */
2776
    public function make_select($name, $values, $checked = '')
2777
    {
2778
        $output = '<select name="'.$name.'" id="'.$name.'">';
2779
        foreach ($values as $key => $value) {
2780
            $output .= '<option value="'.$key.'" '.(($checked == $key) ? 'selected="selected"' : '').'>'.$value.'</option>';
2781
        }
2782
        $output .= '</select>';
2783
2784
        return $output;
2785
    }
2786
2787
    /**
2788
     * Translates a form date into a more usable format
2789
     *
2790
     */
2791
    public function get_date_from_select($prefix)
2792
    {
2793
        return $_POST[$prefix.'_year'].'-'.
2794
            self::two_digits($_POST[$prefix.'_month']).'-'.
2795
            self::two_digits($_POST[$prefix.'_day']).' '.
2796
            self::two_digits($_POST[$prefix.'_hour']).':'.
2797
            self::two_digits($_POST[$prefix.'_minute']).':00';
2798
    }
2799
2800
    /**
2801
     * Converts 1-9 to 01-09
2802
     */
2803
    public function two_digits($number)
2804
    {
2805
        $number = (int) $number;
2806
        return ($number < 10) ? '0'.$number : $number;
2807
    }
2808
2809
    /**
2810
     * Get wiki information
2811
     * @param   int|bool wiki id
2812
     * @return  array   wiki data
2813
     */
2814
    public function getWikiDataFromDb($id)
2815
    {
2816
        $tbl_wiki = $this->tbl_wiki;
2817
        $course_id = api_get_course_int_id();
2818
        if ($id === false) {
2819
            return array();
2820
        }
2821
        $id = intval($id);
2822
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2823
                WHERE c_id = '.$course_id.' AND id = '.$id.' ';
2824
        $result = Database::query($sql);
2825
        $data = array();
2826
        while ($row = Database::fetch_array($result, 'ASSOC')) {
2827
            $data = $row;
2828
        }
2829
2830
        return $data;
2831
    }
2832
2833
    /**
2834
     * @param string $refLink
2835
     * @return array
2836
     */
2837
    public function getLastWikiData($refLink)
2838
    {
2839
        $tbl_wiki = $this->tbl_wiki;
2840
        $groupfilter = $this->groupfilter;
2841
        $condition_session = $this->condition_session;
2842
        $course_id = api_get_course_int_id();
2843
2844
        $sql = 'SELECT * FROM '.$tbl_wiki.'
2845
                WHERE
2846
                    c_id = '.$course_id.' AND
2847
                    reflink="'.Database::escape_string($refLink).'" AND
2848
                    '.$groupfilter.$condition_session.'
2849
                ORDER BY id DESC';
2850
2851
        $result = Database::query($sql);
2852
2853
        return Database::fetch_array($result);
2854
    }
2855
2856
    /**
2857
     * Get wiki information
2858
     * @param   string     wiki id
2859
     * @param int $courseId
2860
     * @return  array   wiki data
2861
     */
2862
    public function getPageByTitle($title, $courseId = null)
2863
    {
2864
        $tbl_wiki = $this->tbl_wiki;
2865
        if (empty($courseId)) {
2866
            $courseId = api_get_course_int_id();
2867
        } else {
2868
            $courseId = intval($courseId);
2869
        }
2870
2871
        if (empty($title) || empty($courseId)) {
2872
            return array();
2873
        }
2874
2875
        $title = Database::escape_string($title);
2876
        $sql = "SELECT * FROM $tbl_wiki
2877
                WHERE c_id = $courseId AND reflink = '$title'";
2878
        $result = Database::query($sql);
2879
        $data = array();
2880
        if (Database::num_rows($result)) {
2881
            $data = Database::fetch_array($result, 'ASSOC');
2882
        }
2883
2884
        return $data;
2885
    }
2886
2887
    /**
2888
     * @param string $title
2889
     * @param int $courseId
2890
     * @param string
2891
     * @param string
2892
     * @return bool
2893
     */
2894
    public function deletePage(
2895
        $title,
2896
        $courseId,
2897
        $groupfilter = null,
2898
        $condition_session = null
2899
    ) {
2900
        $tbl_wiki = $this->tbl_wiki;
2901
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
2902
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
2903
        $tbl_wiki_conf = $this->tbl_wiki_conf;
2904
2905
        $pageInfo = self::getPageByTitle($title, $courseId);
2906
        if (!empty($pageInfo)) {
2907
            $pageId = $pageInfo['id'];
2908
            $sql = "DELETE FROM $tbl_wiki_conf
2909
                    WHERE c_id = $courseId AND page_id = $pageId";
2910
            Database::query($sql);
2911
2912
            $sql = 'DELETE FROM '.$tbl_wiki_discuss.'
2913
                    WHERE c_id = '.$courseId.' AND publication_id = '.$pageId;
2914
            Database::query($sql);
2915
2916
            $sql = 'DELETE FROM  '.$tbl_wiki_mailcue.'
2917
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
2918
            Database::query($sql);
2919
2920
            $sql = 'DELETE FROM '.$tbl_wiki.'
2921
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
2922
            Database::query($sql);
2923
            self::check_emailcue(0, 'E');
2924
2925
            return true;
2926
        }
2927
2928
        return false;
2929
    }
2930
2931
    /**
2932
     * @return array
2933
     */
2934
    public function getAllWiki()
2935
    {
2936
        $tbl_wiki = $this->tbl_wiki;
2937
        $course_id = $this->course_id;
2938
        $condition_session = $this->condition_session;
2939
2940
        $sql = "SELECT * FROM $tbl_wiki
2941
                WHERE
2942
                    c_id = $course_id AND
2943
                    is_editing != '0' ".$condition_session;
2944
        $result = Database::query($sql);
2945
2946
        return Database::store_result($result, 'ASSOC');
2947
    }
2948
2949
    /**
2950
     * @param int $isEditing
2951
     */
2952
    public function updateWikiIsEditing($isEditing)
2953
    {
2954
        $tbl_wiki = $this->tbl_wiki;
2955
        $course_id = $this->course_id;
2956
        $condition_session = $this->condition_session;
2957
        $isEditing = Database::escape_string($isEditing);
2958
2959
        $sql = 'UPDATE '.$tbl_wiki.' SET
2960
                is_editing = "0",
2961
                time_edit = NULL
2962
                WHERE
2963
                    c_id = '.$course_id.' AND
2964
                    is_editing="'.$isEditing.'" '.
2965
            $condition_session;
2966
        Database::query($sql);
2967
    }
2968
2969
    /**
2970
     * Release of blocked pages to prevent concurrent editions
2971
     * @param int $userId
2972
     * @param string $action
2973
     */
2974
    public function blockConcurrentEditions($userId, $action = null)
2975
    {
2976
        $result = self::getAllWiki();
2977
        if (!empty($result)) {
2978
            foreach ($result as $is_editing_block) {
2979
                $max_edit_time = 1200; // 20 minutes
2980
                $timestamp_edit = strtotime($is_editing_block['time_edit']);
2981
                $time_editing = time() - $timestamp_edit;
2982
2983
                // First prevent concurrent users and double version
2984
                if ($is_editing_block['is_editing'] == $userId) {
2985
                    Session::write('_version', $is_editing_block['version']);
2986
                } else {
2987
                    Session::erase('_version');
2988
                }
2989
                // Second checks if has exceeded the time that a page may be available or if a page was edited and saved by its author
2990
                if ($time_editing > $max_edit_time || ($is_editing_block['is_editing'] == $userId && $action != 'edit')) {
2991
                    self::updateWikiIsEditing($is_editing_block['is_editing']);
2992
                }
2993
            }
2994
        }
2995
    }
2996
2997
    /**
2998
     * Showing wiki stats
2999
     */
3000
    public function getStats()
3001
    {
3002
        if (!api_is_allowed_to_edit(false, true)) {
3003
            return false;
3004
        }
3005
3006
        $tbl_wiki = $this->tbl_wiki;
3007
        $course_id = $this->course_id;
3008
        $condition_session = $this->condition_session;
3009
        $groupfilter = $this->groupfilter;
3010
        $session_id = $this->session_id;
3011
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3012
3013
        echo '<div class="actions">'.get_lang('Statistics').'</div>';
3014
3015
        // Check all versions of all pages
3016
        $total_words = 0;
3017
        $total_links = 0;
3018
        $total_links_anchors = 0;
3019
        $total_links_mail = 0;
3020
        $total_links_ftp = 0;
3021
        $total_links_irc = 0;
3022
        $total_links_news = 0;
3023
        $total_wlinks = 0;
3024
        $total_images = 0;
3025
        $clean_total_flash = 0;
3026
        $total_flash = 0;
3027
        $total_mp3 = 0;
3028
        $total_flv_p = 0;
3029
        $total_flv = 0;
3030
        $total_youtube = 0;
3031
        $total_multimedia = 0;
3032
        $total_tables = 0;
3033
3034
        $sql = "SELECT *, COUNT(*) AS TOTAL_VERS, SUM(hits) AS TOTAL_VISITS
3035
                FROM ".$tbl_wiki."
3036
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3037
3038
        $allpages = Database::query($sql);
3039
        while ($row = Database::fetch_array($allpages)) {
3040
            $total_versions = $row['TOTAL_VERS'];
3041
            $total_visits = intval($row['TOTAL_VISITS']);
3042
        }
3043
3044
        $sql = "SELECT * FROM ".$tbl_wiki."
3045
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3046
        $allpages = Database::query($sql);
3047
3048 View Code Duplication
        while ($row = Database::fetch_array($allpages)) {
3049
            $total_words = $total_words + self::word_count($row['content']);
3050
            $total_links = $total_links + substr_count($row['content'], "href=");
3051
            $total_links_anchors = $total_links_anchors + substr_count($row['content'], 'href="#');
3052
            $total_links_mail = $total_links_mail + substr_count($row['content'], 'href="mailto');
3053
            $total_links_ftp = $total_links_ftp + substr_count($row['content'], 'href="ftp');
3054
            $total_links_irc = $total_links_irc + substr_count($row['content'], 'href="irc');
3055
            $total_links_news = $total_links_news + substr_count($row['content'], 'href="news');
3056
            $total_wlinks = $total_wlinks + substr_count($row['content'], "[[");
3057
            $total_images = $total_images + substr_count($row['content'], "<img");
3058
            $clean_total_flash = preg_replace('/player.swf/', ' ', $row['content']);
3059
            $total_flash = $total_flash + substr_count($clean_total_flash, '.swf"');
3060
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3061
            $total_mp3 = $total_mp3 + substr_count($row['content'], ".mp3");
3062
            $total_flv_p = $total_flv_p + substr_count($row['content'], ".flv");
3063
            $total_flv = $total_flv_p / 5;
3064
            $total_youtube = $total_youtube + substr_count($row['content'], "http://www.youtube.com");
3065
            $total_multimedia = $total_multimedia + substr_count($row['content'], "video/x-msvideo");
3066
            $total_tables = $total_tables + substr_count($row['content'], "<table");
3067
        }
3068
3069
        // Check only last version of all pages (current page)
3070
        $sql = ' SELECT *, COUNT(*) AS TOTAL_PAGES, SUM(hits) AS TOTAL_VISITS_LV
3071
                FROM  '.$tbl_wiki.' s1
3072
                WHERE s1.c_id = '.$course_id.' AND id=(
3073
                    SELECT MAX(s2.id)
3074
                    FROM '.$tbl_wiki.' s2
3075
                    WHERE
3076
                        s2.c_id = '.$course_id.' AND
3077
                        s1.reflink = s2.reflink AND
3078
                        '.$groupfilter.' AND
3079
                        session_id='.$session_id.')';
3080
        $allpages = Database::query($sql);
3081
        while ($row = Database::fetch_array($allpages)) {
3082
            $total_pages = $row['TOTAL_PAGES'];
3083
            $total_visits_lv = intval($row['TOTAL_VISITS_LV']);
3084
        }
3085
3086
        $total_words_lv = 0;
3087
        $total_links_lv = 0;
3088
        $total_links_anchors_lv = 0;
3089
        $total_links_mail_lv = 0;
3090
        $total_links_ftp_lv = 0;
3091
        $total_links_irc_lv = 0;
3092
        $total_links_news_lv = 0;
3093
        $total_wlinks_lv = 0;
3094
        $total_images_lv = 0;
3095
        $clean_total_flash_lv = 0;
3096
        $total_flash_lv = 0;
3097
        $total_mp3_lv = 0;
3098
        $total_flv_p_lv = 0;
3099
        $total_flv_lv = 0;
3100
        $total_youtube_lv = 0;
3101
        $total_multimedia_lv = 0;
3102
        $total_tables_lv = 0;
3103
3104
        $sql = 'SELECT * FROM  '.$tbl_wiki.' s1
3105
                WHERE s1.c_id = '.$course_id.' AND id=(
3106
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3107
                    WHERE
3108
                        s2.c_id = '.$course_id.' AND
3109
                        s1.reflink = s2.reflink AND
3110
                        '.$groupfilter.' AND
3111
                        session_id='.$session_id.'
3112
                )';
3113
        $allpages = Database::query($sql);
3114
3115 View Code Duplication
        while ($row = Database::fetch_array($allpages)) {
3116
            $total_words_lv = $total_words_lv + self::word_count($row['content']);
3117
            $total_links_lv = $total_links_lv + substr_count($row['content'], "href=");
3118
            $total_links_anchors_lv = $total_links_anchors_lv + substr_count($row['content'], 'href="#');
3119
            $total_links_mail_lv = $total_links_mail_lv + substr_count($row['content'], 'href="mailto');
3120
            $total_links_ftp_lv = $total_links_ftp_lv + substr_count($row['content'], 'href="ftp');
3121
            $total_links_irc_lv = $total_links_irc_lv + substr_count($row['content'], 'href="irc');
3122
            $total_links_news_lv = $total_links_news_lv + substr_count($row['content'], 'href="news');
3123
            $total_wlinks_lv = $total_wlinks_lv + substr_count($row['content'], "[[");
3124
            $total_images_lv = $total_images_lv + substr_count($row['content'], "<img");
3125
            $clean_total_flash_lv = preg_replace('/player.swf/', ' ', $row['content']);
3126
            $total_flash_lv = $total_flash_lv + substr_count($clean_total_flash_lv, '.swf"');
3127
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3128
            $total_mp3_lv = $total_mp3_lv + substr_count($row['content'], ".mp3");
3129
            $total_flv_p_lv = $total_flv_p_lv + substr_count($row['content'], ".flv");
3130
            $total_flv_lv = $total_flv_p_lv / 5;
3131
            $total_youtube_lv = $total_youtube_lv + substr_count($row['content'], "http://www.youtube.com");
3132
            $total_multimedia_lv = $total_multimedia_lv + substr_count($row['content'], "video/x-msvideo");
3133
            $total_tables_lv = $total_tables_lv + substr_count($row['content'], "<table");
3134
        }
3135
3136
        //Total pages edited at this time
3137
        $total_editing_now = 0;
3138
        $sql = 'SELECT *, COUNT(*) AS TOTAL_EDITING_NOW
3139
                FROM  '.$tbl_wiki.' s1
3140
                WHERE is_editing!=0 AND s1.c_id = '.$course_id.' AND
3141
                id=(
3142
                    SELECT MAX(s2.id)
3143
                    FROM '.$tbl_wiki.' s2
3144
                    WHERE
3145
                        s2.c_id = '.$course_id.' AND
3146
                        s1.reflink = s2.reflink AND
3147
                        '.$groupfilter.' AND
3148
                        session_id='.$session_id.'
3149
        )';
3150
3151
        // Can not use group by because the mark is set in the latest version
3152
        $allpages = Database::query($sql);
3153
        while ($row = Database::fetch_array($allpages)) {
3154
            $total_editing_now = $row['TOTAL_EDITING_NOW'];
3155
        }
3156
3157
        // Total hidden pages
3158
        $total_hidden = 0;
3159
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3160
                WHERE  
3161
                    c_id = '.$course_id.' AND 
3162
                    visibility = 0 AND 
3163
                    '.$groupfilter.$condition_session.'
3164
                GROUP BY reflink';
3165
        // or group by page_id. As the mark of hidden places it in all
3166
        // versions of the page, I can use group by to see the first
3167
        $allpages = Database::query($sql);
3168
        while ($row = Database::fetch_array($allpages)) {
3169
            $total_hidden = $total_hidden + 1;
3170
        }
3171
3172
        //Total protect pages
3173
        $total_protected = 0;
3174
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3175
                WHERE  c_id = '.$course_id.' AND editlock=1 AND '.$groupfilter.$condition_session.'
3176
                GROUP BY reflink';
3177
        // or group by page_id. As the mark of protected page is the first version of the page, I can use group by
3178
        $allpages = Database::query($sql);
3179
        while ($row = Database::fetch_array($allpages)) {
3180
            $total_protected = $total_protected + 1;
3181
        }
3182
3183
        // Total empty versions.
3184
        $total_empty_content = 0;
3185
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3186
                WHERE
3187
                    c_id = '.$course_id.' AND
3188
                    content="" AND
3189
                    '.$groupfilter.$condition_session.'';
3190
        $allpages = Database::query($sql);
3191
        while ($row = Database::fetch_array($allpages)) {
3192
            $total_empty_content = $total_empty_content + 1;
3193
        }
3194
3195
        //Total empty pages (last version)
3196
3197
        $total_empty_content_lv = 0;
3198
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3199
                WHERE s1.c_id = '.$course_id.' AND content="" AND id=(
3200
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3201
                    WHERE 
3202
                        s1.c_id = '.$course_id.' AND 
3203
                        s1.reflink = s2.reflink AND 
3204
                        '.$groupfilter.' AND 
3205
                        session_id='.$session_id.'
3206
                )';
3207
        $allpages = Database::query($sql);
3208
        while ($row = Database::fetch_array($allpages)) {
3209
            $total_empty_content_lv = $total_empty_content_lv + 1;
3210
        }
3211
3212
        // Total locked discuss pages
3213
        $total_lock_disc = 0;
3214
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3215
                WHERE c_id = '.$course_id.' AND addlock_disc=0 AND '.$groupfilter.$condition_session.'
3216
                GROUP BY reflink';//group by because mark lock in all vers, then always is ok
3217
        $allpages = Database::query($sql);
3218
        while ($row = Database::fetch_array($allpages)) {
3219
            $total_lock_disc = $total_lock_disc + 1;
3220
        }
3221
3222
        // Total hidden discuss pages.
3223
        $total_hidden_disc = 0;
3224
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3225
                WHERE c_id = '.$course_id.' AND visibility_disc=0 AND '.$groupfilter.$condition_session.'
3226
                GROUP BY reflink';
3227
        //group by because mark lock in all vers, then always is ok
3228
        $allpages = Database::query($sql);
3229
        while ($row = Database::fetch_array($allpages)) {
3230
            $total_hidden_disc = $total_hidden_disc + 1;
3231
        }
3232
3233
        // Total versions with any short comment by user or system
3234
        $total_comment_version = 0;
3235
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3236
                WHERE c_id = '.$course_id.' AND comment!="" AND '.$groupfilter.$condition_session.'';
3237
        $allpages = Database::query($sql);
3238
        while ($row = Database::fetch_array($allpages)) {
3239
            $total_comment_version = $total_comment_version + 1;
3240
        }
3241
3242
        // Total pages that can only be scored by teachers.
3243
        $total_only_teachers_rating = 0;
3244
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3245
                WHERE c_id = '.$course_id.' AND
3246
                ratinglock_disc = 0 AND
3247
                '.$groupfilter.$condition_session.'
3248
                GROUP BY reflink';//group by because mark lock in all vers, then always is ok
3249
        $allpages = Database::query($sql);
3250
        while ($row = Database::fetch_array($allpages)) {
3251
            $total_only_teachers_rating = $total_only_teachers_rating + 1;
3252
        }
3253
3254
        // Total pages scored by peers
3255
        // put always this line alfter check num all pages and num pages rated by teachers
3256
        $total_rating_by_peers = $total_pages - $total_only_teachers_rating;
3257
3258
        //Total pages identified as standard task
3259
        $total_task = 0;
3260
        $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
3261
              WHERE '.$tbl_wiki_conf.'.c_id = '.$course_id.' AND
3262
               '.$tbl_wiki_conf.'.task!="" AND
3263
               '.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
3264
                '.$tbl_wiki.'.'.$groupfilter.$condition_session;
3265
        $allpages = Database::query($sql);
3266
        while ($row = Database::fetch_array($allpages)) {
3267
            $total_task = $total_task + 1;
3268
        }
3269
3270
        //Total pages identified as teacher page (wiki portfolio mode - individual assignment)
3271
        $total_teacher_assignment = 0;
3272
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3273
                WHERE s1.c_id = '.$course_id.' AND assignment=1 AND id=(
3274
                    SELECT MAX(s2.id)
3275
                    FROM '.$tbl_wiki.' s2
3276
                    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.' AND session_id='.$session_id.'
3277
                )';
3278
        //mark all versions, but do not use group by reflink because y want the pages not versions
3279
        $allpages = Database::query($sql);
3280
        while ($row = Database::fetch_array($allpages)) {
3281
            $total_teacher_assignment = $total_teacher_assignment + 1;
3282
        }
3283
3284
        //Total pages identifies as student page (wiki portfolio mode - individual assignment)
3285
        $total_student_assignment = 0;
3286
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3287
                WHERE s1.c_id = '.$course_id.' AND assignment=2 AND
3288
                id=(SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3289
                WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.' AND session_id='.$session_id.')';
3290
        //mark all versions, but do not use group by reflink because y want the pages not versions
3291
        $allpages = Database::query($sql);
3292
        while ($row = Database::fetch_array($allpages)) {
3293
            $total_student_assignment = $total_student_assignment + 1;
3294
        }
3295
3296
        //Current Wiki status add new pages
3297
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3298
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3299
                GROUP BY addlock';//group by because mark 0 in all vers, then always is ok
3300
        $allpages = Database::query($sql);
3301
        $wiki_add_lock = null;
3302
        while ($row = Database::fetch_array($allpages)) {
3303
            $wiki_add_lock = $row['addlock'];
3304
        }
3305
3306
        if ($wiki_add_lock == 1) {
3307
            $status_add_new_pag = get_lang('Yes');
3308
        } else {
3309
            $status_add_new_pag = get_lang('No');
3310
        }
3311
3312
        //Creation date of the oldest wiki page and version
3313
3314
        $first_wiki_date = null;
3315
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3316
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3317
                ORDER BY dtime ASC 
3318
                LIMIT 1';
3319
        $allpages = Database::query($sql);
3320
        while ($row = Database::fetch_array($allpages)) {
3321
            $first_wiki_date = $row['dtime'];
3322
        }
3323
3324
        // Date of publication of the latest wiki version.
3325
3326
        $last_wiki_date = null;
3327
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3328
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3329
                ORDER BY dtime DESC 
3330
                LIMIT 1';
3331
        $allpages = Database::query($sql);
3332
        while ($row = Database::fetch_array($allpages)) {
3333
            $last_wiki_date = $row['dtime'];
3334
        }
3335
3336
        // Average score of all wiki pages. (If a page has not scored zero rated)
3337
        $media_score = 0;
3338
        $sql = "SELECT *, SUM(score) AS TOTAL_SCORE FROM ".$tbl_wiki."
3339
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."
3340
                GROUP BY reflink ";
3341
        //group by because mark in all versions, then always is ok.
3342
        // Do not use "count" because using "group by", would give a wrong value
3343
        $allpages = Database::query($sql);
3344
        $total_score = 0;
3345
        while ($row = Database::fetch_array($allpages)) {
3346
            $total_score = $total_score + $row['TOTAL_SCORE'];
3347
        }
3348
3349
        if (!empty($total_pages)) {
3350
            $media_score = $total_score / $total_pages;
3351
            //put always this line alfter check num all pages
3352
        }
3353
3354
        // Average user progress in his pages.
3355
        $media_progress = 0;
3356
        $sql = 'SELECT  *, SUM(progress) AS TOTAL_PROGRESS
3357
                FROM  '.$tbl_wiki.' s1
3358
                WHERE s1.c_id = '.$course_id.' AND id=
3359
                (
3360
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3361
                    WHERE
3362
                        s2.c_id = '.$course_id.' AND
3363
                        s1.reflink = s2.reflink AND
3364
                        '.$groupfilter.' AND
3365
                        session_id='.$session_id.')';
3366
        // As the value is only the latest version I can not use group by
3367
        $allpages = Database::query($sql);
3368
        while ($row = Database::fetch_array($allpages)) {
3369
            $total_progress = $row['TOTAL_PROGRESS'];
3370
        }
3371
3372
        if (!empty($total_pages)) {
3373
            $media_progress = $total_progress / $total_pages;
3374
            //put always this line alfter check num all pages
3375
        }
3376
3377
        // Total users that have participated in the Wiki
3378
        $total_users = 0;
3379
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3380
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3381
                GROUP BY user_id';
3382
        //as the mark of user it in all versions of the page, I can use group by to see the first
3383
        $allpages = Database::query($sql);
3384
        while ($row = Database::fetch_array($allpages)) {
3385
            $total_users = $total_users + 1;
3386
        }
3387
3388
        // Total of different IP addresses that have participated in the wiki
3389
        $total_ip = 0;
3390
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3391
              WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3392
              GROUP BY user_ip';
3393
        $allpages = Database::query($sql);
3394
        while ($row = Database::fetch_array($allpages)) {
3395
            $total_ip = $total_ip + 1;
3396
        }
3397
3398
        echo '<table class="data_table">';
3399
        echo '<thead>';
3400
        echo '<tr>';
3401
        echo '<th colspan="2">'.get_lang('General').'</th>';
3402
        echo '</tr>';
3403
        echo '</thead>';
3404
        echo '<tr>';
3405
        echo '<td>'.get_lang('StudentAddNewPages').'</td>';
3406
        echo '<td>'.$status_add_new_pag.'</td>';
3407
        echo '</tr>';
3408
        echo '<tr>';
3409
        echo '<td>'.get_lang('DateCreateOldestWikiPage').'</td>';
3410
        echo '<td>'.$first_wiki_date.'</td>';
3411
        echo '</tr>';
3412
        echo '<tr>';
3413
        echo '<td>'.get_lang('DateEditLatestWikiVersion').'</td>';
3414
        echo '<td>'.$last_wiki_date.'</td>';
3415
        echo '</tr>';
3416
        echo '<tr>';
3417
        echo '<td>'.get_lang('AverageScoreAllPages').'</td>';
3418
        echo '<td>'.$media_score.' %</td>';
3419
        echo '</tr>';
3420
        echo '<tr>';
3421
        echo '<td>'.get_lang('AverageMediaUserProgress').'</td>';
3422
        echo '<td>'.$media_progress.' %</td>';
3423
        echo '</tr>';
3424
        echo '<tr>';
3425
        echo '<td>'.get_lang('TotalWikiUsers').'</td>';
3426
        echo '<td>'.$total_users.'</td>';
3427
        echo '</tr>';
3428
        echo '<tr>';
3429
        echo '<td>'.get_lang('TotalIpAdress').'</td>';
3430
        echo '<td>'.$total_ip.'</td>';
3431
        echo '</tr>';
3432
        echo '</table>';
3433
        echo '<br/>';
3434
3435
        echo '<table class="data_table">';
3436
        echo '<thead>';
3437
        echo '<tr>';
3438
        echo '<th colspan="2">'.get_lang('Pages').' '.get_lang('And').' '.get_lang('Versions').'</th>';
3439
        echo '</tr>';
3440
        echo '</thead>';
3441
        echo '<tr>';
3442
        echo '<td>'.get_lang('Pages').' - '.get_lang('NumContributions').'</td>';
3443
        echo '<td>'.$total_pages.' ('.get_lang('Versions').': '.$total_versions.')</td>';
3444
        echo '</tr>';
3445
        echo '<tr>';
3446
        echo '<td>'.get_lang('EmptyPages').'</td>';
3447
        echo '<td>'.$total_empty_content_lv.' ('.get_lang('Versions').': '.$total_empty_content.')</td>';
3448
        echo '</tr>';
3449
        echo '<tr>';
3450
        echo '<td>'.get_lang('NumAccess').'</td>';
3451
        echo '<td>'.$total_visits_lv.' ('.get_lang('Versions').': '.$total_visits.')</td>';
3452
        echo '</tr>';
3453
        echo '<tr>';
3454
        echo '<td>'.get_lang('TotalPagesEditedAtThisTime').'</td>';
3455
        echo '<td>'.$total_editing_now.'</td>';
3456
        echo '</tr>';
3457
        echo '<tr>';
3458
        echo '<td>'.get_lang('TotalHiddenPages').'</td>';
3459
        echo '<td>'.$total_hidden.'</td>';
3460
        echo '</tr>';
3461
        echo '<tr>';
3462
        echo '<td>'.get_lang('NumProtectedPages').'</td>';
3463
        echo '<td>'.$total_protected.'</td>';
3464
        echo '</tr>';
3465
        echo '<tr>';
3466
        echo '<td>'.get_lang('LockedDiscussPages').'</td>';
3467
        echo '<td>'.$total_lock_disc.'</td>';
3468
        echo '</tr>';
3469
        echo '<tr>';
3470
        echo '<td>'.get_lang('HiddenDiscussPages').'</td>';
3471
        echo '<td>'.$total_hidden_disc.'</td>';
3472
        echo '</tr>';
3473
        echo '<tr>';
3474
        echo '<td>'.get_lang('TotalComments').'</td>';
3475
        echo '<td>'.$total_comment_version.'</td>';
3476
        echo '</tr>';
3477
        echo '<tr>';
3478
        echo '<td>'.get_lang('TotalOnlyRatingByTeacher').'</td>';
3479
        echo '<td>'.$total_only_teachers_rating.'</td>';
3480
        echo '</tr>';
3481
        echo '<tr>';
3482
        echo '<td>'.get_lang('TotalRatingPeers').'</td>';
3483
        echo '<td>'.$total_rating_by_peers.'</td>';
3484
        echo '</tr>';
3485
        echo '<tr>';
3486
        echo '<td>'.get_lang('TotalTeacherAssignments').' - '.get_lang('PortfolioMode').'</td>';
3487
        echo '<td>'.$total_teacher_assignment.'</td>';
3488
        echo '</tr>';
3489
        echo '<tr>';
3490
        echo '<td>'.get_lang('TotalStudentAssignments').' - '.get_lang('PortfolioMode').'</td>';
3491
        echo '<td>'.$total_student_assignment.'</td>';
3492
        echo '</tr>';
3493
        echo '<tr>';
3494
        echo '<td>'.get_lang('TotalTask').' - '.get_lang('StandardMode').'</td>';
3495
        echo '<td>'.$total_task.'</td>';
3496
        echo '</tr>';
3497
        echo '</table>';
3498
        echo '<br/>';
3499
3500
        echo '<table class="data_table">';
3501
        echo '<thead>';
3502
        echo '<tr>';
3503
        echo '<th colspan="3">'.get_lang('ContentPagesInfo').'</th>';
3504
        echo '</tr>';
3505
        echo '<tr>';
3506
        echo '<td></td>';
3507
        echo '<td>'.get_lang('InTheLastVersion').'</td>';
3508
        echo '<td>'.get_lang('InAllVersions').'</td>';
3509
        echo '</tr>';
3510
        echo '</thead>';
3511
        echo '<tr>';
3512
        echo '<td>'.get_lang('NumWords').'</td>';
3513
        echo '<td>'.$total_words_lv.'</td>';
3514
        echo '<td>'.$total_words.'</td>';
3515
        echo '</tr>';
3516
        echo '<tr>';
3517
        echo '<td>'.get_lang('NumlinksHtmlImagMedia').'</td>';
3518
        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>';
3519
        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>';
3520
        echo '</tr>';
3521
        echo '<tr>';
3522
        echo '<td>'.get_lang('NumWikilinks').'</td>';
3523
        echo '<td>'.$total_wlinks_lv.'</td>';
3524
        echo '<td>'.$total_wlinks.'</td>';
3525
        echo '</tr>';
3526
        echo '<tr>';
3527
        echo '<td>'.get_lang('NumImages').'</td>';
3528
        echo '<td>'.$total_images_lv.'</td>';
3529
        echo '<td>'.$total_images.'</td>';
3530
        echo '</tr>';
3531
        echo '<tr>';
3532
        echo '<td>'.get_lang('NumFlash').'</td>';
3533
        echo '<td>'.$total_flash_lv.'</td>';
3534
        echo '<td>'.$total_flash.'</td>';
3535
        echo '</tr>';
3536
        echo '<tr>';
3537
        echo '<td>'.get_lang('NumMp3').'</td>';
3538
        echo '<td>'.$total_mp3_lv.'</td>';
3539
        echo '<td>'.$total_mp3.'</td>';
3540
        echo '</tr>';
3541
        echo '<tr>';
3542
        echo '<td>'.get_lang('NumFlvVideo').'</td>';
3543
        echo '<td>'.$total_flv_lv.'</td>';
3544
        echo '<td>'.$total_flv.'</td>';
3545
        echo '</tr>';
3546
        echo '<tr>';
3547
        echo '<td>'.get_lang('NumYoutubeVideo').'</td>';
3548
        echo '<td>'.$total_youtube_lv.'</td>';
3549
        echo '<td>'.$total_youtube.'</td>';
3550
        echo '</tr>';
3551
        echo '<tr>';
3552
        echo '<td>'.get_lang('NumOtherAudioVideo').'</td>';
3553
        echo '<td>'.$total_multimedia_lv.'</td>';
3554
        echo '<td>'.$total_multimedia.'</td>';
3555
        echo '</tr>';
3556
        echo '<tr>';
3557
        echo '<td>'.get_lang('NumTables').'</td>';
3558
        echo '<td>'.$total_tables_lv.'</td>';
3559
        echo '<td>'.$total_tables.'</td>';
3560
        echo '</tr>';
3561
        echo '</table>';
3562
    }
3563
3564
    /**
3565
     * @param string $action
3566
     */
3567
    public function getActiveUsers($action)
3568
    {
3569
        $tbl_wiki = $this->tbl_wiki;
3570
        $course_id = $this->course_id;
3571
        $condition_session = $this->condition_session;
3572
        $groupfilter = $this->groupfilter;
3573
        $_course = $this->courseInfo;
3574
3575
        echo '<div class="actions">'.get_lang('MostActiveUsers').'</div>';
3576
        $sql = 'SELECT *, COUNT(*) AS NUM_EDIT FROM '.$tbl_wiki.'
3577
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3578
                GROUP BY user_id';
3579
        $allpages = Database::query($sql);
3580
3581
        //show table
3582
        if (Database::num_rows($allpages) > 0) {
3583
            while ($obj = Database::fetch_object($allpages)) {
3584
                $userinfo = api_get_user_info($obj->user_id);
3585
                $row = array();
3586
                if ($obj->user_id != 0 && $userinfo !== false) {
3587
                    $row[] = UserManager::getUserProfileLink($userinfo).'
3588
                            <a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode($obj->user_id).
3589
                        '&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'"></a>';
3590
                } else {
3591
                    $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
3592
                }
3593
                $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>';
3594
                $rows[] = $row;
3595
            }
3596
3597
            $table = new SortableTableFromArrayConfig($rows, 1, 10, 'MostActiveUsersA_table', '', '', 'DESC');
3598
            $table->set_additional_parameters(
3599
                array(
3600
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
3601
                    'action' => Security::remove_XSS($action),
3602
                    'session_id' => Security::remove_XSS($_GET['session_id']),
3603
                    'group_id' => Security::remove_XSS($_GET['group_id'])
3604
                )
3605
            );
3606
            $table->set_header(0, get_lang('Author'), true);
3607
            $table->set_header(
3608
                1,
3609
                get_lang('Contributions'),
3610
                true,
3611
                array('style' => 'width:30px;')
3612
            );
3613
            $table->display();
3614
        }
3615
    }
3616
3617
    /**
3618
     * @param string $page
3619
     */
3620
    public function getDiscuss($page)
3621
    {
3622
        $tbl_wiki = $this->tbl_wiki;
3623
        $course_id = $this->course_id;
3624
        $condition_session = $this->condition_session;
3625
        $groupfilter = $this->groupfilter;
3626
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
3627
3628 View Code Duplication
        if (api_get_session_id() != 0 &&
3629
            api_is_allowed_to_session_edit(false, true) == false
3630
        ) {
3631
            api_not_allowed();
3632
        }
3633
3634 View Code Duplication
        if (!$_GET['title']) {
3635
            Display::addFlash(
3636
                Display::return_message(
3637
                    get_lang("MustSelectPage"),
3638
                    'error',
3639
                    false
3640
                )
3641
            );
3642
3643
            return;
3644
        }
3645
3646
        // First extract the date of last version
3647
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3648
                WHERE
3649
                    c_id = '.$course_id.' AND
3650
                    reflink = "'.Database::escape_string($page).'" AND
3651
                    '.$groupfilter.$condition_session.'
3652
                ORDER BY id DESC';
3653
        $result = Database::query($sql);
3654
        $row = Database::fetch_array($result);
3655
        $lastversiondate = api_get_local_time($row['dtime']);
3656
        $lastuserinfo = api_get_user_info($row['user_id']);
3657
3658
        // Select page to discuss
3659
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3660
                WHERE
3661
                    c_id = '.$course_id.' AND
3662
                    reflink="'.Database::escape_string($page).'" AND
3663
                    '.$groupfilter.$condition_session.'
3664
                ORDER BY id ASC';
3665
        $result = Database::query($sql);
3666
        $row = Database::fetch_array($result);
3667
        $id = $row['id'];
3668
        $firstuserid = $row['user_id'];
3669
3670
        if (isset($_POST['Submit']) && self::double_post($_POST['wpost_id'])) {
3671
            $dtime = api_get_utc_datetime();
3672
            $message_author = api_get_user_id();
3673
3674
            $params = [
3675
                'c_id' => $course_id,
3676
                'publication_id' => $id,
3677
                'userc_id' => $message_author,
3678
                'comment' => $_POST['comment'],
3679
                'p_score' => $_POST['rating'],
3680
                'dtime' => $dtime
3681
            ];
3682
            $discussId = Database::insert($tbl_wiki_discuss, $params);
3683
            if ($discussId) {
3684
                $sql = "UPDATE $tbl_wiki_discuss SET id = iid WHERE iid = $discussId";
3685
                Database::query($sql);
3686
            }
3687
3688
            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 3671 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...
3689
3690
            header('Location: index.php?action=discuss&title='.api_htmlentities(urlencode($page)).'&'.api_get_cidreq());
3691
            exit;
3692
        }
3693
3694
        //mode assignment: previous to show  page type
3695
        $icon_assignment = null;
3696 View Code Duplication
        if ($row['assignment'] == 1) {
3697
            $icon_assignment = Display::return_icon(
3698
                'wiki_assignment.png',
3699
                get_lang('AssignmentDescExtra'),
3700
                '',
3701
                ICON_SIZE_SMALL
3702
            );
3703
        } elseif ($row['assignment'] == 2) {
3704
            $icon_assignment = Display::return_icon(
3705
                'wiki_work.png',
3706
                get_lang('AssignmentWorkExtra'),
3707
                '',
3708
                ICON_SIZE_SMALL
3709
            );
3710
        }
3711
3712
        $countWPost = null;
3713
        $avg_WPost_score = null;
3714
3715
3716
        // Show title and form to discuss if page exist
3717
        if ($id != '') {
3718
            // Show discussion to students if isn't hidden.
3719
            // Show page to all teachers if is hidden.
3720
            // Mode assignments: If is hidden, show pages to student only if student is the author
3721
            if ($row['visibility_disc'] == 1 ||
3722
                api_is_allowed_to_edit(false, true) ||
3723
                api_is_platform_admin() ||
3724
                ($row['assignment'] == 2 && $row['visibility_disc'] == 0 && (api_get_user_id() == $row['user_id']))
3725
            ) {
3726
                echo '<div id="wikititle">';
3727
                // discussion action: protecting (locking) the discussion
3728
                $addlock_disc = null;
3729
                $lock_unlock_disc = null;
3730 View Code Duplication
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3731
                    if (self::check_addlock_discuss() == 1) {
3732
                        $addlock_disc = Display::return_icon(
3733
                            'unlock.png',
3734
                            get_lang('UnlockDiscussExtra'),
3735
                            '',
3736
                            ICON_SIZE_SMALL
3737
                        );
3738
                        $lock_unlock_disc = 'unlockdisc';
3739
                    } else {
3740
                        $addlock_disc = Display::return_icon(
3741
                            'lock.png',
3742
                            get_lang('LockDiscussExtra'),
3743
                            '',
3744
                            ICON_SIZE_SMALL
3745
                        );
3746
                        $lock_unlock_disc = 'lockdisc';
3747
                    }
3748
                }
3749
                echo '<span style="float:right">';
3750
                echo '<a href="index.php?action=discuss&actionpage='.$lock_unlock_disc.'&title='.api_htmlentities(urlencode($page)).'">'.$addlock_disc.'</a>';
3751
                echo '</span>';
3752
3753
                // discussion action: visibility.  Show discussion to students if isn't hidden. Show page to all teachers if is hidden.
3754
                $visibility_disc = null;
3755
                $hide_show_disc = null;
3756 View Code Duplication
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3757
                    if (self::check_visibility_discuss() == 1) {
3758
                        /// TODO: 	Fix Mode assignments: If is hidden, show discussion to student only if student is the author
3759
                        $visibility_disc = Display::return_icon('visible.png', get_lang('ShowDiscussExtra'), '', ICON_SIZE_SMALL);
3760
                        $hide_show_disc = 'hidedisc';
3761
                    } else {
3762
                        $visibility_disc = Display::return_icon('invisible.png', get_lang('HideDiscussExtra'), '', ICON_SIZE_SMALL);
3763
                        $hide_show_disc = 'showdisc';
3764
                    }
3765
                }
3766
                echo '<span style="float:right">';
3767
                echo '<a href="index.php?action=discuss&amp;actionpage='.$hide_show_disc.'&amp;title='.api_htmlentities(urlencode($page)).'">'.$visibility_disc.'</a>';
3768
                echo '</span>';
3769
3770
                //discussion action: check add rating lock. Show/Hide list to rating for all student
3771
                $lock_unlock_rating_disc = null;
3772
                $ratinglock_disc = null;
3773 View Code Duplication
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3774
                    if (self::check_ratinglock_discuss() == 1) {
3775
                        $ratinglock_disc = Display::return_icon('star.png', get_lang('UnlockRatingDiscussExtra'), '', ICON_SIZE_SMALL);
3776
                        $lock_unlock_rating_disc = 'unlockrating';
3777
                    } else {
3778
                        $ratinglock_disc = Display::return_icon('star_na.png', get_lang('LockRatingDiscussExtra'), '', ICON_SIZE_SMALL);
3779
                        $lock_unlock_rating_disc = 'lockrating';
3780
                    }
3781
                }
3782
3783
                echo '<span style="float:right">';
3784
                echo '<a href="index.php?action=discuss&actionpage='.$lock_unlock_rating_disc.'&title='.api_htmlentities(urlencode($page)).'">'.$ratinglock_disc.'</a>';
3785
                echo '</span>';
3786
3787
                //discussion action: email notification
3788
                if (self::check_notify_discuss($page) == 1) {
3789
                    $notify_disc = Display::return_icon(
3790
                        'messagebox_info.png',
3791
                        get_lang('NotifyDiscussByEmail'),
3792
                        '',
3793
                        ICON_SIZE_SMALL
3794
                    );
3795
                    $lock_unlock_notify_disc = 'unlocknotifydisc';
3796
                } else {
3797
                    $notify_disc = Display::return_icon(
3798
                        'mail.png',
3799
                        get_lang('CancelNotifyDiscussByEmail'),
3800
                        '',
3801
                        ICON_SIZE_SMALL
3802
                    );
3803
                    $lock_unlock_notify_disc = 'locknotifydisc';
3804
                }
3805
                echo '<span style="float:right">';
3806
                echo '<a href="index.php?action=discuss&amp;actionpage='.$lock_unlock_notify_disc.'&amp;title='.api_htmlentities(urlencode($page)).'">'.$notify_disc.'</a>';
3807
                echo '</span>';
3808
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities($row['title']);
3809
                if ($lastuserinfo !== false) {
3810
                    echo ' ('.get_lang('MostRecentVersionBy').' '.UserManager::getUserProfileLink($lastuserinfo).' '.$lastversiondate.$countWPost.')'.$avg_WPost_score.' '; //TODO: read average score
3811
                }
3812
3813
                echo '</div>';
3814
                if ($row['addlock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3815
                    //show comments but students can't add theirs
3816
                    ?>
3817
                <div class="panel panel-default">
3818
                    <div class="panel-body">
3819
                    <form name="form1" method="post" action="" class="form-horizontal">
3820
                        <div class="form-group">
3821
                            <label class="col-sm-2 control-label"><?php echo get_lang('Comments'); ?>:</label>
3822
                            <div class="col-sm-10">
3823
                                <?php  echo '<input type="hidden" name="wpost_id" value="'.md5(uniqid(rand(), true)).'">'; //prevent double post ?>
3824
                                <textarea class="form-control" name="comment" cols="80" rows="5" id="comment"></textarea>
3825
                            </div>
3826
                        </div>
3827
                        <div class="form-group">
3828
                             <?php
3829
                                //check if rating is allowed
3830
                                if ($row['ratinglock_disc'] == 1 || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
3831
                                    ?>
3832
                            <label class="col-sm-2 control-label"><?php echo get_lang('Rating'); ?>:</label>
3833
                            <div class="col-sm-10">
3834
                                <select name="rating" id="rating" class="selectpicker">
3835
                                    <option value="-" selected>-</option>
3836
                                    <option value="0">0</option>
3837
                                    <option value="1">1</option>
3838
                                    <option value="2">2</option>
3839
                                    <option value="3">3</option>
3840
                                    <option value="4">4</option>
3841
                                    <option value="5">5</option>
3842
                                    <option value="6">6</option>
3843
                                    <option value="7">7</option>
3844
                                    <option value="8">8</option>
3845
                                    <option value="9">9</option>
3846
                                    <option value="10">10</option>
3847
                                </select>
3848
                            </div>
3849
                            <?php
3850
                                } else {
3851
                                    echo '<input type=hidden name="rating" value="-">'; // must pass a default value to avoid rate automatically
3852
                                }
3853
                                ?>
3854
3855
                          </div>
3856
                        <div class="form-group">
3857
                                <div class="col-sm-offset-2 col-sm-10">
3858
                                  <?php  echo '<button class="btn btn-default" type="submit" name="Submit"> '.get_lang('Send').'</button>'; ?>
3859
                                </div>
3860
                            </div>
3861
                        </div>
3862
                        </div>
3863
                    </form>
3864
3865
                    <?php
3866
3867
                }//end discuss lock
3868
3869
                echo '<hr noshade size="1">';
3870
                $user_table = Database::get_main_table(TABLE_MAIN_USER);
3871
3872
                $sql = "SELECT *
3873
                        FROM $tbl_wiki_discuss reviews, $user_table user
3874
                        WHERE
3875
                            reviews.c_id = $course_id AND
3876
                            reviews.publication_id='".$id."' AND
3877
                            user.user_id='".$firstuserid."'
3878
                        ORDER BY reviews.id DESC";
3879
                $result = Database::query($sql);
3880
3881
                $countWPost = Database::num_rows($result);
3882
                echo get_lang('NumComments').": ".$countWPost; //comment's numbers
3883
3884
                $sql = "SELECT SUM(p_score) as sumWPost
3885
                        FROM $tbl_wiki_discuss
3886
                        WHERE c_id = $course_id AND publication_id = '".$id."' AND NOT p_score='-'
3887
                        ORDER BY id DESC";
3888
                $result2 = Database::query($sql);
3889
                $row2 = Database::fetch_array($result2);
3890
3891
                $sql = "SELECT * FROM $tbl_wiki_discuss
3892
                        WHERE c_id = $course_id AND publication_id='".$id."' AND NOT p_score='-'";
3893
                $result3 = Database::query($sql);
3894
                $countWPost_score = Database::num_rows($result3);
3895
3896
                echo ' - '.get_lang('NumCommentsScore').': '.$countWPost_score; //
3897
3898
                if ($countWPost_score != 0) {
3899
                    $avg_WPost_score = round($row2['sumWPost'] / $countWPost_score, 2).' / 10';
3900
                } else {
3901
                    $avg_WPost_score = $countWPost_score;
3902
                }
3903
3904
                echo ' - '.get_lang('RatingMedia').': '.$avg_WPost_score; // average rating
3905
3906
                $sql = 'UPDATE '.$tbl_wiki.' SET
3907
                        score="'.Database::escape_string($avg_WPost_score).'"
3908
                        WHERE
3909
                            c_id = '.$course_id.' AND
3910
                            reflink="'.Database::escape_string($page).'" AND
3911
                            '.$groupfilter.$condition_session;
3912
                // check if work ok. TODO:
3913
                Database::query($sql);
3914
3915
                echo '<hr noshade size="1">';
3916
3917
                while ($row = Database::fetch_array($result)) {
3918
                    $userinfo = api_get_user_info($row['userc_id']);
3919
                    if (($userinfo['status']) == "5") {
3920
                        $author_status = get_lang('Student');
3921
                    } else {
3922
                        $author_status = get_lang('Teacher');
3923
                    }
3924
3925
                    $name = $userinfo['complete_name'];
3926
                    $author_photo = '<img src="'.$userinfo['avatar'].'" alt="'.api_htmlentities($name).'"  width="40" height="50" align="top"  title="'.api_htmlentities($name).'"  />';
3927
3928
                    //stars
3929
                    $p_score = $row['p_score'];
3930
                    switch ($p_score) {
3931
                        case  0:
3932
                            $imagerating = Display::return_icon('rating/stars_0.gif');
3933
                            break;
3934
                        case  1:
3935
                            $imagerating = Display::return_icon('rating/stars_5.gif');
3936
                            break;
3937
                        case  2:
3938
                            $imagerating = Display::return_icon('rating/stars_10.gif');
3939
                            break;
3940
                        case  3:
3941
                            $imagerating = Display::return_icon('rating/stars_15.gif');
3942
                            break;
3943
                        case  4:
3944
                            $imagerating = Display::return_icon('rating/stars_20.gif');
3945
                            break;
3946
                        case  5:
3947
                            $imagerating = Display::return_icon('rating/stars_25.gif');
3948
                            break;
3949
                        case  6:
3950
                            $imagerating = Display::return_icon('rating/stars_30.gif');
3951
                            break;
3952
                        case  7:
3953
                            $imagerating = Display::return_icon('rating/stars_35.gif');
3954
                            break;
3955
                        case  8:
3956
                            $imagerating = Display::return_icon('rating/stars_40.gif');
3957
                            break;
3958
                        case  9:
3959
                            $imagerating = Display::return_icon('rating/stars_45.gif');
3960
                            break;
3961
                        case  10:
3962
                            $imagerating = Display::return_icon('rating/stars_50.gif');
3963
                            break;
3964
                    }
3965
                    echo '<p><table>';
3966
                    echo '<tr>';
3967
                    echo '<td rowspan="2">'.$author_photo.'</td>';
3968
                    $userProfile = '';
3969
                    if ($userinfo !== false) {
3970
                        $userProfile = UserManager::getUserProfileLink($userinfo);
3971
                    }
3972
                    echo '<td style=" color:#999999">'.$userProfile.' ('.$author_status.') '.
3973
                        api_get_local_time($row['dtime'], null, date_default_timezone_get()).
3974
                        ' - '.get_lang('Rating').': '.$row['p_score'].' '.$imagerating.' </td>';
3975
                    echo '</tr>';
3976
                    echo '<tr>';
3977
                    echo '<td>'.api_htmlentities($row['comment']).'</td>';
3978
                    echo '</tr>';
3979
                    echo "</table>";
3980
                }
3981
            } else {
3982
                Display::addFlash(Display::return_message(get_lang('LockByTeacher'), 'warning', false));
3983
            }
3984
        } else {
3985
            Display::addFlash(Display::return_message(get_lang('DiscussNotAvailable'), 'normal', false));
3986
        }
3987
    }
3988
3989
    /**
3990
     * Show all pages
3991
     */
3992
    public function allPages($action)
3993
    {
3994
        $tbl_wiki = $this->tbl_wiki;
3995
        $course_id = $this->course_id;
3996
        $session_id = $this->session_id;
3997
        $groupfilter = $this->groupfilter;
3998
        $_course = $this->courseInfo;
3999
4000
        echo '<div class="actions">'.get_lang('AllPages');
4001
4002
        // menu delete all wiki
4003 View Code Duplication
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4004
            echo ' <a href="index.php?action=deletewiki&'.api_get_cidreq().'">'.
4005
                Display::return_icon(
4006
                    'delete.png',
4007
                    get_lang('DeleteWiki'),
4008
                    '',
4009
                    ICON_SIZE_MEDIUM
4010
                ).'</a>';
4011
        }
4012
        echo '</div>';
4013
4014
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) { //only by professors if page is hidden
4015
            $sql = 'SELECT  *
4016
                    FROM  '.$tbl_wiki.' s1
4017
        		    WHERE s1.c_id = '.$course_id.' AND id=(
4018
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
4019
                    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.' AND session_id='.$session_id.')';
4020
            // warning don't use group by reflink because does not return the last version
4021
4022
        } else {
4023
            $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1
4024
				    WHERE visibility=1 AND s1.c_id = '.$course_id.' AND id=(
4025
                        SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
4026
                        WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.' AND session_id='.$session_id.')';
4027
            // warning don't use group by reflink because does not return the last version
4028
        }
4029
4030
        $allpages = Database::query($sql);
4031
4032
        //show table
4033
        if (Database::num_rows($allpages) > 0) {
4034
            while ($obj = Database::fetch_object($allpages)) {
4035
                //get author
4036
                $userinfo = api_get_user_info($obj->user_id);
4037
                $username = api_htmlentities(
4038
                    sprintf(get_lang('LoginX'), $userinfo['username']),
4039
                    ENT_QUOTES
4040
                );
4041
4042
                //get type assignment icon
4043
                if ($obj->assignment == 1) {
4044
                    $ShowAssignment = Display::return_icon(
4045
                        'wiki_assignment.png',
4046
                        get_lang('AssignmentDesc'),
4047
                        '',
4048
                        ICON_SIZE_SMALL
4049
                    );
4050
                } elseif ($obj->assignment == 2) {
4051
                    $ShowAssignment = Display::return_icon(
4052
                        'wiki_work.png',
4053
                        get_lang('AssignmentWork'),
4054
                        '',
4055
                        ICON_SIZE_SMALL
4056
                    );
4057
                } elseif ($obj->assignment == 0) {
4058
                    $ShowAssignment = Display::return_icon(
4059
                        'px_transparent.gif'
4060
                    );
4061
                }
4062
4063
                //get icon task
4064
                if (!empty($obj->task)) {
4065
                    $icon_task = Display::return_icon(
4066
                        'wiki_task.png',
4067
                        get_lang('StandardTask'),
4068
                        '',
4069
                        ICON_SIZE_SMALL
4070
                    );
4071
                } else {
4072
                    $icon_task = Display::return_icon('px_transparent.gif');
4073
                }
4074
4075
                $row = array();
4076
                $row[] = $ShowAssignment.$icon_task;
4077
                $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']).'">
4078
                '.api_htmlentities($obj->title).'</a>';
4079 View Code Duplication
                if ($userinfo !== false) {
4080
                    $row[] = UserManager::getUserProfileLink($userinfo);
4081
                } else {
4082
                    $row[] = get_lang('Anonymous').' ('.api_htmlentities(
4083
                            $obj->user_ip
4084
                        ).')';
4085
                }
4086
                $row[] = api_get_local_time(
4087
                    $obj->dtime,
4088
                    null,
4089
                    date_default_timezone_get()
4090
                );
4091
                $showdelete = '';
4092
                if (api_is_allowed_to_edit(
4093
                        false,
4094
                        true
4095
                    ) || api_is_platform_admin()) {
4096
                    $showdelete = ' <a href="'.api_get_self(
4097
                        ).'?cidReq='.$_course['code'].'&action=delete&title='.api_htmlentities(
4098
                            urlencode($obj->reflink)
4099
                        ).'&session_id='.api_htmlentities(
4100
                            $_GET['session_id']
4101
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4102
                        Display::return_icon(
4103
                            'delete.png',
4104
                            get_lang('Delete'),
4105
                            '',
4106
                            ICON_SIZE_SMALL
4107
                        );
4108
                }
4109
                if (api_is_allowed_to_session_edit(false, true)) {
4110
                    $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']).'">'.
4111
                        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']).'">'.
4112
                        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']).'">'.
4113
                        Display::return_icon('history.png', get_lang('History'), '', ICON_SIZE_SMALL).'</a>
4114
                        <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']).'">'.
4115
                        Display::return_icon('what_link_here.png', get_lang('LinksPages'), '', ICON_SIZE_SMALL).'</a>'.$showdelete;
4116
                }
4117
                $rows[] = $row;
4118
            }
4119
4120
            $table = new SortableTableFromArrayConfig($rows, 1, 10, 'AllPages_table', '', '', 'ASC');
4121
            $table->set_additional_parameters(array('cidReq' =>Security::remove_XSS($_GET['cidReq']), 'action'=>Security::remove_XSS($action), 'group_id'=>Security::remove_XSS($_GET['group_id'])));
4122
            $table->set_header(0, get_lang('Type'), true, array('style' => 'width:30px;'));
4123
            $table->set_header(1, get_lang('Title'), true);
4124
            $table->set_header(2, get_lang('Author').' ('.get_lang('LastVersion').')', true);
4125
            $table->set_header(3, get_lang('Date').' ('.get_lang('LastVersion').')', true);
4126
            if (api_is_allowed_to_session_edit(false, true)) {
4127
                $table->set_header(4, get_lang('Actions'), true, array('style' => 'width:130px;'));
4128
            }
4129
            $table->display();
4130
        }
4131
    }
4132
4133
    /**
4134
     * Get recent changes
4135
     * @param string $page
4136
     * @param string $action
4137
     *
4138
     */
4139
    public function recentChanges($page, $action)
4140
    {
4141
        $tbl_wiki = $this->tbl_wiki;
4142
        $course_id = $this->course_id;
4143
        $condition_session = $this->condition_session;
4144
        $groupfilter = $this->groupfilter;
4145
        $tbl_wiki_conf = $this->tbl_wiki_conf;
4146
4147
        if (api_is_allowed_to_session_edit(false, true)) {
4148
            if (self::check_notify_all() == 1) {
4149
                $notify_all = Display::return_icon(
4150
                        'messagebox_info.png',
4151
                        get_lang('NotifyByEmail'),
4152
                        '',
4153
                        ICON_SIZE_SMALL
4154
                    ).' '.get_lang('NotNotifyChanges');
4155
                $lock_unlock_notify_all = 'unlocknotifyall';
4156
            } else {
4157
                $notify_all = Display::return_icon(
4158
                        'mail.png',
4159
                        get_lang('CancelNotifyByEmail'),
4160
                        '',
4161
                        ICON_SIZE_SMALL
4162
                    ).' '.get_lang('NotifyChanges');
4163
                $lock_unlock_notify_all = 'locknotifyall';
4164
            }
4165
        }
4166
4167
        echo '<div class="actions"><span style="float: right;">';
4168
        echo '<a href="index.php?action=recentchanges&amp;actionpage='.$lock_unlock_notify_all.'&amp;title='.api_htmlentities(urlencode($page)).'">'.$notify_all.'</a>';
4169
        echo '</span>'.get_lang('RecentChanges').'</div>';
4170
4171
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) { //only by professors if page is hidden
4172
            $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
4173
        		WHERE 	'.$tbl_wiki_conf.'.c_id= '.$course_id.' AND
4174
        				'.$tbl_wiki.'.c_id= '.$course_id.' AND
4175
        				'.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
4176
        				'.$tbl_wiki.'.'.$groupfilter.$condition_session.'
4177
        		ORDER BY dtime DESC'; // new version
4178
        } else {
4179
            $sql = 'SELECT *
4180
                FROM '.$tbl_wiki.'
4181
                WHERE
4182
                    c_id = '.$course_id.' AND
4183
                    '.$groupfilter.$condition_session.' AND
4184
                    visibility=1
4185
                ORDER BY dtime DESC';
4186
            // old version TODO: Replace by the bottom line
4187
        }
4188
4189
        $allpages = Database::query($sql);
4190
4191
        //show table
4192
        if (Database::num_rows($allpages) > 0) {
4193
            $rows = array();
4194
            while ($obj = Database::fetch_object($allpages)) {
4195
                //get author
4196
                $userinfo = api_get_user_info($obj->user_id);
4197
4198
                //get type assignment icon
4199
                if ($obj->assignment == 1) {
4200
                    $ShowAssignment = Display::return_icon(
4201
                        'wiki_assignment.png',
4202
                        get_lang('AssignmentDesc'),
4203
                        '',
4204
                        ICON_SIZE_SMALL
4205
                    );
4206
                } elseif ($obj->assignment == 2) {
4207
                    $ShowAssignment = Display::return_icon(
4208
                        'wiki_work.png',
4209
                        get_lang('AssignmentWork'),
4210
                        '',
4211
                        ICON_SIZE_SMALL
4212
                    );
4213
                } elseif ($obj->assignment == 0) {
4214
                    $ShowAssignment = Display::return_icon(
4215
                        'px_transparent.gif'
4216
                    );
4217
                }
4218
4219
                // Get icon task
4220
                if (!empty($obj->task)) {
4221
                    $icon_task = Display::return_icon(
4222
                        'wiki_task.png',
4223
                        get_lang('StandardTask'),
4224
                        '',
4225
                        ICON_SIZE_SMALL
4226
                    );
4227
                } else {
4228
                    $icon_task = Display::return_icon('px_transparent.gif');
4229
                }
4230
4231
                $row = array();
4232
                $row[] = api_get_local_time(
4233
                    $obj->dtime,
4234
                    null,
4235
                    date_default_timezone_get()
4236
                );
4237
                $row[] = $ShowAssignment.$icon_task;
4238
                $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().'">'.
4239
                    api_htmlentities($obj->title).'</a>';
4240
                $row[] = $obj->version > 1 ? get_lang('EditedBy') : get_lang('AddedBy');
4241 View Code Duplication
                if ($userinfo !== false) {
4242
                    $row[] = UserManager::getUserProfileLink($userinfo);
4243
                } else {
4244
                    $row[] = get_lang('Anonymous').' ('.api_htmlentities($obj->user_ip).')';
4245
                }
4246
                $rows[] = $row;
4247
            }
4248
4249
            $table = new SortableTableFromArrayConfig(
4250
                $rows,
4251
                0,
4252
                10,
4253
                'RecentPages_table',
4254
                '',
4255
                '',
4256
                'DESC'
4257
            );
4258
            $table->set_additional_parameters(
4259
                array(
4260
                    'cidReq' => api_get_course_id(),
4261
                    'action' => Security::remove_XSS($action),
4262
                    'session_id' => api_get_session_id(),
4263
                    'group_id' => api_get_group_id()
4264
                )
4265
            );
4266
            $table->set_header(
4267
                0,
4268
                get_lang('Date'),
4269
                true,
4270
                array('style' => 'width:200px;')
4271
            );
4272
            $table->set_header(
4273
                1,
4274
                get_lang('Type'),
4275
                true,
4276
                array('style' => 'width:30px;')
4277
            );
4278
            $table->set_header(2, get_lang('Title'), true);
4279
            $table->set_header(
4280
                3,
4281
                get_lang('Actions'),
4282
                true,
4283
                array('style' => 'width:80px;')
4284
            );
4285
            $table->set_header(4, get_lang('Author'), true);
4286
            $table->display();
4287
        }
4288
    }
4289
4290
    /**
4291
     * What links here. Show pages that have linked this page
4292
     *
4293
     * @param string $page
4294
     */
4295
    public function getLinks($page)
4296
    {
4297
        $tbl_wiki = $this->tbl_wiki;
4298
        $course_id = $this->course_id;
4299
        $condition_session = $this->condition_session;
4300
        $groupfilter = $this->groupfilter;
4301
        $_course = $this->courseInfo;
4302
        $action = $this->action;
4303
4304
        if (!$_GET['title']) {
4305
            Display::addFlash(
4306
                Display::return_message(
4307
                    get_lang("MustSelectPage"),
4308
                    'error',
4309
                    false
4310
                )
4311
            );
4312
        } else {
4313
            $sql = 'SELECT * FROM '.$tbl_wiki.'
4314
                    WHERE
4315
                        c_id = '.$course_id.' AND
4316
                        reflink="'.Database::escape_string($page).'" AND
4317
                        '.$groupfilter.$condition_session;
4318
            $result = Database::query($sql);
4319
            $row = Database::fetch_array($result);
4320
4321
            //get type assignment icon
4322
            $ShowAssignment = '';
4323 View Code Duplication
            if ($row['assignment'] == 1) {
4324
                $ShowAssignment = Display::return_icon(
4325
                    'wiki_assignment.png',
4326
                    get_lang('AssignmentDesc'),
4327
                    '',
4328
                    ICON_SIZE_SMALL
4329
                );
4330
            } elseif ($row['assignment'] == 2) {
4331
                $ShowAssignment = Display::return_icon(
4332
                    'wiki_work.png',
4333
                    get_lang('AssignmentWork'),
4334
                    '',
4335
                    ICON_SIZE_SMALL
4336
                );
4337
            } elseif ($row['assignment'] == 0) {
4338
                $ShowAssignment = Display::return_icon('px_transparent.gif');
4339
            }
4340
4341
            //fix Title to reflink (link Main Page)
4342
            if ($page == get_lang('DefaultTitle')) {
4343
                $page = 'index';
4344
            }
4345
4346
            echo '<div id="wikititle">';
4347
            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']).'">'.
4348
                api_htmlentities($row['title']).'</a>';
4349
            echo '</div>';
4350
4351
            //fix index to title Main page into linksto
4352
4353
            if ($page == 'index') {
4354
                $page = str_replace(' ', '_', get_lang('DefaultTitle'));
4355
            }
4356
4357
            //table
4358
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4359
                //only by professors if page is hidden
4360
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4361
                        WHERE s1.c_id = $course_id AND linksto LIKE '%".Database::escape_string($page)."%' AND id=(
4362
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4363
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4364
                //add blank space after like '%" " %' to identify each word
4365
            } else {
4366
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4367
                        WHERE s1.c_id = $course_id AND visibility=1 AND linksto LIKE '%".Database::escape_string($page)."%' AND id=(
4368
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4369
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4370
                //add blank space after like '%" " %' to identify each word
4371
            }
4372
4373
            $allpages = Database::query($sql);
4374
4375
            //show table
4376
            if (Database::num_rows($allpages) > 0) {
4377
                $rows = array();
4378
                while ($obj = Database::fetch_object($allpages)) {
4379
                    //get author
4380
                    $userinfo = api_get_user_info($obj->user_id);
4381
4382
                    //get time
4383
                    $year = substr($obj->dtime, 0, 4);
4384
                    $month = substr($obj->dtime, 5, 2);
4385
                    $day = substr($obj->dtime, 8, 2);
4386
                    $hours = substr($obj->dtime, 11, 2);
4387
                    $minutes = substr($obj->dtime, 14, 2);
4388
                    $seconds = substr($obj->dtime, 17, 2);
4389
4390
                    //get type assignment icon
4391
                    if ($obj->assignment == 1) {
4392
                        $ShowAssignment = Display::return_icon(
4393
                            'wiki_assignment.png',
4394
                            get_lang('AssignmentDesc'),
4395
                            '',
4396
                            ICON_SIZE_SMALL
4397
                        );
4398
                    } elseif ($obj->assignment == 2) {
4399
                        $ShowAssignment = Display::return_icon(
4400
                            'wiki_work.png',
4401
                            get_lang('AssignmentWork'),
4402
                            '',
4403
                            ICON_SIZE_SMALL
4404
                        );
4405
                    } elseif ($obj->assignment == 0) {
4406
                        $ShowAssignment = Display::return_icon(
4407
                            'px_transparent.gif'
4408
                        );
4409
                    }
4410
4411
                    $row = array();
4412
                    $row[] = $ShowAssignment;
4413
                    $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']).'">'.
4414
                        api_htmlentities($obj->title).'</a>';
4415 View Code Duplication
                    if ($userinfo !== false) {
4416
                        $row[] = UserManager::getUserProfileLink($userinfo);
4417
                    } else {
4418
                        $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
4419
                    }
4420
                    $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
4421
                    $rows[] = $row;
4422
                }
4423
4424
                $table = new SortableTableFromArrayConfig(
4425
                    $rows,
4426
                    1,
4427
                    10,
4428
                    'AllPages_table',
4429
                    '',
4430
                    '',
4431
                    'ASC'
4432
                );
4433
                $table->set_additional_parameters(
4434
                    array(
4435
                        'cidReq' => Security::remove_XSS($_GET['cidReq']),
4436
                        'action' => Security::remove_XSS($action),
4437
                        'group_id' => intval($_GET['group_id']),
4438
                    )
4439
                );
4440
                $table->set_header(
4441
                    0,
4442
                    get_lang('Type'),
4443
                    true,
4444
                    array('style' => 'width:30px;')
4445
                );
4446
                $table->set_header(1, get_lang('Title'), true);
4447
                $table->set_header(2, get_lang('Author'), true);
4448
                $table->set_header(3, get_lang('Date'), true);
4449
                $table->display();
4450
            }
4451
        }
4452
    }
4453
4454
    /**
4455
     * @param string $action
4456
     */
4457
    public function getSearchPages($action)
4458
    {
4459
        echo '<div class="actions">'.get_lang('SearchPages').'</div>';
4460
        if (isset($_GET['mode_table'])) {
4461
            if (!isset($_GET['SearchPages_table_page_nr'])) {
4462
                $_GET['search_term'] = isset($_POST['search_term']) ? $_POST['search_term'] : '';
4463
                $_GET['search_content'] = isset($_POST['search_content']) ? $_POST['search_content'] : '';
4464
                $_GET['all_vers'] = isset($_POST['all_vers']) ? $_POST['all_vers'] : '';
4465
            }
4466
            self::display_wiki_search_results(
4467
                $_GET['search_term'],
4468
                $_GET['search_content'],
4469
                $_GET['all_vers']
4470
            );
4471
        } else {
4472
4473
            // initiate the object
4474
            $form = new FormValidator('wiki_search',
4475
                'post',
4476
                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'
4477
            );
4478
4479
            // Setting the form elements
4480
4481
            $form->addText(
4482
                'search_term',
4483
                get_lang('SearchTerm'),
4484
                true,
4485
                array('autofocus' => 'autofocus')
4486
            );
4487
            $form->addElement(
4488
                'checkbox',
4489
                'search_content',
4490
                null,
4491
                get_lang('AlsoSearchContent')
4492
            );
4493
            $form->addElement(
4494
                'checkbox',
4495
                'all_vers',
4496
                null,
4497
                get_lang('IncludeAllVersions')
4498
            );
4499
            $form->addButtonSearch(get_lang('Search'), 'SubmitWikiSearch');
4500
4501
            // setting the rules
4502
            $form->addRule(
4503
                'search_term',
4504
                get_lang('TooShort'),
4505
                'minlength',
4506
                3
4507
            ); //TODO: before fixing the pagination rules worked, not now
4508
4509
            if ($form->validate()) {
4510
                $form->display();
4511
                $values = $form->exportValues();
4512
                self::display_wiki_search_results(
4513
                    $values['search_term'],
4514
                    $values['search_content'],
4515
                    $values['all_vers']
4516
                );
4517
            } else {
4518
                $form->display();
4519
            }
4520
        }
4521
    }
4522
4523
    /**
4524
     * @param int $userId
4525
     * @param string $action
4526
     */
4527
    public function getUserContributions($userId, $action)
4528
    {
4529
        $_course = $this->courseInfo;
4530
        $tbl_wiki = $this->tbl_wiki;
4531
        $course_id = $this->course_id;
4532
        $condition_session = $this->condition_session;
4533
        $groupfilter = $this->groupfilter;
4534
        $userId = intval($userId);
4535
        $userinfo = api_get_user_info($userId);
4536
        if ($userinfo !== false) {
4537
            echo '<div class="actions">'.get_lang('UserContributions').': '.UserManager::getUserProfileLink($userinfo).
4538
                '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.$userId.
4539
                '&session_id='.$this->session_id.'&group_id='.$this->group_id.'">'.
4540
                '</a></div>';
4541
        }
4542
4543
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4544
            //only by professors if page is hidden
4545
            $sql = 'SELECT * FROM '.$tbl_wiki.'
4546
                    WHERE
4547
                        c_id = '.$course_id.' AND
4548
                        '.$groupfilter.$condition_session.' AND
4549
                        user_id="'.$userId.'"';
4550
        } else {
4551
            $sql = 'SELECT * FROM '.$tbl_wiki.'
4552
                    WHERE
4553
                        c_id = '.$course_id.' AND
4554
                        '.$groupfilter.$condition_session.' AND
4555
                        user_id="'.$userId.'" AND
4556
                        visibility=1';
4557
        }
4558
4559
        $allpages = Database::query($sql);
4560
4561
        //show table
4562
        if (Database::num_rows($allpages) > 0) {
4563
            $rows = array();
4564
            while ($obj = Database::fetch_object($allpages)) {
4565
                // Get time
4566
                $year = substr($obj->dtime, 0, 4);
4567
                $month = substr($obj->dtime, 5, 2);
4568
                $day = substr($obj->dtime, 8, 2);
4569
                $hours = substr($obj->dtime, 11, 2);
4570
                $minutes = substr($obj->dtime, 14, 2);
4571
                $seconds = substr($obj->dtime, 17, 2);
4572
4573
                //get type assignment icon
4574
                $ShowAssignment = '';
4575
                if ($obj->assignment == 1) {
4576
                    $ShowAssignment = Display::return_icon(
4577
                        'wiki_assignment.png',
4578
                        get_lang('AssignmentDescExtra'),
4579
                        '',
4580
                        ICON_SIZE_SMALL
4581
                    );
4582
                } elseif ($obj->assignment == 2) {
4583
                    $ShowAssignment = Display::return_icon(
4584
                        'wiki_work.png',
4585
                        get_lang('AssignmentWork'),
4586
                        '',
4587
                        ICON_SIZE_SMALL
4588
                    );
4589
                } elseif ($obj->assignment == 0) {
4590
                    $ShowAssignment = Display::return_icon(
4591
                        'px_transparent.gif'
4592
                    );
4593
                }
4594
4595
                $row = array();
4596
                $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
4597
                $row[] = $ShowAssignment;
4598
                $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().'">'.
4599
                    api_htmlentities($obj->title).'</a>';
4600
                $row[] = Security::remove_XSS($obj->version);
4601
                $row[] = Security::remove_XSS($obj->comment);
4602
                $row[] = Security::remove_XSS($obj->progress).' %';
4603
                $row[] = Security::remove_XSS($obj->score);
4604
                $rows[] = $row;
4605
            }
4606
4607
            $table = new SortableTableFromArrayConfig(
4608
                $rows,
4609
                2,
4610
                10,
4611
                'UsersContributions_table',
4612
                '',
4613
                '',
4614
                'ASC'
4615
            );
4616
            $table->set_additional_parameters(
4617
                array(
4618
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
4619
                    'action' => Security::remove_XSS($action),
4620
                    'user_id' => intval($userId),
4621
                    'session_id' => intval($_GET['session_id']),
4622
                    'group_id' => intval($_GET['group_id']),
4623
                )
4624
            );
4625
            $table->set_header(
4626
                0,
4627
                get_lang('Date'),
4628
                true,
4629
                array('style' => 'width:200px;')
4630
            );
4631
            $table->set_header(
4632
                1,
4633
                get_lang('Type'),
4634
                true,
4635
                array('style' => 'width:30px;')
4636
            );
4637
            $table->set_header(
4638
                2,
4639
                get_lang('Title'),
4640
                true,
4641
                array('style' => 'width:200px;')
4642
            );
4643
            $table->set_header(
4644
                3,
4645
                get_lang('Version'),
4646
                true,
4647
                array('style' => 'width:30px;')
4648
            );
4649
            $table->set_header(
4650
                4,
4651
                get_lang('Comment'),
4652
                true,
4653
                array('style' => 'width:200px;')
4654
            );
4655
            $table->set_header(
4656
                5,
4657
                get_lang('Progress'),
4658
                true,
4659
                array('style' => 'width:30px;')
4660
            );
4661
            $table->set_header(
4662
                6,
4663
                get_lang('Rating'),
4664
                true,
4665
                array('style' => 'width:30px;')
4666
            );
4667
            $table->display();
4668
        }
4669
    }
4670
4671
    /**
4672
     * @param string $action
4673
     */
4674 View Code Duplication
    public function getMostChangedPages($action)
4675
    {
4676
        $_course = $this->courseInfo;
4677
        $tbl_wiki = $this->tbl_wiki;
4678
        $course_id = $this->course_id;
4679
        $condition_session = $this->condition_session;
4680
        $groupfilter = $this->groupfilter;
4681
4682
        echo '<div class="actions">'.get_lang('MostChangedPages').'</div>';
4683
4684
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) { //only by professors if page is hidden
4685
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
4686
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
4687
                    GROUP BY reflink';//TODO:check MAX and group by return last version
4688
        } else {
4689
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
4690
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND visibility=1
4691
                    GROUP BY reflink'; //TODO:check MAX and group by return last version
4692
        }
4693
4694
        $allpages = Database::query($sql);
4695
4696
        //show table
4697
        if (Database::num_rows($allpages) > 0) {
4698
            $rows = array();
4699
            while ($obj = Database::fetch_object($allpages)) {
4700
                //get type assignment icon
4701
                $ShowAssignment = '';
4702
                if ($obj->assignment == 1) {
4703
                    $ShowAssignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'), '', ICON_SIZE_SMALL);
4704
                } elseif ($obj->assignment == 2) {
4705
                    $ShowAssignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWork'), '', ICON_SIZE_SMALL);
4706
                } elseif ($obj->assignment == 0) {
4707
                    $ShowAssignment = Display::return_icon('px_transparent.gif');
4708
                }
4709
4710
                $row = array();
4711
                $row[] = $ShowAssignment;
4712
                $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']).'">'.
4713
                    api_htmlentities($obj->title).'</a>';
4714
                $row[] = $obj->MAX;
4715
                $rows[] = $row;
4716
            }
4717
4718
            $table = new SortableTableFromArrayConfig(
4719
                $rows,
4720
                2,
4721
                10,
4722
                'MostChangedPages_table',
4723
                '',
4724
                '',
4725
                'DESC'
4726
            );
4727
            $table->set_additional_parameters(
4728
                array(
4729
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
4730
                    'action' => Security::remove_XSS($action),
4731
                    'session_id' => intval($_GET['session_id']),
4732
                    'group_id' => intval($_GET['group_id']),
4733
                )
4734
            );
4735
            $table->set_header(
4736
                0,
4737
                get_lang('Type'),
4738
                true,
4739
                array('style' => 'width:30px;')
4740
            );
4741
            $table->set_header(1, get_lang('Title'), true);
4742
            $table->set_header(2, get_lang('Changes'), true);
4743
            $table->display();
4744
        }
4745
    }
4746
4747
    /**
4748
     * Restore page
4749
     * @return bool
4750
     */
4751
    public function restorePage()
4752
    {
4753
        $userId = api_get_user_id();
4754
        $_course = $this->courseInfo;
4755
        $current_row = $this->getWikiData();
4756
        $last_row = $this->getLastWikiData($this->page);
4757
4758
        if (empty($last_row)) {
4759
            return false;
4760
        }
4761
4762
        $PassEdit = false;
4763
4764
        /* Only teachers and platform admin can edit the index page.
4765
        Only teachers and platform admin can edit an assignment teacher*/
4766
        if (($current_row['reflink'] == 'index' || $current_row['reflink'] == '' || $current_row['assignment'] == 1) &&
4767
            (!api_is_allowed_to_edit(false, true) && $this->group_id == 0)
4768
        ) {
4769
            Display::addFlash(
4770
                Display::return_message(
4771
                    get_lang('OnlyEditPagesCourseManager'),
4772
                    'normal',
4773
                    false
4774
                )
4775
            );
4776
        } else {
4777
4778
            // check if is a wiki group
4779
            if ($current_row['group_id'] != 0) {
4780
                $groupInfo = GroupManager::get_group_properties(
4781
                    $this->group_id
4782
                );
4783
                //Only teacher, platform admin and group members can edit a wiki group
4784 View Code Duplication
                if (api_is_allowed_to_edit(false, true) ||
4785
                    api_is_platform_admin() ||
4786
                    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 4780 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...
4787
                    api_is_allowed_in_course()
4788
                ) {
4789
                    $PassEdit = true;
4790
                } else {
4791
                    Display::addFlash(
4792
                        Display::return_message(
4793
                            get_lang('OnlyEditPagesGroupMembers'),
4794
                            'normal',
4795
                            false
4796
                        )
4797
                    );
4798
                }
4799
            } else {
4800
                $PassEdit = true;
4801
            }
4802
4803
            // check if is an assignment
4804
            //$icon_assignment = null;
4805
            if ($current_row['assignment'] == 1) {
4806
                Display::addFlash(
4807
                    Display::return_message(
4808
                        get_lang('EditAssignmentWarning'),
4809
                        'normal',
4810
                        false
4811
                    )
4812
                );
4813
            } elseif ($current_row['assignment'] == 2) {
4814 View Code Duplication
                if (($userId == $current_row['user_id']) == false) {
4815
                    if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4816
                        $PassEdit = true;
4817
                    } else {
4818
                        Display::addFlash(
4819
                            Display::return_message(
4820
                                get_lang('LockByTeacher'),
4821
                                'normal',
4822
                                false
4823
                            )
4824
                        );
4825
                        $PassEdit = false;
4826
                    }
4827
                } else {
4828
                    $PassEdit = true;
4829
                }
4830
            }
4831
4832
            //show editor if edit is allowed
4833
            if ($PassEdit) {
4834
                if ($current_row['editlock'] == 1 &&
4835
                    (api_is_allowed_to_edit(false, true) == false || api_is_platform_admin() == false)
4836
                ) {
4837
                    Display::addFlash(Display::return_message(get_lang('PageLockedExtra'), 'normal', false));
4838
                } else {
4839
                    if ($last_row['is_editing'] != 0 && $last_row['is_editing'] != $userId) {
4840
                        // Checking for concurrent users
4841
                        $timestamp_edit = strtotime($last_row['time_edit']);
4842
                        $time_editing = time() - $timestamp_edit;
4843
                        $max_edit_time = 1200; // 20 minutes
4844
                        $rest_time = $max_edit_time - $time_editing;
4845
                        $userinfo = api_get_user_info($last_row['is_editing']);
4846
                        $is_being_edited = get_lang(
4847
                                'ThisPageisBeginEditedBy'
4848
                            ).' <a href='.$userinfo['profile_url'].'>'.
4849
                            Display::tag(
4850
                                'span',
4851
                                $userinfo['complete_name_with_username']
4852
                            ).
4853
                            get_lang('ThisPageisBeginEditedTryLater').' '.date(
4854
                                "i",
4855
                                $rest_time
4856
                            ).' '.get_lang('MinMinutes');
4857
                        Display::addFlash(
4858
                            Display::return_message(
4859
                                $is_being_edited,
4860
                                'normal',
4861
                                false
4862
                            )
4863
                        );
4864
                    } else {
4865
                        Display::addFlash(
4866
                            Display::return_message(
4867
                                self::restore_wikipage(
4868
                                    $current_row['page_id'],
4869
                                    $current_row['reflink'],
4870
                                    $current_row['title'],
4871
                                    $current_row['content'],
4872
                                    $current_row['group_id'],
4873
                                    $current_row['assignment'],
4874
                                    $current_row['progress'],
4875
                                    $current_row['version'],
4876
                                    $last_row['version'],
4877
                                    $current_row['linksto']
4878
                                ).': <a href="index.php?cidReq='.$_course['code'].'&action=showpage&amp;title='.api_htmlentities(
4879
                                    urlencode($last_row['reflink'])
4880
                                ).'&session_id='.$last_row['session_id'].'&group_id='.$last_row['group_id'].'">'.
4881
                                api_htmlentities($last_row['title']).'</a>',
4882
                                'confirmation',
4883
                                false
4884
                            )
4885
                        );
4886
                    }
4887
                }
4888
            }
4889
        }
4890
    }
4891
4892
    /**
4893
     * @param int|bool $wikiId
4894
     */
4895
    public function setWikiData($wikiId)
4896
    {
4897
        $this->wikiData = self::getWikiDataFromDb($wikiId);
4898
    }
4899
4900
    /**
4901
     * @return array
4902
     */
4903
    public function getWikiData()
4904
    {
4905
        return $this->wikiData;
4906
    }
4907
4908
    /**
4909
     * Check last version
4910
     * @param int $view
4911
     * @return bool
4912
     */
4913
    public function checkLastVersion($view)
4914
    {
4915
        $tbl_wiki = $this->tbl_wiki;
4916
        $course_id = $this->course_id;
4917
        $condition_session = $this->condition_session;
4918
        $groupfilter = $this->groupfilter;
4919
        $page = $this->page;
4920
        $_course = $this->courseInfo;
4921
4922
        if (empty($view)) {
4923
            return false;
4924
        }
4925
4926
        $current_row = $this->getWikiData();
4927
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4928
                WHERE
4929
                    c_id = '.$course_id.' AND
4930
                    reflink = "'.Database::escape_string($page).'" AND
4931
                    '.$groupfilter.$condition_session.'
4932
                ORDER BY id DESC'; //last version
4933
        $result = Database::query($sql);
4934
        $last_row = Database::fetch_array($result);
4935
4936
        if ($view < $last_row['id']) {
4937
            $message = '<center>'.get_lang('NoAreSeeingTheLastVersion').'<br />
4938
            '.get_lang("Version").' (
4939
            <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').'">
4940
            '.$current_row['version'].'
4941
            </a> /
4942
            <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').'">
4943
            '.$last_row['version'].'
4944
            </a>) <br />'.get_lang("ConvertToLastVersion").':
4945
            <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']).'">'.
4946
                get_lang("Restore").'</a></center>';
4947
            Display::addFlash(Display::return_message($message, 'warning', false));
4948
        }
4949
    }
4950
4951
    /**
4952
     *  Get most linked pages
4953
     */
4954
    public function getMostLinked()
4955
    {
4956
        $tbl_wiki = $this->tbl_wiki;
4957
        $course_id = $this->course_id;
4958
        $groupfilter = $this->groupfilter;
4959
        $condition_session = $this->condition_session;
4960
        $_course = $this->courseInfo;
4961
4962
        echo '<div class="actions">'.get_lang('MostLinkedPages').'</div>';
4963
        $pages = array();
4964
        $linked = array();
4965
4966
        // Get name pages
4967
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4968
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
4969
                GROUP BY reflink
4970
                ORDER BY reflink ASC';
4971
        $allpages = Database::query($sql);
4972 View Code Duplication
        while ($row = Database::fetch_array($allpages)) {
4973
            if ($row['reflink'] == 'index') {
4974
                $row['reflink'] = str_replace(
4975
                    ' ',
4976
                    '_',
4977
                    get_lang('DefaultTitle')
4978
                );
4979
            }
4980
            $pages[] = $row['reflink'];
4981
        }
4982
4983
        // Get name refs in last pages
4984
        $sql = 'SELECT *
4985
                FROM '.$tbl_wiki.' s1
4986
                WHERE s1.c_id = '.$course_id.' AND id=(
4987
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
4988
                    WHERE
4989
                        s2.c_id = '.$course_id.' AND
4990
                        s1.reflink = s2.reflink AND
4991
                        '.$groupfilter.$condition_session.'
4992
                )';
4993
4994
        $allpages = Database::query($sql);
4995
4996
        while ($row = Database::fetch_array($allpages)) {
4997
            //remove self reference
4998
            $row['linksto'] = str_replace(
4999
                $row["reflink"],
5000
                " ",
5001
                trim($row["linksto"])
5002
            );
5003
            $refs = explode(" ", trim($row["linksto"]));
5004
5005
            // Find linksto into reflink. If found ->page is linked
5006
            foreach ($refs as $v) {
5007
                if (in_array($v, $pages)) {
5008
                    if (trim($v) != "") {
5009
                        $linked[] = $v;
5010
                    }
5011
                }
5012
            }
5013
        }
5014
5015
        $linked = array_unique($linked);
5016
        //make a unique list. TODO:delete this line and count how many for each page
5017
        //show table
5018
        $rows = array();
5019
        foreach ($linked as $linked_show) {
5020
            $row = array();
5021
            $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']).'">'.
5022
                str_replace('_', ' ', $linked_show).'</a>';
5023
            $rows[] = $row;
5024
        }
5025
5026
        $table = new SortableTableFromArrayConfig(
5027
            $rows,
5028
            0,
5029
            10,
5030
            'LinkedPages_table',
5031
            '',
5032
            '',
5033
            'DESC'
5034
        );
5035
        $table->set_additional_parameters(
5036
            array(
5037
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5038
                'action' => Security::remove_XSS($this->action),
5039
                'session_id' => intval($_GET['session_id']),
5040
                'group_id' => intval($_GET['group_id']),
5041
            )
5042
        );
5043
        $table->set_header(0, get_lang('Title'), true);
5044
        $table->display();
5045
    }
5046
5047
    /**
5048
     * Get orphan pages
5049
     */
5050
    public function getOrphaned()
5051
    {
5052
        $tbl_wiki = $this->tbl_wiki;
5053
        $course_id = $this->course_id;
5054
        $groupfilter = $this->groupfilter;
5055
        $condition_session = $this->condition_session;
5056
        $_course = $this->courseInfo;
5057
5058
        echo '<div class="actions">'.get_lang('OrphanedPages').'</div>';
5059
5060
        $pages = array();
5061
        $orphaned = array();
5062
5063
        //get name pages
5064
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5065
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5066
                GROUP BY reflink
5067
                ORDER BY reflink ASC';
5068
        $allpages = Database::query($sql);
5069
        while ($row = Database::fetch_array($allpages)) {
5070
            $pages[] = $row['reflink'];
5071
        }
5072
5073
        //get name refs in last pages and make a unique list
5074
        $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1
5075
                WHERE s1.c_id = '.$course_id.' AND id=(
5076
                SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5077
                WHERE
5078
                    s2.c_id = '.$course_id.' AND
5079
                    s1.reflink = s2.reflink AND
5080
                    '.$groupfilter.$condition_session.'
5081
                )';
5082
        $allpages = Database::query($sql);
5083
        $array_refs_linked = array();
5084
        while ($row = Database::fetch_array($allpages)) {
5085
            $row['linksto'] = str_replace(
5086
                $row["reflink"],
5087
                " ",
5088
                trim($row["linksto"])
5089
            ); //remove self reference
5090
            $refs = explode(" ", trim($row["linksto"]));
5091
            foreach ($refs as $ref_linked) {
5092
                if ($ref_linked == str_replace(
5093
                        ' ',
5094
                        '_',
5095
                        get_lang('DefaultTitle')
5096
                    )) {
5097
                    $ref_linked = 'index';
5098
                }
5099
                $array_refs_linked[] = $ref_linked;
5100
            }
5101
        }
5102
5103
        $array_refs_linked = array_unique($array_refs_linked);
5104
5105
        //search each name of list linksto into list reflink
5106
        foreach ($pages as $v) {
5107
            if (!in_array($v, $array_refs_linked)) {
5108
                $orphaned[] = $v;
5109
            }
5110
        }
5111
        $rows = array();
5112
        foreach ($orphaned as $orphaned_show) {
5113
            // get visibility status and title
5114
            $sql = 'SELECT *
5115
                    FROM  '.$tbl_wiki.'
5116
		            WHERE
5117
		                c_id = '.$course_id.' AND
5118
		                '.$groupfilter.$condition_session.' AND
5119
		                reflink="'.Database::escape_string($orphaned_show).'"
5120
                    GROUP BY reflink';
5121
            $allpages = Database::query($sql);
5122
            while ($row = Database::fetch_array($allpages)) {
5123
                $orphaned_title = $row['title'];
5124
                $orphaned_visibility = $row['visibility'];
5125 View Code Duplication
                if ($row['assignment'] == 1) {
5126
                    $ShowAssignment = Display::return_icon(
5127
                        'wiki_assignment.png',
5128
                        '',
5129
                        '',
5130
                        ICON_SIZE_SMALL
5131
                    );
5132
                } elseif ($row['assignment'] == 2) {
5133
                    $ShowAssignment = Display::return_icon(
5134
                        'wiki_work.png',
5135
                        '',
5136
                        '',
5137
                        ICON_SIZE_SMALL
5138
                    );
5139
                } elseif ($row['assignment'] == 0) {
5140
                    $ShowAssignment = Display::return_icon(
5141
                        'px_transparent.gif'
5142
                    );
5143
                }
5144
            }
5145
5146
            if (!api_is_allowed_to_edit(false, true) || !api_is_platform_admin(
5147
                ) && $orphaned_visibility == 0) {
5148
                continue;
5149
            }
5150
5151
            //show table
5152
            $row = array();
5153
            $row[] = $ShowAssignment;
5154
            $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']).'">'.
5155
                api_htmlentities($orphaned_title).'</a>';
5156
            $rows[] = $row;
5157
        }
5158
5159
        $table = new SortableTableFromArrayConfig(
5160
            $rows,
5161
            1,
5162
            10,
5163
            'OrphanedPages_table',
5164
            '',
5165
            '',
5166
            'DESC'
5167
        );
5168
        $table->set_additional_parameters(
5169
            array(
5170
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5171
                'action' => Security::remove_XSS($this->action),
5172
                'session_id' => intval($_GET['session_id']),
5173
                'group_id' => intval($_GET['group_id']),
5174
            )
5175
        );
5176
        $table->set_header(
5177
            0,
5178
            get_lang('Type'),
5179
            true,
5180
            array('style' => 'width:30px;')
5181
        );
5182
        $table->set_header(1, get_lang('Title'), true);
5183
        $table->display();
5184
    }
5185
5186
    /**
5187
     * Get wanted pages
5188
     */
5189
    public function getWantedPages()
5190
    {
5191
        $tbl_wiki = $this->tbl_wiki;
5192
        $course_id = $this->course_id;
5193
        $groupfilter = $this->groupfilter;
5194
        $condition_session = $this->condition_session;
5195
5196
        echo '<div class="actions">'.get_lang('WantedPages').'</div>';
5197
        $pages = array();
5198
        $wanted = array();
5199
        //get name pages
5200
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5201
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5202
                GROUP BY reflink
5203
                ORDER BY reflink ASC';
5204
        $allpages = Database::query($sql);
5205
5206 View Code Duplication
        while ($row = Database::fetch_array($allpages)) {
5207
            if ($row['reflink'] == 'index') {
5208
                $row['reflink'] = str_replace(
5209
                    ' ',
5210
                    '_',
5211
                    get_lang('DefaultTitle')
5212
                );
5213
            }
5214
            $pages[] = $row['reflink'];
5215
        }
5216
5217
        //get name refs in last pages
5218
        $sql = 'SELECT * FROM   '.$tbl_wiki.' s1
5219
                WHERE s1.c_id = '.$course_id.' AND id=(
5220
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5221
                    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.$condition_session.'
5222
                )';
5223
5224
        $allpages = Database::query($sql);
5225
5226
        while ($row = Database::fetch_array($allpages)) {
5227
            $refs = explode(" ", trim($row["linksto"]));
5228
            // Find linksto into reflink. If not found ->page is wanted
5229
            foreach ($refs as $v) {
5230
                if (!in_array($v, $pages)) {
5231
                    if (trim($v) != "") {
5232
                        $wanted[] = $v;
5233
                    }
5234
                }
5235
            }
5236
        }
5237
5238
        $wanted = array_unique($wanted); //make a unique list
5239
5240
        //show table
5241
        $rows = array();
5242
        foreach ($wanted as $wanted_show) {
5243
            $row = array();
5244
            $wanted_show = Security::remove_XSS($wanted_show);
5245
            $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
5246
            $rows[] = $row;
5247
        }
5248
5249
        $table = new SortableTableFromArrayConfig(
5250
            $rows,
5251
            0,
5252
            10,
5253
            'WantedPages_table',
5254
            '',
5255
            '',
5256
            'DESC'
5257
        );
5258
        $table->set_additional_parameters(
5259
            array(
5260
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5261
                'action' => Security::remove_XSS($this->action),
5262
                'session_id' => intval($_GET['session_id']),
5263
                'group_id' => intval($_GET['group_id']),
5264
            )
5265
        );
5266
        $table->set_header(0, get_lang('Title'), true);
5267
        $table->display();
5268
    }
5269
5270
    /**
5271
     * Most visited
5272
     */
5273 View Code Duplication
    public function getMostVisited()
5274
    {
5275
        $tbl_wiki = $this->tbl_wiki;
5276
        $course_id = $this->course_id;
5277
        $groupfilter = $this->groupfilter;
5278
        $condition_session = $this->condition_session;
5279
        $_course = $this->courseInfo;
5280
5281
        echo '<div class="actions">'.get_lang('MostVisitedPages').'</div>';
5282
5283
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) { //only by professors if page is hidden
5284
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5285
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5286
                    GROUP BY reflink';
5287
        } else {
5288
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5289
                    WHERE
5290
                        c_id = '.$course_id.' AND
5291
                        '.$groupfilter.$condition_session.' AND
5292
                        visibility=1
5293
                    GROUP BY reflink';
5294
        }
5295
5296
        $allpages = Database::query($sql);
5297
5298
        //show table
5299
        if (Database::num_rows($allpages) > 0) {
5300
            $rows = array();
5301
            while ($obj = Database::fetch_object($allpages)) {
5302
                //get type assignment icon
5303
                $ShowAssignment = '';
5304
                if ($obj->assignment == 1) {
5305
                    $ShowAssignment = Display::return_icon(
5306
                        'wiki_assignment.png',
5307
                        get_lang('AssignmentDesc'),
5308
                        '',
5309
                        ICON_SIZE_SMALL
5310
                    );
5311
                } elseif ($obj->assignment == 2) {
5312
                    $ShowAssignment = $ShowAssignment = Display::return_icon(
5313
                        'wiki_work.png',
5314
                        get_lang('AssignmentWork'),
5315
                        '',
5316
                        ICON_SIZE_SMALL
5317
                    );
5318
                } elseif ($obj->assignment == 0) {
5319
                    $ShowAssignment = Display::return_icon(
5320
                        'px_transparent.gif'
5321
                    );
5322
                }
5323
5324
                $row = array();
5325
                $row[] = $ShowAssignment;
5326
                $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']).'">'.
5327
                    api_htmlentities($obj->title).'</a>';
5328
                $row[] = $obj->tsum;
5329
                $rows[] = $row;
5330
            }
5331
5332
            $table = new SortableTableFromArrayConfig(
5333
                $rows,
5334
                2,
5335
                10,
5336
                'MostVisitedPages_table',
5337
                '',
5338
                '',
5339
                'DESC'
5340
            );
5341
            $table->set_additional_parameters(
5342
                array(
5343
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5344
                    'action' => Security::remove_XSS($this->action),
5345
                    'session_id' => intval($_GET['session_id']),
5346
                    'group_id' => intval($_GET['group_id']),
5347
                )
5348
            );
5349
            $table->set_header(
5350
                0,
5351
                get_lang('Type'),
5352
                true,
5353
                array('style' => 'width:30px;')
5354
            );
5355
            $table->set_header(1, get_lang('Title'), true);
5356
            $table->set_header(2, get_lang('Visits'), true);
5357
            $table->display();
5358
        }
5359
    }
5360
5361
    /**
5362
     * Get actions bar
5363
     * @return string
5364
     */
5365
    public function showActionBar()
5366
    {
5367
        $_course = $this->courseInfo;
5368
        $session_id = $this->session_id;
5369
        $groupId = $this->group_id;
5370
        $page = $this->page;
5371
        $actionsLeft = '';
5372
        $actionsLeft .= '<a href="index.php?action=showpage&title=index&cidReq='.$_course['id'].'&session_id='.$session_id.'&group_id='.$groupId.'">'.
5373
            Display::return_icon(
5374
                'home.png',
5375
                get_lang('Home'),
5376
                '',
5377
                ICON_SIZE_MEDIUM
5378
            ).'</a>';
5379
5380
        if (api_is_allowed_to_session_edit(false, true) && api_is_allowed_to_edit()) {
5381
            // menu add page
5382
            $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=addnew&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab('addnew').'>'
5383
            . Display::return_icon('add.png', get_lang('AddNew'), '', ICON_SIZE_MEDIUM).'</a>';
5384
        }
5385
5386
        $lock_unlock_addnew = null;
5387
        $protect_addnewpage = null;
5388
5389 View Code Duplication
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5390
            // page action: enable or disable the adding of new pages
5391
            if (self::check_addnewpagelock() == 0) {
5392
                $protect_addnewpage = Display::return_icon(
5393
                    'off.png',
5394
                    get_lang('AddOptionProtected')
5395
                );
5396
                $lock_unlock_addnew = 'unlockaddnew';
5397
            } else {
5398
                $protect_addnewpage = Display::return_icon(
5399
                    'on.png',
5400
                    get_lang('AddOptionUnprotected')
5401
                );
5402
                $lock_unlock_addnew = 'lockaddnew';
5403
            }
5404
        }
5405
5406
        // menu find
5407
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab('searchpages').'>'.
5408
            Display::return_icon('search.png', get_lang('SearchPages'), '', ICON_SIZE_MEDIUM).'</a></li>';
5409
        ///menu more
5410
        $actionsLeft .= '<a href="index.php?action=more&amp;title='.api_htmlentities(urlencode($page)).'"'.self::is_active_navigation_tab('more').'>'.
5411
            Display::return_icon('stats.png', get_lang('Statistics'), '', ICON_SIZE_MEDIUM).'</a></li>';
5412
5413
        // menu all pages
5414
        $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').'>'.
5415
            get_lang('AllPages').'</a>';
5416
        // menu recent changes
5417
        $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').'>'.
5418
            get_lang('RecentChanges').'</a>';
5419
        echo Display::toolbarAction('toolbar-wiki', [$actionsLeft]);
5420
    }
5421
5422
    /**
5423
     * Showing warning
5424
     */
5425
    public function deletePageWarning()
5426
    {
5427
        $page = $this->page;
5428
        $course_id = $this->course_id;
5429
        $groupfilter = $this->groupfilter;
5430
        $condition_session = $this->condition_session;
5431
5432 View Code Duplication
        if (!$_GET['title']) {
5433
            Display::addFlash(
5434
                Display::return_message(
5435
                    get_lang('MustSelectPage'),
5436
                    'error',
5437
                    false
5438
                )
5439
            );
5440
5441
            return;
5442
        }
5443
5444
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5445
            Display::addFlash('<div id="wikititle">'.get_lang('DeletePageHistory').'</div>');
5446
            if ($page == "index") {
5447
                Display::addFlash(
5448
                    Display::return_message(
5449
                        get_lang('WarningDeleteMainPage'),
5450
                        'warning',
5451
                        false
5452
                    )
5453
                );
5454
            }
5455
            $message = get_lang('ConfirmDeletePage')."
5456
                <a href=\"index.php?".api_get_cidreq()."\">".get_lang("No")."</a>
5457
                <a href=\"".api_get_self()."?".api_get_cidreq()."&action=delete&title=".api_htmlentities(urlencode($page))."&delete=yes\">".
5458
                get_lang("Yes")."</a>";
5459
5460
            if (!isset($_GET['delete'])) {
5461
                Display::addFlash(Display::return_message($message, 'warning', false));
5462
            }
5463
5464
            if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
5465
                $result = self::deletePage($page, $course_id, $groupfilter, $condition_session);
5466
                if ($result) {
5467
                    Display::addFlash(
5468
                        Display::return_message(
5469
                            get_lang('WikiPageDeleted'),
5470
                            'confirmation',
5471
                            false
5472
                        )
5473
                    );
5474
                }
5475
            }
5476
        } else {
5477
            Display::addFlash(
5478
                Display::return_message(
5479
                    get_lang('OnlyAdminDeletePageWiki'),
5480
                    'normal',
5481
                    false
5482
                )
5483
            );
5484
        }
5485
    }
5486
5487
    /**
5488
     * Edit page
5489
     */
5490
    public function editPage()
5491
    {
5492
        $tbl_wiki = $this->tbl_wiki;
5493
        $tbl_wiki_conf = $this->tbl_wiki_conf;
5494
        $condition_session = $this->condition_session;
5495
        $groupfilter = $this->groupfilter;
5496
        $page = $this->page;
5497
        $course_id = $this->course_id;
5498
        $groupId = $this->group_id;
5499
        $userId = api_get_user_id();
5500
5501 View Code Duplication
        if (api_get_session_id() != 0 &&
5502
            api_is_allowed_to_session_edit(false, true) == false
5503
        ) {
5504
            api_not_allowed();
5505
        }
5506
5507
        $sql = 'SELECT *
5508
                FROM '.$tbl_wiki.' w INNER JOIN '.$tbl_wiki_conf.' c
5509
                ON  (w.c_id = c.c_id AND w.page_id = c.page_id)
5510
                WHERE
5511
    		        w.c_id = '.$course_id.' AND
5512
                    w.reflink= "'.Database::escape_string($page).'" AND
5513
                    w.'.$groupfilter.$condition_session.'
5514
                ORDER BY id DESC';
5515
        $result = Database::query($sql);
5516
        $row = Database::fetch_array($result);
5517
5518
        // we do not need a while loop since we are always displaying the last version
5519
        if ($row['content'] == '' && $row['title'] == '' && $page == '') {
5520
            Display::addFlash(
5521
                Display::return_message(
5522
                    get_lang('MustSelectPage'),
5523
                    'error',
5524
                    false
5525
                )
5526
            );
5527
            return;
5528
        } elseif ($row['content'] == '' && $row['title'] == '' && $page == 'index') {
5529
5530
            // Table structure for better export to pdf
5531
            $default_table_for_content_Start = '<table align="center" border="0"><tr><td align="center">';
5532
            $default_table_for_content_End = '</td></tr></table>';
5533
            $content = $default_table_for_content_Start.sprintf(get_lang('DefaultContent'), api_get_path(WEB_IMG_PATH)).$default_table_for_content_End;
5534
            $title = get_lang('DefaultTitle');
5535
            $page_id = 0;
5536
        } else {
5537
            $content = api_html_entity_decode($row['content']);
5538
            $title = api_html_entity_decode($row['title']);
5539
            $page_id = $row['page_id'];
5540
        }
5541
5542
        // Only teachers and platform admin can edit the index page.
5543
        // Only teachers and platform admin can edit an assignment teacher.
5544
        // And users in groups
5545
5546
        if (($row['reflink'] == 'index' || $row['reflink'] == '' || $row['assignment'] == 1) &&
5547
            (!api_is_allowed_to_edit(false, true) && $groupId == 0) && !api_is_allowed_in_course()
5548
        ) {
5549
            Display::addFlash(
5550
                Display::return_message(get_lang('OnlyEditPagesCourseManager')),
5551
                'error'
5552
            );
5553
        } else {
5554
            $PassEdit = false;
5555
5556
            // Check if is a wiki group
5557
            if (!empty($groupId)) {
5558
                $groupInfo = GroupManager::get_group_properties($groupId);
5559
                //Only teacher, platform admin and group members can edit a wiki group
5560 View Code Duplication
                if (api_is_allowed_to_edit(false, true) ||
5561
                    api_is_platform_admin() ||
5562
                    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 5558 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...
5563
                ) {
5564
                    $PassEdit = true;
5565
                } else {
5566
                    Display::addFlash(
5567
                        Display::return_message(
5568
                            get_lang('OnlyEditPagesGroupMembers')
5569
                        )
5570
                    );
5571
                }
5572
            } else {
5573
                $PassEdit = true;
5574
            }
5575
5576
            $icon_assignment = null;
5577
            // check if is a assignment
5578
            if ($row['assignment'] == 1) {
5579
                Display::addFlash(
5580
                    Display::return_message(get_lang('EditAssignmentWarning'))
5581
                );
5582
5583
                $icon_assignment = Display::return_icon(
5584
                    'wiki_assignment.png',
5585
                    get_lang('AssignmentDescExtra'),
5586
                    '',
5587
                    ICON_SIZE_SMALL
5588
                );
5589
            } elseif ($row['assignment'] == 2) {
5590
                $icon_assignment = Display::return_icon(
5591
                    'wiki_work.png',
5592
                    get_lang('AssignmentWorkExtra'),
5593
                    '',
5594
                    ICON_SIZE_SMALL
5595
                );
5596 View Code Duplication
                if (($userId == $row['user_id']) == false) {
5597
                    if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5598
                        $PassEdit = true;
5599
                    } else {
5600
                        Display::addFlash(
5601
                            Display::return_message(
5602
                                get_lang('LockByTeacher'),
5603
                                'warning'
5604
                            )
5605
                        );
5606
                        $PassEdit = false;
5607
                    }
5608
                } else {
5609
                    $PassEdit = true;
5610
                }
5611
            }
5612
5613
            if ($PassEdit) {
5614
                //show editor if edit is allowed <<<<<
5615
                if ($row['editlock'] == 1 &&
5616
                    (api_is_allowed_to_edit(false, true) == false || api_is_platform_admin() == false)
5617
                ) {
5618
                    Display::addFlash(
5619
                        Display::return_message(
5620
                            get_lang('PageLockedExtra')
5621
                        )
5622
                    );
5623
                } else {
5624
                    // Check tasks
5625
5626
                    if (!empty($row['startdate_assig']) && time() < api_strtotime($row['startdate_assig'])
5627
                    ) {
5628
                        $message = get_lang('TheTaskDoesNotBeginUntil').': '.api_get_local_time($row['startdate_assig']);
5629
5630
                        Display::addFlash(
5631
                            Display::return_message(
5632
                                $message,
5633
                                'warning'
5634
                            )
5635
                        );
5636
5637
                        if (!api_is_allowed_to_edit(false, true)) {
5638
                            $this->redirectHome();
5639
                        }
5640
                    }
5641
5642
                    if (!empty($row['enddate_assig']) &&
5643
                        time() > strtotime($row['enddate_assig']) &&
5644
                        $row['delayedsubmit'] == 0
5645
                    ) {
5646
                        $message = get_lang('TheDeadlineHasBeenCompleted').': '.api_get_local_time($row['enddate_assig']);
5647
                        Display::addFlash(
5648
                            Display::return_message(
5649
                                $message,
5650
                                'warning'
5651
                            )
5652
                        );
5653
                        if (!api_is_allowed_to_edit(false, true)) {
5654
                            $this->redirectHome();
5655
                        }
5656
                    }
5657
5658 View Code Duplication
                    if (!empty($row['max_version']) && $row['version'] >= $row['max_version']) {
5659
                        $message = get_lang('HasReachedMaxiNumVersions');
5660
                        Display::addFlash(
5661
                            Display::return_message(
5662
                                $message,
5663
                                'warning'
5664
                            )
5665
                        );
5666
                        if (!api_is_allowed_to_edit(false, true)) {
5667
                            $this->redirectHome();
5668
                        }
5669
                    }
5670
5671 View Code Duplication
                    if (!empty($row['max_text']) && $row['max_text'] <= self::word_count($row['content'])) {
5672
                        $message = get_lang('HasReachedMaxNumWords');
5673
                        Display::addFlash(
5674
                            Display::return_message(
5675
                                $message,
5676
                                'warning'
5677
                            )
5678
                        );
5679
                        if (!api_is_allowed_to_edit(false, true)) {
5680
                            $this->redirectHome();
5681
                        }
5682
                    }
5683
5684
                    if (!empty($row['task'])) {
5685
                        //previous change 0 by text
5686 View Code Duplication
                        if (!empty($row['startdate_assig'])) {
5687
                            $message_task_startdate = get_lang('No');
5688
                        } else {
5689
                            $message_task_startdate = api_get_local_time(
5690
                                $row['startdate_assig']
5691
                            );
5692
                        }
5693
5694 View Code Duplication
                        if (!empty($row['enddate_assig'])) {
5695
                            $message_task_enddate = get_lang('No');
5696
                        } else {
5697
                            $message_task_enddate = api_get_local_time(
5698
                                $row['enddate_assig']
5699
                            );
5700
                        }
5701
5702
                        if ($row['delayedsubmit'] == 0) {
5703
                            $message_task_delayedsubmit = get_lang('No');
5704
                        } else {
5705
                            $message_task_delayedsubmit = get_lang('Yes');
5706
                        }
5707
5708
                        if ($row['max_version'] == 0) {
5709
                            $message_task_max_version = get_lang('No');
5710
                        } else {
5711
                            $message_task_max_version = $row['max_version'];
5712
                        }
5713
5714
                        if ($row['max_text'] == 0) {
5715
                            $message_task_max_text = get_lang('No');
5716
                        } else {
5717
                            $message_task_max_text = $row['max_text'];
5718
                        }
5719
5720
                        // Comp message
5721
                        $message_task = '<b>'.get_lang('DescriptionOfTheTask').'</b><p>'.$row['task'].'</p><hr>';
5722
                        $message_task .= '<p>'.get_lang('StartDate').': '.$message_task_startdate.'</p>';
5723
                        $message_task .= '<p>'.get_lang('EndDate').': '.$message_task_enddate;
5724
                        $message_task .= ' ('.get_lang('AllowLaterSends').') '.$message_task_delayedsubmit.'</p>';
5725
                        $message_task .= '<p>'.get_lang('OtherSettings').': '.get_lang('NMaxVersion').': '.$message_task_max_version;
5726
                        $message_task .= ' '.get_lang('NMaxWords').': '.$message_task_max_text;
5727
                        // Display message
5728
                        Display::addFlash(
5729
                            Display::return_message(
5730
                                $message_task
5731
                            )
5732
                        );
5733
                    }
5734
5735
                    $feedback_message = '';
5736
                    if ($row['progress'] == $row['fprogress1'] && !empty($row['fprogress1'])) {
5737
                        $feedback_message = '<b>'.get_lang('Feedback').'</b><p>'.api_htmlentities($row['feedback1']).'</p>';
5738
                    } elseif ($row['progress'] == $row['fprogress2'] && !empty($row['fprogress2'])) {
5739
                        $feedback_message = '<b>'.get_lang('Feedback').'</b><p>'.api_htmlentities($row['feedback2']).'</p>';
5740
                    } elseif ($row['progress'] == $row['fprogress3'] && !empty($row['fprogress3'])) {
5741
                        $feedback_message = '<b>'.get_lang('Feedback').'</b><p>'.api_htmlentities($row['feedback3']).'</p>';
5742
                    }
5743
5744
                    if (!empty($feedback_message)) {
5745
                        Display::addFlash(
5746
                            Display::return_message(
5747
                                $feedback_message
5748
                            )
5749
                        );
5750
                    }
5751
5752
                    // Previous checking for concurrent editions
5753
                    if ($row['is_editing'] == 0) {
5754
                        Display::addFlash(
5755
                            Display::return_message(
5756
                                get_lang('WarningMaxEditingTime')
5757
                            )
5758
                        );
5759
                        $time_edit = api_get_utc_datetime();
5760
                        $sql = 'UPDATE '.$tbl_wiki.' SET
5761
                                is_editing = "'.$userId.'",
5762
                                time_edit = "'.$time_edit.'"
5763
                                WHERE c_id = '.$course_id.' AND id="'.$row['id'].'"';
5764
                        Database::query($sql);
5765
                    } elseif ($row['is_editing'] != $userId) {
5766
                        $timestamp_edit = strtotime($row['time_edit']);
5767
                        $time_editing = time() - $timestamp_edit;
5768
                        $max_edit_time = 1200; // 20 minutes
5769
                        $rest_time = $max_edit_time - $time_editing;
5770
5771
                        $userinfo = api_get_user_info($row['is_editing']);
5772
                        if ($userinfo !== false) {
5773
                            $is_being_edited = get_lang('ThisPageisBeginEditedBy').' '.UserManager::getUserProfileLink($userinfo).'
5774
                            ' . get_lang('ThisPageisBeginEditedTryLater').' '.date("i", $rest_time).' '.get_lang('MinMinutes').'';
5775
                        }
5776
5777
                        Display::addFlash(
5778
                            Display::return_message(
5779
                                $is_being_edited,
5780
                                'normal',
5781
                                false
5782
                            )
5783
                        );
5784
5785
                        $this->redirectHome();
5786
                    }
5787
5788
                    // Form.
5789
                    $url = api_get_self().'?action=edit&title='.urlencode($page).'&session_id='.api_get_session_id().'&group_id='.api_get_group_id().'&'.api_get_cidreq();
5790
                    $form = new FormValidator('wiki', 'post', $url);
5791
                    $form->addElement('header', $icon_assignment.str_repeat('&nbsp;', 3).api_htmlentities($title));
5792
                    self::setForm($form, $row);
5793
                    $form->addElement('hidden', 'title');
5794
                    $form->addButtonSave(get_lang('Save'), 'SaveWikiChange');
5795
                    $row['title'] = $title;
5796
                    $row['page_id'] = $page_id;
5797
                    $row['reflink'] = $page;
5798
                    $row['content'] = $content;
5799
5800
                    $form->setDefaults($row);
5801
                    $form->display();
5802
5803
                    // Saving a change
5804
                    if ($form->validate()) {
5805
                        $versionFromSession = Session::read('_version');
5806
                        if (empty($_POST['title'])) {
5807
                            Display::addFlash(
5808
                                Display::return_message(
5809
                                    get_lang("NoWikiPageTitle"),
5810
                                    'error'
5811
                                )
5812
                            );
5813
                        } 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...
5814
                            //double post
5815
                        } elseif ($_POST['version'] != '' && $versionFromSession != 0 && $_POST['version'] != $versionFromSession) {
5816
                            //prevent concurrent users and double version
5817
                            Display::addFlash(
5818
                                Display::return_message(
5819
                                    get_lang("EditedByAnotherUser"),
5820
                                    'error'
5821
                                )
5822
                            );
5823
                        } else {
5824
                            $returnMessage = self::save_wiki(
5825
                                $form->exportValues()
5826
                            );
5827
                            Display::addFlash(
5828
                                Display::return_message(
5829
                                    $returnMessage,
5830
                                    'confirmation'
5831
                                )
5832
                            );
5833
                        }
5834
                        $wikiData = self::getWikiData();
5835
                        $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq();
5836
                        header('Location: '.$redirectUrl);
5837
                        exit;
5838
                    }
5839
                }
5840
            }
5841
        }
5842
    }
5843
5844
    /**
5845
     * Get history
5846
     */
5847
    public function getHistory()
5848
    {
5849
        $tbl_wiki = $this->tbl_wiki;
5850
        $condition_session = $this->condition_session;
5851
        $groupfilter = $this->groupfilter;
5852
        $page = $this->page;
5853
        $course_id = $this->course_id;
5854
        $session_id = $this->session_id;
5855
        $userId = api_get_user_id();
5856
5857 View Code Duplication
        if (!$_GET['title']) {
5858
            Display::addFlash(
5859
                Display::return_message(
5860
                    get_lang("MustSelectPage"),
5861
                    'error',
5862
                    false
5863
                )
5864
            );
5865
5866
            return;
5867
        }
5868
5869
        /* First, see the property visibility that is at the last register and
5870
        therefore we should select descending order.
5871
        But to give ownership to each record,
5872
        this is no longer necessary except for the title. TODO: check this*/
5873
5874
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5875
                WHERE
5876
                    c_id = '.$course_id.' AND
5877
                    reflink="'.Database::escape_string($page).'" AND
5878
                    '.$groupfilter.$condition_session.'
5879
                ORDER BY id DESC';
5880
        $result = Database::query($sql);
5881
5882
        $KeyVisibility = null;
5883
        $KeyAssignment = null;
5884
        $KeyTitle = null;
5885
        $KeyUserId = null;
5886
        while ($row = Database::fetch_array($result)) {
5887
            $KeyVisibility = $row['visibility'];
5888
            $KeyAssignment = $row['assignment'];
5889
            $KeyTitle = $row['title'];
5890
            $KeyUserId = $row['user_id'];
5891
        }
5892
        $icon_assignment = null;
5893
        if ($KeyAssignment == 1) {
5894
            $icon_assignment = Display::return_icon(
5895
                'wiki_assignment.png',
5896
                get_lang('AssignmentDescExtra'),
5897
                '',
5898
                ICON_SIZE_SMALL
5899
            );
5900
        } elseif ($KeyAssignment == 2) {
5901
            $icon_assignment = Display::return_icon(
5902
                'wiki_work.png',
5903
                get_lang('AssignmentWorkExtra'),
5904
                '',
5905
                ICON_SIZE_SMALL
5906
            );
5907
        }
5908
5909
        // Second, show
5910
5911
        //if the page is hidden and is a job only sees its author and professor
5912
        if ($KeyVisibility == 1 ||
5913
            api_is_allowed_to_edit(false, true) ||
5914
            api_is_platform_admin() ||
5915
            (
5916
                $KeyAssignment == 2 && $KeyVisibility == 0 &&
5917
                ($userId == $KeyUserId)
5918
            )
5919
        ) {
5920
            // We show the complete history
5921
            if (!isset($_POST['HistoryDifferences']) && !isset($_POST['HistoryDifferences2'])) {
5922
                $sql = 'SELECT * FROM '.$tbl_wiki.'
5923
                        WHERE
5924
                            c_id = '.$course_id.' AND
5925
                            reflink="'.Database::escape_string($page).'" AND
5926
                            '.$groupfilter.$condition_session.'
5927
                        ORDER BY id DESC';
5928
                $result = Database::query($sql);
5929
                $title = $_GET['title'];
5930
                $group_id = api_get_group_id();
5931
5932
                echo '<div id="wikititle">';
5933
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities(
5934
                        $KeyTitle
5935
                    );
5936
                echo '</div>';
5937
5938
                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).'">';
5939
5940
                echo '<ul style="list-style-type: none;">';
5941
                echo '<br/>';
5942
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.
5943
                    get_lang('ShowDifferences').' '.get_lang('LinesDiff').'</button>';
5944
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.
5945
                    get_lang('ShowDifferences').' '.get_lang('WordsDiff').'</button>';
5946
                echo '<br/><br/>';
5947
5948
                $counter = 0;
5949
                $total_versions = Database::num_rows($result);
5950
5951
                while ($row = Database::fetch_array($result)) {
5952
                    $userinfo = api_get_user_info($row['user_id']);
5953
                    $username = api_htmlentities(sprintf(get_lang('LoginX'), $userinfo['username']), ENT_QUOTES);
5954
5955
                    echo '<li style="margin-bottom: 5px;">';
5956
                    ($counter == 0) ? $oldstyle = 'style="visibility: hidden;"' : $oldstyle = '';
5957
                    ($counter == 0) ? $newchecked = ' checked' : $newchecked = '';
5958
                    ($counter == $total_versions - 1) ? $newstyle = 'style="visibility: hidden;"' : $newstyle = '';
5959
                    ($counter == 1) ? $oldchecked = ' checked' : $oldchecked = '';
5960
                    echo '<input name="old" value="'.$row['id'].'" type="radio" '.$oldstyle.' '.$oldchecked.'/> ';
5961
                    echo '<input name="new" value="'.$row['id'].'" type="radio" '.$newstyle.' '.$newchecked.'/> ';
5962
                    echo '<a href="'.api_get_self().'?action=showpage&amp;title='.api_htmlentities(urlencode($page)).'&amp;view='.$row['id'].'">';
5963
                    echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=showpage&title='.api_htmlentities(urlencode($page)).'&view='.$row['id'].'">';
5964
                    echo api_get_local_time($row['dtime'], null, date_default_timezone_get());
5965
                    echo '</a>';
5966
                    echo ' ('.get_lang('Version').' '.$row['version'].')';
5967
                    echo ' '.get_lang('By').' ';
5968
                    if ($userinfo !== false) {
5969
                        echo UserManager::getUserProfileLink($userinfo);
5970
                    } else {
5971
                        echo get_lang('Anonymous').' ('.api_htmlentities($row['user_ip']).')';
5972
                    }
5973
                    echo ' ( '.get_lang('Progress').': '.api_htmlentities($row['progress']).'%, ';
5974
                    $comment = $row['comment'];
5975
                    if (!empty($comment)) {
5976
                        $comment = api_substr($comment, 0, 100);
5977
                        if ($comment !== false) {
5978
                            $comment = api_htmlentities($comment);
5979
                            echo get_lang('Comments').': '.$comment;
5980
                            if (api_strlen($row['comment']) > 100) {
5981
                                echo '... ';
5982
                            }
5983
                        }
5984
                    } else {
5985
                        echo get_lang('Comments').':  ---';
5986
                    }
5987
                    echo ' ) </li>';
5988
                    $counter++;
5989
                } //end while
5990
5991
                echo '<br/>';
5992
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.get_lang('ShowDifferences').' '.get_lang('LinesDiff').'</button>';
5993
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.get_lang('ShowDifferences').' '.get_lang('WordsDiff').'</button>';
5994
                echo '</ul></form>';
5995
            } else { // We show the differences between two versions
5996
                $version_old = array();
5997 View Code Duplication
                if (isset($_POST['old'])) {
5998
                    $sql_old = "SELECT * FROM $tbl_wiki
5999
                                WHERE c_id = $course_id AND id='".Database::escape_string($_POST['old'])."'";
6000
                    $result_old = Database::query($sql_old);
6001
                    $version_old = Database::fetch_array($result_old);
6002
                }
6003
6004
                $sql_new = "SELECT * FROM $tbl_wiki
6005
                            WHERE c_id = $course_id AND id='".Database::escape_string($_POST['new'])."'";
6006
                $result_new = Database::query($sql_new);
6007
                $version_new = Database::fetch_array($result_new);
6008
                $oldTime = isset($version_old['dtime']) ? $version_old['dtime'] : null;
6009
                $oldContent = isset($version_old['content']) ? $version_old['content'] : null;
6010
6011
                if (isset($_POST['HistoryDifferences'])) {
6012
                    include 'diff.inc.php';
6013
                    //title
6014
                    echo '<div id="wikititle">'.api_htmlentities($version_new['title']).'
6015
                            <font size="-2"><i>('.get_lang('DifferencesNew').'</i>
6016
                            <font style="background-color:#aaaaaa">'.$version_new['dtime'].'</font>
6017
                            <i>'.get_lang('DifferencesOld').'</i>
6018
                            <font style="background-color:#aaaaaa">'.$oldTime.'</font>
6019
                ) '.get_lang('Legend').':  <span class="diffAdded" >'.get_lang('WikiDiffAddedLine').'</span>
6020
                <span class="diffDeleted" >'.get_lang('WikiDiffDeletedLine').'</span> <span class="diffMoved">'.get_lang('WikiDiffMovedLine').'</span></font>
6021
                </div>';
6022
                }
6023
                if (isset($_POST['HistoryDifferences2'])) {
6024
                    //title
6025
                    echo '<div id="wikititle">'.api_htmlentities($version_new['title']).'
6026
                        <font size="-2"><i>('.get_lang('DifferencesNew').'</i> <font style="background-color:#aaaaaa">'.$version_new['dtime'].'</font>
6027
                        <i>'.get_lang('DifferencesOld').'</i> <font style="background-color:#aaaaaa">'.$oldTime.'</font>)
6028
                        '.get_lang('Legend').':  <span class="diffAddedTex" >'.get_lang('WikiDiffAddedTex').'</span>
6029
                        <span class="diffDeletedTex" >'.get_lang('WikiDiffDeletedTex').'</span></font></div>';
6030
                }
6031
6032
6033
                if (isset($_POST['HistoryDifferences'])) {
6034
                    echo '<table>'.diff($oldContent, $version_new['content'], true, 'format_table_line').'</table>'; // format_line mode is better for words
6035
                    echo '<br />';
6036
                    echo '<strong>'.get_lang('Legend').'</strong><div class="diff">'."\n";
6037
                    echo '<table><tr>';
6038
                    echo  '<td>';
6039
                    echo '</td><td>';
6040
                    echo '<span class="diffEqual" >'.get_lang('WikiDiffUnchangedLine').'</span><br />';
6041
                    echo '<span class="diffAdded" >'.get_lang('WikiDiffAddedLine').'</span><br />';
6042
                    echo '<span class="diffDeleted" >'.get_lang('WikiDiffDeletedLine').'</span><br />';
6043
                    echo '<span class="diffMoved" >'.get_lang('WikiDiffMovedLine').'</span><br />';
6044
                    echo '</td>';
6045
                    echo '</tr></table>';
6046
                }
6047
6048
                if (isset($_POST['HistoryDifferences2'])) {
6049
                    $lines1 = array(strip_tags($oldContent)); //without <> tags
6050
                    $lines2 = array(strip_tags($version_new['content'])); //without <> tags
6051
                    $diff = new Text_Diff($lines1, $lines2);
6052
                    $renderer = new Text_Diff_Renderer_inline();
6053
                    echo '<style>del{background:#fcc}ins{background:#cfc}</style>'.$renderer->render($diff); // Code inline
6054
                    echo '<br />';
6055
                    echo '<strong>'.get_lang('Legend').'</strong><div class="diff">'."\n";
6056
                    echo '<table><tr>';
6057
                    echo  '<td>';
6058
                    echo '</td><td>';
6059
                    echo '<span class="diffAddedTex" >'.get_lang('WikiDiffAddedTex').'</span><br />';
6060
                    echo '<span class="diffDeletedTex" >'.get_lang('WikiDiffDeletedTex').'</span><br />';
6061
                    echo '</td>';
6062
                    echo '</tr></table>';
6063
                }
6064
            }
6065
        }
6066
    }
6067
6068
    /**
6069
     * Get stat tables
6070
     */
6071
    public function getStatsTable()
6072
    {
6073
        $_course = $this->courseInfo;
6074
        $session_id = $this->session_id;
6075
        $groupId = $this->group_id;
6076
6077
        echo '<div class="actions">'.get_lang('More').'</div>';
6078
        echo '<table border="0">';
6079
        echo '  <tr>';
6080
        echo '    <td>';
6081
        echo '      <ul>';
6082
        //Submenu Most active users
6083
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mactiveusers&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostActiveUsers').'</a></li>';
6084
        //Submenu Most visited pages
6085
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mvisited&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostVisitedPages').'</a></li>';
6086
        //Submenu Most changed pages
6087
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mostchanged&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostChangedPages').'</a></li>';
6088
        echo '      </ul>';
6089
        echo '    </td>';
6090
        echo '    <td>';
6091
        echo '      <ul>';
6092
        // Submenu Orphaned pages
6093
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=orphaned&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('OrphanedPages').'</a></li>';
6094
        // Submenu Wanted pages
6095
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=wanted&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('WantedPages').'</a></li>';
6096
        // Submenu Most linked pages
6097
        echo '<li><a href="index.php?cidReq='.$_course['code'].'&action=mostlinked&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostLinkedPages').'</a></li>';
6098
        echo '</ul>';
6099
        echo '</td>';
6100
        echo '<td style="vertical-align:top">';
6101
        echo '<ul>';
6102
        // Submenu Statistics
6103
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6104
            echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=statistics&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('Statistics').'</a></li>';
6105
        }
6106
        echo '      </ul>';
6107
        echo'    </td>';
6108
        echo '  </tr>';
6109
        echo '</table>';
6110
    }
6111
6112
    /**
6113
     * Kind of controller
6114
     * @param string $action
6115
     */
6116
    public function handleAction($action)
6117
    {
6118
        $page = $this->page;
6119
        switch ($action) {
6120
            case 'export_to_pdf':
6121
                if (isset($_GET['wiki_id'])) {
6122
                    self::export_to_pdf($_GET['wiki_id'], api_get_course_id());
6123
                    break;
6124
                }
6125
                break;
6126
            case 'export2doc':
6127
                if (isset($_GET['wiki_id'])) {
6128
                    $export2doc = self::export2doc($_GET['wiki_id']);
6129
                    if ($export2doc) {
6130
                        Display::addFlash(
6131
                            Display::return_message(
6132
                                get_lang('ThePageHasBeenExportedToDocArea'),
6133
                                'confirmation',
6134
                                false
6135
                            )
6136
                        );
6137
                    }
6138
                }
6139
                break;
6140
            case 'restorepage':
6141
                self::restorePage();
6142
                break;
6143
            case 'more':
6144
                self::getStatsTable();
6145
                break;
6146
            case 'statistics':
6147
                self::getStats();
6148
                break;
6149
            case 'mactiveusers':
6150
                self::getActiveUsers($action);
6151
                break;
6152
            case 'usercontrib':
6153
                self::getUserContributions($_GET['user_id'], $action);
6154
                break;
6155
            case 'mostchanged':
6156
                $this->getMostChangedPages($action);
6157
                break;
6158
            case 'mvisited':
6159
                self::getMostVisited();
6160
                break;
6161
            case 'wanted':
6162
                $this->getWantedPages();
6163
                break;
6164
            case 'orphaned':
6165
                self::getOrphaned();
6166
                break;
6167
            case 'mostlinked':
6168
                self::getMostLinked();
6169
                break;
6170
            case 'delete':
6171
                self::deletePageWarning($page);
6172
                break;
6173
            case 'deletewiki':
6174
                $title = '<div class="actions">'.get_lang('DeleteWiki').'</div>';
6175
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6176
                    $message = get_lang('ConfirmDeleteWiki');
6177
                    $message .= '<p>
6178
                        <a href="index.php?'.api_get_cidreq().'">'.get_lang('No').'</a>
6179
                        &nbsp;&nbsp;|&nbsp;&nbsp;
6180
                        <a href="'.api_get_self().'?'.api_get_cidreq().'&action=deletewiki&delete=yes">'.
6181
                        get_lang('Yes').'</a>
6182
                    </p>';
6183
6184 View Code Duplication
                    if (!isset($_GET['delete'])) {
6185
                        Display::addFlash(
6186
                            $title.Display::return_message(
6187
                                $message,
6188
                                'warning',
6189
                                false
6190
                            )
6191
                        );
6192
                    }
6193
                } else {
6194
                    Display::addFlash(
6195
                        Display::return_message(
6196
                            get_lang("OnlyAdminDeleteWiki"),
6197
                            'normal',
6198
                            false
6199
                        )
6200
                    );
6201
                }
6202
6203
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6204
                    if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
6205
                        $return_message = self::delete_wiki();
6206
                        Display::addFlash(
6207
                            Display::return_message(
6208
                                $return_message,
6209
                                'confirmation',
6210
                                false
6211
                            )
6212
                        );
6213
                        $this->redirectHome();
6214
                    }
6215
                }
6216
                break;
6217
            case 'searchpages':
6218
                self::getSearchPages($action);
6219
                break;
6220
            case 'links':
6221
                self::getLinks($page);
6222
                break;
6223
            case 'addnew':
6224 View Code Duplication
                if (api_get_session_id() != 0 && api_is_allowed_to_session_edit(false, true) == false) {
6225
                    api_not_allowed();
6226
                }
6227
                $groupInfo = GroupManager::get_group_properties(
6228
                    api_get_group_id()
6229
                );
6230
                echo '<div class="actions">'.get_lang('AddNew').'</div>';
6231
                echo '<br/>';
6232
                //first, check if page index was created. chektitle=false
6233
                if (self::checktitle('index')) {
6234
                    if (api_is_allowed_to_edit(false, true) ||
6235
                        api_is_platform_admin() ||
6236
                        GroupManager::is_user_in_group(
6237
                            api_get_user_id(),
6238
                            $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group...ies(api_get_group_id()) on line 6227 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...
6239
                        ) ||
6240
                        api_is_allowed_in_course()
6241
                    ) {
6242
                        Display::addFlash(
6243
                            Display::return_message(
6244
                                get_lang('GoAndEditMainPage'),
6245
                                'normal',
6246
                                false
6247
                            )
6248
                        );
6249
                    } else {
6250
                        Display::addFlash(
6251
                            Display::return_message(
6252
                                get_lang('WikiStandBy'),
6253
                                'normal',
6254
                                false
6255
                            )
6256
                        );
6257
                    }
6258
                } elseif (self::check_addnewpagelock() == 0 && (api_is_allowed_to_edit(false, true) == false || api_is_platform_admin() == false)) {
6259
                    Display::addFlash(Display::return_message(get_lang('AddPagesLocked'), 'error', false));
6260
                } else {
6261
                    $groupInfo = GroupManager::get_group_properties(
6262
                        api_get_group_id()
6263
                    );
6264
                    if (api_is_allowed_to_edit(false, true) ||
6265
                        api_is_platform_admin() ||
6266
                        GroupManager::is_user_in_group(
6267
                            api_get_user_id(),
6268
                            $groupInfo
0 ignored issues
show
Bug introduced by
It seems like $groupInfo defined by \GroupManager::get_group...ies(api_get_group_id()) on line 6261 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...
6269
                        ) ||
6270
                        $_GET['group_id'] == 0
6271
                    ) {
6272
                        self::display_new_wiki_form();
6273
                    } else {
6274
                        Display::addFlash(
6275
                            Display::return_message(
6276
                                get_lang('OnlyAddPagesGroupMembers'),
6277
                                'normal',
6278
                                false
6279
                            )
6280
                        );
6281
                    }
6282
                }
6283
                break;
6284
            case 'show':
6285
                self::display_wiki_entry($page);
6286
                break;
6287
            case 'showpage':
6288
                self::display_wiki_entry($page);
6289
                break;
6290
            case 'edit':
6291
                self::editPage();
6292
                break;
6293
            case 'history':
6294
                self::getHistory();
6295
                break;
6296
            case 'recentchanges':
6297
                self::recentChanges($page, $action);
6298
                break;
6299
            case 'allpages':
6300
                self::allPages($action);
6301
                break;
6302
            case 'discuss':
6303
                self::getDiscuss($page);
6304
                break;
6305
            case 'export_to_doc_file':
6306
                self::exportTo($_GET['id'], 'odt');
6307
                exit;
6308
                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...
6309
        }
6310
    }
6311
6312
    /**
6313
     * Redirect to home
6314
     */
6315
    public function redirectHome()
6316
    {
6317
        $redirectUrl = $this->url.'&action=showpage&title=index';
6318
        header('Location: '.$redirectUrl.'&'.api_get_cidreq());
6319
        exit;
6320
    }
6321
6322
    /**
6323
     * Export wiki content in a ODF
6324
     * @param int $id
6325
     * @param string int
6326
     * @return bool
6327
     */
6328
    public function exportTo($id, $format = 'doc')
6329
    {
6330
        $data = self::getWikiDataFromDb($id);
6331
6332
        if (isset($data['content']) && !empty($data['content'])) {
6333
            Export::htmlToOdt($data['content'], $data['reflink'], $format);
6334
        }
6335
6336
        return false;
6337
    }
6338
}
6339