//chapter id not in this book!!!!
        error('Chapter not part of this book!');
    }
} else {
    $chapter = null;
}
//check all variables
unset($cmid);
unset($chapterid);
// =========================================================================
// security checks END
// =========================================================================
$mform = new book_chapter_edit_form(null, $cm);
if ($chapter) {
    $chapter->cmid = $cm->id;
    $mform->set_data($chapter);
} else {
    $mform->set_data(array('cmid' => $cm->id, 'pagenum' => $pagenum + 1, 'subchapter' => $subchapter));
}
/// If data submitted, then process and store.
if ($mform->is_cancelled()) {
    if (empty($chapter->id)) {
        redirect("view.php?id={$cm->id}");
    } else {
        redirect("view.php?id={$cm->id}&chapterid={$chapter->id}");
    }
} else {
    if ($data = $mform->get_data(false)) {
        if ($data->id) {
            if (!update_record('book_chapters', addslashes_recursive($data))) {
                error('Could not update your book');