Ejemplo n.º 1
0
 /**
  * If there is no submission record then we are creating one. Text content should be submitted.
  * If a file has already been submitted then check whether the identifier is the same, if it is do nothing.
  * If it's not then either edit submission or create new one depending on module settings.
  */
 public function tii_submission($cm, $tiiassignmentid, $user, $submitter, $identifier, $submissiontype, $itemid = 0, $title = '', $textcontent = '', $cronerror = '')
 {
     global $CFG, $DB, $USER, $turnitinacceptedfiles;
     // Get config, module and course settings that we need.
     $config = turnitintooltwo_admin_config();
     $settings = $this->get_settings($cm->id);
     $moduledata = $DB->get_record($cm->modname, array('id' => $cm->instance));
     $coursedata = $this->get_course_data($cm->id, $cm->course, 'cron');
     // Update user's details on Turnitin.
     $user->edit_tii_user();
     // Clean up old Turnitin submission files.
     if ($itemid != 0 && $submissiontype == 'file' && $cm->modname != 'forum') {
         $this->clean_old_turnitin_submissions($cm, $user->id, $itemid, $submissiontype, $identifier);
     }
     // Work out submission method.
     // If this file has successfully submitted in the past then break, text content is to be submitted.
     switch ($submissiontype) {
         case 'file':
         case 'text_content':
             // Get file data or prepare text submission.
             if ($submissiontype == 'file') {
                 $fs = get_file_storage();
                 $file = $fs->get_file_by_hash($identifier);
                 $title = $file->get_filename();
                 $timemodified = $file->get_timemodified();
                 $filename = $file->get_filename();
                 $textcontent = $file->get_content();
             } else {
                 // Check when text submission was last modified.
                 switch ($cm->modname) {
                     case 'assign':
                         $moodlesubmission = $DB->get_record('assign_submission', array('assignment' => $cm->instance, 'userid' => $user->id, 'id' => $itemid), 'timemodified');
                         break;
                     case 'workshop':
                         $moodlesubmission = $DB->get_record('workshop_submissions', array('workshopid' => $cm->instance, 'authorid' => $user->id), 'timemodified');
                         break;
                 }
                 $title = !empty($title) ? $title : 'onlinetext_' . $user->id . "_" . $cm->id . "_" . $cm->instance . '.txt';
                 $filename = substr($title, -4) == '.txt' ? $title : $title . '.txt';
                 $textcontent = strip_tags($textcontent);
                 $timemodified = $moodlesubmission->timemodified;
             }
             // Get submission method depending on whether there has been a previous submission.
             $submissionfields = 'id, cm, externalid, identifier, statuscode, lastmodified, attempt';
             $typefield = $CFG->dbtype == "oci" ? " to_char(submissiontype) " : " submissiontype ";
             // Double check there is only one submission.
             $previoussubmissions = $DB->get_records_select('plagiarism_turnitin_files', " cm = ? AND userid = ? AND " . $typefield . " = ? AND identifier = ? ", array($cm->id, $user->id, $submissiontype, $identifier), 'id', $submissionfields);
             $previoussubmission = end($previoussubmissions);
             if ($previoussubmission) {
                 // Don't submit if submission hasn't changed.
                 if (in_array($previoussubmission->statuscode, array("success", "error")) && $timemodified <= $previoussubmission->lastmodified) {
                     return true;
                 } else {
                     if ($settings["plagiarism_report_gen"] > 0) {
                         // Replace if Turnitin assignment allows resubmissions or create if we have no Turnitin id stored.
                         $submissionid = $previoussubmission->id;
                         $apimethod = is_null($previoussubmission->externalid) ? "createSubmission" : "replaceSubmission";
                         $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                     } else {
                         $apimethod = "createSubmission";
                         if ($previoussubmission->statuscode != "success") {
                             $submissionid = $previoussubmission->id;
                             $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                         } else {
                             $submissionid = $this->create_new_tii_submission($cm, $user, $identifier, $submissiontype);
                         }
                     }
                 }
             } else {
                 // Check if there is previous submission of text content which we will replace
                 $typefield = $CFG->dbtype == "oci" ? " to_char(submissiontype) " : " submissiontype ";
                 if ($submissiontype == 'text_content' && ($previoussubmission = $DB->get_record_select('plagiarism_turnitin_files', " cm = ? AND userid = ? AND " . $typefield . " = ? ", array($cm->id, $user->id, 'text_content'), 'id, cm, externalid, identifier, statuscode, lastmodified, attempt', 0, 1))) {
                     $submissionid = $previoussubmission->id;
                     $apimethod = is_null($previoussubmission->externalid) || $settings["plagiarism_report_gen"] == 0 ? "createSubmission" : "replaceSubmission";
                     // Delete old text content submissions from Turnitin if not replacing.
                     if ($settings["plagiarism_report_gen"] == 0 && !is_null($previoussubmission->externalid)) {
                         $this->delete_tii_submission($previoussubmission->externalid);
                     }
                     $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                 } else {
                     $apimethod = "createSubmission";
                     $submissionid = $this->create_new_tii_submission($cm, $user, $identifier, $submissiontype);
                 }
             }
             // Remove any old text submissions here if there are any as there is only one per submission
             if ($itemid != 0 && $submissiontype == "text_content") {
                 $this->clean_old_turnitin_submissions($cm, $user->id, $itemid, $submissiontype, $identifier);
             }
             break;
         case 'forum_post':
             if ($previoussubmissions = $DB->get_records_select('plagiarism_turnitin_files', " cm = ? AND userid = ? AND identifier = ? ", array($cm->id, $user->id, $identifier), 'id DESC', 'id, cm, externalid, identifier, statuscode, attempt', 0, 1)) {
                 $previoussubmission = current($previoussubmissions);
                 if ($previoussubmission->statuscode == "success") {
                     return true;
                 } else {
                     $submissionid = $previoussubmission->id;
                     $apimethod = "replaceSubmission";
                     $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                 }
             } else {
                 $apimethod = "createSubmission";
                 $submissionid = $this->create_new_tii_submission($cm, $user, $identifier, $submissiontype);
             }
             $forum_post = $DB->get_record_select('forum_posts', " userid = ? AND id = ? ", array($user->id, $itemid));
             $textcontent = strip_tags($forum_post->message);
             $filename = $title;
             break;
     }
     // Take care of any errors from plugin side.
     $errorcode = 0;
     // Do not submit if we're not accepting anything and content is less than 20 words or 100 characters.
     $content = explode(' ', $textcontent);
     if ($settings['plagiarism_allow_non_or_submissions'] != 1 && (strlen($textcontent) < 100 || count($content) < 20) || empty($textcontent)) {
         $errorcode = 1;
     }
     // Check file is less than maximum allowed size.
     if ($submissiontype == 'file') {
         if ($file->get_filesize() > TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE) {
             $errorcode = 2;
         }
     }
     // Don't submit if a user has not accepted the eula.
     if ($user->id == $submitter && $user->user_agreement_accepted != 1) {
         $errorcode = 3;
     }
     // If applicable, check whether file type is accepted.
     $acceptanyfiletype = !empty($settings["plagiarism_allow_non_or_submissions"]) ? 1 : 0;
     if (!$acceptanyfiletype && $submissiontype == 'file') {
         $filenameparts = explode('.', $filename);
         $fileext = end($filenameparts);
         if (!in_array("." . $fileext, $turnitinacceptedfiles)) {
             $errorcode = 4;
         }
     }
     // Any errors from cron processing take prioirity.
     if (!empty($cronerror)) {
         $errorcode = $cronerror;
     }
     // Save failed submission and don't process any further.
     if ($errorcode != 0) {
         return $this->save_failed_submission($cm, $user, $submissionid, $identifier, $submissiontype, $errorcode, $previoussubmission);
     }
     // Read the stored file/content into a temp file for submitting.
     $submission_title = explode('.', $title);
     $file_string = array($submission_title[0], $cm->id);
     // Only include user's name and id if we're not using blind marking and student privacy.
     if (empty($moduledata->blindmarking) && empty($config->enablepseudo)) {
         $user_details = array($user->id, $user->firstname, $user->lastname);
         $file_string = array_merge($user_details, $file_string);
     }
     $tempfile = turnitintooltwo_tempfile($file_string, $filename);
     $fh = fopen($tempfile, "w");
     fwrite($fh, $textcontent);
     fclose($fh);
     // Create submission object.
     $submission = new TiiSubmission();
     $submission->setAssignmentId($tiiassignmentid);
     if ($apimethod == "replaceSubmission") {
         $submission->setSubmissionId($previoussubmission->externalid);
     }
     $submission->setTitle($title);
     $submission->setAuthorUserId($user->tii_user_id);
     // Account for submission by teacher in assignment module.
     if ($user->id == $submitter) {
         $submission->setSubmitterUserId($user->tii_user_id);
         $submission->setRole('Learner');
     } else {
         $instructor = new turnitintooltwo_user($submitter, 'Instructor');
         $instructor->edit_tii_user();
         $submission->setSubmitterUserId($instructor->tii_user_id);
         $submission->setRole('Instructor');
     }
     $submission->setSubmissionDataPath($tempfile);
     // Initialise Comms Object.
     $turnitincomms = new turnitin_comms();
     $turnitincall = $turnitincomms->initialise_api();
     try {
         $response = $turnitincall->{$apimethod}($submission);
         $newsubmission = $response->getSubmission();
         $newsubmissionid = $newsubmission->getSubmissionId();
         $plagiarismfile = new object();
         if ($apimethod == "replaceSubmission" || $submissionid != 0) {
             $plagiarismfile->id = $submissionid;
         }
         $plagiarismfile->cm = $cm->id;
         $plagiarismfile->userid = $user->id;
         $plagiarismfile->submitter = $submitter;
         $plagiarismfile->identifier = $identifier;
         $plagiarismfile->externalid = $newsubmissionid;
         $plagiarismfile->statuscode = 'success';
         $plagiarismfile->similarityscore = null;
         $plagiarismfile->attempt = !empty($previoussubmission) ? $previoussubmission->attempt + 1 : 1;
         $plagiarismfile->transmatch = 0;
         $plagiarismfile->lastmodified = time();
         $plagiarismfile->submissiontype = $submissiontype;
         $plagiarismfile->errorcode = null;
         $plagiarismfile->errormsg = null;
         if ($apimethod == "replaceSubmission" || $submissionid != 0) {
             if (!$DB->update_record('plagiarism_turnitin_files', $plagiarismfile)) {
                 turnitintooltwo_activitylog("Update record failed (CM: " . $cm->id . ", User: "******")", "PP_UPDATE_SUB");
             }
         } else {
             if (!($fileid = $DB->insert_record('plagiarism_turnitin_files', $plagiarismfile))) {
                 turnitintooltwo_activitylog("Insert record failed (CM: " . $cm->id . ", User: "******")", "PP_INSERT_SUB");
             }
         }
         // Delete the tempfile.
         if (!is_null($tempfile)) {
             unlink($tempfile);
         }
         // Add config field to show submissions have been made which we use to lock anonymous marking setting
         $configfield = new object();
         $configfield->cm = $cm->id;
         $configfield->name = 'submitted';
         $configfield->value = 1;
         if (!($currentconfigfield = $DB->get_field('plagiarism_turnitin_config', 'id', array('cm' => $cm->id, 'name' => 'submitted')))) {
             if (!$DB->insert_record('plagiarism_turnitin_config', $configfield)) {
                 turnitintooltwo_print_error('defaultupdateerror', 'turnitintooltwo', null, null, __FILE__, __LINE__);
             }
         }
         // Send a message to the user's Moodle inbox with the digital receipt.
         $receipt = new receipt_message();
         $input = array('firstname' => $user->firstname, 'lastname' => $user->lastname, 'submission_title' => $title, 'assignment_name' => $moduledata->name, 'course_fullname' => $coursedata->turnitin_ctl, 'submission_date' => date('d-M-Y h:iA'), 'submission_id' => $newsubmissionid);
         $message = $receipt->build_message($input);
         $receipt->send_message($user->id, $message);
         // Output a message in the cron for successfull submission to Turnitin.
         $outputvars = new stdClass();
         $outputvars->title = $title;
         $outputvars->submissionid = $newsubmissionid;
         $outputvars->assignmentname = $moduledata->name;
         $outputvars->coursename = $coursedata->turnitin_ctl;
         mtrace(get_string('cronsubmittedsuccessfully', 'turnitintooltwo', $outputvars));
     } catch (Exception $e) {
         $errorstring = empty($previoussubmission->externalid) ? "pp_createsubmissionerror" : "pp_updatesubmissionerror";
         $plagiarismfile = new object();
         if ($submissionid != 0) {
             $plagiarismfile->id = $submissionid;
         }
         $plagiarismfile->attempt = !empty($previoussubmission) ? $previoussubmission->attempt + 1 : 1;
         $plagiarismfile->cm = $cm->id;
         $plagiarismfile->userid = $user->id;
         $plagiarismfile->submitter = $submitter;
         $plagiarismfile->identifier = $identifier;
         $plagiarismfile->statuscode = 'error';
         $plagiarismfile->lastmodified = time();
         $plagiarismfile->submissiontype = $submissiontype;
         $plagiarismfile->errorcode = 0;
         $plagiarismfile->errormsg = get_string('pp_submission_error', 'turnitintooltwo') . ' ' . $e->getMessage();
         if ($submissionid != 0) {
             if (!$DB->update_record('plagiarism_turnitin_files', $plagiarismfile)) {
                 turnitintooltwo_activitylog("Update record failed (CM: " . $cm->id . ", User: "******") - ", "PP_UPDATE_SUB_ERROR");
             }
         } else {
             if (!($fileid = $DB->insert_record('plagiarism_turnitin_files', $plagiarismfile))) {
                 turnitintooltwo_activitylog("Insert record failed (CM: " . $cm->id . ", User: "******") - ", "PP_INSERT_SUB_ERROR");
             }
         }
         $turnitincomms->handle_exceptions($e, $errorstring, false);
         mtrace('-------------------------');
         mtrace(get_string('pp_submission_error', 'turnitintooltwo') . ': ' . $e->getMessage());
         mtrace('User:  '******' - ' . $user->firstname . ' ' . $user->lastname . ' (' . $user->email . ')');
         mtrace('Course Module: ' . $cm->id . '');
         mtrace('-------------------------');
     }
     return true;
 }
Ejemplo n.º 2
0
 /**
  * If there is no submission record then we are creating one. Text content should be submitted.
  * If a file has already been submitted then check whether the identifier is the same, if it is do nothing.
  * If it's not then either edit submission or create new one depending on module settings.
  */
 public function tii_submission($cm, $tiiassignmentid, $user, $identifier, $submissiontype, $itemid = 0, $title = '', $textcontent = '', $context = 'instant')
 {
     global $CFG, $DB, $USER;
     $settings = $this->get_settings($cm->id);
     // Update user's details on Turnitin.
     $user->edit_tii_user();
     // Clean up old Turnitin submission files.
     if ($itemid != 0 && $submissiontype == 'file' && $cm->modname != 'forum') {
         $this->clean_old_turnitin_submissions($cm, $user->id, $itemid, $submissiontype, $identifier);
     }
     // Work out submission method.
     // If this file has successfully submitted in the past then break, text content is to be submitted.
     switch ($submissiontype) {
         case 'file':
         case 'text_content':
             // Get file data or prepare text submission.
             if ($submissiontype == 'file') {
                 $fs = get_file_storage();
                 $file = $fs->get_file_by_hash($identifier);
                 $title = $file->get_filename();
                 $timemodified = $file->get_timemodified();
                 $filename = $file->get_filename();
                 $textcontent = $file->get_content();
             } else {
                 // If we are submitting text_content via AJAX there will be no actual content passed in so we need to grab it.
                 if ($textcontent == '') {
                     switch ($cm->modname) {
                         case 'assign':
                             // Check whether submission is a group submission so we can get the correct content.
                             // Note: This will not work if the submitting user is in multiple groups.
                             $submissionsquery = array('assignment' => $cm->instance);
                             $submissionsquery['userid'] = $user->id;
                             if ($CFG->branch > 23) {
                                 $moduledata = $DB->get_record($cm->modname, array('id' => $cm->instance));
                                 if ($moduledata->teamsubmission) {
                                     require_once $CFG->dirroot . '/mod/assign/locallib.php';
                                     $context = context_course::instance($cm->course);
                                     $assignment = new assign($context, $cm, null);
                                     $submissionsquery['userid'] = 0;
                                     $submissionsquery['groupid'] = 0;
                                     if ($group = $assignment->get_submission_group($user->id)) {
                                         $submissionsquery['groupid'] = $group->id;
                                     }
                                 }
                             }
                             // This will need to be reworked when linkarray in get_links() contains submission id.
                             $moodlesubmissions = $DB->get_records('assign_submission', $submissionsquery, 'id, timemodified');
                             $moodlesubmission = end($moodlesubmissions);
                             $moodletextsubmission = $DB->get_record('assignsubmission_onlinetext', array('submission' => $moodlesubmission->id), 'onlinetext');
                             $timemodified = $moodlesubmission->timemodified;
                             $textcontent = strip_tags($moodletextsubmission->onlinetext);
                             break;
                         case 'workshop':
                             $moodlesubmission = $DB->get_record('workshop_submissions', array('workshopid' => $cm->instance, 'authorid' => $user->id), 'title, content, timemodified');
                             $timemodified = $moodlesubmission->timemodified;
                             $textcontent = strip_tags($moodlesubmission->content);
                             $title = $moodlesubmission->title;
                             break;
                     }
                 } else {
                     switch ($cm->modname) {
                         case 'assign':
                             $moodlesubmission = $DB->get_record('assign_submission', array('assignment' => $cm->instance, 'userid' => $user->id, 'id' => $itemid), 'id, timemodified');
                             $timemodified = $moodlesubmission->timemodified;
                             $textcontent = strip_tags($textcontent);
                             break;
                         case 'workshop':
                             $moodlesubmission = $DB->get_record('workshop_submissions', array('workshopid' => $cm->instance, 'authorid' => $user->id), 'title, content, timemodified');
                             $timemodified = $moodlesubmission->timemodified;
                             $textcontent = strip_tags($textcontent);
                             break;
                     }
                 }
                 $title = !empty($title) ? $title : 'onlinetext_' . $user->id . "_" . $cm->id . "_" . $cm->instance . '.txt';
                 $filename = substr($title, -4) == '.txt' ? $title : $title . '.txt';
             }
             // Get submission method depending on whether there has been a previous submission.
             $submissionfields = 'id, cm, externalid, identifier, statuscode, lastmodified, attempt, errorcode';
             $typefield = $CFG->dbtype == "oci" ? " to_char(submissiontype) " : " submissiontype ";
             // Double check there is only one submission.
             $previoussubmissions = $DB->get_records_select('plagiarism_turnitin_files', " cm = ? AND userid = ? AND " . $typefield . " = ? AND identifier = ? ", array($cm->id, $user->id, $submissiontype, $identifier), 'id', $submissionfields);
             $previoussubmission = end($previoussubmissions);
             if ($previoussubmission) {
                 $errorcode = (int) $previoussubmission->errorcode;
                 // Don't submit if submission hasn't changed.
                 if ($previoussubmission->statuscode == "success" && ($submissiontype == 'file' && $timemodified <= $previoussubmission->lastmodified || $submissiontype != 'file')) {
                     return true;
                 } else {
                     if ($previoussubmission->statuscode == "error" && $timemodified <= $previoussubmission->lastmodified) {
                         $return["success"] = false;
                         $return["message"] = get_string('errorcode' . $errorcode, 'turnitintooltwo');
                         return $return;
                     } else {
                         if ($previoussubmission->attempt >= 5) {
                             // Do not submit if 5 attempts have been made previously.
                             if ($context == 'cron') {
                                 mtrace('-------------------------');
                                 mtrace(get_string('pastfiveattempts', 'turnitintooltwo') . ':');
                                 mtrace('User:  '******' - ' . $user->firstname . ' ' . $user->lastname . ' (' . $user->email . ')');
                                 mtrace('Course Module: ' . $cm->id . '');
                                 mtrace('-------------------------');
                                 return true;
                             }
                             $return["success"] = false;
                             $return["message"] = get_string('pastfiveattempts', 'turnitintooltwo');
                             return $return;
                         } else {
                             if ($settings["plagiarism_report_gen"] > 0) {
                                 // Replace if Turnitin assignment allows resubmissions or create if we have no Turnitin id stored.
                                 $submissionid = $previoussubmission->id;
                                 $apimethod = is_null($previoussubmission->externalid) ? "createSubmission" : "replaceSubmission";
                                 $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                             } else {
                                 $apimethod = "createSubmission";
                                 if ($previoussubmission->statuscode != "success") {
                                     $submissionid = $previoussubmission->id;
                                     $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                                 } else {
                                     $submissionid = $this->create_new_tii_submission($cm, $user, $identifier, $submissiontype);
                                 }
                             }
                         }
                     }
                 }
             } else {
                 // Check if there is previous submission of text content which we will replace
                 $typefield = $CFG->dbtype == "oci" ? " to_char(submissiontype) " : " submissiontype ";
                 if ($submissiontype == 'text_content' && ($previoussubmission = $DB->get_record_select('plagiarism_turnitin_files', " cm = ? AND userid = ? AND " . $typefield . " = ? ", array($cm->id, $user->id, 'text_content'), 'id, cm, externalid, identifier, statuscode, lastmodified', 0, 1))) {
                     $submissionid = $previoussubmission->id;
                     $apimethod = is_null($previoussubmission->externalid) || $settings["plagiarism_report_gen"] == 0 ? "createSubmission" : "replaceSubmission";
                     // Delete old text content submissions from Turnitin if not replacing.
                     if ($settings["plagiarism_report_gen"] == 0 && !is_null($previoussubmission->externalid)) {
                         $this->delete_tii_submission($previoussubmission->externalid);
                     }
                     $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                 } else {
                     $apimethod = "createSubmission";
                     $submissionid = $this->create_new_tii_submission($cm, $user, $identifier, $submissiontype);
                 }
             }
             // Remove any old text submissions here if there are any as there is only one per submission
             if ($itemid != 0 && $submissiontype == "text_content") {
                 $this->clean_old_turnitin_submissions($cm, $user->id, $itemid, $submissiontype, $identifier);
             }
             break;
         case 'forum_post':
             if ($previoussubmissions = $DB->get_records_select('plagiarism_turnitin_files', " cm = ? AND userid = ? AND identifier = ? ", array($cm->id, $user->id, $identifier), 'id DESC', 'id, cm, externalid, identifier, statuscode', 0, 1)) {
                 $previoussubmission = current($previoussubmissions);
                 if ($previoussubmission->statuscode == "success") {
                     return true;
                 } else {
                     $submissionid = $previoussubmission->id;
                     $apimethod = "replaceSubmission";
                     $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                 }
             } else {
                 $apimethod = "createSubmission";
                 $submissionid = $this->create_new_tii_submission($cm, $user, $identifier, $submissiontype);
             }
             $forum_post = $DB->get_record_select('forum_posts', " userid = ? AND id = ? ", array($user->id, $itemid));
             $textcontent = strip_tags($forum_post->message);
             $filename = $title;
             break;
     }
     // Do not submit if this is text_content and we're not accepting anything and
     // content is less than 20 words or 100 characters.
     if ($submissiontype != 'file') {
         $content = explode(' ', $textcontent);
         if ($settings['plagiarism_allow_non_or_submissions'] != 1 && (strlen($textcontent) < 100 || count($content) < 20) || empty($textcontent)) {
             $plagiarismfile = new object();
             if ($submissionid != 0) {
                 $plagiarismfile->id = $submissionid;
             }
             $plagiarismfile->cm = $cm->id;
             $plagiarismfile->userid = $user->id;
             $plagiarismfile->identifier = $identifier;
             $plagiarismfile->statuscode = 'error';
             $plagiarismfile->errorcode = 1;
             $plagiarismfile->attempt = 1;
             $plagiarismfile->lastmodified = time();
             $plagiarismfile->submissiontype = $submissiontype;
             if ($submissionid != 0) {
                 if (!$DB->update_record('plagiarism_turnitin_files', $plagiarismfile)) {
                     turnitintooltwo_activitylog("Update record failed (CM: " . $cm->id . ", User: "******") - ", "PP_UPDATE_SUB_ERROR");
                 }
             } else {
                 if (!($fileid = $DB->insert_record('plagiarism_turnitin_files', $plagiarismfile))) {
                     turnitintooltwo_activitylog("Insert record failed (CM: " . $cm->id . ", User: "******") - ", "PP_INSERT_SUB_ERROR");
                 }
             }
             if ($context == 'cron') {
                 mtrace('-------------------------');
                 mtrace(get_string('errorcode1', 'turnitintooltwo') . ':');
                 mtrace('User:  '******' - ' . $user->firstname . ' ' . $user->lastname . ' (' . $user->email . ')');
                 mtrace('Course Module: ' . $cm->id . '');
                 mtrace('-------------------------');
                 return true;
             }
             $return["success"] = false;
             $return["message"] = get_string('errorcode1', 'turnitintooltwo');
             return $return;
         }
     }
     // Check file is less than maximum allowed size.
     if ($submissiontype == 'file') {
         if ($file->get_filesize() > TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE) {
             $plagiarismfile = new object();
             if ($submissionid != 0) {
                 $plagiarismfile->id = $submissionid;
             }
             $plagiarismfile->cm = $cm->id;
             $plagiarismfile->userid = $user->id;
             $plagiarismfile->identifier = $identifier;
             $plagiarismfile->statuscode = 'error';
             $plagiarismfile->errorcode = 2;
             $plagiarismfile->attempt = 1;
             $plagiarismfile->lastmodified = time();
             $plagiarismfile->submissiontype = 'file';
             if ($submissionid != 0) {
                 if (!$DB->update_record('plagiarism_turnitin_files', $plagiarismfile)) {
                     turnitintooltwo_activitylog("Update record failed (CM: " . $cm->id . ", User: "******") - ", "PP_UPDATE_SUB_ERROR");
                 }
             } else {
                 if (!($fileid = $DB->insert_record('plagiarism_turnitin_files', $plagiarismfile))) {
                     turnitintooltwo_activitylog("Insert record failed (CM: " . $cm->id . ", User: "******") - ", "PP_INSERT_SUB_ERROR");
                 }
             }
             if ($context == 'cron') {
                 mtrace('-------------------------');
                 mtrace(get_string('errorcode2', 'turnitintooltwo') . ':');
                 mtrace('User:  '******' - ' . $user->firstname . ' ' . $user->lastname . ' (' . $user->email . ')');
                 mtrace('Course Module: ' . $cm->id . '');
                 mtrace('-------------------------');
                 return true;
             }
             $return["success"] = false;
             $return["message"] = get_string('errorcode2', 'turnitintooltwo', display_size(TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE));
             return $return;
         }
     }
     // Read the stored file/content into a temp file for submitting.
     $submission_title = explode('.', $title);
     $file_string = array($submission_title[0], $cm->id);
     $modulepluginsettings = $this->get_settings($cm->id);
     if (!$modulepluginsettings["plagiarism_anonymity"]) {
         $user_details = array($user->id, $user->firstname, $user->lastname);
         $file_string = array_merge($user_details, $file_string);
     }
     $tempfile = turnitintooltwo_tempfile($file_string, $filename);
     $fh = fopen($tempfile, "w");
     fwrite($fh, $textcontent);
     fclose($fh);
     // Create submission object.
     $submission = new TiiSubmission();
     $submission->setAssignmentId($tiiassignmentid);
     if ($apimethod == "replaceSubmission") {
         $submission->setSubmissionId($previoussubmission->externalid);
     }
     $submission->setTitle($title);
     $submission->setAuthorUserId($user->tii_user_id);
     if ($user->id == $USER->id && !is_siteadmin()) {
         $submission->setSubmitterUserId($user->tii_user_id);
         $submission->setRole('Learner');
     } else {
         $instructor = new turnitintooltwo_user($USER->id, 'Instructor');
         $instructor->edit_tii_user();
         $submission->setSubmitterUserId($instructor->tii_user_id);
         $submission->setRole('Instructor');
     }
     $submission->setSubmissionDataPath($tempfile);
     // Initialise Comms Object.
     $turnitincomms = new turnitintooltwo_comms();
     $turnitincall = $turnitincomms->initialise_api();
     try {
         $response = $turnitincall->{$apimethod}($submission);
         $newsubmission = $response->getSubmission();
         $newsubmissionid = $newsubmission->getSubmissionId();
         $plagiarismfile = new object();
         if ($apimethod == "replaceSubmission" || $submissionid != 0) {
             $plagiarismfile->id = $submissionid;
         }
         $plagiarismfile->cm = $cm->id;
         $plagiarismfile->userid = $user->id;
         $plagiarismfile->identifier = $identifier;
         $plagiarismfile->externalid = $newsubmissionid;
         $plagiarismfile->statuscode = 'success';
         $plagiarismfile->similarityscore = null;
         $plagiarismfile->attempt = 1;
         $plagiarismfile->transmatch = 0;
         $plagiarismfile->lastmodified = time();
         $plagiarismfile->submissiontype = $submissiontype;
         $plagiarismfile->errorcode = null;
         $plagiarismfile->errormsg = null;
         if ($apimethod == "replaceSubmission" || $submissionid != 0) {
             if (!$DB->update_record('plagiarism_turnitin_files', $plagiarismfile)) {
                 turnitintooltwo_activitylog("Update record failed (CM: " . $cm->id . ", User: "******")", "PP_UPDATE_SUB");
             }
         } else {
             if (!($fileid = $DB->insert_record('plagiarism_turnitin_files', $plagiarismfile))) {
                 turnitintooltwo_activitylog("Insert record failed (CM: " . $cm->id . ", User: "******")", "PP_INSERT_SUB");
             }
         }
         // Delete the tempfile.
         if (!is_null($tempfile)) {
             unlink($tempfile);
         }
         // Add config field to show submissions have been made which we use to lock anonymous marking setting
         $configfield = new object();
         $configfield->cm = $cm->id;
         $configfield->name = 'submitted';
         $configfield->value = 1;
         if (!($currentconfigfield = $DB->get_field('plagiarism_turnitin_config', 'id', array('cm' => $cm->id, 'name' => 'submitted')))) {
             if (!$DB->insert_record('plagiarism_turnitin_config', $configfield)) {
                 turnitintooltwo_print_error('defaultupdateerror', 'turnitintooltwo', null, null, __FILE__, __LINE__);
             }
         }
         $return["success"] = true;
         $return["message"] = get_string('submissionuploadsuccess', 'turnitintooltwo') . '<br/>' . get_string('turnitinsubmissionid', 'turnitintooltwo') . ': ' . $newsubmissionid;
         //Send a message to the user's Moodle inbox with the digital receipt.
         if (!empty($CFG->smtphosts) && !empty($CFG->smtpuser) && !empty($CFG->smtppass)) {
             $receipt = new receipt_message();
             $moduledata = $DB->get_record($cm->modname, array('id' => $cm->instance));
             $coursedata = turnitintooltwo_assignment::get_course_data($cm->course, 'PP', 'cron');
             $input = array('firstname' => $user->firstname, 'lastname' => $user->lastname, 'submission_title' => $title, 'assignment_name' => $moduledata->name, 'course_fullname' => $coursedata->turnitin_ctl, 'submission_date' => date('d-M-Y h:iA'), 'submission_id' => $newsubmissionid);
             $message = $receipt->build_message($input);
             $receipt->send_message($user->id, $message);
         }
         if ($context == 'cron') {
             return true;
         }
     } catch (Exception $e) {
         $errorstring = empty($previoussubmission->externalid) ? "pp_createsubmissionerror" : "pp_updatesubmissionerror";
         $return["success"] = false;
         $return["message"] = get_string('pp_submission_error', 'turnitintooltwo') . ' ' . $e->getMessage();
         $plagiarismfile = new object();
         if ($submissionid != 0) {
             $plagiarismfile->id = $submissionid;
             // Get attempt no
             $current_record = $DB->get_record('plagiarism_turnitin_files', array("id" => $submissionid));
             $plagiarismfile->attempt = $current_record->attempt + 1;
         } else {
             $plagiarismfile->attempt = 1;
         }
         $plagiarismfile->cm = $cm->id;
         $plagiarismfile->userid = $user->id;
         $plagiarismfile->identifier = $identifier;
         $plagiarismfile->statuscode = 'error';
         $plagiarismfile->lastmodified = time();
         $plagiarismfile->submissiontype = $submissiontype;
         $plagiarismfile->errorcode = 0;
         $plagiarismfile->errormsg = $return["message"];
         if ($submissionid != 0) {
             if (!$DB->update_record('plagiarism_turnitin_files', $plagiarismfile)) {
                 turnitintooltwo_activitylog("Update record failed (CM: " . $cm->id . ", User: "******") - ", "PP_UPDATE_SUB_ERROR");
             }
         } else {
             if (!($fileid = $DB->insert_record('plagiarism_turnitin_files', $plagiarismfile))) {
                 turnitintooltwo_activitylog("Insert record failed (CM: " . $cm->id . ", User: "******") - ", "PP_INSERT_SUB_ERROR");
             }
         }
         $turnitincomms->handle_exceptions($e, $errorstring, false);
         if ($context == 'cron') {
             mtrace('-------------------------');
             mtrace(get_string('pp_submission_error', 'turnitintooltwo') . ': ' . $e->getMessage());
             mtrace('User:  '******' - ' . $user->firstname . ' ' . $user->lastname . ' (' . $user->email . ')');
             mtrace('Course Module: ' . $cm->id . '');
             mtrace('-------------------------');
             return false;
         }
     }
     return $return;
 }