function set_data($defaults) { if (empty($entry->id)) { $entry = new stdClass(); $entry->id = null; } $draftitemid = file_get_submitted_draft_itemid('config_attachments'); file_prepare_draft_area($draftitemid, $this->block->context->id, 'block_slider', 'content', 0, array('subdirs' => true)); $entry->attachments = $draftitemid; parent::set_data($defaults); if ($data = parent::get_data()) { file_save_draft_area_files($data->config_attachments, $this->block->context->id, 'block_slider', 'content', 0, array('subdirs' => true)); } }
/** * Serialize and store config data */ function instance_config_save($data, $nolongerused = false) { global $DB; $config = clone $data; // Move embedded files into a proper filearea and adjust HTML links to match $config->text = file_save_draft_area_files($data->text['itemid'], $this->context->id, 'block_html', 'content', 0, array('subdirs' => true), $data->text['text']); $config->format = $data->text['format']; parent::instance_config_save($config, $nolongerused); }
/** * Updates the provided users profile picture based upon the expected fields * returned from the edit or edit_advanced forms. * * @global moodle_database $DB * @param stdClass $usernew An object that contains some information about the user being updated * @param moodleform $userform The form that was submitted to edit the form * @return bool True if the user was updated, false if it stayed the same. */ function useredit_update_picture(stdClass $usernew, moodleform $userform, $filemanageroptions = array()) { global $CFG, $DB; require_once("$CFG->libdir/gdlib.php"); $context = context_user::instance($usernew->id, MUST_EXIST); $user = $DB->get_record('user', array('id'=>$usernew->id), 'id, picture', MUST_EXIST); $newpicture = $user->picture; // Get file_storage to process files. $fs = get_file_storage(); if (!empty($usernew->deletepicture)) { // The user has chosen to delete the selected users picture $fs->delete_area_files($context->id, 'user', 'icon'); // drop all images in area $newpicture = 0; } else { // Save newly uploaded file, this will avoid context mismatch for newly created users. file_save_draft_area_files($usernew->imagefile, $context->id, 'user', 'newicon', 0, $filemanageroptions); if (($iconfiles = $fs->get_area_files($context->id, 'user', 'newicon')) && count($iconfiles) == 2) { // Get file which was uploaded in draft area foreach ($iconfiles as $file) { if (!$file->is_directory()) { break; } } // Copy file to temporary location and the send it for processing icon if ($iconfile = $file->copy_content_to_temp()) { // There is a new image that has been uploaded // Process the new image and set the user to make use of it. // NOTE: Uploaded images always take over Gravatar $newpicture = (int)process_new_icon($context, 'user', 'icon', 0, $iconfile); // Delete temporary file @unlink($iconfile); // Remove uploaded file. $fs->delete_area_files($context->id, 'user', 'newicon'); } else { // Something went wrong while creating temp file. // Remove uploaded file. $fs->delete_area_files($context->id, 'user', 'newicon'); return false; } } } if ($newpicture != $user->picture) { $DB->set_field('user', 'picture', $newpicture, array('id' => $user->id)); return true; } else { return false; } }
function slideshow_update_instance($data, $mform) { global $CFG, $DB; $cmid = $data->coursemodule; $draftitemid = $data->location; $data->timemodified = time(); $data->id = $data->instance; $DB->update_record("slideshow", $data); $context = get_context_instance(CONTEXT_MODULE, $cmid); if ($draftitemid = file_get_submitted_draft_itemid('location')) { file_save_draft_area_files($draftitemid, $context->id, 'mod_slideshow', 'content', 0, array('subdirs' => true)); } return true; }
function store_annotation_document($data) { global $DB, $CFG; $fs = get_file_storage(); $cmid = $data->coursemodule; $draftitemid = $data->files; $context = context_module::instance($cmid); if ($draftitemid) { $messagetext = file_save_draft_area_files($draftitemid, $context->id, 'mod_annotation', 'content', 0, array('subdirs' => true)); } $files = $fs->get_area_files($context->id, 'mod_annotation', 'content', 0, 'sortorder', false); if (count($files) == 1) { // Only one file attached, set it as main file automatically. $file = reset($files); file_set_sortorder($context->id, 'mod_annotation', 'content', 0, $file->get_filepath(), $file->get_filename(), 1); } // Find out the file location by getting the content hash. $table = "files"; $results = $DB->get_records($table, array('itemid' => $draftitemid)); foreach ($results as $result) { $userid = $result->userid; $timecreated = $result->timecreated; $contenthash = $result->contenthash; break; // Bad way of doing it, TODO. } // Insert a reference into mdl_annotation_document. $table = 'annotation_document'; $record = new stdClass(); $record->id = 0; // DB will auto increment it. $record->userid = $userid; $record->group_id = 0; $record->time_created = $timecreated; $record->documenttype = $data->type; $record->location = $contenthash; $record->lang = ""; // Lang column no longer used, highlightjs automatically detects language. $record->cmid = $cmid; $record->groupannotation = $data->groupannotation; if (isset($record->groupannotationsvisible)) { $record->groupannotationsvisible = $data->groupannotationsvisible; } else { $record->groupannotationsvisible = 0; } $record->allowfrom = $data->allowfrom; $record->allowuntil = $data->allowuntil; $insertid = $DB->insert_record('annotation_document', $record, false); }
/** * Saves the simulation file into the draft area * @return boolean */ public function saveSimulationFilesToDraft($CFG, $context, $draftitemid_applet) { $result = false; $this->maxbytes = get_max_upload_file_size($CFG->maxbytes); //Obtains the folder number to store the file while (file_exists($this->folderpath . $this->incremental)) { $this->incremental++; } //Saves the file in draft area if ($draftitemid_applet) { file_save_draft_area_files($draftitemid_applet, $context->id, 'atto_ejsapp', 'jarfiles', $this->incremental, array('subdirs' => 0, 'maxbytes' => $this->maxbytes, 'maxfiles' => 1, 'accepted_types' => array('application/java-archive', 'application/zip'))); $result = true; } return $result; }
/** * Saves the file from pdfparts record somewhere on the server. * @param object $data */ function pdfparts_set_mainfile($data) { global $DB; $fs = get_file_storage(); $cmid = $data->coursemodule; $draftitemid = $data->files; $context = context_module::instance($cmid); if ($draftitemid) { file_save_draft_area_files($draftitemid, $context->id, 'mod_pdfparts', 'content', 0, array('subdirs' => true)); } $files = $fs->get_area_files($context->id, 'mod_pdfparts', 'content', 0, 'sortorder', false); if (count($files) == 1) { // only one file attached, set it as main file automatically $file = reset($files); file_set_sortorder($context->id, 'mod_pdfparts', 'content', 0, $file->get_filepath(), $file->get_filename(), 1); } }
public function setInitilizationFile($CFG, $DB, $context, $fromform, $incremental, $maxbytes, $folderpath) { $this->setSimulationFilePath(""); file_save_draft_area_files($fromform->recordingfile, $context->id, 'atto_ejsapp', 'recordingfiles', $incremental, array('subdirs' => 0, 'maxbytes' => $maxbytes, 'maxfiles' => 1, 'accepted_types' => '.rec')); $fs = get_file_storage(); if ($files = $fs->get_area_files($context->id, 'atto_ejsapp', 'recordingfiles', $incremental, 'sortorder', false)) { foreach ($files as $file) { $fileurl = moodle_url::make_pluginfile_url($file->get_contextid(), $file->get_component(), $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $file->get_filename()); $this->setSimulationFilePath($fileurl); } } /*$file_records = $DB->get_records('files', array('contextid'=>$context->id, 'component'=>'atto_ejsapp', 'filearea'=>'recordingfiles', 'itemid'=>$incremental), 'filesize DESC'); $file_record = reset($file_records); if($file_record) { $fs = get_file_storage(); $file_state = $fs->get_file_by_id($file_record->id); $file_state->copy_content_to($folderpath . "simfiles/".$file_record->filename); $this->setSimulationFilePath($CFG->wwwroot . '/lib/editor/atto/plugins/ejsapp/jarfiles/' . $incremental . "/simfiles/".$file_record->filename); }*/ }
/** * Adds an instance of a dataform * * @global object * @param object $data * @return $int */ function dataform_add_instance($data) { global $CFG, $DB, $COURSE; $data->timemodified = time(); if (empty($data->grade)) { $data->grade = 0; $data->gradeitems = null; } // Max entries. if (!isset($data->maxentries) or $data->maxentries < -1) { $data->maxentries = -1; } if ($CFG->dataform_maxentries == 0) { $data->maxentries = 0; } else { if ($CFG->dataform_maxentries > 0 and ($data->maxentries > $CFG->dataform_maxentries or $data->maxentries < 0)) { $data->maxentries = $CFG->dataform_maxentries; } } if (!($data->id = $DB->insert_record('dataform', $data))) { return false; } // Activity icon. if (!empty($data->activityicon)) { // We need to use context now, so we need to make sure all needed info is already in db. $DB->set_field('course_modules', 'instance', $data->id, array('id' => $data->coursemodule)); $context = context_module::instance($data->coursemodule); $options = array('subdirs' => 0, 'maxbytes' => $COURSE->maxbytes, 'maxfiles' => 1, 'accepted_types' => array('image')); file_save_draft_area_files($data->activityicon, $context->id, 'mod_dataform', 'activityicon', 0, $options); } // Calendar. \mod_dataform\helper\calendar_event::update_event_timeavailable($data); \mod_dataform\helper\calendar_event::update_event_timedue($data); // Grading. if ($data->grade) { $grademan = \mod_dataform_grade_manager::instance($data->id); $itemparams = $grademan->get_grade_item_params_from_data($data); $grademan->update_grade_item(0, $itemparams); } return $data->id; }
public function save_question_options($formdata) { global $DB; $context = $formdata->context; $options = $DB->get_record('qtype_poodllrecording_opts', array('questionid' => $formdata->id)); if (!$options) { $options = new stdClass(); $options->questionid = $formdata->id; $options->id = $DB->insert_record('qtype_poodllrecording_opts', $options); } //"import_or_save_files" won't work, because it expects output from an editor which is an array with member itemid //the filemanager doesn't produce this, so need to use file save draft area directly //$options->backimage = $this->import_or_save_files($formdata->backimage, // $context, 'qtype_poodllrecording', 'backimage', $formdata->id); if (isset($formdata->backimage)) { file_save_draft_area_files($formdata->backimage, $context->id, 'qtype_poodllrecording', 'backimage', $formdata->id, array('subdirs' => 0, 'maxbytes' => 0, 'maxfiles' => 1)); //save the itemid of the backimage filearea $options->backimage = $formdata->backimage; } else { $options->backimage = null; } //save the selected board size if (isset($formdata->boardsize)) { $options->boardsize = $formdata->boardsize; } else { $options->boardsize = "320x320"; } //if we have a recording time limit if (isset($formdata->timelimit)) { $options->timelimit = $formdata->timelimit; } else { $options->timelimit = 0; } $options->responseformat = $formdata->responseformat; $options->graderinfo = $this->import_or_save_files($formdata->graderinfo, $context, 'qtype_poodllrecording', 'graderinfo', $formdata->id); $options->graderinfoformat = $formdata->graderinfo['format']; $DB->update_record('qtype_poodllrecording_opts', $options); }
public function apply($discussion, $all, $selected, $formdata) { global $CFG; $filecontext = $discussion->get_context(); $forum = $discussion; if (!isset($formdata->mailnow)) { $formdata->mailnow = false; } foreach ($selected as $postid) { // Call the lock for selected discussions. $discussion = mod_forumng_discussion::get_from_id($postid, $formdata->clone); if (!$discussion->is_deleted() && !$discussion->is_locked()) { $newpostid = $discussion->lock($formdata->subject, $formdata->message['text'], $formdata->message['format'], $formdata->attachments, $formdata->mailnow, '', '', $formdata->asmoderator); // Save attachments. file_save_draft_area_files($formdata->attachments, $filecontext->id, 'mod_forumng', 'attachment', $newpostid, null); $newtext = file_save_draft_area_files($formdata->message['itemid'], $filecontext->id, 'mod_forumng', 'message', $newpostid, null, $formdata->message['text']); if ($newtext !== $formdata->message['text']) { mod_forumng_post::update_message_for_files($newpostid, $newtext); } } } // Redirect to the Main page. redirect('../../view.php?' . $forum->get_link_params(mod_forumng::PARAM_PLAIN)); }
/** * Saves files modified by File manager formslib element * * @todo MDL-31073 review this function * @category files * @param stdClass $data $database entry field * @param string $field name of data field * @param array $options various options * @param stdClass $context context - must already exist * @param string $component * @param string $filearea file area name * @param int $itemid must already exist, usually means data is in db * @return stdClass modified data obejct */ function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) { $options = (array) $options; if (!isset($options['subdirs'])) { $options['subdirs'] = false; } if (!isset($options['maxfiles'])) { $options['maxfiles'] = -1; // unlimited } if (!isset($options['maxbytes'])) { $options['maxbytes'] = 0; // unlimited } if (empty($data->{$field . '_filemanager'})) { $data->{$field} = ''; } else { file_save_draft_area_files($data->{$field . '_filemanager'}, $context->id, $component, $filearea, $itemid, $options); $fs = get_file_storage(); if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) { $data->{$field} = '1'; // TODO: this is an ugly hack (skodak) } else { $data->{$field} = ''; } } return $data; }
/** * Upload file for submission * * @param object $cm the course module object * @return array result and message */ function turnitintool_dofileupload_post_29($cm, $turnitintool, $userid, $post) { global $USER, $CFG; $param_do = optional_param('do', null, PARAM_CLEAN); $checksubmission = turnitintool_checkforsubmission($cm, $turnitintool, $post['submissionpart'], $userid); if (isset($checksubmission->id) and $turnitintool->reportgenspeed == 0) { // Kill the script here as we do not want double errors // We only get here if there are no other errors turnitintool_print_error('alreadysubmitted', 'turnitintool', NULL, NULL, __FILE__, __LINE__); exit; } $resubmission = false; if (isset($checksubmission->id) and $turnitintool->reportgenspeed > 0) { $resubmission = true; } if ($resubmission and $checksubmission->dtdue < time()) { turnitintool_print_error('alreadysubmitted', 'turnitintool', NULL, NULL, __FILE__, __LINE__); exit; } $submitobject = new stdClass(); $submitobject->userid = $userid; $submitobject->turnitintoolid = $turnitintool->id; $submitobject->submission_part = $post['submissionpart']; $submitobject->submission_type = $post['submissiontype']; $submitobject->submission_queued = null; $submitobject->submission_attempts = 0; $submitobject->submission_gmimaged = 0; $submitobject->submission_status = null; $submitobject->submission_modified = time(); $submitobject->submission_objectid = !isset($checksubmission->submission_objectid) ? null : $checksubmission->submission_objectid; if (!isset($checksubmission->submission_unanon) or $checksubmission->submission_unanon) { // If non anon resubmission or new submission set the title as what was entered in the form $submitobject->submission_title = $post['submissiontitle']; if (!$turnitintool->anon) { // If not anon assignment and this is a non anon resubmission or a new submission set the unanon flag to true (1) $submitobject->submission_unanon = 1; } } if (!$resubmission) { // Prevent duplication in issues where the TII servers may be inaccessible. if (!($check_existing = turnitintool_get_records_select('turnitintool_submissions', 'userid=' . $submitobject->userid . ' AND turnitintoolid=' . $submitobject->turnitintoolid . ' AND submission_part=' . $submitobject->submission_part))) { if (!($submitobject->id = turnitintool_insert_record('turnitintool_submissions', $submitobject))) { turnitintool_print_error('submissioninserterror', 'turnitintool', NULL, NULL, __FILE__, __LINE__); exit; } } } else { $submitobject->id = $checksubmission->id; $submitobject->submission_score = null; $submitobject->submission_grade = null; if (!turnitintool_update_record('turnitintool_submissions', $submitobject)) { turnitintool_print_error('submissionupdateerror', 'turnitintool', NULL, NULL, __FILE__, __LINE__); exit; } else { $submitobject->id = $checksubmission->id; } } $return = array(); $context = context_module::instance($cm->id); // Get draft item id and save the files in the draft area. $draftitemid = file_get_submitted_draft_itemid('submissionfile'); $uploadoptions = array('maxbytes' => $turnitintool->maxfilesize, 'subdirs' => false, 'maxfiles' => 1, 'accepted_types' => '*'); file_prepare_draft_area($draftitemid, $context->id, 'mod_turnitintool', 'submissions', $submitobject->id, $uploadoptions); file_save_draft_area_files($draftitemid, $context->id, 'mod_turnitintool', 'submissions', $submitobject->id, $uploadoptions); $fs = get_file_storage(); $files = $fs->get_area_files($context->id, 'mod_turnitintool', 'submissions', $submitobject->id, "timecreated", false); // This should only return 1 result. if (count($files) == 0) { $notice['result'] = false; $_SESSION["notice"]["message"] = get_string('submissionfileerror', 'turnitintool'); $_SESSION["notice"]["type"] = "error"; turnitintool_delete_records('turnitintool_submissions', 'id', $submitobject->id); return $notice; } else { $notice['result'] = true; } if (has_capability('mod/turnitintool:grade', turnitintool_get_context('MODULE', $cm->id)) and !$turnitintool->autosubmission) { turnitintool_redirect($CFG->wwwroot . '/mod/turnitintool/view.php?id=' . $cm->id . '&do=allsubmissions'); exit; } else { if (!$turnitintool->autosubmission) { turnitintool_redirect($CFG->wwwroot . '/mod/turnitintool/view.php?id=' . $cm->id . '&do=' . $param_do); exit; } } $notice["subid"] = $submitobject->id; return $notice; }
/** * Create and update question data from the forms. */ public function form_update($formdata, $questionnaire) { global $DB; $this->form_preprocess_data($formdata); if (!empty($formdata->qid)) { // Update existing question. // Handle any attachments in the content. $formdata->itemid = $formdata->content['itemid']; $formdata->format = $formdata->content['format']; $formdata->content = $formdata->content['text']; $formdata->content = file_save_draft_area_files($formdata->itemid, $questionnaire->context->id, 'mod_questionnaire', 'question', $formdata->qid, array('subdirs' => true), $formdata->content); $fields = array('name', 'type_id', 'length', 'precise', 'required', 'content', 'dependquestion', 'dependchoice'); $questionrecord = new \stdClass(); $questionrecord->id = $formdata->qid; foreach ($fields as $f) { if (isset($formdata->{$f})) { $questionrecord->{$f} = trim($formdata->{$f}); } } $result = $this->update($questionrecord, false); if (questionnaire_has_dependencies($questionnaire->questions)) { questionnaire_check_page_breaks($questionnaire); } } else { // Create new question: // Need to update any image content after the question is created, so create then update the content. $formdata->survey_id = $formdata->sid; $fields = array('survey_id', 'name', 'type_id', 'length', 'precise', 'required', 'position', 'dependquestion', 'dependchoice'); $questionrecord = new \stdClass(); foreach ($fields as $f) { if (isset($formdata->{$f})) { $questionrecord->{$f} = trim($formdata->{$f}); } } $questionrecord->content = ''; $this->add($questionrecord); // Handle any attachments in the content. $formdata->itemid = $formdata->content['itemid']; $formdata->format = $formdata->content['format']; $formdata->content = $formdata->content['text']; $content = file_save_draft_area_files($formdata->itemid, $questionnaire->context->id, 'mod_questionnaire', 'question', $this->qid, array('subdirs' => true), $formdata->content); $result = $DB->set_field('questionnaire_question', 'content', $content, array('id' => $this->qid)); } if ($this->has_choices()) { // Now handle any choice updates. $cidx = 0; if (isset($this->choices) && !isset($formdata->makecopy)) { $oldcount = count($this->choices); $echoice = reset($this->choices); $ekey = key($this->choices); } else { $oldcount = 0; } $newchoices = explode("\n", $formdata->allchoices); $nidx = 0; $newcount = count($newchoices); while ($nidx < $newcount && $cidx < $oldcount) { if ($newchoices[$nidx] != $echoice->content) { $choicerecord = new \stdClass(); $choicerecord->id = $ekey; $choicerecord->question_id = $this->qid; $choicerecord->content = trim($newchoices[$nidx]); $r = preg_match_all("/^(\\d{1,2})(=.*)\$/", $newchoices[$nidx], $matches); // This choice has been attributed a "score value" OR this is a rate question type. if ($r) { $newscore = $matches[1][0]; $choicerecord->value = $newscore; } else { // No score value for this choice. $choicerecord->value = null; } $this->update_choice($choicerecord); } $nidx++; $echoice = next($this->choices); $ekey = key($this->choices); $cidx++; } while ($nidx < $newcount) { // New choices... $choicerecord = new \stdClass(); $choicerecord->question_id = $this->qid; $choicerecord->content = trim($newchoices[$nidx]); $r = preg_match_all("/^(\\d{1,2})(=.*)\$/", $choicerecord->content, $matches); // This choice has been attributed a "score value" OR this is a rate question type. if ($r) { $choicerecord->value = $matches[1][0]; } $this->add_choice($choicerecord); $nidx++; } while ($cidx < $oldcount) { end($this->choices); $ekey = key($this->choices); $this->delete_choice($ekey); $cidx++; } } }
/** * Handle a file that has been uploaded * @param object $uploadinfo details of the file / content that has been uploaded * @return int instance id of the newly created mod */ function scorm_dndupload_handle($uploadinfo) { $context = context_module::instance($uploadinfo->coursemodule); file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_scorm', 'package', 0); $fs = get_file_storage(); $files = $fs->get_area_files($context->id, 'mod_scorm', 'package', 0, 'sortorder, itemid, filepath, filename', false); $file = reset($files); // Validate the file, make sure it's a valid SCORM package! $errors = scorm_validate_package($file); if (!empty($errors)) { return false; } // Create a default scorm object to pass to scorm_add_instance()! $scorm = get_config('scorm'); $scorm->course = $uploadinfo->course->id; $scorm->coursemodule = $uploadinfo->coursemodule; $scorm->cmidnumber = ''; $scorm->name = $uploadinfo->displayname; $scorm->scormtype = SCORM_TYPE_LOCAL; $scorm->reference = $file->get_filename(); $scorm->intro = ''; $scorm->width = $scorm->framewidth; $scorm->height = $scorm->frameheight; return scorm_add_instance($scorm, null); }
/** * Update or create an event within the database * * Pass in a object containing the event properties and this function will * insert it into the database and deal with any associated files * * @see add_event() * @see update_event() * * @param stdClass $data object of event * @param bool $checkcapability if moodle should check calendar managing capability or not * @return bool event updated */ public function update($data, $checkcapability = true) { global $CFG, $DB, $USER; foreach ($data as $key => $value) { $this->properties->{$key} = $value; } $this->properties->timemodified = time(); $usingeditor = !empty($this->properties->description) && is_array($this->properties->description); if (empty($this->properties->id) || $this->properties->id < 1) { if ($checkcapability) { if (!calendar_add_event_allowed($this->properties)) { print_error('nopermissiontoupdatecalendar'); } } if ($usingeditor) { switch ($this->properties->eventtype) { case 'user': $this->properties->courseid = 0; $this->properties->course = 0; $this->properties->groupid = 0; $this->properties->userid = $USER->id; break; case 'site': $this->properties->courseid = SITEID; $this->properties->course = SITEID; $this->properties->groupid = 0; $this->properties->userid = $USER->id; break; case 'course': $this->properties->groupid = 0; $this->properties->userid = $USER->id; break; case 'group': $this->properties->userid = $USER->id; break; default: // Ewww we should NEVER get here, but just incase we do lets // fail gracefully $usingeditor = false; break; } // If we are actually using the editor, we recalculate the context because some default values // were set when calculate_context() was called from the constructor. if ($usingeditor) { $this->properties->context = $this->calculate_context($this->properties); $this->editorcontext = $this->properties->context; } $editor = $this->properties->description; $this->properties->format = $this->properties->description['format']; $this->properties->description = $this->properties->description['text']; } // Insert the event into the database $this->properties->id = $DB->insert_record('event', $this->properties); if ($usingeditor) { $this->properties->description = file_save_draft_area_files($editor['itemid'], $this->editorcontext->id, 'calendar', 'event_description', $this->properties->id, $this->editoroptions, $editor['text'], $this->editoroptions['forcehttps']); $DB->set_field('event', 'description', $this->properties->description, array('id' => $this->properties->id)); } // Log the event entry. add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&id=' . $this->properties->id, $this->properties->name); $repeatedids = array(); if (!empty($this->properties->repeat)) { $this->properties->repeatid = $this->properties->id; $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id)); $eventcopy = clone $this->properties; unset($eventcopy->id); for ($i = 1; $i < $eventcopy->repeats; $i++) { $eventcopy->timestart = $eventcopy->timestart + WEEKSECS + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart + WEEKSECS); // Get the event id for the log record. $eventcopyid = $DB->insert_record('event', $eventcopy); // If the context has been set delete all associated files if ($usingeditor) { $fs = get_file_storage(); $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id); foreach ($files as $file) { $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file); } } $repeatedids[] = $eventcopyid; // Log the event entry. add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&id=' . $eventcopyid, $eventcopy->name); } } // Hook for tracking added events self::calendar_event_hook('add_event', array($this->properties, $repeatedids)); return true; } else { if ($checkcapability) { if (!calendar_edit_event_allowed($this->properties)) { print_error('nopermissiontoupdatecalendar'); } } if ($usingeditor) { if ($this->editorcontext !== null) { $this->properties->description = file_save_draft_area_files($this->properties->description['itemid'], $this->editorcontext->id, 'calendar', 'event_description', $this->properties->id, $this->editoroptions, $this->properties->description['text'], $this->editoroptions['forcehttps']); } else { $this->properties->format = $this->properties->description['format']; $this->properties->description = $this->properties->description['text']; } } $event = $DB->get_record('event', array('id' => $this->properties->id)); $updaterepeated = !empty($this->properties->repeatid) && !empty($this->properties->repeateditall); if ($updaterepeated) { // Update all if ($this->properties->timestart != $event->timestart) { $timestartoffset = $this->properties->timestart - $event->timestart; $sql = "UPDATE {event}\n SET name = ?,\n description = ?,\n timestart = timestart + ?,\n timeduration = ?,\n timemodified = ?\n WHERE repeatid = ?"; $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid); } else { $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?"; $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid); } $DB->execute($sql, $params); // Log the event update. add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&id=' . $this->properties->id, $this->properties->name); } else { $DB->update_record('event', $this->properties); $event = calendar_event::load($this->properties->id); $this->properties = $event->properties(); add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&id=' . $this->properties->id, $this->properties->name); } // Hook for tracking event updates self::calendar_event_hook('update_event', array($this->properties, $updaterepeated)); return true; } }
/** * this will update a given instance * * @global object * @param object $feedback the object given by mod_feedback_mod_form * @return boolean */ function feedback_update_instance($feedback) { global $DB; $feedback->timemodified = time(); $feedback->id = $feedback->instance; //check if openenable and/or closeenable is set and set correctly to save in db if (empty($feedback->openenable)) { $feedback->timeopen = 0; } if (empty($feedback->closeenable)) { $feedback->timeclose = 0; } if (empty($feedback->site_after_submit)) { $feedback->site_after_submit = ''; } //save the feedback into the db $DB->update_record("feedback", $feedback); //create or update the new events feedback_set_events($feedback); $context = get_context_instance(CONTEXT_MODULE, $feedback->coursemodule); $editoroptions = feedback_get_editor_options(); // process the custom wysiwyg editor in page_after_submit if ($draftitemid = $feedback->page_after_submit_editor['itemid']) { $feedback->page_after_submit = file_save_draft_area_files($draftitemid, $context->id, 'mod_feedback', 'page_after_submit', 0, $editoroptions, $feedback->page_after_submit_editor['text']); $feedback->page_after_submitformat = $feedback->page_after_submit_editor['format']; } $DB->update_record('feedback', $feedback); return true; }
public function write_setting($data) { global $USER; // Let's not deal with validation here, this is for admins only. $current = $this->get_setting(); if (empty($data) && $current === null) { // This will be the case when applying default settings (installation). return $this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'); } else { if (!is_number($data)) { // Draft item id is expected here! return get_string('errorsetting', 'admin'); } } $options = $this->get_options(); $fs = get_file_storage(); $component = is_null($this->plugin) ? 'core' : $this->plugin; $this->oldhashes = null; if ($current) { $hash = sha1('/' . $options['context']->id . '/' . $component . '/' . $this->filearea . '/' . $this->itemid . $current); if ($file = $fs->get_file_by_hash($hash)) { $this->oldhashes = $file->get_contenthash() . $file->get_pathnamehash(); } unset($file); } if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) { // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime. // But we can safely ignore that if the destination area is empty, so that the user is not prompt // with an error because the draft area does not exist, as he did not use it. $usercontext = context_user::instance($USER->id); if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') { return get_string('errorsetting', 'admin'); } } file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options); $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false); $filepath = ''; if ($files) { /** @var stored_file $file */ $file = reset($files); $filepath = $file->get_filepath() . $file->get_filename(); } return $this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'); }
/** * save editor answers files and update answer record * * @param object $context * @param int $maxbytes * @param object $answer * @param object $answereditor * @param object $responseeditor */ public function save_answers_files($context, $maxbytes, &$answer, $answereditor = '', $responseeditor = '') { global $DB; if (isset($answereditor['itemid'])) { $answer->answer = file_save_draft_area_files($answereditor['itemid'], $context->id, 'mod_lesson', 'page_answers', $answer->id, array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes), $answer->answer, null); $DB->set_field('lesson_answers', 'answer', $answer->answer, array('id' => $answer->id)); } if (isset($responseeditor['itemid'])) { $answer->response = file_save_draft_area_files($responseeditor['itemid'], $context->id, 'mod_lesson', 'page_responses', $answer->id, array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes), $answer->response, null); $DB->set_field('lesson_answers', 'response', $answer->response, array('id' => $answer->id)); } }
/** * Save the attachments in the draft areas. * * @param stdClass $formdata */ protected function save_intro_draft_files($formdata) { if (isset($formdata->introattachments)) { file_save_draft_area_files($formdata->introattachments, $this->get_context()->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0); } }
/** * Serialize and store config data */ function instance_config_save($data, $nolongerused = false) { global $USER, $COURSE; $config = new stdClass(); foreach ($data as $fieldname => $fieldvalue) { if (is_array($fieldvalue)) { $config->{$fieldname} = array(); } else { $config->{$fieldname} = $fieldvalue; } } $fileoptions = array('subdirs' => false, 'maxfiles' => 1, 'maxbytes' => $COURSE->maxbytes, 'accepted_types' => 'web_image', 'return_types' => FILE_INTERNAL); $saved = 0; for ($i = 0; $i < $data->slides; $i++) { $usercontext = context_user::instance($USER->id); $fs = get_file_storage(); $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $data->imageslide[$i], 'id'); if (count($draftfiles) > 1 || isset($data->title[$i]) && !empty($data->title[$i]) || isset($data->caption[$i]) && !empty($data->caption[$i]) || isset($data->link[$i]) && !empty($data->link[$i])) { $config->enabled[$saved] = 0; if (isset($data->enabled[$i]) && !empty($data->enabled[$i])) { $config->enabled[$saved] = $data->enabled[$i]; if ($data->firstslide >= $saved) { $config->firstslide = $saved; } } if (isset($data->imageslide[$i]) && !empty($data->imageslide[$i])) { $config->imageslide[$saved] = $data->imageslide[$i]; file_save_draft_area_files($config->imageslide[$saved], $this->context->id, 'block_slideshow', 'slides', $saved, $fileoptions); } $config->imageposition[$saved] = isset($data->imageposition[$i]) && !empty($data->imageposition[$i]) ? $data->imageposition[$i] : ''; $config->title[$saved] = isset($data->title[$i]) && !empty($data->title[$i]) ? $data->title[$i] : ''; $config->caption[$saved] = isset($data->caption[$i]) && !empty($data->caption[$i]) ? $data->caption[$i] : ''; $config->captionposition[$saved] = isset($data->captionposition[$i]) && !empty($data->captionposition[$i]) ? $data->captionposition[$i] : ''; $config->link[$saved] = isset($data->link[$i]) && !empty($data->link[$i]) ? $data->link[$i] : ''; $saved++; } } for ($i = $saved; $i < $data->slides; $i++) { file_save_draft_area_files($data->imageslide[$i], $this->context->id, 'block_slideshow', 'slides', $i, $fileoptions); } $config->slides = $saved; parent::instance_config_save($config, $nolongerused); }
/** * Given an object containing all the necessary data, * (defined by the form in mod_form.php) this function * will update an existing instance with new data. * * @param stdClass $workshop An object from the form in mod_form.php * @return bool success */ function workshop_update_instance(stdclass $workshop) { global $CFG, $DB; require_once(dirname(__FILE__) . '/locallib.php'); $workshop->timemodified = time(); $workshop->id = $workshop->instance; $workshop->useexamples = (int)!empty($workshop->useexamples); $workshop->usepeerassessment = (int)!empty($workshop->usepeerassessment); $workshop->useselfassessment = (int)!empty($workshop->useselfassessment); $workshop->latesubmissions = (int)!empty($workshop->latesubmissions); $workshop->phaseswitchassessment = (int)!empty($workshop->phaseswitchassessment); $workshop->evaluation = 'best'; // todo - if the grading strategy is being changed, we must replace all aggregated peer grades with nulls // todo - if maximum grades are being changed, we should probably recalculate or invalidate them $DB->update_record('workshop', $workshop); $context = get_context_instance(CONTEXT_MODULE, $workshop->coursemodule); // process the custom wysiwyg editors if ($draftitemid = $workshop->instructauthorseditor['itemid']) { $workshop->instructauthors = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'instructauthors', 0, workshop::instruction_editors_options($context), $workshop->instructauthorseditor['text']); $workshop->instructauthorsformat = $workshop->instructauthorseditor['format']; } if ($draftitemid = $workshop->instructreviewerseditor['itemid']) { $workshop->instructreviewers = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'instructreviewers', 0, workshop::instruction_editors_options($context), $workshop->instructreviewerseditor['text']); $workshop->instructreviewersformat = $workshop->instructreviewerseditor['format']; } // re-save the record with the replaced URLs in editor fields $DB->update_record('workshop', $workshop); // update gradebook items workshop_grade_item_update($workshop); workshop_grade_item_category_update($workshop); // update calendar events workshop_calendar_update($workshop, $workshop->coursemodule); return true; }
/** * Handle a file that has been uploaded * @param object $uploadinfo details of the file / content that has been uploaded * @return int instance id of the newly created mod */ function folder_dndupload_handle($uploadinfo) { global $DB, $USER; // Gather the required info. $data = new stdClass(); $data->course = $uploadinfo->course->id; $data->name = $uploadinfo->displayname; $data->intro = '<p>' . $uploadinfo->displayname . '</p>'; $data->introformat = FORMAT_HTML; $data->coursemodule = $uploadinfo->coursemodule; $data->files = null; // We will unzip the file and sort out the contents below. $data->id = folder_add_instance($data, null); // Retrieve the file from the draft file area. $context = context_module::instance($uploadinfo->coursemodule); file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_folder', 'temp', 0, array('subdirs' => true)); $fs = get_file_storage(); $files = $fs->get_area_files($context->id, 'mod_folder', 'temp', 0, 'sortorder', false); // Only ever one file - extract the contents. $file = reset($files); $success = $file->extract_to_storage(new zip_packer(), $context->id, 'mod_folder', 'content', 0, '/', $USER->id); $fs->delete_area_files($context->id, 'mod_folder', 'temp', 0); if ($success) { return $data->id; } $DB->delete_records('folder', array('id' => $data->id)); return false; }
function update_content($recordid, $value, $name = '') { global $CFG, $DB, $USER; if (!($content = $DB->get_record('data_content', array('fieldid' => $this->field->id, 'recordid' => $recordid)))) { // Quickly make one now! $content = new stdClass(); $content->fieldid = $this->field->id; $content->recordid = $recordid; $id = $DB->insert_record('data_content', $content); $content = $DB->get_record('data_content', array('id' => $id)); } $names = explode('_', $name); switch ($names[2]) { case 'file': $fs = get_file_storage(); file_save_draft_area_files($value, $this->context->id, 'mod_data', 'content', $content->id); $usercontext = context_user::instance($USER->id); $files = $fs->get_area_files($this->context->id, 'mod_data', 'content', $content->id, 'itemid, filepath, filename', false); // We expect no or just one file (maxfiles = 1 option is set for the form_filemanager). if (count($files) == 0) { $content->content = null; } else { $file = array_values($files)[0]; if (count($files) > 1) { // This should not happen with a consistent database. Inform admins/developers about the inconsistency. debugging('more then one file found in mod_data instance {$this->data->id} picture field (field id: {$this->field->id}) area during update data record {$recordid} (content id: {$content->id})', DEBUG_NORMAL); } if ($file->get_imageinfo() === false) { $url = new moodle_url('/mod/data/edit.php', array('d' => $this->field->dataid)); redirect($url, get_string('invalidfiletype', 'error', $file->get_filename())); } $content->content = $file->get_filename(); $this->update_thumbnail($content, $file); } $DB->update_record('data_content', $content); break; case 'alttext': // only changing alt tag $content->content1 = clean_param($value, PARAM_NOTAGS); $DB->update_record('data_content', $content); break; default: break; } }
public function update_session_from_form_data($formdata, $sessionid) { global $DB; if (!($sess = $DB->get_record('attendance_sessions', array('id' => $sessionid)))) { print_error('No such session in this course'); } $sess->sessdate = $formdata->sessiondate; $sess->duration = $formdata->durtime['hours'] * HOURSECS + $formdata->durtime['minutes'] * MINSECS; $description = file_save_draft_area_files($formdata->sdescription['itemid'], $this->context->id, 'mod_attendance', 'session', $sessionid, array('subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0), $formdata->sdescription['text']); $sess->description = $description; $sess->descriptionformat = $formdata->sdescription['format']; $sess->timemodified = time(); $DB->update_record('attendance_sessions', $sess); $info = construct_session_full_date_time($sess->sessdate, $sess->duration); $event = \mod_attendance\event\session_updated::create(array('objectid' => $this->id, 'context' => $this->context, 'other' => array('info' => $info, 'sessionid' => $sessionid, 'action' => att_sessions_page_params::ACTION_UPDATE))); $event->add_record_snapshot('course_modules', $this->cm); $event->add_record_snapshot('attendance_sessions', $sess); $event->trigger(); }
/** * Testing deleting original files. * * @copyright 2012 Dongsheng Cai {@link http://dongsheng.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ public function test_delete_original_file_from_draft() { global $USER, $DB; $this->resetAfterTest(true); $generator = $this->getDataGenerator(); $user = $generator->create_user(); $usercontext = context_user::instance($user->id); $USER = $DB->get_record('user', array('id' => $user->id)); $repositorypluginname = 'user'; $args = array(); $args['type'] = $repositorypluginname; $repos = repository::get_instances($args); $userrepository = reset($repos); $this->assertInstanceOf('repository', $userrepository); $fs = get_file_storage(); $syscontext = context_system::instance(); $filecontent = 'User file content'; // Create a user private file. $userfilerecord = new stdClass(); $userfilerecord->contextid = $usercontext->id; $userfilerecord->component = 'user'; $userfilerecord->filearea = 'private'; $userfilerecord->itemid = 0; $userfilerecord->filepath = '/'; $userfilerecord->filename = 'userfile.txt'; $userfilerecord->source = 'test'; $userfile = $fs->create_file_from_string($userfilerecord, $filecontent); $userfileref = $fs->pack_reference($userfilerecord); $contenthash = $userfile->get_contenthash(); $filerecord = array('contextid' => $syscontext->id, 'component' => 'core', 'filearea' => 'phpunit', 'itemid' => 0, 'filepath' => '/', 'filename' => 'test.txt'); // Create a file reference. $fileref = $fs->create_file_from_reference($filerecord, $userrepository->id, $userfileref); $this->assertInstanceOf('stored_file', $fileref); $this->assertEquals($userrepository->id, $fileref->get_repository_id()); $this->assertSame($userfile->get_contenthash(), $fileref->get_contenthash()); $this->assertEquals($userfile->get_filesize(), $fileref->get_filesize()); $this->assertRegExp('#' . $userfile->get_filename() . '$#', $fileref->get_reference_details()); $draftitemid = 0; file_prepare_draft_area($draftitemid, $usercontext->id, 'user', 'private', 0); $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid); $this->assertCount(2, $draftfiles); $draftfile = $fs->get_file($usercontext->id, 'user', 'draft', $draftitemid, $userfilerecord->filepath, $userfilerecord->filename); $draftfile->delete(); // Save changed file. file_save_draft_area_files($draftitemid, $usercontext->id, 'user', 'private', 0); // The file reference should be a regular moodle file now. $fileref = $fs->get_file($syscontext->id, 'core', 'phpunit', 0, '/', 'test.txt'); $this->assertFalse($fileref->is_external_file()); $this->assertSame($contenthash, $fileref->get_contenthash()); $this->assertEquals($filecontent, $fileref->get_content()); }
function update_content($recordid, $value, $name='') { global $DB; $content = new stdClass(); $content->fieldid = $this->field->id; $content->recordid = $recordid; $names = explode('_', $name); if (!empty($names[2])) { if ($names[2] == 'itemid') { // the value will be retrieved by file_get_submitted_draft_itemid, do not need to save in DB return true; } else { $content->$names[2] = clean_param($value, PARAM_NOTAGS); // content[1-4] } } else { $content->content = clean_param($value, PARAM_CLEAN); } if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) { $content->id = $oldcontent->id; } else { $content->id = $DB->insert_record('data_content', $content); if (!$content->id) { return false; } } if (!empty($content->content)) { $draftitemid = file_get_submitted_draft_itemid('field_'. $this->field->id. '_itemid'); $options = $this->get_options(); $content->content = file_save_draft_area_files($draftitemid, $this->context->id, 'mod_data', 'content', $content->id, $options, $content->content); } $rv = $DB->update_record('data_content', $content); return $rv; }
function link_to_gdoc($name, $link, $type = null, $modtype = 'url') { global $COURSE, $DB, $CFG, $USER; require_once "{$CFG->dirroot}/mod/{$modtype}/lib.php"; //add $fromform = new stdClass(); $newform = new stdClass(); $mform = new MoodleQuickForm(null, 'POST', 'nothing'); $module = $DB->get_record("modules", array('name' => $modtype)); $course = $COURSE; $cw = get_course_section(0, $course->id); $cm = null; // fields for mdl_url $fromform->course = $course->id; $fromform->name = $name; $fromform->introformat = 0; $fromform->introeditor = 0; $fromform->externalurl = $link; /* if ($type !== 'dir') { $fromform->display = 6; $fromform->displayoptions = 'a:2:{s:10:"popupwidth";i:1024;s:11:"popupheight";i:768;}'; } else { */ $fromform->display = 0; $fromform->popupwidth = 1024; $fromform->popupheight = 768; $fromform->popupwidth = null; $fromform->popupheight = null; $fromform->displayoptions = 'a:1:{s:10:"printintro";i:0;}'; // } // fields for mdl_course_module $fromform->module = $module->id; $fromform->instance = ''; $fromform->section = 0; // The section number itself - relative!!! (section column in course_sections) $fromform->idnumber = null; $fromform->score = 0; $fromform->indent = 0; $fromform->visible = 1; $fromform->visibleold = 1; $fromform->groupmode = $course->groupmode; $fromform->groupingid = 0; $fromform->groupmembersonly = 0; $fromform->completion = 0; $fromform->completionview = 0; $fromform->completionexpected = 0; $fromform->availablefrom = 0; $fromform->availableuntil = 0; $fromform->showavailability = 0; $fromform->showdescription = 0; $fromform->conditiongradegroup = array(); $fromform->conditionfieldgroup = array(); // fields for mdl_course_sections $fromform->summaryformat = 0; $fromform->modulename = clean_param($module->name, PARAM_SAFEDIR); // For safety // $fromform->add = 'resource'; // $fromform->type = $type == 'dir' ? 'collection' : 'file'; // $fromform->return = 0; //must be false if this is an add, go back to course view on cancel // $fromform->coursemodule = ''; // $fromform->popup = 'resizable=1,scrollbars=1,directories=1,location=1,menubar=1,toolbar=1,status=1,width=1024,height=768'; // require_login($course->id); // needed to setup proper $COURSE $context = get_context_instance(CONTEXT_COURSE, $course->id); require_capability('moodle/course:manageactivities', $context); if (!empty($course->groupmodeforce) or !isset($fromform->groupmode)) { $fromform->groupmode = 0; // do not set groupmode } if (!course_allowed_module($course, $fromform->modulename)) { print_error('moduledisable', '', '', $fromform->modulename); } // first add course_module record because we need the context $newcm = new stdClass(); $newcm->course = $course->id; $newcm->module = $fromform->module; $newcm->instance = 0; // not known yet, will be updated later (this is similar to restore code) $newcm->visible = $fromform->visible; $newcm->groupmode = $fromform->groupmode; $newcm->groupingid = $fromform->groupingid; $newcm->groupmembersonly = $fromform->groupmembersonly; $completion = new completion_info($course); if ($completion->is_enabled()) { $newcm->completion = $fromform->completion; $newcm->completiongradeitemnumber = $fromform->completiongradeitemnumber; $newcm->completionview = $fromform->completionview; $newcm->completionexpected = $fromform->completionexpected; } if (!empty($CFG->enableavailability)) { $newcm->availablefrom = $fromform->availablefrom; $newcm->availableuntil = $fromform->availableuntil; $newcm->showavailability = $fromform->showavailability; } if (isset($fromform->showdescription)) { $newcm->showdescription = $fromform->showdescription; } else { $newcm->showdescription = 0; } if (!($fromform->coursemodule = add_course_module($newcm))) { print_error('cannotaddcoursemodule'); } if (plugin_supports('mod', $fromform->modulename, FEATURE_MOD_INTRO, true)) { $draftid_editor = file_get_submitted_draft_itemid('introeditor'); file_prepare_draft_area($draftid_editor, null, null, null, null); $fromform->introeditor = array('text' => '', 'format' => FORMAT_HTML, 'itemid' => $draftid_editor); // TODO: add better default } if (plugin_supports('mod', $fromform->modulename, FEATURE_MOD_INTRO, true)) { $introeditor = $fromform->introeditor; unset($fromform->introeditor); $fromform->intro = $introeditor['text']; $fromform->introformat = $introeditor['format']; } $addinstancefunction = $fromform->modulename . "_add_instance"; $updateinstancefunction = $fromform->modulename . "_update_instance"; $returnfromfunc = $addinstancefunction($fromform, $mform); // $returnfromfunc = url_add_instance($fromform, $mform); if (!$returnfromfunc or !is_number($returnfromfunc)) { // undo everything we can $modcontext = get_context_instance(CONTEXT_MODULE, $fromform->coursemodule); delete_context(CONTEXT_MODULE, $fromform->coursemodule); $DB->delete_records('course_modules', array('id' => $fromform->coursemodule)); if (!is_number($returnfromfunc)) { print_error('invalidfunction', '', course_get_url($course, $cw->section)); } else { print_error('cannotaddnewmodule', '', course_get_url($course, $cw->section), $fromform->modulename); } } $fromform->instance = $returnfromfunc; $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id' => $fromform->coursemodule)); // update embedded links and save files $modcontext = get_context_instance(CONTEXT_MODULE, $fromform->coursemodule); if (!empty($introeditor)) { $fromform->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id, 'mod_' . $fromform->modulename, 'intro', 0, array('subdirs' => true), $introeditor['text']); $DB->set_field($fromform->modulename, 'intro', $fromform->intro, array('id' => $fromform->instance)); } // course_modules and course_sections each contain a reference // to each other, so we have to update one of them twice. $sectionid = add_mod_to_section($fromform); $DB->set_field('course_modules', 'section', $sectionid, array('id' => $fromform->coursemodule)); // make sure visibility is set correctly (in particular in calendar) set_coursemodule_visible($fromform->coursemodule, $fromform->visible); if (isset($fromform->cmidnumber)) { //label // set cm idnumber set_coursemodule_idnumber($fromform->coursemodule, $fromform->cmidnumber); } // Set up conditions if ($CFG->enableavailability) { condition_info::update_cm_from_form((object) array('id' => $fromform->coursemodule), $fromform, false); } $eventname = 'mod_created'; add_to_log($course->id, "course", "add mod", "../mod/{$fromform->modulename}/view.php?id={$fromform->coursemodule}", "{$fromform->modulename} {$fromform->instance}"); add_to_log($course->id, $fromform->modulename, "add", "view.php?id={$fromform->coursemodule}", "{$fromform->instance}", $fromform->coursemodule); // Trigger mod_created/mod_updated event with information about this module. $eventdata = new stdClass(); $eventdata->modulename = $fromform->modulename; $eventdata->name = $fromform->name; $eventdata->cmid = $fromform->coursemodule; $eventdata->courseid = $course->id; $eventdata->userid = $USER->id; events_trigger($eventname, $eventdata); rebuild_course_cache($course->id); return 1; }
/** * Given an object containing all the necessary data, * create a new discussion and return the id * * @param object $post * @param mixed $mform * @param string $unused * @param int $userid * @return object */ function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) { global $USER, $CFG, $DB; $timenow = time(); if (is_null($userid)) { $userid = $USER->id; } // The first post is stored as a real post, and linked // to from the discuss entry. $forum = $DB->get_record('forum', array('id'=>$discussion->forum)); $cm = get_coursemodule_from_instance('forum', $forum->id); $post = new stdClass(); $post->discussion = 0; $post->parent = 0; $post->userid = $userid; $post->created = $timenow; $post->modified = $timenow; $post->mailed = FORUM_MAILED_PENDING; $post->subject = $discussion->name; $post->message = $discussion->message; $post->messageformat = $discussion->messageformat; $post->messagetrust = $discussion->messagetrust; $post->attachments = isset($discussion->attachments) ? $discussion->attachments : null; $post->forum = $forum->id; // speedup $post->course = $forum->course; // speedup $post->mailnow = $discussion->mailnow; $post->id = $DB->insert_record("forum_posts", $post); // TODO: Fix the calling code so that there always is a $cm when this function is called if (!empty($cm->id) && !empty($discussion->itemid)) { // In "single simple discussions" this may not exist yet $context = context_module::instance($cm->id); $text = file_save_draft_area_files($discussion->itemid, $context->id, 'mod_forum', 'post', $post->id, mod_forum_post_form::editor_options(), $post->message); $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id)); } // Now do the main entry for the discussion, linking to this first post $discussion->firstpost = $post->id; $discussion->timemodified = $timenow; $discussion->usermodified = $post->userid; $discussion->userid = $userid; $post->discussion = $DB->insert_record("forum_discussions", $discussion); // Finally, set the pointer on the post. $DB->set_field("forum_posts", "discussion", $post->discussion, array("id"=>$post->id)); if (!empty($cm->id)) { forum_add_attachment($post, $forum, $cm, $mform, $unused); } if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) { forum_tp_mark_post_read($post->userid, $post, $post->forum); } // Let Moodle know that assessable content is uploaded (eg for plagiarism detection) if (!empty($cm->id)) { forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion'); } return $post->discussion; }
/** * Save the file belonging to one text field. * * @param array $field the data from the form (or from import). This will * normally have come from the formslib editor element, so it will be an * array with keys 'text', 'format' and 'itemid'. However, when we are * importing, it will be an array with keys 'text', 'format' and 'files' * @param object $context the context the question is in. * @param string $component indentifies the file area question. * @param string $filearea indentifies the file area questiontext, * generalfeedback, answerfeedback, etc. * @param int $itemid identifies the file area. * * @return string the text for this field, after files have been processed. */ protected function import_or_save_files($field, $context, $component, $filearea, $itemid) { if (!empty($field['itemid'])) { // This is the normal case. We are safing the questions editing form. return file_save_draft_area_files($field['itemid'], $context->id, $component, $filearea, $itemid, $this->fileoptions, trim($field['text'])); } else if (!empty($field['files'])) { // This is the case when we are doing an import. foreach ($field['files'] as $file) { $this->import_file($context, $component, $filearea, $itemid, $file); } } return trim($field['text']); }