require_capability('mod/journal:addentries', $context);
if (!($journal = $DB->get_record("journal", array("id" => $cm->instance)))) {
    print_error("Course module is incorrect");
}
// Header
$PAGE->set_url('/mod/journal/edit.php', array('id' => $id));
$PAGE->navbar->add(get_string('edit'));
$PAGE->set_title(format_string($journal->name));
$PAGE->set_heading($course->fullname);
$data = new StdClass();
$entry = $DB->get_record("journal_entries", array("userid" => $USER->id, "journal" => $journal->id));
if ($entry) {
    $data->text["text"] = $entry->text;
}
$data->id = $cm->id;
$form = new mod_journal_entry_form(null, array('current' => $data));
/// If data submitted, then process and store.
if ($fromform = $form->get_data()) {
    // Prevent CSFR.
    confirm_sesskey();
    $timenow = time();
    // Common
    $newentry = new StdClass();
    $newentry->text = $fromform->text["text"];
    $newentry->format = $fromform->text["format"];
    $newentry->modified = $timenow;
    if ($entry) {
        $newentry->id = $entry->id;
        if (!$DB->update_record("journal_entries", $newentry)) {
            print_error("Could not update your journal");
        }
$PAGE->set_heading($course->fullname);
$data = new stdClass();
$entry = $DB->get_record("journal_entries", array("userid" => $USER->id, "journal" => $journal->id));
if ($entry) {
    $data->entryid = $entry->id;
    $data->text = $entry->text;
    $data->textformat = $entry->format;
} else {
    $data->entryid = null;
    $data->text = '';
    $data->textformat = FORMAT_HTML;
}
$data->id = $cm->id;
$editoroptions = array('maxfiles' => EDITOR_UNLIMITED_FILES, 'context' => $context, 'subdirs' => false, 'enable_filemanagement' => true);
$data = file_prepare_standard_editor($data, 'text', $editoroptions, $context, 'mod_journal', 'entry', $data->entryid);
$form = new mod_journal_entry_form(null, array('entryid' => $data->entryid, 'editoroptions' => $editoroptions));
$form->set_data($data);
if ($form->is_cancelled()) {
    redirect($CFG->wwwroot . '/mod/journal/view.php?id=' . $cm->id);
} else {
    if ($fromform = $form->get_data()) {
        /// If data submitted, then process and store.
        // Prevent CSFR.
        confirm_sesskey();
        $timenow = time();
        // This will be overwriten after being we have the entryid.
        $newentry = new stdClass();
        $newentry->text = $fromform->text_editor['text'];
        $newentry->format = $fromform->text_editor['format'];
        $newentry->modified = $timenow;
        if ($entry) {