public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . "/mod/turnitintooltwo/lib.php";
     require_once $CFG->dirroot . "/mod/turnitintooltwo/turnitintooltwo_view.class.php";
     $data = (array) $this->get_custom_data();
     // Make sure we are still wanted.
     $submission = $DB->get_record('turnitintooltwo_submissions', array('id' => $data['submissionid']));
     if (!$submission) {
         return true;
     }
     cli_writeln("Processing Turnitintooltwo submission: " . $data['submissionid']);
     $user = $DB->get_record('user', array('id' => $data['userid']));
     \core\session\manager::set_user($user);
     $turnitintooltwo = $DB->get_record('turnitintooltwo', array('id' => $data['tiiid']));
     list($course, $cm) = get_course_and_cm_from_instance($turnitintooltwo, 'turnitintooltwo');
     try {
         $turnitintooltwoassignment = new \turnitintooltwo_assignment($turnitintooltwo->id, $turnitintooltwo);
         $turnitintooltwosubmission = new \turnitintooltwo_submission($data['submissionid'], "moodle", $turnitintooltwoassignment);
         $parts = $turnitintooltwoassignment->get_parts();
         $tiisubmission = $turnitintooltwosubmission->do_tii_submission($cm, $turnitintooltwoassignment);
         // Update submission.
         $DB->update_record('turnitintooltwo_submissions', array('id' => $data['submissionid'], 'submission_modified' => $data['subtime']));
     } catch (\Exception $e) {
         $tiisubmission = array('success' => false, 'message' => $e->getMessage());
         cli_writeln($e->getMessage());
     }
     $digitalreceipt = $tiisubmission;
     $digitalreceipt['is_manual'] = 0;
     $digitalreceipt = json_encode($digitalreceipt);
     $this->update_sub_status($data['submissionid'], $tiisubmission['success'], $digitalreceipt);
     if ($tiisubmission['success'] === true) {
         $lockedassignment = new \stdClass();
         $lockedassignment->id = $turnitintooltwoassignment->turnitintooltwo->id;
         $lockedassignment->submitted = 1;
         $DB->update_record('turnitintooltwo', $lockedassignment);
         $lockedpart = new \stdClass();
         $lockedpart->id = $data['submissionpart'];
         $lockedpart->submitted = 1;
         // Disable anonymous marking if post date has passed.
         if ($parts[$data['submissionpart']]->dtpost <= time()) {
             $lockedpart->unanon = 1;
         }
         $DB->update_record('turnitintooltwo_parts', $lockedpart);
         cli_writeln("Finished processing successful submission: " . $data['submissionid']);
     } else {
         turnitintooltwo_add_to_log($course->id, "errored submission", 'view.php?id=' . $cm->id, "Failed to submit '" . $turnitintooltwosubmission->submission_title . "'", $cm->id, $user->id, array('submissionid' => $data['submissionid']));
         cli_writeln("Finished processing unsuccessful submission: " . $data['submissionid']);
     }
     \core\session\manager::set_user(get_admin());
     return $tiisubmission['success'];
 }
Esempio n. 2
0
    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();
$turnitintooltwoassignment = new turnitintooltwo_assignment($turnitintooltwo->id, $turnitintooltwo);
// Define file upload options.
$maxbytessite = $CFG->maxbytes == 0 || $CFG->maxbytes > TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE ? TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE : $CFG->maxbytes;
$maxbytescourse = $COURSE->maxbytes == 0 || $COURSE->maxbytes > TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE ? TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE : $COURSE->maxbytes;
$maxfilesize = get_user_max_upload_file_size(context_module::instance($cm->id), $maxbytessite, $maxbytescourse, $turnitintooltwoassignment->turnitintooltwo->maxfilesize);
$maxfilesize = $maxfilesize <= 0 ? TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE : $maxfilesize;
$turnitintooltwofileuploadoptions = array('maxbytes' => $maxfilesize, 'subdirs' => false, 'maxfiles' => 1, 'accepted_types' => '*');
if (!($parts = $turnitintooltwoassignment->get_parts())) {
    turnitintooltwo_print_error('partgeterror', 'turnitintooltwo', null, null, __FILE__, __LINE__);
}
// Get whether user is a tutor/student.
$istutor = has_capability('mod/turnitintooltwo:grade', context_module::instance($cm->id));
$userrole = $istutor ? 'Instructor' : 'Learner';
// Deal with actions here.
if (!empty($action)) {
    turnitintooltwo_activitylog("Action: " . $action . " | Id: " . $turnitintooltwo->id . " | Part: " . $part, "REQUEST");
 /**
  * Create a migrated turnitin assignment in Moodle
  *
  * @global type $DB
  * @global type $CFG
  * @param array $partids the ids of turnitin assignment to create as parts of new assignment
  * @param int $courseid
  * @param string $assignmentname
  * @return boolean false if failed
  */
 public static function create_migration_assignment($partids, $courseid, $assignmentname)
 {
     global $DB, $CFG, $OUTPUT;
     $config = turnitintooltwo_admin_config();
     $partids = (array) $partids;
     $tempassignment = new turnitintooltwo_assignment(0, '', 'M');
     $newassignment = $tempassignment->update_assignment_from_tii($partids);
     $newassignment["turnitintooltwo"]->course = $courseid;
     $newassignment["turnitintooltwo"]->name = $assignmentname;
     $newassignment["turnitintooltwo"]->numparts = count($partids);
     $newassignment["turnitintooltwo"]->gradedisplay = 1;
     $newassignment["turnitintooltwo"]->shownonsubmission = 1;
     $newassignment["turnitintooltwo"]->usegrademark = $config->usegrademark;
     // Get maximum grade.
     $newassignment["turnitintooltwo"]->grade = 0;
     foreach ($newassignment["parts"] as $part) {
         if ($newassignment["turnitintooltwo"]->grade < $part->maxmarks) {
             $newassignment["turnitintooltwo"]->grade = $part->maxmarks;
         }
     }
     $turnitintooltwoassignment = new turnitintooltwo_assignment(0, $newassignment["turnitintooltwo"]);
     if (!($toolid = $DB->insert_record("turnitintooltwo", $turnitintooltwoassignment->turnitintooltwo))) {
         turnitintooltwo_activitylog(get_string('migrationassignmentcreationerror', 'turnitintooltwo', $courseid), "REQUEST");
         return false;
     } else {
         turnitintooltwo_activitylog(get_string('migrationassignmentcreated', 'turnitintooltwo', $toolid), "REQUEST");
     }
     $module = $DB->get_record("modules", array("name" => "turnitintooltwo"));
     $coursemodule = new stdClass();
     $coursemodule->course = $courseid;
     $coursemodule->module = $module->id;
     $coursemodule->added = time();
     $coursemodule->instance = $toolid;
     $coursemodule->section = 0;
     include_once $CFG->dirroot . "/course/lib.php";
     // Add Course module and get course section.
     if (!($coursemodule->coursemodule = add_course_module($coursemodule))) {
         echo $OUTPUT->notification(get_string('migrationassignmenterror1', 'turnitintooltwo', $courseid));
         turnitintooltwo_activitylog(get_string('migrationassignmenterror1', 'turnitintooltwo', $courseid), "REQUEST");
         return false;
     }
     if (is_callable('course_add_cm_to_section')) {
         if (!($sectionid = course_add_cm_to_section($coursemodule->course, $coursemodule->coursemodule, $coursemodule->section))) {
             echo $OUTPUT->notification(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid));
             turnitintooltwo_activitylog(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid), "REQUEST");
             return false;
         }
     } else {
         if (!($sectionid = add_mod_to_section($coursemodule))) {
             echo $OUTPUT->notification(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid));
             turnitintooltwo_activitylog(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid), "REQUEST");
             return false;
         }
     }
     $DB->set_field("course_modules", "section", $sectionid, array("id" => $coursemodule->coursemodule));
     rebuild_course_cache($courseid);
     foreach ($newassignment["parts"] as $part) {
         $part->turnitintooltwoid = $toolid;
         $part->deleted = 0;
         $part->migrated = -1;
         if ($part->id = $DB->insert_record("turnitintooltwo_parts", $part)) {
             turnitintooltwo_activitylog(get_string('migrationassignmentpartcreated', 'turnitintooltwo', $part->id), "REQUEST");
         }
         if ($turnitintooltwoassignment->create_event($toolid, $part->partname, $part->dtdue)) {
             $part->migrated = 1;
             $DB->update_record("turnitintooltwo_parts", $part);
         } else {
             echo $OUTPUT->notification(get_string('migrationassignmenterror3', 'turnitintooltwo', $courseid));
             turnitintooltwo_activitylog(get_string('migrationassignmenterror3', 'turnitintooltwo', $courseid), "REQUEST");
         }
     }
 }
 /**
  * Return a table containing all the assignments in the relevant course
  *
  * @global type $CFG
  * @global type $OUTPUT
  * @param obj $course the moodle course data
  * @return output
  */
 public function show_assignments($course)
 {
     global $CFG, $OUTPUT, $USER;
     $turnitintooltwos = turnitintooltwo_assignment::get_all_assignments_in_course($course);
     $table = new html_table();
     $table->id = "dataTable";
     $rows = array();
     // Do the table headers.
     $cells = array();
     if ($course->format == "weeks") {
         $cells["weeks"] = new html_table_cell(get_string("week"));
     } else {
         if ($course->format == "topics") {
             $cells["topics"] = new html_table_cell(get_string("topic"));
         }
     }
     $cells["name"] = new html_table_cell(get_string("name"));
     $cells["start_date"] = new html_table_cell(get_string("dtstart", "turnitintooltwo"));
     $cells["number_of_parts"] = new html_table_cell(get_string("numberofparts", "turnitintooltwo"));
     $cells["submissions"] = new html_table_cell(get_string("submissions", "turnitintooltwo"));
     $table->head = $cells;
     $i = 1;
     foreach ($turnitintooltwos as $turnitintooltwo) {
         $cm = get_coursemodule_from_id('turnitintooltwo', $turnitintooltwo->coursemodule, $course->id);
         $turnitintooltwoassignment = new turnitintooltwo_assignment($turnitintooltwo->id, $turnitintooltwo);
         if ($course->format == "weeks" || $course->format == "topics") {
             $cells[$course->format] = new html_table_cell($turnitintooltwoassignment->turnitintooltwo->section);
             $cells[$course->format]->attributes["class"] = "centered_cell";
         }
         // Show links dimmed if the mod is hidden.
         $attributes["class"] = !$turnitintooltwo->visible ? 'dimmed' : '';
         $linkurl = $CFG->wwwroot . '/mod/turnitintooltwo/view.php?id=' . $turnitintooltwoassignment->turnitintooltwo->coursemodule . '&do=submissions';
         $cells["name"] = new html_table_cell(html_writer::link($linkurl, $turnitintooltwo->name, $attributes));
         $cells["start_date"] = new html_table_cell(userdate($turnitintooltwoassignment->get_start_date(), get_string('strftimedatetimeshort', 'langconfig')));
         $cells["start_date"]->attributes["class"] = "centered_cell";
         $cells["number_of_parts"] = new html_table_cell(count($turnitintooltwoassignment->get_parts()));
         $cells["number_of_parts"]->attributes["class"] = "centered_cell";
         if (has_capability('mod/turnitintooltwo:grade', context_module::instance($cm->id))) {
             $noofsubmissions = $turnitintooltwoassignment->count_submissions($cm, 0);
         } else {
             $noofsubmissions = count($turnitintooltwoassignment->get_user_submissions($USER->id, $turnitintooltwoassignment->turnitintooltwo->id));
         }
         $cells["submissions"] = new html_table_cell(html_writer::link($linkurl, $noofsubmissions, $attributes));
         $cells["submissions"]->attributes["class"] = "centered_cell";
         $rows[$i] = new html_table_row($cells);
         $i++;
     }
     $table->data = $rows;
     return $OUTPUT->box(html_writer::table($table), 'generalbox boxaligncenter');
 }
             // Create the module as an assignment in Turnitin.
             $tiiassignment = $pluginturnitin->sync_tii_assignment($cm, $coursedata->turnitin_cid);
             $tiiassignmentid = $tiiassignment['tiiassignmentid'];
         }
         $user = new turnitintooltwo_user($USER->id, "Instructor");
         $user->join_user_to_class($coursedata->turnitin_cid);
         echo html_writer::tag("div", turnitintooltwo_view::output_lti_form_launch('peermark_manager', 'Instructor', $tiiassignmentid), array("class" => "launch_form", "style" => "display:none;"));
         echo html_writer::script("<!--\n                                    window.document.forms[0].submit();\n                                    //-->");
     }
     break;
 case "rubricview":
     $isstudent = $cm->modname == "forum" ? has_capability('mod/' . $cm->modname . ':replypost', $context) : has_capability('mod/' . $cm->modname . ':submit', $context);
     if ($isstudent) {
         $tiiassignment = $DB->get_record('plagiarism_turnitin_config', array('cm' => $cm->id, 'name' => 'turnitin_assignid'));
         $user = new turnitintooltwo_user($USER->id, "Learner");
         $coursedata = turnitintooltwo_assignment::get_course_data($cm->course, 'PP');
         $user->join_user_to_class($coursedata->turnitin_cid);
         echo html_writer::tag("div", turnitintooltwo_view::output_lti_form_launch('rubric_view', 'Learner', $tiiassignment->value), array("class" => "launch_form", "style" => "display:none;"));
         echo html_writer::script("<!--\n                                    window.document.forms[0].submit();\n                                    //-->");
     }
     break;
 case "peermarkreviews":
     $isstudent = $cm->modname == "forum" ? has_capability('mod/' . $cm->modname . ':replypost', $context) : has_capability('mod/' . $cm->modname . ':submit', $context);
     if ($userrole == 'Instructor' || $isstudent) {
         $role = $istutor ? 'Instructor' : 'Learner';
         $tiiassignment = $DB->get_record('plagiarism_turnitin_config', array('cm' => $cm->id, 'name' => 'turnitin_assignid'));
         echo html_writer::tag("div", turnitintooltwo_view::output_lti_form_launch('peermark_reviews', $role, $tiiassignment->value), array("class" => "launch_form", "style" => "display:none;"));
         echo html_writer::script("<!--\n                                    window.document.forms[0].submit();\n                                    //-->");
     }
     break;
 case "actionuseragreement":
Esempio n. 6
0
             turnitintooltwo_assignment::create_migration_assignment($partids, $courseid, $assignmentname);
         }
     }
     break;
 case "edit_course_end_date":
     if (!confirm_sesskey()) {
         throw new moodle_exception('invalidsesskey', 'error');
     }
     if (has_capability('moodle/course:update', context_system::instance())) {
         $tiicourseid = required_param('tii_course_id', PARAM_INT);
         $tiicoursetitle = required_param('tii_course_title', PARAM_TEXT);
         $enddated = required_param('end_date_d', PARAM_INT);
         $enddatem = required_param('end_date_m', PARAM_INT);
         $enddatey = required_param('end_date_y', PARAM_INT);
         $enddate = mktime(00, 00, 00, $enddatem, $enddated, $enddatey);
         if (turnitintooltwo_assignment::edit_tii_course_end_date($tiicourseid, $tiicoursetitle, $enddate)) {
             $return["status"] = "success";
             $return["end_date"] = userdate($enddate, get_string('strftimedate', 'langconfig'));
         } else {
             $return["status"] = "fail";
             $return["msg"] = get_string('unanonymiseerror', 'turnitintooltwo');
         }
     } else {
         $return["status"] = "fail";
         $return["msg"] = get_string('nopermissions', 'error', get_string('course:update', 'role'));
     }
     echo json_encode($return);
     break;
 case "check_upgrade":
     if (!confirm_sesskey()) {
         throw new moodle_exception('invalidsesskey', 'error');
Esempio n. 7
0
switch ($cmd) {
    case "supportwizard":
        $PAGE->requires->jquery_plugin('turnitintooltwo-turnitin_helpdesk', 'mod_turnitintooltwo');
        $title = get_string('turnitinhelpdesk', 'turnitintooltwo');
        include "classes/helpdeskwizard/helpdeskwizard.php";
        $helpdeskwizard = new helpdeskwizard();
        $output = $helpdeskwizard->output_wizard($id);
        break;
    case "supportform":
        include "classes/helpdeskwizard/helpdeskwizard.php";
        $helpdeskwizard = new helpdeskwizard();
        $title = get_string('turnitinhelpdesk', 'turnitintooltwo');
        // Get the Turnitin class id if we are in a class context.
        $tiiclass = 0;
        if ($id != 0) {
            $course = turnitintooltwo_assignment::get_course_data($course->id);
            $tiiclass = isset($course->turnitin_cid) ? $course->turnitin_cid : 0;
        }
        $category = optional_param('category', "", PARAM_ALPHAEXT);
        $sub_category = optional_param('sub_category', "", PARAM_ALPHAEXT);
        $config = turnitintooltwo_admin_config();
        $plugin_version = turnitintooltwo_get_version();
        // Parameters to pass to support form.
        $params = array('category' => $category, 'sub_category' => $sub_category, 'class_id' => $tiiclass, 'vle_version' => 'Moodle (' . $CFG->branch . ') ' . $CFG->version, 'integration_id' => 'MoodleDirectV2', 'integration_version' => $plugin_version, 'account_id' => $config->accountid);
        // Output Iframe containing Turnitin Helpdesk form.
        $output = $helpdeskwizard->output_form($params);
        break;
    case "courses":
        require_capability('moodle/course:create', context_system::instance());
        $title = get_string('restorationheader', 'turnitintooltwo');
        $jsrequired = true;
 /**
  * Edit the submission in Turnitin so a tutor can see the identity of the student
  *
  * @param string $reason
  * @return boolean
  */
 public function unanonymise_submission($reason)
 {
     // Get user and part details.
     $turnitintooltwoassignment = new turnitintooltwo_assignment($this->turnitintooltwoid);
     $partdetails = $turnitintooltwoassignment->get_part_details($this->submission_part);
     $user = new turnitintooltwo_user($this->userid);
     // Initialise Comms Object.
     $turnitincomms = new turnitintooltwo_comms();
     $turnitincall = $turnitincomms->initialise_api();
     $submission = new TiiSubmission();
     $submission->setSubmissionId($this->submission_objectid);
     $submission->setAssignmentId($partdetails->tiiassignid);
     if (strlen($reason) < 5) {
         $reason = "No specified reason: " . $reason;
     }
     $submission->setAnonymousRevealReason($reason);
     $submission->setAnonymousRevealUser($user->tii_user_id);
     $submission->setAnonymousRevealDateTime(date("c"));
     try {
         $turnitincall->updateSubmission($submission);
         return true;
     } catch (Exception $e) {
         $turnitincomms->handle_exceptions($e, "unanonymiseerror", false);
         return false;
     }
 }
Esempio n. 9
0
/**
 * Show the table that will display the assignments in course migration
 *
 * @param int the course id to get assignments for
 * @global type $DB
 * @global type $OUTPUT
 * @return html
 */
function turnitintooltwo_init_browser_assignment_table($tiicourseid)
{
    global $OUTPUT, $DB;
    $table = new html_table();
    $table->id = "assignmentBrowserTable";
    $output = "";
    $courseid = 0;
    $coursetitle = '';
    $turnitincourse = $DB->get_records_sql("\n                            SELECT tc.turnitin_cid, tc.course_type, tc.courseid\n                            FROM {turnitintooltwo_courses} tc\n                            RIGHT JOIN {course} c ON c.id = tc.courseid\n                            WHERE tc.turnitin_cid = ? ", array($tiicourseid));
    if (!empty($turnitincourse)) {
        $course = current($turnitincourse);
        $coursedetails = turnitintooltwo_assignment::get_course_data($course->courseid, $course->course_type);
        $courseid = $course->courseid;
        $coursetitle = $coursedetails->fullname;
    }
    $class = empty($coursetitle) ? ' hidden_class' : '';
    $coursetitle = html_writer::tag('span', $coursetitle, array('id' => 'existing_course_title_span'));
    $output .= html_writer::tag("h3", get_string('courseexistsmoodle', 'turnitintooltwo') . $coursetitle, array('class' => 'existing_course_title_h3' . $class));
    // Do the table headers.
    $cells = array();
    $cells[0] = new html_table_cell('&nbsp;');
    $cells[1] = new html_table_cell(get_string('turnitintooltwoname', 'turnitintooltwo'));
    $cells[2] = new html_table_cell(get_string('maxmarks', 'turnitintooltwo'));
    $cells[3] = new html_table_cell(get_string('turnitinid', 'turnitintooltwo'));
    $table->head = $cells;
    $elements = array();
    $elements[] = array('html', get_string('coursebrowserassignmentdesc', 'turnitintooltwo'));
    $elements[] = array('html', html_writer::table($table));
    $elements[] = array('text', 'assignmentname', get_string('assignmenttitle', 'turnitintooltwo'));
    $elements[] = array('button', 'create_assignment', get_string('downloadassignment', 'turnitintooltwo'));
    $customdata = array();
    $customdata["elements"] = $elements;
    $customdata["hide_submit"] = true;
    $customdata["disable_form_change_checker"] = true;
    $assignmentform = new turnitintooltwo_form('', $customdata);
    $output .= $OUTPUT->box($_SESSION["stored_tii_courses"][$tiicourseid], '', 'tii_course_name');
    $output .= $OUTPUT->box($tiicourseid, '', 'tii_course_id');
    $output .= $OUTPUT->box($courseid, '', 'course_id');
    $output .= $assignmentform->display();
    return $output;
}
 /**
  * If no user data was restored after everything has been restored then
  * create a new course in Turnitin
  */
 public function after_restore()
 {
     global $DB, $CFG;
     if (!empty($_SESSION['tii_course_reset'])) {
         $course = turnitintooltwo_assignment::get_course_data($_SESSION['course_id']);
         //Get the main site admin.
         $admins = explode(",", $CFG->siteadmins);
         $ownerid = $admins[0];
         // Get the number of assignments that already exist on this course that aren't part of recreation.
         $assignments = 0;
         if (!empty($_SESSION['assignments_to_create'])) {
             $modules = $_SESSION['assignments_to_create'];
             list($notinsql, $notinparams) = $DB->get_in_or_equal($modules, SQL_PARAMS_QM, 'param', false);
             $assignments = $DB->count_records_select('turnitintooltwo', " course = ? AND id " . $notinsql, array_merge(array($_SESSION['course_id']), $notinparams));
         }
         // Only recreate course on Turnitin if Turnitin Assignments don't exist on destination course.
         if ($assignments == 0) {
             // Remove Turnitin link from course
             $turnitin_course = new stdClass();
             $turnitin_course->id = $course->tii_rel_id;
             $turnitin_course->turnitin_cid = 0;
             $DB->update_record('turnitintooltwo_courses', $turnitin_course);
             // Recreate course in Turnitin
             $course->turnitin_cid = 0;
             $tmpassignment = new turnitintooltwo_assignment(0, '', '');
             $turnitin_course = $tmpassignment->create_tii_course($course, $ownerid);
             // Join the course as Instructor
             $owner = new turnitintooltwo_user($ownerid, 'Instructor');
             $owner->join_user_to_class($turnitin_course->turnitin_cid);
         }
         unset($_SESSION['tii_course_reset']);
         unset($_SESSION['course_id']);
     }
     if (!empty($_SESSION['assignments_to_create'])) {
         foreach ($_SESSION["assignments_to_create"] as $new_assignment_id) {
             $assignment = new turnitintooltwo_assignment($new_assignment_id);
             $assignment->unlink_assignment();
             $assignment->edit_moodle_assignment(true, true);
         }
         unset($_SESSION['tii_assignment_reset']);
         unset($_SESSION['assignments_to_create']);
     }
 }
 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();
 }
 /**
  * Migrate course from previous version of plugin to this
  */
 public function migrate_previous_course($coursedata, $turnitincid, $workflowcontext = "site")
 {
     global $DB, $USER;
     $turnitincourse = new stdClass();
     $turnitincourse->courseid = $coursedata->id;
     $turnitincourse->ownerid = $USER->id;
     $turnitincourse->turnitin_cid = $turnitincid;
     $turnitincourse->turnitin_ctl = $coursedata->fullname . " (Moodle PP)";
     $turnitincourse->course_type = 'PP';
     if (empty($coursedata->tii_rel_id)) {
         $method = "insert_record";
     } else {
         $method = "update_record";
         $turnitincourse->id = $coursedata->tii_rel_id;
     }
     if (!($insertid = $DB->{$method}('turnitintooltwo_courses', $turnitincourse))) {
         if ($workflowcontext != "cron") {
             turnitintooltwo_print_error('classupdateerror', 'plagiarism_turnitin', null, null, __FILE__, __LINE__);
             exit;
         }
     }
     $turnitintooltwoassignment = new turnitintooltwo_assignment(0, '', 'PP');
     $turnitintooltwoassignment->edit_tii_course($coursedata, "PP");
     $coursedata->turnitin_cid = $turnitincid;
     $coursedata->turnitin_ctl = $turnitincourse->turnitin_ctl;
     return $coursedata;
 }
Esempio n. 13
0
 /**
  * If there is no submission record then we are creating one. Text content should be submitted.
  * If a file has already been submitted then check whether the identifier is the same, if it is do nothing.
  * If it's not then either edit submission or create new one depending on module settings.
  */
 public function tii_submission($cm, $tiiassignmentid, $user, $identifier, $submissiontype, $itemid = 0, $title = '', $textcontent = '', $context = 'instant')
 {
     global $CFG, $DB, $USER;
     $settings = $this->get_settings($cm->id);
     // Update user's details on Turnitin.
     $user->edit_tii_user();
     // Clean up old Turnitin submission files.
     if ($itemid != 0 && $submissiontype == 'file' && $cm->modname != 'forum') {
         $this->clean_old_turnitin_submissions($cm, $user->id, $itemid, $submissiontype, $identifier);
     }
     // Work out submission method.
     // If this file has successfully submitted in the past then break, text content is to be submitted.
     switch ($submissiontype) {
         case 'file':
         case 'text_content':
             // Get file data or prepare text submission.
             if ($submissiontype == 'file') {
                 $fs = get_file_storage();
                 $file = $fs->get_file_by_hash($identifier);
                 $title = $file->get_filename();
                 $timemodified = $file->get_timemodified();
                 $filename = $file->get_filename();
                 $textcontent = $file->get_content();
             } else {
                 // If we are submitting text_content via AJAX there will be no actual content passed in so we need to grab it.
                 if ($textcontent == '') {
                     switch ($cm->modname) {
                         case 'assign':
                             // Check whether submission is a group submission so we can get the correct content.
                             // Note: This will not work if the submitting user is in multiple groups.
                             $submissionsquery = array('assignment' => $cm->instance);
                             $submissionsquery['userid'] = $user->id;
                             if ($CFG->branch > 23) {
                                 $moduledata = $DB->get_record($cm->modname, array('id' => $cm->instance));
                                 if ($moduledata->teamsubmission) {
                                     require_once $CFG->dirroot . '/mod/assign/locallib.php';
                                     $context = context_course::instance($cm->course);
                                     $assignment = new assign($context, $cm, null);
                                     $submissionsquery['userid'] = 0;
                                     $submissionsquery['groupid'] = 0;
                                     if ($group = $assignment->get_submission_group($user->id)) {
                                         $submissionsquery['groupid'] = $group->id;
                                     }
                                 }
                             }
                             // This will need to be reworked when linkarray in get_links() contains submission id.
                             $moodlesubmissions = $DB->get_records('assign_submission', $submissionsquery, 'id, timemodified');
                             $moodlesubmission = end($moodlesubmissions);
                             $moodletextsubmission = $DB->get_record('assignsubmission_onlinetext', array('submission' => $moodlesubmission->id), 'onlinetext');
                             $timemodified = $moodlesubmission->timemodified;
                             $textcontent = strip_tags($moodletextsubmission->onlinetext);
                             break;
                         case 'workshop':
                             $moodlesubmission = $DB->get_record('workshop_submissions', array('workshopid' => $cm->instance, 'authorid' => $user->id), 'title, content, timemodified');
                             $timemodified = $moodlesubmission->timemodified;
                             $textcontent = strip_tags($moodlesubmission->content);
                             $title = $moodlesubmission->title;
                             break;
                     }
                 } else {
                     switch ($cm->modname) {
                         case 'assign':
                             $moodlesubmission = $DB->get_record('assign_submission', array('assignment' => $cm->instance, 'userid' => $user->id, 'id' => $itemid), 'id, timemodified');
                             $timemodified = $moodlesubmission->timemodified;
                             $textcontent = strip_tags($textcontent);
                             break;
                         case 'workshop':
                             $moodlesubmission = $DB->get_record('workshop_submissions', array('workshopid' => $cm->instance, 'authorid' => $user->id), 'title, content, timemodified');
                             $timemodified = $moodlesubmission->timemodified;
                             $textcontent = strip_tags($textcontent);
                             break;
                     }
                 }
                 $title = !empty($title) ? $title : 'onlinetext_' . $user->id . "_" . $cm->id . "_" . $cm->instance . '.txt';
                 $filename = substr($title, -4) == '.txt' ? $title : $title . '.txt';
             }
             // Get submission method depending on whether there has been a previous submission.
             $submissionfields = 'id, cm, externalid, identifier, statuscode, lastmodified, attempt, errorcode';
             $typefield = $CFG->dbtype == "oci" ? " to_char(submissiontype) " : " submissiontype ";
             // Double check there is only one submission.
             $previoussubmissions = $DB->get_records_select('plagiarism_turnitin_files', " cm = ? AND userid = ? AND " . $typefield . " = ? AND identifier = ? ", array($cm->id, $user->id, $submissiontype, $identifier), 'id', $submissionfields);
             $previoussubmission = end($previoussubmissions);
             if ($previoussubmission) {
                 $errorcode = (int) $previoussubmission->errorcode;
                 // Don't submit if submission hasn't changed.
                 if ($previoussubmission->statuscode == "success" && ($submissiontype == 'file' && $timemodified <= $previoussubmission->lastmodified || $submissiontype != 'file')) {
                     return true;
                 } else {
                     if ($previoussubmission->statuscode == "error" && $timemodified <= $previoussubmission->lastmodified) {
                         $return["success"] = false;
                         $return["message"] = get_string('errorcode' . $errorcode, 'turnitintooltwo');
                         return $return;
                     } else {
                         if ($previoussubmission->attempt >= 5) {
                             // Do not submit if 5 attempts have been made previously.
                             if ($context == 'cron') {
                                 mtrace('-------------------------');
                                 mtrace(get_string('pastfiveattempts', 'turnitintooltwo') . ':');
                                 mtrace('User:  '******' - ' . $user->firstname . ' ' . $user->lastname . ' (' . $user->email . ')');
                                 mtrace('Course Module: ' . $cm->id . '');
                                 mtrace('-------------------------');
                                 return true;
                             }
                             $return["success"] = false;
                             $return["message"] = get_string('pastfiveattempts', 'turnitintooltwo');
                             return $return;
                         } else {
                             if ($settings["plagiarism_report_gen"] > 0) {
                                 // Replace if Turnitin assignment allows resubmissions or create if we have no Turnitin id stored.
                                 $submissionid = $previoussubmission->id;
                                 $apimethod = is_null($previoussubmission->externalid) ? "createSubmission" : "replaceSubmission";
                                 $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                             } else {
                                 $apimethod = "createSubmission";
                                 if ($previoussubmission->statuscode != "success") {
                                     $submissionid = $previoussubmission->id;
                                     $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                                 } else {
                                     $submissionid = $this->create_new_tii_submission($cm, $user, $identifier, $submissiontype);
                                 }
                             }
                         }
                     }
                 }
             } else {
                 // Check if there is previous submission of text content which we will replace
                 $typefield = $CFG->dbtype == "oci" ? " to_char(submissiontype) " : " submissiontype ";
                 if ($submissiontype == 'text_content' && ($previoussubmission = $DB->get_record_select('plagiarism_turnitin_files', " cm = ? AND userid = ? AND " . $typefield . " = ? ", array($cm->id, $user->id, 'text_content'), 'id, cm, externalid, identifier, statuscode, lastmodified', 0, 1))) {
                     $submissionid = $previoussubmission->id;
                     $apimethod = is_null($previoussubmission->externalid) || $settings["plagiarism_report_gen"] == 0 ? "createSubmission" : "replaceSubmission";
                     // Delete old text content submissions from Turnitin if not replacing.
                     if ($settings["plagiarism_report_gen"] == 0 && !is_null($previoussubmission->externalid)) {
                         $this->delete_tii_submission($previoussubmission->externalid);
                     }
                     $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                 } else {
                     $apimethod = "createSubmission";
                     $submissionid = $this->create_new_tii_submission($cm, $user, $identifier, $submissiontype);
                 }
             }
             // Remove any old text submissions here if there are any as there is only one per submission
             if ($itemid != 0 && $submissiontype == "text_content") {
                 $this->clean_old_turnitin_submissions($cm, $user->id, $itemid, $submissiontype, $identifier);
             }
             break;
         case 'forum_post':
             if ($previoussubmissions = $DB->get_records_select('plagiarism_turnitin_files', " cm = ? AND userid = ? AND identifier = ? ", array($cm->id, $user->id, $identifier), 'id DESC', 'id, cm, externalid, identifier, statuscode', 0, 1)) {
                 $previoussubmission = current($previoussubmissions);
                 if ($previoussubmission->statuscode == "success") {
                     return true;
                 } else {
                     $submissionid = $previoussubmission->id;
                     $apimethod = "replaceSubmission";
                     $this->reset_tii_submission($cm, $user, $identifier, $previoussubmission, $submissiontype);
                 }
             } else {
                 $apimethod = "createSubmission";
                 $submissionid = $this->create_new_tii_submission($cm, $user, $identifier, $submissiontype);
             }
             $forum_post = $DB->get_record_select('forum_posts', " userid = ? AND id = ? ", array($user->id, $itemid));
             $textcontent = strip_tags($forum_post->message);
             $filename = $title;
             break;
     }
     // Do not submit if this is text_content and we're not accepting anything and
     // content is less than 20 words or 100 characters.
     if ($submissiontype != 'file') {
         $content = explode(' ', $textcontent);
         if ($settings['plagiarism_allow_non_or_submissions'] != 1 && (strlen($textcontent) < 100 || count($content) < 20) || empty($textcontent)) {
             $plagiarismfile = new object();
             if ($submissionid != 0) {
                 $plagiarismfile->id = $submissionid;
             }
             $plagiarismfile->cm = $cm->id;
             $plagiarismfile->userid = $user->id;
             $plagiarismfile->identifier = $identifier;
             $plagiarismfile->statuscode = 'error';
             $plagiarismfile->errorcode = 1;
             $plagiarismfile->attempt = 1;
             $plagiarismfile->lastmodified = time();
             $plagiarismfile->submissiontype = $submissiontype;
             if ($submissionid != 0) {
                 if (!$DB->update_record('plagiarism_turnitin_files', $plagiarismfile)) {
                     turnitintooltwo_activitylog("Update record failed (CM: " . $cm->id . ", User: "******") - ", "PP_UPDATE_SUB_ERROR");
                 }
             } else {
                 if (!($fileid = $DB->insert_record('plagiarism_turnitin_files', $plagiarismfile))) {
                     turnitintooltwo_activitylog("Insert record failed (CM: " . $cm->id . ", User: "******") - ", "PP_INSERT_SUB_ERROR");
                 }
             }
             if ($context == 'cron') {
                 mtrace('-------------------------');
                 mtrace(get_string('errorcode1', 'turnitintooltwo') . ':');
                 mtrace('User:  '******' - ' . $user->firstname . ' ' . $user->lastname . ' (' . $user->email . ')');
                 mtrace('Course Module: ' . $cm->id . '');
                 mtrace('-------------------------');
                 return true;
             }
             $return["success"] = false;
             $return["message"] = get_string('errorcode1', 'turnitintooltwo');
             return $return;
         }
     }
     // Check file is less than maximum allowed size.
     if ($submissiontype == 'file') {
         if ($file->get_filesize() > TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE) {
             $plagiarismfile = new object();
             if ($submissionid != 0) {
                 $plagiarismfile->id = $submissionid;
             }
             $plagiarismfile->cm = $cm->id;
             $plagiarismfile->userid = $user->id;
             $plagiarismfile->identifier = $identifier;
             $plagiarismfile->statuscode = 'error';
             $plagiarismfile->errorcode = 2;
             $plagiarismfile->attempt = 1;
             $plagiarismfile->lastmodified = time();
             $plagiarismfile->submissiontype = 'file';
             if ($submissionid != 0) {
                 if (!$DB->update_record('plagiarism_turnitin_files', $plagiarismfile)) {
                     turnitintooltwo_activitylog("Update record failed (CM: " . $cm->id . ", User: "******") - ", "PP_UPDATE_SUB_ERROR");
                 }
             } else {
                 if (!($fileid = $DB->insert_record('plagiarism_turnitin_files', $plagiarismfile))) {
                     turnitintooltwo_activitylog("Insert record failed (CM: " . $cm->id . ", User: "******") - ", "PP_INSERT_SUB_ERROR");
                 }
             }
             if ($context == 'cron') {
                 mtrace('-------------------------');
                 mtrace(get_string('errorcode2', 'turnitintooltwo') . ':');
                 mtrace('User:  '******' - ' . $user->firstname . ' ' . $user->lastname . ' (' . $user->email . ')');
                 mtrace('Course Module: ' . $cm->id . '');
                 mtrace('-------------------------');
                 return true;
             }
             $return["success"] = false;
             $return["message"] = get_string('errorcode2', 'turnitintooltwo', display_size(TURNITINTOOLTWO_MAX_FILE_UPLOAD_SIZE));
             return $return;
         }
     }
     // Read the stored file/content into a temp file for submitting.
     $submission_title = explode('.', $title);
     $file_string = array($submission_title[0], $cm->id);
     $modulepluginsettings = $this->get_settings($cm->id);
     if (!$modulepluginsettings["plagiarism_anonymity"]) {
         $user_details = array($user->id, $user->firstname, $user->lastname);
         $file_string = array_merge($user_details, $file_string);
     }
     $tempfile = turnitintooltwo_tempfile($file_string, $filename);
     $fh = fopen($tempfile, "w");
     fwrite($fh, $textcontent);
     fclose($fh);
     // Create submission object.
     $submission = new TiiSubmission();
     $submission->setAssignmentId($tiiassignmentid);
     if ($apimethod == "replaceSubmission") {
         $submission->setSubmissionId($previoussubmission->externalid);
     }
     $submission->setTitle($title);
     $submission->setAuthorUserId($user->tii_user_id);
     if ($user->id == $USER->id && !is_siteadmin()) {
         $submission->setSubmitterUserId($user->tii_user_id);
         $submission->setRole('Learner');
     } else {
         $instructor = new turnitintooltwo_user($USER->id, 'Instructor');
         $instructor->edit_tii_user();
         $submission->setSubmitterUserId($instructor->tii_user_id);
         $submission->setRole('Instructor');
     }
     $submission->setSubmissionDataPath($tempfile);
     // Initialise Comms Object.
     $turnitincomms = new turnitintooltwo_comms();
     $turnitincall = $turnitincomms->initialise_api();
     try {
         $response = $turnitincall->{$apimethod}($submission);
         $newsubmission = $response->getSubmission();
         $newsubmissionid = $newsubmission->getSubmissionId();
         $plagiarismfile = new object();
         if ($apimethod == "replaceSubmission" || $submissionid != 0) {
             $plagiarismfile->id = $submissionid;
         }
         $plagiarismfile->cm = $cm->id;
         $plagiarismfile->userid = $user->id;
         $plagiarismfile->identifier = $identifier;
         $plagiarismfile->externalid = $newsubmissionid;
         $plagiarismfile->statuscode = 'success';
         $plagiarismfile->similarityscore = null;
         $plagiarismfile->attempt = 1;
         $plagiarismfile->transmatch = 0;
         $plagiarismfile->lastmodified = time();
         $plagiarismfile->submissiontype = $submissiontype;
         $plagiarismfile->errorcode = null;
         $plagiarismfile->errormsg = null;
         if ($apimethod == "replaceSubmission" || $submissionid != 0) {
             if (!$DB->update_record('plagiarism_turnitin_files', $plagiarismfile)) {
                 turnitintooltwo_activitylog("Update record failed (CM: " . $cm->id . ", User: "******")", "PP_UPDATE_SUB");
             }
         } else {
             if (!($fileid = $DB->insert_record('plagiarism_turnitin_files', $plagiarismfile))) {
                 turnitintooltwo_activitylog("Insert record failed (CM: " . $cm->id . ", User: "******")", "PP_INSERT_SUB");
             }
         }
         // Delete the tempfile.
         if (!is_null($tempfile)) {
             unlink($tempfile);
         }
         // Add config field to show submissions have been made which we use to lock anonymous marking setting
         $configfield = new object();
         $configfield->cm = $cm->id;
         $configfield->name = 'submitted';
         $configfield->value = 1;
         if (!($currentconfigfield = $DB->get_field('plagiarism_turnitin_config', 'id', array('cm' => $cm->id, 'name' => 'submitted')))) {
             if (!$DB->insert_record('plagiarism_turnitin_config', $configfield)) {
                 turnitintooltwo_print_error('defaultupdateerror', 'turnitintooltwo', null, null, __FILE__, __LINE__);
             }
         }
         $return["success"] = true;
         $return["message"] = get_string('submissionuploadsuccess', 'turnitintooltwo') . '<br/>' . get_string('turnitinsubmissionid', 'turnitintooltwo') . ': ' . $newsubmissionid;
         //Send a message to the user's Moodle inbox with the digital receipt.
         if (!empty($CFG->smtphosts) && !empty($CFG->smtpuser) && !empty($CFG->smtppass)) {
             $receipt = new receipt_message();
             $moduledata = $DB->get_record($cm->modname, array('id' => $cm->instance));
             $coursedata = turnitintooltwo_assignment::get_course_data($cm->course, 'PP', 'cron');
             $input = array('firstname' => $user->firstname, 'lastname' => $user->lastname, 'submission_title' => $title, 'assignment_name' => $moduledata->name, 'course_fullname' => $coursedata->turnitin_ctl, 'submission_date' => date('d-M-Y h:iA'), 'submission_id' => $newsubmissionid);
             $message = $receipt->build_message($input);
             $receipt->send_message($user->id, $message);
         }
         if ($context == 'cron') {
             return true;
         }
     } catch (Exception $e) {
         $errorstring = empty($previoussubmission->externalid) ? "pp_createsubmissionerror" : "pp_updatesubmissionerror";
         $return["success"] = false;
         $return["message"] = get_string('pp_submission_error', 'turnitintooltwo') . ' ' . $e->getMessage();
         $plagiarismfile = new object();
         if ($submissionid != 0) {
             $plagiarismfile->id = $submissionid;
             // Get attempt no
             $current_record = $DB->get_record('plagiarism_turnitin_files', array("id" => $submissionid));
             $plagiarismfile->attempt = $current_record->attempt + 1;
         } else {
             $plagiarismfile->attempt = 1;
         }
         $plagiarismfile->cm = $cm->id;
         $plagiarismfile->userid = $user->id;
         $plagiarismfile->identifier = $identifier;
         $plagiarismfile->statuscode = 'error';
         $plagiarismfile->lastmodified = time();
         $plagiarismfile->submissiontype = $submissiontype;
         $plagiarismfile->errorcode = 0;
         $plagiarismfile->errormsg = $return["message"];
         if ($submissionid != 0) {
             if (!$DB->update_record('plagiarism_turnitin_files', $plagiarismfile)) {
                 turnitintooltwo_activitylog("Update record failed (CM: " . $cm->id . ", User: "******") - ", "PP_UPDATE_SUB_ERROR");
             }
         } else {
             if (!($fileid = $DB->insert_record('plagiarism_turnitin_files', $plagiarismfile))) {
                 turnitintooltwo_activitylog("Insert record failed (CM: " . $cm->id . ", User: "******") - ", "PP_INSERT_SUB_ERROR");
             }
         }
         $turnitincomms->handle_exceptions($e, $errorstring, false);
         if ($context == 'cron') {
             mtrace('-------------------------');
             mtrace(get_string('pp_submission_error', 'turnitintooltwo') . ': ' . $e->getMessage());
             mtrace('User:  '******' - ' . $user->firstname . ' ' . $user->lastname . ' (' . $user->email . ')');
             mtrace('Course Module: ' . $cm->id . '');
             mtrace('-------------------------');
             return false;
         }
     }
     return $return;
 }