lib.php 25.7 KB
Newer Older
1
<?php
2
// This file is part of Moodle - http://moodle.org/
Petr Skoda's avatar
Petr Skoda committed
3
4
5
6
7
8
9
10
11
12
13
14
15
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
Petr Skoda's avatar
Petr Skoda committed
16

Petr Skoda's avatar
Petr Skoda committed
17
18
19
/**
 * Book module core interaction API
 *
20
21
 * @package    mod_book
 * @copyright  2004-2011 Petr Skoda {@link http://skodak.org}
Petr Skoda's avatar
Petr Skoda committed
22
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
Petr Skoda's avatar
Petr Skoda committed
24

Petr Skoda's avatar
Petr Skoda committed
25
defined('MOODLE_INTERNAL') || die;
Petr Skoda's avatar
Petr Skoda committed
26

27
28
29
30
31
/**
 * Returns list of available numbering types
 * @return array
 */
function book_get_numbering_types() {
32
    global $CFG; // required for the include
33

34
    require_once(__DIR__.'/locallib.php');
35

36
37
38
39
40
41
    return array (
        BOOK_NUM_NONE       => get_string('numbering0', 'mod_book'),
        BOOK_NUM_NUMBERS    => get_string('numbering1', 'mod_book'),
        BOOK_NUM_BULLETS    => get_string('numbering2', 'mod_book'),
        BOOK_NUM_INDENTED   => get_string('numbering3', 'mod_book')
    );
42
43
}

44
45
46
47
48
/**
 * Returns list of available navigation link types.
 * @return array
 */
function book_get_nav_types() {
49
    require_once(__DIR__.'/locallib.php');
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

    return array (
        BOOK_LINK_TOCONLY   => get_string('navtoc', 'mod_book'),
        BOOK_LINK_IMAGE     => get_string('navimages', 'mod_book'),
        BOOK_LINK_TEXT      => get_string('navtext', 'mod_book'),
    );
}

/**
 * Returns list of available navigation link CSS classes.
 * @return array
 */
function book_get_nav_classes() {
    return array ('navtoc', 'navimages', 'navtext');
}

Petr Skoda's avatar
Petr Skoda committed
66
67
68
69
70
71
72
/**
 * Add book instance.
 *
 * @param stdClass $data
 * @param stdClass $mform
 * @return int new book instance id
 */
73
function book_add_instance($data, $mform) {
Petr Skoda's avatar
Petr Skoda committed
74
    global $DB;
Petr Skoda's avatar
Petr Skoda committed
75

76
77
78
79
    $data->timecreated = time();
    $data->timemodified = $data->timecreated;
    if (!isset($data->customtitles)) {
        $data->customtitles = 0;
80
    }
Petr Skoda's avatar
Petr Skoda committed
81

82
83
84
85
86
87
    $id = $DB->insert_record('book', $data);

    $completiontimeexpected = !empty($data->completionexpected) ? $data->completionexpected : null;
    \core_completion\api::update_completion_date_event($data->coursemodule, 'book', $id, $completiontimeexpected);

    return $id;
Petr Skoda's avatar
Petr Skoda committed
88
89
}

Petr Skoda's avatar
Petr Skoda committed
90
91
92
93
94
95
96
/**
 * Update book instance.
 *
 * @param stdClass $data
 * @param stdClass $mform
 * @return bool true
 */
97
function book_update_instance($data, $mform) {
Petr Skoda's avatar
Petr Skoda committed
98
    global $DB;
Petr Skoda's avatar
Petr Skoda committed
99

100
101
102
103
    $data->timemodified = time();
    $data->id = $data->instance;
    if (!isset($data->customtitles)) {
        $data->customtitles = 0;
104
    }
Petr Skoda's avatar
Petr Skoda committed
105

106
    $DB->update_record('book', $data);
Petr Skoda's avatar
Petr Skoda committed
107

108
109
110
    $book = $DB->get_record('book', array('id'=>$data->id));
    $DB->set_field('book', 'revision', $book->revision+1, array('id'=>$book->id));

111
112
113
    $completiontimeexpected = !empty($data->completionexpected) ? $data->completionexpected : null;
    \core_completion\api::update_completion_date_event($data->coursemodule, 'book', $book->id, $completiontimeexpected);

Petr Skoda's avatar
Petr Skoda committed
114
    return true;
Petr Skoda's avatar
Petr Skoda committed
115
116
}

Petr Skoda's avatar
Petr Skoda committed
117
/**
118
 * Delete book instance by activity id
Petr Skoda's avatar
Petr Skoda committed
119
120
121
122
 *
 * @param int $id
 * @return bool success
 */
Petr Skoda's avatar
Petr Skoda committed
123
function book_delete_instance($id) {
Petr Skoda's avatar
Petr Skoda committed
124
    global $DB;
Petr Skoda's avatar
Petr Skoda committed
125

Petr Skoda's avatar
Petr Skoda committed
126
    if (!$book = $DB->get_record('book', array('id'=>$id))) {
Petr Skoda's avatar
Petr Skoda committed
127
128
129
        return false;
    }

130
131
132
    $cm = get_coursemodule_from_instance('book', $id);
    \core_completion\api::update_completion_date_event($cm->id, 'book', $id, null);

Petr Skoda's avatar
Petr Skoda committed
133
134
    $DB->delete_records('book_chapters', array('bookid'=>$book->id));
    $DB->delete_records('book', array('id'=>$book->id));
Petr Skoda's avatar
Petr Skoda committed
135

Petr Skoda's avatar
Petr Skoda committed
136
    return true;
Petr Skoda's avatar
Petr Skoda committed
137
138
}

139
140
141
/**
 * Given a course and a time, this module should find recent activity
 * that has occurred in book activities and print it out.
142
143
144
145
146
 *
 * @param stdClass $course
 * @param bool $viewfullnames
 * @param int $timestart
 * @return bool true if there was output, or false is there was none
147
 */
148
function book_print_recent_activity($course, $viewfullnames, $timestart) {
Petr Skoda's avatar
Petr Skoda committed
149
150
151
    return false;  //  True if anything was printed, otherwise false
}

152
153
154
155
156
157
/**
 * This function is used by the reset_course_userdata function in moodlelib.
 * @param $data the data submitted from the reset course.
 * @return array status array
 */
function book_reset_userdata($data) {
158
    global $DB;
159
160
161
    // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
    // See MDL-9367.

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
    $status = [];

    if (!empty($data->reset_book_tags)) {
        // Loop through the books and remove the tags from the chapters.
        if ($books = $DB->get_records('book', array('course' => $data->courseid))) {
            foreach ($books as $book) {
                if (!$cm = get_coursemodule_from_instance('book', $book->id)) {
                    continue;
                }

                $context = context_module::instance($cm->id);
                core_tag_tag::delete_instances('mod_book', null, $context->id);
            }
        }


        $status[] = [
            'component' => get_string('modulenameplural', 'book'),
            'item' => get_string('tagsdeleted', 'book'),
            'error' => false
        ];
    }

    return $status;
}

/**
 * The elements to add the course reset form.
 *
 * @param moodleform $mform
 */
function book_reset_course_form_definition(&$mform) {
    $mform->addElement('header', 'bookheader', get_string('modulenameplural', 'book'));
    $mform->addElement('checkbox', 'reset_book_tags', get_string('removeallbooktags', 'book'));
196
197
}

198
199
200
201
202
/**
 * No cron in book.
 *
 * @return bool
 */
Petr Skoda's avatar
Petr Skoda committed
203
204
205
206
function book_cron () {
    return true;
}

207
208
209
/**
 * No grading in book.
 *
210
 * @param int $bookid
211
212
 * @return null
 */
Petr Skoda's avatar
Petr Skoda committed
213
function book_grades($bookid) {
Petr Skoda's avatar
Petr Skoda committed
214
    return null;
Petr Skoda's avatar
Petr Skoda committed
215
216
}

217
218
219
/**
 * This function returns if a scale is being used by one book
 * it it has support for grading and scales. Commented code should be
Petr Skoda's avatar
Petr Skoda committed
220
 * modified if necessary. See book, glossary or journal modules
221
 * as reference.
Petr Skoda's avatar
Petr Skoda committed
222
 *
223
224
 * @param int $bookid
 * @param int $scaleid
225
226
 * @return boolean True if the scale is used by any journal
 */
227
function book_scale_used($bookid, $scaleid) {
228
    return false;
Petr Skoda's avatar
Petr Skoda committed
229
230
}

231
/**
Petr Skoda's avatar
Petr Skoda committed
232
 * Checks if scale is being used by any instance of book
233
234
 *
 * This is used to find out if scale used anywhere
Petr Skoda's avatar
Petr Skoda committed
235
 *
236
237
 * @param int $scaleid
 * @return bool true if the scale is used by any book
238
 */
Petr Skoda's avatar
Petr Skoda committed
239
function book_scale_used_anywhere($scaleid) {
240
241
    return false;
}
242

243
244
/**
 * Return read actions.
245
246
247
248
249
 *
 * Note: This is not used by new logging system. Event with
 *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
 *       be considered as view action.
 *
250
251
 * @return array
 */
252
function book_get_view_actions() {
253
    global $CFG; // necessary for includes
254

255
    $return = array('view', 'view all');
256

257
    $plugins = core_component::get_plugin_list('booktool');
258
    foreach ($plugins as $plugin => $dir) {
259
260
261
262
263
        if (file_exists("$dir/lib.php")) {
            require_once("$dir/lib.php");
        }
        $function = 'booktool_'.$plugin.'_get_view_actions';
        if (function_exists($function)) {
264
            if ($actions = $function()) {
265
266
267
268
269
270
                $return = array_merge($return, $actions);
            }
        }
    }

    return $return;
271
272
}

273
274
/**
 * Return write actions.
275
276
277
278
279
 *
 * Note: This is not used by new logging system. Event with
 *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
 *       will be considered as post action.
 *
280
281
 * @return array
 */
282
function book_get_post_actions() {
283
    global $CFG; // necessary for includes
284

285
    $return = array('update');
286

287
    $plugins = core_component::get_plugin_list('booktool');
288
    foreach ($plugins as $plugin => $dir) {
289
290
291
292
293
        if (file_exists("$dir/lib.php")) {
            require_once("$dir/lib.php");
        }
        $function = 'booktool_'.$plugin.'_get_post_actions';
        if (function_exists($function)) {
Petr Skoda's avatar
Petr Skoda committed
294
            if ($actions = $function()) {
295
296
297
298
299
300
                $return = array_merge($return, $actions);
            }
        }
    }

    return $return;
301
}
Petr Skoda's avatar
Petr Skoda committed
302
303
304
305
306
307
308
309
310

/**
 * Supported features
 *
 * @param string $feature FEATURE_xx constant for requested feature
 * @return mixed True if module supports feature, false if not, null if doesn't know
 */
function book_supports($feature) {
    switch($feature) {
311
        case FEATURE_MOD_ARCHETYPE:           return MOD_ARCHETYPE_RESOURCE;
Petr Skoda's avatar
Petr Skoda committed
312
313
314
        case FEATURE_GROUPS:                  return false;
        case FEATURE_GROUPINGS:               return false;
        case FEATURE_MOD_INTRO:               return true;
Petr Skoda's avatar
Petr Skoda committed
315
        case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
316
317
        case FEATURE_GRADE_HAS_GRADE:         return false;
        case FEATURE_GRADE_OUTCOMES:          return false;
Petr Skoda's avatar
Petr Skoda committed
318
        case FEATURE_BACKUP_MOODLE2:          return true;
319
        case FEATURE_SHOW_DESCRIPTION:        return true;
Petr Skoda's avatar
Petr Skoda committed
320
321
322
323

        default: return null;
    }
}
Petr Skoda's avatar
Petr Skoda committed
324
325
326
327

/**
 * Adds module specific settings to the settings block
 *
328
 * @param settings_navigation $settingsnav The settings navigation object
Petr Skoda's avatar
Petr Skoda committed
329
 * @param navigation_node $booknode The node to add module settings to
Petr Skoda's avatar
Petr Skoda committed
330
331
332
 * @return void
 */
function book_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $booknode) {
333
    global $USER, $PAGE, $OUTPUT;
Petr Skoda's avatar
Petr Skoda committed
334

335
336
337
338
    if ($booknode->children->count() > 0) {
        $firstkey = $booknode->children->get_key_list()[0];
    } else {
        $firstkey = null;
Petr Skoda's avatar
Petr Skoda committed
339
340
    }

Petr Skoda's avatar
Petr Skoda committed
341
342
    $params = $PAGE->url->params();

343
344
    if ($PAGE->cm->modname === 'book' and !empty($params['id']) and !empty($params['chapterid'])
            and has_capability('mod/book:edit', $PAGE->cm->context)) {
345
346
347
348
349
350
351
352
        if (!empty($USER->editing)) {
            $string = get_string("turneditingoff");
            $edit = '0';
        } else {
            $string = get_string("turneditingon");
            $edit = '1';
        }
        $url = new moodle_url('/mod/book/view.php', array('id'=>$params['id'], 'chapterid'=>$params['chapterid'], 'edit'=>$edit, 'sesskey'=>sesskey()));
353
354
        $editnode = navigation_node::create($string, $url, navigation_node::TYPE_SETTING);
        $booknode->add_node($editnode, $firstkey);
355
        $PAGE->set_button($OUTPUT->single_button($url, $string));
356
    }
357
358
359
360
361
362
363
364
365
366
367

    $plugins = core_component::get_plugin_list('booktool');
    foreach ($plugins as $plugin => $dir) {
        if (file_exists("$dir/lib.php")) {
            require_once("$dir/lib.php");
        }
        $function = 'booktool_'.$plugin.'_extend_settings_navigation';
        if (function_exists($function)) {
            $function($settingsnav, $booknode);
        }
    }
Petr Skoda's avatar
Petr Skoda committed
368
369
}

Petr Skoda's avatar
Petr Skoda committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384

/**
 * Lists all browsable file areas
 * @param object $course
 * @param object $cm
 * @param object $context
 * @return array
 */
function book_get_file_areas($course, $cm, $context) {
    $areas = array();
    $areas['chapter'] = get_string('chapters', 'mod_book');
    return $areas;
}

/**
385
 * File browsing support for book module chapter area.
Petr Skoda's avatar
Petr Skoda committed
386
387
388
389
390
391
392
393
394
395
396
397
398
399
 * @param object $browser
 * @param object $areas
 * @param object $course
 * @param object $cm
 * @param object $context
 * @param string $filearea
 * @param int $itemid
 * @param string $filepath
 * @param string $filename
 * @return object file_info instance or null if not found
 */
function book_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
    global $CFG, $DB;

400
    // note: 'intro' area is handled in file_browser automatically
Petr Skoda's avatar
Petr Skoda committed
401
402
403
404
405
406
407
408
409

    if (!has_capability('mod/book:read', $context)) {
        return null;
    }

    if ($filearea !== 'chapter') {
        return null;
    }

410
    require_once(__DIR__.'/locallib.php');
Petr Skoda's avatar
Petr Skoda committed
411
412

    if (is_null($itemid)) {
413
        return new book_file_info($browser, $course, $cm, $context, $areas, $filearea);
Petr Skoda's avatar
Petr Skoda committed
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
    }

    $fs = get_file_storage();
    $filepath = is_null($filepath) ? '/' : $filepath;
    $filename = is_null($filename) ? '.' : $filename;
    if (!$storedfile = $fs->get_file($context->id, 'mod_book', $filearea, $itemid, $filepath, $filename)) {
        return null;
    }

    // modifications may be tricky - may cause caching problems
    $canwrite = has_capability('mod/book:edit', $context);

    $chaptername = $DB->get_field('book_chapters', 'title', array('bookid'=>$cm->instance, 'id'=>$itemid));
    $chaptername = format_string($chaptername, true, array('context'=>$context));

    $urlbase = $CFG->wwwroot.'/pluginfile.php';
    return new file_info_stored($browser, $context, $storedfile, $urlbase, $chaptername, true, true, $canwrite, false);
}

Petr Skoda's avatar
Petr Skoda committed
433
434
435
/**
 * Serves the book attachments. Implements needed access control ;-)
 *
436
437
438
439
440
441
442
 * @param stdClass $course course object
 * @param cm_info $cm course module object
 * @param context $context context object
 * @param string $filearea file area
 * @param array $args extra arguments
 * @param bool $forcedownload whether or not force download
 * @param array $options additional options affecting the file serving
443
 * @return bool false if file not found, does not return if found - just send the file
Petr Skoda's avatar
Petr Skoda committed
444
 */
445
function book_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
446
    global $CFG, $DB;
Petr Skoda's avatar
Petr Skoda committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475

    if ($context->contextlevel != CONTEXT_MODULE) {
        return false;
    }

    require_course_login($course, true, $cm);

    if ($filearea !== 'chapter') {
        return false;
    }

    if (!has_capability('mod/book:read', $context)) {
        return false;
    }

    $chid = (int)array_shift($args);

    if (!$book = $DB->get_record('book', array('id'=>$cm->instance))) {
        return false;
    }

    if (!$chapter = $DB->get_record('book_chapters', array('id'=>$chid, 'bookid'=>$book->id))) {
        return false;
    }

    if ($chapter->hidden and !has_capability('mod/book:viewhiddenchapters', $context)) {
        return false;
    }

476
477
478
479
    // Download the contents of a chapter as an html file.
    if ($args[0] == 'index.html') {
        $filename = "index.html";

480
481
482
483
484
485
486
487
488
489
        // We need to rewrite the pluginfile URLs so the media filters can work.
        $content = file_rewrite_pluginfile_urls($chapter->content, 'webservice/pluginfile.php', $context->id, 'mod_book', 'chapter',
                                                $chapter->id);
        $formatoptions = new stdClass;
        $formatoptions->noclean = true;
        $formatoptions->overflowdiv = true;
        $formatoptions->context = $context;

        $content = format_text($content, $chapter->contentformat, $formatoptions);

490
        // Remove @@PLUGINFILE@@/.
491
492
493
494
        $options = array('reverse' => true);
        $content = file_rewrite_pluginfile_urls($content, 'webservice/pluginfile.php', $context->id, 'mod_book', 'chapter',
                                                $chapter->id, $options);
        $content = str_replace('@@PLUGINFILE@@/', '', $content);
495
496
497
498

        $titles = "";
        // Format the chapter titles.
        if (!$book->customtitles) {
499
            require_once(__DIR__.'/locallib.php');
500
501
502
503
504
505
506
507
508
509
510
511
512
513
            $chapters = book_preload_chapters($book);

            if (!$chapter->subchapter) {
                $currtitle = book_get_chapter_title($chapter->id, $chapters, $book, $context);
                // Note that we can't use the $OUTPUT->heading() in WS_SERVER mode.
                $titles = "<h3>$currtitle</h3>";
            } else {
                $currtitle = book_get_chapter_title($chapters[$chapter->id]->parent, $chapters, $book, $context);
                $currsubtitle = book_get_chapter_title($chapter->id, $chapters, $book, $context);
                // Note that we can't use the $OUTPUT->heading() in WS_SERVER mode.
                $titles = "<h3>$currtitle</h3>";
                $titles .= "<h4>$currsubtitle</h4>";
            }
        }
Petr Skoda's avatar
Petr Skoda committed
514

515
        $content = $titles . $content;
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530

        send_file($content, $filename, 0, 0, true, true);
    } else {
        $fs = get_file_storage();
        $relativepath = implode('/', $args);
        $fullpath = "/$context->id/mod_book/chapter/$chid/$relativepath";
        if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
            return false;
        }

        // Nasty hack because we do not have file revisions in book yet.
        $lifetime = $CFG->filelifetime;
        if ($lifetime > 60 * 10) {
            $lifetime = 60 * 10;
        }
531

532
533
534
        // Finally send the file.
        send_stored_file($file, $lifetime, 0, $forcedownload, $options);
    }
Petr Skoda's avatar
Petr Skoda committed
535
536
537
538
539
540
541
542
543
544
545
546
547
548
}

/**
 * Return a list of page types
 *
 * @param string $pagetype current page type
 * @param stdClass $parentcontext Block's parent context
 * @param stdClass $currentcontext Current context of block
 * @return array
 */
function book_page_type_list($pagetype, $parentcontext, $currentcontext) {
    $module_pagetype = array('mod-book-*'=>get_string('page-mod-book-x', 'mod_book'));
    return $module_pagetype;
}
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572

/**
 * Export book resource contents
 *
 * @param  stdClass $cm     Course module object
 * @param  string $baseurl  Base URL for file downloads
 * @return array of file content
 */
function book_export_contents($cm, $baseurl) {
    global $DB;

    $contents = array();
    $context = context_module::instance($cm->id);

    $book = $DB->get_record('book', array('id' => $cm->instance), '*', MUST_EXIST);

    $fs = get_file_storage();

    $chapters = $DB->get_records('book_chapters', array('bookid' => $book->id), 'pagenum');

    $structure = array();
    $currentchapter = 0;

    foreach ($chapters as $chapter) {
573
        if ($chapter->hidden && !has_capability('mod/book:viewhiddenchapters', $context)) {
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
            continue;
        }

        // Generate the book structure.
        $thischapter = array(
            "title"     => format_string($chapter->title, true, array('context' => $context)),
            "href"      => $chapter->id . "/index.html",
            "level"     => 0,
            "subitems"  => array()
        );

        // Main chapter.
        if (!$chapter->subchapter) {
            $currentchapter = $chapter->pagenum;
            $structure[$currentchapter] = $thischapter;
        } else {
            // Subchapter.
            $thischapter['level'] = 1;
            $structure[$currentchapter]["subitems"][] = $thischapter;
        }

        // Export the chapter contents.

        // Main content (html).
        $filename = 'index.html';
        $chapterindexfile = array();
        $chapterindexfile['type']         = 'file';
        $chapterindexfile['filename']     = $filename;
        // Each chapter in a subdirectory.
        $chapterindexfile['filepath']     = "/{$chapter->id}/";
        $chapterindexfile['filesize']     = 0;
        $chapterindexfile['fileurl']      = moodle_url::make_webservice_pluginfile_url(
                    $context->id, 'mod_book', 'chapter', $chapter->id, '/', 'index.html')->out(false);
607
608
        $chapterindexfile['timecreated']  = $chapter->timecreated;
        $chapterindexfile['timemodified'] = $chapter->timemodified;
609
610
611
612
613
        $chapterindexfile['content']      = format_string($chapter->title, true, array('context' => $context));
        $chapterindexfile['sortorder']    = 0;
        $chapterindexfile['userid']       = null;
        $chapterindexfile['author']       = null;
        $chapterindexfile['license']      = null;
614
        $chapterindexfile['tags']         = \core_tag\external\util::get_item_tags('mod_book', 'book_chapters', $chapter->id);
615
        $chapterindexfile['ishidden']     = (bool) $chapter->hidden;
616
617
618
619
620
621
622
623
        $contents[] = $chapterindexfile;

        // Chapter files (images usually).
        $files = $fs->get_area_files($context->id, 'mod_book', 'chapter', $chapter->id, 'sortorder DESC, id ASC', false);
        foreach ($files as $fileinfo) {
            $file = array();
            $file['type']         = 'file';
            $file['filename']     = $fileinfo->get_filename();
624
            $file['filepath']     = "/{$chapter->id}" . $fileinfo->get_filepath();
625
626
627
628
629
630
631
632
633
634
            $file['filesize']     = $fileinfo->get_filesize();
            $file['fileurl']      = moodle_url::make_webservice_pluginfile_url(
                                        $context->id, 'mod_book', 'chapter', $chapter->id,
                                        $fileinfo->get_filepath(), $fileinfo->get_filename())->out(false);
            $file['timecreated']  = $fileinfo->get_timecreated();
            $file['timemodified'] = $fileinfo->get_timemodified();
            $file['sortorder']    = $fileinfo->get_sortorder();
            $file['userid']       = $fileinfo->get_userid();
            $file['author']       = $fileinfo->get_author();
            $file['license']      = $fileinfo->get_license();
635
636
637
638
639
            $file['mimetype']     = $fileinfo->get_mimetype();
            $file['isexternalfile'] = $fileinfo->is_external_file();
            if ($file['isexternalfile']) {
                $file['repositorytype'] = $fileinfo->get_repository_type();
            }
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
            $contents[] = $file;
        }
    }

    // First content is the structure in encoded JSON format.
    $structurefile = array();
    $structurefile['type']         = 'content';
    $structurefile['filename']     = 'structure';
    $structurefile['filepath']     = "/";
    $structurefile['filesize']     = 0;
    $structurefile['fileurl']      = null;
    $structurefile['timecreated']  = $book->timecreated;
    $structurefile['timemodified'] = $book->timemodified;
    $structurefile['content']      = json_encode(array_values($structure));
    $structurefile['sortorder']    = 0;
    $structurefile['userid']       = null;
    $structurefile['author']       = null;
    $structurefile['license']      = null;

    // Add it as first element.
    array_unshift($contents, $structurefile);

    return $contents;
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
}

/**
 * Mark the activity completed (if required) and trigger the course_module_viewed event.
 *
 * @param  stdClass $book       book object
 * @param  stdClass $chapter    chapter object
 * @param  bool $islaschapter   is the las chapter of the book?
 * @param  stdClass $course     course object
 * @param  stdClass $cm         course module object
 * @param  stdClass $context    context object
 * @since Moodle 3.0
 */
function book_view($book, $chapter, $islastchapter, $course, $cm, $context) {

    // First case, we are just opening the book.
    if (empty($chapter)) {
        \mod_book\event\course_module_viewed::create_from_book($book, $context)->trigger();

    } else {
        \mod_book\event\chapter_viewed::create_from_chapter($book, $context, $chapter)->trigger();

        if ($islastchapter) {
            // We cheat a bit here in assuming that viewing the last page means the user viewed the whole book.
            $completion = new completion_info($course);
            $completion->set_module_viewed($cm);
        }
    }
}
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716

/**
 * Check if the module has any update that affects the current user since a given time.
 *
 * @param  cm_info $cm course module data
 * @param  int $from the time to check updates from
 * @param  array $filter  if we need to check only specific updates
 * @return stdClass an object with the different type of areas indicating if they were updated or not
 * @since Moodle 3.2
 */
function book_check_updates_since(cm_info $cm, $from, $filter = array()) {
    global $DB;

    $context = $cm->context;
    $updates = new stdClass();
    if (!has_capability('mod/book:read', $context)) {
        return $updates;
    }
    $updates = course_check_module_updates_since($cm, $from, array('content'), $filter);

    $select = 'bookid = :id AND (timecreated > :since1 OR timemodified > :since2)';
    $params = array('id' => $cm->instance, 'since1' => $from, 'since2' => $from);
    if (!has_capability('mod/book:viewhiddenchapters', $context)) {
        $select .= ' AND hidden = 0';
    }
717
718
719
720
721
722
    $updates->entries = (object) array('updated' => false);
    $entries = $DB->get_records_select('book_chapters', $select, $params, '', 'id');
    if (!empty($entries)) {
        $updates->entries->updated = true;
        $updates->entries->itemids = array_keys($entries);
    }
723
724
725

    return $updates;
}
726
727
728
729
730
731
732
733
734

/**
 * Get icon mapping for font-awesome.
 */
function mod_book_get_fontawesome_icon_map() {
    return [
        'mod_book:chapter' => 'fa-bookmark-o',
        'mod_book:nav_prev' => 'fa-arrow-left',
        'mod_book:nav_prev_dis' => 'fa-angle-left',
735
        'mod_book:nav_sep' => 'fa-minus',
736
737
738
739
740
741
        'mod_book:add' => 'fa-plus',
        'mod_book:nav_next' => 'fa-arrow-right',
        'mod_book:nav_next_dis' => 'fa-angle-right',
        'mod_book:nav_exit' => 'fa-arrow-up',
    ];
}
742
743

/**
744
745
746
747
 * This function receives a calendar event and returns the action associated with it, or null if there is none.
 *
 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
 * is not displayed on the block.
748
 *
749
 * @param calendar_event $event
750
 * @param \core_calendar\action_factory $factory
751
 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
752
 * @return \core_calendar\local\event\entities\action_interface|null
753
 */
754
function mod_book_core_calendar_provide_event_action(calendar_event $event,
755
756
757
758
759
760
761
762
763
                                                     \core_calendar\action_factory $factory,
                                                     int $userid = 0) {
    global $USER;

    if (empty($userid)) {
        $userid = $USER->id;
    }

    $cm = get_fast_modinfo($event->courseid, $userid)->instances['book'][$event->instance];
764
765
766
767
768
769

    if (!$cm->uservisible) {
        // The module is not visible to the user for any reason.
        return null;
    }

770
771
    $context = context_module::instance($cm->id);

772
    if (!has_capability('mod/book:read', $context, $userid)) {
773
774
775
        return null;
    }

776
    $completion = new \completion_info($cm->get_course());
777

778
    $completiondata = $completion->get_data($cm, false, $userid);
779
780
781
782
783
784
785
786
787
788
789

    if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
        return null;
    }

    return $factory->create_instance(
        get_string('view'),
        new \moodle_url('/mod/book/view.php', ['id' => $cm->id]),
        1,
        true
    );
790
}