/**
  * Update assignment from Turnitin
  *
  * @global type $DB
  * @param array $assignmentids array of assignment ids, if 0 then array is created inside
  * @return object
  */
 public function update_assignment_from_tii($assignmentids = 0)
 {
     global $DB;
     // Initialise Comms Object.
     $turnitincomms = new turnitintooltwo_comms();
     $turnitincall = $turnitincomms->initialise_api();
     if (!$assignmentids) {
         $parts = $this->get_parts();
         $assignments = array();
         foreach ($parts as $part) {
             $assignments[] = $part->tiiassignid;
             $partids[$part->tiiassignid] = $part->id;
         }
     } else {
         $assignments = $assignmentids;
     }
     $assignment = new TiiAssignment();
     try {
         if (count($assignments) == 1) {
             $assignment->setAssignmentId(current($assignments));
             $response = $turnitincall->readAssignment($assignment);
             $readassignments[0] = $response->getAssignment();
         } else {
             $assignment->setAssignmentIds($assignments);
             $response = $turnitincall->readAssignments($assignment);
             $readassignments = $response->getAssignments();
         }
         $assignmentdetails = "";
         $newparts = array();
         foreach ($readassignments as $readassignment) {
             $part = new stdClass();
             $part->dtstart = strtotime($readassignment->getStartDate());
             $part->dtdue = strtotime($readassignment->getDueDate());
             $part->dtpost = strtotime($readassignment->getFeedbackReleaseDate());
             $part->maxmarks = $readassignment->getMaxGrade();
             $part->tiiassignid = $readassignment->getAssignmentId();
             if ($assignmentids == 0) {
                 $part->id = $partids[$readassignment->getAssignmentId()];
                 if (!($dbpart = $DB->update_record('turnitintooltwo_parts', $part))) {
                     turnitintooltwo_activitylog(get_string('turnitintooltwoupdateerror', 'turnitintooltwo') . ' - ID: ' . $this->turnitintooltwo->id . ' - Part: ' . $part->id, 'API_ERROR');
                 }
             } else {
                 $part->partname = $readassignment->getTitle();
                 $newparts[] = $part;
             }
             // Update main turnitintooltwo details but only once.
             if (empty($assignmentdetails)) {
                 $assignmentdetails = new stdClass();
                 if ($assignmentids == 0) {
                     $assignmentdetails->id = $this->turnitintooltwo->id;
                 } else {
                     $assignmentdetails->timecreated = time();
                     $assignmentdetails->dateformat = "d/m/Y";
                     $assignmentdetails->autoupdates = 1;
                     $assignmentdetails->commentedittime = 1800;
                     $assignmentdetails->commentmaxsize = 800;
                     $assignmentdetails->autosubmission = 1;
                     $assignmentdetails->timemodified = time();
                     $assignmentdetails->intro = $readassignment->getInstructions();
                 }
                 $assignmentdetails->allowlate = $readassignment->getLateSubmissionsAllowed();
                 $assignmentdetails->reportgenspeed = $readassignment->getResubmissionRule();
                 $assignmentdetails->submitpapersto = $readassignment->getSubmitPapersTo();
                 $assignmentdetails->spapercheck = $readassignment->getSubmittedDocumentsCheck();
                 $assignmentdetails->internetcheck = $readassignment->getInternetCheck();
                 $assignmentdetails->journalcheck = $readassignment->getPublicationsCheck();
                 $assignmentdetails->studentreports = $readassignment->getAuthorOriginalityAccess();
                 $assignmentdetails->rubric = $readassignment->getRubricId();
                 $assignmentdetails->excludebiblio = $readassignment->getBibliographyExcluded();
                 $assignmentdetails->excludequoted = $readassignment->getQuotedExcluded();
                 $assignmentdetails->excludetype = $readassignment->getSmallMatchExclusionType();
                 $assignmentdetails->excludevalue = $readassignment->getSmallMatchExclusionThreshold();
                 $assignmentdetails->erater = $readassignment->getErater();
                 $assignmentdetails->erater_handbook = $readassignment->getEraterHandbook();
                 $assignmentdetails->erater_dictionary = $readassignment->getEraterSpellingDictionary();
                 $assignmentdetails->erater_spelling = (int) $readassignment->getEraterSpelling();
                 $assignmentdetails->erater_grammar = (int) $readassignment->getEraterGrammar();
                 $assignmentdetails->erater_usage = (int) $readassignment->getEraterUsage();
                 $assignmentdetails->erater_mechanics = (int) $readassignment->getEraterMechanics();
                 $assignmentdetails->erater_style = (int) $readassignment->getEraterStyle();
                 $assignmentdetails->transmatch = (int) $readassignment->getTranslatedMatching();
                 $assignmentdetails->allownonor = (int) $readassignment->getAllowNonOrSubmissions();
             }
             // Get Peermark Assignments.
             $peermarkassignments = $readassignment->getPeermarkAssignments();
             if (count($peermarkassignments)) {
                 $peermarkids = array();
                 foreach ($peermarkassignments as $peermarkassignment) {
                     $peermark = new stdClass();
                     $peermark->tiiassignid = $peermarkassignment->getAssignmentId();
                     $peermark->parent_tii_assign_id = $part->tiiassignid;
                     $peermark->dtstart = strtotime($peermarkassignment->getStartDate());
                     $peermark->dtdue = strtotime($peermarkassignment->getDueDate());
                     $peermark->dtpost = strtotime($peermarkassignment->getFeedbackReleaseDate());
                     $peermark->maxmarks = (int) $peermarkassignment->getMaxGrade();
                     $peermark->title = $peermarkassignment->getTitle();
                     $peermark->instructions = $peermarkassignment->getInstructions();
                     $peermark->distributed_reviews = (int) $peermarkassignment->getDistributedReviews();
                     $peermark->selected_reviews = (int) $peermarkassignment->getSelectedReviews();
                     $peermark->self_review = (int) $peermarkassignment->getSelfReviewRequired();
                     $peermark->non_submitters_review = (int) $peermarkassignment->getNonSubmittersToReview();
                     $currentpeermark = $DB->get_record('turnitintooltwo_peermarks', array('tiiassignid' => $peermark->tiiassignid));
                     if ($currentpeermark) {
                         $peermark->id = $currentpeermark->id;
                         $DB->update_record('turnitintooltwo_peermarks', $peermark);
                     } else {
                         $peermark->id = $DB->insert_record('turnitintooltwo_peermarks', $peermark);
                     }
                     $peermarkids[] = $peermark->id;
                 }
                 list($notinsql, $notinparams) = $DB->get_in_or_equal($peermarkids, SQL_PARAMS_QM, 'param', false);
                 $DB->delete_records_select('turnitintooltwo_peermarks', " parent_tii_assign_id = ? AND id " . $notinsql, array_merge(array($part->tiiassignid), $notinparams));
             } else {
                 $DB->delete_records('turnitintooltwo_peermarks', array('parent_tii_assign_id' => $part->tiiassignid));
             }
         }
         if ($assignmentids == 0) {
             if (!($update = $DB->update_record('turnitintooltwo', $assignmentdetails))) {
                 turnitintooltwo_activitylog(get_string('turnitintooltwoupdateerror', 'turnitintooltwo') . ' - ID: ' . $this->turnitintooltwo->id, 'API_ERROR');
             }
             $_SESSION["assignment_updated"][$this->turnitintooltwo->id] = time();
         } else {
             return array("turnitintooltwo" => $assignmentdetails, "parts" => $newparts);
         }
     } catch (Exception $e) {
         // We will use the locally stored assignment data if we can't connect to Turnitin.
         $turnitincomms->handle_exceptions($e, 'tiiassignmentgeterror', false);
     }
 }
$turnitintooltwoassignment = new turnitintooltwo_assignment($turnitintooltwo->id, $turnitintooltwo);
// Define file upload options.
$maxbytessite = $CFG->maxbytes == 0 || $CFG->maxbytes > TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE ? TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE : $CFG->maxbytes;
$maxbytescourse = $COURSE->maxbytes == 0 || $COURSE->maxbytes > TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE ? TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE : $COURSE->maxbytes;
$maxfilesize = get_user_max_upload_file_size(context_module::instance($cm->id), $maxbytessite, $maxbytescourse, $turnitintooltwoassignment->turnitintooltwo->maxfilesize);
$maxfilesize = $maxfilesize <= 0 ? TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE : $maxfilesize;
$turnitintooltwofileuploadoptions = array('maxbytes' => $maxfilesize, 'subdirs' => false, 'maxfiles' => 1, 'accepted_types' => '*');
if (!($parts = $turnitintooltwoassignment->get_parts())) {
    turnitintooltwo_print_error('partgeterror', 'turnitintooltwo', null, null, __FILE__, __LINE__);
}
// Get whether user is a tutor/student.
$istutor = has_capability('mod/turnitintooltwo:grade', context_module::instance($cm->id));
$userrole = $istutor ? 'Instructor' : 'Learner';
// Deal with actions here.
if (!empty($action)) {
    turnitintooltwo_activitylog("Action: " . $action . " | Id: " . $turnitintooltwo->id . " | Part: " . $part, "REQUEST");
    switch ($action) {
        case "delpart":
            if (!confirm_sesskey()) {
                throw new moodle_exception('invalidsesskey', 'error');
            }
            if ($turnitintooltwoassignment->delete_moodle_assignment_part($turnitintooltwoassignment->turnitintooltwo->id, $part)) {
                $_SESSION["notice"]['message'] = get_string('partdeleted', 'turnitintooltwo');
            }
            redirect(new moodle_url('/course/mod.php', array('update' => $cm->id, 'return' => true, 'sesskey' => sesskey())));
            exit;
            break;
        case "addtutor":
            if (!confirm_sesskey()) {
                throw new moodle_exception('invalidsesskey', 'error');
            }
 /**
  * Log API exceptions and print error to screen if required
  *
  * @param object $e
  * @param string $tterrorstr
  * @param boolean $toscreen
  */
 public static function handle_exceptions($e, $tterrorstr = "", $toscreen = true, $embedded = false)
 {
     $errorstr = "";
     if (!empty($tterrorstr)) {
         $errorstr = get_string($tterrorstr, 'turnitintooltwo') . "<br/><br/>";
         if ($embedded == true) {
             $errorstr .= get_string('tii_submission_failure', 'turnitintooltwo') . "<br/><br/>";
         }
     }
     if (is_callable(array($e, 'getFaultCode'))) {
         $errorstr .= get_string('faultcode', 'turnitintooltwo') . ": " . $e->getFaultCode() . " | ";
     }
     if (is_callable(array($e, 'getFile'))) {
         $errorstr .= get_string('file') . ": " . $e->getFile() . " | ";
     }
     if (is_callable(array($e, 'getLine'))) {
         $errorstr .= get_string('line', 'turnitintooltwo') . ": " . $e->getLine() . " | ";
     }
     if (is_callable(array($e, 'getMessage'))) {
         $errorstr .= get_string('message', 'turnitintooltwo') . ": " . $e->getMessage() . " | ";
     }
     if (is_callable(array($e, 'getCode'))) {
         $errorstr .= get_string('code', 'turnitintooltwo') . ": " . $e->getCode();
     }
     turnitintooltwo_activitylog($errorstr, "API_ERROR");
     if ($toscreen) {
         turnitintooltwo_print_error($errorstr, null);
     } else {
         if ($embedded) {
             return $errorstr;
         }
     }
 }
 /**
  * Remove a user from a class in Turnitin
  *
  * @param type $membershipid for the course/class for this user
  * @return boolean true if successful
  */
 public static function remove_user_from_class($membershipid)
 {
     $turnitincomms = new turnitintooltwo_comms();
     $turnitincall = $turnitincomms->initialise_api();
     $membership = new TiiMembership();
     $membership->setMembershipId($membershipid);
     try {
         $turnitincall->deleteMembership($membership);
         turnitintooltwo_activitylog("User removed from class - Membership Id: (" . $membershipid . ")", "REQUEST");
         return true;
     } catch (Exception $e) {
         $turnitincomms->handle_exceptions($e, 'userremoveerror');
     }
 }
 /**
  * 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;
 }
示例#6
0
/**
 * Gets the courses for this account from Turnitin.
 *
 * @param array $tiiintegrationids the integration ids we want courses from
 * @return array of data in a datatables readable format
 */
function turnitintooltwo_get_courses_from_tii($tiiintegrationids, $coursetitle, $courseintegration, $courseenddate = null, $requestsource = "mod")
{
    global $CFG, $DB, $OUTPUT, $USER;
    set_time_limit(0);
    $_SESSION["stored_tii_courses"] = array();
    $return = array();
    $return["aaData"] = array();
    $secho = optional_param('sEcho', 0, PARAM_INT);
    $ssortdir = optional_param('sSortDir_0', 'desc', PARAM_ALPHA);
    $isortcol = optional_param('iSortCol_0', '6', PARAM_INT);
    $turnitincomms = new turnitintooltwo_comms();
    $turnitincall = $turnitincomms->initialise_api();
    $class = new TiiClass();
    $class->setTitle($coursetitle);
    if ($courseenddate != null) {
        $class->setDateFrom(gmdate("Y-m-d", strtotime($courseenddate)) . 'T00:00:00Z');
    }
    if (array_key_exists($courseintegration, $tiiintegrationids)) {
        $class->setIntegrationId($courseintegration);
    }
    if (!is_siteadmin()) {
        $turnitintooltwouser = new turnitintooltwo_user($USER->id, 'Instructor');
        $tiiinstructorid = $turnitintooltwouser->tii_user_id;
        $class->setUserId($tiiinstructorid);
        $class->setUserRole('Instructor');
    }
    try {
        $response = $turnitincall->findClasses($class);
        $findclass = $response->getClass();
        $classids = $findclass->getClassIds();
    } catch (Exception $e) {
        turnitintooltwo_activitylog(get_string('migrationcoursegeterror', 'turnitintooltwo'), "REQUEST");
        $classids = array();
    }
    // Get currently linked courses.
    $currentcourses = array();
    if (!empty($classids)) {
        list($insql, $inparams) = $DB->get_in_or_equal($classids);
        $currentcourses["PP"] = $DB->get_records_sql("SELECT tc.turnitin_cid FROM {turnitintooltwo_courses} tc " . "RIGHT JOIN {course} c ON c.id = tc.courseid " . "WHERE tc.course_type = 'PP' AND tc.turnitin_cid " . $insql, $inparams);
        $currentcourses["TT"] = $DB->get_records_sql("SELECT tc.turnitin_cid FROM {turnitintooltwo_courses} tc " . "RIGHT JOIN {course} c ON c.id = tc.courseid " . "WHERE tc.course_type = 'TT' AND tc.turnitin_cid " . $insql, $inparams);
    }
    $class = new TiiClass();
    $class->setClassIds($classids);
    $tiicourses = array();
    $i = 0;
    if (!empty($classids)) {
        try {
            $response = $turnitincall->readClasses($class);
            $readclasses = $response->getClasses();
            foreach ($readclasses as $readclass) {
                if (array_key_exists($readclass->getIntegrationId(), $tiiintegrationids)) {
                    $_SESSION["stored_tii_courses"][$readclass->getClassId()] = $readclass->getTitle();
                    // If we're coming from block we don't need any information, just the number of records
                    if ($requestsource == "mod") {
                        $linkpage = is_siteadmin() ? "settings_extras.php" : "extras.php";
                        $titlecell = html_writer::link($CFG->wwwroot . '/mod/turnitintooltwo/' . $linkpage . '?cmd=class_recreation&id=' . $readclass->getClassId() . '&view_context=box&sesskey=' . sesskey(), $readclass->getTitle(), array("class" => "course_recreate", "id" => "course_" . $readclass->getClassId()));
                        $datecell = html_writer::link('.edit_course_end_date_form', html_writer::tag('span', userdate(strtotime($readclass->getEndDate()), get_string('strftimedate', 'langconfig')), array("id" => $readclass->getClassId() . "_" . gmdate("j", strtotime($readclass->getEndDate())) . "_" . gmdate("n", strtotime($readclass->getEndDate())) . "_" . gmdate("Y", strtotime($readclass->getEndDate())))) . " " . $OUTPUT->pix_icon('edit', get_string('edit'), 'mod_turnitintooltwo'), array("class" => "edit_course_end_link", "id" => "course_date_" . $readclass->getClassId()));
                        $checkbox = '';
                        $class = '';
                        if (empty($currentcourses["PP"][$readclass->getClassId()]) && empty($currentcourses["TT"][$readclass->getClassId()])) {
                            $class = 'hidden_class';
                            $checkbox = html_writer::checkbox('check_' . $readclass->getClassId(), $readclass->getClassId(), false, '', array("class" => "browser_checkbox"));
                        }
                        $moodlecell = $OUTPUT->pix_icon('tick', get_string('moodlelinked', 'turnitintooltwo'), 'mod_turnitintooltwo', array('class' => $class, 'id' => 'tick_' . $readclass->getClassId()));
                        $tiicourses[$i] = array($checkbox, $titlecell, $tiiintegrationids[$readclass->getIntegrationId()], $datecell, $readclass->getClassId(), $moodlecell, $readclass->getTitle(), userdate(strtotime($readclass->getEndDate()), get_string('strftimedate', 'langconfig')));
                    }
                    $i++;
                    // Keep course names in case of course recreation.
                    $_SESSION['tii_classes'][$readclass->getClassId()] = $readclass->getTitle();
                }
            }
            if (count($tiicourses) > 0 && $requestsource == "mod") {
                turnitintooltwo_sort_array($tiicourses, $isortcol, $ssortdir);
                $j = 0;
                foreach ($tiicourses as $class) {
                    $return["aaData"][$j] = $class;
                    $j++;
                }
            }
        } catch (Exception $e) {
            $turnitincomms->handle_exceptions($e, 'coursegettiierror');
        }
    }
    $return["iTotalRecords"] = $i;
    $return["iTotalDisplayRecords"] = $i;
    $return["sEcho"] = $secho;
    $return["blockHTML"] = $i == 0 ? '' : get_string('coursestomigrate', 'mod_turnitintooltwo', $i);
    return $return;
}
 /**
  * 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;
 }
         throw new moodle_exception('invalidsesskey', 'error');
     }
     $message = optional_param('message', '', PARAM_ALPHAEXT);
     // Get the id from the turnitintooltwo_users table so we can update
     $turnitin_user = $DB->get_record('turnitintooltwo_users', array('userid' => $USER->id));
     // Build user object for update
     $eula_user = new object();
     $eula_user->id = $turnitin_user->id;
     $eula_user->user_agreement_accepted = 0;
     if ($message == 'turnitin_eula_accepted') {
         $eula_user->user_agreement_accepted = 1;
         turnitintooltwo_activitylog("User " . $USER->id . " (" . $turnitin_user->turnitin_uid . ") accepted the EULA.", "PP_EULA_ACCEPTANCE");
     } else {
         if ($message == 'turnitin_eula_declined') {
             $eula_user->user_agreement_accepted = -1;
             turnitintooltwo_activitylog("User " . $USER->id . " (" . $turnitin_user->turnitin_uid . ") declined the EULA.", "PP_EULA_ACCEPTANCE");
         }
     }
     // Update the user using the above object
     $DB->update_record('turnitintooltwo_users', $eula_user, $bulk = false);
     break;
 case "resubmit_event":
     if (!confirm_sesskey()) {
         throw new moodle_exception('invalidsesskey', 'error');
     }
     $forumdata = optional_param('forumdata', '', PARAM_ALPHAEXT);
     $forumpost = optional_param('forumpost', '', PARAM_ALPHAEXT);
     $submissionid = required_param('submissionid', PARAM_INT);
     $tiisubmission = new turnitin_submission($submissionid, array('forumdata' => $forumdata, 'forumpost' => $forumpost));
     $tiisubmission->recreate_submission_event();
     break;
示例#9
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;
 }