public function get_content()
 {
     global $CFG, $OUTPUT, $USER, $PAGE, $DB;
     if ($this->content !== null) {
         return $this->content;
     }
     $config = turnitintooltwo_admin_config();
     $output = '';
     // Show link to Helpdesk wizard if enabled and the logged in user is an instrutor.
     if (!empty($USER->id) && $config->helpdeskwizard && has_capability('moodle/course:manageactivities', context_system::instance())) {
         $output = $OUTPUT->box(html_writer::tag('p', html_writer::link($CFG->wwwroot . '/mod/turnitintooltwo/extras.php?cmd=supportwizard', get_string('helpdesklink', 'block_turnitin'))));
     }
     if (!empty($USER->id) && has_capability('moodle/course:create', context_system::instance())) {
         $PAGE->requires->jquery();
         $PAGE->requires->jquery_plugin('block-turnitin', 'block_turnitin');
         $cssurl = new moodle_url($CFG->wwwroot . '/mod/turnitintooltwo/css/styles_block.css');
         $PAGE->requires->css($cssurl);
         $output .= $OUTPUT->box($OUTPUT->pix_icon('loader', '', 'mod_turnitintooltwo'), 'centered_cell', 'block_loading');
         $output .= html_writer::link($CFG->wwwroot . '/mod/turnitintooltwo/extras.php?cmd=courses', html_writer::tag('noscript', get_string('coursestomigrate', 'block_turnitin', '')), array('id' => 'block_migrate_content'));
     }
     $this->content = new stdClass();
     $this->content->text = $output;
     $this->content->footer = '';
     return $this->content;
 }
 /**
  * Log networking performance details of an individual request
  *
  * @param resource $ch The cURL handle corresponding to the request to log
  * @param float $total_response_time Total time taken for the request in seconds
  */
 protected function log($ch, $total_response_time)
 {
     global $CFG, $USER, $action;
     static $config;
     if (empty($config)) {
         $config = turnitintooltwo_admin_config();
     }
     if ($config->enableperformancelogs) {
         // We only keep 10 log files, delete any additional files.
         $prefix = "perflog_";
         $dirpath = $CFG->tempdir . "/turnitintooltwo/logs";
         if (!file_exists($dirpath)) {
             mkdir($dirpath, 0777, true);
         }
         $dir = opendir($dirpath);
         $files = array();
         while ($entry = readdir($dir)) {
             if (substr(basename($entry), 0, 1) != "." and substr_count(basename($entry), $prefix) > 0) {
                 $files[] = basename($entry);
             }
         }
         sort($files);
         for ($i = 0; $i < count($files) - 10; $i++) {
             unlink($dirpath . "/" . $files[$i]);
         }
         // Prepare string.
         $str = '';
         if (!empty($action)) {
             $str .= " - {$action}";
         } else {
             $do = !empty($_REQUEST['do']) ? $_REQUEST['do'] : '';
             if (!empty($do)) {
                 $str .= " - {$do}";
             }
         }
         $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
         $str .= " - HTTP:" . $http_status;
         if ($http_status === 0 && curl_getinfo($ch, CURLINFO_SIZE_UPLOAD) === 0) {
             // CURLINFO_CONNECT_TIME is not reliable when the request fails to connect.
             $connect_time = $total_response_time;
         } else {
             $connect_time = curl_getinfo($ch, CURLINFO_CONNECT_TIME);
         }
         $str .= " - connect:" . sprintf('%0.3f', $connect_time);
         $str .= " - total:" . sprintf('%0.3f', $total_response_time);
         $str .= " - up:" . curl_getinfo($ch, CURLINFO_SIZE_UPLOAD);
         $str .= " - down:" . curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD);
         $str .= " - userid:" . $USER->id;
         $str .= " - " . $_SERVER['REQUEST_URI'];
         if ($http_status === 0) {
             $str .= " - " . curl_error($ch);
         }
         // Write to log file.
         $filepath = $dirpath . "/" . $prefix . gmdate('Y-m-d', time()) . ".txt";
         $file = fopen($filepath, 'a');
         $output = date('Y-m-d H:i:s O') . $str . "\r\n";
         fwrite($file, $output);
         fclose($file);
     }
 }
 public function __construct($accountid = null, $accountshared = null, $url = null)
 {
     $config = turnitintooltwo_admin_config();
     $tiiapiurl = substr($config->apiurl, -1) == '/' ? substr($config->apiurl, 0, -1) : $config->apiurl;
     $this->tiiintegrationid = 12;
     $this->tiiaccountid = is_null($accountid) ? $config->accountid : $accountid;
     $this->tiiapiurl = is_null($url) ? $tiiapiurl : $url;
     $this->tiisecretkey = is_null($accountshared) ? $config->secretkey : $accountshared;
     if (empty($this->tiiaccountid) || empty($this->tiiapiurl) || empty($this->tiisecretkey)) {
         turnitintooltwo_print_error('configureerror', 'turnitintooltwo');
     }
     $this->diagnostic = $config->enablediagnostic;
     $this->langcode = $this->get_lang();
 }
 protected function define_structure()
 {
     global $DB;
     $config = turnitintooltwo_admin_config();
     // To know if we are including userinfo
     $userinfo = $this->get_setting_value('userinfo');
     // Define each element separated
     $turnitintooltwo = new backup_nested_element('turnitintooltwo', array('id'), array('type', 'name', 'grade', 'numparts', 'tiiaccount', 'defaultdtstart', 'defaultdtdue', 'defaultdtpost', 'anon', 'portfolio', 'allowlate', 'reportgenspeed', 'submitpapersto', 'spapercheck', 'internetcheck', 'journalcheck', 'maxfilesize', 'intro', 'introformat', 'timecreated', 'timemodified', 'studentreports', 'dateformat', 'usegrademark', 'gradedisplay', 'autoupdates', 'commentedittime', 'commentmaxsize', 'autosubmission', 'shownonsubmission', 'excludebiblio', 'excludequoted', 'excludevalue', 'excludetype', 'erater', 'erater_handbook', 'erater_dictionary', 'erater_spelling', 'erater_grammar', 'erater_usage', 'erater_mechanics', 'erater_style', 'transmatch'));
     $parts = new backup_nested_element('parts');
     $part = new backup_nested_element('part', array('id'), array('turnitintooltwoid', 'partname', 'tiiassignid', 'dtstart', 'dtdue', 'dtpost', 'maxmarks', 'deleted', 'migrated'));
     $courses = new backup_nested_element('courses');
     $course = new backup_nested_element('course', array('id'), array('courseid', 'ownerid', 'ownertiiuid', 'owneremail', 'ownerfn', 'ownerln', 'ownerun', 'turnitin_ctl', 'turnitin_cid', 'course_type'));
     $submissions = new backup_nested_element('submissions');
     $submission = new backup_nested_element('submission', array('id'), array('userid', 'submission_part', 'submission_title', 'submission_type', 'submission_filename', 'submission_objectid', 'submission_score', 'submission_grade', 'submission_gmimaged', 'submission_status', 'submission_queued', 'submission_attempts', 'submission_modified', 'submission_parent', 'submission_nmuserid', 'submission_nmfirstname', 'submission_nmlastname', 'submission_unanon', 'submission_anonreason', 'submission_transmatch', 'submission_orcapable', 'submission_acceptnothing', 'tiiuserid'));
     // Build the tree
     $submissions->add_child($submission);
     $parts->add_child($part);
     $turnitintooltwo->add_child($parts);
     $turnitintooltwo->add_child($course);
     $turnitintooltwo->add_child($submissions);
     // Define sources
     $turnitintooltwo->set_source_table('turnitintooltwo', array('id' => backup::VAR_ACTIVITYID));
     $values['tiiaccount'] = $config->accountid;
     $turnitintooltwo->fill_values($values);
     $part->set_source_table('turnitintooltwo_parts', array('turnitintooltwoid' => backup::VAR_ACTIVITYID));
     $course->set_source_sql('
         SELECT  t.id, t.courseid, t.ownerid, tu.turnitin_uid AS ownertiiuid,
                 u.email AS owneremail, u.firstname AS ownerfn, u.lastname AS ownerln,
                 u.username AS ownerun, t.turnitin_ctl, t.turnitin_cid
           FROM {turnitintooltwo_courses} t, {user} u, {turnitintooltwo_users} tu
          WHERE t.ownerid=u.id AND tu.userid=t.ownerid AND t.courseid = ?', array(backup::VAR_COURSEID));
     // All the rest of elements only happen if we are including user info
     if ($userinfo) {
         //$submission->set_source_table('turnitintooltwo_submissions', array('turnitintooltwoid' => '../../id'));
         $submission->set_source_sql('
         SELECT  s.*, tu.turnitin_uid AS tiiuserid
           FROM {turnitintooltwo_submissions} s, {turnitintooltwo_users} tu
          WHERE s.userid=tu.userid AND s.turnitintooltwoid = ?', array(backup::VAR_ACTIVITYID));
     }
     // Define id annotations
     $submission->annotate_ids('user', 'userid');
     // Define file annotations
     $turnitintooltwo->annotate_files('mod_turnitintooltwo', 'intro', null);
     // This file area hasn't itemid
     $submission->annotate_files('mod_turnitintooltwo', 'submissions', 'id');
     // Return the root element (turnitintooltwo), wrapped into standard activity structure
     return $this->prepare_activity_structure($turnitintooltwo);
 }
 protected function process_turnitintooltwo($data)
 {
     global $DB;
     $config = turnitintooltwo_admin_config();
     $_SESSION['tii_assignment_reset'] = 1;
     if ($this->get_setting_value('userinfo') == 1) {
         $_SESSION['tii_course_reset'] = 0;
         $_SESSION['tii_assignment_reset'] = 0;
     }
     $data = (object) $data;
     $oldid = $data->id;
     $data->course = $this->get_courseid();
     // Work out whether we are duplicating a module activity or course.
     // If activity then we do not want to reset the course.
     $type = $this->get_task()->get_info()->type;
     if ($type == 'activity') {
         $_SESSION['tii_course_reset'] = 0;
     }
     if ($data->grade < 0) {
         // scale found, get mapping
         $data->grade = -$this->get_mappingid('scale', abs($data->grade));
     }
     if ($config->accountid != $data->tiiaccount) {
         $a = new stdClass();
         $a->backupid = $data->tiiaccount;
         $a->current = $config->accountid;
         turnitintooltwo_print_error('wrongaccountid', 'turnitintooltwo', NULL, $a);
         return false;
     } else {
         // insert the activity record
         $newitemid = $DB->insert_record('turnitintooltwo', $data);
         $_SESSION['assignment_id'] = $newitemid;
         // immediately after inserting "activity" record, call this
         $this->apply_activity_instance($newitemid);
     }
 }
        turnitintooltwo_print_error('coursemodidincorrect', 'turnitintooltwo');
    }
}
// If opening DV then $viewcontext needs to be set to box
$viewcontext = $do == "origreport" || $do == "grademark" || $do == "default" ? "box" : $viewcontext;
require_login($course->id, true, $cm);
turnitintooltwo_activitylog('view.php?id=' . $id . '&do=' . $do, "REQUEST");
//Check if the user has the capability to view the page - used when an assignment is set to hidden.
$context = context_module::instance($cm->id);
require_capability('mod/turnitintooltwo:view', $context);
//Set the page layout to base.
$PAGE->set_pagelayout('base');
// Settings for page navigation
if ($viewcontext == "window") {
    // Show navigation if required.
    $config = turnitintooltwo_admin_config();
    if ($config->inboxlayout == 1) {
        $PAGE->set_cm($cm);
        $PAGE->set_pagelayout('incourse');
    }
}
// Don't show messages popup if we are in submission modal.
$forbiddenmsgscreens = array('submission_success', 'submitpaper');
if (in_array($do, $forbiddenmsgscreens)) {
    $PAGE->set_popup_notification_allowed(false);
}
// Configure URL correctly.
$urlparams = array('id' => $id, 'a' => $a, 'part' => $part, 'user' => $user, 'do' => $do, 'action' => $action, 'view_context' => $viewcontext);
$url = new moodle_url('/mod/turnitintooltwo/view.php', $urlparams);
// Load Javascript and CSS.
$turnitintooltwoview->load_page_components();
 /**
  * Edit the assignment in Moodle then on Turnitin
  *
  * @global type $USER
  * @global type $DB
  * @param boolean $createevent - setting to determine whether to create a calendar event.
  * @return boolean
  */
 public function edit_moodle_assignment($createevent = true)
 {
     global $USER, $DB, $CFG;
     $config = turnitintooltwo_admin_config();
     $this->turnitintooltwo->id = $this->id;
     $this->turnitintooltwo->timemodified = time();
     // Get Moodle Course Object.
     $course = $this->get_course_data($this->turnitintooltwo->course);
     // Get the Turnitin owner of this this Course or make user the owner if none.
     $ownerid = $this->get_tii_owner($course->id);
     if (!empty($ownerid)) {
         $owner = new turnitintooltwo_user($ownerid, 'Instructor');
     } else {
         $owner = new turnitintooltwo_user($USER->id, 'Instructor');
     }
     // Edit course in Turnitin.
     $this->edit_tii_course($course);
     $course->turnitin_ctl = $course->fullname . " (Moodle TT)";
     // Get Current Moodle Turnitin Tool data (Assignment).
     if (!($turnitintooltwonow = $DB->get_record("turnitintooltwo", array("id" => $this->id)))) {
         turnitintooltwo_print_error('turnitintooltwogeterror', 'turnitintooltwo', null, null, __FILE__, __LINE__);
         exit;
     }
     // Get Current Moodle Turnitin Tool Parts Object.
     if (!($parts = $DB->get_records_select("turnitintooltwo_parts", " turnitintooltwoid = ? ", array($this->id), 'id ASC'))) {
         turnitintooltwo_print_error('partgeterror', 'turnitintooltwo', null, null, __FILE__, __LINE__);
         exit;
     }
     $partids = array_keys($parts);
     // Update GradeMark setting depending on config setting.
     $this->turnitintooltwo->usegrademark = $config->usegrademark;
     // Set the checkbox settings for updates.
     $this->turnitintooltwo->erater_spelling = isset($this->turnitintooltwo->erater_spelling) ? $this->turnitintooltwo->erater_spelling : 0;
     $this->turnitintooltwo->erater_grammar = isset($this->turnitintooltwo->erater_grammar) ? $this->turnitintooltwo->erater_grammar : 0;
     $this->turnitintooltwo->erater_usage = isset($this->turnitintooltwo->erater_usage) ? $this->turnitintooltwo->erater_usage : 0;
     $this->turnitintooltwo->erater_mechanics = isset($this->turnitintooltwo->erater_mechanics) ? $this->turnitintooltwo->erater_mechanics : 0;
     $this->turnitintooltwo->erater_style = isset($this->turnitintooltwo->erater_style) ? $this->turnitintooltwo->erater_style : 0;
     $this->turnitintooltwo->transmatch = isset($this->turnitintooltwo->transmatch) ? $this->turnitintooltwo->transmatch : 0;
     $this->turnitintooltwo->institution_check = isset($this->turnitintooltwo->institution_check) ? $this->turnitintooltwo->institution_check : 0;
     // Update each individual part.
     for ($i = 1; $i <= $this->turnitintooltwo->numparts; $i++) {
         // Update Turnitin Assignment.
         $assignment = new TiiAssignment();
         $assignment->setClassId($course->turnitin_cid);
         $assignment->setAuthorOriginalityAccess($this->turnitintooltwo->studentreports);
         $assignment->setRubricId(!empty($this->turnitintooltwo->rubric) ? $this->turnitintooltwo->rubric : '');
         $assignment->setSubmitPapersTo($this->turnitintooltwo->submitpapersto);
         $assignment->setResubmissionRule($this->turnitintooltwo->reportgenspeed);
         $assignment->setBibliographyExcluded($this->turnitintooltwo->excludebiblio);
         $assignment->setQuotedExcluded($this->turnitintooltwo->excludequoted);
         $assignment->setSmallMatchExclusionType($this->turnitintooltwo->excludetype);
         $assignment->setSmallMatchExclusionThreshold((int) $this->turnitintooltwo->excludevalue);
         $assignment->setLateSubmissionsAllowed($this->turnitintooltwo->allowlate);
         if ($config->repositoryoption == 1) {
             $assignment->setInstitutionCheck(isset($this->turnitintooltwo->institution_check) ? $this->turnitintooltwo->institution_check : 0);
         }
         $attribute = "maxmarks" . $i;
         $assignment->setMaxGrade($this->turnitintooltwo->{$attribute});
         $assignment->setSubmittedDocumentsCheck($this->turnitintooltwo->spapercheck);
         $assignment->setInternetCheck($this->turnitintooltwo->internetcheck);
         $assignment->setPublicationsCheck($this->turnitintooltwo->journalcheck);
         $assignment->setTranslatedMatching($this->turnitintooltwo->transmatch);
         $assignment->setAllowNonOrSubmissions($this->turnitintooltwo->allownonor);
         // Erater settings.
         $assignment->setErater(isset($this->turnitintooltwo->erater) ? $this->turnitintooltwo->erater : 0);
         $assignment->setEraterSpelling($this->turnitintooltwo->erater_spelling);
         $assignment->setEraterGrammar($this->turnitintooltwo->erater_grammar);
         $assignment->setEraterUsage($this->turnitintooltwo->erater_usage);
         $assignment->setEraterMechanics($this->turnitintooltwo->erater_mechanics);
         $assignment->setEraterStyle($this->turnitintooltwo->erater_style);
         $assignment->setEraterSpellingDictionary(isset($this->turnitintooltwo->erater_dictionary) ? $this->turnitintooltwo->erater_dictionary : 'en_US');
         $assignment->setEraterHandbook(isset($this->turnitintooltwo->erater_handbook) ? $this->turnitintooltwo->erater_handbook : 0);
         $attribute = "dtstart" . $i;
         $assignment->setStartDate(gmdate("Y-m-d\\TH:i:s\\Z", $this->turnitintooltwo->{$attribute}));
         $attribute = "dtdue" . $i;
         $assignment->setDueDate(gmdate("Y-m-d\\TH:i:s\\Z", $this->turnitintooltwo->{$attribute}));
         $attribute = "dtpost" . $i;
         $assignment->setFeedbackReleaseDate(gmdate("Y-m-d\\TH:i:s\\Z", $this->turnitintooltwo->{$attribute}));
         $attribute = "partname" . $i;
         $assignment->setTitle($this->turnitintooltwo->name . " " . $this->turnitintooltwo->{$attribute} . " (Moodle TT)");
         // Initialise part.
         $part = new stdClass();
         $part->turnitintooltwoid = $this->id;
         $part->partname = $this->turnitintooltwo->{$attribute};
         $part->deleted = 0;
         $part->maxmarks = $assignment->getMaxGrade();
         $part->dtstart = strtotime($assignment->getStartDate());
         $part->dtdue = strtotime($assignment->getDueDate());
         $part->dtpost = strtotime($assignment->getFeedbackReleaseDate());
         $parttiiassignid = 0;
         if ($i <= count($partids) && !empty($partids[$i - 1])) {
             $partdetails = $this->get_part_details($partids[$i - 1]);
             $part->submitted = $partdetails->submitted;
             $part->unanon = $partdetails->unanon;
             // Set anonymous marking depending on whether part has been unanonymised.
             if ($config->useanon && $partdetails->unanon != 1) {
                 $assignment->setAnonymousMarking($this->turnitintooltwo->anon);
             }
             $parttiiassignid = $partdetails->tiiassignid;
         }
         if ($parttiiassignid > 0) {
             $assignment->setAssignmentId($parttiiassignid);
             $this->edit_tii_assignment($assignment);
         } else {
             $parttiiassignid = $this->create_tii_assignment($assignment, $this->id, $i);
             $part->submitted = 0;
         }
         $part->tiiassignid = $parttiiassignid;
         // Unanonymise part if necessary.
         if ($part->dtpost < time() && $part->submitted == 1) {
             $part->unanon = 1;
         }
         $properties = new stdClass();
         $properties->name = $this->turnitintooltwo->name . ' - ' . $part->partname;
         $properties->description = $this->turnitintooltwo->intro;
         $properties->courseid = $this->turnitintooltwo->course;
         $properties->groupid = 0;
         $properties->userid = 0;
         $properties->modulename = 'turnitintooltwo';
         $properties->instance = $this->id;
         $properties->eventtype = 'due';
         $properties->timestart = $part->dtdue;
         $properties->timeduration = 0;
         if ($i <= count($partids) && !empty($partdetails->id)) {
             $part->id = $partids[$i - 1];
             // Get Current Moodle part data.
             if (!($partnow = $DB->get_record("turnitintooltwo_parts", array("id" => $part->id)))) {
                 turnitintooltwo_print_error('partgeterror', 'turnitintooltwo', null, null, __FILE__, __LINE__);
                 exit;
             }
             if (!($dbpart = $DB->update_record('turnitintooltwo_parts', $part))) {
                 turnitintooltwo_print_error('partupdateerror', 'turnitintooltwo', null, $i, __FILE__, __LINE__);
                 exit;
             } else {
                 turnitintooltwo_activitylog("Moodle Assignment part updated (" . $part->id . ") - " . $part->partname, "REQUEST");
             }
             // Delete existing events for this assignment part.
             $eventname = $turnitintooltwonow->name . " - " . $partnow->partname;
             $dbselect = " modulename = ? AND instance = ? AND name LIKE ? ";
             // Moodle pre 2.5 on SQL Server errors here as queries weren't allowed on ntext fields, the relevant fields
             // are nvarchar from 2.6 onwards so we have to cast the relevant fields in pre 2.5 SQL Server setups.
             if ($CFG->branch <= 25 && $CFG->dbtype == "sqlsrv") {
                 $dbselect = " CAST(modulename AS nvarchar(max)) = ? AND instance = ? AND CAST(name AS nvarchar(max)) = ? ";
             }
             $DB->delete_records_select('event', $dbselect, array('turnitintooltwo', $this->id, $eventname));
         } else {
             if (!($dbpart = $DB->insert_record('turnitintooltwo_parts', $part))) {
                 turnitintooltwo_print_error('partdberror', 'turnitintooltwo', null, $i, __FILE__, __LINE__);
                 exit;
             }
         }
         if ($createevent == true) {
             require_once $CFG->dirroot . '/calendar/lib.php';
             $event = new calendar_event($properties);
             $event->update($properties, false);
         }
     }
     $this->turnitintooltwo->timemodified = time();
     $update = $DB->update_record("turnitintooltwo", $this->turnitintooltwo);
     turnitintooltwo_activitylog("Turnitintool updated (" . $this->id . ") - " . $this->turnitintooltwo->name, "REQUEST");
     // Define grade settings.
     if (!isset($_SESSION['tii_assignment_reset'])) {
         turnitintooltwo_grade_item_update($this->turnitintooltwo);
     }
     return $update;
 }
 /**
  * Edit the user's details on Turnitin (only name can be updated)
  *
  * @param object $user_details A data object for the user
  * @param var $role user role to create
  */
 public function edit_tii_user()
 {
     $config = turnitintooltwo_admin_config();
     $turnitincomms = new turnitintooltwo_comms();
     $turnitincall = $turnitincomms->initialise_api();
     // Only update if pseudo is not enabled.
     if (empty($config->enablepseudo)) {
         $user = new TiiUser();
         $user->setFirstName($this->firstname);
         $user->setLastName($this->lastname);
         $user->setUserId($this->tii_user_id);
         $user->setDefaultRole($this->role);
         try {
             $turnitincall->updateUser($user);
             turnitintooltwo_activitylog("Turnitin User updated: " . $this->id . " (" . $this->tii_user_id . ")", "REQUEST");
         } catch (Exception $e) {
             $toscreen = $this->workflowcontext == "cron" ? false : true;
             $turnitincomms->handle_exceptions($e, 'userupdateerror', $toscreen);
         }
     }
 }
 /**
  * Get the row for this submission in the inbox table
  *
  * @global object $CFG
  * @global type $OUTPUT
  * @param type $cm
  * @param type $turnitintooltwoassignment
  * @param type $parts
  * @param type $partid
  * @param type $submission
  * @param type $useroverallgrades
  * @param type $istutor
  * @return type
  */
 public function get_submission_inbox_row($cm, $turnitintooltwoassignment, $parts, $partid, $submission, &$useroverallgrades, $istutor, $context = 'all')
 {
     global $CFG, $OUTPUT, $USER, $DB;
     $config = turnitintooltwo_admin_config();
     $moodleuserid = substr($submission->userid, 0, 3) != 'nm-' && $submission->userid != 0 ? $submission->userid : 0;
     if (!$istutor) {
         $user = new turnitintooltwo_user($USER->id, "Learner");
     }
     $checkbox = "&nbsp;";
     if (!empty($submission->submission_objectid) && $istutor) {
         $checkbox = html_writer::checkbox('check_' . $submission->submission_objectid, $submission->submission_objectid, false, '', array("class" => "inbox_checkbox"));
     }
     if (!$istutor) {
         // If students viewing it will show 'digital receipt' link
         if (!empty($submission->submission_objectid)) {
             $studentname = html_writer::link($CFG->wwwroot . '/mod/turnitintooltwo/view.php?id=' . $cm->id . '&do=digital_receipt&submissionid=' . $submission->submission_objectid . '&view_context=box', $OUTPUT->pix_icon('receipt', get_string('digitalreceipt', 'turnitintooltwo'), 'mod_turnitintooltwo', array('id' => 'tii_digital_receipt_icon')) . get_string('viewdigitalreceipt', 'turnitintooltwo'), array('class' => 'tii_digital_receipt'));
         } else {
             $studentname = "--";
         }
         //Determine whether the student can see the overall grade, based on the post time of all parts.
         $display_overall_grade = 1;
         foreach (array_keys($parts) as $ar_key => $ar_value) {
             if ($parts[$ar_value]->dtpost > time()) {
                 $display_overall_grade = 0;
             }
         }
     } else {
         if ($turnitintooltwoassignment->turnitintooltwo->anon && $parts[$partid]->unanon != 1) {
             if (empty($submission->submission_unanon) and $parts[$partid]->dtpost > time() and !empty($submission->submission_objectid)) {
                 // Anonymous marking is on, postdate has not passed and a submission has been made.
                 $studentname = html_writer::link('.unanonymise_form', get_string('anonenabled', 'turnitintooltwo'), array("class" => "unanonymise", "id" => "submission_" . $submission->submission_objectid));
             } else {
                 if (($parts[$partid]->dtpost <= time() or !empty($submission->submission_unanon)) and empty($submission->nmoodle)) {
                     // Post date has passed or anonymous marking disabled for user and user is a moodle user.
                     $studentname = html_writer::link($CFG->wwwroot . "/user/view.php?id=" . $submission->userid . "&course=" . $turnitintooltwoassignment->turnitintooltwo->course, format_string($submission->lastname) . ", " . format_string($submission->firstname));
                 } else {
                     if (($parts[$partid]->dtpost <= time() or !empty($submission->submission_unanon)) and !empty($submission->nmoodle)) {
                         // Post date has passed or anonymous marking disabled for user and user is a NON moodle user.
                         $studentname = html_writer::tag("span", format_string($submission->lastname) . ", " . format_string($submission->firstname) . " (" . get_string('nonmoodleuser', 'turnitintooltwo') . ")", array("class" => "italic"));
                     } else {
                         // User has not made a submission.
                         $studentname = html_writer::tag("span", get_string('anonenabled', 'turnitintooltwo'), array("class" => "italic"));
                     }
                 }
             }
         } else {
             if (empty($submission->nmoodle)) {
                 // Link to user profile.
                 $studentname = html_writer::link($CFG->wwwroot . "/user/view.php?id=" . $submission->userid . "&course=" . $turnitintooltwoassignment->turnitintooltwo->course, format_string($submission->lastname) . ", " . format_string($submission->firstname));
             } else {
                 if (!empty($submission->nmoodle) && substr($submission->userid, 0, 3) != 'nm-') {
                     // Moodle User not enrolled on this course as a student.
                     $studentname = html_writer::link($CFG->wwwroot . "/user/view.php?id=" . $submission->userid . "&course=" . $turnitintooltwoassignment->turnitintooltwo->course, format_string($submission->lastname) . ", " . format_string($submission->firstname) . " (" . get_string('nonenrolledstudent', 'turnitintooltwo') . ")", array("class" => "italic"));
                 } else {
                     // Non Moodle user.
                     $studentname = html_writer::tag("span", format_string($submission->lastname) . ", " . format_string($submission->firstname) . " (" . get_string('nonmoodleuser', 'turnitintooltwo') . ")", array("class" => "italic"));
                 }
             }
         }
     }
     // Submission title with link to open DV.
     if (!empty($submission->submission_objectid) and !empty($submission->submission_objectid)) {
         $title = $OUTPUT->box_start('default_open', 'default_' . $submission->submission_objectid . '_' . $partid . '_' . $moodleuserid);
         $title .= $OUTPUT->box(format_string($submission->submission_title), 'submission_title underline');
         $title .= $OUTPUT->box($CFG->wwwroot . '/mod/turnitintooltwo/view.php?id=' . $cm->id, 'dv_url', 'default_url_' . $submission->submission_objectid);
         $title .= $OUTPUT->box_end(true);
         $rawtitle = $submission->submission_title;
     } else {
         $title = "--";
         $rawtitle = "--";
     }
     $objectid = !empty($submission->submission_objectid) ? $submission->submission_objectid : "--";
     // Show date of submission or link to submit if it didn't work.
     if (empty($submission->submission_objectid) and !empty($submission->id)) {
         $rawmodified = 1;
         $modified = html_writer::link($CFG->wwwroot . "/mod/turnitintooltwo/view.php?id=" . $cm->id . "&action=manualsubmission" . "&sub=" . $submission->id . '&sesskey=' . sesskey(), $OUTPUT->pix_icon('icon-sml', get_string('submittoturnitin', 'turnitintooltwo'), 'mod_turnitintooltwo') . " " . get_string('submittoturnitin', 'turnitintooltwo'));
     } else {
         if (empty($submission->submission_objectid)) {
             $rawmodified = 0;
             $modified = "--";
         } else {
             $rawmodified = (int) $submission->submission_modified;
             $modified = userdate($submission->submission_modified, get_string('strftimedatetimeshort', 'langconfig'));
             if ($submission->submission_modified > $parts[$partid]->dtdue) {
                 $modified = html_writer::tag('span', $modified, array("class" => "late_submission"));
             }
         }
     }
     // Show Originality score with link to open document viewer.
     if (!empty($submission->id) && is_null($submission->submission_score) && $submission->submission_orcapable == 0) {
         // Don't show if there is no OR score and submission is not OR capable
         $rawscore = null;
         $score = '--';
     } else {
         if (!empty($submission->id) && !empty($submission->submission_objectid) && ($istutor || $turnitintooltwoassignment->turnitintooltwo->studentreports)) {
             // Show score.
             if (is_null($submission->submission_score)) {
                 $score = $OUTPUT->box_start('row_score', 'origreport_' . $submission->submission_objectid . '_' . $partid . '_' . $moodleuserid);
                 $score .= $OUTPUT->box('&nbsp;', 'score_colour score_colour_');
                 $score .= $OUTPUT->box(get_string('pending', 'turnitintooltwo'), 'origreport_score');
                 $rawscore = null;
             } else {
                 $score = $OUTPUT->box_start('row_score origreport_open', 'origreport_' . $submission->submission_objectid . '_' . $partid . '_' . $moodleuserid);
                 // Put EN flag if translated matching is on and that is the score used.
                 $transmatch = $submission->submission_transmatch == 1 ? 'EN' : '&nbsp;';
                 $score .= $OUTPUT->box($transmatch, 'score_colour score_colour_' . round($submission->submission_score, -1));
                 $score .= $OUTPUT->box($submission->submission_score . '%', 'origreport_score');
                 $rawscore = $submission->submission_score;
             }
             // Put in div placeholder for DV launch form.
             $score .= $OUTPUT->box('', 'launch_form', 'origreport_form_' . $submission->submission_objectid);
             // URL for DV launcher
             $score .= $OUTPUT->box($CFG->wwwroot . '/mod/turnitintooltwo/view.php?id=' . $cm->id, 'dv_url', 'origreport_url_' . $submission->submission_objectid);
             $score .= $OUTPUT->box_end(true);
         } else {
             $rawscore = null;
             $score = '--';
         }
     }
     // Show grade and link to DV.
     if ($config->usegrademark) {
         if ($turnitintooltwoassignment->turnitintooltwo->grade == 0) {
             //We set the grade column to N/A if there is no grade type set.
             $rawgrade = null;
             $grade = $OUTPUT->box('N/A', '');
         } else {
             if (isset($submission->submission_objectid) && ($istutor || !$istutor && $parts[$partid]->dtpost < time())) {
                 $submissiongrade = !is_null($submission->submission_grade) ? $submission->submission_grade : '';
                 if (is_null($submission->submission_grade) || $submission->submission_gmimaged == 0 && !$istutor) {
                     $submissiongrade = "--";
                 }
                 // Show warning to instructor if student can still resubmit.
                 $canresubmit = $turnitintooltwoassignment->turnitintooltwo->reportgenspeed > 0;
                 $tutorbeforeduedate = $istutor && time() < $parts[$partid]->dtdue;
                 $allowedlate = $turnitintooltwoassignment->turnitintooltwo->allowlate == 1 && empty($submission->nmoodle);
                 $class = $canresubmit && ($tutorbeforeduedate || $allowedlate) ? 'graded_warning' : '';
                 // Output grademark icon.
                 $grade = $OUTPUT->box(html_writer::tag('i', '', array('class' => 'fa fa-pencil fa-lg gm-blue')), 'grademark_open' . $class, 'grademark_' . $submission->submission_objectid . '_' . $partid . '_' . $moodleuserid, array('title' => $CFG->wwwroot . '/mod/turnitintooltwo/view.php?id=' . $cm->id));
                 // Show grade.
                 $grade .= $OUTPUT->box(html_writer::tag('span', $submissiongrade, array("class" => "grade")) . "/" . $parts[$partid]->maxmarks, 'grademark_grade');
                 // Put in div placeholder for DV launch form.
                 $grade .= $OUTPUT->box('', 'launch_form', 'grademark_form_' . $submission->submission_objectid);
                 // URL for DV launcher
                 $grade .= $OUTPUT->box($CFG->wwwroot . '/mod/turnitintooltwo/view.php?id=' . $cm->id, 'dv_url', 'grademark_url_' . $submission->submission_objectid);
                 $rawgrade = $submissiongrade == "--" ? null : $submissiongrade;
             } else {
                 if (!isset($submission->submission_objectid) && empty($submission->id) && $istutor) {
                     // Allow nothing submission if no submission has been made and this is a tutor
                     $grade = $OUTPUT->box(html_writer::tag('i', '', array('class' => 'fa fa-pencil fa-lg grey')), 'submit_nothing', 'submitnothing_0_' . $partid . '_' . $submission->userid);
                     $rawgrade = null;
                 } else {
                     $rawgrade = null;
                     $grade = $OUTPUT->box('--', '');
                 }
             }
         }
         // Show average grade if more than 1 part.
         if (count($parts) > 1 || $turnitintooltwoassignment->turnitintooltwo->grade < 0) {
             $overallgrade = '--';
             if ($submission->nmoodle != 1 && ($istutor || !$istutor && $parts[$partid]->dtpost < time())) {
                 if (!isset($useroverallgrades[$submission->userid])) {
                     $usersubmissions = $turnitintooltwoassignment->get_user_submissions($submission->userid, $turnitintooltwoassignment->turnitintooltwo->id);
                     $useroverallgrades[$submission->userid] = $turnitintooltwoassignment->get_overall_grade($usersubmissions);
                 }
                 if ($turnitintooltwoassignment->turnitintooltwo->grade == 0 || $useroverallgrades[$submission->userid] === '--' || !$istutor && $display_overall_grade == 0) {
                 } else {
                     if ($turnitintooltwoassignment->turnitintooltwo->grade < 0) {
                         // Scale.
                         $scale = $DB->get_record('scale', array('id' => $turnitintooltwoassignment->turnitintooltwo->grade * -1));
                         $scalearray = explode(",", $scale->scale);
                         $overallgrade = $scalearray[$useroverallgrades[$submission->userid] - 1];
                     } else {
                         $overallgrade = round($useroverallgrades[$submission->userid] / $turnitintooltwoassignment->turnitintooltwo->grade * 100, 1) . '%';
                     }
                 }
                 if ($overallgrade != '--') {
                     $overallgrade = html_writer::tag("span", $overallgrade, array("class" => "overallgrade_" . $submission->userid));
                 }
             }
         }
     }
     // Indicate whether student has seen grademark image.
     if ($istutor) {
         if (isset($submission->submission_objectid)) {
             $submissionattempts = !empty($submission->submission_attempts) ? $submission->submission_attempts : 0;
             if ($submissionattempts > 0) {
                 $studentread = $OUTPUT->pix_icon('icon-student-read', get_string('student_read', 'turnitintooltwo') . ' ' . userdate($submissionattempts), 'mod_turnitintooltwo', array("class" => "student_read_icon"));
             } else {
                 $studentread = $OUTPUT->pix_icon('icon-dot', get_string('student_notread', 'turnitintooltwo'), 'mod_turnitintooltwo', array("class" => "student_dot_icon"));
             }
         } else {
             $studentread = "--";
         }
     }
     // Upload Submission.
     if ((!isset($submission->submission_objectid) || $turnitintooltwoassignment->turnitintooltwo->reportgenspeed != 0) && empty($submission->nmoodle) && time() > $parts[$partid]->dtstart) {
         if (empty($submission->submission_objectid)) {
             $submission->submission_objectid = 0;
         }
         $uploadtext = !$istutor ? html_writer::tag('span', get_string('submitpaper', 'turnitintooltwo')) : '';
         $eulaaccepted = 0;
         if ($submission->userid == $USER->id) {
             $submission_user = new turnitintooltwo_user($submission->userid, "Learner");
             $coursedata = $turnitintooltwoassignment->get_course_data($turnitintooltwoassignment->turnitintooltwo->course);
             $submission_user->join_user_to_class($coursedata->turnitin_cid);
             $eulaaccepted = $submission_user->user_agreement_accepted == 0 ? $submission_user->get_accepted_user_agreement() : $submission_user->user_agreement_accepted;
         }
         $upload = html_writer::link($CFG->wwwroot . '/mod/turnitintooltwo/view.php?id=' . $cm->id . '&part=' . $partid . '&user='******'&do=submitpaper&view_context=box_solid', $uploadtext . ' ' . html_writer::tag('i', '', array('class' => 'fa fa-cloud-upload fa-lg')), array("class" => "upload_box nowrap", "id" => "upload_" . $submission->submission_objectid . "_" . $partid . "_" . $submission->userid, 'data-eula' => $eulaaccepted, 'data-user-type' => $istutor));
         if (time() > $parts[$partid]->dtdue && $turnitintooltwoassignment->turnitintooltwo->allowlate == 0 && !$istutor) {
             $upload = "&nbsp;";
         }
     } else {
         $upload = "&nbsp;";
     }
     // Download submission in original format.
     if (!empty($submission->submission_objectid) && !empty($submission->id) && !$submission->submission_acceptnothing) {
         $download = $OUTPUT->box(html_writer::tag('i', '', array('class' => 'fa fa-cloud-download fa-lg')), 'download_original_open', 'downloadoriginal_' . $submission->submission_objectid . "_" . $partid . "_" . $moodleuserid);
         $download .= $OUTPUT->box('', 'launch_form', 'downloadoriginal_form_' . $submission->submission_objectid);
         // Add in LTI launch form incase Javascript is disabled.
         if (!$istutor) {
             $download .= html_writer::tag('noscript', $this->output_dv_launch_form("downloadoriginal", $submission->submission_objectid, $user->tii_user_id, "Learner", get_string('downloadsubmission', 'turnitintooltwo')));
         }
     } else {
         $download = "--";
     }
     $refresh = '--';
     if (!empty($submission->id) && $istutor) {
         $refresh = html_writer::tag('div', html_writer::tag('i', '', array('class' => 'fa fa-refresh fa-lg', 'title' => get_string('turnitinrefreshsubmissions', 'turnitintooltwo'))) . html_writer::tag('i', '', array('class' => 'fa fa-spinner fa-spin')), array('class' => 'refresh_row', 'id' => 'refreshrow_' . $submission->submission_objectid . '_' . $partid . '_' . $moodleuserid));
     }
     // Delete Link.
     $delete = "--";
     if ($istutor) {
         if (!empty($submission->id)) {
             $fnd = array("\n", "\r");
             $rep = array('\\n', '\\r');
             $confirmstring = empty($submission->submission_objectid) ? 'deleteconfirm' : 'turnitindeleteconfirm';
             $string = str_replace($fnd, $rep, get_string($confirmstring, 'turnitintooltwo'));
             $attributes = array("onclick" => "return confirm('" . $string . "');");
             $delete = html_writer::link($CFG->wwwroot . '/mod/turnitintooltwo/view.php?id=' . $cm->id . '&action=deletesubmission&sub=' . $submission->id . '&sesskey=' . sesskey(), html_writer::tag('i', '', array('class' => 'fa fa-trash-o fa-lg')), $attributes);
         }
     } else {
         if (empty($submission->submission_objectid) && !empty($submission->id)) {
             $fnd = array("\n", "\r");
             $rep = array('\\n', '\\r');
             $string = str_replace($fnd, $rep, get_string('deleteconfirm', 'turnitintooltwo'));
             $attributes = array("onclick" => "return confirm('" . $string . "');");
             $delete = html_writer::link($CFG->wwwroot . '/mod/turnitintooltwo/view.php?id=' . $cm->id . '&action=deletesubmission&sub=' . $submission->id . '&sesskey=' . sesskey(), html_writer::tag('i', '', array('class' => 'fa fa-trash-o fa-lg')), $attributes);
         }
     }
     $data = array($partid, $checkbox, $studentname, $rawtitle, $title, $objectid, $rawmodified, $modified);
     if ($istutor || !$istutor && $turnitintooltwoassignment->turnitintooltwo->studentreports) {
         $data[] = $rawscore;
         $data[] = $score;
     }
     if ($config->usegrademark) {
         $data[] = $rawgrade;
         $data[] = $grade;
         if (count($parts) > 1 || $turnitintooltwoassignment->turnitintooltwo->grade < 0) {
             $data[] = $overallgrade;
         }
     }
     if ($istutor) {
         $data[] = $studentread;
     }
     $data[] = $upload;
     $data[] = $download;
     if ($istutor) {
         $data[] = $refresh;
     }
     $data[] = $delete;
     return $data;
 }
 /**
  * Due to moodle's internal plugin hooks we can not use our bespoke form class for Turnitin
  * settings. This form shows in settings > defaults as well as the activity creation screen.
  *
  * @global type $CFG
  * @param type $plugin_defaults
  * @return type
  */
 public function add_elements_to_settings_form($mform, $course, $location = "activity", $cmid = 0, $currentrubric = 0)
 {
     global $CFG, $OUTPUT, $PAGE, $USER, $DB;
     // Include JS strings (closebutton is needed from both plugins).
     $PAGE->requires->string_for_js('changerubricwarning', 'plagiarism_turnitin');
     $PAGE->requires->string_for_js('closebutton', 'turnitintooltwo');
     $PAGE->requires->string_for_js('closebutton', 'plagiarism_turnitin');
     $config = turnitintooltwo_admin_config();
     $config_warning = '';
     $rubrics = array();
     if ($location == "activity") {
         $instructor = new turnitintooltwo_user($USER->id, 'Instructor');
         $instructor->join_user_to_class($course->turnitin_cid);
         $rubrics = $instructor->get_instructor_rubrics();
         // Get rubrics that are shared on the account.
         $turnitinclass = new turnitin_class($course->id);
         $turnitinclass->sharedrubrics = array();
         $turnitinclass->read_class_from_tii();
         // Merge the arrays, prioitising instructor owned arrays.
         $rubrics = $rubrics + $turnitinclass->sharedrubrics;
     }
     $options = array(0 => get_string('no'), 1 => get_string('yes'));
     $genoptions = array(0 => get_string('genimmediately1', 'plagiarism_turnitin'), 1 => get_string('genimmediately2', 'plagiarism_turnitin'), 2 => get_string('genduedate', 'plagiarism_turnitin'));
     $excludetypeoptions = array(0 => get_string('no'), 1 => get_string('excludewords', 'plagiarism_turnitin'), 2 => get_string('excludepercent', 'plagiarism_turnitin'));
     if ($location == "defaults") {
         $mform->addElement('header', 'plugin_header', get_string('turnitindefaults', 'plagiarism_turnitin'));
         $mform->addElement('html', get_string("defaultsdesc", "turnitintooltwo"));
     }
     if ($location != "defaults") {
         $mform->addElement('header', 'plugin_header', get_string('turnitinpluginsettings', 'plagiarism_turnitin'));
         // Add in custom Javascript and CSS.
         $PAGE->requires->jquery();
         $PAGE->requires->jquery_plugin('ui');
         $PAGE->requires->jquery_plugin('turnitintooltwo-turnitintooltwo', 'mod_turnitintooltwo');
         $PAGE->requires->jquery_plugin('plagiarism-turnitin_module', 'plagiarism_turnitin');
         $PAGE->requires->jquery_plugin('turnitintooltwo-colorbox', 'mod_turnitintooltwo');
         $cssurl = new moodle_url('/mod/turnitintooltwo/css/colorbox.css');
         $PAGE->requires->css($cssurl);
         // Refresh Grades
         $refreshgrades = '';
         if ($cmid != 0) {
             // If assignment has submissions then show a refresh grades button
             $numsubs = $DB->count_records('plagiarism_turnitin_files', array('cm' => $cmid));
             if ($numsubs > 0) {
                 $refreshgrades = html_writer::tag('div', $OUTPUT->pix_icon('refresh', get_string('turnitinrefreshsubmissions', 'plagiarism_turnitin'), 'plagiarism_turnitin') . html_writer::tag('span', get_string('turnitinrefreshsubmissions', 'plagiarism_turnitin')), array('class' => 'plagiarism_turnitin_refresh_grades'));
                 $refreshgrades .= html_writer::tag('div', $OUTPUT->pix_icon('loading', get_string('turnitinrefreshingsubmissions', 'plagiarism_turnitin'), 'plagiarism_turnitin') . html_writer::tag('span', get_string('turnitinrefreshingsubmissions', 'plagiarism_turnitin')), array('class' => 'plagiarism_turnitin_refreshing_grades'));
             }
         }
         // Quickmark Manager.
         $quickmarkmanagerlink = '';
         if ($config->usegrademark) {
             $quickmarkmanagerlink .= $OUTPUT->box_start('row_quickmark_manager', '');
             $quickmarkmanagerlink .= html_writer::link($CFG->wwwroot . '/mod/turnitintooltwo/extras.php?cmd=quickmarkmanager&view_context=box', get_string('launchquickmarkmanager', 'plagiarism_turnitin'), array('class' => 'plagiarism_turnitin_quickmark_manager_launch', 'title' => get_string('launchquickmarkmanager', 'plagiarism_turnitin')));
             $quickmarkmanagerlink .= html_writer::tag('span', '', array('class' => 'launch_form', 'id' => 'quickmark_manager_form'));
             $quickmarkmanagerlink .= $OUTPUT->box_end(true);
         }
         $use_turnitin = $DB->get_record('plagiarism_turnitin_config', array('cm' => $cmid, 'name' => 'use_turnitin'));
         // Peermark Manager.
         $peermarkmanagerlink = '';
         if (!empty($config->enablepeermark) && !empty($use_turnitin->value)) {
             if ($cmid != 0) {
                 $peermarkmanagerlink .= $OUTPUT->box_start('row_peermark_manager', '');
                 $peermarkmanagerlink .= html_writer::link($CFG->wwwroot . '/plagiarism/turnitin/ajax.php?cmid=' . $cmid . '&action=peermarkmanager&view_context=box', get_string('launchpeermarkmanager', 'plagiarism_turnitin'), array('class' => 'peermark_manager_launch', 'id' => 'peermark_manager_' . $cmid, 'title' => get_string('launchpeermarkmanager', 'plagiarism_turnitin')));
                 $peermarkmanagerlink .= html_writer::tag('span', '', array('class' => 'launch_form', 'id' => 'peermark_manager_form'));
                 $peermarkmanagerlink .= $OUTPUT->box_end(true);
             }
         }
         if (!empty($quickmarkmanagerlink) || !empty($peermarkmanagerlink) || !empty($refreshgrades)) {
             $mform->addElement('static', 'static', '', $refreshgrades . $quickmarkmanagerlink . $peermarkmanagerlink);
         }
     }
     $locks = $DB->get_records_sql("SELECT name, value FROM {plagiarism_turnitin_config} WHERE cm IS NULL");
     if (empty($config_warning)) {
         $mform->addElement('select', 'use_turnitin', get_string("useturnitin", "turnitintooltwo"), $options);
         $this->lock($mform, $location, $locks);
         $mform->addElement('select', 'plagiarism_show_student_report', get_string("studentreports", "turnitintooltwo"), $options);
         $this->lock($mform, $location, $locks);
         $mform->addHelpButton('plagiarism_show_student_report', 'studentreports', 'plagiarism_turnitin');
         if ($mform->elementExists('submissiondrafts') || $location == 'defaults') {
             $tiidraftoptions = array(0 => get_string("submitondraft", "turnitintooltwo"), 1 => get_string("submitonfinal", "turnitintooltwo"));
             $mform->addElement('select', 'plagiarism_draft_submit', get_string("draftsubmit", "turnitintooltwo"), $tiidraftoptions);
             $this->lock($mform, $location, $locks);
             $mform->disabledIf('plagiarism_draft_submit', 'submissiondrafts', 'eq', 0);
         }
         $mform->addElement('select', 'plagiarism_allow_non_or_submissions', get_string("allownonor", "turnitintooltwo"), $options);
         $this->lock($mform, $location, $locks);
         $mform->addHelpButton('plagiarism_allow_non_or_submissions', 'allownonor', 'plagiarism_turnitin');
         $suboptions = array(0 => get_string('norepository', 'plagiarism_turnitin'), 1 => get_string('standardrepository', 'plagiarism_turnitin'));
         switch ($config->repositoryoption) {
             case 0:
                 // Standard options
                 $mform->addElement('select', 'plagiarism_submitpapersto', get_string('submitpapersto', 'plagiarism_turnitin'), $suboptions);
                 $this->lock($mform, $location, $locks);
                 break;
             case 1:
                 // Standard options + Allow Instituional Repository
                 $suboptions[2] = get_string('institutionalrepository', 'plagiarism_turnitin');
                 $mform->addElement('select', 'plagiarism_submitpapersto', get_string('submitpapersto', 'plagiarism_turnitin'), $suboptions);
                 $this->lock($mform, $location, $locks);
                 break;
             case 2:
                 // Force Standard Repository
                 $mform->addElement('hidden', 'plagiarism_submitpapersto', 1);
                 $mform->setType('plagiarism_submitpapersto', PARAM_RAW);
                 break;
             case 3:
                 // Force No Repository
                 $mform->addElement('hidden', 'plagiarism_submitpapersto', 0);
                 $mform->setType('plagiarism_submitpapersto', PARAM_RAW);
                 break;
         }
         $mform->addElement('html', html_writer::tag('div', get_string('checkagainstnote', 'plagiarism_turnitin'), array('class' => 'tii_checkagainstnote')));
         $mform->addElement('select', 'plagiarism_compare_student_papers', get_string("spapercheck", "turnitintooltwo"), $options);
         $this->lock($mform, $location, $locks);
         $mform->addElement('select', 'plagiarism_compare_internet', get_string("internetcheck", "turnitintooltwo"), $options);
         $this->lock($mform, $location, $locks);
         $mform->addElement('select', 'plagiarism_compare_journals', get_string("journalcheck", "turnitintooltwo"), $options);
         $this->lock($mform, $location, $locks);
         if ($config->repositoryoption == 1) {
             $mform->addElement('select', 'plagiarism_compare_institution', get_string('compareinstitution', 'plagiarism_turnitin'), $options);
             $this->lock($mform, $location, $locks);
         }
         $mform->addElement('select', 'plagiarism_report_gen', get_string("reportgenspeed", "turnitintooltwo"), $genoptions);
         $this->lock($mform, $location, $locks);
         $mform->addElement('html', html_writer::tag('div', get_string('genspeednote', 'plagiarism_turnitin'), array('class' => 'tii_genspeednote')));
         $mform->addElement('select', 'plagiarism_exclude_biblio', get_string("excludebiblio", "turnitintooltwo"), $options);
         $this->lock($mform, $location, $locks);
         $mform->addElement('select', 'plagiarism_exclude_quoted', get_string("excludequoted", "turnitintooltwo"), $options);
         $this->lock($mform, $location, $locks);
         $mform->addElement('select', 'plagiarism_exclude_matches', get_string("excludevalue", "turnitintooltwo"), $excludetypeoptions);
         $this->lock($mform, $location, $locks);
         $mform->addElement('text', 'plagiarism_exclude_matches_value', '');
         $mform->setType('plagiarism_exclude_matches_value', PARAM_INT);
         $mform->addRule('plagiarism_exclude_matches_value', null, 'numeric', null, 'client');
         $mform->disabledIf('plagiarism_exclude_matches_value', 'plagiarism_exclude_matches', 'eq', 0);
         if ($location == 'defaults') {
             $mform->addElement('text', 'plagiarism_locked_message', get_string("locked_message", "plagiarism_turnitin"), 'maxlength="50" size="50"');
             $mform->setType('plagiarism_locked_message', PARAM_TEXT);
             $mform->setDefault('plagiarism_locked_message', get_string("locked_message_default", "plagiarism_turnitin"));
             $mform->addHelpButton('plagiarism_locked_message', 'locked_message', 'plagiarism_turnitin');
         }
         if ($location == "activity" && $config->usegrademark) {
             // Populate Rubric options.
             $rubricoptions = array('' => get_string('norubric', 'plagiarism_turnitin')) + $rubrics;
             if (!empty($currentrubric)) {
                 $rubricoptions[$currentrubric] = isset($rubricoptions[$currentrubric]) ? $rubricoptions[$currentrubric] : get_string('otherrubric', 'plagiarism_turnitin');
             }
             $mform->addElement('select', 'plagiarism_rubric', get_string('attachrubric', 'plagiarism_turnitin'), $rubricoptions);
             $mform->addElement('static', 'rubric_link', '', html_writer::link($CFG->wwwroot . '/mod/turnitintooltwo/extras.php?cmd=rubricmanager&view_context=box', get_string('launchrubricmanager', 'plagiarism_turnitin'), array('class' => 'rubric_manager_launch', 'title' => get_string('launchrubricmanager', 'plagiarism_turnitin'))) . html_writer::tag('span', '', array('class' => 'launch_form', 'id' => 'rubric_manager_form')));
             $mform->setDefault('plagiarism_rubric', '');
             $mform->addElement('hidden', 'rubric_warning_seen', '');
             $mform->setType('rubric_warning_seen', PARAM_RAW);
             $mform->addElement('static', 'rubric_note', '', get_string('attachrubricnote', 'plagiarism_turnitin'));
         } else {
             $mform->addElement('hidden', 'plagiarism_rubric', '');
             $mform->setType('plagiarism_rubric', PARAM_RAW);
         }
         if (!empty($config->useerater)) {
             $handbookoptions = array(1 => get_string('erater_handbook_advanced', 'plagiarism_turnitin'), 2 => get_string('erater_handbook_highschool', 'plagiarism_turnitin'), 3 => get_string('erater_handbook_middleschool', 'plagiarism_turnitin'), 4 => get_string('erater_handbook_elementary', 'plagiarism_turnitin'), 5 => get_string('erater_handbook_learners', 'plagiarism_turnitin'));
             $dictionaryoptions = array('en_US' => get_string('erater_dictionary_enus', 'plagiarism_turnitin'), 'en_GB' => get_string('erater_dictionary_engb', 'plagiarism_turnitin'), 'en' => get_string('erater_dictionary_en', 'plagiarism_turnitin'));
             $mform->addElement('select', 'plagiarism_erater', get_string('erater', 'plagiarism_turnitin'), $options);
             $mform->setDefault('plagiarism_erater', 0);
             $mform->addElement('select', 'plagiarism_erater_handbook', get_string('erater_handbook', 'plagiarism_turnitin'), $handbookoptions);
             $mform->setDefault('plagiarism_erater_handbook', 2);
             $mform->disabledIf('plagiarism_erater_handbook', 'plagiarism_erater', 'eq', 0);
             $mform->addElement('select', 'plagiarism_erater_dictionary', get_string('erater_dictionary', 'plagiarism_turnitin'), $dictionaryoptions);
             $mform->setDefault('plagiarism_erater_dictionary', 'en_US');
             $mform->disabledIf('plagiarism_erater_dictionary', 'plagiarism_erater', 'eq', 0);
             $mform->addElement('checkbox', 'plagiarism_erater_spelling', get_string('erater_categories', 'plagiarism_turnitin'), " " . get_string('erater_spelling', 'plagiarism_turnitin'));
             $mform->disabledIf('plagiarism_erater_spelling', 'plagiarism_erater', 'eq', 0);
             $mform->addElement('checkbox', 'plagiarism_erater_grammar', '', " " . get_string('erater_grammar', 'plagiarism_turnitin'));
             $mform->disabledIf('plagiarism_erater_grammar', 'plagiarism_erater', 'eq', 0);
             $mform->addElement('checkbox', 'plagiarism_erater_usage', '', " " . get_string('erater_usage', 'plagiarism_turnitin'));
             $mform->disabledIf('plagiarism_erater_usage', 'plagiarism_erater', 'eq', 0);
             $mform->addElement('checkbox', 'plagiarism_erater_mechanics', '', " " . get_string('erater_mechanics', 'plagiarism_turnitin'));
             $mform->disabledIf('plagiarism_erater_mechanics', 'plagiarism_erater', 'eq', 0);
             $mform->addElement('checkbox', 'plagiarism_erater_style', '', " " . get_string('erater_style', 'plagiarism_turnitin'));
             $mform->disabledIf('plagiarism_erater_style', 'plagiarism_erater', 'eq', 0);
         }
         $mform->addElement('html', html_writer::tag('div', get_string('anonblindmarkingnote', 'plagiarism_turnitin'), array('class' => 'tii_anonblindmarkingnote')));
         if ($config->transmatch) {
             $mform->addElement('select', 'plagiarism_transmatch', get_string("transmatch", "turnitintooltwo"), $options);
         } else {
             $mform->addElement('hidden', 'plagiarism_transmatch', 0);
         }
         $mform->setType('plagiarism_transmatch', PARAM_INT);
         $mform->addElement('hidden', 'action', "defaults");
         $mform->setType('action', PARAM_RAW);
     } else {
         $mform->addElement('hidden', 'use_turnitin', 0);
         $mform->setType('use_turnitin', PARAM_INT);
     }
     // Disable the form change checker - added in 2.3.2.
     if (is_callable(array($mform, 'disable_form_change_checker'))) {
         $mform->disable_form_change_checker();
     }
 }
 /**
  * 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;
 }
Exemple #12
0
/**
 * Get users for unlinking/relinking. Called from ajax.php via turnitintooltwo.js.
 *
 * @global type $DB
 * @return array return array of users to display
 */
function turnitintooltwo_getusers()
{
    global $DB;
    $config = turnitintooltwo_admin_config();
    $return = array();
    $idisplaystart = optional_param('iDisplayStart', 0, PARAM_INT);
    $idisplaylength = optional_param('iDisplayLength', 10, PARAM_INT);
    $secho = optional_param('sEcho', 1, PARAM_INT);
    $displaycolumns = array('tu.userid', 'tu.turnitin_uid', 'mu.lastname', 'mu.firstname', 'mu.email');
    $queryparams = array();
    // Add sort to query.
    $isortcol[0] = optional_param('iSortCol_0', null, PARAM_INT);
    $isortingcols = optional_param('iSortingCols', 0, PARAM_INT);
    $queryorder = "";
    if (!is_null($isortcol[0])) {
        $queryorder = " ORDER BY ";
        $startorder = $queryorder;
        for ($i = 0; $i < intval($isortingcols); $i++) {
            $isortcol[$i] = optional_param('iSortCol_' . $i, null, PARAM_INT);
            $bsortable[$i] = optional_param('bSortable_' . $isortcol[$i], null, PARAM_TEXT);
            $ssortdir[$i] = optional_param('sSortDir_' . $i, null, PARAM_TEXT);
            if ($bsortable[$i] == "true") {
                $queryorder .= $displaycolumns[$isortcol[$i]] . " " . $ssortdir[$i] . ", ";
            }
        }
        if ($queryorder == $startorder) {
            $queryorder = "";
        } else {
            $queryorder = substr_replace($queryorder, "", -2);
        }
    }
    // Add search to query.
    $ssearch = optional_param('sSearch', '', PARAM_TEXT);
    $querywhere = ' WHERE ( ';
    for ($i = 0; $i < count($displaycolumns); $i++) {
        $bsearchable[$i] = optional_param('bSearchable_' . $i, null, PARAM_TEXT);
        if (!is_null($bsearchable[$i]) && $bsearchable[$i] == "true" && $ssearch != '') {
            $include = true;
            if ($i <= 1) {
                if (!is_int($ssearch) || is_null($ssearch)) {
                    $include = false;
                }
            }
            if ($include) {
                $querywhere .= $DB->sql_like($displaycolumns[$i], ':search_term_' . $i, false) . " OR ";
                $queryparams['search_term_' . $i] = '%' . $ssearch . '%';
            }
        }
    }
    if ($querywhere == ' WHERE ( ') {
        $querywhere = "";
    } else {
        $querywhere = substr_replace($querywhere, "", -3);
        $querywhere .= " )";
    }
    $query = "SELECT tu.id AS id, tu.userid AS userid, tu.turnitin_uid AS turnitin_uid, tu.turnitin_utp AS turnitin_utp, " . "mu.firstname AS firstname, mu.lastname AS lastname, mu.email AS email " . "FROM {turnitintooltwo_users} tu " . "LEFT JOIN {user} mu ON tu.userid = mu.id " . $querywhere . $queryorder;
    $users = $DB->get_records_sql($query, $queryparams, $idisplaystart, $idisplaylength);
    $totalusers = count($DB->get_records_sql($query, $queryparams));
    $return["aaData"] = array();
    foreach ($users as $user) {
        $checkbox = html_writer::checkbox('userids[]', $user->id, false, '', array("class" => "browser_checkbox"));
        $pseudoemail = "";
        if (!empty($config->enablepseudo)) {
            $pseudouser = new TiiPseudoUser(turnitintooltwo_user::get_pseudo_domain());
            $pseudouser->setEmail($user->email);
            $pseudoemail = $pseudouser->getEmail();
        }
        $return["aaData"][] = array($checkbox, $user->turnitin_uid == 0 ? '' : $user->turnitin_uid, format_string($user->lastname), format_string($user->firstname), $pseudoemail);
    }
    $return["sEcho"] = $secho;
    $return["iTotalRecords"] = count($users);
    $return["iTotalDisplayRecords"] = $totalusers;
    return $return;
}
 public function show_form($instructorrubrics, $modulestring = '', $tiicourseid)
 {
     global $CFG, $OUTPUT, $COURSE, $PAGE;
     $PAGE->requires->string_for_js('changerubricwarning', 'turnitintooltwo');
     $PAGE->requires->string_for_js('closebutton', 'turnitintooltwo');
     $config = turnitintooltwo_admin_config();
     $mform =& $this->_form;
     $script = '';
     // Add in custom Javascript and CSS.
     if ($CFG->branch <= 25) {
         $script .= html_writer::tag('script', '', array("type" => "text/javascript", "src" => $CFG->wwwroot . "/mod/turnitintooltwo/jquery/jquery-1.8.2.min.js"));
         $script .= html_writer::tag('script', '', array("id" => "plugin_turnitin_script", "type" => "text/javascript", "src" => $CFG->wwwroot . "/mod/turnitintooltwo/jquery/turnitintooltwo.min.js"));
         $script .= html_writer::tag('script', '', array("type" => "text/javascript", "src" => $CFG->wwwroot . "/mod/turnitintooltwo/jquery/jquery-ui-1.10.4.custom.min.js"));
         $script .= html_writer::tag('script', '', array("type" => "text/javascript", "src" => $CFG->wwwroot . "/mod/turnitintooltwo/jquery/jquery.colorbox.js"));
         $script .= html_writer::tag('script', '', array("type" => "text/javascript", "src" => $CFG->wwwroot . "/mod/turnitintooltwo/jquery/jquery.colorbox.js"));
         $script .= html_writer::tag('script', '', array("type" => "text/javascript", "src" => $CFG->wwwroot . "/mod/turnitintooltwo/jquery/moment.js"));
     } else {
         $PAGE->requires->jquery();
         $PAGE->requires->jquery_plugin('ui');
         $PAGE->requires->jquery_plugin('turnitintooltwo-turnitintooltwo', 'mod_turnitintooltwo');
         $PAGE->requires->jquery_plugin('turnitintooltwo-colorbox', 'mod_turnitintooltwo');
         $PAGE->requires->jquery_plugin('turnitintooltwo-moment', 'mod_turnitintooltwo');
     }
     $PAGE->requires->string_for_js('anonalert', 'turnitintooltwo');
     $script .= html_writer::tag('link', '', array("rel" => "stylesheet", "type" => "text/css", "href" => $CFG->wwwroot . "/mod/turnitintooltwo/styles.css"));
     $script .= html_writer::tag('link', '', array("rel" => "stylesheet", "type" => "text/css", "href" => $CFG->wwwroot . "/mod/turnitintooltwo/css/colorbox.css"));
     $script .= html_writer::tag('link', '', array("rel" => "stylesheet", "type" => "text/css", "href" => $CFG->wwwroot . "/mod/turnitintooltwo/css/tii-icon-webfont.css"));
     $mform->addElement('html', $script);
     $config_warning = '';
     if (empty($config->accountid) || empty($config->secretkey) || empty($config->apiurl)) {
         $config_warning = html_writer::tag('div', get_string('configureerror', 'turnitintooltwo'), array('class' => 'library_not_present_warning'));
     }
     if ($config_warning != '') {
         $mform->addElement('html', $config_warning);
     }
     $noscript = html_writer::tag('noscript', get_string('noscript', 'turnitintooltwo'), array("class" => "warning"));
     $mform->addElement('html', $noscript);
     if (isset($_SESSION["notice"])) {
         $notice = $_SESSION["notice"];
         if (empty($_SESSION["notice"]["type"])) {
             $notice["type"] = "general";
         }
         unset($_SESSION["notice"]);
     } else {
         $notice = null;
     }
     if (!is_null($notice)) {
         $mform->addElement('html', $OUTPUT->box($notice["message"], 'generalbox', $notice["type"]));
     }
     $mform->addElement('header', 'general', get_string('general', 'form'));
     $mform->addElement('text', 'name', get_string('turnitintooltwoname', 'turnitintooltwo'), array('size' => '64'));
     $mform->setType('name', PARAM_RAW);
     $mform->addRule('name', null, 'required', null, 'client');
     $input = new stdClass();
     $input->length = 40;
     $input->field = get_string('turnitintooltwoname', 'turnitintooltwo');
     $mform->addRule('name', get_string('maxlength', 'turnitintooltwo', $input), 'maxlength', 40, 'client');
     $mform->addRule('name', get_string('maxlength', 'turnitintooltwo', $input), 'maxlength', 40, 'server');
     if ($CFG->branch >= 29) {
         $this->standard_intro_elements(get_string('turnitintooltwointro', 'turnitintooltwo'));
     } else {
         $this->add_intro_editor(true, get_string('turnitintooltwointro', 'turnitintooltwo'));
     }
     $typeoptions = turnitintooltwo_filetype_array(true);
     $mform->addElement('select', 'type', get_string('type', 'turnitintooltwo'), $typeoptions);
     $mform->addHelpButton('type', 'types', 'turnitintooltwo');
     $mform->addRule('type', get_string('required'), 'required', null, 'client');
     $mform->setDefault('type', $config->default_type);
     $options = array();
     if ($this->updating) {
         $j = $this->current->numparts;
     } else {
         $j = 1;
     }
     for ($i = $j; $i <= 5; $i++) {
         $options[$i] = $i;
     }
     $mform->addElement('select', 'numparts', get_string('numberofparts', 'turnitintooltwo'), $options);
     $mform->addHelpButton('numparts', 'numberofparts', 'turnitintooltwo');
     $mform->setDefault('numparts', $config->default_numparts);
     $mform->addElement('hidden', 'portfolio', 0);
     $mform->setType('portfolio', PARAM_INT);
     $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;
     $options = get_max_upload_sizes($maxbytessite, $maxbytescourse, TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE);
     $mform->addElement('select', 'maxfilesize', get_string('maxfilesize', 'turnitintooltwo'), $options);
     $mform->addHelpButton('maxfilesize', 'maxfilesize', 'turnitintooltwo');
     unset($options);
     for ($i = 0; $i <= 100; $i++) {
         $options[$i] = $i;
     }
     $ynoptions = array(0 => get_string('no'), 1 => get_string('yes'));
     if ($this->updating and $config->useanon and isset($this->turnitintooltwo->anon) and $this->turnitintooltwo->submitted == 1) {
         $staticout = (isset($this->turnitintooltwo->anon) and $this->turnitintooltwo->anon) ? get_string('yes') : get_string('no');
         $mform->addElement('static', 'static', get_string('turnitinanon', 'turnitintooltwo'), $staticout);
         $mform->addElement('hidden', 'anon', $this->turnitintooltwo->anon);
         $mform->addHelpButton('anon', 'turnitinanon', 'turnitintooltwo');
     } else {
         if ($config->useanon) {
             $mform->addElement('select', 'anon', get_string('turnitinanon', 'turnitintooltwo'), $ynoptions);
             $mform->addHelpButton('anon', 'turnitinanon', 'turnitintooltwo');
             $anondefault = isset($config->default_anon) ? $config->default_anon : 0;
             $mform->setDefault('anon', $anondefault);
         } else {
             $mform->addElement('hidden', 'anon', 0);
         }
     }
     $mform->setType('anon', PARAM_INT);
     $mform->addElement('select', 'allownonor', get_string('allownonor', 'turnitintooltwo'), $ynoptions);
     $mform->addHelpButton('allownonor', 'allownonor', 'turnitintooltwo');
     $mform->setDefault('allownonor', $config->default_allownonor);
     $mform->addElement('select', 'studentreports', get_string('studentreports', 'turnitintooltwo'), $ynoptions);
     $mform->addHelpButton('studentreports', 'studentreports', 'turnitintooltwo');
     $mform->setDefault('studentreports', $config->default_studentreports);
     $gradedisplayoptions = array(1 => get_string('displaygradesaspercent', 'turnitintooltwo'), 2 => get_string('displaygradesasfraction', 'turnitintooltwo'));
     $mform->addElement('select', 'gradedisplay', get_string('displaygradesas', 'turnitintooltwo'), $gradedisplayoptions);
     $mform->addHelpButton('gradedisplay', 'displaygradesas', 'turnitintooltwo');
     $mform->setDefault('gradedisplay', $config->default_gradedisplay);
     $refreshoptions = array(1 => get_string('yesgrades', 'turnitintooltwo'), 0 => get_string('nogrades', 'turnitintooltwo'));
     $mform->addElement('select', 'autoupdates', get_string('autorefreshgrades', 'turnitintooltwo'), $refreshoptions);
     $mform->addHelpButton('autoupdates', 'autorefreshgrades', 'turnitintooltwo');
     $mform->setDefault('autoupdates', 1);
     $mform->addElement('checkbox', 'set_instructor_defaults', '', " " . get_string('setinstructordefaults', 'turnitintooltwo'));
     $mform->setDefault('set_instructor_defaults', false);
     $mform->addHelpButton('set_instructor_defaults', 'setinstructordefaults', 'turnitintooltwo');
     $dateoptions = array('startyear' => date('Y', strtotime('-6 years')), 'stopyear' => date('Y', strtotime('+6 years')), 'timezone' => 99, 'applydst' => true, 'step' => 1, 'optional' => false);
     $this->standard_grading_coursemodule_elements();
     if (isset($this->_cm->id)) {
         $turnitintooltwoassignment = new turnitintooltwo_assignment($this->_cm->instance);
         $parts = $turnitintooltwoassignment->get_parts();
         $partsArray = array();
         foreach ($parts as $key => $value) {
             $partsArray[] = $value;
         }
     }
     for ($i = 1; $i <= 5; $i++) {
         $mform->addElement('header', 'partdates' . $i, get_string('partname', 'turnitintooltwo') . " " . $i);
         if (isset($this->_cm->id) && isset($partsArray[$i - 1])) {
             $partdetails = $turnitintooltwoassignment->get_part_details($partsArray[$i - 1]->id);
             $mform->addElement('html', '<div class="assignment-part-' . $i . '" data-anon="' . $turnitintooltwoassignment->turnitintooltwo->anon . '" data-unanon="' . $partdetails->unanon . '" data-submitted="' . $partdetails->submitted . '" data-part-id="' . $i . '">');
         }
         // Delete part link.
         if ($this->updating && $this->current->numparts > 1 && $i <= $this->current->numparts) {
             $attributes = array('class' => 'delete_link');
             $numsubsattribute = "numsubs" . $i;
             if ($this->current->{$numsubsattribute} > 0) {
                 $fnd = array("\n", "\r");
                 $rep = array('\\n', '\\r');
                 $string = str_replace($fnd, $rep, get_string('partdeletewarning', 'turnitintooltwo'));
                 $attributes["onclick"] = "return confirm('" . $string . "');";
             }
             $partidattribute = "id" . $i;
             $url = new moodle_url($CFG->wwwroot . "/mod/turnitintooltwo/view.php", array('id' => $this->_cm->id, 'action' => 'delpart', 'part' => $this->current->{$partidattribute}, 'sesskey' => sesskey()));
             $deletelink = html_writer::link($url, get_string('deletepart', 'turnitintooltwo') . " " . $OUTPUT->pix_icon('delete', get_string('delete'), 'mod_turnitintooltwo'), $attributes);
             $mform->addElement('html', $deletelink);
         }
         $mform->addElement('text', 'partname' . $i, get_string('name'));
         $mform->setType('partname' . $i, PARAM_RAW);
         $mform->setDefault('partname' . $i, get_string('turnitinpart', 'turnitintooltwo', $i));
         $mform->addRule('partname' . $i, null, 'required', null, 'client');
         $input = new stdClass();
         $input->length = 40;
         $input->field = get_string('partname', 'turnitintooltwo') . " " . get_string('name');
         $mform->addRule('partname' . $i, get_string('maxlength', 'turnitintooltwo', $input), 'maxlength', 40, 'client');
         $mform->addRule('partname' . $i, get_string('maxlength', 'turnitintooltwo', $input), 'maxlength', 40, 'server');
         $mform->addElement('date_time_selector', 'dtstart' . $i, get_string('dtstart', 'turnitintooltwo'), $dateoptions);
         $mform->setDefault('dtstart' . $i, time());
         $mform->addElement('date_time_selector', 'dtdue' . $i, get_string('dtdue', 'turnitintooltwo'), $dateoptions);
         $mform->setDefault('dtdue' . $i, strtotime('+7 days'));
         $mform->addElement('date_time_selector', 'dtpost' . $i, get_string('dtpost', 'turnitintooltwo'), $dateoptions);
         $mform->setDefault('dtpost' . $i, strtotime('+7 days'));
         $mform->addElement('text', 'maxmarks' . $i, get_string('maxmarks', 'turnitintooltwo'));
         $mform->setType('maxmarks' . $i, PARAM_INT);
         $mform->setDefault('maxmarks' . $i, '100');
         $mform->addRule('maxmarks' . $i, null, 'numeric', null, 'client');
     }
     $mform->addElement('header', 'advanced', get_string('turnitinoroptions', 'turnitintooltwo'));
     $mform->addElement('select', 'allowlate', get_string('allowlate', 'turnitintooltwo'), $ynoptions);
     $mform->setDefault('allowlate', $config->default_allowlate);
     $genoptions = array(0 => get_string('genimmediately1', 'turnitintooltwo'), 1 => get_string('genimmediately2', 'turnitintooltwo'), 2 => get_string('genduedate', 'turnitintooltwo'));
     $mform->addElement('select', 'reportgenspeed', get_string('reportgenspeed', 'turnitintooltwo'), $genoptions);
     $mform->addHelpButton('reportgenspeed', 'reportgenspeed', 'turnitintooltwo');
     $mform->setDefault('reportgenspeed', $config->default_reportgenspeed);
     $mform->addElement('html', html_writer::tag('div', get_string('genspeednote', 'turnitintooltwo'), array('class' => 'tii_genspeednote')));
     $suboptions = array(0 => get_string('norepository', 'turnitintooltwo'), 1 => get_string('standardrepository', 'turnitintooltwo'));
     switch ($config->repositoryoption) {
         case 0:
             // Standard options
             $mform->addElement('select', 'submitpapersto', get_string('submitpapersto', 'turnitintooltwo'), $suboptions);
             $mform->addHelpButton('submitpapersto', 'submitpapersto', 'turnitintooltwo');
             $mform->setDefault('submitpapersto', $config->default_submitpapersto);
             break;
         case 1:
             // Standard options + Allow Instituional Repository
             $suboptions[2] = get_string('institutionalrepository', 'turnitintooltwo');
             $mform->addElement('select', 'submitpapersto', get_string('submitpapersto', 'turnitintooltwo'), $suboptions);
             $mform->addHelpButton('submitpapersto', 'submitpapersto', 'turnitintooltwo');
             $mform->setDefault('submitpapersto', $config->default_submitpapersto);
             break;
         case 2:
             // Force Standard Repository
             $mform->addElement('hidden', 'submitpapersto', 1);
             $mform->setType('submitpapersto', PARAM_RAW);
             break;
         case 3:
             // Force No Repository
             $mform->addElement('hidden', 'submitpapersto', 0);
             $mform->setType('submitpapersto', PARAM_RAW);
             break;
     }
     $mform->addElement('html', html_writer::tag('div', get_string('checkagainstnote', 'turnitintooltwo'), array('class' => 'tii_checkagainstnote')));
     $mform->addElement('select', 'spapercheck', get_string('spapercheck', 'turnitintooltwo'), $ynoptions);
     $mform->addHelpButton('spapercheck', 'spapercheck', 'turnitintooltwo');
     $mform->setDefault('spapercheck', $config->default_spapercheck);
     $mform->addElement('select', 'internetcheck', get_string('internetcheck', 'turnitintooltwo'), $ynoptions);
     $mform->addHelpButton('internetcheck', 'internetcheck', 'turnitintooltwo');
     $mform->setDefault('internetcheck', $config->default_internetcheck);
     $mform->addElement('select', 'journalcheck', get_string('journalcheck', 'turnitintooltwo'), $ynoptions);
     $mform->addHelpButton('journalcheck', 'journalcheck', 'turnitintooltwo');
     $mform->setDefault('journalcheck', $config->default_journalcheck);
     if ($config->repositoryoption == "1") {
         $mform->addElement('select', 'institution_check', get_string('institutionalcheck', 'turnitintooltwo'), $ynoptions);
         $mform->setDefault('institution_check', $config->default_institutioncheck);
     }
     if ($this->numsubs > 0) {
         $staticout = (isset($this->turnitintooltwo->excludebiblio) and $this->turnitintooltwo->excludebiblio) ? get_string('yes') : get_string('no');
         $mform->addElement('static', 'static', get_string('excludebiblio', 'turnitintooltwo'), $staticout);
         $mform->addElement('hidden', 'excludebiblio', $this->turnitintooltwo->excludebiblio);
         $staticout = (isset($this->turnitintooltwo->excludequoted) and $this->turnitintooltwo->excludequoted) ? get_string('yes') : get_string('no');
         $mform->addElement('static', 'static', get_string('excludequoted', 'turnitintooltwo'), $staticout);
         $mform->addElement('hidden', 'excludequoted', $this->turnitintooltwo->excludequoted);
         $staticout = (isset($this->turnitintooltwo->excludetype) and $this->turnitintooltwo->excludetype == 1) ? get_string('excludewords', 'turnitintooltwo') : get_string('excludepercent', 'turnitintooltwo');
         $staticval = (isset($this->turnitintooltwo->excludevalue) and empty($this->turnitintooltwo->excludevalue)) ? get_string('nolimit', 'turnitintooltwo') : $this->turnitintooltwo->excludevalue . ' ' . $staticout;
         $mform->addElement('static', 'static', get_string('excludevalue', 'turnitintooltwo'), $staticval);
         $mform->addElement('hidden', 'excludevalue', $this->turnitintooltwo->excludevalue);
         $mform->addElement('hidden', 'excludetype', $this->turnitintooltwo->excludetype);
     } else {
         $mform->addElement('select', 'excludebiblio', get_string('excludebiblio', 'turnitintooltwo'), $ynoptions);
         $mform->addHelpButton('excludebiblio', 'excludebiblio', 'turnitintooltwo');
         $mform->setDefault('excludebiblio', $config->default_excludebiblio);
         $mform->addElement('select', 'excludequoted', get_string('excludequoted', 'turnitintooltwo'), $ynoptions);
         $mform->addHelpButton('excludequoted', 'excludequoted', 'turnitintooltwo');
         $mform->setDefault('excludequoted', $config->default_excludequoted);
         $mform->addElement('text', 'excludevalue', get_string('excludevalue', 'turnitintooltwo'), array('size' => '12'));
         $mform->addHelpButton('excludevalue', 'excludevalue', 'turnitintooltwo');
         $input = new stdClass();
         $input->length = 9;
         $input->field = get_string('excludevalue', 'turnitintooltwo');
         $mform->addRule('excludevalue', get_string('maxlength', 'turnitintooltwo', $input), 'maxlength', 9, 'client');
         $mform->addRule('excludevalue', get_string('maxlength', 'turnitintooltwo', $input), 'maxlength', 9, 'server');
         $mform->addRule('excludevalue', null, 'numeric', null, 'client');
         $mform->addRule('excludevalue', null, 'numeric', null, 'server');
         $typeoptions = array(1 => get_string('excludewords', 'turnitintooltwo'), 2 => get_string('excludepercent', 'turnitintooltwo'));
         $mform->addElement('select', 'excludetype', '', $typeoptions);
         $mform->setDefault('excludetype', 1);
     }
     $mform->setType('excludebiblio', PARAM_RAW);
     $mform->setType('excludequoted', PARAM_RAW);
     $mform->setType('excludevalue', PARAM_RAW);
     $mform->setType('excludetype', PARAM_RAW);
     if (isset($config->transmatch) && $config->transmatch == '1') {
         $mform->addElement('select', 'transmatch', get_string('transmatch', 'turnitintooltwo'), $ynoptions);
         $mform->setDefault('transmatch', $config->default_transmatch);
     }
     // Populate Rubric options.
     if (!empty($config->usegrademark)) {
         $mform->addElement('header', 'advanced', get_string('turnitingmoptions', 'turnitintooltwo'));
         $rubricoptions = array('' => get_string('norubric', 'turnitintooltwo')) + $instructorrubrics;
         if (!empty($this->turnitintooltwo->rubric)) {
             $rubricoptions[$this->turnitintooltwo->rubric] = isset($rubricoptions[$this->turnitintooltwo->rubric]) ? $rubricoptions[$this->turnitintooltwo->rubric] : get_string('otherrubric', 'turnitintooltwo');
         }
         $rubricline = array();
         $rubricline[] = $mform->createElement('select', 'rubric', '', $rubricoptions);
         $rubricline[] = $mform->createElement('static', 'rubric_link', '', html_writer::link($CFG->wwwroot . '/mod/turnitintooltwo/extras.php?' . 'cmd=rubricmanager&tiicourseid=' . $tiicourseid . '&view_context=box', html_writer::tag('i', '', array('class' => 'tiiicon icon-rubric icon-lg icon_margin')) . get_string('launchrubricmanager', 'turnitintooltwo'), array('class' => 'rubric_manager_launch', 'title' => get_string('launchrubricmanager', 'turnitintooltwo'))) . html_writer::tag('span', '', array('class' => 'launch_form', 'id' => 'rubric_manager_form')));
         $mform->setDefault('rubric', '');
         $mform->addGroup($rubricline, 'rubricline', get_string('attachrubric', 'turnitintooltwo'), array(' '), false);
         $mform->addElement('hidden', 'rubric_warning_seen', '');
         $mform->setType('rubric_warning_seen', PARAM_RAW);
         $mform->addElement('static', 'rubric_note', '', get_string('attachrubricnote', 'turnitintooltwo'));
     } else {
         $mform->addElement('hidden', 'rubric', '');
         $mform->setType('rubric', PARAM_RAW);
     }
     if (!empty($config->usegrademark) && !empty($config->useerater)) {
         $handbookoptions = array(1 => get_string('erater_handbook_advanced', 'turnitintooltwo'), 2 => get_string('erater_handbook_highschool', 'turnitintooltwo'), 3 => get_string('erater_handbook_middleschool', 'turnitintooltwo'), 4 => get_string('erater_handbook_elementary', 'turnitintooltwo'), 5 => get_string('erater_handbook_learners', 'turnitintooltwo'));
         $dictionaryoptions = array('en_US' => get_string('erater_dictionary_enus', 'turnitintooltwo'), 'en_GB' => get_string('erater_dictionary_engb', 'turnitintooltwo'), 'en' => get_string('erater_dictionary_en', 'turnitintooltwo'));
         $mform->addElement('select', 'erater', get_string('erater', 'turnitintooltwo'), $ynoptions);
         $mform->setDefault('erater', $config->default_erater);
         $mform->addElement('select', 'erater_handbook', get_string('erater_handbook', 'turnitintooltwo'), $handbookoptions);
         $mform->setDefault('erater_handbook', $config->default_erater_handbook);
         $mform->disabledIf('erater_handbook', 'erater', 'eq', 0);
         $mform->addElement('select', 'erater_dictionary', get_string('erater_dictionary', 'turnitintooltwo'), $dictionaryoptions);
         $mform->setDefault('erater_dictionary', $config->default_erater_dictionary);
         $mform->disabledIf('erater_dictionary', 'erater', 'eq', 0);
         $mform->addElement('checkbox', 'erater_spelling', get_string('erater_categories', 'turnitintooltwo'), " " . get_string('erater_spelling', 'turnitintooltwo'));
         $mform->setDefault('erater_spelling', $config->default_erater_spelling);
         $mform->disabledIf('erater_spelling', 'erater', 'eq', 0);
         $mform->addElement('checkbox', 'erater_grammar', '', " " . get_string('erater_grammar', 'turnitintooltwo'));
         $mform->setDefault('erater_grammar', $config->default_erater_grammar);
         $mform->disabledIf('erater_grammar', 'erater', 'eq', 0);
         $mform->addElement('checkbox', 'erater_usage', '', " " . get_string('erater_usage', 'turnitintooltwo'));
         $mform->setDefault('erater_usage', $config->default_erater_usage);
         $mform->disabledIf('erater_usage', 'erater', 'eq', 0);
         $mform->addElement('checkbox', 'erater_mechanics', '', " " . get_string('erater_mechanics', 'turnitintooltwo'));
         $mform->setDefault('erater_mechanics', $config->default_erater_mechanics);
         $mform->disabledIf('erater_mechanics', 'erater', 'eq', 0);
         $mform->addElement('checkbox', 'erater_style', '', " " . get_string('erater_style', 'turnitintooltwo'));
         $mform->setDefault('erater_style', $config->default_erater_style);
         $mform->disabledIf('erater_style', 'erater', 'eq', 0);
     }
     $mform->addElement('hidden', 'ownerid', null);
     $mform->setType('ownerid', PARAM_RAW);
     $mform->addElement('html', $modulestring);
     $features = new stdClass();
     $features->groups = true;
     $features->groupings = true;
     $features->groupmembersonly = true;
     $this->standard_coursemodule_elements($features);
     $this->add_action_buttons();
 }
 /**
  * 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;
 }
 /**
  * Create the module as an assignment within Turnitin if it does not exist,
  * if we have a Turnitin id for the module then edit it
  */
 public function sync_tii_assignment($cm, $coursetiiid, $workflowcontext = "site", $submittoturnitin = false)
 {
     global $DB, $CFG;
     $config = turnitintooltwo_admin_config();
     $modulepluginsettings = $this->get_settings($cm->id);
     $moduledata = $DB->get_record($cm->modname, array('id' => $cm->instance));
     // Configure assignment object to send to Turnitin.
     $assignment = new TiiAssignment();
     $assignment->setClassId($coursetiiid);
     // Need to truncate the moodle assignment title to be compatible with a Turnitin class (max length 99)
     $assignment->setTitle(mb_strlen($moduledata->name) > 80 ? mb_substr($moduledata->name, 0, 80) . "... (Moodle PP)" : $moduledata->name . " (Moodle PP)");
     $assignment->setSubmitPapersTo(isset($modulepluginsettings["plagiarism_submitpapersto"]) ? $modulepluginsettings["plagiarism_submitpapersto"] : 1);
     $assignment->setSubmittedDocumentsCheck($modulepluginsettings["plagiarism_compare_student_papers"]);
     $assignment->setInternetCheck($modulepluginsettings["plagiarism_compare_internet"]);
     $assignment->setPublicationsCheck($modulepluginsettings["plagiarism_compare_journals"]);
     if ($config->repositoryoption == 1) {
         $institutioncheck = isset($modulepluginsettings["plagiarism_compare_institution"]) ? $modulepluginsettings["plagiarism_compare_institution"] : 0;
         $assignment->setInstitutionCheck($institutioncheck);
     }
     $assignment->setAuthorOriginalityAccess($modulepluginsettings["plagiarism_show_student_report"]);
     $assignment->setResubmissionRule((int) $modulepluginsettings["plagiarism_report_gen"]);
     $assignment->setBibliographyExcluded($modulepluginsettings["plagiarism_exclude_biblio"]);
     $assignment->setQuotedExcluded($modulepluginsettings["plagiarism_exclude_quoted"]);
     $assignment->setSmallMatchExclusionType($modulepluginsettings["plagiarism_exclude_matches"]);
     $modulepluginsettings["plagiarism_exclude_matches_value"] = !empty($modulepluginsettings["plagiarism_exclude_matches_value"]) ? $modulepluginsettings["plagiarism_exclude_matches_value"] : 0;
     $assignment->setSmallMatchExclusionThreshold($modulepluginsettings["plagiarism_exclude_matches_value"]);
     if ($config->useanon) {
         $assignment->setAnonymousMarking($modulepluginsettings["plagiarism_anonymity"]);
     }
     $assignment->setAllowNonOrSubmissions(!empty($modulepluginsettings["plagiarism_allow_non_or_submissions"]) ? 1 : 0);
     $assignment->setTranslatedMatching(!empty($modulepluginsettings["plagiarism_transmatch"]) ? 1 : 0);
     // Moodle handles submissions and whether they are allowed so this should always be true.
     // Otherwise, the Turnitin setting is incompatible with Moodle due to multiple files and resubmission rules.
     $assignment->setLateSubmissionsAllowed(1);
     $assignment->setMaxGrade(0);
     $assignment->setRubricId(!empty($modulepluginsettings["plagiarism_rubric"]) ? $modulepluginsettings["plagiarism_rubric"] : '');
     if (!empty($moduledata->grade)) {
         $assignment->setMaxGrade($moduledata->grade < 0 ? 100 : (int) $moduledata->grade);
     }
     if (!empty($moduledata->allowsubmissionsfromdate)) {
         $dtstart = $moduledata->allowsubmissionsfromdate;
     } else {
         if (!empty($moduledata->timeavailable)) {
             $dtstart = $moduledata->timeavailable;
         } else {
             $dtstart = $cm->added;
         }
     }
     $dtstart = $dtstart <= strtotime('-1 year') ? strtotime('-11 months') : $dtstart;
     $assignment->setStartDate(gmdate("Y-m-d\\TH:i:s\\Z", $dtstart));
     // Set post date. If "hidden until" has been set in gradebook then we will use that value, otherwise we will
     // use start date. If the grades are to be completely hidden then we will set post date in the future.
     // From 2.6, if grading markflow is enabled and no grades have been released, we will use due date +4 weeks.
     $dtpost = 0;
     if ($cm->modname != "forum") {
         if ($gradeitem = $DB->get_record('grade_items', array('iteminstance' => $cm->instance, 'itemmodule' => $cm->modname, 'courseid' => $cm->course, 'itemnumber' => 0))) {
             switch ($gradeitem->hidden) {
                 case 1:
                     $dtpost = strtotime('+6 months');
                     break;
                 case 0:
                     $dtpost = $dtstart;
                     // If any grades have been released early via marking workflow, set post date to current time.
                     if ($CFG->branch >= 26 && $cm->modname == 'assign' && !empty($moduledata->markingworkflow)) {
                         $gradesreleased = $DB->record_exists('assign_user_flags', array('assignment' => $cm->instance, 'workflowstate' => 'released'));
                         $dtpost = $gradesreleased ? time() : strtotime('+1 month');
                     }
                     break;
                 default:
                     $dtpost = $gradeitem->hidden;
                     break;
             }
         }
     }
     // Ensure post date can't be before start date
     if ($dtpost < $dtstart) {
         $dtpost = $dtstart;
     }
     // Set due date, dependent on various things.
     $dtdue = !empty($moduledata->duedate) ? $moduledata->duedate : 0;
     // If the due date has been set more than a year ahead then restrict it to 1 year from now.
     if ($dtdue > strtotime('+1 year')) {
         $dtdue = strtotime('+1 year');
     }
     // If a cut-off date has been set, use that as the Turnitin due date.
     if (!empty($moduledata->cutoffdate)) {
         $dtdue = $moduledata->cutoffdate;
     }
     // Ensure due date can't be before start date
     if ($dtdue <= $dtstart) {
         $dtdue = strtotime('+1 month', $dtstart);
     }
     // Ensure due date is always in the future for submissions.
     if ($dtdue <= time() && $submittoturnitin) {
         $dtdue = strtotime('+1 day');
     }
     $assignment->setDueDate(gmdate("Y-m-d\\TH:i:s\\Z", $dtdue));
     $assignment->setFeedbackReleaseDate(gmdate("Y-m-d\\TH:i:s\\Z", $dtpost));
     // Erater settings.
     $assignment->setErater(isset($modulepluginsettings["plagiarism_erater"]) ? $modulepluginsettings["plagiarism_erater"] : 0);
     $assignment->setEraterSpelling(isset($modulepluginsettings["plagiarism_erater_spelling"]) ? $modulepluginsettings["plagiarism_erater_spelling"] : 0);
     $assignment->setEraterGrammar(isset($modulepluginsettings["plagiarism_erater_grammar"]) ? $modulepluginsettings["plagiarism_erater_grammar"] : 0);
     $assignment->setEraterUsage(isset($modulepluginsettings["plagiarism_erater_usage"]) ? $modulepluginsettings["plagiarism_erater_usage"] : 0);
     $assignment->setEraterMechanics(isset($modulepluginsettings["plagiarism_erater_mechanics"]) ? $modulepluginsettings["plagiarism_erater_mechanics"] : 0);
     $assignment->setEraterStyle(isset($modulepluginsettings["plagiarism_erater_style"]) ? $modulepluginsettings["plagiarism_erater_style"] : 0);
     $assignment->setEraterSpellingDictionary(isset($modulepluginsettings["plagiarism_erater_dictionary"]) ? $modulepluginsettings["plagiarism_erater_dictionary"] : 'en_US');
     $assignment->setEraterHandbook(isset($modulepluginsettings["plagiarism_erater_handbook"]) ? $modulepluginsettings["plagiarism_erater_handbook"] : 0);
     // If we have a turnitin id then edit the assignment otherwise create it.
     if ($tiiassignment = $DB->get_record('plagiarism_turnitin_config', array('cm' => $cm->id, 'name' => 'turnitin_assignid'), 'value')) {
         $assignment->setAssignmentId($tiiassignment->value);
         $turnitintooltwoassignment = new turnitintooltwo_assignment(0, '', 'PP');
         $turnitintooltwoassignment->edit_tii_assignment($assignment, $workflowcontext);
         $turnitinassignid = $tiiassignment->value;
     } else {
         $turnitintooltwoassignment = new turnitintooltwo_assignment(0, '', 'PP');
         $turnitinassignid = $turnitintooltwoassignment->create_tii_assignment($assignment, 0, 0, 'plagiarism_plugin', $workflowcontext);
         $moduleconfigvalue = new stdClass();
         $moduleconfigvalue->cm = $cm->id;
         $moduleconfigvalue->name = 'turnitin_assignid';
         $moduleconfigvalue->value = $turnitinassignid;
         $DB->insert_record('plagiarism_turnitin_config', $moduleconfigvalue);
     }
     // Save the post date we have stored in Turnitin
     $moduleconfigvalue = new stdClass();
     $moduleconfigvalue->cm = $cm->id;
     $moduleconfigvalue->name = 'plagiarism_post_date';
     $moduleconfigvalue->value = $dtpost;
     if ($plagiarism_post_date = $DB->get_record('plagiarism_turnitin_config', array('cm' => $cm->id, 'name' => 'plagiarism_post_date'), 'id')) {
         $moduleconfigvalue->id = $plagiarism_post_date->id;
         $DB->update_record('plagiarism_turnitin_config', $moduleconfigvalue);
     } else {
         $DB->insert_record('plagiarism_turnitin_config', $moduleconfigvalue);
     }
     return $turnitinassignid;
 }
 /**
  * Enrol the user on this course/class in Turnitin
  *
  * @param type $tiicourseid id for the course/class in Turnitin
  * @return boolean
  */
 public function join_user_to_class($tiicourseid)
 {
     $turnitincomms = new turnitintooltwo_comms();
     // We only want an API log entry for this if diagnostic mode is set to Debugging
     if (empty($config)) {
         $config = turnitintooltwo_admin_config();
     }
     if ($config->enablediagnostic != 2) {
         $turnitincomms->setDiagnostic(0);
     }
     $turnitincall = $turnitincomms->initialise_api();
     $membership = new TiiMembership();
     $membership->setClassId($tiicourseid);
     $membership->setUserId($this->tii_user_id);
     $membership->setRole($this->role);
     try {
         $turnitincall->createMembership($membership);
         turnitintooltwo_activitylog("User " . $this->id . " (" . $this->tii_user_id . ") joined to class (" . $tiicourseid . ")", "REQUEST");
         return true;
     } catch (Exception $e) {
         // Ignore exception as we don't need it, this saves time as the alternative
         // is checking all class memberships to see if user is already enrolled.
         $faultcode = $e->getFaultCode();
         if ($faultcode == 'invaliddata') {
             return null;
         } else {
             return false;
         }
     }
 }