/**
  * 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;
     // Instantiate error code
     $errorcode = 0;
     // 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, $user);
     }
     // 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();
                 try {
                     $textcontent = $file->get_content();
                 } catch (Exception $e) {
                     turnitintooltwo_activitylog('File content not found on submission: ' . $pathnamehash, 'PP_NO_FILE');
                     mtrace($e);
                     mtrace('File content not found on submission. pathnamehash: ' . $pathnamehash);
                     $errorcode = 9;
                 }
             } 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($cm, $previoussubmission->externalid, $user);
                     }
                     $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, $user);
             }
             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;
     }
     // 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 = strtolower(end($filenameparts));
         if (!in_array("." . $fileext, $turnitinacceptedfiles)) {
             $errorcode = 4;
         }
     }
     // 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);
     }
     try {
         $tempfile = turnitintooltwo_tempfile($file_string, $filename);
     } catch (Exception $e) {
         $errorcode = 8;
     }
     // 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);
     }
     $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 stdClass();
         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 stdClass();
         $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', 'plagiarism_turnitin', null, null, __FILE__, __LINE__);
             }
         }
         // Send a message to the user's Moodle inbox with the digital receipt.
         $receipt = new pp_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', 'plagiarism_turnitin', $outputvars));
     } catch (Exception $e) {
         $errorstring = empty($previoussubmission->externalid) ? "pp_createsubmissionerror" : "pp_updatesubmissionerror";
         $plagiarismfile = new stdClass();
         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', 'plagiarism_turnitin') . ' ' . $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', 'plagiarism_turnitin') . ': ' . $e->getMessage());
         mtrace('User:  '******' - ' . $user->firstname . ' ' . $user->lastname . ' (' . $user->email . ')');
         mtrace('Course Module: ' . $cm->id . '');
         mtrace('-------------------------');
     }
     return true;
 }
 /**
  * Make submission to Turnitin
  *
  * @global type $DB
  * @param object $cm the course module object
  * @return string $message to display to user
  */
 public function do_tii_submission($cm, $turnitintooltwoassignment)
 {
     global $DB, $USER, $CFG;
     $config = turnitintooltwo_admin_config();
     $notice = array("success" => false);
     $context = context_module::instance($cm->id);
     // Check if user is a member of class, if not then join them to it.
     $course = $turnitintooltwoassignment->get_course_data($turnitintooltwoassignment->turnitintooltwo->course);
     $user = new turnitintooltwo_user($this->userid, 'Learner');
     $user->join_user_to_class($course->turnitin_cid);
     $user->edit_tii_user();
     // Get the stored file and read it into a temp file for submitting to Turnitin.
     $fs = get_file_storage();
     $files = $fs->get_area_files($context->id, 'mod_turnitintooltwo', 'submissions', $this->id, "timecreated", false);
     $tempfile = "";
     foreach ($files as $file) {
         $filename = array($this->submission_title, $cm->id);
         if (!$turnitintooltwoassignment->turnitintooltwo->anon && empty($config->enablepseudo)) {
             $user_details = array($this->userid, $user->firstname, $user->lastname);
             $filename = array_merge($user_details, $filename);
         }
         $suffix = $file->get_filename();
         $tempfile = turnitintooltwo_tempfile($filename, $suffix);
         $fh = fopen($tempfile, "w");
         fwrite($fh, $file->get_content());
         fclose($fh);
     }
     if (!empty($tempfile)) {
         $part = $turnitintooltwoassignment->get_part_details($this->submission_part);
         // Initialise Comms Object.
         $turnitincomms = new turnitintooltwo_comms();
         $turnitincall = $turnitincomms->initialise_api();
         // Create Submission object to send to Turnitin.
         $newsubmission = new TiiSubmission();
         $newsubmission->setAssignmentId($part->tiiassignid);
         if (!is_null($this->submission_objectid)) {
             $newsubmission->setSubmissionId($this->submission_objectid);
             $apimethod = "replaceSubmission";
         } else {
             $apimethod = "createSubmission";
         }
         $newsubmission->setTitle($this->submission_title);
         $newsubmission->setAuthorUserId($user->tii_user_id);
         if ($user->id == $USER->id) {
             $newsubmission->setSubmitterUserId($user->tii_user_id);
             $newsubmission->setRole('Learner');
         } else {
             $instructor = new turnitintooltwo_user($USER->id, 'Instructor');
             $instructor->edit_tii_user();
             $newsubmission->setSubmitterUserId($instructor->tii_user_id);
             $newsubmission->setRole('Instructor');
         }
         $newsubmission->setSubmissionDataPath($tempfile);
         try {
             $response = $turnitincall->{$apimethod}($newsubmission);
             $newsubmission = $response->getSubmission();
             // Save the submission.
             $submission = new stdClass();
             $submission->id = $this->id;
             $submission->userid = $this->userid;
             $submission->turnitintooltwoid = $this->turnitintooltwoid;
             $submission->submission_part = $this->submission_part;
             $submission->submission_title = $this->submission_title;
             $submission->submission_type = $this->submission_type;
             $submission->submission_filename = $this->submission_filename;
             $submission->submission_objectid = $newsubmission->getSubmissionId();
             $submission->submission_score = $this->submission_score;
             $submission->submission_grade = $this->submission_grade;
             $submission->submission_gmimaged = $this->submission_gmimaged;
             $submission->submission_status = $this->submission_status;
             $submission->submission_queued = $this->submission_queued;
             $submission->submission_attempts = $this->submission_attempts;
             $submission->submission_modified = time();
             $submission->submission_nmuserid = $this->submission_nmuserid;
             $submission->submission_nmfirstname = $this->submission_nmfirstname;
             $submission->submission_nmlastname = $this->submission_nmlastname;
             $submission->submission_unanon = $this->submission_unanon;
             $submission->submission_unanonreason = $this->submission_unanonreason;
             $submission->submission_transmatch = $this->submission_transmatch;
             $submission->submission_acceptnothing = 0;
             $DB->update_record('turnitintooltwo_submissions', $submission);
             // Delete the tempfile.
             if (!is_null($tempfile)) {
                 unlink($tempfile);
             }
             $notice["success"] = true;
             $notice["message"] = get_string('submissionuploadsuccess', 'turnitintooltwo');
             $notice["extract"] = $newsubmission->getTextExtract();
             $notice["tii_submission_id"] = $submission->submission_objectid;
             //Send a message to the user's Moodle inbox with the digital receipt.
             $input = array('firstname' => $user->firstname, 'lastname' => $user->lastname, 'submission_title' => $this->submission_title, 'assignment_name' => $turnitintooltwoassignment->turnitintooltwo->name, 'assignment_part' => $partdetails = $turnitintooltwoassignment->get_part_details($this->submission_part)->partname, 'course_fullname' => $course->fullname, 'submission_date' => date('d-M-Y h:iA'), 'submission_id' => $submission->submission_objectid);
             // Student digital receipt
             $message = $this->receipt->build_message($input);
             $this->receipt->send_message($this->userid, $message);
             // Instructor digital receipt
             $this->submission_instructors = get_enrolled_users($context, 'mod/turnitintooltwo:grade', 0, 'u.id');
             if (!empty($this->submission_instructors)) {
                 $message = $this->instructor_receipt->build_instructor_message($input);
                 $this->instructor_receipt->send_instructor_message($this->submission_instructors, $message);
             }
             // Create a log entry for submission going to Turnitin.
             $logstring = $apimethod == "replaceSubmission" ? 'addresubmissiontiidesc' : 'addsubmissiontiidesc';
             turnitintooltwo_add_to_log($turnitintooltwoassignment->turnitintooltwo->course, "add submission", 'view.php?id=' . $cm->id, get_string($logstring, 'turnitintooltwo') . " '" . $this->submission_title . "'", $cm->id, $user->id);
             // Add to activity log.
             turnitintooltwo_activitylog("Action: Submission | Id: " . $this->turnitintooltwoid . " | Part: " . $submission->submission_part . " | User ID: " . $user->id . " (" . $user->tii_user_id . ") Submission title: " . $submission->submission_title, "REQUEST");
         } catch (Exception $e) {
             $errorstring = !is_null($this->submission_objectid) ? "updatesubmissionerror" : "createsubmissionerror";
             $error = $turnitincomms->handle_exceptions($e, $errorstring, false, true);
             $notice["message"] = $error;
             $notice["success"] = false;
         }
     } else {
         $notice["success"] = false;
         $notice["message"] = get_string('emptycreatedfile', 'turnitintooltwo');
     }
     return $notice;
 }
Example #3
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;
 }