Passed
Push — master ( 4aec42...69e1de )
by Julito
17:30
created

Wiki   F

Complexity

Total Complexity 695

Size/Duplication

Total Lines 7189
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 4737
dl 0
loc 7189
rs 0.8
c 0
b 0
f 0
wmc 695

67 Methods

Rating   Name   Duplication   Size   Complexity  
A delete_wiki() 0 38 3
B links_to() 0 32 7
A checktitle() 0 20 2
A __construct() 0 22 2
A detect_mail_link() 0 7 1
B make_wiki_link_clickable() 0 50 9
B display_new_wiki_form() 0 61 10
A detect_news_link() 0 7 1
A detect_ftp_link() 0 7 1
A detect_irc_link() 0 7 1
F save_new_wiki() 0 173 25
A restore_wikipage() 0 57 2
A detect_anchor_link() 0 7 1
A detect_external_link() 0 6 1
C setForm() 0 144 8
F save_wiki() 0 185 19
B check_addnewpagelock() 0 49 10
A wiki_exist() 0 19 2
B check_ratinglock_discuss() 0 59 9
B check_visibility_discuss() 0 57 9
A is_active_navigation_tab() 0 4 3
B check_notify_page() 0 70 10
B check_notify_all() 0 55 9
A double_post() 0 15 3
A word_count() 0 43 1
F display_wiki_entry() 0 398 51
B check_visibility_page() 0 62 10
C check_emailcue() 0 208 13
B check_notify_discuss() 0 59 8
C export2doc() 0 136 8
B check_protect_page() 0 46 9
A export_to_pdf() 0 65 4
B check_addlock_discuss() 0 57 9
B getWantedPages() 0 93 8
F getOrphaned() 0 139 15
F getStats() 0 680 28
D recentChanges() 0 157 13
F display_wiki_search_results() 0 300 21
A redirectHome() 0 5 1
B getSearchPages() 0 66 7
A updateWikiIsEditing() 0 15 1
C getUserContributions() 0 138 9
A checkLastVersion() 0 48 3
B deletePageWarning() 0 69 9
B getMostChangedPages() 0 89 8
B getActiveUsers() 0 69 5
A setWikiData() 0 3 1
A deletePage() 0 35 2
A getPageByTitle() 0 23 5
B getMostLinked() 0 96 8
D auto_add_page_users() 0 167 13
B showActionBar() 0 93 6
F restorePage() 0 145 23
F handleAction() 0 217 50
B blockConcurrentEditions() 0 22 7
F allPages() 0 219 16
A getWikiDataFromDb() 0 17 3
B getMostVisited() 0 91 8
A getStatsTable() 0 53 3
F editPage() 0 409 63
A getWikiData() 0 3 1
F getLinks() 0 169 15
F getDiscuss() 0 443 48
A getLastWikiData() 0 17 1
F getHistory() 0 295 29
A exportTo() 0 9 3
A getAllWiki() 0 13 1

How to fix   Complexity   

Complex Class

Complex classes like Wiki often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Wiki, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use ChamiloSession as Session;
6
7
/**
8
 * Class Wiki
9
 * Functions library for the wiki tool.
10
 *
11
 * @author Juan Carlos Raña <[email protected]>
12
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
13
 * @author Julio Montoya <[email protected]> using the pdf.lib.php library
14
 */
15
class Wiki
16
{
17
    public $tbl_wiki;
18
    public $tbl_wiki_discuss;
19
    public $tbl_wiki_mailcue;
20
    public $tbl_wiki_conf;
21
    public $session_id = null;
22
    public $course_id = null;
23
    public $condition_session = null;
24
    public $group_id;
25
    public $assig_user_id;
26
    public $groupfilter = 'group_id=0';
27
    public $courseInfo;
28
    public $charset;
29
    public $page;
30
    public $action;
31
    public $wikiData = [];
32
    public $url;
33
34
    /**
35
     * Constructor.
36
     */
37
    public function __construct()
38
    {
39
        // Database table definition
40
        $this->tbl_wiki = Database::get_course_table(TABLE_WIKI);
41
        $this->tbl_wiki_discuss = Database::get_course_table(
42
            TABLE_WIKI_DISCUSS
43
        );
44
        $this->tbl_wiki_mailcue = Database::get_course_table(
45
            TABLE_WIKI_MAILCUE
46
        );
47
        $this->tbl_wiki_conf = Database::get_course_table(TABLE_WIKI_CONF);
48
49
        $this->session_id = api_get_session_id();
50
        $this->condition_session = api_get_session_condition($this->session_id);
51
        $this->course_id = api_get_course_int_id();
52
        $this->group_id = api_get_group_id();
53
54
        if (!empty($this->group_id)) {
55
            $this->groupfilter = ' group_id="'.$this->group_id.'"';
56
        }
57
        $this->courseInfo = api_get_course_info();
58
        $this->url = api_get_path(WEB_CODE_PATH).'wiki/index.php?'.api_get_cidreq();
59
    }
60
61
    /**
62
     * Check whether this title is already used.
63
     *
64
     * @param string $link
65
     *
66
     * @return bool False if title is already taken
67
     *
68
     * @author Patrick Cool <[email protected]>, Ghent University
69
     */
70
    public function checktitle($link)
71
    {
72
        $tbl_wiki = $this->tbl_wiki;
73
        $condition_session = $this->condition_session;
74
        $course_id = $this->course_id;
75
        $groupfilter = $this->groupfilter;
76
77
        $sql = 'SELECT * FROM '.$tbl_wiki.'
78
                WHERE
79
                    c_id = '.$course_id.' AND
80
                    reflink="'.Database::escape_string($link).'" AND
81
                    '.$groupfilter.$condition_session.'';
82
        $result = Database::query($sql);
83
        $num = Database::num_rows($result);
84
        // the value has not been found and is this available
85
        if (0 == $num) {
86
            return true;
87
        }
88
89
        return false;
90
    }
91
92
    /**
93
     * check wikilinks that has a page.
94
     *
95
     * @author Juan Carlos Raña <[email protected]>
96
     *
97
     * @param string $input
98
     *
99
     * @return string
100
     */
101
    public function links_to($input)
102
    {
103
        $input_array = preg_split(
104
            "/(\[\[|\]\])/",
105
            $input,
106
            -1,
107
            PREG_SPLIT_DELIM_CAPTURE
108
        );
109
        $all_links = [];
110
111
        foreach ($input_array as $key => $value) {
112
            if (isset($input_array[$key - 1]) && '[[' == $input_array[$key - 1] &&
113
                isset($input_array[$key + 1]) && ']]' == $input_array[$key + 1]
114
            ) {
115
                if (false !== api_strpos($value, "|")) {
116
                    $full_link_array = explode("|", $value);
117
                    $link = trim($full_link_array[0]);
118
                    $title = trim($full_link_array[1]);
119
                } else {
120
                    $link = trim($value);
121
                    $title = trim($value);
122
                }
123
                unset($input_array[$key - 1]);
124
                unset($input_array[$key + 1]);
125
                //replace blank spaces by _ within the links. But to remove links at the end add a blank space
126
                $all_links[] = Database::escape_string(
127
                    str_replace(' ', '_', $link)
128
                ).' ';
129
            }
130
        }
131
132
        return implode($all_links);
133
    }
134
135
    /**
136
     * detect and add style to external links.
137
     *
138
     * @author Juan Carlos Raña Trabado
139
     */
140
    public function detect_external_link($input)
141
    {
142
        $exlink = 'href=';
143
        $exlinkStyle = 'class="wiki_link_ext" href=';
144
145
        return str_replace($exlink, $exlinkStyle, $input);
146
    }
147
148
    /**
149
     * detect and add style to anchor links.
150
     *
151
     * @author Juan Carlos Raña Trabado
152
     */
153
    public function detect_anchor_link($input)
154
    {
155
        $anchorlink = 'href="#';
156
        $anchorlinkStyle = 'class="wiki_anchor_link" href="#';
157
        $output = str_replace($anchorlink, $anchorlinkStyle, $input);
158
159
        return $output;
160
    }
161
162
    /**
163
     * detect and add style to mail links
164
     * author Juan Carlos Raña Trabado.
165
     */
166
    public function detect_mail_link($input)
167
    {
168
        $maillink = 'href="mailto';
169
        $maillinkStyle = 'class="wiki_mail_link" href="mailto';
170
        $output = str_replace($maillink, $maillinkStyle, $input);
171
172
        return $output;
173
    }
174
175
    /**
176
     * detect and add style to ftp links.
177
     *
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
     *
192
     * @author Juan Carlos Raña Trabado
193
     */
194
    public function detect_news_link($input)
195
    {
196
        $newslink = 'href="news';
197
        $newslinkStyle = 'class="wiki_news_link" href="news';
198
        $output = str_replace($newslink, $newslinkStyle, $input);
199
200
        return $output;
201
    }
202
203
    /**
204
     * detect and add style to irc links.
205
     *
206
     * @author Juan Carlos Raña Trabado
207
     */
208
    public function detect_irc_link($input)
209
    {
210
        $irclink = 'href="irc';
211
        $irclinkStyle = 'class="wiki_irc_link" href="irc';
212
        $output = str_replace($irclink, $irclinkStyle, $input);
213
214
        return $output;
215
    }
216
217
    /**
218
     * This function allows users to have [link to a title]-style links like in most regular wikis.
219
     * It is true that the adding of links is probably the most anoying part of Wiki for the people
220
     * who know something about the wiki syntax.
221
     *
222
     * @author Patrick Cool <[email protected]>, Ghent University
223
     * Improvements [[]] and [[ | ]]by Juan Carlos Raña
224
     * Improvements internal wiki style and mark group by Juan Carlos Raña
225
     */
226
    public function make_wiki_link_clickable($input)
227
    {
228
        $groupId = api_get_group_id();
229
        //now doubles brackets
230
        $input_array = preg_split(
231
            "/(\[\[|\]\])/",
232
            $input,
233
            -1,
234
            PREG_SPLIT_DELIM_CAPTURE
235
        );
236
237
        foreach ($input_array as $key => $value) {
238
            //now doubles brackets
239
            if (isset($input_array[$key - 1]) &&
240
                '[[' == $input_array[$key - 1] && ']]' == $input_array[$key + 1]
241
            ) {
242
                // now full wikilink
243
                if (false !== api_strpos($value, "|")) {
244
                    $full_link_array = explode("|", $value);
245
                    $link = trim(strip_tags($full_link_array[0]));
246
                    $title = trim($full_link_array[1]);
247
                } else {
248
                    $link = trim(strip_tags($value));
249
                    $title = trim($value);
250
                }
251
252
                //if wikilink is homepage
253
                if ('index' == $link) {
254
                    $title = get_lang('Home');
255
                }
256
                if ($link == get_lang('Home')) {
257
                    $link = 'index';
258
                }
259
260
                // 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
261
                if (self::checktitle(
262
                    strtolower(str_replace(' ', '_', $link))
263
                )) {
264
                    $link = api_html_entity_decode($link);
265
                    $input_array[$key] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?'.api_get_cidreq().'&action=addnew&title='.Security::remove_XSS($link).'&group_id='.$groupId.'" class="new_wiki_link">'.$title.'</a>';
266
                } else {
267
                    $input_array[$key] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?'.api_get_cidreq().'&action=showpage&title='.urlencode(strtolower(str_replace(' ', '_', $link))).'&group_id='.$groupId.'" class="wiki_link">'.$title.'</a>';
268
                }
269
                unset($input_array[$key - 1]);
270
                unset($input_array[$key + 1]);
271
            }
272
        }
273
        $output = implode('', $input_array);
274
275
        return $output;
276
    }
277
278
    /**
279
     * This function saves a change in a wiki page.
280
     *
281
     * @author Patrick Cool <[email protected]>, Ghent University
282
     *
283
     * @param array $values
284
     *
285
     * @return language string saying that the changes are stored
286
     */
287
    public function save_wiki($values)
288
    {
289
        $tbl_wiki = $this->tbl_wiki;
290
        $tbl_wiki_conf = $this->tbl_wiki_conf;
291
292
        $_course = $this->courseInfo;
293
        $time = api_get_utc_datetime();
294
        $session_id = api_get_session_id();
295
        $groupId = api_get_group_id();
296
        $userId = api_get_user_id();
297
        $groupInfo = GroupManager::get_group_properties($groupId);
298
        $course_id = api_get_course_int_id();
299
300
        $_clean = [
301
            'task' => '',
302
            'feedback1' => '',
303
            'feedback2' => '',
304
            'feedback3' => '',
305
            'fprogress1' => '',
306
            'fprogress2' => '',
307
            'fprogress3' => '',
308
            'max_text' => 0,
309
            'max_version' => 0,
310
            'delayedsubmit' => '',
311
            'assignment' => 0,
312
        ];
313
314
        $pageId = intval($values['page_id']);
315
316
        // NOTE: visibility, visibility_disc and ratinglock_disc changes
317
        // are not made here, but through the interce buttons
318
319
        // cleaning the variables
320
        if ('true' == api_get_setting('htmlpurifier_wiki')) {
321
            //$purifier = new HTMLPurifier();
322
            $values['content'] = Security::remove_XSS($values['content']);
323
        }
324
        $version = intval($values['version']) + 1;
325
        $linkTo = self::links_to($values['content']); //and check links content
326
327
        //cleaning config variables
328
        if (!empty($values['task'])) {
329
            $_clean['task'] = $values['task'];
330
        }
331
332
        if (!empty($values['feedback1']) ||
333
            !empty($values['feedback2']) ||
334
            !empty($values['feedback3'])
335
        ) {
336
            $_clean['feedback1'] = $values['feedback1'];
337
            $_clean['feedback2'] = $values['feedback2'];
338
            $_clean['feedback3'] = $values['feedback3'];
339
            $_clean['fprogress1'] = $values['fprogress1'];
340
            $_clean['fprogress2'] = $values['fprogress2'];
341
            $_clean['fprogress3'] = $values['fprogress3'];
342
        }
343
344
        if (isset($values['initstartdate']) && 1 == $values['initstartdate']) {
345
            $_clean['startdate_assig'] = $values['startdate_assig'];
346
        } else {
347
            $_clean['startdate_assig'] = null;
348
        }
349
350
        if (isset($values['initenddate']) && 1 == $values['initenddate']) {
351
            $_clean['enddate_assig'] = $values['enddate_assig'];
352
        } else {
353
            $_clean['enddate_assig'] = null;
354
        }
355
356
        if (isset($values['delayedsubmit'])) {
357
            $_clean['delayedsubmit'] = $values['delayedsubmit'];
358
        }
359
360
        if (!empty($values['max_text']) || !empty($values['max_version'])) {
361
            $_clean['max_text'] = $values['max_text'];
362
            $_clean['max_version'] = $values['max_version'];
363
        }
364
365
        $values['assignment'] = isset($values['assignment']) ? $values['assignment'] : 0;
366
        $values['page_id'] = isset($values['page_id']) ? $values['page_id'] : 0;
367
368
        $params = [
369
            'c_id' => $course_id,
370
            'addlock' => 1,
371
            'visibility' => 1,
372
            'visibility_disc' => 1,
373
            'addlock_disc' => 1,
374
            'ratinglock_disc' => 1,
375
            'page_id' => $pageId,
376
            'reflink' => trim($values['reflink']),
377
            'title' => trim($values['title']),
378
            'content' => $values['content'],
379
            'user_id' => $userId,
380
            'group_id' => $groupId,
381
            'dtime' => $time,
382
            'assignment' => $values['assignment'],
383
            'comment' => $values['comment'],
384
            'progress' => $values['progress'],
385
            'version' => $version,
386
            'linksto' => $linkTo,
387
            'user_ip' => $_SERVER['REMOTE_ADDR'],
388
            'session_id' => $session_id,
389
            'page_id' => $values['page_id'],
390
            'editlock' => 0,
391
            'is_editing' => 0,
392
            'time_edit' => $time,
393
            'tag' => '',
394
        ];
395
396
        $id = Database::insert($tbl_wiki, $params);
397
398
        if ($id > 0) {
399
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
400
            Database::query($sql);
401
402
            // insert into item_property
403
            api_item_property_update(
404
                $_course,
405
                TOOL_WIKI,
406
                $id,
407
                'WikiAdded',
408
                $userId,
409
                $groupInfo
410
            );
411
412
            if (0 == $values['page_id']) {
413
                $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
414
                        WHERE c_id = '.$course_id.' AND iid ="'.$id.'"';
415
                Database::query($sql);
416
            }
417
        }
418
419
        // Update wiki config
420
        if ('index' == $values['reflink'] && 1 == $version) {
421
            $params = [
422
                'c_id' => $course_id,
423
                'page_id' => $id,
424
                'task' => $_clean['task'],
425
                'feedback1' => $_clean['feedback1'],
426
                'feedback2' => $_clean['feedback2'],
427
                'feedback3' => $_clean['feedback3'],
428
                'fprogress1' => $_clean['fprogress1'],
429
                'fprogress2' => $_clean['fprogress2'],
430
                'fprogress3' => $_clean['fprogress3'],
431
                'max_text' => intval($_clean['max_text']),
432
                'max_version' => intval($_clean['max_version']),
433
                'startdate_assig' => $_clean['startdate_assig'],
434
                'enddate_assig' => $_clean['enddate_assig'],
435
                'delayedsubmit' => $_clean['delayedsubmit'],
436
            ];
437
            Database::insert($tbl_wiki_conf, $params);
438
        } else {
439
            $params = [
440
                'task' => $_clean['task'],
441
                'feedback1' => $_clean['feedback1'],
442
                'feedback2' => $_clean['feedback2'],
443
                'feedback3' => $_clean['feedback3'],
444
                'fprogress1' => $_clean['fprogress1'],
445
                'fprogress2' => $_clean['fprogress2'],
446
                'fprogress3' => $_clean['fprogress3'],
447
                'max_text' => intval($_clean['max_text']),
448
                'max_version' => intval($_clean['max_version']),
449
                'startdate_assig' => $_clean['startdate_assig'],
450
                'enddate_assig' => $_clean['enddate_assig'],
451
                'delayedsubmit' => $_clean['delayedsubmit'],
452
            ];
453
            Database::update(
454
                $tbl_wiki_conf,
455
                $params,
456
                ['page_id = ? AND c_id = ?' => [$pageId, $course_id]]
457
            );
458
        }
459
460
        api_item_property_update(
461
            $_course,
462
            'wiki',
463
            $id,
464
            'WikiAdded',
465
            $userId,
466
            $groupInfo
467
        );
468
        self::check_emailcue($_clean['reflink'], 'P', $time, $userId);
469
        $this->setWikiData($id);
470
471
        return get_lang('Saved');
472
    }
473
474
    /**
475
     * This function restore a wikipage.
476
     *
477
     * @author Juan Carlos Raña <[email protected]>
478
     *
479
     * @return string Message of success (to be printed on screen)
480
     */
481
    public function restore_wikipage(
482
        $r_page_id,
483
        $r_reflink,
484
        $r_title,
485
        $r_content,
486
        $r_group_id,
487
        $r_assignment,
488
        $r_progress,
489
        $c_version,
490
        $r_version,
491
        $r_linksto
492
    ) {
493
        $tbl_wiki = $this->tbl_wiki;
494
        $_course = $this->courseInfo;
495
        $r_user_id = api_get_user_id();
496
        $r_dtime = api_get_utc_datetime();
497
        $r_version = $r_version + 1;
498
        $r_comment = get_lang('Restored from version').': '.$c_version;
499
        $session_id = api_get_session_id();
500
        $course_id = api_get_course_int_id();
501
        $groupInfo = GroupManager::get_group_properties($r_group_id);
502
503
        $params = [
504
            'c_id' => $course_id,
505
            'page_id' => $r_page_id,
506
            'reflink' => $r_reflink,
507
            'title' => $r_title,
508
            'content' => $r_content,
509
            'user_id' => $r_user_id,
510
            'group_id' => $r_group_id,
511
            'dtime' => $r_dtime,
512
            'assignment' => $r_assignment,
513
            'comment' => $r_comment,
514
            'progress' => $r_progress,
515
            'version' => $r_version,
516
            'linksto' => $r_linksto,
517
            'user_ip' => $_SERVER['REMOTE_ADDR'],
518
            'session_id' => $session_id,
519
        ];
520
        $id = Database::insert($tbl_wiki, $params);
521
522
        if ($id) {
523
            $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
524
            Database::query($sql);
525
526
            api_item_property_update(
527
                $_course,
528
                'wiki',
529
                $id,
530
                'WikiAdded',
531
                api_get_user_id(),
532
                $groupInfo
533
            );
534
            self::check_emailcue($r_reflink, 'P', $r_dtime, $r_user_id);
535
        }
536
537
        return get_lang('The page has been restored. You can view it by clicking');
538
    }
539
540
    /**
541
     * This function delete a wiki.
542
     *
543
     * @author Juan Carlos Raña <[email protected]>
544
     *
545
     * @return string Message of success (to be printed)
546
     */
547
    public function delete_wiki()
548
    {
549
        $tbl_wiki = $this->tbl_wiki;
550
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
551
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
552
        $tbl_wiki_conf = $this->tbl_wiki_conf;
553
        $conditionSession = $this->condition_session;
554
        $groupFilter = $this->groupfilter;
555
        $course_id = $this->course_id;
556
557
        $sql = "SELECT page_id FROM $tbl_wiki
558
                WHERE c_id = $course_id AND $groupFilter $conditionSession
559
                ORDER BY id DESC";
560
561
        $result = Database::query($sql);
562
        $pageList = Database::store_result($result);
563
        if ($pageList) {
564
            foreach ($pageList as $pageData) {
565
                $pageId = $pageData['page_id'];
566
                $sql = "DELETE FROM $tbl_wiki_conf
567
                        WHERE c_id = $course_id AND page_id = $pageId";
568
                Database::query($sql);
569
570
                $sql = "DELETE FROM $tbl_wiki_discuss
571
                        WHERE c_id = $course_id AND publication_id = $pageId";
572
                Database::query($sql);
573
            }
574
        }
575
576
        $sql = "DELETE FROM $tbl_wiki_mailcue
577
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
578
        Database::query($sql);
579
580
        $sql = "DELETE FROM $tbl_wiki
581
                WHERE c_id = $course_id AND $groupFilter $conditionSession ";
582
        Database::query($sql);
583
584
        return get_lang('Your Group wiki has been deleted');
585
    }
586
587
    /**
588
     * This function saves a new wiki page.
589
     *
590
     * @author Patrick Cool <[email protected]>, Ghent University
591
     *
592
     * @todo consider merging this with the function save_wiki into one single function.
593
     *
594
     * @return string Message of success
595
     */
596
    public function save_new_wiki($values)
597
    {
598
        $tbl_wiki = $this->tbl_wiki;
599
        $tbl_wiki_conf = $this->tbl_wiki_conf;
600
        $assig_user_id = $this->assig_user_id;
601
        $_clean = [];
602
603
        // cleaning the variables
604
        $_clean['assignment'] = '';
605
        if (isset($values['assignment'])) {
606
            $_clean['assignment'] = $values['assignment'];
607
        }
608
609
        // session_id
610
        $session_id = api_get_session_id();
611
        // Unlike ordinary pages of pages of assignments.
612
        // Allow create a ordinary page although there is a assignment with the same name
613
        if (2 == $_clean['assignment'] || 1 == $_clean['assignment']) {
614
            $page = str_replace(
615
                ' ',
616
                '_',
617
                $values['title']."_uass".$assig_user_id
618
            );
619
        } else {
620
            $page = str_replace(' ', '_', $values['title']);
621
        }
622
        $_clean['reflink'] = $page;
623
        $_clean['title'] = trim($values['title']);
624
        $_clean['content'] = $values['content'];
625
626
        if ('true' === api_get_setting('htmlpurifier_wiki')) {
627
            $purifier = new HTMLPurifier();
628
            $_clean['content'] = $purifier->purify($_clean['content']);
629
        }
630
631
        //re-check after strip_tags if the title is empty
632
        if (empty($_clean['title']) || empty($_clean['reflink'])) {
633
            return false;
634
        }
635
636
        if (2 == $_clean['assignment']) {
637
            //config by default for individual assignment (students)
638
            //Identifies the user as a creator, not the teacher who created
639
            $_clean['user_id'] = intval($assig_user_id);
640
            $_clean['visibility'] = 0;
641
            $_clean['visibility_disc'] = 0;
642
            $_clean['ratinglock_disc'] = 0;
643
        } else {
644
            $_clean['user_id'] = api_get_user_id();
645
            $_clean['visibility'] = 1;
646
            $_clean['visibility_disc'] = 1;
647
            $_clean['ratinglock_disc'] = 1;
648
        }
649
650
        $_clean['comment'] = $values['comment'];
651
        $_clean['progress'] = $values['progress'];
652
        $_clean['version'] = 1;
653
654
        $groupId = api_get_group_id();
655
        $groupInfo = GroupManager::get_group_properties($groupId);
656
657
        //check wikilinks
658
        $_clean['linksto'] = self::links_to($_clean['content']);
659
660
        // cleaning config variables
661
        $_clean['task'] = isset($values['task']) ? $values['task'] : '';
662
        $_clean['feedback1'] = isset($values['feedback1']) ? $values['feedback1'] : '';
663
        $_clean['feedback2'] = isset($values['feedback2']) ? $values['feedback2'] : '';
664
        $_clean['feedback3'] = isset($values['feedback3']) ? $values['feedback3'] : '';
665
        $_clean['fprogress1'] = isset($values['fprogress1']) ? $values['fprogress1'] : '';
666
        $_clean['fprogress2'] = isset($values['fprogress2']) ? $values['fprogress2'] : '';
667
        $_clean['fprogress3'] = isset($values['fprogress3']) ? $values['fprogress3'] : '';
668
669
        if (isset($values['initstartdate']) && 1 == $values['initstartdate']) {
670
            $_clean['startdate_assig'] = $values['startdate_assig'];
671
        } else {
672
            $_clean['startdate_assig'] = null;
673
        }
674
675
        if (isset($values['initenddate']) && 1 == $values['initenddate']) {
676
            $_clean['enddate_assig'] = $values['enddate_assig'];
677
        } else {
678
            $_clean['enddate_assig'] = null;
679
        }
680
681
        $_clean['delayedsubmit'] = isset($values['delayedsubmit']) ? $values['delayedsubmit'] : '';
682
        $_clean['max_text'] = isset($values['max_text']) ? $values['max_text'] : '';
683
        $_clean['max_version'] = isset($values['max_version']) ? $values['max_version'] : '';
684
685
        $course_id = api_get_course_int_id();
686
687
        // Filter no _uass
688
        if ('INDEX' === api_strtoupper(trim($values['title']))) {
689
            Display::addFlash(
690
                Display::return_message(
691
                    get_lang('To start Group wiki go and edit Main page'),
692
                    'warning',
693
                    false
694
                )
695
            );
696
        } else {
697
            $var = $_clean['reflink'];
698
            $group_id = intval($_GET['group_id']);
699
            if (!self::checktitle($var)) {
700
                return get_lang('This page name already exists. To edit the page content, click here:').
701
                    '<a href="index.php?action=edit&title='.$var.'&group_id='.$group_id.'">'.
702
                    $values['title'].'</a>';
703
            } else {
704
                $dtime = api_get_utc_datetime();
705
706
                $params = [
707
                    'c_id' => $course_id,
708
                    'reflink' => $_clean['reflink'],
709
                    'title' => $_clean['title'],
710
                    'content' => $_clean['content'],
711
                    'user_id' => $_clean['user_id'],
712
                    'group_id' => $groupId,
713
                    'dtime' => $dtime,
714
                    'visibility' => $_clean['visibility'],
715
                    'visibility_disc' => $_clean['visibility_disc'],
716
                    'ratinglock_disc' => $_clean['ratinglock_disc'],
717
                    'assignment' => $_clean['assignment'],
718
                    'comment' => $_clean['comment'],
719
                    'progress' => $_clean['progress'],
720
                    'version' => $_clean['version'],
721
                    'linksto' => $_clean['linksto'],
722
                    'user_ip' => $_SERVER['REMOTE_ADDR'],
723
                    'session_id' => $session_id,
724
                    'addlock_disc' => 1,
725
                ];
726
                $id = Database::insert($tbl_wiki, $params);
727
                if ($id > 0) {
728
                    $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id";
729
                    Database::query($sql);
730
731
                    //insert into item_property
732
                    api_item_property_update(
733
                        api_get_course_info(),
734
                        TOOL_WIKI,
735
                        $id,
736
                        'WikiAdded',
737
                        api_get_user_id(),
738
                        $groupInfo
739
                    );
740
741
                    $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'"
742
                            WHERE c_id = '.$course_id.' AND id = "'.$id.'"';
743
                    Database::query($sql);
744
745
                    // insert wiki config
746
                    $params = [
747
                        'c_id' => $course_id,
748
                        'page_id' => $id,
749
                        'task' => $_clean['task'],
750
                        'feedback1' => $_clean['feedback1'],
751
                        'feedback2' => $_clean['feedback2'],
752
                        'feedback3' => $_clean['feedback3'],
753
                        'fprogress1' => $_clean['fprogress1'],
754
                        'fprogress2' => $_clean['fprogress2'],
755
                        'fprogress3' => $_clean['fprogress3'],
756
                        'max_text' => $_clean['max_text'],
757
                        'max_version' => $_clean['max_version'],
758
                        'startdate_assig' => $_clean['startdate_assig'],
759
                        'enddate_assig' => $_clean['enddate_assig'],
760
                        'delayedsubmit' => $_clean['delayedsubmit'],
761
                    ];
762
763
                    Database::insert($tbl_wiki_conf, $params);
764
765
                    $this->setWikiData($id);
766
                    self::check_emailcue(0, 'A');
767
768
                    return get_lang('The wiki page has been saved..');
769
                }
770
            }
771
        }
772
    }
773
774
    /**
775
     * @param FormValidator $form
776
     * @param array         $row
777
     */
778
    public function setForm($form, $row = [])
779
    {
780
        $toolBar = api_is_allowed_to_edit(null, true)
781
            ? [
782
                'ToolbarSet' => 'Wiki',
783
                'Width' => '100%',
784
                'Height' => '400',
785
            ]
786
            : [
787
                'ToolbarSet' => 'WikiStudent',
788
                'Width' => '100%',
789
                'Height' => '400',
790
                'UserStatus' => 'student',
791
            ];
792
793
        $form->addHtmlEditor(
794
            'content',
795
            get_lang('Content'),
796
            false,
797
            false,
798
            $toolBar
799
        );
800
        //$content
801
        $form->addElement('text', 'comment', get_lang('Comments'));
802
        $progress = ['', 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
803
804
        $form->addElement(
805
            'select',
806
            'progress',
807
            get_lang('Progress'),
808
            $progress
809
        );
810
811
        if ((api_is_allowed_to_edit(false, true) ||
812
            api_is_platform_admin()) &&
813
            isset($row['reflink']) && 'index' != $row['reflink']
814
        ) {
815
            $form->addElement(
816
                'advanced_settings',
817
                'advanced_params',
818
                get_lang('Advanced settings')
819
            );
820
            $form->addElement(
821
                'html',
822
                '<div id="advanced_params_options" style="display:none">'
823
            );
824
825
            $form->addHtmlEditor(
826
                'task',
827
                get_lang('Description of the assignment'),
828
                false,
829
                false,
830
                [
831
                    'ToolbarSet' => 'wiki_task',
832
                    'Width' => '100%',
833
                    'Height' => '200',
834
                ]
835
            );
836
837
            $form->addElement('label', null, get_lang('Add guidance messages associated with the progress on the page'));
838
            $form->addElement('textarea', 'feedback1', get_lang('First message'));
839
            $form->addElement(
840
                'select',
841
                'fprogress1',
842
                get_lang('Progress'),
843
                $progress
844
            );
845
846
            $form->addElement('textarea', 'feedback2', get_lang('Second message'));
847
            $form->addElement(
848
                'select',
849
                'fprogress2',
850
                get_lang('Progress'),
851
                $progress
852
            );
853
854
            $form->addElement('textarea', 'feedback3', get_lang('Third message'));
855
            $form->addElement(
856
                'select',
857
                'fprogress3',
858
                get_lang('Progress'),
859
                $progress
860
            );
861
862
            $form->addElement(
863
                'checkbox',
864
                'initstartdate',
865
                null,
866
                get_lang('Start Date'),
867
                ['id' => 'start_date_toggle']
868
            );
869
870
            $style = "display:block";
871
            $row['initstartdate'] = 1;
872
            if (empty($row['startdate_assig'])) {
873
                $style = "display:none";
874
                $row['initstartdate'] = null;
875
            }
876
877
            $form->addElement(
878
                'html',
879
                '<div id="start_date" style="'.$style.'">'
880
            );
881
            $form->addDatePicker('startdate_assig', '');
882
            $form->addElement('html', '</div>');
883
            $form->addElement(
884
                'checkbox',
885
                'initenddate',
886
                null,
887
                get_lang('End Date'),
888
                ['id' => 'end_date_toggle']
889
            );
890
891
            $style = "display:block";
892
            $row['initenddate'] = 1;
893
            if (empty($row['enddate_assig'])) {
894
                $style = "display:none";
895
                $row['initenddate'] = null;
896
            }
897
898
            $form->addHtml('<div id="end_date" style="'.$style.'">');
899
            $form->addDatePicker('enddate_assig', '');
900
            $form->addHtml('</div>');
901
            $form->addElement(
902
                'checkbox',
903
                'delayedsubmit',
904
                null,
905
                get_lang('Allow delayed sending')
906
            );
907
            $form->addElement('text', 'max_text', get_lang('Maximum number of words'));
908
            $form->addElement('text', 'max_version', get_lang('Maximum number of versions'));
909
            $form->addElement(
910
                'checkbox',
911
                'assignment',
912
                null,
913
                get_lang('This will create a special wiki page in which the teacher can describe the task and which will be automatically linked to the wiki pages where learners perform the task. Both the teacher\'s and the learner\'s pages are created automatically. in these tasks, learners can only edit and view theirs pages, but this can be changed easily if you need to.')
914
            );
915
            $form->addElement('html', '</div>');
916
        }
917
918
        $form->addElement('hidden', 'page_id');
919
        $form->addElement('hidden', 'reflink');
920
        $form->addElement('hidden', 'version');
921
        $form->addElement('hidden', 'wpost_id', api_get_unique_id());
922
    }
923
924
    /**
925
     * This function displays the form for adding a new wiki page.
926
     *
927
     * @author Patrick Cool <[email protected]>, Ghent University
928
     *
929
     * @return string html code
930
     */
931
    public function display_new_wiki_form()
932
    {
933
        $url = api_get_self().'?'.api_get_cidreq(
934
            ).'&action=addnew&group_id='.api_get_group_id();
935
        $form = new FormValidator('wiki_new', 'post', $url);
936
        $form->addElement('text', 'title', get_lang('Title'));
937
        $form->addRule('title', get_lang('Required field'), 'required');
938
        self::setForm($form);
939
        $title = isset($_GET['title']) ? Security::remove_XSS(
940
            $_GET['title']
941
        ) : '';
942
        $form->setDefaults(['title' => $title]);
943
        $form->addElement('button', 'SaveWikiNew', get_lang('Save'));
944
        $form->display();
945
946
        if ($form->validate()) {
947
            $values = $form->exportValues();
948
            if (isset($values['startdate_assig']) &&
949
                isset($values['enddate_assig']) &&
950
                strtotime($values['startdate_assig']) > strtotime(
951
                    $values['enddate_assig']
952
                )
953
            ) {
954
                Display::addFlash(
955
                    Display::return_message(
956
                        get_lang("End DateCannotBeBeforeTheStart Date"),
957
                        'error',
958
                        false
959
                    )
960
                );
961
            } elseif (!self::double_post($_POST['wpost_id'])) {
962
                //double post
963
            } else {
964
                if (isset($values['assignment']) && 1 == $values['assignment']) {
965
                    self::auto_add_page_users($values);
966
                }
967
968
                $return_message = self::save_new_wiki($values);
969
970
                if (false == $return_message) {
971
                    Display::addFlash(
972
                        Display::return_message(
973
                            get_lang('Your changes have been saved. You still have to give a name to the page'),
974
                            'error',
975
                            false
976
                        )
977
                    );
978
                } else {
979
                    Display::addFlash(
980
                        Display::return_message(
981
                            $return_message,
982
                            'confirmation',
983
                            false
984
                        )
985
                    );
986
                }
987
988
                $wikiData = self::getWikiData();
989
                $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq();
990
                header('Location: '.$redirectUrl);
991
                exit;
992
            }
993
        }
994
    }
995
996
    /**
997
     * This function displays a wiki entry.
998
     *
999
     * @author Patrick Cool <[email protected]>, Ghent University
1000
     * @author Juan Carlos Raña Trabado
1001
     *
1002
     * @param string $newtitle
1003
     *
1004
     * @return string html code
1005
     */
1006
    public function display_wiki_entry($newtitle)
1007
    {
1008
        $tbl_wiki = $this->tbl_wiki;
1009
        $tbl_wiki_conf = $this->tbl_wiki_conf;
1010
        $condition_session = $this->condition_session;
1011
        $groupfilter = $this->groupfilter;
1012
        $page = $this->page;
1013
1014
        $session_id = api_get_session_id();
1015
        $course_id = api_get_course_int_id();
1016
1017
        if ($newtitle) {
1018
            $pageMIX = $newtitle; //display the page after it is created
1019
        } else {
1020
            $pageMIX = $page; //display current page
1021
        }
1022
1023
        $filter = null;
1024
        if (isset($_GET['view']) && $_GET['view']) {
1025
            $_clean['view'] = Database::escape_string($_GET['view']);
1026
            $filter = ' AND w.id="'.$_clean['view'].'"';
1027
        }
1028
1029
        // First, check page visibility in the first page version
1030
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1031
                WHERE
1032
                    c_id = '.$course_id.' AND
1033
                    reflink="'.Database::escape_string($pageMIX).'" AND
1034
                   '.$groupfilter.$condition_session.'
1035
                ORDER BY iid ASC';
1036
        $result = Database::query($sql);
1037
        $row = Database::fetch_array($result, 'ASSOC');
1038
1039
        $KeyVisibility = null;
1040
        if ($KeyVisibility) {
1041
            $KeyVisibility = $row['visibility'];
1042
        }
1043
1044
        // second, show the last version
1045
        $sql = 'SELECT * FROM '.$tbl_wiki.' w
1046
                INNER JOIN '.$tbl_wiki_conf.' wc
1047
                ON (wc.page_id = w.page_id AND wc.c_id = w.c_id)
1048
                WHERE
1049
                    w.c_id 		  = '.$course_id.' AND
1050
                    w.reflink	  = "'.Database::escape_string($pageMIX).'" AND
1051
                    w.session_id  = '.$session_id.' AND
1052
                    w.'.$groupfilter.'  '.$filter.'
1053
                ORDER BY w.iid DESC';
1054
1055
        $result = Database::query($sql);
1056
        // we do not need a while loop since we are always displaying the last version
1057
        $row = Database::fetch_array($result, 'ASSOC');
1058
1059
        //log users access to wiki (page_id)
1060
        if (!empty($row['page_id'])) {
1061
            Event::addEvent(LOG_WIKI_ACCESS, LOG_WIKI_PAGE_ID, $row['page_id']);
1062
        }
1063
1064
        //update visits
1065
        if ($row && $row['id']) {
1066
            $sql = 'UPDATE '.$tbl_wiki.' SET hits=(hits+1)
1067
                    WHERE c_id = '.$course_id.' AND iid='.$row['id'].'';
1068
            Database::query($sql);
1069
        }
1070
1071
        $groupInfo = GroupManager::get_group_properties(api_get_group_id());
1072
1073
        // if both are empty and we are displaying the index page then we display the default text.
1074
        if ($row && '' == $row['content'] && '' == $row['title'] && 'index' === $page) {
1075
            if (api_is_allowed_to_edit(false, true) ||
1076
                api_is_platform_admin() ||
1077
                GroupManager::isUserInGroup(api_get_user_id(), api_get_group_entity()) ||
1078
                api_is_allowed_in_course()
1079
            ) {
1080
                //Table structure for better export to pdf
1081
                $default_table_for_content_Start = '<table align="center" border="0"><tr><td align="center">';
1082
                $default_table_for_content_End = '</td></tr></table>';
1083
                $content = $default_table_for_content_Start.
1084
                    sprintf(
1085
                        get_lang(' <br/> <br/> <p align="center"> <img src="%swiki/wcollaborative.png" alt="Working as a team" title="Working as a team" /></p> <p align="center">To begin editing this page and remove this text</p>'),
1086
                        api_get_path(WEB_IMG_PATH)
1087
                    ).
1088
                    $default_table_for_content_End;
1089
                $title = get_lang('Home');
1090
            } else {
1091
                return Display::addFlash(
1092
                    Display::return_message(
1093
                        get_lang('This Group wiki is frozen so far. A trainer must start it.'),
1094
                        'normal',
1095
                        false
1096
                    )
1097
                );
1098
            }
1099
        } else {
1100
            if ($row) {
1101
                $content = Security::remove_XSS($row['content']);
1102
                $title = Security::remove_XSS($row['title']);
1103
            }
1104
        }
1105
1106
        if (empty($row)) {
1107
            return '';
1108
        }
1109
1110
        //assignment mode: identify page type
1111
        $icon_assignment = null;
1112
        if (1 == $row['assignment']) {
1113
            $icon_assignment = Display::return_icon(
1114
                'wiki_assignment.png',
1115
                get_lang('This page is an assignment proposed by a trainer'),
1116
                '',
1117
                ICON_SIZE_SMALL
1118
            );
1119
        } elseif (2 == $row['assignment']) {
1120
            $icon_assignment = Display::return_icon(
1121
                'wiki_work.png',
1122
                get_lang('Learner paper'),
1123
                '',
1124
                ICON_SIZE_SMALL
1125
            );
1126
        }
1127
1128
        // task mode
1129
        $icon_task = null;
1130
        if (!empty($row['task'])) {
1131
            $icon_task = Display::return_icon(
1132
                'wiki_task.png',
1133
                get_lang('Standard Task'),
1134
                '',
1135
                ICON_SIZE_SMALL
1136
            );
1137
        }
1138
1139
        // Show page. Show page to all users if isn't hide page. Mode assignments: if student is the author, can view
1140
        if ("1" == $KeyVisibility ||
1141
            api_is_allowed_to_edit(false, true) ||
1142
            api_is_platform_admin() ||
1143
            (2 == $row['assignment'] && "0" == $KeyVisibility && (api_get_user_id() == $row['user_id'])) ||
1144
            api_is_allowed_in_course()
1145
        ) {
1146
            $actionsLeft = '';
1147
            // menu edit page
1148
            $editLink = '<a href="index.php?'.api_get_cidreq().'&action=edit&title='.api_htmlentities(urlencode($page)).'"'.self::is_active_navigation_tab('edit').'>'.
1149
                Display::return_icon(
1150
                    'edit.png',
1151
                    get_lang('Edit this page'),
1152
                    '',
1153
                    ICON_SIZE_MEDIUM
1154
                ).'</a>';
1155
1156
            if (api_is_allowed_to_edit(false, true)) {
1157
                $actionsLeft .= $editLink;
1158
            } else {
1159
                if ((api_is_allowed_in_course() ||
1160
                    GroupManager::isUserInGroup(
1161
                        api_get_user_id(),
1162
                        api_get_group_entity()
1163
                    ))
1164
                ) {
1165
                    $actionsLeft .= $editLink;
1166
                } else {
1167
                    $actionsLeft .= '';
1168
                }
1169
            }
1170
1171
            $actionsRight = '';
1172
1173
            $protect_page = null;
1174
            $lock_unlock_protect = null;
1175
            // page action: protecting (locking) the page
1176
            if (api_is_allowed_to_edit(false, true) ||
1177
                api_is_platform_admin()
1178
            ) {
1179
                if (1 == self::check_protect_page()) {
1180
                    $protect_page = Display::return_icon(
1181
                        'lock.png',
1182
                        get_lang('This page is protected. Trainers only can change it'),
1183
                        '',
1184
                        ICON_SIZE_MEDIUM
1185
                    );
1186
                    $lock_unlock_protect = 'unlock';
1187
                } else {
1188
                    $protect_page = Display::return_icon(
1189
                        'unlock.png',
1190
                        get_lang('This page is unprotected. All course users or group members can edit this page'),
1191
                        '',
1192
                        ICON_SIZE_MEDIUM
1193
                    );
1194
                    $lock_unlock_protect = 'lock';
1195
                }
1196
            }
1197
1198
            if ($row['id']) {
1199
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_protect.'&title='.api_htmlentities(urlencode($page)).'">'.
1200
                $protect_page.'</a>';
1201
            }
1202
1203
            $visibility_page = null;
1204
            $lock_unlock_visibility = null;
1205
            //page action: visibility
1206
            if (api_is_allowed_to_edit(false, true) ||
1207
                api_is_platform_admin()
1208
            ) {
1209
                if (1 == self::check_visibility_page()) {
1210
                    $visibility_page = Display::return_icon(
1211
                        'visible.png',
1212
                        get_lang('Now the page is visible by all users'),
1213
                        '',
1214
                        ICON_SIZE_MEDIUM
1215
                    );
1216
                    $lock_unlock_visibility = 'invisible';
1217
                } else {
1218
                    $visibility_page = Display::return_icon(
1219
                        'invisible.png',
1220
                        get_lang('Now the page only is visible by trainer'),
1221
                        '',
1222
                        ICON_SIZE_MEDIUM
1223
                    );
1224
                    $lock_unlock_visibility = 'visible';
1225
                }
1226
            }
1227
1228
            if ($row['id']) {
1229
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_visibility.'&title='.api_htmlentities(urlencode($page)).'">'.
1230
                    $visibility_page.'</a>';
1231
            }
1232
1233
            //page action: notification
1234
            if (api_is_allowed_to_session_edit()) {
1235
                if (1 == self::check_notify_page($page)) {
1236
                    $notify_page = Display::return_icon(
1237
                        'messagebox_info.png',
1238
                        get_lang('Notify me by e-mail when somebody replies'),
1239
                        '',
1240
                        ICON_SIZE_MEDIUM
1241
                    );
1242
                    $lock_unlock_notify_page = 'unlocknotify';
1243
                } else {
1244
                    $notify_page = Display::return_icon(
1245
                        'mail.png',
1246
                        get_lang('CancelNotify me by e-mail when somebody replies'),
1247
                        '',
1248
                        ICON_SIZE_MEDIUM
1249
                    );
1250
                    $lock_unlock_notify_page = 'locknotify';
1251
                }
1252
            }
1253
1254
            // Only available if row['id'] is set
1255
            if ($row['id']) {
1256
                if (api_is_allowed_to_session_edit(false, true) &&
1257
                    api_is_allowed_to_edit() ||
1258
                    GroupManager::isUserInGroup(
1259
                        api_get_user_id(),
1260
                        api_get_group_entity()
1261
                    )
1262
                ) {
1263
                    // menu discuss page
1264
                    $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=discuss&title='.api_htmlentities(
1265
                            urlencode($page)
1266
                        ).'" '.self::is_active_navigation_tab('discuss').'>'.
1267
                        Display::return_icon(
1268
                            'discuss.png',
1269
                            get_lang('Discuss this page'),
1270
                            '',
1271
                            ICON_SIZE_MEDIUM
1272
                        ).'</a>';
1273
                }
1274
1275
                //menu history
1276
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=history&title='.api_htmlentities(
1277
                        urlencode($page)
1278
                    ).'" '.self::is_active_navigation_tab('history').'>'.
1279
                    Display::return_icon(
1280
                        'history.png',
1281
                        get_lang('History'),
1282
                        '',
1283
                        ICON_SIZE_MEDIUM
1284
                    ).'</a>';
1285
                //menu linkspages
1286
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'action=links&title='.api_htmlentities(
1287
                        urlencode($page)
1288
                    ).'" '.self::is_active_navigation_tab('links').'>'.
1289
                    Display::return_icon(
1290
                        'what_link_here.png',
1291
                        get_lang('What links here'),
1292
                        '',
1293
                        ICON_SIZE_MEDIUM
1294
                    ).'</a>';
1295
1296
                //menu delete wikipage
1297
                if (api_is_allowed_to_edit(false, true) ||
1298
                    api_is_platform_admin()
1299
                ) {
1300
                    $actionsRight .= '<a href="index.php?action=delete&'.api_get_cidreq().'&title='.api_htmlentities(
1301
                            urlencode($page)
1302
                        ).'"'.self::is_active_navigation_tab('delete').'>'.
1303
                        Display::return_icon(
1304
                            'delete.png',
1305
                            get_lang('Delete this page'),
1306
                            '',
1307
                            ICON_SIZE_MEDIUM
1308
                        ).'</a>';
1309
                }
1310
1311
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=showpage&actionpage='.$lock_unlock_notify_page.'&title='.api_htmlentities(
1312
                        urlencode($page)
1313
                    ).'">'.
1314
                    $notify_page.'</a>';
1315
1316
                // Page action: copy last version to doc area
1317
                if (api_is_allowed_to_edit(false, true) ||
1318
                    api_is_platform_admin()
1319
                ) {
1320
                    $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export2doc&wiki_id='.$row['id'].'">'.
1321
                        Display::return_icon(
1322
                            'export_to_documents.png',
1323
                            get_lang('Export latest version of this page to Documents'),
1324
                            '',
1325
                            ICON_SIZE_MEDIUM
1326
                        ).'</a>';
1327
                }
1328
1329
                $actionsRight .= '<a href="index.php?'.api_get_cidreq().'&action=export_to_pdf&wiki_id='.$row['id'].'">'.
1330
                    Display::return_icon(
1331
                        'pdf.png',
1332
                        get_lang('Export to PDF'),
1333
                        '',
1334
                        ICON_SIZE_MEDIUM
1335
                    ).'</a>';
1336
1337
                $unoconv = api_get_configuration_value('unoconv.binaries');
1338
                if ($unoconv) {
1339
                    $actionsRight .= '<a href="'.api_get_path(WEB_CODE_PATH).'wiki/index.php?action=export_to_doc_file&id='.$row['id'].'&'.api_get_cidreq().'">'.
1340
                        Display::return_icon(
1341
                            'export_doc.png',
1342
                            get_lang('Export to .doc'),
1343
                            [],
1344
                            ICON_SIZE_MEDIUM
1345
                        ).'</a>';
1346
                }
1347
1348
                //export to print?>
1349
                <script>
1350
                    function goprint() {
1351
                        var a = window.open('', '', 'width=800,height=600');
1352
                        a.document.open("text/html");
1353
                        a.document.write($('#wikicontent .panel-heading').html());
1354
                        a.document.write($('#wikicontent .panel-body').html());
1355
                        a.document.close();
1356
                        a.print();
1357
                    }
1358
                </script>
1359
                <?php
1360
                $actionsRight .= Display::url(
1361
                    Display::return_icon(
1362
                        'printer.png',
1363
                        get_lang('Print'),
1364
                        '',
1365
                        ICON_SIZE_MEDIUM
1366
                    ),
1367
                    '#',
1368
                    ['onclick' => "javascript: goprint();"]
1369
                );
1370
            }
1371
1372
            echo Display::toolbarAction(
1373
                'toolbar-wikistudent',
1374
                [$actionsLeft, $actionsRight]
1375
            );
1376
1377
            if (self::wiki_exist($title)) {
1378
                $pageTitle = $icon_assignment.'&nbsp;'.
1379
                    $icon_task.'&nbsp;'.api_htmlentities($title);
1380
            } else {
1381
                $pageTitle = api_htmlentities($title);
1382
            }
1383
1384
            $pageWiki = self::make_wiki_link_clickable(
1385
                self::detect_external_link(
1386
                    self::detect_anchor_link(
1387
                        self::detect_mail_link(
1388
                            self::detect_ftp_link(
1389
                                self::detect_irc_link(
1390
                                    self::detect_news_link($content)
1391
                                )
1392
                            )
1393
                        )
1394
                    )
1395
                )
1396
            );
1397
1398
            $footerWiki =
1399
                get_lang('Progress').': '.($row['progress'] * 10).'%&nbsp;&nbsp;&nbsp;'.
1400
                get_lang('Rating').': '.$row['score'].'&nbsp;&nbsp;&nbsp;'.
1401
                get_lang('Words').': '.self::word_count($content);
1402
            // wikicontent require to print wiki document
1403
            echo '<div id="wikicontent">'.Display::panel($pageWiki, $pageTitle, $footerWiki).'</div>';
1404
        } //end filter visibility
1405
    }
1406
1407
    /**
1408
     * This function counted the words in a document. Thanks Adeel Khan.
1409
     *
1410
     * @param   string  Document's text
0 ignored issues
show
Documentation Bug introduced by
The doc comment Document's at position 0 could not be parsed: Unknown type name 'Document's' at position 0 in Document's.
Loading history...
1411
     *
1412
     * @return int Number of words
1413
     */
1414
    public function word_count($document)
1415
    {
1416
        $search = [
1417
            '@<script[^>]*?>.*?</script>@si',
1418
            '@<style[^>]*?>.*?</style>@siU',
1419
            '@<div id="player.[^>]*?>.*?</div>@',
1420
            '@<![\s\S]*?--[ \t\n\r]*>@',
1421
        ];
1422
1423
        $document = preg_replace($search, '', $document);
1424
1425
        // strip all html tags
1426
        $wc = strip_tags($document);
1427
        $wc = html_entity_decode(
1428
            $wc,
1429
            ENT_NOQUOTES,
1430
            'UTF-8'
1431
        ); // TODO:test also old html_entity_decode(utf8_encode($wc))
1432
1433
        // remove 'words' that don't consist of alphanumerical characters or punctuation. And fix accents and some letters
1434
        $pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@|á|é|í|ó|ú|à|è|ì|ò|ù|ä|ë|ï|ö|ü|Á|É|Í|Ó|Ú|À|È|Ò|Ù|Ä|Ë|Ï|Ö|Ü|â|ê|î|ô|û|Â|Ê|Î|Ô|Û|ñ|Ñ|ç|Ç)]+#";
1435
        $wc = trim(preg_replace($pattern, " ", $wc));
1436
1437
        // remove one-letter 'words' that consist only of punctuation
1438
        $wc = trim(
1439
            preg_replace(
1440
                "#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#",
1441
                " ",
1442
                $wc
1443
            )
1444
        );
1445
1446
        // remove superfluous whitespace
1447
        $wc = preg_replace("/\s\s+/", " ", $wc);
1448
1449
        // split string into an array of words
1450
        $wc = explode(" ", $wc);
1451
1452
        // remove empty elements
1453
        $wc = array_filter($wc);
1454
1455
        // return the number of words
1456
        return count($wc);
1457
    }
1458
1459
    /**
1460
     * This function checks if wiki title exist.
1461
     */
1462
    public function wiki_exist($title)
1463
    {
1464
        $tbl_wiki = $this->tbl_wiki;
1465
        $groupfilter = $this->groupfilter;
1466
        $condition_session = $this->condition_session;
1467
        $course_id = api_get_course_int_id();
1468
1469
        $sql = 'SELECT id FROM '.$tbl_wiki.'
1470
              WHERE
1471
                c_id = '.$course_id.' AND
1472
                title="'.Database::escape_string($title).'" AND
1473
                '.$groupfilter.$condition_session.'
1474
              ORDER BY id ASC';
1475
        $result = Database::query($sql);
1476
        $cant = Database::num_rows($result);
1477
        if ($cant > 0) {
1478
            return true;
1479
        } else {
1480
            return false;
1481
        }
1482
    }
1483
1484
    /**
1485
     * Checks if this navigation tab has to be set to active.
1486
     *
1487
     * @author Patrick Cool <[email protected]>, Ghent University
1488
     *
1489
     * @return string html code
1490
     */
1491
    public function is_active_navigation_tab($paramwk)
1492
    {
1493
        if (isset($_GET['action']) && $_GET['action'] == $paramwk) {
1494
            return ' class="active"';
1495
        }
1496
    }
1497
1498
    /**
1499
     * Lock add pages.
1500
     *
1501
     * @author Juan Carlos Raña <[email protected]>
1502
     * return current database status of protect page and change it if get action
1503
     */
1504
    public function check_addnewpagelock()
1505
    {
1506
        $tbl_wiki = $this->tbl_wiki;
1507
        $condition_session = $this->condition_session;
1508
        $groupfilter = $this->groupfilter;
1509
        $course_id = api_get_course_int_id();
1510
1511
        $sql = 'SELECT *
1512
                FROM '.$tbl_wiki.'
1513
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1514
                ORDER BY iid ASC';
1515
1516
        $result = Database::query($sql);
1517
        $row = Database::fetch_array($result);
1518
1519
        $status_addlock = null;
1520
        if ($row) {
1521
            $status_addlock = $row['addlock'];
1522
        }
1523
1524
        // Change status
1525
        if (api_is_allowed_to_edit(false, true) ||
1526
            api_is_platform_admin()
1527
        ) {
1528
            if (isset($_GET['actionpage'])) {
1529
                if ('lockaddnew' == $_GET['actionpage'] && 1 == $status_addlock) {
1530
                    $status_addlock = 0;
1531
                }
1532
                if ('unlockaddnew' == $_GET['actionpage'] && 0 == $status_addlock) {
1533
                    $status_addlock = 1;
1534
                }
1535
                $sql = 'UPDATE '.$tbl_wiki.' SET
1536
                            addlock="'.Database::escape_string($status_addlock).'"
1537
                        WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session;
1538
                Database::query($sql);
1539
            }
1540
1541
            $sql = 'SELECT *
1542
                    FROM '.$tbl_wiki.'
1543
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
1544
                    ORDER BY iid ASC';
1545
            $result = Database::query($sql);
1546
            $row = Database::fetch_array($result);
1547
            if ($row) {
1548
                return $row['addlock'];
1549
            }
1550
        }
1551
1552
        return null;
1553
    }
1554
1555
    /**
1556
     * Protect page.
1557
     *
1558
     * @author Juan Carlos Raña <[email protected]>
1559
     * return current database status of protect page and change it if get action
1560
     */
1561
    public function check_protect_page()
1562
    {
1563
        $tbl_wiki = $this->tbl_wiki;
1564
        $condition_session = $this->condition_session;
1565
        $groupfilter = $this->groupfilter;
1566
        $page = $this->page;
1567
1568
        $course_id = api_get_course_int_id();
1569
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1570
              WHERE
1571
                c_id = '.$course_id.' AND
1572
                reflink="'.Database::escape_string($page).'" AND
1573
                '.$groupfilter.$condition_session.'
1574
              ORDER BY id ASC';
1575
1576
        $result = Database::query($sql);
1577
        $row = Database::fetch_array($result);
1578
        $status_editlock = $row['editlock'];
1579
        $id = $row['page_id'];
1580
1581
        // Change status
1582
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1583
            if (isset($_GET['actionpage']) && 'lock' == $_GET['actionpage'] && 0 == $status_editlock) {
1584
                $status_editlock = 1;
1585
            }
1586
            if (isset($_GET['actionpage']) && 'unlock' == $_GET['actionpage'] && 1 == $status_editlock) {
1587
                $status_editlock = 0;
1588
            }
1589
1590
            $sql = 'UPDATE '.$tbl_wiki.' SET
1591
                    editlock="'.Database::escape_string($status_editlock).'"
1592
                    WHERE c_id = '.$course_id.' AND page_id="'.$id.'"';
1593
            Database::query($sql);
1594
1595
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1596
                    WHERE
1597
                        c_id = '.$course_id.' AND
1598
                        reflink="'.Database::escape_string($page).'" AND
1599
                    '.$groupfilter.$condition_session.'
1600
                  ORDER BY id ASC';
1601
            $result = Database::query($sql);
1602
            $row = Database::fetch_array($result);
1603
        }
1604
1605
        //show status
1606
        return $row['editlock'];
1607
    }
1608
1609
    /**
1610
     * Visibility page.
1611
     *
1612
     * @author Juan Carlos Raña <[email protected]>
1613
     * return current database status of visibility and change it if get action
1614
     */
1615
    public function check_visibility_page()
1616
    {
1617
        $tbl_wiki = $this->tbl_wiki;
1618
        $page = $this->page;
1619
        $condition_session = $this->condition_session;
1620
        $groupfilter = $this->groupfilter;
1621
        $course_id = api_get_course_int_id();
1622
1623
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1624
                WHERE
1625
                    c_id = '.$course_id.' AND
1626
                    reflink="'.Database::escape_string($page).'" AND
1627
                    '.$groupfilter.$condition_session.'
1628
                ORDER BY id ASC';
1629
        $result = Database::query($sql);
1630
        $row = Database::fetch_array($result);
1631
        $status_visibility = $row['visibility'];
1632
        //change status
1633
        if (api_is_allowed_to_edit(false, true) ||
1634
            api_is_platform_admin()
1635
        ) {
1636
            if (isset($_GET['actionpage']) &&
1637
                'visible' == $_GET['actionpage'] &&
1638
                0 == $status_visibility
1639
            ) {
1640
                $status_visibility = 1;
1641
            }
1642
            if (isset($_GET['actionpage']) &&
1643
                'invisible' == $_GET['actionpage'] &&
1644
                1 == $status_visibility
1645
            ) {
1646
                $status_visibility = 0;
1647
            }
1648
1649
            $sql = 'UPDATE '.$tbl_wiki.' SET
1650
                    visibility = "'.Database::escape_string($status_visibility).'"
1651
                    WHERE
1652
                        c_id = '.$course_id.' AND
1653
                        reflink="'.Database::escape_string($page).'" AND
1654
                        '.$groupfilter.$condition_session;
1655
            Database::query($sql);
1656
1657
            // Although the value now is assigned to all (not only the first),
1658
            // these three lines remain necessary.
1659
            // They do that by changing the page state is
1660
            // made when you press the button and not have to wait to change his page
1661
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1662
                    WHERE
1663
                        c_id = '.$course_id.' AND
1664
                        reflink="'.Database::escape_string($page).'" AND
1665
                        '.$groupfilter.$condition_session.'
1666
                    ORDER BY id ASC';
1667
            $result = Database::query($sql);
1668
            $row = Database::fetch_array($result);
1669
        }
1670
1671
        if (empty($row['id'])) {
1672
            $row['visibility'] = 1;
1673
        }
1674
1675
        //show status
1676
        return $row['visibility'];
1677
    }
1678
1679
    /**
1680
     * Visibility discussion.
1681
     *
1682
     * @author Juan Carlos Raña <[email protected]>
1683
     *
1684
     * @return int current database status of discuss visibility
1685
     *             and change it if get action page
1686
     */
1687
    public function check_visibility_discuss()
1688
    {
1689
        $tbl_wiki = $this->tbl_wiki;
1690
        $page = $this->page;
1691
        $condition_session = $this->condition_session;
1692
        $groupfilter = $this->groupfilter;
1693
        $course_id = api_get_course_int_id();
1694
1695
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1696
                WHERE
1697
                    c_id = '.$course_id.' AND
1698
                    reflink="'.Database::escape_string($page).'" AND
1699
                    '.$groupfilter.$condition_session.'
1700
                ORDER BY id ASC';
1701
        $result = Database::query($sql);
1702
        $row = Database::fetch_array($result);
1703
1704
        $status_visibility_disc = $row['visibility_disc'];
1705
1706
        //change status
1707
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
1708
            if (isset($_GET['actionpage']) &&
1709
                'showdisc' == $_GET['actionpage'] &&
1710
                0 == $status_visibility_disc
1711
            ) {
1712
                $status_visibility_disc = 1;
1713
            }
1714
            if (isset($_GET['actionpage']) &&
1715
                'hidedisc' == $_GET['actionpage'] &&
1716
                1 == $status_visibility_disc
1717
            ) {
1718
                $status_visibility_disc = 0;
1719
            }
1720
1721
            $sql = 'UPDATE '.$tbl_wiki.' SET
1722
                    visibility_disc="'.Database::escape_string($status_visibility_disc).'"
1723
                    WHERE
1724
                        c_id = '.$course_id.' AND
1725
                        reflink="'.Database::escape_string($page).'" AND
1726
                        '.$groupfilter.$condition_session;
1727
            Database::query($sql);
1728
1729
            // Although the value now is assigned to all (not only the first),
1730
            // these three lines remain necessary.
1731
            // They do that by changing the page state is made when you press
1732
            // the button and not have to wait to change his page
1733
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1734
                    WHERE
1735
                        c_id = '.$course_id.' AND
1736
                        reflink="'.Database::escape_string($page).'" AND
1737
                        '.$groupfilter.$condition_session.'
1738
                    ORDER BY id ASC';
1739
            $result = Database::query($sql);
1740
            $row = Database::fetch_array($result);
1741
        }
1742
1743
        return $row['visibility_disc'];
1744
    }
1745
1746
    /**
1747
     * Lock add discussion.
1748
     *
1749
     * @author Juan Carlos Raña <[email protected]>
1750
     *
1751
     * @return int current database status of lock dicuss and change if get action
1752
     */
1753
    public function check_addlock_discuss()
1754
    {
1755
        $tbl_wiki = $this->tbl_wiki;
1756
        $page = $this->page;
1757
        $condition_session = $this->condition_session;
1758
        $groupfilter = $this->groupfilter;
1759
        $course_id = api_get_course_int_id();
1760
1761
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1762
                WHERE
1763
                    c_id = '.$course_id.' AND
1764
                    reflink="'.Database::escape_string($page).'" AND
1765
                    '.$groupfilter.$condition_session.'
1766
                ORDER BY id ASC';
1767
        $result = Database::query($sql);
1768
        $row = Database::fetch_array($result);
1769
1770
        $status_addlock_disc = $row['addlock_disc'];
1771
1772
        //change status
1773
        if (api_is_allowed_to_edit() || api_is_platform_admin()) {
1774
            if (isset($_GET['actionpage']) &&
1775
                'lockdisc' == $_GET['actionpage'] &&
1776
                0 == $status_addlock_disc
1777
            ) {
1778
                $status_addlock_disc = 1;
1779
            }
1780
            if (isset($_GET['actionpage']) &&
1781
                'unlockdisc' == $_GET['actionpage'] &&
1782
                1 == $status_addlock_disc
1783
            ) {
1784
                $status_addlock_disc = 0;
1785
            }
1786
1787
            $sql = 'UPDATE '.$tbl_wiki.' SET
1788
                    addlock_disc="'.Database::escape_string($status_addlock_disc).'"
1789
                    WHERE
1790
                        c_id = '.$course_id.' AND
1791
                        reflink = "'.Database::escape_string($page).'" AND
1792
                         '.$groupfilter.$condition_session;
1793
            Database::query($sql);
1794
1795
            // Although the value now is assigned to all (not only the first),
1796
            // these three lines remain necessary.
1797
            // They do that by changing the page state is made when you press
1798
            // the button and not have to wait to change his page
1799
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1800
                    WHERE
1801
                        c_id = '.$course_id.' AND
1802
                        reflink="'.Database::escape_string($page).'" AND
1803
                        '.$groupfilter.$condition_session.'
1804
                    ORDER BY id ASC';
1805
            $result = Database::query($sql);
1806
            $row = Database::fetch_array($result);
1807
        }
1808
1809
        return $row['addlock_disc'];
1810
    }
1811
1812
    /**
1813
     * Lock rating discussion.
1814
     *
1815
     * @author Juan Carlos Raña <[email protected]>
1816
     *
1817
     * @return int current database status of rating discuss and change it if get action
1818
     */
1819
    public function check_ratinglock_discuss()
1820
    {
1821
        $tbl_wiki = $this->tbl_wiki;
1822
        $page = $this->page;
1823
        $condition_session = $this->condition_session;
1824
        $groupfilter = $this->groupfilter;
1825
        $course_id = api_get_course_int_id();
1826
1827
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1828
                WHERE
1829
                    c_id = '.$course_id.' AND
1830
                    reflink="'.Database::escape_string($page).'" AND
1831
                    '.$groupfilter.$condition_session.'
1832
                ORDER BY id ASC';
1833
        $result = Database::query($sql);
1834
        $row = Database::fetch_array($result);
1835
        $status_ratinglock_disc = $row['ratinglock_disc'];
1836
1837
        //change status
1838
        if (api_is_allowed_to_edit(false, true) ||
1839
            api_is_platform_admin()
1840
        ) {
1841
            if (isset($_GET['actionpage']) &&
1842
                'lockrating' == $_GET['actionpage'] &&
1843
                0 == $status_ratinglock_disc
1844
            ) {
1845
                $status_ratinglock_disc = 1;
1846
            }
1847
            if (isset($_GET['actionpage']) &&
1848
                'unlockrating' == $_GET['actionpage'] &&
1849
                1 == $status_ratinglock_disc
1850
            ) {
1851
                $status_ratinglock_disc = 0;
1852
            }
1853
1854
            $sql = 'UPDATE '.$tbl_wiki.'
1855
                    SET ratinglock_disc="'.Database::escape_string($status_ratinglock_disc).'"
1856
                    WHERE
1857
                        c_id = '.$course_id.' AND
1858
                        reflink="'.Database::escape_string($page).'" AND
1859
                        '.$groupfilter.$condition_session;
1860
            // Visibility. Value to all,not only for the first
1861
            Database::query($sql);
1862
1863
            // Although the value now is assigned to all (not only the first),
1864
            // these three lines remain necessary. They do that by changing the
1865
            // page state is made when you press the button and not have to wait
1866
            // to change his page
1867
            $sql = 'SELECT * FROM '.$tbl_wiki.'
1868
                    WHERE
1869
                        c_id = '.$course_id.' AND
1870
                        reflink="'.Database::escape_string($page).'" AND
1871
                    '.$groupfilter.$condition_session.'
1872
                  ORDER BY id ASC';
1873
            $result = Database::query($sql);
1874
            $row = Database::fetch_array($result);
1875
        }
1876
1877
        return $row['ratinglock_disc'];
1878
    }
1879
1880
    /**
1881
     * Notify page changes.
1882
     *
1883
     * @author Juan Carlos Raña <[email protected]>
1884
     *
1885
     * @return int the current notification status
1886
     */
1887
    public function check_notify_page($reflink)
1888
    {
1889
        $tbl_wiki = $this->tbl_wiki;
1890
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1891
        $condition_session = $this->condition_session;
1892
        $groupfilter = $this->groupfilter;
1893
        $groupId = api_get_group_id();
1894
        $session_id = api_get_session_id();
1895
        $course_id = api_get_course_int_id();
1896
        $userId = api_get_user_id();
1897
1898
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1899
                WHERE
1900
                    c_id = '.$course_id.' AND
1901
                    reflink="'.$reflink.'" AND
1902
                    '.$groupfilter.$condition_session.'
1903
                ORDER BY id ASC';
1904
        $result = Database::query($sql);
1905
        $row = Database::fetch_array($result);
1906
        $id = $row['id'];
1907
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1908
                WHERE
1909
                    c_id = '.$course_id.' AND
1910
                    id="'.$id.'" AND
1911
                    user_id="'.api_get_user_id().'" AND
1912
                    type="P"';
1913
        $result = Database::query($sql);
1914
        $row = Database::fetch_array($result);
1915
        $idm = $row['id'];
1916
        if (empty($idm)) {
1917
            $status_notify = 0;
1918
        } else {
1919
            $status_notify = 1;
1920
        }
1921
1922
        // Change status
1923
        if (isset($_GET['actionpage']) &&
1924
            'locknotify' == $_GET['actionpage'] &&
1925
            0 == $status_notify
1926
        ) {
1927
            $sql = "SELECT id FROM $tbl_wiki_mailcue
1928
                    WHERE c_id = $course_id AND id = $id AND user_id = $userId";
1929
            $result = Database::query($sql);
1930
            $exist = false;
1931
            if (Database::num_rows($result)) {
1932
                $exist = true;
1933
            }
1934
            if (false == $exist) {
1935
                $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
1936
                ($course_id, '".$id."','".api_get_user_id()."','P','".$groupId."','".$session_id."')";
1937
                Database::query($sql);
1938
            }
1939
            $status_notify = 1;
1940
        }
1941
1942
        if (isset($_GET['actionpage']) &&
1943
            'unlocknotify' == $_GET['actionpage'] &&
1944
            1 == $status_notify
1945
        ) {
1946
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
1947
                    WHERE
1948
                        id="'.$id.'" AND
1949
                        user_id="'.api_get_user_id().'" AND
1950
                        type="P" AND
1951
                        c_id = '.$course_id;
1952
            Database::query($sql);
1953
            $status_notify = 0;
1954
        }
1955
1956
        return $status_notify;
1957
    }
1958
1959
    /**
1960
     * Notify discussion changes.
1961
     *
1962
     * @author Juan Carlos Raña <[email protected]>
1963
     *
1964
     * @param string $reflink
1965
     *
1966
     * @return int current database status of rating discuss and change it if get action
1967
     */
1968
    public function check_notify_discuss($reflink)
1969
    {
1970
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
1971
        $tbl_wiki = $this->tbl_wiki;
1972
        $condition_session = $this->condition_session;
1973
        $groupfilter = $this->groupfilter;
1974
1975
        $course_id = api_get_course_int_id();
1976
        $groupId = api_get_group_id();
1977
        $session_id = api_get_session_id();
1978
1979
        $sql = 'SELECT * FROM '.$tbl_wiki.'
1980
                WHERE
1981
                    c_id = '.$course_id.' AND
1982
                    reflink="'.$reflink.'" AND
1983
                    '.$groupfilter.$condition_session.'
1984
                ORDER BY id ASC';
1985
        $result = Database::query($sql);
1986
        $row = Database::fetch_array($result);
1987
        $id = $row['id'];
1988
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
1989
                WHERE
1990
                    c_id = '.$course_id.' AND id="'.$id.'" AND user_id="'.api_get_user_id().'" AND type="D"';
1991
        $result = Database::query($sql);
1992
        $row = Database::fetch_array($result);
1993
        $idm = $row['id'];
1994
1995
        if (empty($idm)) {
1996
            $status_notify_disc = 0;
1997
        } else {
1998
            $status_notify_disc = 1;
1999
        }
2000
2001
        // change status
2002
        if (isset($_GET['actionpage']) &&
2003
            'locknotifydisc' == $_GET['actionpage'] &&
2004
            0 == $status_notify_disc
2005
        ) {
2006
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, id, user_id, type, group_id, session_id) VALUES
2007
            ($course_id, '".$id."','".api_get_user_id()."','D','".$groupId."','".$session_id."')";
2008
            Database::query($sql);
2009
            $status_notify_disc = 1;
2010
        }
2011
        if (isset($_GET['actionpage']) &&
2012
            'unlocknotifydisc' == $_GET['actionpage'] &&
2013
            1 == $status_notify_disc
2014
        ) {
2015
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
2016
                    WHERE
2017
                        c_id = '.$course_id.' AND
2018
                        id="'.$id.'" AND
2019
                        user_id="'.api_get_user_id().'" AND
2020
                        type="D" AND
2021
                        c_id = '.$course_id;
2022
            Database::query($sql);
2023
            $status_notify_disc = 0;
2024
        }
2025
2026
        return $status_notify_disc;
2027
    }
2028
2029
    /**
2030
     * Notify all changes.
2031
     *
2032
     * @author Juan Carlos Raña <[email protected]>
2033
     */
2034
    public function check_notify_all()
2035
    {
2036
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
2037
        $course_id = api_get_course_int_id();
2038
        $groupId = api_get_group_id();
2039
        $session_id = api_get_session_id();
2040
2041
        $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2042
                WHERE
2043
                    c_id = '.$course_id.' AND
2044
                    user_id="'.api_get_user_id().'" AND
2045
                    type="F" AND
2046
                    group_id="'.$groupId.'" AND
2047
                    session_id="'.$session_id.'"';
2048
        $result = Database::query($sql);
2049
        $row = Database::fetch_array($result);
2050
2051
        $idm = $row['user_id'];
2052
2053
        if (empty($idm)) {
2054
            $status_notify_all = 0;
2055
        } else {
2056
            $status_notify_all = 1;
2057
        }
2058
2059
        //change status
2060
        if (isset($_GET['actionpage']) &&
2061
            'locknotifyall' == $_GET['actionpage'] &&
2062
            0 == $status_notify_all
2063
        ) {
2064
            $sql = "INSERT INTO ".$tbl_wiki_mailcue." (c_id, user_id, type, group_id, session_id) VALUES
2065
            ($course_id, '".api_get_user_id()."','F','".$groupId."','".$session_id."')";
2066
            Database::query($sql);
2067
            $status_notify_all = 1;
2068
        }
2069
2070
        if (isset($_GET['actionpage']) &&
2071
            isset($_GET['actionpage']) &&
2072
            'unlocknotifyall' == $_GET['actionpage'] &&
2073
            1 == $status_notify_all
2074
        ) {
2075
            $sql = 'DELETE FROM '.$tbl_wiki_mailcue.'
2076
                   WHERE
2077
                    c_id = '.$course_id.' AND
2078
                    user_id="'.api_get_user_id().'" AND
2079
                    type="F" AND
2080
                    group_id="'.$groupId.'" AND
2081
                    session_id="'.$session_id.'" AND
2082
                    c_id = '.$course_id;
2083
            Database::query($sql);
2084
            $status_notify_all = 0;
2085
        }
2086
2087
        //show status
2088
        return $status_notify_all;
2089
    }
2090
2091
    /**
2092
     * Sends pending e-mails.
2093
     */
2094
    public function check_emailcue(
2095
        $id_or_ref,
2096
        $type,
2097
        $lastime = '',
2098
        $lastuser = ''
2099
    ) {
2100
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
2101
        $tbl_wiki = $this->tbl_wiki;
2102
        $condition_session = $this->condition_session;
2103
        $groupfilter = $this->groupfilter;
2104
        $_course = $this->courseInfo;
2105
        $groupId = api_get_group_id();
2106
        $session_id = api_get_session_id();
2107
        $course_id = api_get_course_int_id();
2108
        $group_properties = GroupManager::get_group_properties($groupId);
2109
        $group_name = $group_properties['name'];
2110
        $allow_send_mail = false; //define the variable to below
2111
        $email_assignment = null;
2112
        if ('P' == $type) {
2113
            //if modifying a wiki page
2114
            //first, current author and time
2115
            //Who is the author?
2116
            $userinfo = api_get_user_info($lastuser);
2117
            $email_user_author = get_lang('edited by').': '.$userinfo['complete_name'];
2118
2119
            //When ?
2120
            $year = substr($lastime, 0, 4);
2121
            $month = substr($lastime, 5, 2);
2122
            $day = substr($lastime, 8, 2);
2123
            $hours = substr($lastime, 11, 2);
2124
            $minutes = substr($lastime, 14, 2);
2125
            $seconds = substr($lastime, 17, 2);
2126
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2127
2128
            //second, extract data from first reg
2129
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2130
                    WHERE
2131
                        c_id = '.$course_id.' AND
2132
                        reflink="'.$id_or_ref.'" AND
2133
                        '.$groupfilter.$condition_session.'
2134
                    ORDER BY id ASC';
2135
            $result = Database::query($sql);
2136
            $row = Database::fetch_array($result);
2137
            $id = $row['id'];
2138
            $email_page_name = $row['title'];
2139
            if (1 == $row['visibility']) {
2140
                $allow_send_mail = true; //if visibility off - notify off
2141
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2142
                        WHERE
2143
                            c_id = '.$course_id.' AND
2144
                            id="'.$id.'" AND
2145
                            type="'.$type.'" OR
2146
                            type="F" AND
2147
                            group_id="'.$groupId.'" AND
2148
                            session_id="'.$session_id.'"';
2149
                //type: P=page, D=discuss, F=full.
2150
                $result = Database::query($sql);
2151
                $emailtext = get_lang('It has modified the page').
2152
                    '<strong>'.$email_page_name.'</strong> '.
2153
                    get_lang('Group wiki');
2154
            }
2155
        } elseif ('D' == $type) {
2156
            //if added a post to discuss
2157
            //first, current author and time
2158
            //Who is the author of last message?
2159
            $userinfo = api_get_user_info($lastuser);
2160
            $email_user_author = get_lang('added by').': '.$userinfo['complete_name'];
2161
2162
            //When ?
2163
            $year = substr($lastime, 0, 4);
2164
            $month = substr($lastime, 5, 2);
2165
            $day = substr($lastime, 8, 2);
2166
            $hours = substr($lastime, 11, 2);
2167
            $minutes = substr($lastime, 14, 2);
2168
            $seconds = substr($lastime, 17, 2);
2169
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2170
            //second, extract data from first reg
2171
            $id = $id_or_ref; //$id_or_ref is id from tblwiki
2172
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2173
                    WHERE c_id = '.$course_id.' AND id="'.$id.'"
2174
                    ORDER BY id ASC';
2175
2176
            $result = Database::query($sql);
2177
            $row = Database::fetch_array($result);
2178
2179
            $email_page_name = $row['title'];
2180
            if (1 == $row['visibility_disc']) {
2181
                $allow_send_mail = true; //if visibility off - notify off
2182
                $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2183
                        WHERE
2184
                            c_id = '.$course_id.' AND
2185
                            id="'.$id.'" AND
2186
                            type="'.$type.'" OR
2187
                            type="F" AND
2188
                            group_id="'.$groupId.'" AND
2189
                            session_id="'.$session_id.'"';
2190
                //type: P=page, D=discuss, F=full
2191
                $result = Database::query($sql);
2192
                $emailtext = get_lang(
2193
                        'EmailGroup wikiPageDiscAdded'
2194
                    ).' <strong>'.$email_page_name.'</strong> '.get_lang(
2195
                        'Group wiki'
2196
                    );
2197
            }
2198
        } elseif ('A' == $type) {
2199
            //for added pages
2200
            $id = 0; //for tbl_wiki_mailcue
2201
            $sql = 'SELECT * FROM '.$tbl_wiki.'
2202
                    WHERE c_id = '.$course_id.'
2203
                    ORDER BY id DESC'; //the added is always the last
2204
2205
            $result = Database::query($sql);
2206
            $row = Database::fetch_array($result);
2207
            $email_page_name = $row['title'];
2208
2209
            //Who is the author?
2210
            $userinfo = api_get_user_info($row['user_id']);
2211
            $email_user_author = get_lang('added by').': '.$userinfo['complete_name'];
2212
2213
            //When ?
2214
            $year = substr($row['dtime'], 0, 4);
2215
            $month = substr($row['dtime'], 5, 2);
2216
            $day = substr($row['dtime'], 8, 2);
2217
            $hours = substr($row['dtime'], 11, 2);
2218
            $minutes = substr($row['dtime'], 14, 2);
2219
            $seconds = substr($row['dtime'], 17, 2);
2220
            $email_date_changes = $day.' '.$month.' '.$year.' '.$hours.":".$minutes.":".$seconds;
2221
2222
            if (0 == $row['assignment']) {
2223
                $allow_send_mail = true;
2224
            } elseif (1 == $row['assignment']) {
2225
                $email_assignment = get_lang('This page is an assignment proposed by a trainer').' ('.get_lang('individual assignment mode').')';
2226
                $allow_send_mail = true;
2227
            } elseif (2 == $row['assignment']) {
2228
                $allow_send_mail = false; //Mode tasks: avoids notifications to all users about all users
2229
            }
2230
2231
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2232
                    WHERE
2233
                        c_id = '.$course_id.' AND
2234
                        id="'.$id.'" AND
2235
                        type="F" AND
2236
                        group_id="'.$groupId.'" AND
2237
                        session_id="'.$session_id.'"';
2238
2239
            //type: P=page, D=discuss, F=full
2240
            $result = Database::query($sql);
2241
            $emailtext = get_lang('EmailGroup wikiPageAdded').' <strong>'.
2242
                $email_page_name.'</strong> '.get_lang('in').' '.get_lang('Group wiki');
2243
        } elseif ('E' == $type) {
2244
            $id = 0;
2245
            $allow_send_mail = true;
2246
            // Who is the author?
2247
            $userinfo = api_get_user_info(api_get_user_id()); //current user
2248
            $email_user_author = get_lang('deleted by').': '.$userinfo['complete_name'];
2249
            //When ?
2250
            $today = date('r'); //current time
2251
            $email_date_changes = $today;
2252
            $sql = 'SELECT * FROM '.$tbl_wiki_mailcue.'
2253
                    WHERE
2254
                        c_id = '.$course_id.' AND
2255
                        id="'.$id.'" AND type="F" AND
2256
                        group_id="'.$groupId.'" AND
2257
                        session_id="'.$session_id.'"'; //type: P=page, D=discuss, F=wiki
2258
            $result = Database::query($sql);
2259
            $emailtext = get_lang('EmailGroup wikipageDedeleted');
2260
        }
2261
        ///make and send email
2262
        if ($allow_send_mail) {
2263
            while ($row = Database::fetch_array($result)) {
2264
                $userinfo = api_get_user_info(
2265
                    $row['user_id']
2266
                ); //$row['user_id'] obtained from tbl_wiki_mailcue
2267
                $name_to = $userinfo['complete_name'];
2268
                $email_to = $userinfo['email'];
2269
                $sender_name = api_get_setting('emailAdministrator');
2270
                $sender_email = api_get_setting('emailAdministrator');
2271
                $email_subject = get_lang(
2272
                        'EmailGroup wikiChanges'
2273
                    ).' - '.$_course['official_code'];
2274
                $email_body = get_lang('Dear user').' '.api_get_person_name(
2275
                        $userinfo['firstname'],
2276
                        $userinfo['lastname']
2277
                    ).',<br /><br />';
2278
                if (0 == $session_id) {
2279
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' - '.$group_name.'</strong><br /><br /><br />';
2280
                } else {
2281
                    $email_body .= $emailtext.' <strong>'.$_course['name'].' ('.api_get_session_name(
2282
                            api_get_session_id()
2283
                        ).') - '.$group_name.'</strong><br /><br /><br />';
2284
                }
2285
                $email_body .= $email_user_author.' ('.$email_date_changes.')<br /><br /><br />';
2286
                $email_body .= $email_assignment.'<br /><br /><br />';
2287
                $email_body .= '<font size="-2">'.get_lang(
2288
                        'EmailGroup wikiChangesExt_1'
2289
                    ).': <strong>'.get_lang('Notify me of changes').'</strong><br />';
2290
                $email_body .= get_lang(
2291
                        'EmailGroup wikiChangesExt_2'
2292
                    ).': <strong>'.get_lang(
2293
                        'NotNotify me of changes'
2294
                    ).'</strong></font><br />';
2295
                @api_mail_html(
2296
                    $name_to,
2297
                    $email_to,
2298
                    $email_subject,
2299
                    $email_body,
2300
                    $sender_name,
2301
                    $sender_email
2302
                );
2303
            }
2304
        }
2305
    }
2306
2307
    /**
2308
     * Function export last wiki page version to document area.
2309
     *
2310
     * @param int $doc_id wiki page id
2311
     *
2312
     * @return mixed
2313
     *
2314
     * @author Juan Carlos Raña <[email protected]>
2315
     */
2316
    public function export2doc($doc_id)
2317
    {
2318
        $_course = $this->courseInfo;
2319
        $groupId = api_get_group_id();
2320
        $groupInfo = GroupManager::get_group_properties($groupId);
2321
        $data = self::getWikiDataFromDb($doc_id);
2322
2323
        if (empty($data)) {
2324
            return false;
2325
        }
2326
2327
        $wikiTitle = $data['title'];
2328
        $wikiContents = $data['content'];
2329
2330
        $template =
2331
            '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2332
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{LANGUAGE}" lang="{LANGUAGE}">
2333
            <head>
2334
            <title>{TITLE}</title>
2335
            <meta http-equiv="Content-Type" content="text/html; charset={ENCODING}" />
2336
            <style type="text/css" media="screen, projection">
2337
            /*<![CDATA[*/
2338
            {CSS}
2339
            /*]]>*/
2340
            </style>
2341
            {ASCIIMATHML_SCRIPT}</head>
2342
            <body dir="{TEXT_DIRECTION}">
2343
            {CONTENT}
2344
            </body>
2345
            </html>';
2346
2347
        $css_file = api_get_path(SYS_CSS_PATH).'themes/'.api_get_setting('stylesheets').'/default.css';
2348
        if (file_exists($css_file)) {
2349
            $css = @file_get_contents($css_file);
2350
        } else {
2351
            $css = '';
2352
        }
2353
        // Fixing some bugs in css files.
2354
        $root_rel = api_get_path(REL_PATH);
2355
        $css_path = 'main/css/';
2356
        $theme = api_get_setting('stylesheets').'/';
2357
        $css = str_replace(
2358
            'behavior:url("/main/css/csshover3.htc");',
2359
            '',
2360
            $css
2361
        );
2362
        $css = str_replace('main/', $root_rel.'main/', $css);
2363
        $css = str_replace(
2364
            'images/',
2365
            $root_rel.$css_path.$theme.'images/',
2366
            $css
2367
        );
2368
        $css = str_replace('../../img/', $root_rel.'main/img/', $css);
2369
        $asciimathmal_script = (api_contains_asciimathml(
2370
                $wikiContents
2371
            ) || api_contains_asciisvg($wikiContents))
2372
            ? '<script src="'.api_get_path(
2373
                WEB_CODE_PATH
2374
            ).'inc/lib/javascript/asciimath/ASCIIMathML.js" type="text/javascript"></script>'."\n" : '';
2375
2376
        $template = str_replace(
2377
            [
2378
                '{LANGUAGE}',
2379
                '{ENCODING}',
2380
                '{TEXT_DIRECTION}',
2381
                '{TITLE}',
2382
                '{CSS}',
2383
                '{ASCIIMATHML_SCRIPT}',
2384
            ],
2385
            [
2386
                api_get_language_isocode(),
2387
                api_get_system_encoding(),
2388
                api_get_text_direction(),
2389
                $wikiTitle,
2390
                $css,
2391
                $asciimathmal_script,
2392
            ],
2393
            $template
2394
        );
2395
2396
        if (0 != $groupId) {
2397
            $groupPart = '_group'.$groupId; // and add groupId to put the same document title in different groups
2398
            $group_properties = GroupManager::get_group_properties($groupId);
2399
            $groupPath = $group_properties['directory'];
2400
        } else {
2401
            $groupPart = '';
2402
            $groupPath = '';
2403
        }
2404
2405
        $exportDir = api_get_path(SYS_COURSE_PATH).api_get_course_path(
2406
            ).'/document'.$groupPath;
2407
        $exportFile = api_replace_dangerous_char($wikiTitle).$groupPart;
2408
        $wikiContents = trim(
2409
            preg_replace(
2410
                "/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/",
2411
                "$1",
2412
                $wikiContents
2413
            )
2414
        );
2415
        //TODO: put link instead of title
2416
        $wikiContents = str_replace('{CONTENT}', $wikiContents, $template);
2417
        // replace relative path by absolute path for courses, so you can see
2418
        // items into this page wiki (images, mp3, etc..) exported in documents
2419
        if (false !== api_strpos(
2420
                $wikiContents,
2421
                '../..'.api_get_path(REL_COURSE_PATH)
2422
            )) {
2423
            $web_course_path = api_get_path(WEB_COURSE_PATH);
2424
            $wikiContents = str_replace(
2425
                '../..'.api_get_path(REL_COURSE_PATH),
2426
                $web_course_path,
2427
                $wikiContents
2428
            );
2429
        }
2430
2431
        $i = 1;
2432
        //only export last version, but in new export new version in document area
2433
        while (file_exists($exportDir.'/'.$exportFile.'_'.$i.'.html')) {
2434
            $i++;
2435
        }
2436
2437
        $wikiFileName = $exportFile.'_'.$i.'.html';
2438
        $exportPath = $exportDir.'/'.$wikiFileName;
2439
2440
        file_put_contents($exportPath, $wikiContents);
2441
        $document = DocumentManager::addDocument(
2442
            $_course,
2443
            $groupPath.'/'.$wikiFileName,
2444
            'file',
2445
            filesize($exportPath),
2446
            $wikiTitle
2447
        );
2448
2449
        $id = $document->getId();
2450
2451
        return $id;
2452
    }
2453
2454
    /**
2455
     * Exports the wiki page to PDF.
2456
     */
2457
    public function export_to_pdf($id, $course_code)
2458
    {
2459
        if (!api_is_platform_admin()) {
2460
            if ('true' !== api_get_setting('students_export2pdf')) {
2461
                Display::addFlash(
2462
                    Display::return_message(
2463
                        get_lang('PDF download is not allowed for students'),
2464
                        'error',
2465
                        false
2466
                    )
2467
                );
2468
2469
                return false;
2470
            }
2471
        }
2472
2473
        $data = self::getWikiDataFromDb($id);
2474
        $content_pdf = api_html_entity_decode(
2475
            $data['content'],
2476
            ENT_QUOTES,
2477
            api_get_system_encoding()
2478
        );
2479
2480
        //clean wiki links
2481
        $content_pdf = trim(
2482
            preg_replace(
2483
                "/\[[\[]?([^\]|]*)[|]?([^|\]]*)\][\]]?/",
2484
                "$1",
2485
                $content_pdf
2486
            )
2487
        );
2488
        //TODO: It should be better to display the link insted of the tile but it is hard for [[title]] links
2489
2490
        $title_pdf = api_html_entity_decode(
2491
            $data['title'],
2492
            ENT_QUOTES,
2493
            api_get_system_encoding()
2494
        );
2495
        $title_pdf = api_utf8_encode($title_pdf, api_get_system_encoding());
2496
        $content_pdf = api_utf8_encode($content_pdf, api_get_system_encoding());
2497
2498
        $html = '
2499
        <!-- defines the headers/footers - this must occur before the headers/footers are set -->
2500
2501
        <!--mpdf
2502
        <pageheader name="odds" content-left="'.$title_pdf.'"  header-style-left="color: #880000; font-style: italic;"  line="1" />
2503
        <pagefooter name="odds" content-right="{PAGENO}/{nb}" line="1" />
2504
2505
        <!-- set the headers/footers - they will occur from here on in the document -->
2506
        <!--mpdf
2507
        <setpageheader name="odds" page="odd" value="on" show-this-page="1" />
2508
        <setpagefooter name="odds" page="O" value="on" />
2509
2510
        mpdf-->'.$content_pdf;
2511
2512
        $css_file = api_get_path(SYS_CSS_PATH).'themes/'.api_get_setting('stylesheets').'/print.css';
2513
        if (file_exists($css_file)) {
2514
            $css = @file_get_contents($css_file);
2515
        } else {
2516
            $css = '';
2517
        }
2518
2519
        $pdf = new PDF();
2520
        $pdf->content_to_pdf($html, $css, $title_pdf, $course_code);
2521
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
2522
    }
2523
2524
    /**
2525
     * Function prevent double post (reload or F5).
2526
     */
2527
    public function double_post($wpost_id)
2528
    {
2529
        $postId = Session::read('wpost_id');
2530
        if (!empty($postId)) {
2531
            if ($wpost_id == $postId) {
2532
                return false;
2533
            } else {
2534
                Session::write('wpost_id', $wpost_id);
2535
2536
                return true;
2537
            }
2538
        } else {
2539
            Session::write('wpost_id', $wpost_id);
2540
2541
            return true;
2542
        }
2543
    }
2544
2545
    /**
2546
     * Function wizard individual assignment.
2547
     *
2548
     * @author Juan Carlos Raña <[email protected]>
2549
     */
2550
    public function auto_add_page_users($values)
2551
    {
2552
        $assignment_type = $values['assignment'];
2553
        $session_id = $this->session_id;
2554
        $groupId = api_get_group_id();
2555
        $groupInfo = GroupManager::get_group_properties($groupId);
2556
        $group = api_get_group_entity($groupId);
2557
2558
        if (0 == $groupId) {
2559
            //extract course members
2560
            if (!empty($session_id)) {
2561
                $a_users_to_add = CourseManager::get_user_list_from_course_code(
2562
                    api_get_course_id(),
2563
                    $session_id
2564
                );
2565
            } else {
2566
                $a_users_to_add = CourseManager::get_user_list_from_course_code(
2567
                    api_get_course_id(),
2568
                    0
2569
                );
2570
            }
2571
        } else {
2572
            //extract group members
2573
            $subscribed_users = GroupManager::get_subscribed_users($groupInfo);
2574
            $tutors = $group->getTutors();
2575
            $subscribed_tutors = [];
2576
            foreach ($tutors as $tutor) {
2577
                $subscribed_tutors[] =$tutor->getUser()->getId();
2578
            }
2579
            $a_users_to_add_with_duplicates = array_merge(
2580
                $subscribed_users,
2581
                $subscribed_tutors
2582
            );
2583
            //remove duplicates
2584
            $a_users_to_add = $a_users_to_add_with_duplicates;
2585
            $a_users_to_add = array_unique($a_users_to_add);
2586
        }
2587
2588
        $all_students_pages = [];
2589
        // Data about teacher
2590
        $userId = api_get_user_id();
2591
        $userinfo = api_get_user_info($userId);
2592
        $username = api_htmlentities(
2593
            sprintf(get_lang('Login: %s'), $userinfo['username'], ENT_QUOTES)
2594
        );
2595
        $name = $userinfo['complete_name']." - ".$username;
2596
        $photo = '<img src="'.$userinfo['avatar'].'" alt="'.$name.'"  width="40" height="50" align="top" title="'.$name.'"  />';
2597
2598
        // teacher assignment title
2599
        $title_orig = $values['title'];
2600
2601
        // teacher assignment reflink
2602
        $link2teacher = $values['title'] = $title_orig."_uass".$userId;
2603
2604
        // first: teacher name, photo, and assignment description (original content)
2605
        $content_orig_A = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2606
        <table border="0">
2607
            <tr><td style="font-size:24px">'.get_lang('Assignment proposed by the trainer').'</td></tr>
2608
            <tr><td>'.$photo.'<br />'.Display::tag(
2609
                'span',
2610
                api_get_person_name(
2611
                    $userinfo['firstname'],
2612
                    $userinfo['lastname']
2613
                ),
2614
                ['title' => $username]
2615
            ).'</td></tr>
2616
        </table></div>';
2617
2618
        $content_orig_B = '<br/><div align="center" style="font-size:24px">'.
2619
            get_lang('Assignment proposed by the trainerription').': '.
2620
            $title_orig.'</div><br/>'.Security::remove_XSS($_POST['content']);
2621
2622
        //Second: student list (names, photo and links to their works).
2623
        //Third: Create Learners work pages.
2624
        foreach ($a_users_to_add as $o_user_to_add) {
2625
            if ($o_user_to_add['user_id'] != $userId) {
2626
                // except that puts the task
2627
                $assig_user_id = $o_user_to_add['user_id'];
2628
                // identifies each page as created by the student, not by teacher
2629
2630
                $userPicture = UserManager::getUserPicture($assig_user_id);
2631
                $username = api_htmlentities(
2632
                    sprintf(
2633
                        get_lang('Login: %s'),
2634
                        $o_user_to_add['username'],
2635
                        ENT_QUOTES
2636
                    )
2637
                );
2638
                $name = api_get_person_name(
2639
                        $o_user_to_add['firstname'],
2640
                        $o_user_to_add['lastname']
2641
                    )." . ".$username;
2642
                $photo = '<img src="'.$userPicture.'" alt="'.$name.'"  width="40" height="50" align="bottom" title="'.$name.'"  />';
2643
2644
                $is_tutor_of_group = GroupManager::isTutorOfGroup(
2645
                    $assig_user_id,
2646
                    $group
2647
                ); //student is tutor
2648
                $is_tutor_and_member = GroupManager::isTutorOfGroup(
2649
                        $assig_user_id,
2650
                        $group
2651
                    ) &&
2652
                    GroupManager::is_subscribed($assig_user_id, $group);
2653
                // student is tutor and member
2654
                if ($is_tutor_and_member) {
2655
                    $status_in_group = get_lang('Coach and group member');
2656
                } else {
2657
                    if ($is_tutor_of_group) {
2658
                        $status_in_group = get_lang('Group tutor');
2659
                    } else {
2660
                        $status_in_group = " "; //get_lang('GroupStandardMember')
2661
                    }
2662
                }
2663
2664
                if (1 == $assignment_type) {
2665
                    $values['title'] = $title_orig;
2666
                    $values['content'] = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
2667
                    <table border="0">
2668
                    <tr><td style="font-size:24px">'.get_lang('Learner paper').'</td></tr>
2669
                    <tr><td>'.$photo.'<br />'.$name.'</td></tr></table>
2670
                    </div>[['.$link2teacher.' | '.get_lang(
2671
                            'AssignmentLinktoTrainerPage'
2672
                        ).']] ';
2673
                    //If $content_orig_B is added here, the task written by
2674
                    // the professor was copied to the page of each student.
2675
                    // TODO: config options
2676
                    // AssignmentLinktoTeacherPage
2677
                    $all_students_pages[] = '<li>'.
2678
                        Display::tag(
2679
                            'span',
2680
                            strtoupper(
2681
                                $o_user_to_add['lastname']
2682
                            ).', '.$o_user_to_add['firstname'],
2683
                            ['title' => $username]
2684
                        ).
2685
                        ' [['.Security::remove_XSS(
2686
                            $_POST['title']
2687
                        )."_uass".$assig_user_id.' | '.$photo.']] '.$status_in_group.'</li>';
2688
                    // don't change this line without guaranteeing
2689
                    // that users will be ordered by last names in the
2690
                    // following format (surname, name)
2691
                    $values['assignment'] = 2;
2692
                }
2693
                $this->assig_user_id = $assig_user_id;
2694
                self::save_new_wiki($values);
2695
            }
2696
        }
2697
2698
        foreach ($a_users_to_add as $o_user_to_add) {
2699
            if ($o_user_to_add['user_id'] == $userId) {
2700
                $assig_user_id = $o_user_to_add['user_id'];
2701
                if (1 == $assignment_type) {
2702
                    $values['title'] = $title_orig;
2703
                    $values['comment'] = get_lang('Assignment proposed by the trainer');
2704
                    sort($all_students_pages);
2705
                    $values['content'] = $content_orig_A.$content_orig_B.'<br/>
2706
                    <div align="center" style="font-size:18px; background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2707
                    '.get_lang('Access to the papers written by learners').'
2708
                    </div><br/>
2709
                    <div style="background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
2710
                    <ol>'.implode($all_students_pages).'</ol>
2711
                    </div>
2712
                    <br/>';
2713
                    $values['assignment'] = 1;
2714
                }
2715
                $this->assig_user_id = $assig_user_id;
2716
                self::save_new_wiki($values);
2717
            }
2718
        }
2719
    }
2720
2721
    /**
2722
     * Displays the results of a wiki search.
2723
     *
2724
     * @param   string  Search term
2725
     * @param   int     Whether to search the contents (1) or just the titles (0)
2726
     * @param int
2727
     */
2728
    public function display_wiki_search_results(
2729
        $search_term,
2730
        $search_content = 0,
2731
        $all_vers = 0
2732
    ) {
2733
        $tbl_wiki = $this->tbl_wiki;
2734
        $condition_session = $this->condition_session;
2735
        $groupfilter = $this->groupfilter;
2736
        $_course = $this->courseInfo;
2737
        $course_id = api_get_course_int_id();
2738
        echo '<legend>'.get_lang('Group wikiSearchResults').': '.Security::remove_XSS(
2739
                $search_term
2740
            );
2741
        echo '</legend>';
2742
2743
        //only by professors when page is hidden
2744
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
2745
            if ('1' == $all_vers) {
2746
                if ('1' == $search_content) {
2747
                    $sql = "SELECT * FROM ".$tbl_wiki."
2748
                            WHERE
2749
                                c_id = $course_id AND
2750
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2751
                                content LIKE '%".Database::escape_string(
2752
                            $search_term
2753
                        )."%' AND ".$groupfilter.$condition_session;
2754
                } else {
2755
                    $sql = "SELECT * FROM ".$tbl_wiki."
2756
                            WHERE
2757
                                c_id = $course_id AND
2758
                                title LIKE '%".Database::escape_string(
2759
                            $search_term
2760
                        )."%' AND ".$groupfilter.$condition_session;
2761
                }
2762
            } else {
2763
                if ('1' == $search_content) {
2764
                    // warning don't use group by reflink because don't return the last version
2765
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2766
                            WHERE
2767
                                s1.c_id = $course_id AND
2768
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2769
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2770
                                id=(
2771
                                    SELECT MAX(s2.id)
2772
                                    FROM ".$tbl_wiki." s2
2773
                                    WHERE
2774
                                        s2.c_id = $course_id AND
2775
                                        s1.reflink = s2.reflink AND
2776
                                        ".$groupfilter.$condition_session.")";
2777
                } else {
2778
                    // warning don't use group by reflink because don't return the last version
2779
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2780
                            WHERE
2781
                                s1.c_id = $course_id AND
2782
                                title LIKE '%".Database::escape_string(
2783
                            $search_term
2784
                        )."%' AND
2785
                                id = (
2786
                                    SELECT MAX(s2.id)
2787
                                    FROM ".$tbl_wiki." s2
2788
                                    WHERE
2789
                                        s2.c_id = $course_id AND
2790
                                        s1.reflink = s2.reflink AND
2791
                                        ".$groupfilter.$condition_session.")";
2792
                }
2793
            }
2794
        } else {
2795
            if ('1' == $all_vers) {
2796
                if ('1' == $search_content) {
2797
                    //search all pages and all versions
2798
                    $sql = "SELECT * FROM ".$tbl_wiki."
2799
                            WHERE
2800
                                c_id = $course_id AND
2801
                                visibility=1 AND
2802
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2803
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2804
                                ".$groupfilter.$condition_session;
2805
                } else {
2806
                    $sql = "SELECT * FROM ".$tbl_wiki."
2807
                            WHERE
2808
                                c_id = $course_id AND
2809
                                visibility=1 AND
2810
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2811
                                ".$groupfilter.$condition_session;
2812
                }
2813
            } else {
2814
                if ('1' == $search_content) {
2815
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2816
                            WHERE
2817
                                s1.c_id = $course_id AND
2818
                                visibility=1 AND
2819
                                title LIKE '%".Database::escape_string($search_term)."%' OR
2820
                                content LIKE '%".Database::escape_string($search_term)."%' AND
2821
                                id=(
2822
                                    SELECT MAX(s2.id)
2823
                                    FROM ".$tbl_wiki." s2
2824
                                    WHERE s2.c_id = $course_id AND
2825
                                    s1.reflink = s2.reflink AND
2826
                                    ".$groupfilter.$condition_session.")";
2827
                } else {
2828
                    // warning don't use group by reflink because don't return the last version
2829
                    $sql = "SELECT * FROM ".$tbl_wiki." s1
2830
                            WHERE
2831
                                s1.c_id = $course_id AND
2832
                                visibility=1 AND
2833
                                title LIKE '%".Database::escape_string($search_term)."%' AND
2834
                            id = (
2835
                                SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
2836
                                WHERE s2.c_id = $course_id AND
2837
                                s1.reflink = s2.reflink AND
2838
                                ".$groupfilter.$condition_session.")";
2839
                }
2840
            }
2841
        }
2842
2843
        $result = Database::query($sql);
2844
2845
        //show table
2846
        $rows = [];
2847
        if (Database::num_rows($result) > 0) {
2848
            while ($obj = Database::fetch_object($result)) {
2849
                // get author
2850
                $userinfo = api_get_user_info($obj->user_id);
2851
                // get time
2852
                $year = substr($obj->dtime, 0, 4);
2853
                $month = substr($obj->dtime, 5, 2);
2854
                $day = substr($obj->dtime, 8, 2);
2855
                $hours = substr($obj->dtime, 11, 2);
2856
                $minutes = substr($obj->dtime, 14, 2);
2857
                $seconds = substr($obj->dtime, 17, 2);
2858
2859
                //get type assignment icon
2860
                if (1 == $obj->assignment) {
2861
                    $ShowAssignment = Display::return_icon(
2862
                        'wiki_assignment.png',
2863
                        get_lang('Assignment proposed by the trainer'),
2864
                        '',
2865
                        ICON_SIZE_SMALL
2866
                    );
2867
                } elseif (2 == $obj->assignment) {
2868
                    $ShowAssignment = Display::return_icon(
2869
                        'wiki_work.png',
2870
                        get_lang('Learner paper'),
2871
                        '',
2872
                        ICON_SIZE_SMALL
2873
                    );
2874
                } elseif (0 == $obj->assignment) {
2875
                    $ShowAssignment = Display::return_icon(
2876
                        'px_transparent.gif'
2877
                    );
2878
                }
2879
                $row = [];
2880
                $row[] = $ShowAssignment;
2881
2882
                if ('1' == $all_vers) {
2883
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2884
                        ).'&action=showpage&title='.api_htmlentities(
2885
                            urlencode($obj->reflink)
2886
                        ).'&view='.$obj->id.'&session_id='.api_htmlentities(
2887
                            urlencode($_GET['$session_id'])
2888
                        ).'&group_id='.api_htmlentities(
2889
                            urlencode($_GET['group_id'])
2890
                        ).'">'.
2891
                        api_htmlentities($obj->title).'</a>';
2892
                } else {
2893
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2894
                        ).'&action=showpage&title='.api_htmlentities(
2895
                            urlencode($obj->reflink)
2896
                        ).'&session_id='.api_htmlentities(
2897
                            $_GET['session_id']
2898
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2899
                        $obj->title.'</a>';
2900
                }
2901
2902
                $row[] = (0 != $obj->user_id && false !== $userinfo) ? UserManager::getUserProfileLink(
2903
                    $userinfo
2904
                ) : get_lang('Anonymous').' ('.$obj->user_ip.')';
2905
                $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
2906
2907
                if ('1' == $all_vers) {
2908
                    $row[] = $obj->version;
2909
                } else {
2910
                    $showdelete = '';
2911
                    if (api_is_allowed_to_edit(
2912
                            false,
2913
                            true
2914
                        ) || api_is_platform_admin()) {
2915
                        $showdelete = ' <a href="'.api_get_self(
2916
                            ).'?'.api_get_cidreq(
2917
                            ).'&action=delete&title='.api_htmlentities(
2918
                                urlencode($obj->reflink)
2919
                            ).'&group_id='.api_htmlentities(
2920
                                $_GET['group_id']
2921
                            ).'">'.
2922
                            Display::return_icon(
2923
                                'delete.png',
2924
                                get_lang('Delete'),
2925
                                '',
2926
                                ICON_SIZE_SMALL
2927
                            );
2928
                    }
2929
                    $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
2930
                        ).'&action=edit&title='.api_htmlentities(
2931
                            urlencode($obj->reflink)
2932
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2933
                        Display::return_icon(
2934
                            'edit.png',
2935
                            get_lang('Edit'),
2936
                            '',
2937
                            ICON_SIZE_SMALL
2938
                        ).'</a>
2939
                        <a href="'.api_get_self(
2940
                        ).'?cidReq='.$_course['code'].'&action=discuss&title='.api_htmlentities(
2941
                            urlencode($obj->reflink)
2942
                        ).'&session_id='.api_htmlentities(
2943
                            $_GET['session_id']
2944
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2945
                        Display::return_icon(
2946
                            'discuss.png',
2947
                            get_lang('Discuss'),
2948
                            '',
2949
                            ICON_SIZE_SMALL
2950
                        ).'</a>
2951
                        <a href="'.api_get_self(
2952
                        ).'?cidReq='.$_course['code'].'&action=history&title='.api_htmlentities(
2953
                            urlencode($obj->reflink)
2954
                        ).'&session_id='.api_htmlentities(
2955
                            $_GET['session_id']
2956
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2957
                        Display::return_icon(
2958
                            'history.png',
2959
                            get_lang('History'),
2960
                            '',
2961
                            ICON_SIZE_SMALL
2962
                        ).'</a> <a href="'.api_get_self(
2963
                        ).'?cidReq='.$_course['code'].'&action=links&title='.api_htmlentities(
2964
                            urlencode($obj->reflink)
2965
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
2966
                        Display::return_icon(
2967
                            'what_link_here.png',
2968
                            get_lang('What links here'),
2969
                            '',
2970
                            ICON_SIZE_SMALL
2971
                        ).'</a>'.$showdelete;
2972
                }
2973
                $rows[] = $row;
2974
            }
2975
2976
            $table = new SortableTableFromArrayConfig(
2977
                $rows,
2978
                1,
2979
                10,
2980
                'SearchPages_table',
2981
                '',
2982
                '',
2983
                'ASC'
2984
            );
2985
            $table->set_additional_parameters(
2986
                [
2987
                    'cidReq' => $_GET['cidReq'],
2988
                    'action' => $_GET['action'],
2989
                    'group_id' => intval($_GET['group_id']),
2990
                    'mode_table' => 'yes2',
2991
                    'search_term' => $search_term,
2992
                    'search_content' => $search_content,
2993
                    'all_vers' => $all_vers,
2994
                ]
2995
            );
2996
            $table->set_header(
2997
                0,
2998
                get_lang('Type'),
2999
                true,
3000
                ['style' => 'width:30px;']
3001
            );
3002
            $table->set_header(1, get_lang('Title'), true);
3003
            if ('1' == $all_vers) {
3004
                $table->set_header(2, get_lang('Author'), true);
3005
                $table->set_header(3, get_lang('Date'), true);
3006
                $table->set_header(4, get_lang('Version'), true);
3007
            } else {
3008
                $table->set_header(
3009
                    2,
3010
                    get_lang('Author').' ('.get_lang('Latest version').')',
3011
                    true
3012
                );
3013
                $table->set_header(
3014
                    3,
3015
                    get_lang('Date').' ('.get_lang('Latest version').')',
3016
                    true
3017
                );
3018
                $table->set_header(
3019
                    4,
3020
                    get_lang('Detail'),
3021
                    false,
3022
                    ['style' => 'width:130px;']
3023
                );
3024
            }
3025
            $table->display();
3026
        } else {
3027
            echo get_lang('No search results');
3028
        }
3029
    }
3030
3031
    /**
3032
     * Get wiki information.
3033
     *
3034
     * @param   int|bool wiki id
3035
     *
3036
     * @return array wiki data
3037
     */
3038
    public function getWikiDataFromDb($id)
3039
    {
3040
        $tbl_wiki = $this->tbl_wiki;
3041
        $course_id = api_get_course_int_id();
3042
        if (false === $id) {
3043
            return [];
3044
        }
3045
        $id = intval($id);
3046
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3047
                WHERE c_id = '.$course_id.' AND id = '.$id.' ';
3048
        $result = Database::query($sql);
3049
        $data = [];
3050
        while ($row = Database::fetch_array($result, 'ASSOC')) {
3051
            $data = $row;
3052
        }
3053
3054
        return $data;
3055
    }
3056
3057
    /**
3058
     * @param string $refLink
3059
     *
3060
     * @return array
3061
     */
3062
    public function getLastWikiData($refLink)
3063
    {
3064
        $tbl_wiki = $this->tbl_wiki;
3065
        $groupfilter = $this->groupfilter;
3066
        $condition_session = $this->condition_session;
3067
        $course_id = api_get_course_int_id();
3068
3069
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3070
                WHERE
3071
                    c_id = '.$course_id.' AND
3072
                    reflink="'.Database::escape_string($refLink).'" AND
3073
                    '.$groupfilter.$condition_session.'
3074
                ORDER BY id DESC';
3075
3076
        $result = Database::query($sql);
3077
3078
        return Database::fetch_array($result);
3079
    }
3080
3081
    /**
3082
     * Get wiki information.
3083
     *
3084
     * @param   string     wiki id
3085
     * @param int $courseId
3086
     *
3087
     * @return array wiki data
3088
     */
3089
    public function getPageByTitle($title, $courseId = null)
3090
    {
3091
        $tbl_wiki = $this->tbl_wiki;
3092
        if (empty($courseId)) {
3093
            $courseId = api_get_course_int_id();
3094
        } else {
3095
            $courseId = intval($courseId);
3096
        }
3097
3098
        if (empty($title) || empty($courseId)) {
3099
            return [];
3100
        }
3101
3102
        $title = Database::escape_string($title);
3103
        $sql = "SELECT * FROM $tbl_wiki
3104
                WHERE c_id = $courseId AND reflink = '$title'";
3105
        $result = Database::query($sql);
3106
        $data = [];
3107
        if (Database::num_rows($result)) {
3108
            $data = Database::fetch_array($result, 'ASSOC');
3109
        }
3110
3111
        return $data;
3112
    }
3113
3114
    /**
3115
     * @param string $title
3116
     * @param int    $courseId
3117
     * @param string
3118
     * @param string
3119
     *
3120
     * @return bool
3121
     */
3122
    public function deletePage(
3123
        $title,
3124
        $courseId,
3125
        $groupfilter = null,
3126
        $condition_session = null
3127
    ) {
3128
        $tbl_wiki = $this->tbl_wiki;
3129
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
3130
        $tbl_wiki_mailcue = $this->tbl_wiki_mailcue;
3131
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3132
3133
        $pageInfo = self::getPageByTitle($title, $courseId);
3134
        if (!empty($pageInfo)) {
3135
            $pageId = $pageInfo['id'];
3136
            $sql = "DELETE FROM $tbl_wiki_conf
3137
                    WHERE c_id = $courseId AND page_id = $pageId";
3138
            Database::query($sql);
3139
3140
            $sql = 'DELETE FROM '.$tbl_wiki_discuss.'
3141
                    WHERE c_id = '.$courseId.' AND publication_id = '.$pageId;
3142
            Database::query($sql);
3143
3144
            $sql = 'DELETE FROM  '.$tbl_wiki_mailcue.'
3145
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3146
            Database::query($sql);
3147
3148
            $sql = 'DELETE FROM '.$tbl_wiki.'
3149
                    WHERE c_id = '.$courseId.' AND id = '.$pageId.' AND '.$groupfilter.$condition_session.'';
3150
            Database::query($sql);
3151
            self::check_emailcue(0, 'E');
3152
3153
            return true;
3154
        }
3155
3156
        return false;
3157
    }
3158
3159
    /**
3160
     * @return array
3161
     */
3162
    public function getAllWiki()
3163
    {
3164
        $tbl_wiki = $this->tbl_wiki;
3165
        $course_id = $this->course_id;
3166
        $condition_session = $this->condition_session;
3167
3168
        $sql = "SELECT * FROM $tbl_wiki
3169
                WHERE
3170
                    c_id = $course_id AND
3171
                    is_editing != '0' ".$condition_session;
3172
        $result = Database::query($sql);
3173
3174
        return Database::store_result($result, 'ASSOC');
3175
    }
3176
3177
    /**
3178
     * @param int $isEditing
3179
     */
3180
    public function updateWikiIsEditing($isEditing)
3181
    {
3182
        $tbl_wiki = $this->tbl_wiki;
3183
        $course_id = $this->course_id;
3184
        $condition_session = $this->condition_session;
3185
        $isEditing = Database::escape_string($isEditing);
3186
3187
        $sql = 'UPDATE '.$tbl_wiki.' SET
3188
                is_editing = "0",
3189
                time_edit = NULL
3190
                WHERE
3191
                    c_id = '.$course_id.' AND
3192
                    is_editing="'.$isEditing.'" '.
3193
            $condition_session;
3194
        Database::query($sql);
3195
    }
3196
3197
    /**
3198
     * Release of blocked pages to prevent concurrent editions.
3199
     *
3200
     * @param int    $userId
3201
     * @param string $action
3202
     */
3203
    public function blockConcurrentEditions($userId, $action = null)
3204
    {
3205
        $result = self::getAllWiki();
3206
        if (!empty($result)) {
3207
            foreach ($result as $is_editing_block) {
3208
                $max_edit_time = 1200; // 20 minutes
3209
                $timestamp_edit = strtotime($is_editing_block['time_edit']);
3210
                $time_editing = time() - $timestamp_edit;
3211
3212
                // First prevent concurrent users and double version
3213
                if ($is_editing_block['is_editing'] == $userId) {
3214
                    Session::write('_version', $is_editing_block['version']);
3215
                } else {
3216
                    Session::erase('_version');
3217
                }
3218
                // Second checks if has exceeded the time that a page may
3219
                // be available or if a page was edited and saved by its author
3220
                if ($time_editing > $max_edit_time ||
3221
                    ($is_editing_block['is_editing'] == $userId &&
3222
                        'edit' != $action)
3223
                ) {
3224
                    self::updateWikiIsEditing($is_editing_block['is_editing']);
3225
                }
3226
            }
3227
        }
3228
    }
3229
3230
    /**
3231
     * Showing wiki stats.
3232
     */
3233
    public function getStats()
3234
    {
3235
        if (!api_is_allowed_to_edit(false, true)) {
3236
            return false;
3237
        }
3238
3239
        $tbl_wiki = $this->tbl_wiki;
3240
        $course_id = $this->course_id;
3241
        $condition_session = $this->condition_session;
3242
        $groupfilter = $this->groupfilter;
3243
        $session_id = $this->session_id;
3244
        $tbl_wiki_conf = $this->tbl_wiki_conf;
3245
3246
        echo '<div class="actions">'.get_lang('Statistics').'</div>';
3247
3248
        // Check all versions of all pages
3249
        $total_words = 0;
3250
        $total_links = 0;
3251
        $total_links_anchors = 0;
3252
        $total_links_mail = 0;
3253
        $total_links_ftp = 0;
3254
        $total_links_irc = 0;
3255
        $total_links_news = 0;
3256
        $total_wlinks = 0;
3257
        $total_images = 0;
3258
        $clean_total_flash = 0;
3259
        $total_flash = 0;
3260
        $total_mp3 = 0;
3261
        $total_flv_p = 0;
3262
        $total_flv = 0;
3263
        $total_youtube = 0;
3264
        $total_multimedia = 0;
3265
        $total_tables = 0;
3266
3267
        $sql = "SELECT *, COUNT(*) AS TOTAL_VERS, SUM(hits) AS TOTAL_VISITS
3268
                FROM ".$tbl_wiki."
3269
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3270
3271
        $allpages = Database::query($sql);
3272
        while ($row = Database::fetch_array($allpages)) {
3273
            $total_versions = $row['TOTAL_VERS'];
3274
            $total_visits = intval($row['TOTAL_VISITS']);
3275
        }
3276
3277
        $sql = "SELECT * FROM ".$tbl_wiki."
3278
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."";
3279
        $allpages = Database::query($sql);
3280
3281
        while ($row = Database::fetch_array($allpages)) {
3282
            $total_words = $total_words + self::word_count($row['content']);
3283
            $total_links = $total_links + substr_count(
3284
                $row['content'],
3285
                "href="
3286
            );
3287
            $total_links_anchors = $total_links_anchors + substr_count(
3288
                $row['content'],
3289
                'href="#'
3290
            );
3291
            $total_links_mail = $total_links_mail + substr_count(
3292
                $row['content'],
3293
                'href="mailto'
3294
            );
3295
            $total_links_ftp = $total_links_ftp + substr_count(
3296
                $row['content'],
3297
                'href="ftp'
3298
            );
3299
            $total_links_irc = $total_links_irc + substr_count(
3300
                $row['content'],
3301
                'href="irc'
3302
            );
3303
            $total_links_news = $total_links_news + substr_count(
3304
                $row['content'],
3305
                'href="news'
3306
            );
3307
            $total_wlinks = $total_wlinks + substr_count($row['content'], "[[");
3308
            $total_images = $total_images + substr_count(
3309
                $row['content'],
3310
                "<img"
3311
            );
3312
            $clean_total_flash = preg_replace(
3313
                '/player.swf/',
3314
                ' ',
3315
                $row['content']
3316
            );
3317
            $total_flash = $total_flash + substr_count(
3318
                $clean_total_flash,
3319
                '.swf"'
3320
            );
3321
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3322
            $total_mp3 = $total_mp3 + substr_count($row['content'], ".mp3");
3323
            $total_flv_p = $total_flv_p + substr_count($row['content'], ".flv");
3324
            $total_flv = $total_flv_p / 5;
3325
            $total_youtube = $total_youtube + substr_count(
3326
                $row['content'],
3327
                "http://www.youtube.com"
3328
            );
3329
            $total_multimedia = $total_multimedia + substr_count(
3330
                $row['content'],
3331
                "video/x-msvideo"
3332
            );
3333
            $total_tables = $total_tables + substr_count(
3334
                $row['content'],
3335
                "<table"
3336
            );
3337
        }
3338
3339
        // Check only last version of all pages (current page)
3340
        $sql = ' SELECT *, COUNT(*) AS TOTAL_PAGES, SUM(hits) AS TOTAL_VISITS_LV
3341
                FROM  '.$tbl_wiki.' s1
3342
                WHERE s1.c_id = '.$course_id.' AND id=(
3343
                    SELECT MAX(s2.id)
3344
                    FROM '.$tbl_wiki.' s2
3345
                    WHERE
3346
                        s2.c_id = '.$course_id.' AND
3347
                        s1.reflink = s2.reflink AND
3348
                        '.$groupfilter.' AND
3349
                        session_id='.$session_id.')';
3350
        $allpages = Database::query($sql);
3351
        while ($row = Database::fetch_array($allpages)) {
3352
            $total_pages = $row['TOTAL_PAGES'];
3353
            $total_visits_lv = intval($row['TOTAL_VISITS_LV']);
3354
        }
3355
3356
        $total_words_lv = 0;
3357
        $total_links_lv = 0;
3358
        $total_links_anchors_lv = 0;
3359
        $total_links_mail_lv = 0;
3360
        $total_links_ftp_lv = 0;
3361
        $total_links_irc_lv = 0;
3362
        $total_links_news_lv = 0;
3363
        $total_wlinks_lv = 0;
3364
        $total_images_lv = 0;
3365
        $clean_total_flash_lv = 0;
3366
        $total_flash_lv = 0;
3367
        $total_mp3_lv = 0;
3368
        $total_flv_p_lv = 0;
3369
        $total_flv_lv = 0;
3370
        $total_youtube_lv = 0;
3371
        $total_multimedia_lv = 0;
3372
        $total_tables_lv = 0;
3373
3374
        $sql = 'SELECT * FROM  '.$tbl_wiki.' s1
3375
                WHERE s1.c_id = '.$course_id.' AND id=(
3376
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3377
                    WHERE
3378
                        s2.c_id = '.$course_id.' AND
3379
                        s1.reflink = s2.reflink AND
3380
                        '.$groupfilter.' AND
3381
                        session_id='.$session_id.'
3382
                )';
3383
        $allpages = Database::query($sql);
3384
3385
        while ($row = Database::fetch_array($allpages)) {
3386
            $total_words_lv = $total_words_lv + self::word_count(
3387
                $row['content']
3388
            );
3389
            $total_links_lv = $total_links_lv + substr_count(
3390
                $row['content'],
3391
                "href="
3392
            );
3393
            $total_links_anchors_lv = $total_links_anchors_lv + substr_count(
3394
                $row['content'],
3395
                'href="#'
3396
            );
3397
            $total_links_mail_lv = $total_links_mail_lv + substr_count(
3398
                $row['content'],
3399
                'href="mailto'
3400
            );
3401
            $total_links_ftp_lv = $total_links_ftp_lv + substr_count(
3402
                $row['content'],
3403
                'href="ftp'
3404
            );
3405
            $total_links_irc_lv = $total_links_irc_lv + substr_count(
3406
                $row['content'],
3407
                'href="irc'
3408
            );
3409
            $total_links_news_lv = $total_links_news_lv + substr_count(
3410
                $row['content'],
3411
                'href="news'
3412
            );
3413
            $total_wlinks_lv = $total_wlinks_lv + substr_count(
3414
                $row['content'],
3415
                "[["
3416
            );
3417
            $total_images_lv = $total_images_lv + substr_count(
3418
                $row['content'],
3419
                "<img"
3420
            );
3421
            $clean_total_flash_lv = preg_replace(
3422
                '/player.swf/',
3423
                ' ',
3424
                $row['content']
3425
            );
3426
            $total_flash_lv = $total_flash_lv + substr_count(
3427
                $clean_total_flash_lv,
3428
                '.swf"'
3429
            );
3430
            //.swf" end quotes prevent insert swf through flvplayer (is not counted)
3431
            $total_mp3_lv = $total_mp3_lv + substr_count(
3432
                $row['content'],
3433
                ".mp3"
3434
            );
3435
            $total_flv_p_lv = $total_flv_p_lv + substr_count(
3436
                $row['content'],
3437
                ".flv"
3438
            );
3439
            $total_flv_lv = $total_flv_p_lv / 5;
3440
            $total_youtube_lv = $total_youtube_lv + substr_count(
3441
                $row['content'],
3442
                "http://www.youtube.com"
3443
            );
3444
            $total_multimedia_lv = $total_multimedia_lv + substr_count(
3445
                $row['content'],
3446
                "video/x-msvideo"
3447
            );
3448
            $total_tables_lv = $total_tables_lv + substr_count(
3449
                $row['content'],
3450
                "<table"
3451
            );
3452
        }
3453
3454
        //Total pages edited at this time
3455
        $total_editing_now = 0;
3456
        $sql = 'SELECT *, COUNT(*) AS TOTAL_EDITING_NOW
3457
                FROM  '.$tbl_wiki.' s1
3458
                WHERE is_editing!=0 AND s1.c_id = '.$course_id.' AND
3459
                id=(
3460
                    SELECT MAX(s2.id)
3461
                    FROM '.$tbl_wiki.' s2
3462
                    WHERE
3463
                        s2.c_id = '.$course_id.' AND
3464
                        s1.reflink = s2.reflink AND
3465
                        '.$groupfilter.' AND
3466
                        session_id='.$session_id.'
3467
        )';
3468
3469
        // Can not use group by because the mark is set in the latest version
3470
        $allpages = Database::query($sql);
3471
        while ($row = Database::fetch_array($allpages)) {
3472
            $total_editing_now = $row['TOTAL_EDITING_NOW'];
3473
        }
3474
3475
        // Total hidden pages
3476
        $total_hidden = 0;
3477
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3478
                WHERE
3479
                    c_id = '.$course_id.' AND
3480
                    visibility = 0 AND
3481
                    '.$groupfilter.$condition_session.'
3482
                GROUP BY reflink';
3483
        // or group by page_id. As the mark of hidden places it in all
3484
        // versions of the page, I can use group by to see the first
3485
        $allpages = Database::query($sql);
3486
        while ($row = Database::fetch_array($allpages)) {
3487
            $total_hidden = $total_hidden + 1;
3488
        }
3489
3490
        //Total protect pages
3491
        $total_protected = 0;
3492
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3493
                WHERE
3494
                    c_id = '.$course_id.' AND
3495
                    editlock = 1 AND
3496
                     '.$groupfilter.$condition_session.'
3497
                GROUP BY reflink';
3498
        // or group by page_id. As the mark of protected page is the
3499
        // first version of the page, I can use group by
3500
        $allpages = Database::query($sql);
3501
        while ($row = Database::fetch_array($allpages)) {
3502
            $total_protected = $total_protected + 1;
3503
        }
3504
3505
        // Total empty versions.
3506
        $total_empty_content = 0;
3507
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3508
                WHERE
3509
                    c_id = '.$course_id.' AND
3510
                    content="" AND
3511
                    '.$groupfilter.$condition_session.'';
3512
        $allpages = Database::query($sql);
3513
        while ($row = Database::fetch_array($allpages)) {
3514
            $total_empty_content = $total_empty_content + 1;
3515
        }
3516
3517
        //Total empty pages (last version)
3518
3519
        $total_empty_content_lv = 0;
3520
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3521
                WHERE s1.c_id = '.$course_id.' AND content="" AND id=(
3522
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3523
                    WHERE
3524
                        s1.c_id = '.$course_id.' AND
3525
                        s1.reflink = s2.reflink AND
3526
                        '.$groupfilter.' AND
3527
                        session_id='.$session_id.'
3528
                )';
3529
        $allpages = Database::query($sql);
3530
        while ($row = Database::fetch_array($allpages)) {
3531
            $total_empty_content_lv = $total_empty_content_lv + 1;
3532
        }
3533
3534
        // Total locked discuss pages
3535
        $total_lock_disc = 0;
3536
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3537
                WHERE c_id = '.$course_id.' AND addlock_disc=0 AND '.$groupfilter.$condition_session.'
3538
                GROUP BY reflink'; //group by because mark lock in all vers, then always is ok
3539
        $allpages = Database::query($sql);
3540
        while ($row = Database::fetch_array($allpages)) {
3541
            $total_lock_disc = $total_lock_disc + 1;
3542
        }
3543
3544
        // Total hidden discuss pages.
3545
        $total_hidden_disc = 0;
3546
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3547
                WHERE c_id = '.$course_id.' AND visibility_disc=0 AND '.$groupfilter.$condition_session.'
3548
                GROUP BY reflink';
3549
        //group by because mark lock in all vers, then always is ok
3550
        $allpages = Database::query($sql);
3551
        while ($row = Database::fetch_array($allpages)) {
3552
            $total_hidden_disc = $total_hidden_disc + 1;
3553
        }
3554
3555
        // Total versions with any short comment by user or system
3556
        $total_comment_version = 0;
3557
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3558
                WHERE c_id = '.$course_id.' AND comment!="" AND '.$groupfilter.$condition_session.'';
3559
        $allpages = Database::query($sql);
3560
        while ($row = Database::fetch_array($allpages)) {
3561
            $total_comment_version = $total_comment_version + 1;
3562
        }
3563
3564
        // Total pages that can only be scored by teachers.
3565
        $total_only_teachers_rating = 0;
3566
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3567
                WHERE c_id = '.$course_id.' AND
3568
                ratinglock_disc = 0 AND
3569
                '.$groupfilter.$condition_session.'
3570
                GROUP BY reflink'; //group by because mark lock in all vers, then always is ok
3571
        $allpages = Database::query($sql);
3572
        while ($row = Database::fetch_array($allpages)) {
3573
            $total_only_teachers_rating = $total_only_teachers_rating + 1;
3574
        }
3575
3576
        // Total pages scored by peers
3577
        // put always this line alfter check num all pages and num pages rated by teachers
3578
        $total_rating_by_peers = $total_pages - $total_only_teachers_rating;
3579
3580
        //Total pages identified as standard task
3581
        $total_task = 0;
3582
        $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
3583
              WHERE '.$tbl_wiki_conf.'.c_id = '.$course_id.' AND
3584
               '.$tbl_wiki_conf.'.task!="" AND
3585
               '.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
3586
                '.$tbl_wiki.'.'.$groupfilter.$condition_session;
3587
        $allpages = Database::query($sql);
3588
        while ($row = Database::fetch_array($allpages)) {
3589
            $total_task = $total_task + 1;
3590
        }
3591
3592
        //Total pages identified as teacher page (wiki portfolio mode - individual assignment)
3593
        $total_teacher_assignment = 0;
3594
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3595
                WHERE s1.c_id = '.$course_id.' AND assignment=1 AND id=(
3596
                    SELECT MAX(s2.id)
3597
                    FROM '.$tbl_wiki.' s2
3598
                    WHERE
3599
                        s2.c_id = '.$course_id.' AND
3600
                        s1.reflink = s2.reflink AND
3601
                        '.$groupfilter.' AND
3602
                         session_id='.$session_id.'
3603
                )';
3604
        //mark all versions, but do not use group by reflink because y want the pages not versions
3605
        $allpages = Database::query($sql);
3606
        while ($row = Database::fetch_array($allpages)) {
3607
            $total_teacher_assignment = $total_teacher_assignment + 1;
3608
        }
3609
3610
        //Total pages identifies as student page (wiki portfolio mode - individual assignment)
3611
        $total_student_assignment = 0;
3612
        $sql = 'SELECT  * FROM  '.$tbl_wiki.' s1
3613
                WHERE s1.c_id = '.$course_id.' AND assignment=2 AND
3614
                id = (SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3615
                WHERE
3616
                    s2.c_id = '.$course_id.' AND
3617
                    s1.reflink = s2.reflink AND
3618
                    '.$groupfilter.' AND
3619
                    session_id='.$session_id.'
3620
                )';
3621
        //mark all versions, but do not use group by reflink because y want the pages not versions
3622
        $allpages = Database::query($sql);
3623
        while ($row = Database::fetch_array($allpages)) {
3624
            $total_student_assignment = $total_student_assignment + 1;
3625
        }
3626
3627
        //Current Wiki status add new pages
3628
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3629
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3630
                GROUP BY addlock'; //group by because mark 0 in all vers, then always is ok
3631
        $allpages = Database::query($sql);
3632
        $wiki_add_lock = null;
3633
        while ($row = Database::fetch_array($allpages)) {
3634
            $wiki_add_lock = $row['addlock'];
3635
        }
3636
3637
        if (1 == $wiki_add_lock) {
3638
            $status_add_new_pag = get_lang('Yes');
3639
        } else {
3640
            $status_add_new_pag = get_lang('No');
3641
        }
3642
3643
        // Creation date of the oldest wiki page and version
3644
        $first_wiki_date = null;
3645
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3646
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3647
                ORDER BY dtime ASC
3648
                LIMIT 1';
3649
        $allpages = Database::query($sql);
3650
        while ($row = Database::fetch_array($allpages)) {
3651
            $first_wiki_date = api_get_local_time($row['dtime']);
3652
        }
3653
3654
        // Date of publication of the latest wiki version.
3655
3656
        $last_wiki_date = null;
3657
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3658
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3659
                ORDER BY dtime DESC
3660
                LIMIT 1';
3661
        $allpages = Database::query($sql);
3662
        while ($row = Database::fetch_array($allpages)) {
3663
            $last_wiki_date = api_get_local_time($row['dtime']);
3664
        }
3665
3666
        // Average score of all wiki pages. (If a page has not scored zero rated)
3667
        $media_score = 0;
3668
        $sql = "SELECT *, SUM(score) AS TOTAL_SCORE FROM ".$tbl_wiki."
3669
                WHERE c_id = $course_id AND ".$groupfilter.$condition_session."
3670
                GROUP BY reflink ";
3671
        //group by because mark in all versions, then always is ok.
3672
        // Do not use "count" because using "group by", would give a wrong value
3673
        $allpages = Database::query($sql);
3674
        $total_score = 0;
3675
        while ($row = Database::fetch_array($allpages)) {
3676
            $total_score = $total_score + $row['TOTAL_SCORE'];
3677
        }
3678
3679
        if (!empty($total_pages)) {
3680
            $media_score = $total_score / $total_pages;
3681
            //put always this line alfter check num all pages
3682
        }
3683
3684
        // Average user progress in his pages.
3685
        $media_progress = 0;
3686
        $sql = 'SELECT  *, SUM(progress) AS TOTAL_PROGRESS
3687
                FROM  '.$tbl_wiki.' s1
3688
                WHERE s1.c_id = '.$course_id.' AND id=
3689
                (
3690
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
3691
                    WHERE
3692
                        s2.c_id = '.$course_id.' AND
3693
                        s1.reflink = s2.reflink AND
3694
                        '.$groupfilter.' AND
3695
                        session_id='.$session_id.'
3696
                )';
3697
        // As the value is only the latest version I can not use group by
3698
        $allpages = Database::query($sql);
3699
        while ($row = Database::fetch_array($allpages)) {
3700
            $total_progress = $row['TOTAL_PROGRESS'];
3701
        }
3702
3703
        if (!empty($total_pages)) {
3704
            $media_progress = $total_progress / $total_pages;
3705
            //put always this line alfter check num all pages
3706
        }
3707
3708
        // Total users that have participated in the Group wiki
3709
        $total_users = 0;
3710
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3711
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3712
                GROUP BY user_id';
3713
        //as the mark of user it in all versions of the page, I can use group by to see the first
3714
        $allpages = Database::query($sql);
3715
        while ($row = Database::fetch_array($allpages)) {
3716
            $total_users = $total_users + 1;
3717
        }
3718
3719
        // Total of different IP addresses that have participated in the wiki
3720
        $total_ip = 0;
3721
        $sql = 'SELECT * FROM '.$tbl_wiki.'
3722
              WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3723
              GROUP BY user_ip';
3724
        $allpages = Database::query($sql);
3725
        while ($row = Database::fetch_array($allpages)) {
3726
            $total_ip = $total_ip + 1;
3727
        }
3728
3729
        echo '<table class="data_table">';
3730
        echo '<thead>';
3731
        echo '<tr>';
3732
        echo '<th colspan="2">'.get_lang('General').'</th>';
3733
        echo '</tr>';
3734
        echo '</thead>';
3735
        echo '<tr>';
3736
        echo '<td>'.get_lang('Learners can add new pages to the Wiki').'</td>';
3737
        echo '<td>'.$status_add_new_pag.'</td>';
3738
        echo '</tr>';
3739
        echo '<tr>';
3740
        echo '<td>'.get_lang('DateCreateOldestGroup wikiPage').'</td>';
3741
        echo '<td>'.$first_wiki_date.'</td>';
3742
        echo '</tr>';
3743
        echo '<tr>';
3744
        echo '<td>'.get_lang('DateEditLatestGroup wikiVersion').'</td>';
3745
        echo '<td>'.$last_wiki_date.'</td>';
3746
        echo '</tr>';
3747
        echo '<tr>';
3748
        echo '<td>'.get_lang('Average rating of all pages').'</td>';
3749
        echo '<td>'.$media_score.' %</td>';
3750
        echo '</tr>';
3751
        echo '<tr>';
3752
        echo '<td>'.get_lang('Mean estimated progress by users on their pages').'</td>';
3753
        echo '<td>'.$media_progress.' %</td>';
3754
        echo '</tr>';
3755
        echo '<tr>';
3756
        echo '<td>'.get_lang('TotalGroup wikiUsers').'</td>';
3757
        echo '<td>'.$total_users.'</td>';
3758
        echo '</tr>';
3759
        echo '<tr>';
3760
        echo '<td>'.get_lang('Total different IP addresses that have contributed to Wiki').'</td>';
3761
        echo '<td>'.$total_ip.'</td>';
3762
        echo '</tr>';
3763
        echo '</table>';
3764
        echo '<br/>';
3765
3766
        echo '<table class="data_table">';
3767
        echo '<thead>';
3768
        echo '<tr>';
3769
        echo '<th colspan="2">'.get_lang('Pages').' '.get_lang(
3770
                'And'
3771
            ).' '.get_lang('Versions').'</th>';
3772
        echo '</tr>';
3773
        echo '</thead>';
3774
        echo '<tr>';
3775
        echo '<td>'.get_lang('Pages').' - '.get_lang(
3776
                'Numcontributions'
3777
            ).'</td>';
3778
        echo '<td>'.$total_pages.' ('.get_lang(
3779
                'Versions'
3780
            ).': '.$total_versions.')</td>';
3781
        echo '</tr>';
3782
        echo '<tr>';
3783
        echo '<td>'.get_lang('Total of empty pages').'</td>';
3784
        echo '<td>'.$total_empty_content_lv.' ('.get_lang(
3785
                'Versions'
3786
            ).': '.$total_empty_content.')</td>';
3787
        echo '</tr>';
3788
        echo '<tr>';
3789
        echo '<td>'.get_lang('Number of visits').'</td>';
3790
        echo '<td>'.$total_visits_lv.' ('.get_lang(
3791
                'Versions'
3792
            ).': '.$total_visits.')</td>';
3793
        echo '</tr>';
3794
        echo '<tr>';
3795
        echo '<td>'.get_lang('Total pages edited at this time').'</td>';
3796
        echo '<td>'.$total_editing_now.'</td>';
3797
        echo '</tr>';
3798
        echo '<tr>';
3799
        echo '<td>'.get_lang('Total hidden pages').'</td>';
3800
        echo '<td>'.$total_hidden.'</td>';
3801
        echo '</tr>';
3802
        echo '<tr>';
3803
        echo '<td>'.get_lang('Number of protected pages').'</td>';
3804
        echo '<td>'.$total_protected.'</td>';
3805
        echo '</tr>';
3806
        echo '<tr>';
3807
        echo '<td>'.get_lang('Number of discussion pages blocked').'</td>';
3808
        echo '<td>'.$total_lock_disc.'</td>';
3809
        echo '</tr>';
3810
        echo '<tr>';
3811
        echo '<td>'.get_lang('Number of discussion pages hidden').'</td>';
3812
        echo '<td>'.$total_hidden_disc.'</td>';
3813
        echo '</tr>';
3814
        echo '<tr>';
3815
        echo '<td>'.get_lang('Total comments on various versions of the pages').'</td>';
3816
        echo '<td>'.$total_comment_version.'</td>';
3817
        echo '</tr>';
3818
        echo '<tr>';
3819
        echo '<td>'.get_lang('Total pages can only be scored by a teacher').'</td>';
3820
        echo '<td>'.$total_only_teachers_rating.'</td>';
3821
        echo '</tr>';
3822
        echo '<tr>';
3823
        echo '<td>'.get_lang('Total pages that can be scored by other learners').'</td>';
3824
        echo '<td>'.$total_rating_by_peers.'</td>';
3825
        echo '</tr>';
3826
        echo '<tr>';
3827
        echo '<td>'.get_lang('Number of assignments pages proposed by a teacher').' - '.get_lang(
3828
                'PortfolioMode'
3829
            ).'</td>';
3830
        echo '<td>'.$total_teacher_assignment.'</td>';
3831
        echo '</tr>';
3832
        echo '<tr>';
3833
        echo '<td>'.get_lang('Number of individual assignments learner pages').' - '.get_lang(
3834
                'PortfolioMode'
3835
            ).'</td>';
3836
        echo '<td>'.$total_student_assignment.'</td>';
3837
        echo '</tr>';
3838
        echo '<tr>';
3839
        echo '<td>'.get_lang('Number of tasks').' - '.get_lang(
3840
                'StandardMode'
3841
            ).'</td>';
3842
        echo '<td>'.$total_task.'</td>';
3843
        echo '</tr>';
3844
        echo '</table>';
3845
        echo '<br/>';
3846
3847
        echo '<table class="data_table">';
3848
        echo '<thead>';
3849
        echo '<tr>';
3850
        echo '<th colspan="3">'.get_lang('ContentPagesinfo').'</th>';
3851
        echo '</tr>';
3852
        echo '<tr>';
3853
        echo '<td></td>';
3854
        echo '<td>'.get_lang('inTheLatest version').'</td>';
3855
        echo '<td>'.get_lang('inAllVersions').'</td>';
3856
        echo '</tr>';
3857
        echo '</thead>';
3858
        echo '<tr>';
3859
        echo '<td>'.get_lang('Number of words').'</td>';
3860
        echo '<td>'.$total_words_lv.'</td>';
3861
        echo '<td>'.$total_words.'</td>';
3862
        echo '</tr>';
3863
        echo '<tr>';
3864
        echo '<td>'.get_lang('Number of external html links inserted (text, images, ...).').'</td>';
3865
        echo '<td>'.$total_links_lv.' ('.get_lang(
3866
                'Anchors'
3867
            ).':'.$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>';
3868
        echo '<td>'.$total_links.' ('.get_lang(
3869
                'Anchors'
3870
            ).':'.$total_links_anchors.', Mail:'.$total_links_mail.', FTP:'.$total_links_ftp.', IRC:'.$total_links_irc.', News:'.$total_links_news.', ... ) </td>';
3871
        echo '</tr>';
3872
        echo '<tr>';
3873
        echo '<td>'.get_lang('NumGroup wikilinks').'</td>';
3874
        echo '<td>'.$total_wlinks_lv.'</td>';
3875
        echo '<td>'.$total_wlinks.'</td>';
3876
        echo '</tr>';
3877
        echo '<tr>';
3878
        echo '<td>'.get_lang('Number of inserted images').'</td>';
3879
        echo '<td>'.$total_images_lv.'</td>';
3880
        echo '<td>'.$total_images.'</td>';
3881
        echo '</tr>';
3882
        echo '<tr>';
3883
        echo '<td>'.get_lang('Number of inserted flash files').'</td>';
3884
        echo '<td>'.$total_flash_lv.'</td>';
3885
        echo '<td>'.$total_flash.'</td>';
3886
        echo '</tr>';
3887
        echo '<tr>';
3888
        echo '<td>'.get_lang('Number of mp3 audio files inserted').'</td>';
3889
        echo '<td>'.$total_mp3_lv.'</td>';
3890
        echo '<td>'.$total_mp3.'</td>';
3891
        echo '</tr>';
3892
        echo '<tr>';
3893
        echo '<td>'.get_lang('Number of FLV video files inserted').'</td>';
3894
        echo '<td>'.$total_flv_lv.'</td>';
3895
        echo '<td>'.$total_flv.'</td>';
3896
        echo '</tr>';
3897
        echo '<tr>';
3898
        echo '<td>'.get_lang('Number of Youtube video embedded').'</td>';
3899
        echo '<td>'.$total_youtube_lv.'</td>';
3900
        echo '<td>'.$total_youtube.'</td>';
3901
        echo '</tr>';
3902
        echo '<tr>';
3903
        echo '<td>'.get_lang('Number of audio and video files inserted (except mp3 and flv)').'</td>';
3904
        echo '<td>'.$total_multimedia_lv.'</td>';
3905
        echo '<td>'.$total_multimedia.'</td>';
3906
        echo '</tr>';
3907
        echo '<tr>';
3908
        echo '<td>'.get_lang('Number of tables inserted').'</td>';
3909
        echo '<td>'.$total_tables_lv.'</td>';
3910
        echo '<td>'.$total_tables.'</td>';
3911
        echo '</tr>';
3912
        echo '</table>';
3913
    }
3914
3915
    /**
3916
     * @param string $action
3917
     */
3918
    public function getActiveUsers($action)
3919
    {
3920
        $tbl_wiki = $this->tbl_wiki;
3921
        $course_id = $this->course_id;
3922
        $condition_session = $this->condition_session;
3923
        $groupfilter = $this->groupfilter;
3924
        $_course = $this->courseInfo;
3925
3926
        echo '<div class="actions">'.get_lang('Most active users').'</div>';
3927
        $sql = 'SELECT *, COUNT(*) AS NUM_EDIT FROM '.$tbl_wiki.'
3928
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
3929
                GROUP BY user_id';
3930
        $allpages = Database::query($sql);
3931
3932
        //show table
3933
        if (Database::num_rows($allpages) > 0) {
3934
            while ($obj = Database::fetch_object($allpages)) {
3935
                $userinfo = api_get_user_info($obj->user_id);
3936
                $row = [];
3937
                if (0 != $obj->user_id && false !== $userinfo) {
3938
                    $row[] = UserManager::getUserProfileLink($userinfo).'
3939
                            <a href="'.api_get_self(
3940
                        ).'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode(
3941
                            $obj->user_id
3942
                        ).
3943
                        '&session_id='.api_htmlentities(
3944
                            $_GET['session_id']
3945
                        ).'&group_id='.api_htmlentities(
3946
                            $_GET['group_id']
3947
                        ).'"></a>';
3948
                } else {
3949
                    $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
3950
                }
3951
                $row[] = '<a href="'.api_get_self(
3952
                    ).'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.urlencode(
3953
                        $obj->user_id
3954
                    ).'&session_id='.api_htmlentities(
3955
                        $_GET['session_id']
3956
                    ).'&group_id='.api_htmlentities(
3957
                        $_GET['group_id']
3958
                    ).'">'.$obj->NUM_EDIT.'</a>';
3959
                $rows[] = $row;
3960
            }
3961
3962
            $table = new SortableTableFromArrayConfig(
3963
                $rows,
3964
                1,
3965
                10,
3966
                'MostActiveUsersA_table',
3967
                '',
3968
                '',
3969
                'DESC'
3970
            );
3971
            $table->set_additional_parameters(
3972
                [
3973
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
3974
                    'action' => Security::remove_XSS($action),
3975
                    'session_id' => Security::remove_XSS($_GET['session_id']),
3976
                    'group_id' => Security::remove_XSS($_GET['group_id']),
3977
                ]
3978
            );
3979
            $table->set_header(0, get_lang('Author'), true);
3980
            $table->set_header(
3981
                1,
3982
                get_lang('contributions'),
3983
                true,
3984
                ['style' => 'width:30px;']
3985
            );
3986
            $table->display();
3987
        }
3988
    }
3989
3990
    /**
3991
     * @param string $page
3992
     */
3993
    public function getDiscuss($page)
3994
    {
3995
        $tbl_wiki = $this->tbl_wiki;
3996
        $course_id = $this->course_id;
3997
        $condition_session = $this->condition_session;
3998
        $groupfilter = $this->groupfilter;
3999
        $tbl_wiki_discuss = $this->tbl_wiki_discuss;
4000
4001
        if (0 != api_get_session_id() &&
4002
            false == api_is_allowed_to_session_edit(false, true)
4003
        ) {
4004
            api_not_allowed();
4005
        }
4006
4007
        if (!$_GET['title']) {
4008
            Display::addFlash(
4009
                Display::return_message(
4010
                    get_lang("You must select a page first"),
4011
                    'error',
4012
                    false
4013
                )
4014
            );
4015
4016
            return;
4017
        }
4018
4019
        // First extract the date of last version
4020
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4021
                WHERE
4022
                    c_id = '.$course_id.' AND
4023
                    reflink = "'.Database::escape_string($page).'" AND
4024
                    '.$groupfilter.$condition_session.'
4025
                ORDER BY id DESC';
4026
        $result = Database::query($sql);
4027
        $row = Database::fetch_array($result);
4028
        $lastversiondate = api_get_local_time($row['dtime']);
4029
        $lastuserinfo = api_get_user_info($row['user_id']);
4030
4031
        // Select page to discuss
4032
        $sql = 'SELECT * FROM '.$tbl_wiki.'
4033
                WHERE
4034
                    c_id = '.$course_id.' AND
4035
                    reflink="'.Database::escape_string($page).'" AND
4036
                    '.$groupfilter.$condition_session.'
4037
                ORDER BY id ASC';
4038
        $result = Database::query($sql);
4039
        $row = Database::fetch_array($result);
4040
        $id = $row['id'];
4041
        $firstuserid = $row['user_id'];
4042
4043
        if (isset($_POST['Submit']) && self::double_post($_POST['wpost_id'])) {
4044
            $dtime = api_get_utc_datetime();
4045
            $message_author = api_get_user_id();
4046
4047
            $params = [
4048
                'c_id' => $course_id,
4049
                'publication_id' => $id,
4050
                'userc_id' => $message_author,
4051
                'comment' => $_POST['comment'],
4052
                'p_score' => $_POST['rating'],
4053
                'dtime' => $dtime,
4054
            ];
4055
            $discussId = Database::insert($tbl_wiki_discuss, $params);
4056
            if ($discussId) {
4057
                $sql = "UPDATE $tbl_wiki_discuss SET id = iid WHERE iid = $discussId";
4058
                Database::query($sql);
4059
            }
4060
4061
            self::check_emailcue($id, 'D', $dtime, $message_author);
4062
4063
            header(
4064
                'Location: index.php?action=discuss&title='.api_htmlentities(urlencode($page)).'&'.api_get_cidreq()
4065
            );
4066
            exit;
4067
        }
4068
4069
        // mode assignment: previous to show  page type
4070
        $icon_assignment = null;
4071
        if (1 == $row['assignment']) {
4072
            $icon_assignment = Display::return_icon(
4073
                'wiki_assignment.png',
4074
                get_lang('This page is an assignment proposed by a trainer'),
4075
                '',
4076
                ICON_SIZE_SMALL
4077
            );
4078
        } elseif (2 == $row['assignment']) {
4079
            $icon_assignment = Display::return_icon(
4080
                'wiki_work.png',
4081
                get_lang('Learner paperExtra'),
4082
                '',
4083
                ICON_SIZE_SMALL
4084
            );
4085
        }
4086
4087
        $countWPost = null;
4088
        $avg_WPost_score = null;
4089
4090
        // Show title and form to discuss if page exist
4091
        if ('' != $id) {
4092
            // Show discussion to students if isn't hidden.
4093
            // Show page to all teachers if is hidden.
4094
            // Mode assignments: If is hidden, show pages to student only if student is the author
4095
            if (1 == $row['visibility_disc'] ||
4096
                api_is_allowed_to_edit(false, true) ||
4097
                api_is_platform_admin() ||
4098
                (2 == $row['assignment'] && 0 == $row['visibility_disc'] && (api_get_user_id() == $row['user_id']))
4099
            ) {
4100
                echo '<div id="wikititle">';
4101
                // discussion action: protecting (locking) the discussion
4102
                $addlock_disc = null;
4103
                $lock_unlock_disc = null;
4104
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4105
                    if (1 == self::check_addlock_discuss()) {
4106
                        $addlock_disc = Display::return_icon(
4107
                            'unlock.png',
4108
                            get_lang('Now all members can add comments to this discussion'),
4109
                            '',
4110
                            ICON_SIZE_SMALL
4111
                        );
4112
                        $lock_unlock_disc = 'unlockdisc';
4113
                    } else {
4114
                        $addlock_disc = Display::return_icon(
4115
                            'lock.png',
4116
                            get_lang('Now only trainers can add comments to this discussion'),
4117
                            '',
4118
                            ICON_SIZE_SMALL
4119
                        );
4120
                        $lock_unlock_disc = 'lockdisc';
4121
                    }
4122
                }
4123
                echo '<span style="float:right">';
4124
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_disc.'&title='.api_htmlentities(
4125
                        urlencode($page)
4126
                    ).'">'.$addlock_disc.'</a>';
4127
                echo '</span>';
4128
4129
                // discussion action: visibility.  Show discussion to students if isn't hidden. Show page to all teachers if is hidden.
4130
                $visibility_disc = null;
4131
                $hide_show_disc = null;
4132
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4133
                    if (1 == self::check_visibility_discuss()) {
4134
                        /// TODO: 	Fix Mode assignments: If is hidden, show discussion to student only if student is the author
4135
                        $visibility_disc = Display::return_icon(
4136
                            'visible.png',
4137
                            get_lang('Now discussion is visible by all users'),
4138
                            '',
4139
                            ICON_SIZE_SMALL
4140
                        );
4141
                        $hide_show_disc = 'hidedisc';
4142
                    } else {
4143
                        $visibility_disc = Display::return_icon(
4144
                            'invisible.png',
4145
                            get_lang('Now discussion is visible by trainers only'),
4146
                            '',
4147
                            ICON_SIZE_SMALL
4148
                        );
4149
                        $hide_show_disc = 'showdisc';
4150
                    }
4151
                }
4152
                echo '<span style="float:right">';
4153
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$hide_show_disc.'&title='.api_htmlentities(
4154
                        urlencode($page)
4155
                    ).'">'.$visibility_disc.'</a>';
4156
                echo '</span>';
4157
4158
                // discussion action: check add rating lock. Show/Hide list to rating for all student
4159
                $lock_unlock_rating_disc = null;
4160
                $ratinglock_disc = null;
4161
                if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4162
                    if (1 == self::check_ratinglock_discuss()) {
4163
                        $ratinglock_disc = Display::return_icon(
4164
                            'star.png',
4165
                            get_lang('Now all members can rate this page'),
4166
                            '',
4167
                            ICON_SIZE_SMALL
4168
                        );
4169
                        $lock_unlock_rating_disc = 'unlockrating';
4170
                    } else {
4171
                        $ratinglock_disc = Display::return_icon(
4172
                            'star_na.png',
4173
                            get_lang('Now only trainers can rate this page'),
4174
                            '',
4175
                            ICON_SIZE_SMALL
4176
                        );
4177
                        $lock_unlock_rating_disc = 'lockrating';
4178
                    }
4179
                }
4180
4181
                echo '<span style="float:right">';
4182
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_rating_disc.'&title='.api_htmlentities(
4183
                        urlencode($page)
4184
                    ).'">'.$ratinglock_disc.'</a>';
4185
                echo '</span>';
4186
4187
                // discussion action: email notification
4188
                if (1 == self::check_notify_discuss($page)) {
4189
                    $notify_disc = Display::return_icon(
4190
                        'messagebox_info.png',
4191
                        get_lang('Notify by e-mail of new comments about this page is allowed'),
4192
                        '',
4193
                        ICON_SIZE_SMALL
4194
                    );
4195
                    $lock_unlock_notify_disc = 'unlocknotifydisc';
4196
                } else {
4197
                    $notify_disc = Display::return_icon(
4198
                        'mail.png',
4199
                        get_lang('CancelNotify by e-mail of new comments about this page is allowed'),
4200
                        '',
4201
                        ICON_SIZE_SMALL
4202
                    );
4203
                    $lock_unlock_notify_disc = 'locknotifydisc';
4204
                }
4205
                echo '<span style="float:right">';
4206
                echo '<a href="index.php?'.api_get_cidreq().'&action=discuss&actionpage='.$lock_unlock_notify_disc.'&title='.api_htmlentities(
4207
                        urlencode($page)
4208
                    ).'">'.$notify_disc.'</a>';
4209
                echo '</span>';
4210
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities(
4211
                        $row['title']
4212
                    );
4213
                if (false !== $lastuserinfo) {
4214
                    echo ' ('.get_lang('The latest version was edited by').' '.
4215
                        UserManager::getUserProfileLink($lastuserinfo).' '.$lastversiondate.$countWPost.')'.$avg_WPost_score.' '; //TODO: read average score
4216
                }
4217
4218
                echo '</div>';
4219
                if (1 == $row['addlock_disc'] || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4220
                    //show comments but students can't add theirs
4221
                    ?>
4222
                    <div class="panel panel-default">
4223
                        <div class="panel-body">
4224
                            <form name="form1" method="post" action=""
4225
                                  class="form-horizontal">
4226
                                <div class="form-group">
4227
                                    <label
4228
                                        class="col-sm-2 control-label">
4229
                                        <?php echo get_lang('Comments'); ?>:</label>
4230
                                    <div class="col-sm-10">
4231
                                        <?php echo '<input type="hidden" name="wpost_id" value="'.md5(uniqid(rand(), true)).'">'; //prevent double post?>
4232
                                        <textarea class="form-control"
4233
                                                  name="comment" cols="80"
4234
                                                  rows="5"
4235
                                                  id="comment">
4236
                                        </textarea>
4237
                                    </div>
4238
                                </div>
4239
                                <div class="form-group">
4240
                                    <?php
4241
                                    //check if rating is allowed
4242
                                    if (1 == $row['ratinglock_disc'] || api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4243
                                        ?>
4244
                                        <label
4245
                                            class="col-sm-2 control-label"><?php echo get_lang('Rating'); ?>:</label>
4246
                                        <div class="col-sm-10">
4247
                                            <select name="rating" id="rating" class="selectpicker">
4248
                                                <option value="-" selected>-</option>
4249
                                                <option value="0">0</option>
4250
                                                <option value="1">1</option>
4251
                                                <option value="2">2</option>
4252
                                                <option value="3">3</option>
4253
                                                <option value="4">4</option>
4254
                                                <option value="5">5</option>
4255
                                                <option value="6">6</option>
4256
                                                <option value="7">7</option>
4257
                                                <option value="8">8</option>
4258
                                                <option value="9">9</option>
4259
                                                <option value="10">10</option>
4260
                                            </select>
4261
                                        </div>
4262
                                        <?php
4263
                                    } else {
4264
                                        echo '<input type=hidden name="rating" value="-">';
4265
                                        // must pass a default value to avoid rate automatically
4266
                                    } ?>
4267
4268
                                </div>
4269
                                <div class="form-group">
4270
                                    <div class="col-sm-offset-2 col-sm-10">
4271
                                        <?php echo '<button class="btn btn-default" type="submit" name="Submit"> '.
4272
                                            get_lang('Send message').'</button>'; ?>
4273
                                    </div>
4274
                                </div>
4275
                        </div>
4276
                    </div>
4277
                    </form>
4278
                    <?php
4279
                }
4280
                // end discuss lock
4281
4282
                echo '<hr noshade size="1">';
4283
                $user_table = Database::get_main_table(TABLE_MAIN_USER);
4284
4285
                $sql = "SELECT *
4286
                        FROM $tbl_wiki_discuss reviews, $user_table user
4287
                        WHERE
4288
                            reviews.c_id = $course_id AND
4289
                            reviews.publication_id='".$id."' AND
4290
                            user.id ='".$firstuserid."'
4291
                        ORDER BY reviews.id DESC";
4292
                $result = Database::query($sql);
4293
4294
                $countWPost = Database::num_rows($result);
4295
                echo get_lang('Comments on this page').": ".$countWPost; //comment's numbers
4296
4297
                $sql = "SELECT SUM(p_score) as sumWPost
4298
                        FROM $tbl_wiki_discuss
4299
                        WHERE c_id = $course_id AND publication_id = '".$id."' AND NOT p_score='-'
4300
                        ORDER BY id DESC";
4301
                $result2 = Database::query($sql);
4302
                $row2 = Database::fetch_array($result2);
4303
4304
                $sql = "SELECT * FROM $tbl_wiki_discuss
4305
                        WHERE c_id = $course_id AND publication_id='".$id."' AND NOT p_score='-'";
4306
                $result3 = Database::query($sql);
4307
                $countWPost_score = Database::num_rows($result3);
4308
4309
                echo ' - '.get_lang('Comments on this pageScore').': '.$countWPost_score;
4310
4311
                if (0 != $countWPost_score) {
4312
                    $avg_WPost_score = round($row2['sumWPost'] / $countWPost_score, 2).' / 10';
4313
                } else {
4314
                    $avg_WPost_score = $countWPost_score;
4315
                }
4316
4317
                echo ' - '.get_lang('The average rating for the page is').': '.$avg_WPost_score; // average rating
4318
4319
                $sql = 'UPDATE '.$tbl_wiki.' SET
4320
                        score = "'.Database::escape_string($avg_WPost_score).'"
4321
                        WHERE
4322
                            c_id = '.$course_id.' AND
4323
                            reflink="'.Database::escape_string($page).'" AND
4324
                            '.$groupfilter.$condition_session;
4325
                // check if work ok. TODO:
4326
                Database::query($sql);
4327
4328
                echo '<hr noshade size="1">';
4329
                while ($row = Database::fetch_array($result)) {
4330
                    $userinfo = api_get_user_info($row['userc_id']);
4331
                    if ("5" == ($userinfo['status'])) {
4332
                        $author_status = get_lang('Learner');
4333
                    } else {
4334
                        $author_status = get_lang('Trainer');
4335
                    }
4336
4337
                    $name = $userinfo['complete_name'];
4338
                    $author_photo = '<img src="'.$userinfo['avatar'].'" alt="'.api_htmlentities($name).'"  width="40" height="50" align="top"  title="'.api_htmlentities($name).'"  />';
4339
4340
                    // stars
4341
                    $p_score = $row['p_score'];
4342
                    switch ($p_score) {
4343
                        case  0:
4344
                            $imagerating = Display::return_icon(
4345
                                'rating/stars_0.gif'
4346
                            );
4347
                            break;
4348
                        case  1:
4349
                            $imagerating = Display::return_icon(
4350
                                'rating/stars_5.gif'
4351
                            );
4352
                            break;
4353
                        case  2:
4354
                            $imagerating = Display::return_icon(
4355
                                'rating/stars_10.gif'
4356
                            );
4357
                            break;
4358
                        case  3:
4359
                            $imagerating = Display::return_icon(
4360
                                'rating/stars_15.gif'
4361
                            );
4362
                            break;
4363
                        case  4:
4364
                            $imagerating = Display::return_icon(
4365
                                'rating/stars_20.gif'
4366
                            );
4367
                            break;
4368
                        case  5:
4369
                            $imagerating = Display::return_icon(
4370
                                'rating/stars_25.gif'
4371
                            );
4372
                            break;
4373
                        case  6:
4374
                            $imagerating = Display::return_icon(
4375
                                'rating/stars_30.gif'
4376
                            );
4377
                            break;
4378
                        case  7:
4379
                            $imagerating = Display::return_icon(
4380
                                'rating/stars_35.gif'
4381
                            );
4382
                            break;
4383
                        case  8:
4384
                            $imagerating = Display::return_icon(
4385
                                'rating/stars_40.gif'
4386
                            );
4387
                            break;
4388
                        case  9:
4389
                            $imagerating = Display::return_icon(
4390
                                'rating/stars_45.gif'
4391
                            );
4392
                            break;
4393
                        case  10:
4394
                            $imagerating = Display::return_icon(
4395
                                'rating/stars_50.gif'
4396
                            );
4397
                            break;
4398
                    }
4399
                    echo '<p><table>';
4400
                    echo '<tr>';
4401
                    echo '<td rowspan="2">'.$author_photo.'</td>';
4402
                    $userProfile = '';
4403
                    if (false !== $userinfo) {
4404
                        $userProfile = UserManager::getUserProfileLink(
4405
                            $userinfo
4406
                        );
4407
                    }
4408
                    echo '<td style=" color:#999999">'.$userProfile.' ('.$author_status.') '.
4409
                        api_get_local_time(
4410
                            $row['dtime']
4411
                        ).
4412
                        ' - '.get_lang(
4413
                            'Rating'
4414
                        ).': '.$row['p_score'].' '.$imagerating.' </td>';
4415
                    echo '</tr>';
4416
                    echo '<tr>';
4417
                    echo '<td>'.api_htmlentities($row['comment']).'</td>';
4418
                    echo '</tr>';
4419
                    echo "</table>";
4420
                }
4421
            } else {
4422
                Display::addFlash(
4423
                    Display::return_message(
4424
                        get_lang('LockByTrainer'),
4425
                        'warning',
4426
                        false
4427
                    )
4428
                );
4429
            }
4430
        } else {
4431
            Display::addFlash(
4432
                Display::return_message(
4433
                    get_lang('Discuss not available'),
4434
                    'normal',
4435
                    false
4436
                )
4437
            );
4438
        }
4439
    }
4440
4441
    /**
4442
     * Show all pages.
4443
     */
4444
    public function allPages($action)
4445
    {
4446
        $tbl_wiki = $this->tbl_wiki;
4447
        $course_id = $this->course_id;
4448
        $session_id = $this->session_id;
4449
        $groupfilter = $this->groupfilter;
4450
        $_course = $this->courseInfo;
4451
4452
        echo '<div class="actions">'.get_lang('All pages');
4453
4454
        // menu delete all wiki
4455
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4456
            echo ' <a href="index.php?action=deletewiki&'.api_get_cidreq().'">'.
4457
                Display::return_icon(
4458
                    'delete.png',
4459
                    get_lang('DeleteGroup wiki'),
4460
                    '',
4461
                    ICON_SIZE_MEDIUM
4462
                ).'</a>';
4463
        }
4464
        echo '</div>';
4465
4466
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4467
            // only by professors if page is hidden
4468
            // warning don't use group by reflink because does not return the last version
4469
            $sql = 'SELECT  *
4470
                    FROM  '.$tbl_wiki.' s1
4471
        		    WHERE s1.c_id = '.$course_id.' AND id=(
4472
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
4473
                    WHERE
4474
                        s2.c_id = '.$course_id.' AND
4475
                        s1.reflink = s2.reflink AND
4476
                        '.$groupfilter.' AND
4477
                        session_id='.$session_id.')';
4478
        } else {
4479
            // warning don't use group by reflink because does not return the last version
4480
            $sql = 'SELECT  *  FROM '.$tbl_wiki.' s1
4481
				    WHERE visibility=1 AND s1.c_id = '.$course_id.' AND id=(
4482
                        SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
4483
                        WHERE
4484
                            s2.c_id = '.$course_id.' AND
4485
                            s1.reflink = s2.reflink AND
4486
                             '.$groupfilter.' AND
4487
                             session_id='.$session_id.')';
4488
        }
4489
4490
        $allpages = Database::query($sql);
4491
4492
        //show table
4493
        if (Database::num_rows($allpages) > 0) {
4494
            while ($obj = Database::fetch_object($allpages)) {
4495
                //get author
4496
                $userinfo = api_get_user_info($obj->user_id);
4497
                $username = api_htmlentities(
4498
                    sprintf(get_lang('Login: %s'), $userinfo['username']),
4499
                    ENT_QUOTES
4500
                );
4501
4502
                //get type assignment icon
4503
                if (1 == $obj->assignment) {
4504
                    $ShowAssignment = Display::return_icon(
4505
                        'wiki_assignment.png',
4506
                        get_lang('Assignment proposed by the trainer'),
4507
                        '',
4508
                        ICON_SIZE_SMALL
4509
                    );
4510
                } elseif (2 == $obj->assignment) {
4511
                    $ShowAssignment = Display::return_icon(
4512
                        'wiki_work.png',
4513
                        get_lang('Learner paper'),
4514
                        '',
4515
                        ICON_SIZE_SMALL
4516
                    );
4517
                } elseif (0 == $obj->assignment) {
4518
                    $ShowAssignment = Display::return_icon(
4519
                        'px_transparent.gif'
4520
                    );
4521
                }
4522
4523
                //get icon task
4524
                if (!empty($obj->task)) {
4525
                    $icon_task = Display::return_icon(
4526
                        'wiki_task.png',
4527
                        get_lang('Standard Task'),
4528
                        '',
4529
                        ICON_SIZE_SMALL
4530
                    );
4531
                } else {
4532
                    $icon_task = Display::return_icon('px_transparent.gif');
4533
                }
4534
4535
                $row = [];
4536
                $row[] = $ShowAssignment.$icon_task;
4537
                $row[] = '<a href="'.api_get_self(
4538
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4539
                        urlencode($obj->reflink)
4540
                    ).'&session_id='.api_htmlentities(
4541
                        $_GET['session_id']
4542
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">
4543
                '.api_htmlentities($obj->title).'</a>';
4544
                if (false !== $userinfo) {
4545
                    $row[] = UserManager::getUserProfileLink($userinfo);
4546
                } else {
4547
                    $row[] = get_lang('Anonymous').' ('.api_htmlentities(
4548
                            $obj->user_ip
4549
                        ).')';
4550
                }
4551
                $row[] = api_get_local_time(
4552
                    $obj->dtime
4553
                );
4554
                $showdelete = '';
4555
                if (api_is_allowed_to_edit(
4556
                        false,
4557
                        true
4558
                    ) || api_is_platform_admin()) {
4559
                    $showdelete = ' <a href="'.api_get_self(
4560
                        ).'?cidReq='.$_course['code'].'&action=delete&title='.api_htmlentities(
4561
                            urlencode($obj->reflink)
4562
                        ).'&session_id='.api_htmlentities(
4563
                            $_GET['session_id']
4564
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4565
                        Display::return_icon(
4566
                            'delete.png',
4567
                            get_lang('Delete'),
4568
                            '',
4569
                            ICON_SIZE_SMALL
4570
                        );
4571
                }
4572
                if (api_is_allowed_to_session_edit(false, true)) {
4573
                    $row[] = '<a href="'.api_get_self(
4574
                        ).'?cidReq='.$_course['code'].'&action=edit&title='.api_htmlentities(
4575
                            urlencode($obj->reflink)
4576
                        ).'&session_id='.api_htmlentities(
4577
                            $_GET['session_id']
4578
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4579
                        Display::return_icon(
4580
                            'edit.png',
4581
                            get_lang('Edit'),
4582
                            '',
4583
                            ICON_SIZE_SMALL
4584
                        ).'</a> <a href="'.api_get_self(
4585
                        ).'?cidReq='.$_course['code'].'&action=discuss&title='.api_htmlentities(
4586
                            urlencode($obj->reflink)
4587
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4588
                        Display::return_icon(
4589
                            'discuss.png',
4590
                            get_lang('Discuss'),
4591
                            '',
4592
                            ICON_SIZE_SMALL
4593
                        ).'</a> <a href="'.api_get_self(
4594
                        ).'?cidReq='.$_course['code'].'&action=history&title='.api_htmlentities(
4595
                            urlencode($obj->reflink)
4596
                        ).'&session_id='.api_htmlentities(
4597
                            $_GET['session_id']
4598
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4599
                        Display::return_icon(
4600
                            'history.png',
4601
                            get_lang('History'),
4602
                            '',
4603
                            ICON_SIZE_SMALL
4604
                        ).'</a>
4605
                        <a href="'.api_get_self(
4606
                        ).'?cidReq='.$_course['code'].'&action=links&title='.api_htmlentities(
4607
                            urlencode($obj->reflink)
4608
                        ).'&session_id='.api_htmlentities(
4609
                            $_GET['session_id']
4610
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4611
                        Display::return_icon(
4612
                            'what_link_here.png',
4613
                            get_lang('What links here'),
4614
                            '',
4615
                            ICON_SIZE_SMALL
4616
                        ).'</a>'.$showdelete;
4617
                }
4618
                $rows[] = $row;
4619
            }
4620
4621
            $table = new SortableTableFromArrayConfig(
4622
                $rows,
4623
                1,
4624
                10,
4625
                'AllPages_table',
4626
                '',
4627
                '',
4628
                'ASC'
4629
            );
4630
            $table->set_additional_parameters(
4631
                [
4632
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
4633
                    'action' => Security::remove_XSS($action),
4634
                    'group_id' => Security::remove_XSS($_GET['group_id']),
4635
                ]
4636
            );
4637
            $table->set_header(
4638
                0,
4639
                get_lang('Type'),
4640
                true,
4641
                ['style' => 'width:30px;']
4642
            );
4643
            $table->set_header(1, get_lang('Title'), true);
4644
            $table->set_header(
4645
                2,
4646
                get_lang('Author').' ('.get_lang('Latest version').')',
4647
                true
4648
            );
4649
            $table->set_header(
4650
                3,
4651
                get_lang('Date').' ('.get_lang('Latest version').')',
4652
                true
4653
            );
4654
            if (api_is_allowed_to_session_edit(false, true)) {
4655
                $table->set_header(
4656
                    4,
4657
                    get_lang('Detail'),
4658
                    true,
4659
                    ['style' => 'width:130px;']
4660
                );
4661
            }
4662
            $table->display();
4663
        }
4664
    }
4665
4666
    /**
4667
     * Get recent changes.
4668
     *
4669
     * @param string $page
4670
     * @param string $action
4671
     */
4672
    public function recentChanges($page, $action)
4673
    {
4674
        $tbl_wiki = $this->tbl_wiki;
4675
        $course_id = $this->course_id;
4676
        $condition_session = $this->condition_session;
4677
        $groupfilter = $this->groupfilter;
4678
        $tbl_wiki_conf = $this->tbl_wiki_conf;
4679
4680
        if (api_is_allowed_to_session_edit(false, true)) {
4681
            if (1 == self::check_notify_all()) {
4682
                $notify_all = Display::return_icon(
4683
                        'messagebox_info.png',
4684
                        get_lang('Notify me by e-mail when somebody replies'),
4685
                        '',
4686
                        ICON_SIZE_SMALL
4687
                    ).' '.get_lang('NotNotify me of changes');
4688
                $lock_unlock_notify_all = 'unlocknotifyall';
4689
            } else {
4690
                $notify_all = Display::return_icon(
4691
                        'mail.png',
4692
                        get_lang('CancelNotify me by e-mail when somebody replies'),
4693
                        '',
4694
                        ICON_SIZE_SMALL
4695
                    ).' '.get_lang('Notify me of changes');
4696
                $lock_unlock_notify_all = 'locknotifyall';
4697
            }
4698
        }
4699
4700
        echo '<div class="actions"><span style="float: right;">';
4701
        echo '<a href="index.php?action=recentchanges&actionpage='.$lock_unlock_notify_all.'&'.api_get_cidreq().'&title='.api_htmlentities(
4702
                urlencode($page)
4703
            ).'">'.$notify_all.'</a>';
4704
        echo '</span>'.get_lang('Latest changes').'</div>';
4705
4706
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4707
            //only by professors if page is hidden
4708
            $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
4709
        		WHERE 	'.$tbl_wiki_conf.'.c_id= '.$course_id.' AND
4710
        				'.$tbl_wiki.'.c_id= '.$course_id.' AND
4711
        				'.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
4712
        				'.$tbl_wiki.'.'.$groupfilter.$condition_session.'
4713
        		ORDER BY dtime DESC'; // new version
4714
        } else {
4715
            $sql = 'SELECT *
4716
                FROM '.$tbl_wiki.'
4717
                WHERE
4718
                    c_id = '.$course_id.' AND
4719
                    '.$groupfilter.$condition_session.' AND
4720
                    visibility=1
4721
                ORDER BY dtime DESC';
4722
            // old version TODO: Replace by the bottom line
4723
        }
4724
4725
        $allpages = Database::query($sql);
4726
4727
        //show table
4728
        if (Database::num_rows($allpages) > 0) {
4729
            $rows = [];
4730
            while ($obj = Database::fetch_object($allpages)) {
4731
                //get author
4732
                $userinfo = api_get_user_info($obj->user_id);
4733
4734
                //get type assignment icon
4735
                if (1 == $obj->assignment) {
4736
                    $ShowAssignment = Display::return_icon(
4737
                        'wiki_assignment.png',
4738
                        get_lang('Assignment proposed by the trainer'),
4739
                        '',
4740
                        ICON_SIZE_SMALL
4741
                    );
4742
                } elseif (2 == $obj->assignment) {
4743
                    $ShowAssignment = Display::return_icon(
4744
                        'wiki_work.png',
4745
                        get_lang('Learner paper'),
4746
                        '',
4747
                        ICON_SIZE_SMALL
4748
                    );
4749
                } elseif (0 == $obj->assignment) {
4750
                    $ShowAssignment = Display::return_icon(
4751
                        'px_transparent.gif'
4752
                    );
4753
                }
4754
4755
                // Get icon task
4756
                if (!empty($obj->task)) {
4757
                    $icon_task = Display::return_icon(
4758
                        'wiki_task.png',
4759
                        get_lang('Standard Task'),
4760
                        '',
4761
                        ICON_SIZE_SMALL
4762
                    );
4763
                } else {
4764
                    $icon_task = Display::return_icon('px_transparent.gif');
4765
                }
4766
4767
                $row = [];
4768
                $row[] = api_get_local_time(
4769
                    $obj->dtime
4770
                );
4771
                $row[] = $ShowAssignment.$icon_task;
4772
                $row[] = '<a href="'.api_get_self().'?'.api_get_cidreq(
4773
                    ).'&action=showpage&title='.api_htmlentities(
4774
                        urlencode($obj->reflink)
4775
                    ).'&view='.$obj->id.'&session_id='.api_get_session_id(
4776
                    ).'&group_id='.api_get_group_id().'">'.
4777
                    api_htmlentities($obj->title).'</a>';
4778
                $row[] = $obj->version > 1 ? get_lang('edited by') : get_lang(
4779
                    'added by'
4780
                );
4781
                if (false !== $userinfo) {
4782
                    $row[] = UserManager::getUserProfileLink($userinfo);
4783
                } else {
4784
                    $row[] = get_lang('Anonymous').' ('.api_htmlentities(
4785
                            $obj->user_ip
4786
                        ).')';
4787
                }
4788
                $rows[] = $row;
4789
            }
4790
4791
            $table = new SortableTableFromArrayConfig(
4792
                $rows,
4793
                0,
4794
                10,
4795
                'RecentPages_table',
4796
                '',
4797
                '',
4798
                'DESC'
4799
            );
4800
            $table->set_additional_parameters(
4801
                [
4802
                    'cidReq' => api_get_course_id(),
4803
                    'action' => Security::remove_XSS($action),
4804
                    'session_id' => api_get_session_id(),
4805
                    'group_id' => api_get_group_id(),
4806
                ]
4807
            );
4808
            $table->set_header(
4809
                0,
4810
                get_lang('Date'),
4811
                true,
4812
                ['style' => 'width:200px;']
4813
            );
4814
            $table->set_header(
4815
                1,
4816
                get_lang('Type'),
4817
                true,
4818
                ['style' => 'width:30px;']
4819
            );
4820
            $table->set_header(2, get_lang('Title'), true);
4821
            $table->set_header(
4822
                3,
4823
                get_lang('Detail'),
4824
                true,
4825
                ['style' => 'width:80px;']
4826
            );
4827
            $table->set_header(4, get_lang('Author'), true);
4828
            $table->display();
4829
        }
4830
    }
4831
4832
    /**
4833
     * What links here. Show pages that have linked this page.
4834
     *
4835
     * @param string $page
4836
     */
4837
    public function getLinks($page)
4838
    {
4839
        $tbl_wiki = $this->tbl_wiki;
4840
        $course_id = $this->course_id;
4841
        $condition_session = $this->condition_session;
4842
        $groupfilter = $this->groupfilter;
4843
        $_course = $this->courseInfo;
4844
        $action = $this->action;
4845
4846
        if (!$_GET['title']) {
4847
            Display::addFlash(
4848
                Display::return_message(
4849
                    get_lang("You must select a page first"),
4850
                    'error',
4851
                    false
4852
                )
4853
            );
4854
        } else {
4855
            $sql = 'SELECT * FROM '.$tbl_wiki.'
4856
                    WHERE
4857
                        c_id = '.$course_id.' AND
4858
                        reflink="'.Database::escape_string($page).'" AND
4859
                        '.$groupfilter.$condition_session;
4860
            $result = Database::query($sql);
4861
            $row = Database::fetch_array($result);
4862
4863
            //get type assignment icon
4864
            $ShowAssignment = '';
4865
            if (1 == $row['assignment']) {
4866
                $ShowAssignment = Display::return_icon(
4867
                    'wiki_assignment.png',
4868
                    get_lang('Assignment proposed by the trainer'),
4869
                    '',
4870
                    ICON_SIZE_SMALL
4871
                );
4872
            } elseif (2 == $row['assignment']) {
4873
                $ShowAssignment = Display::return_icon(
4874
                    'wiki_work.png',
4875
                    get_lang('Learner paper'),
4876
                    '',
4877
                    ICON_SIZE_SMALL
4878
                );
4879
            } elseif (0 == $row['assignment']) {
4880
                $ShowAssignment = Display::return_icon('px_transparent.gif');
4881
            }
4882
4883
            //fix Title to reflink (link Main Page)
4884
            if ($page == get_lang('Home')) {
4885
                $page = 'index';
4886
            }
4887
4888
            echo '<div id="wikititle">';
4889
            echo get_lang(
4890
                    'What links hereFrom'
4891
                ).': '.$ShowAssignment.' <a href="'.api_get_self(
4892
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4893
                    urlencode($page)
4894
                ).'&session_id='.api_htmlentities(
4895
                    $_GET['session_id']
4896
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4897
                api_htmlentities($row['title']).'</a>';
4898
            echo '</div>';
4899
4900
            //fix index to title Main page into linksto
4901
4902
            if ('index' == $page) {
4903
                $page = str_replace(' ', '_', get_lang('Home'));
4904
            }
4905
4906
            if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
4907
                // only by professors if page is hidden
4908
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4909
                        WHERE s1.c_id = $course_id AND linksto LIKE '%".Database::escape_string(
4910
                        $page
4911
                    )."%' AND id=(
4912
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4913
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4914
            } else {
4915
                //add blank space after like '%" " %' to identify each word
4916
                $sql = "SELECT * FROM ".$tbl_wiki." s1
4917
                        WHERE s1.c_id = $course_id AND visibility=1 AND linksto LIKE '%".Database::escape_string(
4918
                        $page
4919
                    )."%' AND id=(
4920
                        SELECT MAX(s2.id) FROM ".$tbl_wiki." s2
4921
                        WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";
4922
            }
4923
4924
            $allpages = Database::query($sql);
4925
4926
            //show table
4927
            if (Database::num_rows($allpages) > 0) {
4928
                $rows = [];
4929
                while ($obj = Database::fetch_object($allpages)) {
4930
                    //get author
4931
                    $userinfo = api_get_user_info($obj->user_id);
4932
4933
                    //get time
4934
                    $year = substr($obj->dtime, 0, 4);
4935
                    $month = substr($obj->dtime, 5, 2);
4936
                    $day = substr($obj->dtime, 8, 2);
4937
                    $hours = substr($obj->dtime, 11, 2);
4938
                    $minutes = substr($obj->dtime, 14, 2);
4939
                    $seconds = substr($obj->dtime, 17, 2);
4940
4941
                    //get type assignment icon
4942
                    if (1 == $obj->assignment) {
4943
                        $ShowAssignment = Display::return_icon(
4944
                            'wiki_assignment.png',
4945
                            get_lang('Assignment proposed by the trainer'),
4946
                            '',
4947
                            ICON_SIZE_SMALL
4948
                        );
4949
                    } elseif (2 == $obj->assignment) {
4950
                        $ShowAssignment = Display::return_icon(
4951
                            'wiki_work.png',
4952
                            get_lang('Learner paper'),
4953
                            '',
4954
                            ICON_SIZE_SMALL
4955
                        );
4956
                    } elseif (0 == $obj->assignment) {
4957
                        $ShowAssignment = Display::return_icon(
4958
                            'px_transparent.gif'
4959
                        );
4960
                    }
4961
4962
                    $row = [];
4963
                    $row[] = $ShowAssignment;
4964
                    $row[] = '<a href="'.api_get_self(
4965
                        ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
4966
                            urlencode($obj->reflink)
4967
                        ).'&session_id='.api_htmlentities(
4968
                            $_GET['session_id']
4969
                        ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
4970
                        api_htmlentities($obj->title).'</a>';
4971
                    if (false !== $userinfo) {
4972
                        $row[] = UserManager::getUserProfileLink($userinfo);
4973
                    } else {
4974
                        $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
4975
                    }
4976
                    $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
4977
                    $rows[] = $row;
4978
                }
4979
4980
                $table = new SortableTableFromArrayConfig(
4981
                    $rows,
4982
                    1,
4983
                    10,
4984
                    'AllPages_table',
4985
                    '',
4986
                    '',
4987
                    'ASC'
4988
                );
4989
                $table->set_additional_parameters(
4990
                    [
4991
                        'cidReq' => Security::remove_XSS($_GET['cidReq']),
4992
                        'action' => Security::remove_XSS($action),
4993
                        'group_id' => intval($_GET['group_id']),
4994
                    ]
4995
                );
4996
                $table->set_header(
4997
                    0,
4998
                    get_lang('Type'),
4999
                    true,
5000
                    ['style' => 'width:30px;']
5001
                );
5002
                $table->set_header(1, get_lang('Title'), true);
5003
                $table->set_header(2, get_lang('Author'), true);
5004
                $table->set_header(3, get_lang('Date'), true);
5005
                $table->display();
5006
            }
5007
        }
5008
    }
5009
5010
    /**
5011
     * @param string $action
5012
     */
5013
    public function getSearchPages($action)
5014
    {
5015
        echo '<div class="actions">'.get_lang('Search').'</div>';
5016
        if (isset($_GET['mode_table'])) {
5017
            if (!isset($_GET['SearchPages_table_page_nr'])) {
5018
                $_GET['search_term'] = isset($_POST['search_term']) ? $_POST['search_term'] : '';
5019
                $_GET['search_content'] = isset($_POST['search_content']) ? $_POST['search_content'] : '';
5020
                $_GET['all_vers'] = isset($_POST['all_vers']) ? $_POST['all_vers'] : '';
5021
            }
5022
            self::display_wiki_search_results(
5023
                $_GET['search_term'],
5024
                $_GET['search_content'],
5025
                $_GET['all_vers']
5026
            );
5027
        } else {
5028
            // initiate the object
5029
            $form = new FormValidator(
5030
                'wiki_search',
5031
                'post',
5032
                api_get_self().'?cidReq='.api_get_course_id(
5033
                ).'&action='.api_htmlentities(
5034
                    $action
5035
                ).'&session_id='.api_get_session_id(
5036
                ).'&group_id='.api_get_group_id().'&mode_table=yes1'
5037
            );
5038
5039
            // Setting the form elements
5040
5041
            $form->addText(
5042
                'search_term',
5043
                get_lang('Search term'),
5044
                true,
5045
                ['autofocus' => 'autofocus']
5046
            );
5047
            $form->addElement(
5048
                'checkbox',
5049
                'search_content',
5050
                null,
5051
                get_lang('Search also in content')
5052
            );
5053
            $form->addElement(
5054
                'checkbox',
5055
                'all_vers',
5056
                null,
5057
                get_lang('includeAllVersions')
5058
            );
5059
            $form->addButtonSearch(get_lang('Search'), 'SubmitGroup wikiSearch');
5060
5061
            // setting the rules
5062
            $form->addRule(
5063
                'search_term',
5064
                get_lang('Too short'),
5065
                'minlength',
5066
                3
5067
            ); //TODO: before fixing the pagination rules worked, not now
5068
5069
            if ($form->validate()) {
5070
                $form->display();
5071
                $values = $form->exportValues();
5072
                self::display_wiki_search_results(
5073
                    $values['search_term'],
5074
                    $values['search_content'],
5075
                    $values['all_vers']
5076
                );
5077
            } else {
5078
                $form->display();
5079
            }
5080
        }
5081
    }
5082
5083
    /**
5084
     * @param int    $userId
5085
     * @param string $action
5086
     */
5087
    public function getUserContributions($userId, $action)
5088
    {
5089
        $_course = $this->courseInfo;
5090
        $tbl_wiki = $this->tbl_wiki;
5091
        $course_id = $this->course_id;
5092
        $condition_session = $this->condition_session;
5093
        $groupfilter = $this->groupfilter;
5094
        $userId = intval($userId);
5095
        $userinfo = api_get_user_info($userId);
5096
        if (false !== $userinfo) {
5097
            echo '<div class="actions">'.
5098
                get_lang('Usercontributions').': '.UserManager::getUserProfileLink($userinfo).
5099
                '<a href="'.api_get_self().'?cidReq='.$_course['code'].'&action=usercontrib&user_id='.$userId.
5100
                '&session_id='.$this->session_id.'&group_id='.$this->group_id.'">'.
5101
                '</a></div>';
5102
        }
5103
5104
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
5105
            //only by professors if page is hidden
5106
            $sql = 'SELECT * FROM '.$tbl_wiki.'
5107
                    WHERE
5108
                        c_id = '.$course_id.' AND
5109
                        '.$groupfilter.$condition_session.' AND
5110
                        user_id="'.$userId.'"';
5111
        } else {
5112
            $sql = 'SELECT * FROM '.$tbl_wiki.'
5113
                    WHERE
5114
                        c_id = '.$course_id.' AND
5115
                        '.$groupfilter.$condition_session.' AND
5116
                        user_id="'.$userId.'" AND
5117
                        visibility=1';
5118
        }
5119
5120
        $allpages = Database::query($sql);
5121
5122
        //show table
5123
        if (Database::num_rows($allpages) > 0) {
5124
            $rows = [];
5125
            while ($obj = Database::fetch_object($allpages)) {
5126
                //get type assignment icon
5127
                $ShowAssignment = '';
5128
                if (1 == $obj->assignment) {
5129
                    $ShowAssignment = Display::return_icon(
5130
                        'wiki_assignment.png',
5131
                        get_lang('This page is an assignment proposed by a trainer'),
5132
                        '',
5133
                        ICON_SIZE_SMALL
5134
                    );
5135
                } elseif (2 == $obj->assignment) {
5136
                    $ShowAssignment = Display::return_icon(
5137
                        'wiki_work.png',
5138
                        get_lang('Learner paper'),
5139
                        '',
5140
                        ICON_SIZE_SMALL
5141
                    );
5142
                } elseif (0 == $obj->assignment) {
5143
                    $ShowAssignment = Display::return_icon(
5144
                        'px_transparent.gif'
5145
                    );
5146
                }
5147
5148
                $row = [];
5149
                $row[] = api_get_local_time($obj->dtime);
5150
                $row[] = $ShowAssignment;
5151
                $row[] = '<a href="'.api_get_self(
5152
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5153
                        urlencode($obj->reflink)
5154
                    ).'&view='.$obj->id.'&session_id='.api_get_session_id(
5155
                    ).'&group_id='.api_get_group_id().'">'.
5156
                    api_htmlentities($obj->title).'</a>';
5157
                $row[] = Security::remove_XSS($obj->version);
5158
                $row[] = Security::remove_XSS($obj->comment);
5159
                $row[] = Security::remove_XSS($obj->progress).' %';
5160
                $row[] = Security::remove_XSS($obj->score);
5161
                $rows[] = $row;
5162
            }
5163
5164
            $table = new SortableTableFromArrayConfig(
5165
                $rows,
5166
                2,
5167
                10,
5168
                'UsersContributions_table',
5169
                '',
5170
                '',
5171
                'ASC'
5172
            );
5173
            $table->set_additional_parameters(
5174
                [
5175
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5176
                    'action' => Security::remove_XSS($action),
5177
                    'user_id' => intval($userId),
5178
                    'session_id' => intval($_GET['session_id']),
5179
                    'group_id' => intval($_GET['group_id']),
5180
                ]
5181
            );
5182
            $table->set_header(
5183
                0,
5184
                get_lang('Date'),
5185
                true,
5186
                ['style' => 'width:200px;']
5187
            );
5188
            $table->set_header(
5189
                1,
5190
                get_lang('Type'),
5191
                true,
5192
                ['style' => 'width:30px;']
5193
            );
5194
            $table->set_header(
5195
                2,
5196
                get_lang('Title'),
5197
                true,
5198
                ['style' => 'width:200px;']
5199
            );
5200
            $table->set_header(
5201
                3,
5202
                get_lang('Version'),
5203
                true,
5204
                ['style' => 'width:30px;']
5205
            );
5206
            $table->set_header(
5207
                4,
5208
                get_lang('Comment'),
5209
                true,
5210
                ['style' => 'width:200px;']
5211
            );
5212
            $table->set_header(
5213
                5,
5214
                get_lang('Progress'),
5215
                true,
5216
                ['style' => 'width:30px;']
5217
            );
5218
            $table->set_header(
5219
                6,
5220
                get_lang('Rating'),
5221
                true,
5222
                ['style' => 'width:30px;']
5223
            );
5224
            $table->display();
5225
        }
5226
    }
5227
5228
    /**
5229
     * @param string $action
5230
     */
5231
    public function getMostChangedPages($action)
5232
    {
5233
        $_course = $this->courseInfo;
5234
        $tbl_wiki = $this->tbl_wiki;
5235
        $course_id = $this->course_id;
5236
        $condition_session = $this->condition_session;
5237
        $groupfilter = $this->groupfilter;
5238
5239
        echo '<div class="actions">'.get_lang('Most changed pages').'</div>';
5240
5241
        if (api_is_allowed_to_edit(false, true) ||
5242
            api_is_platform_admin()
5243
        ) { //only by professors if page is hidden
5244
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
5245
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5246
                    GROUP BY reflink'; //TODO:check MAX and group by return last version
5247
        } else {
5248
            $sql = 'SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'
5249
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND visibility=1
5250
                    GROUP BY reflink'; //TODO:check MAX and group by return last version
5251
        }
5252
5253
        $allpages = Database::query($sql);
5254
5255
        //show table
5256
        if (Database::num_rows($allpages) > 0) {
5257
            $rows = [];
5258
            while ($obj = Database::fetch_object($allpages)) {
5259
                //get type assignment icon
5260
                $ShowAssignment = '';
5261
                if (1 == $obj->assignment) {
5262
                    $ShowAssignment = Display::return_icon(
5263
                        'wiki_assignment.png',
5264
                        get_lang('Assignment proposed by the trainer'),
5265
                        '',
5266
                        ICON_SIZE_SMALL
5267
                    );
5268
                } elseif (2 == $obj->assignment) {
5269
                    $ShowAssignment = Display::return_icon(
5270
                        'wiki_work.png',
5271
                        get_lang('Learner paper'),
5272
                        '',
5273
                        ICON_SIZE_SMALL
5274
                    );
5275
                } elseif (0 == $obj->assignment) {
5276
                    $ShowAssignment = Display::return_icon(
5277
                        'px_transparent.gif'
5278
                    );
5279
                }
5280
5281
                $row = [];
5282
                $row[] = $ShowAssignment;
5283
                $row[] = '<a href="'.api_get_self(
5284
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5285
                        urlencode($obj->reflink)
5286
                    ).'&session_id='.api_htmlentities(
5287
                        $_GET['session_id']
5288
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5289
                    api_htmlentities($obj->title).'</a>';
5290
                $row[] = $obj->MAX;
5291
                $rows[] = $row;
5292
            }
5293
5294
            $table = new SortableTableFromArrayConfig(
5295
                $rows,
5296
                2,
5297
                10,
5298
                'MostChangedPages_table',
5299
                '',
5300
                '',
5301
                'DESC'
5302
            );
5303
            $table->set_additional_parameters(
5304
                [
5305
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5306
                    'action' => Security::remove_XSS($action),
5307
                    'session_id' => intval($_GET['session_id']),
5308
                    'group_id' => intval($_GET['group_id']),
5309
                ]
5310
            );
5311
            $table->set_header(
5312
                0,
5313
                get_lang('Type'),
5314
                true,
5315
                ['style' => 'width:30px;']
5316
            );
5317
            $table->set_header(1, get_lang('Title'), true);
5318
            $table->set_header(2, get_lang('Changes'), true);
5319
            $table->display();
5320
        }
5321
    }
5322
5323
    /**
5324
     * Restore page.
5325
     *
5326
     * @return bool
5327
     */
5328
    public function restorePage()
5329
    {
5330
        $userId = api_get_user_id();
5331
        $_course = $this->courseInfo;
5332
        $current_row = $this->getWikiData();
5333
        $last_row = $this->getLastWikiData($this->page);
5334
5335
        if (empty($last_row)) {
5336
            return false;
5337
        }
5338
5339
        $PassEdit = false;
5340
5341
        /* Only teachers and platform admin can edit the index page.
5342
        Only teachers and platform admin can edit an assignment teacher*/
5343
        if (('index' == $current_row['reflink'] ||
5344
                '' == $current_row['reflink'] ||
5345
                1 == $current_row['assignment']) &&
5346
            (!api_is_allowed_to_edit(false, true) &&
5347
                0 == $this->group_id)
5348
        ) {
5349
            Display::addFlash(
5350
                Display::return_message(
5351
                    get_lang('OnlyEditsCourseManager'),
5352
                    'normal',
5353
                    false
5354
                )
5355
            );
5356
        } else {
5357
            // check if is a wiki group
5358
            if (0 != $current_row['group_id']) {
5359
                $groupInfo = GroupManager::get_group_properties(
5360
                    $this->group_id
5361
                );
5362
                //Only teacher, platform admin and group members can edit a wiki group
5363
                if (api_is_allowed_to_edit(false, true) ||
5364
                    api_is_platform_admin() ||
5365
                    GroupManager::isUserInGroup($userId, api_get_group_entity($this->group_id)) ||
5366
                    api_is_allowed_in_course()
5367
                ) {
5368
                    $PassEdit = true;
5369
                } else {
5370
                    Display::addFlash(
5371
                        Display::return_message(
5372
                            get_lang('OnlyEditsGroupMembers'),
5373
                            'normal',
5374
                            false
5375
                        )
5376
                    );
5377
                }
5378
            } else {
5379
                $PassEdit = true;
5380
            }
5381
5382
            // check if is an assignment
5383
            //$icon_assignment = null;
5384
            if (1 == $current_row['assignment']) {
5385
                Display::addFlash(
5386
                    Display::return_message(
5387
                        get_lang('You can edit this page, but the pages of learners will not be modified'),
5388
                        'normal',
5389
                        false
5390
                    )
5391
                );
5392
            } elseif (2 == $current_row['assignment']) {
5393
                if (false == ($userId == $current_row['user_id'])) {
5394
                    if (api_is_allowed_to_edit(
5395
                            false,
5396
                            true
5397
                        ) || api_is_platform_admin()) {
5398
                        $PassEdit = true;
5399
                    } else {
5400
                        Display::addFlash(
5401
                            Display::return_message(
5402
                                get_lang('LockByTrainer'),
5403
                                'normal',
5404
                                false
5405
                            )
5406
                        );
5407
                        $PassEdit = false;
5408
                    }
5409
                } else {
5410
                    $PassEdit = true;
5411
                }
5412
            }
5413
5414
            //show editor if edit is allowed
5415
            if ($PassEdit) {
5416
                if (1 == $current_row['editlock'] &&
5417
                    (false == api_is_allowed_to_edit(false, true) ||
5418
                        false == api_is_platform_admin())
5419
                ) {
5420
                    Display::addFlash(
5421
                        Display::return_message(
5422
                            get_lang('This page is protected. Trainers only can change it'),
5423
                            'normal',
5424
                            false
5425
                        )
5426
                    );
5427
                } else {
5428
                    if (0 != $last_row['is_editing'] && $last_row['is_editing'] != $userId) {
5429
                        // Checking for concurrent users
5430
                        $timestamp_edit = strtotime($last_row['time_edit']);
5431
                        $time_editing = time() - $timestamp_edit;
5432
                        $max_edit_time = 1200; // 20 minutes
5433
                        $rest_time = $max_edit_time - $time_editing;
5434
                        $userinfo = api_get_user_info($last_row['is_editing']);
5435
                        $is_being_edited = get_lang(
5436
                                'ThisPageisBeginedited by'
5437
                            ).' <a href='.$userinfo['profile_url'].'>'.
5438
                            Display::tag(
5439
                                'span',
5440
                                $userinfo['complete_name_with_username']
5441
                            ).
5442
                            get_lang('Please try again later. If the user who is currently editing the page does not save it, this page will be available to you around').' '.date(
5443
                                "i",
5444
                                $rest_time
5445
                            ).' '.get_lang('minutes');
5446
                        Display::addFlash(
5447
                            Display::return_message(
5448
                                $is_being_edited,
5449
                                'normal',
5450
                                false
5451
                            )
5452
                        );
5453
                    } else {
5454
                        Display::addFlash(
5455
                            Display::return_message(
5456
                                self::restore_wikipage(
5457
                                    $current_row['page_id'],
5458
                                    $current_row['reflink'],
5459
                                    $current_row['title'],
5460
                                    $current_row['content'],
5461
                                    $current_row['group_id'],
5462
                                    $current_row['assignment'],
5463
                                    $current_row['progress'],
5464
                                    $current_row['version'],
5465
                                    $last_row['version'],
5466
                                    $current_row['linksto']
5467
                                ).': <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5468
                                    urlencode($last_row['reflink'])
5469
                                ).'&session_id='.$last_row['session_id'].'&group_id='.$last_row['group_id'].'">'.
5470
                                api_htmlentities($last_row['title']).'</a>',
5471
                                'confirmation',
5472
                                false
5473
                            )
5474
                        );
5475
                    }
5476
                }
5477
            }
5478
        }
5479
    }
5480
5481
    /**
5482
     * @param int|bool $wikiId
5483
     */
5484
    public function setWikiData($wikiId)
5485
    {
5486
        $this->wikiData = self::getWikiDataFromDb($wikiId);
5487
    }
5488
5489
    /**
5490
     * @return array
5491
     */
5492
    public function getWikiData()
5493
    {
5494
        return $this->wikiData;
5495
    }
5496
5497
    /**
5498
     * Check last version.
5499
     *
5500
     * @param int $view
5501
     *
5502
     * @return bool
5503
     */
5504
    public function checkLastVersion($view)
5505
    {
5506
        $tbl_wiki = $this->tbl_wiki;
5507
        $course_id = $this->course_id;
5508
        $condition_session = $this->condition_session;
5509
        $groupfilter = $this->groupfilter;
5510
        $page = $this->page;
5511
        $_course = $this->courseInfo;
5512
5513
        if (empty($view)) {
5514
            return false;
5515
        }
5516
5517
        $current_row = $this->getWikiData();
5518
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5519
                WHERE
5520
                    c_id = '.$course_id.' AND
5521
                    reflink = "'.Database::escape_string($page).'" AND
5522
                    '.$groupfilter.$condition_session.'
5523
                ORDER BY id DESC'; //last version
5524
        $result = Database::query($sql);
5525
        $last_row = Database::fetch_array($result);
5526
5527
        if ($view < $last_row['id']) {
5528
            $message = '<center>'.get_lang('NoAreSeeingTheLatest version').'<br />
5529
            '.get_lang("Version").' (
5530
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5531
                    urlencode($current_row['reflink'])
5532
                ).'&group_id='.$current_row['group_id'].'&session_id='.$current_row['session_id'].'&view='.api_htmlentities(
5533
                    $_GET['view']
5534
                ).'" title="'.get_lang('Current version').'">
5535
            '.$current_row['version'].'
5536
            </a> /
5537
            <a href="index.php?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5538
                    urlencode($last_row['reflink'])
5539
                ).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'" title="'.get_lang(
5540
                    'Latest version'
5541
                ).'">
5542
            '.$last_row['version'].'
5543
            </a>) <br />'.get_lang("ConvertToLatest version").':
5544
            <a href="index.php?cidReq='.$_course['id'].'&action=restorepage&title='.api_htmlentities(
5545
                    urlencode($last_row['reflink'])
5546
                ).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'&view='.api_htmlentities(
5547
                    $_GET['view']
5548
                ).'">'.
5549
                get_lang("Restore").'</a></center>';
5550
            Display::addFlash(
5551
                Display::return_message($message, 'warning', false)
5552
            );
5553
        }
5554
    }
5555
5556
    /**
5557
     *  Get most linked pages.
5558
     */
5559
    public function getMostLinked()
5560
    {
5561
        $tbl_wiki = $this->tbl_wiki;
5562
        $course_id = $this->course_id;
5563
        $groupfilter = $this->groupfilter;
5564
        $condition_session = $this->condition_session;
5565
        $_course = $this->courseInfo;
5566
5567
        echo '<div class="actions">'.get_lang('Pages most linked').'</div>';
5568
        $pages = [];
5569
        $linked = [];
5570
5571
        // Get name pages
5572
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5573
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5574
                GROUP BY reflink
5575
                ORDER BY reflink ASC';
5576
        $allpages = Database::query($sql);
5577
        while ($row = Database::fetch_array($allpages)) {
5578
            if ('index' == $row['reflink']) {
5579
                $row['reflink'] = str_replace(
5580
                    ' ',
5581
                    '_',
5582
                    get_lang('Home')
5583
                );
5584
            }
5585
            $pages[] = $row['reflink'];
5586
        }
5587
5588
        // Get name refs in last pages
5589
        $sql = 'SELECT *
5590
                FROM '.$tbl_wiki.' s1
5591
                WHERE s1.c_id = '.$course_id.' AND id=(
5592
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5593
                    WHERE
5594
                        s2.c_id = '.$course_id.' AND
5595
                        s1.reflink = s2.reflink AND
5596
                        '.$groupfilter.$condition_session.'
5597
                )';
5598
5599
        $allpages = Database::query($sql);
5600
5601
        while ($row = Database::fetch_array($allpages)) {
5602
            //remove self reference
5603
            $row['linksto'] = str_replace(
5604
                $row["reflink"],
5605
                " ",
5606
                trim($row["linksto"])
5607
            );
5608
            $refs = explode(" ", trim($row["linksto"]));
5609
5610
            // Find linksto into reflink. If found ->page is linked
5611
            foreach ($refs as $v) {
5612
                if (in_array($v, $pages)) {
5613
                    if ("" != trim($v)) {
5614
                        $linked[] = $v;
5615
                    }
5616
                }
5617
            }
5618
        }
5619
5620
        $linked = array_unique($linked);
5621
        //make a unique list. TODO:delete this line and count how many for each page
5622
        //show table
5623
        $rows = [];
5624
        foreach ($linked as $linked_show) {
5625
            $row = [];
5626
            $row[] = '<a href="'.api_get_self(
5627
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5628
                    urlencode(str_replace('_', ' ', $linked_show))
5629
                ).'&session_id='.api_htmlentities(
5630
                    $_GET['session_id']
5631
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5632
                str_replace('_', ' ', $linked_show).'</a>';
5633
            $rows[] = $row;
5634
        }
5635
5636
        $table = new SortableTableFromArrayConfig(
5637
            $rows,
5638
            0,
5639
            10,
5640
            'LinkedPages_table',
5641
            '',
5642
            '',
5643
            'DESC'
5644
        );
5645
        $table->set_additional_parameters(
5646
            [
5647
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5648
                'action' => Security::remove_XSS($this->action),
5649
                'session_id' => intval($_GET['session_id']),
5650
                'group_id' => intval($_GET['group_id']),
5651
            ]
5652
        );
5653
        $table->set_header(0, get_lang('Title'), true);
5654
        $table->display();
5655
    }
5656
5657
    /**
5658
     * Get orphan pages.
5659
     */
5660
    public function getOrphaned()
5661
    {
5662
        $tbl_wiki = $this->tbl_wiki;
5663
        $course_id = $this->course_id;
5664
        $groupfilter = $this->groupfilter;
5665
        $condition_session = $this->condition_session;
5666
        $_course = $this->courseInfo;
5667
5668
        echo '<div class="actions">'.get_lang('Orphaned pages').'</div>';
5669
5670
        $pages = [];
5671
        $orphaned = [];
5672
5673
        //get name pages
5674
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5675
                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5676
                GROUP BY reflink
5677
                ORDER BY reflink ASC';
5678
        $allpages = Database::query($sql);
5679
        while ($row = Database::fetch_array($allpages)) {
5680
            $pages[] = $row['reflink'];
5681
        }
5682
5683
        //get name refs in last pages and make a unique list
5684
        $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1
5685
                WHERE s1.c_id = '.$course_id.' AND id=(
5686
                SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5687
                WHERE
5688
                    s2.c_id = '.$course_id.' AND
5689
                    s1.reflink = s2.reflink AND
5690
                    '.$groupfilter.$condition_session.'
5691
                )';
5692
        $allpages = Database::query($sql);
5693
        $array_refs_linked = [];
5694
        while ($row = Database::fetch_array($allpages)) {
5695
            $row['linksto'] = str_replace(
5696
                $row["reflink"],
5697
                " ",
5698
                trim($row["linksto"])
5699
            ); //remove self reference
5700
            $refs = explode(" ", trim($row["linksto"]));
5701
            foreach ($refs as $ref_linked) {
5702
                if ($ref_linked == str_replace(
5703
                        ' ',
5704
                        '_',
5705
                        get_lang('Home')
5706
                    )) {
5707
                    $ref_linked = 'index';
5708
                }
5709
                $array_refs_linked[] = $ref_linked;
5710
            }
5711
        }
5712
5713
        $array_refs_linked = array_unique($array_refs_linked);
5714
5715
        //search each name of list linksto into list reflink
5716
        foreach ($pages as $v) {
5717
            if (!in_array($v, $array_refs_linked)) {
5718
                $orphaned[] = $v;
5719
            }
5720
        }
5721
        $rows = [];
5722
        foreach ($orphaned as $orphaned_show) {
5723
            // get visibility status and title
5724
            $sql = 'SELECT *
5725
                    FROM  '.$tbl_wiki.'
5726
		            WHERE
5727
		                c_id = '.$course_id.' AND
5728
		                '.$groupfilter.$condition_session.' AND
5729
		                reflink="'.Database::escape_string($orphaned_show).'"
5730
                    GROUP BY reflink';
5731
            $allpages = Database::query($sql);
5732
            while ($row = Database::fetch_array($allpages)) {
5733
                $orphaned_title = $row['title'];
5734
                $orphaned_visibility = $row['visibility'];
5735
                if (1 == $row['assignment']) {
5736
                    $ShowAssignment = Display::return_icon(
5737
                        'wiki_assignment.png',
5738
                        '',
5739
                        '',
5740
                        ICON_SIZE_SMALL
5741
                    );
5742
                } elseif (2 == $row['assignment']) {
5743
                    $ShowAssignment = Display::return_icon(
5744
                        'wiki_work.png',
5745
                        '',
5746
                        '',
5747
                        ICON_SIZE_SMALL
5748
                    );
5749
                } elseif (0 == $row['assignment']) {
5750
                    $ShowAssignment = Display::return_icon(
5751
                        'px_transparent.gif'
5752
                    );
5753
                }
5754
            }
5755
5756
            if (!api_is_allowed_to_edit(false, true) || !api_is_platform_admin(
5757
                ) && 0 == $orphaned_visibility) {
5758
                continue;
5759
            }
5760
5761
            //show table
5762
            $row = [];
5763
            $row[] = $ShowAssignment;
5764
            $row[] = '<a href="'.api_get_self(
5765
                ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5766
                    urlencode($orphaned_show)
5767
                ).'&session_id='.api_htmlentities(
5768
                    $_GET['session_id']
5769
                ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5770
                api_htmlentities($orphaned_title).'</a>';
5771
            $rows[] = $row;
5772
        }
5773
5774
        $table = new SortableTableFromArrayConfig(
5775
            $rows,
5776
            1,
5777
            10,
5778
            'OrphanedPages_table',
5779
            '',
5780
            '',
5781
            'DESC'
5782
        );
5783
        $table->set_additional_parameters(
5784
            [
5785
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5786
                'action' => Security::remove_XSS($this->action),
5787
                'session_id' => intval($_GET['session_id']),
5788
                'group_id' => intval($_GET['group_id']),
5789
            ]
5790
        );
5791
        $table->set_header(
5792
            0,
5793
            get_lang('Type'),
5794
            true,
5795
            ['style' => 'width:30px;']
5796
        );
5797
        $table->set_header(1, get_lang('Title'), true);
5798
        $table->display();
5799
    }
5800
5801
    /**
5802
     * Get wanted pages.
5803
     */
5804
    public function getWantedPages()
5805
    {
5806
        $tbl_wiki = $this->tbl_wiki;
5807
        $course_id = $this->course_id;
5808
        $groupfilter = $this->groupfilter;
5809
        $condition_session = $this->condition_session;
5810
5811
        echo '<div class="actions">'.get_lang('Wanted pages').'</div>';
5812
        $pages = [];
5813
        $wanted = [];
5814
        //get name pages
5815
        $sql = 'SELECT * FROM '.$tbl_wiki.'
5816
                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5817
                GROUP BY reflink
5818
                ORDER BY reflink ASC';
5819
        $allpages = Database::query($sql);
5820
5821
        while ($row = Database::fetch_array($allpages)) {
5822
            if ('index' == $row['reflink']) {
5823
                $row['reflink'] = str_replace(
5824
                    ' ',
5825
                    '_',
5826
                    get_lang('Home')
5827
                );
5828
            }
5829
            $pages[] = $row['reflink'];
5830
        }
5831
5832
        //get name refs in last pages
5833
        $sql = 'SELECT * FROM   '.$tbl_wiki.' s1
5834
                WHERE s1.c_id = '.$course_id.' AND id=(
5835
                    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
5836
                    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.$condition_session.'
5837
                )';
5838
5839
        $allpages = Database::query($sql);
5840
5841
        while ($row = Database::fetch_array($allpages)) {
5842
            $refs = explode(" ", trim($row["linksto"]));
5843
            // Find linksto into reflink. If not found ->page is wanted
5844
            foreach ($refs as $v) {
5845
                if (!in_array($v, $pages)) {
5846
                    if ("" != trim($v)) {
5847
                        $wanted[] = $v;
5848
                    }
5849
                }
5850
            }
5851
        }
5852
5853
        $wanted = array_unique($wanted); //make a unique list
5854
5855
        //show table
5856
        $rows = [];
5857
        foreach ($wanted as $wanted_show) {
5858
            $row = [];
5859
            $wanted_show = Security::remove_XSS($wanted_show);
5860
            $row[] = '<a href="'.api_get_path(
5861
                    WEB_PATH
5862
                ).'main/wiki/index.php?cidReq=&action=addnew&title='.str_replace(
5863
                    '_',
5864
                    ' ',
5865
                    $wanted_show
5866
                ).'&session_id='.api_htmlentities(
5867
                    $_GET['session_id']
5868
                ).'&group_id='.api_htmlentities(
5869
                    $_GET['group_id']
5870
                ).'" class="new_wiki_link">'.str_replace(
5871
                    '_',
5872
                    ' ',
5873
                    $wanted_show
5874
                ).'</a>'; //meter un remove xss en lugar de htmlentities
5875
            $rows[] = $row;
5876
        }
5877
5878
        $table = new SortableTableFromArrayConfig(
5879
            $rows,
5880
            0,
5881
            10,
5882
            'WantedPages_table',
5883
            '',
5884
            '',
5885
            'DESC'
5886
        );
5887
        $table->set_additional_parameters(
5888
            [
5889
                'cidReq' => Security::remove_XSS($_GET['cidReq']),
5890
                'action' => Security::remove_XSS($this->action),
5891
                'session_id' => intval($_GET['session_id']),
5892
                'group_id' => intval($_GET['group_id']),
5893
            ]
5894
        );
5895
        $table->set_header(0, get_lang('Title'), true);
5896
        $table->display();
5897
    }
5898
5899
    /**
5900
     * Most visited.
5901
     */
5902
    public function getMostVisited()
5903
    {
5904
        $tbl_wiki = $this->tbl_wiki;
5905
        $course_id = $this->course_id;
5906
        $groupfilter = $this->groupfilter;
5907
        $condition_session = $this->condition_session;
5908
        $_course = $this->courseInfo;
5909
5910
        echo '<div class="actions">'.get_lang('Most visited pages').'</div>';
5911
5912
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin(
5913
            )) { //only by professors if page is hidden
5914
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5915
                    WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
5916
                    GROUP BY reflink';
5917
        } else {
5918
            $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
5919
                    WHERE
5920
                        c_id = '.$course_id.' AND
5921
                        '.$groupfilter.$condition_session.' AND
5922
                        visibility=1
5923
                    GROUP BY reflink';
5924
        }
5925
5926
        $allpages = Database::query($sql);
5927
5928
        //show table
5929
        if (Database::num_rows($allpages) > 0) {
5930
            $rows = [];
5931
            while ($obj = Database::fetch_object($allpages)) {
5932
                //get type assignment icon
5933
                $ShowAssignment = '';
5934
                if (1 == $obj->assignment) {
5935
                    $ShowAssignment = Display::return_icon(
5936
                        'wiki_assignment.png',
5937
                        get_lang('Assignment proposed by the trainer'),
5938
                        '',
5939
                        ICON_SIZE_SMALL
5940
                    );
5941
                } elseif (2 == $obj->assignment) {
5942
                    $ShowAssignment = $ShowAssignment = Display::return_icon(
5943
                        'wiki_work.png',
5944
                        get_lang('Learner paper'),
5945
                        '',
5946
                        ICON_SIZE_SMALL
5947
                    );
5948
                } elseif (0 == $obj->assignment) {
5949
                    $ShowAssignment = Display::return_icon(
5950
                        'px_transparent.gif'
5951
                    );
5952
                }
5953
5954
                $row = [];
5955
                $row[] = $ShowAssignment;
5956
                $row[] = '<a href="'.api_get_self(
5957
                    ).'?cidReq='.$_course['code'].'&action=showpage&title='.api_htmlentities(
5958
                        urlencode($obj->reflink)
5959
                    ).'&session_id='.api_htmlentities(
5960
                        $_GET['session_id']
5961
                    ).'&group_id='.api_htmlentities($_GET['group_id']).'">'.
5962
                    api_htmlentities($obj->title).'</a>';
5963
                $row[] = $obj->tsum;
5964
                $rows[] = $row;
5965
            }
5966
5967
            $table = new SortableTableFromArrayConfig(
5968
                $rows,
5969
                2,
5970
                10,
5971
                'MostVisitedPages_table',
5972
                '',
5973
                '',
5974
                'DESC'
5975
            );
5976
            $table->set_additional_parameters(
5977
                [
5978
                    'cidReq' => Security::remove_XSS($_GET['cidReq']),
5979
                    'action' => Security::remove_XSS($this->action),
5980
                    'session_id' => intval($_GET['session_id']),
5981
                    'group_id' => intval($_GET['group_id']),
5982
                ]
5983
            );
5984
            $table->set_header(
5985
                0,
5986
                get_lang('Type'),
5987
                true,
5988
                ['style' => 'width:30px;']
5989
            );
5990
            $table->set_header(1, get_lang('Title'), true);
5991
            $table->set_header(2, get_lang('Visits'), true);
5992
            $table->display();
5993
        }
5994
    }
5995
5996
    /**
5997
     * Get actions bar.
5998
     *
5999
     * @return string
6000
     */
6001
    public function showActionBar()
6002
    {
6003
        $_course = $this->courseInfo;
6004
        $session_id = $this->session_id;
6005
        $groupId = $this->group_id;
6006
        $page = $this->page;
6007
        $actionsLeft = '';
6008
        $actionsLeft .= '<a href="index.php?action=showpage&title=index&cidReq='.$_course['id'].'&session_id='.$session_id.'&group_id='.$groupId.'">'.
6009
            Display::return_icon(
6010
                'home.png',
6011
                get_lang('Home'),
6012
                '',
6013
                ICON_SIZE_MEDIUM
6014
            ).'</a>';
6015
6016
        if (api_is_allowed_to_session_edit(
6017
                false,
6018
                true
6019
            ) && api_is_allowed_to_edit()) {
6020
            // menu add page
6021
            $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=addnew&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6022
                    'addnew'
6023
                ).'>'
6024
                .Display::return_icon(
6025
                    'new_document.png',
6026
                    get_lang('Add new page'),
6027
                    '',
6028
                    ICON_SIZE_MEDIUM
6029
                ).'</a>';
6030
        }
6031
6032
        $lock_unlock_addnew = null;
6033
        $protect_addnewpage = null;
6034
6035
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6036
            // page action: enable or disable the adding of new pages
6037
            if (0 == self::check_addnewpagelock()) {
6038
                $protect_addnewpage = Display::return_icon(
6039
                    'off.png',
6040
                    get_lang('The Add option has been protected. Trainers only can add pages to this Wiki. But learners and group members can still edit them')
6041
                );
6042
                $lock_unlock_addnew = 'unlockaddnew';
6043
            } else {
6044
                $protect_addnewpage = Display::return_icon(
6045
                    'on.png',
6046
                    get_lang('The add option has been enabled for all course users and group members')
6047
                );
6048
                $lock_unlock_addnew = 'lockaddnew';
6049
            }
6050
        }
6051
6052
        // menu find
6053
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6054
                'searchpages'
6055
            ).'>'.
6056
            Display::return_icon(
6057
                'search.png',
6058
                get_lang('Search'),
6059
                '',
6060
                ICON_SIZE_MEDIUM
6061
            ).'</a>';
6062
        ///menu more
6063
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'&action=more&title='.api_htmlentities(
6064
                urlencode($page)
6065
            ).'"'.self::is_active_navigation_tab('more').'>'.
6066
            Display::return_icon(
6067
                'statistics.png',
6068
                get_lang('Statistics'),
6069
                '',
6070
                ICON_SIZE_MEDIUM
6071
            ).'</a>';
6072
6073
        // menu all pages
6074
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=allpages&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6075
                'allpages'
6076
            ).'>'.
6077
            Display::return_icon(
6078
                'list_badges.png',
6079
                get_lang('All pages'),
6080
                '',
6081
                ICON_SIZE_MEDIUM
6082
            ).'</a>';
6083
        // menu recent changes
6084
        $actionsLeft .= '<a href="index.php?cidReq='.$_course['id'].'&action=recentchanges&session_id='.$session_id.'&group_id='.$groupId.'"'.self::is_active_navigation_tab(
6085
                'recentchanges'
6086
            ).'>'.
6087
            Display::return_icon(
6088
                'history.png',
6089
                get_lang('Latest changes'),
6090
                '',
6091
                ICON_SIZE_MEDIUM
6092
            ).'</a>';
6093
        echo Display::toolbarAction('toolbar-wiki', [$actionsLeft]);
6094
    }
6095
6096
    /**
6097
     * Showing warning.
6098
     */
6099
    public function deletePageWarning()
6100
    {
6101
        $page = $this->page;
6102
        $course_id = $this->course_id;
6103
        $groupfilter = $this->groupfilter;
6104
        $condition_session = $this->condition_session;
6105
6106
        if (!$_GET['title']) {
6107
            Display::addFlash(
6108
                Display::return_message(
6109
                    get_lang('You must select a page first'),
6110
                    'error',
6111
                    false
6112
                )
6113
            );
6114
6115
            return;
6116
        }
6117
6118
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6119
            Display::addFlash(
6120
                '<div id="wikititle">'.get_lang('Delete this page and all its versions').'</div>'
6121
            );
6122
            if ("index" == $page) {
6123
                Display::addFlash(
6124
                    Display::return_message(
6125
                        get_lang('Deleting the homepage of the Wiki is not recommended because it is the main access to the wiki.<br />If, however, you need to do so, do not forget to re-create this Homepage. Until then, other users will not be able to add new pages.'),
6126
                        'warning',
6127
                        false
6128
                    )
6129
                );
6130
            }
6131
            $message = get_lang('Are you sure you want to delete this page and its history?')."
6132
                <a href=\"index.php?".api_get_cidreq()."\">".get_lang("No")."</a>
6133
                <a href=\"".api_get_self()."?".api_get_cidreq(
6134
                )."&action=delete&title=".api_htmlentities(
6135
                    urlencode($page)
6136
                )."&delete=yes\">".
6137
                get_lang("Yes")."</a>";
6138
6139
            if (!isset($_GET['delete'])) {
6140
                Display::addFlash(
6141
                    Display::return_message($message, 'warning', false)
6142
                );
6143
            }
6144
6145
            if (isset($_GET['delete']) && 'yes' == $_GET['delete']) {
6146
                $result = self::deletePage(
6147
                    $page,
6148
                    $course_id,
6149
                    $groupfilter,
6150
                    $condition_session
6151
                );
6152
                if ($result) {
6153
                    Display::addFlash(
6154
                        Display::return_message(
6155
                            get_lang('Group wikiPageDeleted'),
6156
                            'confirmation',
6157
                            false
6158
                        )
6159
                    );
6160
                }
6161
            }
6162
        } else {
6163
            Display::addFlash(
6164
                Display::return_message(
6165
                    get_lang('OnlyAdminDeletePageGroup wiki'),
6166
                    'normal',
6167
                    false
6168
                )
6169
            );
6170
        }
6171
    }
6172
6173
    /**
6174
     * Edit page.
6175
     */
6176
    public function editPage()
6177
    {
6178
        $tbl_wiki = $this->tbl_wiki;
6179
        $tbl_wiki_conf = $this->tbl_wiki_conf;
6180
        $condition_session = $this->condition_session;
6181
        $groupfilter = $this->groupfilter;
6182
        $page = $this->page;
6183
        $course_id = $this->course_id;
6184
        $groupId = $this->group_id;
6185
        $userId = api_get_user_id();
6186
6187
        if (0 != api_get_session_id() &&
6188
            false == api_is_allowed_to_session_edit(false, true)
6189
        ) {
6190
            api_not_allowed();
6191
        }
6192
6193
        $sql = 'SELECT *
6194
                FROM '.$tbl_wiki.' w INNER JOIN '.$tbl_wiki_conf.' c
6195
                ON  (w.c_id = c.c_id AND w.page_id = c.page_id)
6196
                WHERE
6197
    		        w.c_id = '.$course_id.' AND
6198
                    w.reflink= "'.Database::escape_string($page).'" AND
6199
                    w.'.$groupfilter.$condition_session.'
6200
                ORDER BY id DESC';
6201
        $result = Database::query($sql);
6202
        $row = Database::fetch_array($result);
6203
6204
        // we do not need a while loop since we are always displaying the last version
6205
        if ('' == $row['content'] && '' == $row['title'] && '' == $page) {
6206
            Display::addFlash(
6207
                Display::return_message(
6208
                    get_lang('You must select a page first'),
6209
                    'error',
6210
                    false
6211
                )
6212
            );
6213
6214
            return;
6215
        } elseif ('' == $row['content'] && '' == $row['title'] && 'index' == $page) {
6216
            // Table structure for better export to pdf
6217
            $default_table_for_content_Start = '<table align="center" border="0"><tr><td align="center">';
6218
            $default_table_for_content_End = '</td></tr></table>';
6219
            $content = $default_table_for_content_Start.sprintf(
6220
                    get_lang(' <br/> <br/> <p align="center"> <img src="%swiki/wcollaborative.png" alt="Working as a team" title="Working as a team" /></p> <p align="center">To begin editing this page and remove this text</p>'),
6221
                    api_get_path(WEB_IMG_PATH)
6222
                ).$default_table_for_content_End;
6223
            $title = get_lang('Home');
6224
            $page_id = 0;
6225
        } else {
6226
            $content = api_html_entity_decode($row['content']);
6227
            $title = api_html_entity_decode($row['title']);
6228
            $page_id = $row['page_id'];
6229
        }
6230
6231
        // Only teachers and platform admin can edit the index page.
6232
        // Only teachers and platform admin can edit an assignment teacher.
6233
        // And users in groups
6234
6235
        if (('index' == $row['reflink'] || '' == $row['reflink'] || 1 == $row['assignment']) &&
6236
            (!api_is_allowed_to_edit(
6237
                    false,
6238
                    true
6239
                ) && 0 == $groupId) && !api_is_allowed_in_course()
6240
        ) {
6241
            Display::addFlash(
6242
                Display::return_message(
6243
                    get_lang('OnlyEditsCourseManager'),
6244
                    'error'
6245
                )
6246
            );
6247
        } else {
6248
            $PassEdit = false;
6249
            // Check if is a wiki group
6250
            if (!empty($groupId)) {
6251
                $groupInfo = GroupManager::get_group_properties($groupId);
6252
                //Only teacher, platform admin and group members can edit a wiki group
6253
                if (api_is_allowed_to_edit(false, true) ||
6254
                    api_is_platform_admin() ||
6255
                    GroupManager::isUserInGroup($userId, api_get_group_entity($groupId))
6256
                ) {
6257
                    $PassEdit = true;
6258
                } else {
6259
                    Display::addFlash(
6260
                        Display::return_message(
6261
                            get_lang('OnlyEditsGroupMembers')
6262
                        )
6263
                    );
6264
                }
6265
            } else {
6266
                $PassEdit = true;
6267
            }
6268
6269
            $icon_assignment = null;
6270
            // check if is a assignment
6271
            if (1 == $row['assignment']) {
6272
                Display::addFlash(
6273
                    Display::return_message(get_lang('You can edit this page, but the pages of learners will not be modified'))
6274
                );
6275
6276
                $icon_assignment = Display::return_icon(
6277
                    'wiki_assignment.png',
6278
                    get_lang('This page is an assignment proposed by a trainer'),
6279
                    '',
6280
                    ICON_SIZE_SMALL
6281
                );
6282
            } elseif (2 == $row['assignment']) {
6283
                $icon_assignment = Display::return_icon(
6284
                    'wiki_work.png',
6285
                    get_lang('Learner paperExtra'),
6286
                    '',
6287
                    ICON_SIZE_SMALL
6288
                );
6289
                if (false == ($userId == $row['user_id'])) {
6290
                    if (api_is_allowed_to_edit(
6291
                            false,
6292
                            true
6293
                        ) || api_is_platform_admin()) {
6294
                        $PassEdit = true;
6295
                    } else {
6296
                        Display::addFlash(
6297
                            Display::return_message(
6298
                                get_lang('LockByTrainer'),
6299
                                'warning'
6300
                            )
6301
                        );
6302
                        $PassEdit = false;
6303
                    }
6304
                } else {
6305
                    $PassEdit = true;
6306
                }
6307
            }
6308
6309
            if ($PassEdit) {
6310
                //show editor if edit is allowed <<<<<
6311
                if (1 == $row['editlock'] &&
6312
                    (false == api_is_allowed_to_edit(false, true) ||
6313
                        false == api_is_platform_admin())
6314
                ) {
6315
                    Display::addFlash(
6316
                        Display::return_message(
6317
                            get_lang('This page is protected. Trainers only can change it')
6318
                        )
6319
                    );
6320
                } else {
6321
                    // Check tasks
6322
                    if (!empty($row['startdate_assig']) && time() <
6323
                        api_strtotime($row['startdate_assig'])
6324
                    ) {
6325
                        $message = get_lang(
6326
                                'TheTaskDoesNotBeginUntil'
6327
                            ).': '.api_get_local_time($row['startdate_assig']);
6328
6329
                        Display::addFlash(
6330
                            Display::return_message(
6331
                                $message,
6332
                                'warning'
6333
                            )
6334
                        );
6335
6336
                        if (!api_is_allowed_to_edit(false, true)) {
6337
                            $this->redirectHome();
6338
                        }
6339
                    }
6340
6341
                    if (!empty($row['enddate_assig']) &&
6342
                        time() > strtotime($row['enddate_assig']) &&
6343
                        0 == $row['delayedsubmit']
6344
                    ) {
6345
                        $message = get_lang(
6346
                                'TheDeadlineHasBeenCompleted'
6347
                            ).': '.api_get_local_time($row['enddate_assig']);
6348
                        Display::addFlash(
6349
                            Display::return_message(
6350
                                $message,
6351
                                'warning'
6352
                            )
6353
                        );
6354
                        if (!api_is_allowed_to_edit(false, true)) {
6355
                            $this->redirectHome();
6356
                        }
6357
                    }
6358
6359
                    if (!empty($row['max_version']) && $row['version'] >= $row['max_version']) {
6360
                        $message = get_lang('You have exceeded the number of versions allowed');
6361
                        Display::addFlash(
6362
                            Display::return_message(
6363
                                $message,
6364
                                'warning'
6365
                            )
6366
                        );
6367
                        if (!api_is_allowed_to_edit(false, true)) {
6368
                            $this->redirectHome();
6369
                        }
6370
                    }
6371
6372
                    if (!empty($row['max_text']) && $row['max_text'] <= self::word_count(
6373
                            $row['content']
6374
                        )) {
6375
                        $message = get_lang('HasReachedMaxNumber of words');
6376
                        Display::addFlash(
6377
                            Display::return_message(
6378
                                $message,
6379
                                'warning'
6380
                            )
6381
                        );
6382
                        if (!api_is_allowed_to_edit(false, true)) {
6383
                            $this->redirectHome();
6384
                        }
6385
                    }
6386
6387
                    if (!empty($row['task'])) {
6388
                        //previous change 0 by text
6389
                        if (!empty($row['startdate_assig'])) {
6390
                            $message_task_startdate = get_lang('No');
6391
                        } else {
6392
                            $message_task_startdate = api_get_local_time(
6393
                                $row['startdate_assig']
6394
                            );
6395
                        }
6396
6397
                        if (!empty($row['enddate_assig'])) {
6398
                            $message_task_enddate = get_lang('No');
6399
                        } else {
6400
                            $message_task_enddate = api_get_local_time(
6401
                                $row['enddate_assig']
6402
                            );
6403
                        }
6404
6405
                        if (0 == $row['delayedsubmit']) {
6406
                            $message_task_delayedsubmit = get_lang('No');
6407
                        } else {
6408
                            $message_task_delayedsubmit = get_lang('Yes');
6409
                        }
6410
6411
                        if (0 == $row['max_version']) {
6412
                            $message_task_max_version = get_lang('No');
6413
                        } else {
6414
                            $message_task_max_version = $row['max_version'];
6415
                        }
6416
6417
                        if (0 == $row['max_text']) {
6418
                            $message_task_max_text = get_lang('No');
6419
                        } else {
6420
                            $message_task_max_text = $row['max_text'];
6421
                        }
6422
6423
                        // Comp message
6424
                        $message_task = '<b>'.get_lang(
6425
                                'Description of the assignment'
6426
                            ).'</b><p>'.$row['task'].'</p><hr>';
6427
                        $message_task .= '<p>'.get_lang(
6428
                                'Start Date'
6429
                            ).': '.$message_task_startdate.'</p>';
6430
                        $message_task .= '<p>'.get_lang(
6431
                                'End Date'
6432
                            ).': '.$message_task_enddate;
6433
                        $message_task .= ' ('.get_lang(
6434
                                'Allow delayed sending'
6435
                            ).') '.$message_task_delayedsubmit.'</p>';
6436
                        $message_task .= '<p>'.get_lang(
6437
                                'OtherSettings'
6438
                            ).': '.get_lang(
6439
                                'Maximum number of versions'
6440
                            ).': '.$message_task_max_version;
6441
                        $message_task .= ' '.get_lang(
6442
                                'Maximum number of words'
6443
                            ).': '.$message_task_max_text;
6444
                        // Display message
6445
                        Display::addFlash(
6446
                            Display::return_message(
6447
                                $message_task
6448
                            )
6449
                        );
6450
                    }
6451
6452
                    $feedback_message = '';
6453
                    if ($row['progress'] == $row['fprogress1'] && !empty($row['fprogress1'])) {
6454
                        $feedback_message = '<b>'.get_lang(
6455
                                'Feedback'
6456
                            ).'</b><p>'.api_htmlentities(
6457
                                $row['feedback1']
6458
                            ).'</p>';
6459
                    } elseif ($row['progress'] == $row['fprogress2'] && !empty($row['fprogress2'])) {
6460
                        $feedback_message = '<b>'.get_lang(
6461
                                'Feedback'
6462
                            ).'</b><p>'.api_htmlentities(
6463
                                $row['feedback2']
6464
                            ).'</p>';
6465
                    } elseif ($row['progress'] == $row['fprogress3'] && !empty($row['fprogress3'])) {
6466
                        $feedback_message = '<b>'.get_lang(
6467
                                'Feedback'
6468
                            ).'</b><p>'.api_htmlentities(
6469
                                $row['feedback3']
6470
                            ).'</p>';
6471
                    }
6472
6473
                    if (!empty($feedback_message)) {
6474
                        Display::addFlash(
6475
                            Display::return_message(
6476
                                $feedback_message
6477
                            )
6478
                        );
6479
                    }
6480
6481
                    // Previous checking for concurrent editions
6482
                    if (0 == $row['is_editing']) {
6483
                        Display::addFlash(
6484
                            Display::return_message(
6485
                                get_lang('You have 20 minutes to edit this page. After this time, if you have not saved the page, another user will be able to edit it, and you might lose your changes')
6486
                            )
6487
                        );
6488
                        $time_edit = api_get_utc_datetime();
6489
                        $sql = 'UPDATE '.$tbl_wiki.' SET
6490
                                is_editing = "'.$userId.'",
6491
                                time_edit = "'.$time_edit.'"
6492
                                WHERE c_id = '.$course_id.' AND id="'.$row['id'].'"';
6493
                        Database::query($sql);
6494
                    } elseif ($row['is_editing'] != $userId) {
6495
                        $timestamp_edit = strtotime($row['time_edit']);
6496
                        $time_editing = time() - $timestamp_edit;
6497
                        $max_edit_time = 1200; // 20 minutes
6498
                        $rest_time = $max_edit_time - $time_editing;
6499
6500
                        $userinfo = api_get_user_info($row['is_editing']);
6501
                        if (false !== $userinfo) {
6502
                            $is_being_edited = get_lang(
6503
                                    'ThisPageisBeginedited by'
6504
                                ).' '.UserManager::getUserProfileLink(
6505
                                    $userinfo
6506
                                ).'
6507
                            '.get_lang(
6508
                                    'Please try again later. If the user who is currently editing the page does not save it, this page will be available to you around'
6509
                                ).' '.date("i", $rest_time).' '.get_lang(
6510
                                    'minutes'
6511
                                ).'';
6512
                        }
6513
6514
                        Display::addFlash(
6515
                            Display::return_message(
6516
                                $is_being_edited,
6517
                                'normal',
6518
                                false
6519
                            )
6520
                        );
6521
6522
                        $this->redirectHome();
6523
                    }
6524
6525
                    // Form.
6526
                    $url = api_get_self().'?action=edit&title='.urlencode(
6527
                            $page
6528
                        ).'&session_id='.api_get_session_id(
6529
                        ).'&group_id='.api_get_group_id().'&'.api_get_cidreq();
6530
                    $form = new FormValidator('wiki', 'post', $url);
6531
                    $form->addElement(
6532
                        'header',
6533
                        $icon_assignment.str_repeat(
6534
                            '&nbsp;',
6535
                            3
6536
                        ).api_htmlentities($title)
6537
                    );
6538
                    self::setForm($form, $row);
6539
                    $form->addElement('hidden', 'title');
6540
                    $form->addButtonSave(get_lang('Save'), 'SaveWikiChange');
6541
                    $row['title'] = $title;
6542
                    $row['page_id'] = $page_id;
6543
                    $row['reflink'] = $page;
6544
                    $row['content'] = $content;
6545
6546
                    $form->setDefaults($row);
6547
                    $form->display();
6548
6549
                    // Saving a change
6550
                    if ($form->validate()) {
6551
                        $versionFromSession = Session::read('_version');
6552
                        if (empty($_POST['title'])) {
6553
                            Display::addFlash(
6554
                                Display::return_message(
6555
                                    get_lang("Your changes have been saved. You still have to give a name to the page"),
6556
                                    'error'
6557
                                )
6558
                            );
6559
                        } elseif (!self::double_post($_POST['wpost_id'])) {
6560
                            //double post
6561
                        } elseif ('' != $_POST['version'] && 0 != $versionFromSession && $_POST['version'] != $versionFromSession) {
6562
                            //prevent concurrent users and double version
6563
                            Display::addFlash(
6564
                                Display::return_message(
6565
                                    get_lang("edited byAnotherUser"),
6566
                                    'error'
6567
                                )
6568
                            );
6569
                        } else {
6570
                            $returnMessage = self::save_wiki(
6571
                                $form->exportValues()
6572
                            );
6573
                            Display::addFlash(
6574
                                Display::return_message(
6575
                                    $returnMessage,
6576
                                    'confirmation'
6577
                                )
6578
                            );
6579
                        }
6580
                        $wikiData = self::getWikiData();
6581
                        $redirectUrl = $this->url.'&action=showpage&title='.$wikiData['reflink'].'&'.api_get_cidreq(
6582
                            );
6583
                        header('Location: '.$redirectUrl);
6584
                        exit;
6585
                    }
6586
                }
6587
            }
6588
        }
6589
    }
6590
6591
    /**
6592
     * Get history.
6593
     */
6594
    public function getHistory()
6595
    {
6596
        $tbl_wiki = $this->tbl_wiki;
6597
        $condition_session = $this->condition_session;
6598
        $groupfilter = $this->groupfilter;
6599
        $page = $this->page;
6600
        $course_id = $this->course_id;
6601
        $session_id = $this->session_id;
6602
        $userId = api_get_user_id();
6603
6604
        if (!$_GET['title']) {
6605
            Display::addFlash(
6606
                Display::return_message(
6607
                    get_lang("You must select a page first"),
6608
                    'error',
6609
                    false
6610
                )
6611
            );
6612
6613
            return;
6614
        }
6615
6616
        /* First, see the property visibility that is at the last register and
6617
        therefore we should select descending order.
6618
        But to give ownership to each record,
6619
        this is no longer necessary except for the title. TODO: check this*/
6620
6621
        $sql = 'SELECT * FROM '.$tbl_wiki.'
6622
                WHERE
6623
                    c_id = '.$course_id.' AND
6624
                    reflink="'.Database::escape_string($page).'" AND
6625
                    '.$groupfilter.$condition_session.'
6626
                ORDER BY id DESC';
6627
        $result = Database::query($sql);
6628
6629
        $KeyVisibility = null;
6630
        $KeyAssignment = null;
6631
        $KeyTitle = null;
6632
        $KeyUserId = null;
6633
        while ($row = Database::fetch_array($result)) {
6634
            $KeyVisibility = $row['visibility'];
6635
            $KeyAssignment = $row['assignment'];
6636
            $KeyTitle = $row['title'];
6637
            $KeyUserId = $row['user_id'];
6638
        }
6639
        $icon_assignment = null;
6640
        if (1 == $KeyAssignment) {
6641
            $icon_assignment = Display::return_icon(
6642
                'wiki_assignment.png',
6643
                get_lang('This page is an assignment proposed by a trainer'),
6644
                '',
6645
                ICON_SIZE_SMALL
6646
            );
6647
        } elseif (2 == $KeyAssignment) {
6648
            $icon_assignment = Display::return_icon(
6649
                'wiki_work.png',
6650
                get_lang('Learner paperExtra'),
6651
                '',
6652
                ICON_SIZE_SMALL
6653
            );
6654
        }
6655
6656
        // Second, show
6657
        //if the page is hidden and is a job only sees its author and professor
6658
        if (1 == $KeyVisibility ||
6659
            api_is_allowed_to_edit(false, true) ||
6660
            api_is_platform_admin() ||
6661
            (
6662
                2 == $KeyAssignment && 0 == $KeyVisibility &&
6663
                ($userId == $KeyUserId)
6664
            )
6665
        ) {
6666
            // We show the complete history
6667
            if (!isset($_POST['HistoryDifferences']) &&
6668
                !isset($_POST['HistoryDifferences2'])
6669
            ) {
6670
                $sql = 'SELECT * FROM '.$tbl_wiki.'
6671
                        WHERE
6672
                            c_id = '.$course_id.' AND
6673
                            reflink="'.Database::escape_string($page).'" AND
6674
                            '.$groupfilter.$condition_session.'
6675
                        ORDER BY id DESC';
6676
                $result = Database::query($sql);
6677
                $title = $_GET['title'];
6678
                $group_id = api_get_group_id();
6679
6680
                echo '<div id="wikititle">';
6681
                echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities(
6682
                        $KeyTitle
6683
                    );
6684
                echo '</div>';
6685
6686
                echo '<form id="differences" method="POST" action="index.php?'.api_get_cidreq(
6687
                    ).'&action=history&title='.api_htmlentities(
6688
                        urlencode($title)
6689
                    ).'&session_id='.api_htmlentities(
6690
                        $session_id
6691
                    ).'&group_id='.api_htmlentities($group_id).'">';
6692
6693
                echo '<ul style="list-style-type: none;">';
6694
                echo '<br/>';
6695
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.
6696
                    get_lang('Compare selected versions').' '.get_lang(
6697
                        'line by line'
6698
                    ).'</button>';
6699
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.
6700
                    get_lang('Compare selected versions').' '.get_lang(
6701
                        'word by word'
6702
                    ).'</button>';
6703
                echo '<br/><br/>';
6704
6705
                $counter = 0;
6706
                $total_versions = Database::num_rows($result);
6707
6708
                while ($row = Database::fetch_array($result)) {
6709
                    $userinfo = api_get_user_info($row['user_id']);
6710
                    $username = api_htmlentities(
6711
                        sprintf(get_lang('Login: %s'), $userinfo['username']),
6712
                        ENT_QUOTES
6713
                    );
6714
6715
                    echo '<li style="margin-bottom: 5px;">';
6716
                    (0 == $counter) ? $oldstyle = 'style="visibility: hidden;"' : $oldstyle = '';
6717
                    (0 == $counter) ? $newchecked = ' checked' : $newchecked = '';
6718
                    ($counter == $total_versions - 1) ? $newstyle = 'style="visibility: hidden;"' : $newstyle = '';
6719
                    (1 == $counter) ? $oldchecked = ' checked' : $oldchecked = '';
6720
                    echo '<input name="old" value="'.$row['id'].'" type="radio" '.$oldstyle.' '.$oldchecked.'/> ';
6721
                    echo '<input name="new" value="'.$row['id'].'" type="radio" '.$newstyle.' '.$newchecked.'/> ';
6722
                    echo '<a href="'.api_get_self(
6723
                        ).'?action=showpage&title='.api_htmlentities(
6724
                            urlencode($page)
6725
                        ).'&view='.$row['id'].'">';
6726
                    echo '<a href="'.api_get_self().'?'.api_get_cidreq(
6727
                        ).'&action=showpage&title='.api_htmlentities(
6728
                            urlencode($page)
6729
                        ).'&view='.$row['id'].'">';
6730
                    echo api_get_local_time(
6731
                        $row['dtime']
6732
                    );
6733
                    echo '</a>';
6734
                    echo ' ('.get_lang('Version').' '.$row['version'].')';
6735
                    echo ' '.get_lang('By').' ';
6736
                    if (false !== $userinfo) {
6737
                        echo UserManager::getUserProfileLink($userinfo);
6738
                    } else {
6739
                        echo get_lang('Anonymous').' ('.api_htmlentities(
6740
                                $row['user_ip']
6741
                            ).')';
6742
                    }
6743
                    echo ' ( '.get_lang('Progress').': '.api_htmlentities(
6744
                            $row['progress']
6745
                        ).'%, ';
6746
                    $comment = $row['comment'];
6747
                    if (!empty($comment)) {
6748
                        $comment = api_substr($comment, 0, 100);
6749
                        if (false !== $comment) {
6750
                            $comment = api_htmlentities($comment);
6751
                            echo get_lang('Comments').': '.$comment;
6752
                            if (api_strlen($row['comment']) > 100) {
6753
                                echo '... ';
6754
                            }
6755
                        }
6756
                    } else {
6757
                        echo get_lang('Comments').':  ---';
6758
                    }
6759
                    echo ' ) </li>';
6760
                    $counter++;
6761
                } //end while
6762
6763
                echo '<br/>';
6764
                echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.get_lang(
6765
                        'Compare selected versions'
6766
                    ).' '.get_lang('line by line').'</button>';
6767
                echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.get_lang(
6768
                        'Compare selected versions'
6769
                    ).' '.get_lang('word by word').'</button>';
6770
                echo '</ul></form>';
6771
            } else { // We show the differences between two versions
6772
                $version_old = [];
6773
                if (isset($_POST['old'])) {
6774
                    $sql_old = "SELECT * FROM $tbl_wiki
6775
                                WHERE c_id = $course_id AND id='".Database::escape_string(
6776
                            $_POST['old']
6777
                        )."'";
6778
                    $result_old = Database::query($sql_old);
6779
                    $version_old = Database::fetch_array($result_old);
6780
                }
6781
6782
                $sql_new = "SELECT * FROM $tbl_wiki
6783
                            WHERE
6784
                              c_id = $course_id AND
6785
                              id = '".Database::escape_string($_POST['new'])."'";
6786
                $result_new = Database::query($sql_new);
6787
                $version_new = Database::fetch_array($result_new);
6788
                $oldTime = isset($version_old['dtime']) ? api_get_local_time($version_old['dtime']) : null;
6789
                $oldContent = isset($version_old['content']) ? $version_old['content'] : null;
6790
6791
                if (isset($_POST['HistoryDifferences'])) {
6792
                    include 'diff.inc.php';
6793
                    //title
6794
                    echo '<div id="wikititle">'.api_htmlentities(
6795
                            $version_new['title']
6796
                        ).'
6797
                            <font size="-2"><i>('.get_lang('Changes in version').'</i>
6798
                            <font style="background-color:#aaaaaa">'.api_get_local_time($version_new['dtime']).'</font>
6799
                            <i>'.get_lang('old version of').'</i>
6800
                            <font style="background-color:#aaaaaa">'.$oldTime.'</font>
6801
                ) '.get_lang('Legend').':  <span class="diffAdded" >'.get_lang(
6802
                            'Group wikiDiffAddedLine'
6803
                        ).'</span>
6804
                <span class="diffDeleted" >'.get_lang(
6805
                            'Group wikiDiffDeletedLine'
6806
                        ).'</span> <span class="diffMoved">'.get_lang(
6807
                            'Group wikiDiffMovedLine'
6808
                        ).'</span></font>
6809
                </div>';
6810
                }
6811
                if (isset($_POST['HistoryDifferences2'])) {
6812
                    //title
6813
                    echo '<div id="wikititle">'.api_htmlentities(
6814
                            $version_new['title']
6815
                        ).'
6816
                        <font size="-2"><i>('.get_lang(
6817
                            'Changes in version'
6818
                        ).'</i> <font style="background-color:#aaaaaa">'.api_get_local_time($version_new['dtime']).'</font>
6819
                        <i>'.get_lang(
6820
                            'old version of'
6821
                        ).'</i> <font style="background-color:#aaaaaa">'.$oldTime.'</font>)
6822
                        '.get_lang(
6823
                            'Legend'
6824
                        ).':  <span class="diffAddedTex" >'.get_lang(
6825
                            'Group wikiDiffAddedTex'
6826
                        ).'</span>
6827
                        <span class="diffDeletedTex" >'.get_lang(
6828
                            'Group wikiDiffDeletedTex'
6829
                        ).'</span></font></div>';
6830
                }
6831
6832
                if (isset($_POST['HistoryDifferences'])) {
6833
                    echo '<table>'.diff(
6834
                            $oldContent,
6835
                            $version_new['content'],
6836
                            true,
6837
                            'format_table_line'
6838
                        ).'</table>'; // format_line mode is better for words
6839
                    echo '<br />';
6840
                    echo '<strong>'.get_lang(
6841
                            'Legend'
6842
                        ).'</strong><div class="diff">'."\n";
6843
                    echo '<table><tr>';
6844
                    echo '<td>';
6845
                    echo '</td><td>';
6846
                    echo '<span class="diffEqual" >'.get_lang(
6847
                            'Group wikiDiffUnchangedLine'
6848
                        ).'</span><br />';
6849
                    echo '<span class="diffAdded" >'.get_lang(
6850
                            'Group wikiDiffAddedLine'
6851
                        ).'</span><br />';
6852
                    echo '<span class="diffDeleted" >'.get_lang(
6853
                            'Group wikiDiffDeletedLine'
6854
                        ).'</span><br />';
6855
                    echo '<span class="diffMoved" >'.get_lang(
6856
                            'Group wikiDiffMovedLine'
6857
                        ).'</span><br />';
6858
                    echo '</td>';
6859
                    echo '</tr></table>';
6860
                }
6861
6862
                if (isset($_POST['HistoryDifferences2'])) {
6863
                    $lines1 = [strip_tags($oldContent)]; //without <> tags
6864
                    $lines2 = [
6865
                        strip_tags(
6866
                            $version_new['content']
6867
                        ),
6868
                    ]; //without <> tags
6869
                    $diff = new Text_Diff($lines1, $lines2);
6870
                    $renderer = new Text_Diff_Renderer_inline();
6871
                    echo '<style>del{background:#fcc}ins{background:#cfc}</style>'.$renderer->render(
6872
                            $diff
6873
                        ); // Code inline
6874
                    echo '<br />';
6875
                    echo '<strong>'.get_lang(
6876
                            'Legend'
6877
                        ).'</strong><div class="diff">'."\n";
6878
                    echo '<table><tr>';
6879
                    echo '<td>';
6880
                    echo '</td><td>';
6881
                    echo '<span class="diffAddedTex" >'.get_lang(
6882
                            'Group wikiDiffAddedTex'
6883
                        ).'</span><br />';
6884
                    echo '<span class="diffDeletedTex" >'.get_lang(
6885
                            'Group wikiDiffDeletedTex'
6886
                        ).'</span><br />';
6887
                    echo '</td>';
6888
                    echo '</tr></table>';
6889
                }
6890
            }
6891
        }
6892
    }
6893
6894
    /**
6895
     * Get stat tables.
6896
     */
6897
    public function getStatsTable()
6898
    {
6899
        $_course = $this->courseInfo;
6900
        $session_id = $this->session_id;
6901
        $groupId = $this->group_id;
6902
6903
        echo '<div class="actions">'.get_lang('More').'</div>';
6904
        echo '<table border="0">';
6905
        echo '  <tr>';
6906
        echo '    <td>';
6907
        echo '      <ul>';
6908
        //Submenu Most active users
6909
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mactiveusers&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6910
                'Most active users'
6911
            ).'</a></li>';
6912
        //Submenu Most visited pages
6913
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mvisited&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6914
                'Most visited pages'
6915
            ).'</a></li>';
6916
        //Submenu Most changed pages
6917
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=mostchanged&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6918
                'Most changed pages'
6919
            ).'</a></li>';
6920
        echo '      </ul>';
6921
        echo '    </td>';
6922
        echo '    <td>';
6923
        echo '      <ul>';
6924
        // Submenu Orphaned pages
6925
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=orphaned&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6926
                'Orphaned pages'
6927
            ).'</a></li>';
6928
        // Submenu Wanted pages
6929
        echo '        <li><a href="index.php?cidReq='.$_course['code'].'&action=wanted&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6930
                'Wanted pages'
6931
            ).'</a></li>';
6932
        // Submenu Most linked pages
6933
        echo '<li><a href="index.php?cidReq='.$_course['code'].'&action=mostlinked&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6934
                'Pages most linked'
6935
            ).'</a></li>';
6936
        echo '</ul>';
6937
        echo '</td>';
6938
        echo '<td style="vertical-align:top">';
6939
        echo '<ul>';
6940
        // Submenu Statistics
6941
        if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
6942
            echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=statistics&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang(
6943
                    'Statistics'
6944
                ).'</a></li>';
6945
        }
6946
        echo '      </ul>';
6947
        echo '    </td>';
6948
        echo '  </tr>';
6949
        echo '</table>';
6950
    }
6951
6952
    /**
6953
     * Kind of controller.
6954
     *
6955
     * @param string $action
6956
     */
6957
    public function handleAction($action)
6958
    {
6959
        $page = $this->page;
6960
        switch ($action) {
6961
            case 'export_to_pdf':
6962
                if (isset($_GET['wiki_id'])) {
6963
                    self::export_to_pdf($_GET['wiki_id'], api_get_course_id());
6964
                    break;
6965
                }
6966
                break;
6967
            case 'export2doc':
6968
                if (isset($_GET['wiki_id'])) {
6969
                    $export2doc = self::export2doc($_GET['wiki_id']);
6970
                    if ($export2doc) {
6971
                        Display::addFlash(
6972
                            Display::return_message(
6973
                                get_lang('The page has been exported to the document tool'),
6974
                                'confirmation',
6975
                                false
6976
                            )
6977
                        );
6978
                    }
6979
                }
6980
                break;
6981
            case 'restorepage':
6982
                self::restorePage();
6983
                break;
6984
            case 'more':
6985
                self::getStatsTable();
6986
                break;
6987
            case 'statistics':
6988
                self::getStats();
6989
                break;
6990
            case 'mactiveusers':
6991
                self::getActiveUsers($action);
6992
                break;
6993
            case 'usercontrib':
6994
                self::getUserContributions($_GET['user_id'], $action);
6995
                break;
6996
            case 'mostchanged':
6997
                $this->getMostChangedPages($action);
6998
                break;
6999
            case 'mvisited':
7000
                self::getMostVisited();
7001
                break;
7002
            case 'wanted':
7003
                $this->getWantedPages();
7004
                break;
7005
            case 'orphaned':
7006
                self::getOrphaned();
7007
                break;
7008
            case 'mostlinked':
7009
                self::getMostLinked();
7010
                break;
7011
            case 'delete':
7012
                self::deletePageWarning($page);
7013
                break;
7014
            case 'deletewiki':
7015
                $title = '<div class="actions">'.get_lang(
7016
                        'DeleteGroup wiki'
7017
                    ).'</div>';
7018
                if (api_is_allowed_to_edit(
7019
                        false,
7020
                        true
7021
                    ) || api_is_platform_admin()) {
7022
                    $message = get_lang('ConfirmDeleteGroup wiki');
7023
                    $message .= '<p>
7024
                        <a href="index.php?'.api_get_cidreq().'">'.get_lang(
7025
                            'No'
7026
                        ).'</a>
7027
                        &nbsp;&nbsp;|&nbsp;&nbsp;
7028
                        <a href="'.api_get_self().'?'.api_get_cidreq(
7029
                        ).'&action=deletewiki&delete=yes">'.
7030
                        get_lang('Yes').'</a>
7031
                    </p>';
7032
7033
                    if (!isset($_GET['delete'])) {
7034
                        Display::addFlash(
7035
                            $title.Display::return_message(
7036
                                $message,
7037
                                'warning',
7038
                                false
7039
                            )
7040
                        );
7041
                    }
7042
                } else {
7043
                    Display::addFlash(
7044
                        Display::return_message(
7045
                            get_lang("OnlyAdminDeleteGroup wiki"),
7046
                            'normal',
7047
                            false
7048
                        )
7049
                    );
7050
                }
7051
7052
                if (api_is_allowed_to_edit(
7053
                        false,
7054
                        true
7055
                    ) || api_is_platform_admin()) {
7056
                    if (isset($_GET['delete']) && 'yes' == $_GET['delete']) {
7057
                        $return_message = self::delete_wiki();
7058
                        Display::addFlash(
7059
                            Display::return_message(
7060
                                $return_message,
7061
                                'confirmation',
7062
                                false
7063
                            )
7064
                        );
7065
                        $this->redirectHome();
7066
                    }
7067
                }
7068
                break;
7069
            case 'searchpages':
7070
                self::getSearchPages($action);
7071
                break;
7072
            case 'links':
7073
                self::getLinks($page);
7074
                break;
7075
            case 'addnew':
7076
                if (0 != api_get_session_id() && false == api_is_allowed_to_session_edit(
7077
                        false,
7078
                        true
7079
                    )) {
7080
                    api_not_allowed();
7081
                }
7082
                $groupInfo = GroupManager::get_group_properties(
7083
                    api_get_group_id()
7084
                );
7085
                echo '<div class="actions">'.get_lang('Add new page').'</div>';
7086
                echo '<br/>';
7087
                //first, check if page index was created. chektitle=false
7088
                if (self::checktitle('index')) {
7089
                    if (api_is_allowed_to_edit(false, true) ||
7090
                        api_is_platform_admin() ||
7091
                        GroupManager::isUserInGroup(
7092
                            api_get_user_id(),
7093
                            api_get_group_entity()
7094
                        ) ||
7095
                        api_is_allowed_in_course()
7096
                    ) {
7097
                        Display::addFlash(
7098
                            Display::return_message(
7099
                                get_lang('To start Group wiki go and edit Main page'),
7100
                                'normal',
7101
                                false
7102
                            )
7103
                        );
7104
                    } else {
7105
                        Display::addFlash(
7106
                            Display::return_message(
7107
                                get_lang('This Group wiki is frozen so far. A trainer must start it.'),
7108
                                'normal',
7109
                                false
7110
                            )
7111
                        );
7112
                    }
7113
                } elseif (0 == self::check_addnewpagelock(
7114
                    ) && (false == api_is_allowed_to_edit(
7115
                            false,
7116
                            true
7117
                        ) || false == api_is_platform_admin())) {
7118
                    Display::addFlash(
7119
                        Display::return_message(
7120
                            get_lang('The add option has been temporarily disabled by the trainer'),
7121
                            'error',
7122
                            false
7123
                        )
7124
                    );
7125
                } else {
7126
                    $groupinfo = GroupManager::get_group_properties(
7127
                        api_get_group_id()
7128
                    );
7129
                    if (api_is_allowed_to_edit(false, true) ||
7130
                        api_is_platform_admin() ||
7131
                        GroupManager::isUserInGroup(
7132
                            api_get_user_id(),
7133
                            api_get_group_entity
7134
                        ) ||
7135
                        0 == $_GET['group_id']
7136
                    ) {
7137
                        self::display_new_wiki_form();
7138
                    } else {
7139
                        Display::addFlash(
7140
                            Display::return_message(
7141
                                get_lang('Trainers and members of this group only can add pages to the group Wiki'),
7142
                                'normal',
7143
                                false
7144
                            )
7145
                        );
7146
                    }
7147
                }
7148
                break;
7149
            case 'show':
7150
                self::display_wiki_entry($page);
7151
                break;
7152
            case 'showpage':
7153
                self::display_wiki_entry($page);
7154
                break;
7155
            case 'edit':
7156
                self::editPage();
7157
                break;
7158
            case 'history':
7159
                self::getHistory();
7160
                break;
7161
            case 'recentchanges':
7162
                self::recentChanges($page, $action);
7163
                break;
7164
            case 'allpages':
7165
                self::allPages($action);
7166
                break;
7167
            case 'discuss':
7168
                self::getDiscuss($page);
7169
                break;
7170
            case 'export_to_doc_file':
7171
                self::exportTo($_GET['id'], 'odt');
7172
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
7173
                break;
7174
        }
7175
    }
7176
7177
    /**
7178
     * Redirect to home.
7179
     */
7180
    public function redirectHome()
7181
    {
7182
        $redirectUrl = $this->url.'&action=showpage&title=index';
7183
        header('Location: '.$redirectUrl.'&'.api_get_cidreq());
7184
        exit;
7185
    }
7186
7187
    /**
7188
     * Export wiki content in a ODF.
7189
     *
7190
     * @param int $id
7191
     * @param string int
7192
     *
7193
     * @return bool
7194
     */
7195
    public function exportTo($id, $format = 'doc')
7196
    {
7197
        $data = self::getWikiDataFromDb($id);
7198
7199
        if (isset($data['content']) && !empty($data['content'])) {
7200
            Export::htmlToOdt($data['content'], $data['reflink'], $format);
7201
        }
7202
7203
        return false;
7204
    }
7205
}
7206