Преглед изворни кода

Code Quality:
Update all indentation from 4 spaces to 2 spaces
Remove deprecated functions from locallib.php
- Most functions were reimplemented libs files at the lib folder

IMPORTANT:
- Files are now recorded with itemid as feedbackid to avoid recording as duplicate
- Functions that manipulate files already updated
- gradeimporter, feedback and type names now allows for 256 characters on database
- Plugin has to be reinstalled to apply db changes
- Forms name field expects that limitation
- On instance deletion, now correctly deletes all files and all submission types

Bernardo пре 2 година
родитељ
комит
ed948877b6

+ 52 - 52
classes/event/gradeimporter_submission_created.php

@@ -17,62 +17,62 @@
 namespace mod_gradeimporter\event;
 
 class gradeimporter_submission_created extends \core\event\base {
-    protected function init() {
-        $this->data['crud'] = 'c';
-        $this->data['edulevel'] = self::LEVEL_PARTICIPATING;
-    }
+  protected function init() {
+    $this->data['crud'] = 'c';
+    $this->data['edulevel'] = self::LEVEL_PARTICIPATING;
+  }
 
-    /**
-     * Returns the description of what happened
-     *
-     * @return string
-     */
-    public function get_description () {
-        return "The user with id '$this->userid' has created a submission " .
-                "on the grade importer with the course module id '$this->contextinstanceid'.";
-    }
+  /**
+   * Returns the description of what happened
+   *
+   * @return string
+   */
+  public function get_description () {
+    return "The user with id '$this->userid' has created a submission " .
+        "on the grade importer with the course module id '$this->contextinstanceid'.";
+  }
 
-    /**
-     * Returns localised event name
-     *
-     * @return string
-     */
-    public static function get_name () {
-        return get_string('eventmodelsubmissioncreated', 'mod_gradeimporter');
-    }
+  /**
+   * Returns localised event name
+   *
+   * @return string
+   */
+  public static function get_name () {
+    return get_string('eventmodelsubmissioncreated', 'mod_gradeimporter');
+  }
 
-    /**
-     * Get URL related to the action
-     *
-     * @return \moodle_url
-     */
-    public function get_url () {
-        $url = new \moodle_url('/mod/gradeimporter/view.php', array('id' => $this->contextinstanceid));
-        return $url;
-    }
+  /**
+   * Get URL related to the action
+   *
+   * @return \moodle_url
+   */
+  public function get_url () {
+    $url = new \moodle_url('/mod/gradeimporter/view.php', array('id' => $this->contextinstanceid));
+    return $url;
+  }
 
-    /**
-     * Return the legacy event log data.
-     *
-     * @return array|null
-     */
-    protected function get_legacy_logdata () {
-        // The legacy log table expects a relative path to /mod/model/ !!
-        $logurl = new \moodle_url('/mod/gradeimporter/view.php', array('id' => $this->contextinstanceid));
-        return array($this->courseid, 'gradeimporter', 'editgradeimporter', $logurl,
-                        $this->other['gradeimporterid'], $this->gradeimporterid);
-    }
+  /**
+   * Return the legacy event log data.
+   *
+   * @return array|null
+   */
+  protected function get_legacy_logdata () {
+    // The legacy log table expects a relative path to /mod/model/ !!
+    $logurl = new \moodle_url('/mod/gradeimporter/view.php', array('id' => $this->contextinstanceid));
+    return array($this->courseid, 'gradeimporter', 'editgradeimporter', $logurl,
+            $this->other['gradeimporterid'], $this->gradeimporterid);
+  }
 
-    /**
-     * Custom validation
-     *
-     * @throws \coding_exception
-     * @return void
-     */
-    protected function validate_data () {
-        parent::validate_data();
-        if ($this->contextlevel != CONTEXT_MODULE) {
-            throw new \coding_exception('Context level must be CONTEXT_MODULE');
-        }
+  /**
+   * Custom validation
+   *
+   * @throws \coding_exception
+   * @return void
+   */
+  protected function validate_data () {
+    parent::validate_data();
+    if ($this->contextlevel != CONTEXT_MODULE) {
+      throw new \coding_exception('Context level must be CONTEXT_MODULE');
     }
+  }
 }

+ 11 - 11
db/install.xml

@@ -7,14 +7,14 @@
     <TABLE NAME="gradeimporter" COMMENT="gradeimporter instance table, this table links the submissions to the course." NEXT="grade_importer_submission">
       <FIELDS>
         <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" ENUM="false" COMMENT="primary key" NEXT="course"/>
-        <FIELD NAME="course" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="The id of the course this instance is placed on" 
+        <FIELD NAME="course" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="The id of the course this instance is placed on"
                   PREVIOUS="id" NEXT="name"/>
-        <FIELD NAME="name" TYPE="char" LENGTH="50" NOTNULL="true" SEQUENCE="false" ENUM="false" COMMENT="Instance name" PREVIOUS="course" NEXT="intro"/>
-        <FIELD NAME="intro" TYPE="text" NOTNULL="false" SEQUENCE="false" COMMENT="Description of the grades that are going to be available on the module" 
+        <FIELD NAME="name" TYPE="char" LENGTH="256" NOTNULL="true" SEQUENCE="false" ENUM="false" COMMENT="Instance name" PREVIOUS="course" NEXT="intro"/>
+        <FIELD NAME="intro" TYPE="text" NOTNULL="false" SEQUENCE="false" COMMENT="Description of the grades that are going to be available on the module"
               PREVIOUS="NAME" NEXT="timecreated"/>
-        <FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="Time stamp from when the instance was first created" 
+        <FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="Time stamp from when the instance was first created"
               PREVIOUS="intro" NEXT="timemodified"/>
-        <FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="Last time the instance was modified" 
+        <FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="Last time the instance was modified"
                 PREVIOUS="timecreated" NEXT="usermodified"/>
         <FIELD NAME="usermodified" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="timemodified"/>
       </FIELDS>
@@ -26,7 +26,7 @@
     <TABLE NAME="gradeimporter_submission" COMMENT="submission table, relates the submission to the gradeimporter, feedback files and student." PREVIOUS="gradeimporter" NEXT="gradeimporter_submissiontype" >
       <FIELDS>
         <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true" NEXT="gradeimporter"/>
-        <FIELD NAME="gradeimporterid" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" 
+        <FIELD NAME="gradeimporterid" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"
               COMMENT="Which gradeimporter instance this submission is related to" PREVIOUS="id" NEXT="type"/>
         <FIELD NAME="type" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="Type of the submission (exam, exercise list,"
                 PREVIOUS="gradeimporter" NEXT="gradebook"/>
@@ -38,7 +38,7 @@
                 PREVIOUS="timecreated" NEXT="usermodified"/>
         <FIELD NAME="usermodified" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"
                 PREVIOUS="timemodified" NEXT="name"/>
-        <FIELD NAME="name" TYPE="char" LENGTH="20" NOTNULL="true" SEQUENCE="false" COMMENT="submission name"
+        <FIELD NAME="name" TYPE="char" LENGTH="256" NOTNULL="true" SEQUENCE="false" COMMENT="submission name"
                 PREVIOUS="usermodified" NEXT="info"/>
         <FIELD NAME="description" TYPE="text" NOTNULL="false" SEQUENCE="false" COMMENT="Description of the submission type ex: exam 1 given on day YYYY/MM/DD"
               PREVIOUS="name" NEXT="descriptionformat"/>
@@ -61,10 +61,10 @@
       <FIELDS>
         <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true" NEXT="gradeimporterid"/>
         <FIELD NAME="gradeimporterid" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="Which gradeimporter instance this submission is related to" PREVIOUS="id" NEXT="name"/>
-        <FIELD NAME="name" TYPE="char" LENGTH="20" NOTNULL="true" SEQUENCE="false" COMMENT="Type name (exam, exercises list, etc)." 
+        <FIELD NAME="name" TYPE="char" LENGTH="20" NOTNULL="true" SEQUENCE="false" COMMENT="Type name (exam, exercises list, etc)."
                     PREVIOUS="gradeimporterid" NEXT="info"/>
-        
-        <FIELD NAME="description" TYPE="text" NOTNULL="false" SEQUENCE="false" COMMENT="Submission type description. eg for exam type: exams given in class." 
+
+        <FIELD NAME="description" TYPE="text" NOTNULL="false" SEQUENCE="false" COMMENT="Submission type description. eg for exam type: exams given in class."
                     PREVIOUS="name" NEXT="descriptionformat"/>
         <FIELD NAME="descriptionformat" TYPE="char" LENGTH="10" NOTNULL="false" DEFAULT="plaintext" SEQUENCE="false" COMMENT="Type description format (html, plaintext, etc.)"/>
       </FIELDS>
@@ -96,7 +96,7 @@
                     PREVIOUS="timecreated" NEXT="contextid"/>
         <FIELD NAME="contextid" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false"
                     PREVIOUS="timemodified" NEXT="filename"/>
-        <FIELD NAME="name" TYPE="char" LENGTH="30" NOTNULL="true" SEQUENCE="false" COMMENT="File name to fetch at pluginfile." 
+        <FIELD NAME="name" TYPE="char" LENGTH="30" NOTNULL="true" SEQUENCE="false" COMMENT="File name to fetch at pluginfile."
                     PREVIOUS="contextid"/>
       </FIELDS>
       <KEYS>

+ 51 - 55
forms/submission/submission.php

@@ -18,16 +18,13 @@ require_once('../../../../config.php');
 require_once('../../locallib.php');
 require_once('../../lib.php');
 
-// Test libs
-// require_once('../../libs/testlib.php'); // Remove when going to production
-
 require_once('submission_form.php'); // Requires Form class File
 require_once('submission_form_functions.php'); // Require functions file for submission form
 
-$cmid = required_param('cmid', PARAM_INT);            // Course Module ID.
-$id = optional_param('id', 0, PARAM_INT);           // Gradeimporter id.
-$subid = optional_param('subid', -1, PARAM_INT);       // Submission id.
-// $update = optional_param('update', 0, PARAM_INT);      // If 1 the submission is beign updated.
+$cmid = required_param('cmid', PARAM_INT);      // Course Module ID.
+$id = optional_param('id', 0, PARAM_INT);       // Gradeimporter id.
+$subid = optional_param('subid', -1, PARAM_INT);     // Submission id.
+// $update = optional_param('update', 0, PARAM_INT);    // If 1 the submission is beign updated.
 
 // Checks if everything is correct
 // If any of the queries fail, throw error because of MUST_EXIST clause
@@ -42,7 +39,7 @@ $context = context_module::instance($cm->id);
 // Sets URL
 $url = new moodle_url('/mod/gradeimporter/forms/submission/submission.php', array('cmid' => $cm->id));
 if (!empty($id)) {
-    $url->param('id', $id);
+  $url->param('id', $id);
 }
 $PAGE->set_url($url);
 
@@ -53,9 +50,9 @@ require_capability('mod/gradeimporter:edit', $context);
 // Prepare data for submission form
 
 if (!isset($entry)) {
-    // If its creating new submission
-    $entry = new stdClass();
-    $entry->id = null;
+  // If its creating new submission
+  $entry = new stdClass();
+  $entry->id = null;
 }
 
 // Set parameters to sendo to the form
@@ -64,61 +61,60 @@ $maxbytes = $course->maxbytes;
 
 // Prepare file manager
 $filemanageroptions = array('subdirs' => 0,
-                                    'maxbytes' => $maxbytes,
-                                    'areamaxbytes' => 10485760,
-                                    'maxfiles' => 1,
-                                    'accepted_types' => array('.csv', '.zip')
-                                );
+                  'maxbytes' => $maxbytes,
+                  'areamaxbytes' => 10485760,
+                  'maxfiles' => 1,
+                  'accepted_types' => array('.csv', '.zip')
+                );
 
 $entry = file_prepare_standard_filemanager($entry, 'submissionfiles', $filemanageroptions, $context,
-                                                'mod_gradeimporter', 'submissionfiles', $entry->id);
+                        'mod_gradeimporter', 'submissionfiles', $entry->id);
 
 // Create new mform to show to the user
 $mform = new mod_gradeimporter_submission_form(null, array('submission' => $entry,
-                                                            'filemanageroptions' => $filemanageroptions,
-                                                            'gradeimporterid' => $gradeimporter->id,
-                                                            'cmid' => $cm->id
-                                                        )
-                                                );
+                              'filemanageroptions' => $filemanageroptions,
+                              'gradeimporterid' => $gradeimporter->id,
+                              'cmid' => $cm->id
+                            )
+                        );
 
 if ($mform->is_cancelled()) {
-    // Handle form cancel operation, if cancel button is present on form
-    redirect("view.php?id=$cm->id&edit=1");
+  // Handle form cancel operation, if cancel button is present on form
+  redirect("view.php?id=$cm->id&edit=1");
 } else if ($formdata = $mform->get_data()) {
 
-    // reset_submissions($context->id); // Remove when going to production
+  validate_formdata($formdata);
+  // If validate didnt throw error then everything is fine
+  $entry = create_submission($formdata, $gradeimporter->id, $USER->id);
 
-    $entry = create_submission($formdata, $gradeimporter->id, $USER->id);
+  // Gets file manager content
+  $entry = file_postupdate_standard_filemanager($entry, 'submissionfiles',
+                      $filemanageroptions, $context, 'mod_gradeimporter',
+                      'submissionfiles', $entry->id);
 
-    // Gets file manager content
-    $entry = file_postupdate_standard_filemanager($entry, 'submissionfiles',
-                                            $filemanageroptions, $context, 'mod_gradeimporter',
-                                            'submissionfiles', $entry->id);
+  store_files($context, $cm, $entry);
+  // When complete redirect to view.php
+  redirect("view.php?id=$cm->id&edit=1");
 
-    store_files($context, $cm, $entry);
-    // When complete redirect to view.php
-    // uncomment later
-    redirect("view.php?id=$cm->id&edit=1");
-    // In this case you process validated data. $mform->get_data() returns data posted in form.
 } else {
-    // This branch is executed if the form is submitted but the data doesn't validate and the form should be redisplayed
-    // ...or on the first display of the form.
-    if ($subid != -1) {
-        // If its updating an existing submission
-        // Get data from db and insert into form
-        $subdata = $DB->get_record('gradeimporter_submission', array('id' => $subid));
-        $subdata->description = array('text' => $subdata->description,
-                                        'format' => $subdata->descriptionformat
-                                    );
-        $mform->set_data($subdata);
-    }
-
-    $PAGE->set_title($gradeimporter->name);
-    $PAGE->set_heading($course->fullname);
-    echo $OUTPUT->header();
-    echo $OUTPUT->heading(format_string($gradeimporter->name), 2);
-
-    $mform->display();
-
-    echo $OUTPUT->footer();
+  // This branch is executed if the form is submitted but the data doesn't validate and the form should be redisplayed
+  // ...or on the first display of the form.
+  if ($subid != -1) {
+    // If its updating an existing submission
+    // Get data from db and insert into form
+    $subdata = $DB->get_record('gradeimporter_submission', array('id' => $subid));
+    $subdata->description = array('text' => $subdata->description,
+                    'format' => $subdata->descriptionformat
+                  );
+    $mform->set_data($subdata);
+  }
+
+  $PAGE->set_title($gradeimporter->name);
+  $PAGE->set_heading($course->fullname);
+  echo $OUTPUT->header();
+  echo $OUTPUT->heading(format_string($gradeimporter->name), 2);
+
+  $mform->display();
+
+  echo $OUTPUT->footer();
 }

+ 73 - 74
forms/submission/submission_form.php

@@ -22,80 +22,79 @@ require_once("submission_form_functions.php");
 
 class mod_gradeimporter_submission_form extends moodleform {
 
-    public function definition() {
-        global $CFG, $DB;
-
-        $mform = $this->_form;
-
-        // Custom data
-        $submission = $this->_customdata['submission']; // Load fields data
-        $filemanageroptions = $this->_customdata['filemanageroptions'];
-        $gradeimporterid = $this->_customdata['gradeimporterid'];
-        $cmid = $this->_customdata['cmid'];
-        // ----------------------------------------------------------------
-        // General information
-
-        // Header
-        $mform->addElement('header',  'newsub',  get_string('newsubmission', 'gradeimporter'));
-
-        // Submission name field
-        $mform->addElement('text', 'name', get_string('submissionname', 'gradeimporter'));
-        $mform->setType('name', PARAM_TEXT);
-        $mform->addRule('name', null, 'required', null, 'client');
-
-        $mform->addElement('editor', 'description', get_string('description'));
-        $mform->setType('description', PARAM_TEXT);
-
-        $mform->addElement('filemanager', 'submissionfiles_filemanager', get_string('submissionfiles', 'gradeimporter'),
-                            null, $filemanageroptions);
-        $mform->addHelpButton('submissionfiles_filemanager', 'submissionfiles', 'gradeimporter');
-
-        // Add button to open new subtypeform
-        $subtypeformurl = new moodle_url("/mod/gradeimporter/forms/submissiontype/submissiontype.php",
-                                            array('cmid' => $cmid, 'id' => $gradeimporterid)
-                                        );
-        $newsubtypebutton = "<div class=\"col-md-9 form-inline align-items-start felement\">
-                                <button class=\"btn btn-primary\" onclick=\"window.open('$subtypeformurl','_self')\">
-                                    New type
-                                </button>
-                            </div>";
-        $mform->addElement('html', $newsubtypebutton);
-
-        // To edit
-        $subtypes = get_types_array($gradeimporterid);
-        var_dump ($subtypes);
-        if ($subtypes) {
-            $selectvalues = array();
-            foreach ($subtypes as $id => $type) {
-                $selectvalues[$id] = $type->name;
-            }
-        } else {
-            $selectvalues = array('create new type first');
-        }
-        $mform->addElement('select', 'type', get_string('submissiontype', 'gradeimporter'), $selectvalues);
-
-        $mform->addElement('selectyesno', 'visibility',  get_string('visibility', 'gradeimporter'));
-        $mform->setDefault('visibility', array('value' => 1));
-        $mform->addHelpButton('visibility', 'visibility', 'gradeimporter');
-
-        $mform->addElement('selectyesno', 'gradebook',  get_string('gradebook', 'gradeimporter'));
-        $mform->setDefault('gradebook', array('value' => 0));
-        $mform->addHelpButton('gradebook', 'gradebook', 'gradeimporter');
-
-        // -----------------------------
-        // Hidden fields
-        $mform->addElement('hidden', 'id');
-        $mform->setType('id', PARAM_INT);
-        $mform->addElement('hidden', 'cmid');
-        $mform->setType('cmid', PARAM_INT);
-
-        // ------------------------------
-        // Save and cancel buttons
-        $this->add_action_buttons();
-
-        // ------------------------------
-        // Sets preloaded data to fields
-        $this->set_data($submission);
+  public function definition() {
+    global $CFG, $DB;
+
+    $mform = $this->_form;
+
+    // Custom data
+    $submission = $this->_customdata['submission']; // Load fields data
+    $filemanageroptions = $this->_customdata['filemanageroptions'];
+    $gradeimporterid = $this->_customdata['gradeimporterid'];
+    $cmid = $this->_customdata['cmid'];
+    // ----------------------------------------------------------------
+    // General information
+
+    // Header
+    $mform->addElement('header',  'newsub',  get_string('newsubmission', 'gradeimporter'));
+
+    // Submission name field
+    $mform->addElement('text', 'name', get_string('submissionname', 'gradeimporter'), array('maxlength' => '256'));
+    $mform->setType('name', PARAM_TEXT);
+    $mform->addRule('name', null, 'required', null, 'client');
+
+    $mform->addElement('editor', 'description', get_string('description'));
+    $mform->setType('description', PARAM_TEXT);
+
+    $mform->addElement('filemanager', 'submissionfiles_filemanager', get_string('submissionfiles', 'gradeimporter'),
+              null, $filemanageroptions);
+    $mform->addHelpButton('submissionfiles_filemanager', 'submissionfiles', 'gradeimporter');
+
+    // Add button to open new subtypeform
+    $subtypeformurl = new moodle_url("/mod/gradeimporter/forms/submissiontype/submissiontype.php",
+                      array('cmid' => $cmid, 'id' => $gradeimporterid)
+                    );
+    $newsubtypebutton = "<div class=\"col-md-9 form-inline align-items-start felement\">
+                <button class=\"btn btn-primary\" onclick=\"window.open('$subtypeformurl','_self')\">
+                  New type
+                </button>
+              </div>";
+    $mform->addElement('html', $newsubtypebutton);
+
+    // To edit
+    $subtypes = get_types_array($gradeimporterid);
+    if ($subtypes) {
+      $selectvalues = array();
+      foreach ($subtypes as $id => $type) {
+        $selectvalues[$id] = $type->name;
+      }
+    } else {
+      $selectvalues = array(-1 => 'create new type first');
     }
+    $mform->addElement('select', 'type', get_string('submissiontype', 'gradeimporter'), $selectvalues);
+
+    $mform->addElement('selectyesno', 'visibility',  get_string('visibility', 'gradeimporter'));
+    $mform->setDefault('visibility', array('value' => 1));
+    $mform->addHelpButton('visibility', 'visibility', 'gradeimporter');
+
+    $mform->addElement('selectyesno', 'gradebook',  get_string('gradebook', 'gradeimporter'));
+    $mform->setDefault('gradebook', array('value' => 0));
+    $mform->addHelpButton('gradebook', 'gradebook', 'gradeimporter');
+
+    // -----------------------------
+    // Hidden fields
+    $mform->addElement('hidden', 'id');
+    $mform->setType('id', PARAM_INT);
+    $mform->addElement('hidden', 'cmid');
+    $mform->setType('cmid', PARAM_INT);
+
+    // ------------------------------
+    // Save and cancel buttons
+    $this->add_action_buttons();
+
+    // ------------------------------
+    // Sets preloaded data to fields
+    $this->set_data($submission);
+  }
 
 }

+ 156 - 149
forms/submission/submission_form_functions.php

@@ -15,183 +15,190 @@
 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
 
 function create_submission ($data, $gradeimporterid, $userid) {
-    global $DB;
-    $timenow = time();
-    if (empty($data->id)) {
-        // If is new db entry;
-        $data->gradeimporterid = $gradeimporterid;
-        $data->usermodified = $userid;
-        $data->timecreated = $timenow;
-
-        $isnewentry = true;
-    } else {
-        $isnewentry = false;
-    }
-
-    $data->descriptionformat = $data->description["format"];
-    $data->description = $data->description["text"];
-    $data->timemodified = $timenow;
-    $data->position = -1; // Do later
-
-    if ($isnewentry) {
-        // If is new entry insert data into DB and gets id
-        $data->id = $DB->insert_record('gradeimporter_submission', $data);
-    }
-
-    // If not new entry updates information
-    // If new entry inserts id into DB
-    $DB->update_record('gradeimporter_submission', $data);
-
-    return $data;
+  global $DB;
+  $timenow = time();
+  if (empty($data->id)) {
+    // If is new db entry;
+    $data->gradeimporterid = $gradeimporterid;
+    $data->usermodified = $userid;
+    $data->timecreated = $timenow;
+
+    $isnewentry = true;
+  } else {
+    $isnewentry = false;
+  }
+
+  $data->descriptionformat = $data->description["format"];
+  $data->description = $data->description["text"];
+  $data->timemodified = $timenow;
+  $data->position = -1; // Do later
+
+  if ($isnewentry) {
+    // If is new entry insert data into DB and gets id
+    $data->id = $DB->insert_record('gradeimporter_submission', $data);
+  }
+
+  // If not new entry updates information
+  // If new entry inserts id into DB
+  $DB->update_record('gradeimporter_submission', $data);
+
+  return $data;
 }
 
 
 
 function store_files ($context, $cm, $data) {
-    global $CFG;
-    $fs = get_file_storage();
-    $files = $fs->get_area_files($context->id, 'mod_gradeimporter',
-                                'submissionfiles', $data->id
-                            );
-    foreach ($files as $file) {
+  global $CFG;
+  $fs = get_file_storage();
+  $files = $fs->get_area_files($context->id, 'mod_gradeimporter',
+                'submissionfiles', $data->id
+              );
+  foreach ($files as $file) {
+    if ($file->get_mimetype() == 'text/csv') {
+      read_csv($file->get_content(), $context, $data);
+      return;
+    }
+    if ($file->get_mimetype() == 'application/zip') {
+      // If it is a .zip file, extract files from the zip
+      $zipfiles = read_zip($file, $context, $fs);
+      // Search a .csv file
+      foreach ($zipfiles as $file) {
+
         if ($file->get_mimetype() == 'text/csv') {
-            read_csv($file->get_content(), $context, $data);
-            return;
-        }
-        if ($file->get_mimetype() == 'application/zip') {
-            // If it is a .zip file, extract files from the zip
-            $zipfiles = read_zip($file, $context, $fs);
-            // Search a .csv file
-            foreach ($zipfiles as $file) {
-
-                if ($file->get_mimetype() == 'text/csv') {
-                    // If csv is found, pass it to read_csv()
-                    read_csv($file->get_content(), $context, $data, $zipfiles);
-                    // Only expects one csv so doesn't look for another
-                }
-            }
-            // Finished processing files from zip, so delete temp copies
-            $fs->delete_area_files($context->id, 'mod_gradeimporter', 'unpacktemp', 0);
+          // If csv is found, pass it to read_csv()
+          read_csv($file->get_content(), $context, $data, $zipfiles);
+          // Only expects one csv so doesn't look for another
         }
+      }
+      // Finished processing files from zip, so delete temp copies
+      $fs->delete_area_files($context->id, 'mod_gradeimporter', 'unpacktemp', 0);
     }
+  }
 }
 
 function read_csv ($content, $context, $data, $zipfiles = null) {
 
-    $csv = prepare_csv($content);
-    foreach ($csv as $feedback) {
-        $feedbackid = store_feedback($feedback, $context->id, $data->id);
-        if ($feedback['file'] != "") {
-            // If feedback has associated file, insert it into pluginfile
-            foreach ($zipfiles as $file) {
-                // Search in zipfiles to find same name then feedback['file']
-                if ($feedback['file'] == $file->get_filename()) {
-                    $feedbackfileinfo = store_feedback_file($feedback, $context, $data, $file, $feedbackid);
-                    break;
-                }
-            }
-            // Already used all files, so delete extra copies
-
+  $csv = prepare_csv($content);
+  foreach ($csv as $feedback) {
+    $feedbackid = store_feedback($feedback, $context->id, $data->id);
+    if ($feedback['file'] != "") {
+      // If feedback has associated file, insert it into pluginfile
+      foreach ($zipfiles as $file) {
+        // Search in zipfiles to find same name then feedback['file']
+        if ($feedback['file'] == $file->get_filename()) {
+          $feedbackfileinfo = store_feedback_file($feedback, $context, $data, $file, $feedbackid);
+          break;
         }
+      }
+      // Already used all files, so delete extra copies
 
     }
+
+  }
 }
 
 function prepare_csv ($content) {
-    $csvlines = explode(PHP_EOL, $content);
-    $csv = array();
-    foreach ($csvlines as $line) {
-        $csv[] = str_getcsv($line);
-    }
-    $header = array_shift($csv);
-
-    $outputcsv = array();
-    $outputcsv = array_map(
-                            function($v)use($header){
-                                return array_combine($header, $v);
-                            },
-                            $csv
-                        );
-
-    return $outputcsv;
+  $csvlines = explode(PHP_EOL, $content);
+  $csv = array();
+  foreach ($csvlines as $line) {
+    $csv[] = str_getcsv($line);
+  }
+  $header = array_shift($csv);
+
+  $outputcsv = array();
+  $outputcsv = array_map(
+              function($v)use($header){
+                return array_combine($header, $v);
+              },
+              $csv
+            );
+
+  return $outputcsv;
 }
 
 function store_feedback ($feedback, $contextid, $submissionid) {
-    global $DB;
-    // Prepare data to submit to gradeimporter_feedback table
-    $entry = new stdClass();
-    $entry->id = null;
-
-    $entry->timecreated = time();
-    $entry->timemodified = time();
-
-    $entry->submissionid = $submissionid;
-    $entry->studentid = $feedback['id'];
-    $entry->grade = $feedback['grade'];
-    $entry->comment = $feedback['comment'];
-    $entry->name = $feedback['file'];
-    $entry->fileid = 0;
-    $entry->usermodified = 1;
-    $entry->contextid = $contextid;
-
-    // Insert data into gradeimporter_feedback table and gets ID
-    $entry->id = $DB->insert_record('gradeimporter_feedback', $entry);
-
+  global $DB;
+  // Prepare data to submit to gradeimporter_feedback table
+  $entry = new stdClass();
+  $entry->id = null;
+
+  $entry->timecreated = time();
+  $entry->timemodified = time();
+
+  $entry->submissionid = $submissionid;
+  $entry->studentid = $feedback['id'];
+  $entry->grade = $feedback['grade'];
+  $entry->comment = $feedback['comment'];
+  $entry->name = $feedback['file'];
+  $entry->fileid = 0;
+  $entry->usermodified = 1;
+  $entry->contextid = $contextid;
+
+  // Insert data into gradeimporter_feedback table and gets ID
+  $entry->id = $DB->insert_record('gradeimporter_feedback', $entry);
+
+  return $entry->id;
 }
 
 function store_feedback_file ($feedback, $context, $submission, $filetostore, $feedbackid) {
-    // Prepare file
-    $fs = get_file_storage();
-    $fileinfo = array(
-        'contextid' => $context->id,
-        'component' => 'mod_gradeimporter',
-        'filearea' => 'submissionfiles',
-        'itemid' => 0,
-        'filepath' => "/",
-        'filename' => $filetostore->get_filename(),
-        'timecreated' => time(), 'timemodified' => time()
-    );
-
-    $fileinfo = $fs->create_file_from_storedfile($fileinfo, $filetostore);
-
-    return $fileinfo;
+  // Prepare file
+  $fs = get_file_storage();
+  $fileinfo = array(
+    'contextid' => $context->id,
+    'component' => 'mod_gradeimporter',
+    'filearea' => 'submissionfiles',
+    'itemid' => $feedbackid,
+    'filepath' => "/",
+    'filename' => $filetostore->get_filename(),
+    'timecreated' => time(), 'timemodified' => time()
+  );
+
+  $fileinfo = $fs->create_file_from_storedfile($fileinfo, $filetostore);
+
+  return $fileinfo;
 }
 
 function read_zip ($file, $context, $fs) {
-    global $CFG;
-    // Get file packer to unpack zip
-    $packer = get_file_packer('application/zip');
-
-    // Clear area_files if it has been used before
-    $fs->delete_area_files($context->id,
-                            'mod_gradeimporter',
-                            'unpacktemp'
-                        );
-
-    // Extract to temp areafiles
-    $file->extract_to_storage($packer,
-                                $context->id,
-                                'mod_gradeimporter',
-                                'unpacktemp',
-                                0,
-                                $CFG->tempdir,
-                                false
-                            );
-
-    // Get extracted files from unpacktemp area file
-    $tempfiles = $fs->get_area_files($context->id,
-                                    'mod_gradeimporter',
-                                    'unpacktemp'
-                        );
-
-    // Returns an array of files object
-    return $tempfiles;
+  global $CFG;
+  // Get file packer to unpack zip
+  $packer = get_file_packer('application/zip');
+
+  // Clear area_files if it has been used before
+  $fs->delete_area_files($context->id,
+              'mod_gradeimporter',
+              'unpacktemp'
+            );
+
+  // Extract to temp areafiles
+  $file->extract_to_storage($packer,
+                $context->id,
+                'mod_gradeimporter',
+                'unpacktemp',
+                0,
+                $CFG->tempdir,
+                false
+              );
+
+  // Get extracted files from unpacktemp area file
+  $tempfiles = $fs->get_area_files($context->id,
+                  'mod_gradeimporter',
+                  'unpacktemp'
+            );
+
+  // Returns an array of files object
+  return $tempfiles;
 }
 
 function get_types_array($gradeimporterid) {
-    global $DB, $CFG;
-    // Gets moodle table prefix, usually mdl_
-    $tp = $CFG->prefix;
-    $query = "select id, name from {$tp}gradeimporter_submissiontype where gradeimporterid = $gradeimporterid";
-    return $DB->get_records_sql($query);
+  global $DB, $CFG;
+  // Gets moodle table prefix, usually mdl_
+  $tp = $CFG->prefix;
+  $query = "select id, name from {$tp}gradeimporter_submissiontype where gradeimporterid = $gradeimporterid";
+  return $DB->get_records_sql($query);
+}
+
+function validate_formdata($data) {
+  if ($data->type == -1) {
+    throw new moodle_exception(get_string('invalidtype', 'gradeimporter'));
+  }
 }

+ 43 - 43
forms/submissiontype/submissiontype.php

@@ -33,7 +33,7 @@ $context = context_module::instance($cm->id);
 // Sets url
 $url = new moodle_url('/mod/gradeimporter/submissiontype.php', array('cmid' => $cm->id));
 if (!empty($id)) {
-    $url->param('id', $id);
+  $url->param('id', $id);
 }
 $PAGE->set_url($url);
 
@@ -42,8 +42,8 @@ require_login($course, false, $cm);
 require_capability('mod/gradeimporter:edit', $context);
 
 if (!isSet($entry)) {
-    $entry = new stdClass();
-    $entry->id = null;
+  $entry = new stdClass();
+  $entry->id = null;
 }
 
 $entry->cmid = $cm->id;
@@ -52,51 +52,51 @@ $entry->gradeimporterid = $gradeimporter->id;
 $mform = new mod_gradeimporter_submissiontype_form(null, array('submissiontype' => $entry));
 
 if ($mform->is_cancelled()) {
-    if ($id) {
-        redirect("view.php?id=$cm->id&mode=entry&hook=$id");
-    } else {
-        redirect("view.php?id=$cm->id");
-    }
+  if ($id) {
+    redirect("view.php?id=$cm->id&mode=entry&hook=$id");
+  } else {
+    redirect("view.php?id=$cm->id");
+  }
 } else if ($entry = $mform->get_data()) {
-    // If data is valid
-    // Submit $entry into DB
-    if (empty($entry->id)) {
-        // If entry doesn't have id its a new entry
-        $entry->gradeimporterid = $gradeimporter->id;
-        $isnewentry = true;
-    } else {
-        $isnewentry = false;
-    }
-
-    $entry->description        = $entry->description_editor["text"];
-    $entry->descriptionformat  = FORMAT_HTML;
-
-    if ($isnewentry) {
-        $entry->id = $DB->insert_record('gradeimporter_submissiontype', $entry);
-    } else {
-        $DB->update_record('gradeimporter', $submissiontype);
-    }
-
-    if ($isnewentry) {
-        // Update completion state
-        $completion = new completion_info($course);
-        if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC && $gradeimporter->completionentries) {
-            $completion->update_state($cm, COMPLETION_COMPLETE);
-        }
+  // If data is valid
+  // Submit $entry into DB
+  if (empty($entry->id)) {
+    // If entry doesn't have id its a new entry
+    $entry->gradeimporterid = $gradeimporter->id;
+    $isnewentry = true;
+  } else {
+    $isnewentry = false;
+  }
+
+  $entry->description    = $entry->description_editor["text"];
+  $entry->descriptionformat  = FORMAT_HTML;
+
+  if ($isnewentry) {
+    $entry->id = $DB->insert_record('gradeimporter_submissiontype', $entry);
+  } else {
+    $DB->update_record('gradeimporter', $submissiontype);
+  }
+
+  if ($isnewentry) {
+    // Update completion state
+    $completion = new completion_info($course);
+    if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC && $gradeimporter->completionentries) {
+      $completion->update_state($cm, COMPLETION_COMPLETE);
     }
+  }
 
-    redirect("../submission/submission.php?id=$id&cmid=$cm->id&page=0");
+  redirect("../submission/submission.php?id=$id&cmid=$cm->id&page=0");
 }
 
 if ($typeid != -1) {
-    // If typeid is not empty then its editing an already existing submissiontype
-    // Get data from DB and insert into form
-    $PAGE->navbar->add(get_string('edit'));
-    $data = $DB->get_record('gradeimporter_submissiontype', array('id' => $typeid));
-    $data->description_editor = array('text' => $data->description,
-                                        'format' => $data->descriptionformat
-                                    );
-    $mform->set_data($data);
+  // If typeid is not empty then its editing an already existing submissiontype
+  // Get data from DB and insert into form
+  $PAGE->navbar->add(get_string('edit'));
+  $data = $DB->get_record('gradeimporter_submissiontype', array('id' => $typeid));
+  $data->description_editor = array('text' => $data->description,
+                    'format' => $data->descriptionformat
+                  );
+  $mform->set_data($data);
 }
 
 $PAGE->set_title($gradeimporter->name);
@@ -104,7 +104,7 @@ $PAGE->set_heading($course->fullname);
 echo $OUTPUT->header();
 echo $OUTPUT->heading(format_string($gradeimporter->name), 2);
 if ($gradeimporter->intro) {
-    echo $OUTPUT->box(format_module_intro('gradeimporter', $gradeimporter, $cm->id), 'generalbox', 'intro');
+  echo $OUTPUT->box(format_module_intro('gradeimporter', $gradeimporter, $cm->id), 'generalbox', 'intro');
 }
 
 $mform->display();

+ 32 - 32
forms/submissiontype/submissiontype_form.php

@@ -19,36 +19,36 @@ require_once($CFG->dirroot.'/lib/formslib.php');
 
 class mod_gradeimporter_submissiontype_form extends moodleform {
 
-    public function definition() {
-        global $CFG, $DB;
-
-        $mform = $this->_form;
-        $submissiontype = $this->_customdata['submissiontype'];
-
-        // --------------------
-        // Form starts here
-        $mform->addElement('header', 'general', get_string('general', 'form'));
-
-        // Submission type name
-        $mform->addElement('text', 'name', get_string('name', 'gradeimporter'), array('size' => '64'));
-        $mform->setType('name', PARAM_TEXT);
-        $mform->addRule('name', get_string('error_nameField', 'gradeimporter'), 'required', null, 'client');
-
-        // Description
-        $mform->addElement('editor', 'description_editor', get_string('submissionDescription', 'gradeimporter'));
-        $mform->setType('description_editor', PARAM_TEXT);
-
-        // Hidden fields
-        $mform->addElement('hidden', 'id');
-        $mform->setType('id', PARAM_INT);
-        $mform->addElement('hidden', 'cmid');
-        $mform->setType('cmid', PARAM_INT);
-        $mform->addElement('hidden', 'gradeimporterid');
-        $mform->setType('gradeimporterid', PARAM_INT);
-
-        // Buttons
-        $this->add_action_buttons();
-
-        $this->set_data($submissiontype);
-    }
+  public function definition() {
+    global $CFG, $DB;
+
+    $mform = $this->_form;
+    $submissiontype = $this->_customdata['submissiontype'];
+
+    // --------------------
+    // Form starts here
+    $mform->addElement('header', 'general', get_string('general', 'form'));
+
+    // Submission type name
+    $mform->addElement('text', 'name', get_string('name', 'gradeimporter'), array('maxlength' => '256'));
+    $mform->setType('name', PARAM_TEXT);
+    $mform->addRule('name', get_string('error_nameField', 'gradeimporter'), 'required', null, 'client');
+
+    // Description
+    $mform->addElement('editor', 'description_editor', get_string('submissionDescription', 'gradeimporter'));
+    $mform->setType('description_editor', PARAM_TEXT);
+
+    // Hidden fields
+    $mform->addElement('hidden', 'id');
+    $mform->setType('id', PARAM_INT);
+    $mform->addElement('hidden', 'cmid');
+    $mform->setType('cmid', PARAM_INT);
+    $mform->addElement('hidden', 'gradeimporterid');
+    $mform->setType('gradeimporterid', PARAM_INT);
+
+    // Buttons
+    $this->add_action_buttons();
+
+    $this->set_data($submissiontype);
+  }
 }

+ 1 - 1
index.php

@@ -20,5 +20,5 @@ $id = required_param('id', PARAM_INT); // Course ID.
 
 // Ensure that the course specified is valid
 if (!$course = $DB->get_record('course', array('id' => $id))) {
-    throw new moodle_exception('Course ID is incorrect');
+  throw new moodle_exception('Course ID is incorrect');
 }

+ 2 - 0
lang/en/forms_lang.php

@@ -26,3 +26,5 @@ $string['submissionfiles'] = 'Submission files';
 $string['submissionfiles_help'] = 'Submit 1 file with all submissions inside it, either a .csv or a .zip with a csv and a folder with the submissions inside it';
 
 $string['newtypebutton'] = 'New type';
+  // Exceptions
+  $string['invalidtype'] = "Submission type is invalid, must first create a type";

+ 128 - 123
lib.php

@@ -16,143 +16,148 @@
 
 // Adds gradeimporter to add new activity page
 function tool_devcourse_extend_navigation_course($navigation, $course, $coursecontext) {
-    $url = new moodle_url('/admin/tool/devcourse/index.php');
-    $devcoursenode = navigation_node::create('Development course', $url, navigation_node::TYPE_CUSTOM, 'Dev course', 'devcourse');
-    $navigation->add_node($devcoursenode);
+  $url = new moodle_url('/admin/tool/devcourse/index.php');
+  $devcoursenode = navigation_node::create('Development course', $url, navigation_node::TYPE_CUSTOM, 'Dev course', 'devcourse');
+  $navigation->add_node($devcoursenode);
 }
 
 function gradeimporter_supports($feature) {
-    switch ($feature) {
-        case FEATURE_MOD_ARCHETYPE:
-            return MOD_ARCHETYPE_RESOURCE;
-        case FEATURE_GROUPS:
-            return false;
-        case FEATURE_GROUPINGS:
-            return false;
-        case FEATURE_MOD_INTRO:
-            return true;
-        case FEATURE_COMPLETION_TRACKS_VIEWS:
-            return true;
-        case FEATURE_GRADE_HAS_GRADE:
-            return false;
-        case FEATURE_GRADE_OUTCOMES:
-            return false;
-        case FEATURE_BACKUP_MOODLE2:
-            return true;
-        default:
-            return null;
-    }
+  switch ($feature) {
+    case FEATURE_MOD_ARCHETYPE:
+      return MOD_ARCHETYPE_RESOURCE;
+    case FEATURE_GROUPS:
+      return false;
+    case FEATURE_GROUPINGS:
+      return false;
+    case FEATURE_MOD_INTRO:
+      return true;
+    case FEATURE_COMPLETION_TRACKS_VIEWS:
+      return true;
+    case FEATURE_GRADE_HAS_GRADE:
+      return false;
+    case FEATURE_GRADE_OUTCOMES:
+      return false;
+    case FEATURE_BACKUP_MOODLE2:
+      return true;
+    default:
+      return null;
+  }
 }
 
 function gradeimporter_add_instance($data, $mform) {
-    /*
-        *Given an object containing all the necessary data,
-        *(defined by the form in mod_form.php) this function
-        *creates a new instance and returns the id of this new
-        *instance.
-        *
-        *@param $data: an object from the form in mod_form.php
-        *@return int: the id of the newly inserted gradeimport record
-    */
-    global $DB;
-    $data->timemodified = time();
-
-    $data->id = $DB->insert_record("gradeimporter", $data);
-
-    return $data->id;
-}
-
-function gradeimporter_update_instance($data) {
-    /*
-        *given an object containing all the necessary data,
-        *(defined by the form in mod_form.php) this function
-        *updates an existing instance with the new data.
-        *
-        *@param $data: an object from the form mod_form.php
-        *@return boolean: if the record update was a success of fail
-    */
-    global $DB;
-
-    $data->timemodified = time();
-    $data->id = $data->instance;
-
-    return $DB->update_record('gradeimporter', $data);
-}
-
-function gradeimporter_delete_instance($data) {
-    /*
-    *Given an id of a gradeimporter instance,
-    * this function permanently deletes the instance
-    * and any data that depends on it.
+  /*
+    *Given an object containing all the necessary data,
+    *(defined by the form in mod_form.php) this function
+    *creates a new instance and returns the id of this new
+    *instance.
     *
-    *@param int $id: Id of the gradeimporter instance
-    *@return boolean, if the deletion was a success or
-    *                 a failure.
-    */
+    *@param $data: an object from the form in mod_form.php
+    *@return int: the id of the newly inserted gradeimport record
+  */
+  global $DB;
+  $data->timemodified = time();
 
-    global $DB;
+  $data->id = $DB->insert_record("gradeimporter", $data);
 
-    if (!$data = $DB->get_record('gradeimporter', array('id' => $id))) {
-        return false;
-    }
+  return $data->id;
+}
 
-    $cm = get_coursemodule_from_instance('gradeimporter', $gradeimporter->id);
+function gradeimporter_update_instance($data) {
+  /*
+    *given an object containing all the necessary data,
+    *(defined by the form in mod_form.php) this function
+    *updates an existing instance with the new data.
+    *
+    *@param $data: an object from the form mod_form.php
+    *@return boolean: if the record update was a success of fail
+  */
+  global $DB;
 
-    $context = context_module::instance($cm->id);
-    // Files
-    $fs = get_file_storage();
-    $fs->delete_area_files($context->id, 'mod_gradeimporter');
+  $data->timemodified = time();
+  $data->id = $data->instance;
 
-    // Delete all files and submissions associated with this instance
-    $DB->delete_records('gradeimporter_submission', array('gradeimporterid' => $gradeimporter->id));
-    $DB->delete_records('gradeimporter_feedback', array('gradeimporterid' => $gradeimporter->id));
+  return $DB->update_record('gradeimporter', $data);
+}
 
-    // Delete the instance itself
-    $DB->delete_records('gradeimporter', array('id' => $id));
-    return true;
+function gradeimporter_delete_instance($data) {
+  /*
+  *Given an id of a gradeimporter instance,
+  * this function permanently deletes the instance
+  * and any data that depends on it.
+  *
+  *@param int $id: Id of the gradeimporter instance
+  *@return boolean, if the deletion was a success or
+  *         a failure.
+  */
+
+  global $DB;
+
+  if (!$data = $DB->get_record('gradeimporter', array('id' => $id))) {
+    return false;
+  }
+
+  $cm = get_coursemodule_from_instance('gradeimporter', $gradeimporter->id);
+
+  $context = context_module::instance($cm->id);
+  // Files
+  $fs = get_file_storage();
+  $fs->delete_area_files($context->id, 'submissionfiles');
+
+  // Delete all files and submissions associated with this instance
+  $DB->delete_records('gradeimporter_submission', array('gradeimporterid' => $gradeimporter->id));
+  $DB->delete_records('gradeimporter_feedback', array('gradeimporterid' => $gradeimporter->id));
+  $DB->delete_records('gradeimporter_submissiontype', array('gradeimporterid' => $gradeimporter->id));
+
+  // Delete the instance itself
+  $DB->delete_records('gradeimporter', array('id' => $id));
+  return true;
 }
 
+
+/**
+ * Implementation of pluginfile function to get file from a pluginfile url
+ */
 function mod_gradeimporter_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
-    // Check the contextlevel is as expected - if your plugin is a block, this becomes CONTEXT_BLOCK, etc.
-    if ($context->contextlevel != CONTEXT_MODULE) {
-        return false;
-    }
-    // Make sure the filearea is one of those used by the plugin.
-    if ($filearea !== 'submissionfiles') {
-        return false;
-    }
-
-    // Make sure the user is logged in and has access to the module
-    // (plugins that are not course modules should leave out the 'cm' part).
-    require_login($course, true, $cm);
-
-    // Check the relevant capabilities - these may vary depending on the filearea being accessed.
-    if (!has_capability('mod/gradeimporter:view', $context)) {
-        return false;
-    }
-
-    // Leave this line out if you set the itemid to null in make_pluginfile_url (set $itemid to 0 instead).
-    $itemid = array_shift($args); // The first item in the $args array.
-
-    // Use the itemid to retrieve any relevant data records and perform any security checks to see if the
-    // user really does have access to the file in question.
-
-    // Extract the filename / filepath from the $args array.
-    $filename = array_pop($args); // The last item in the $args array.
-    if (!$args) {
-        $filepath = '/'; // If $args is empty => the path is '/'
-    } else {
-        $filepath = '/'.implode('/', $args).'/'; // If $args contains elements of the filepath
-    }
-
-    // Retrieve the file from the Files API.
-    $fs = get_file_storage();
-    $file = $fs->get_file($context->id, 'mod_gradeimporter', $filearea, $itemid, $filepath, $filename);
-    if (!$file) {
-        echo "didnt find the file";
-        return false; // The file does not exist.
-    }
-
-    // We can now send the file back to the browser - in this case with a cache lifetime of 1 day and no filtering.
-    send_stored_file($file, 86400, 0, $forcedownload, $options);
+  // Check the contextlevel is as expected - if your plugin is a block, this becomes CONTEXT_BLOCK, etc.
+  if ($context->contextlevel != CONTEXT_MODULE) {
+    return false;
+  }
+  // Make sure the filearea is one of those used by the plugin.
+  if ($filearea !== 'submissionfiles') {
+    return false;
+  }
+
+  // Make sure the user is logged in and has access to the module
+  // (plugins that are not course modules should leave out the 'cm' part).
+  require_login($course, true, $cm);
+
+  // Check the relevant capabilities - these may vary depending on the filearea being accessed.
+  if (!has_capability('mod/gradeimporter:view', $context)) {
+    return false;
+  }
+
+  // Leave this line out if you set the itemid to null in make_pluginfile_url (set $itemid to 0 instead).
+  $itemid = array_shift($args); // The first item in the $args array.
+
+  // Use the itemid to retrieve any relevant data records and perform any security checks to see if the
+  // user really does have access to the file in question.
+
+  // Extract the filename / filepath from the $args array.
+  $filename = array_pop($args); // The last item in the $args array.
+  if (!$args) {
+    $filepath = '/'; // If $args is empty => the path is '/'
+  } else {
+    $filepath = '/'.implode('/', $args).'/'; // If $args contains elements of the filepath
+  }
+
+  // Retrieve the file from the Files API.
+  $fs = get_file_storage();
+  $file = $fs->get_file($context->id, 'mod_gradeimporter', $filearea, $itemid, $filepath, $filename);
+  if (!$file) {
+    echo "didnt find the file";
+    return false; // The file does not exist.
+  }
+
+  // We can now send the file back to the browser - in this case with a cache lifetime of 1 day and no filtering.
+  send_stored_file($file, 86400, 0, $forcedownload, $options);
 }

+ 75 - 63
libs/student_viewlib.php

@@ -13,83 +13,95 @@
 //
 // You should have received a copy of the GNU General Public License
 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
-function query_feedbacks($cmid, $gradeimporterid) {
-    global $DB, $USER, $CFG;
 
-    // Get moodle table prefix, usually 'mdl_'
-    $tp = $CFG->prefix;
+/**
+ * Queries all feedbacks for a student on gradeimporter_feedback table
+ * @param int $gradeimporterid - Which gradeimporter instance the feedbacks are related to
+ * @return array $records - With all feedbacks this student has on this gradeimporter instance
+ */
+function query_feedbacks ($gradeimporterid) {
+  global $DB, $USER, $CFG;
 
-    // Build database query to fetch feedbacks for the student
-    $query = " SELECT
-                gst.name as typename,
-                gst.id as typeid,
-                gst.description as typedescription,
-                gf.id as id,
-                gs.name as submissionname,
-                gs.id as submissionid,
-                gf.grade as grade,
-                gf.comment as comment,
-                gf.name as filename,
-                gs.description as submissiondescription,
-                gs.position as position
-                FROM {$tp}gradeimporter_feedback as gf
-                JOIN {$tp}gradeimporter_submission as gs
-                    ON gf.submissionid = gs.id
-                JOIN {$tp}gradeimporter_submissiontype as gst
-                    ON gs.type = gst.id
-                WHERE gs.gradeimporterid = {$gradeimporterid}
-                    AND gf.studentid = {$USER->id}
-                    AND gs.visibility = 1
-            ";
-    // Query database to find students feedbacks
-    $records = $DB->get_records_sql($query);
+  // Get moodle table prefix, usually 'mdl_'
+  $tp = $CFG->prefix;
 
-    // Return query result
-    return $records;
+  // Build database query to fetch feedbacks for the student
+  $query = " SELECT
+        gf.id as id,
+        gst.name as typename,
+        gst.id as typeid,
+        gst.description as typedescription,
+        gs.name as submissionname,
+        gs.id as submissionid,
+        gf.grade as grade,
+        gf.comment as comment,
+        gf.name as filename,
+        gf.contextid as contextid,
+        gs.description as submissiondescription,
+        gs.position as position
+        FROM {$tp}gradeimporter_feedback as gf
+        JOIN {$tp}gradeimporter_submission as gs
+          ON gf.submissionid = gs.id
+        JOIN {$tp}gradeimporter_submissiontype as gst
+          ON gs.type = gst.id
+        WHERE gs.gradeimporterid = {$gradeimporterid}
+          AND gf.studentid = {$USER->id}
+          AND gs.visibility = 1
+      ";
+  // Query database to find students feedbacks
+  $records = $DB->get_records_sql($query);
+  // Return query result
+  return $records;
 }
 
+/**
+ * Builds table to show all feedbacks
+ * @param array $feedbacks - array with all feedbacks of the student, fetched with query_feedbacks()
+ * @param int $cmid - Course module id, to build pluginfile as we have to know which course the feedbacks are related to
+ * @return html_writer $table - String with table html with all feedbacks, ready to be shown
+ */
 function make_feedback_table ($feedbacks, $cmid) {
-    $table = new html_table();
-    $table->head = array(get_string('type', 'gradeimporter'),
-                    get_string('submission', 'gradeimporter'),
-                    get_string('grade', 'gradeimporter'),
-                    get_string('comment', 'gradeimporter'),
-                    get_string('file', 'gradeimporter')
-                );
-    $table->aling = array('center', 'center', 'center', 'center', 'center');
-    $table->attributes = array('class' => 'generaltable mod_index');
+  $table = new html_table();
+  $table->head = array(get_string('type', 'gradeimporter'),
+          get_string('submission', 'gradeimporter'),
+          get_string('grade', 'gradeimporter'),
+          get_string('comment', 'gradeimporter'),
+          get_string('file', 'gradeimporter')
+        );
+  $table->aling = array('center', 'center', 'center', 'center', 'center');
+  $table->attributes = array('class' => 'generaltable mod_index');
 
-    if (count($feedbacks)) {
-        // If feedbacks is not an empty list
-        foreach ($feedbacks as $type => $feedback) {
-            $rowvalues = array('type_name',
-                                $feedback->submissionname,
-                                $feedback->grade,
-                                $feedback->comment,
-                                get_file($feedback, $cmid)
-                            );
+  if (count($feedbacks)) {
+    // If feedbacks is not an empty list
+    foreach ($feedbacks as $type => $feedback) {
+      $rowvalues = array('type_name',
+                $feedback->submissionname,
+                $feedback->grade,
+                $feedback->comment,
+                get_file($feedback, $cmid)
+              );
 
-            $row = new html_table_row($rowvalues);
-            $table->data[] = $row;
-        }
+      $row = new html_table_row($rowvalues);
+      $table->data[] = $row;
     }
-    echo html_writer::table($table);
+  }
+  echo html_writer::table($table);
 }
 
 function get_file ($feedback, $cmid) {
 
-    $context = context_module::instance($cmid);
+  $context = context_module::instance($cmid);
 
-    $url = moodle_url::make_pluginfile_url($context->id,
-                                            'mod_gradeimporter',
-                                            'submissionfiles',
-                                            0,
-                                            "/",
-                                            $feedback->filename,
-                                            true
-                                        );
+  $url = moodle_url::make_pluginfile_url($feedback->contextid,
+                      'mod_gradeimporter',
+                      'submissionfiles',
+                      $feedback->submissionid,
+                      "/",
+                      $feedback->filename,
+                      true
+                    );
 
-    // Return pluginfile url, will use function mod_gradeimporter_pluginfile at lib.php to serve the file
-    return "<a href='{$url}'>$feedback->filename</a>";
+  // Return pluginfile url, will use function mod_gradeimporter_pluginfile at lib.php to serve the file
+  return "<a href='{$url}'>$feedback->filename</a>";
 
 }

+ 193 - 135
libs/teacher_viewlib.php

@@ -13,151 +13,209 @@
 //
 // You should have received a copy of the GNU General Public License
 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
-class Teacherview {
-    private $cmid;
-    private $gradeimporterid;
-    private $context;
-    private $cellstyle = "border:1px solid black; text-align:center";
-
-    public function __construct (int $cmid, int $gradeimporterid) {
-        $this->cmid = $cmid;
-        $this->gradeimporterid = $gradeimporterid;
-        $this->context = context_module::instance($cmid);
-    }
 
-    private function get_cmid () {
-        return $this->cmid;
-    }
-    private function get_gradeimporterid () {
-        return $this->gradeimporterid;
-    }
-    private function get_context () {
-        return $this->context;
-    }
-    private function get_cellstyle () {
-        return $this->cellstyle;
-    }
 
-    public function make_table () {
-        global $DB, $CFG;
-
-        // Prepare variables
-        $studentlist = $this->get_studentlist();
-        $submissions = $this->get_submissions();
-
-        // Create table
-        $table = new html_table();
-        $table->align = array('center');
-        $table->attributes = array('class' => 'generaltable mod_index');
-
-        $submissions = $this->get_submissions();
-        if (!$submissions) {
-            $this->no_submissions();
-            return;
-        }
-        $table->data[] = $this->get_table_head($submissions);
-        foreach ($studentlist as $student) {
-            $table->data[] = $this->get_studentsubmissions($student, $submissions);
-        }
-
-        return html_writer::table($table);
+class Teacherview {
+  /**
+   * @property gradeimporterid used to query DB at get_submissions()
+   * @property context used to get studentslist at get_studentlist()
+   * @property cellstyle style used by table cells. Black border and centered text
+   */
+  private $gradeimporterid;
+  private $context;
+  private $cellstyle = "border:1px solid black; text-align:center";
+
+  /**
+   * @param int cmid to get context
+   * @param int gradeimporterid to query database
+   * constructor
+   */
+  public function __construct (int $cmid, int $gradeimporterid) {
+    $this->gradeimporterid = $gradeimporterid;
+    $this->context = context_module::instance($cmid);
+  }
+
+  private function get_gradeimporterid () {
+    return $this->gradeimporterid;
+  }
+  private function get_context () {
+    return $this->context;
+  }
+  private function get_cellstyle () {
+    return $this->cellstyle;
+  }
+
+  /**
+   * builds teacherview table using php html_table class
+   * Gets all submissions from get_submissions()
+   * Header is built with get_table_head() passing submissions as param
+   * Each row is a different student
+   * Gets each row with get_studentsubmissions()
+   * @return table as html string
+   */
+  public function make_table () {
+    global $DB, $CFG;
+
+    // Prepare variables
+    $studentlist = $this->get_studentlist();
+    $submissions = $this->get_submissions();
+
+    // Create table
+    $table = new html_table();
+    $table->align = array('center');
+    $table->attributes = array('class' => 'generaltable mod_index');
+
+    $submissions = $this->get_submissions();
+    if (!$submissions) {
+      $this->no_submissions();
+      return;
     }
-
-    private function get_studentlist () {
-        // Get students list with userid as key and fullname as value
-        $enrolledusers = get_enrolled_users($this->get_context(), 'mod/gradeimporter:view',
-                                        0, 'u.id, u.firstname, u.lastname',
-                                        'u.firstname, u.lastname'
-                                    );
-        $studentlist = array();
-        foreach ($enrolledusers as $user) {
-            $studentlist[$user->id] = array('name' => $user->firstname." ".$user->lastname,
-                                            'id' => $user->id);
-        }
-
-        return $studentlist;
+    $table->data[] = $this->get_table_head($submissions);
+    foreach ($studentlist as $student) {
+      $table->data[] = $this->get_studentsubmissions($student, $submissions);
     }
 
-    private function get_table_head ($submissions) {
-        // Creates teacher view table head
-        $header = new html_table_row();
-
-        // Add name header to header row
-        $header->cells[] = $this->make_cell(get_string('nameCol', 'gradeimporter'), 1);
-
-        foreach ($submissions as $submission) {
-            // $subname = editSub($submission->name, $gradeimporterid, $cmid, $submission->id);
-            $header->cells[] = $this->make_cell($submission->name, 2);
-        }
-        return $header;
+    return html_writer::table($table);
+  }
+
+  /**
+   * Gets students list from moodle function get_enrolled_users
+   * Builds a list from $enrolledusers with:
+   * * Keys as student id;
+   * * Values as student fullname and student id.
+   * @return array $studentlist - students data (name and id)
+   */
+  private function get_studentlist () {
+    // Get students list with userid as key and fullname as value
+    $enrolledusers = get_enrolled_users($this->get_context(), 'mod/gradeimporter:view',
+                    0, 'u.id, u.firstname, u.lastname',
+                    'u.firstname, u.lastname'
+                  );
+    $studentlist = array();
+    foreach ($enrolledusers as $user) {
+      $studentlist[$user->id] = array('name' => $user->firstname." ".$user->lastname,
+                      'id' => $user->id);
     }
 
-    private function get_studentsubmissions ($student, $submissions) {
-        global $DB;
-        // Create new row for the student
-        $row = new html_table_row();
-
-        // Set first cell of the row as the students fullname
-        $row->cells[] = $this->make_cell($student["name"], 1);
-
-        // Foreach submission checks if student has a feedback for it
-        // If they have, fill it with grade + filename (possibly grade+link to full feedback)
-        // If they don't have fill it with grade and filename as -
-        foreach ($submissions as $submission) {
-            $feedback = $DB->get_record('gradeimporter_feedback',
-                                        ['submissionid' => $submission->id,
-                                            'studentid' => $student['id']]
-                                        );
-            if ($feedback) {
-                $fileurl = $this->feedback_url($feedback);
-                $grade = $feedback->grade;
-            } else {
-                $fileurl = '-';
-                $grade = '-';
-            }
-            $row->cells[] = $this->make_cell($grade, 1);
-
-            $row->cells[] = $this->make_cell($fileurl, 1);
-        }
-        return $row;
-    }
+    return $studentlist;
+  }
 
-    private function get_submissions () {
-        global $CFG, $DB;
-        // Get table prefix
-        $tp = $CFG->prefix;
-
-        // Build Query
-        $sql = "SELECT id, name, type
-                FROM {$tp}gradeimporter_submission
-                WHERE gradeimporterid ={$this->get_gradeimporterid()}
-                ORDER BY type, id";
-        // Query DB
-        $submissions = $DB->get_records_sql($sql);
-        // Return submissions
-        return $submissions;
-    }
+  /**
+   * Builds a row with first column being "name" for students names
+   * Other rows are submissions names
+   * @return html_table_row $header
+   */
+  private function get_table_head ($submissions) {
+    // Creates teacher view table head
+    $header = new html_table_row();
 
-    private function no_submissions () {
-        echo "No submissions";
-    }
+    // Add name header to header row
+    $header->cells[] = $this->make_cell(get_string('nameCol', 'gradeimporter'), 1);
 
-    private function feedback_url ($feedback) {
-        $url = moodle_url::make_pluginfile_url($feedback->contextid,
-                                            'mod_gradeimporter',
-                                            'submissionfiles',
-                                            0,
-                                            "/",
-                                            $feedback->name,
-                                            true
-                                        );
-        return "<a href='{$url}'>$feedback->name</a>";
+    foreach ($submissions as $submission) {
+      // Add a icon to redirect to submission form to edit the sub
+      $header->cells[] = $this->make_cell($submission->name, 2);
     }
-
-    private function make_cell ($text, $colspan) {
-        $cell = new html_table_cell($text);
-        $cell->style = $this->get_cellstyle();
-        $cell->colspan = $colspan;
-        return $cell;
+    return $header;
+  }
+
+  /**
+   * Build a row for a student defined by param $student
+   * @param array $student, array with keys "name" and "id"
+   * @param $submissions, submissions list to find each submission for this student
+   * For each submission at $submissions tries do fetch feedback from DB:
+   * * If submission is found adds grade and link to feedback file to row
+   * * If doesn't have the submission sets grade and link to " - "
+   * @return html_table_row $row with each column being grade and feedbackfile for the submission
+   */
+  private function get_studentsubmissions ($student, $submissions) {
+    global $DB;
+    // Create new row for the student
+    $row = new html_table_row();
+
+    // Set first cell of the row as the students fullname
+    $row->cells[] = $this->make_cell($student["name"], 1);
+
+    // Foreach submission checks if student has a feedback for it
+    // If they have, fill it with grade + filename (possibly grade+link to full feedback)
+    // If they don't have fill it with grade and filename as -
+    foreach ($submissions as $submission) {
+      $feedback = $DB->get_record('gradeimporter_feedback',
+                    ['submissionid' => $submission->id,
+                      'studentid' => $student['id']]
+                    );
+      if ($feedback) {
+        $fileurl = $this->feedback_url($feedback);
+        $grade = $feedback->grade;
+      } else {
+        $fileurl = '-';
+        $grade = '-';
+      }
+      $row->cells[] = $this->make_cell($grade, 1);
+
+      $row->cells[] = $this->make_cell($fileurl, 1);
     }
+    return $row;
+  }
+
+  /**
+   * Fetch all submissions for this gradeimporter instance on gradeimporter_submissions table
+   * Build query using $this->gradeimporterid property
+   * @return $submissions fetched from gradeimporter_submission table
+   */
+  private function get_submissions () {
+    global $CFG, $DB;
+    // Get table prefix
+    $tp = $CFG->prefix;
+
+    // Build Query
+    $sql = "SELECT id, name, type
+        FROM {$tp}gradeimporter_submission
+        WHERE gradeimporterid ={$this->get_gradeimporterid()}
+        ORDER BY type, id";
+    // Query DB
+    $submissions = $DB->get_records_sql($sql);
+    // Return submissions
+    return $submissions;
+  }
+
+  /**
+   * Prints html when there are no submissions to show
+   * @underconstruction
+   * @return void
+   */
+  private function no_submissions () {
+    echo "No submissions";
+  }
+
+  /**
+   * Builds fileplugin url to feedback file
+   * @param array $feedback fetched from gradeimporter_feedback table
+   * @return html hyperlink to download feedback file
+   */
+  private function feedback_url ($feedback) {
+    $url = moodle_url::make_pluginfile_url($feedback->contextid,
+                      'mod_gradeimporter',
+                      'submissionfiles',
+                      $feedback->id,
+                      "/",
+                      $feedback->name,
+                      true
+                    );
+    return "<a href='{$url}'>$feedback->name</a>";
+  }
+
+  /**
+   * Makes a cell object to be inserted into a row
+   * Cell style is predifined on class properties
+   * @param string $text - Text shown on the cell
+   * @param int $colspan - How many columns this cell ocuppies
+   * @return html_table_cell $cell - cell built on the function
+   */
+  private function make_cell ($text, $colspan) {
+    $cell = new html_table_cell($text);
+    $cell->style = $this->get_cellstyle();
+    $cell->colspan = $colspan;
+    return $cell;
+  }
 }

+ 7 - 7
libs/testlib.php

@@ -18,11 +18,11 @@
 
 function reset_submissions($contextid) {
 
-    global $DB;
-    // Remove data from gradeimporter_submission and gradeimporter_feedback tables
-    $DB->delete_records('gradeimporter_submission');
-    $DB->delete_records('gradeimporter_feedback');
-    // Delete feedbackfiles
-    $fs = get_file_storage();
-    $fs->delete_area_files($contextid, 'mod_gradeimporter', 'submissionfiles');
+  global $DB;
+  // Remove data from gradeimporter_submission and gradeimporter_feedback tables
+  $DB->delete_records('gradeimporter_submission');
+  $DB->delete_records('gradeimporter_feedback');
+  // Delete feedbackfiles
+  $fs = get_file_storage();
+  $fs->delete_area_files($contextid, 'mod_gradeimporter', 'submissionfiles');
 }

+ 16 - 81
locallib.php

@@ -14,85 +14,20 @@
 // You should have received a copy of the GNU General Public License
 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
 
-defined('MOODLE_INTERNAL') || die();
-
-function get_comments($cmid, $id) {
-    global $DB, $USER, $CFG;
-    $tp = $CFG->prefix; // gets moodle tables prefix, not everyone uses mdl_
-
-    $sql = "
-          SELECT gf.id gf_id,
-                gf.grade,
-                gf.comment gf_comment,
-                gf.contextid gf_contextid,
-                gf.fileid gf_fileid,
-                gf.name gf_name,
-                gs.name gs_name,
-                gs.description gs_description,
-                gst.name gst_name,
-                gst.description gst_description,
-                fileid
-            FROM ".$tp."gradeimporter_feedback gf
-            JOIN ".$tp."gradeimporter_submission gs
-              ON gf.submissionid = gs.id
-            JOIN ".$tp."gradeimporter_submissiontype gst
-              ON gs.type = gst.id
-          WHERE gf.studentid = ?";
-
-    $records = $DB->get_records_sql($sql, array('studentid' => $USER->id));
-
-    $data = array();
-    if (count($records)) {
-        foreach ($records as $value) {
-            if (!array_key_exists($value->gst_name, $data)) {
-                $data[$value->gst_name] = array();
-            }
-
-            $fileurl = buildurl($cmid, $value->gf_id, $value->gf_name);
-
-            $data[$value->gst_name][] = array($value->gs_name, $value->grade, $value->gf_comment, $fileurl);
-        }
-    }
-
-    return $data;
-}
-
-require_once($CFG->libdir . '/filelib.php');
-require_once("$CFG->libdir/csvlib.class.php");
-
-
-function buildurl($cmid, $fileid, $filename) {
-    $fileurl = new moodle_url("/mod/gradeimporter/view.php", array('id' => $cmid, 'fileid' => $fileid, 'filename' => $filename, 'action' => 1));
-    return "<a href=$fileurl target=_blank> $filename</a>";
-}
-
-function editSub($subname, $gradeimporterid, $cmid, $subid) {
-    $url = new moodle_url("/mod/gradeimporter/submission.php", array('id' => $gradeimporterid,
-                                                                    'cmid' => $cmid,
-                                                                    'subid' => $subid,
-                                                                    'update' => 1
-                                                                  )
-                           );
-    return $subname.'<a href='.$url.' target="_blank"><i class="icon fa fa-pencil fa-fw"  title="'
-                        .get_string('editSub', 'gradeimporter')
-                        .'" aria-label="'
-                        .get_string('editSub', 'gradeimporter').'"></i>';
-}
-
-function exportCSV($context) {
-    $enrolledusers = get_enrolled_users($context, 'mod/gradeimporter:student');
-    $header = array('id', 'name', 'email', 'grade', 'comment', 'file');
-
-    $csvexport = new csv_export_writer();
-    $csvexport->set_filename('config');
-    $csvexport->add_data($header);
-
-    foreach ($enrolledusers as $value) {
-        $name = $value->firstname . ' ' . $value->lastname;
-        $studententry = array($value->id, $name, $value->email, '', '', '');
-        $csvexport->add_data($studententry);
-    }
-
-    $csvexport->download_file();
-    // $dlfile = $csvexporter->download_array('config', $data);
+function exportcsv($context) {
+  $enrolledusers = get_enrolled_users($context, 'mod/gradeimporter:student');
+  $header = array('id', 'name', 'email', 'grade', 'comment', 'file');
+
+  $csvexport = new csv_export_writer();
+  $csvexport->set_filename('config');
+  $csvexport->add_data($header);
+
+  foreach ($enrolledusers as $value) {
+    $name = $value->firstname . ' ' . $value->lastname;
+    $studententry = array($value->id, $name, $value->email, '', '', '');
+    $csvexport->add_data($studententry);
+  }
+
+  $csvexport->download_file();
+  // $dlfile = $csvexporter->download_array('config', $data);
 }

+ 42 - 40
mod_form.php

@@ -20,44 +20,46 @@ require_once($CFG->dirroot.'/course/moodleform_mod.php');
 require_once($CFG->dirroot.'/mod/gradeimporter/lib.php');
 
 class mod_gradeimporter_mod_form extends moodleform_mod {
-    public function definition() {
-        global $CFG, $COURSE, $USER, $DB, $OUTPUT;
-
-        $mform =& $this->_form;
-        $coursemodulesid = optional_param('update', 0, PARAM_INT);
-
-        // Header
-        $mform->addElement('header', 'general', get_string('general', 'gradeimporter'));
-
-        // Name text field
-        $mform->addElement('text', 'name', get_string('name', 'gradeimporter'), array('size' => '64'));
-        $mform->setType('name', PARAM_TEXT);
-        $mform->addRule('name', get_string('error_nameField', 'gradeimporter'), 'required', null, 'client');
-
-        // Description
-        $this->standard_intro_elements(get_string('description', 'gradeimporter'));
-
-        $features = array('groups' => false, 'groupings' => false,
-                        'groupmembersonly' => false,  'outcomes' => false,
-                        'gradecat' => false, 'idnumber' => false
-                    );
-
-        $this->standard_coursemodule_elements($features);
-
-        // Hidden fields
-        $mform->addElement('hidden', 'action');
-        $mform->setType('action', PARAM_TEXT);
-        $mform->addElement('hidden', 'id');
-        $mform->setType('id', PARAM_TEXT);
-        $mform->addElement('hidden', 'author_name');
-        $mform->setType('author_name', PARAM_TEXT);
-        $mform->addElement('hidden', 'author_modified_name');
-        $mform->setType('author_modified_name', PARAM_TEXT);
-        $mform->addElement('hidden', 'timecreated');
-        $mform->setType('timecreated', PARAM_TEXT);
-        $mform->addElement('hidden', 'position');
-        $mform->setType('position', PARAM_TEXT);
-
-        $this->add_action_buttons();
-    }
+  public function definition() {
+    global $CFG, $COURSE, $USER, $DB, $OUTPUT;
+
+    $mform =& $this->_form;
+    $coursemodulesid = optional_param('update', 0, PARAM_INT);
+
+    // Header
+    $mform->addElement('header', 'general', get_string('general', 'gradeimporter'));
+
+    // Name text field
+    $mform->addElement('text', 'name', get_string('name', 'gradeimporter'), array('size' => '64',
+                                                                                  'maxlength' => "256")
+                                                                                );
+    $mform->setType('name', PARAM_TEXT);
+    $mform->addRule('name', get_string('error_nameField', 'gradeimporter'), 'required', null, 'client');
+
+    // Description
+    $this->standard_intro_elements(get_string('description', 'gradeimporter'));
+
+    $features = array('groups' => false, 'groupings' => false,
+            'groupmembersonly' => false,  'outcomes' => false,
+            'gradecat' => false, 'idnumber' => false
+          );
+
+    $this->standard_coursemodule_elements($features);
+
+    // Hidden fields
+    $mform->addElement('hidden', 'action');
+    $mform->setType('action', PARAM_TEXT);
+    $mform->addElement('hidden', 'id');
+    $mform->setType('id', PARAM_TEXT);
+    $mform->addElement('hidden', 'author_name');
+    $mform->setType('author_name', PARAM_TEXT);
+    $mform->addElement('hidden', 'author_modified_name');
+    $mform->setType('author_modified_name', PARAM_TEXT);
+    $mform->addElement('hidden', 'timecreated');
+    $mform->setType('timecreated', PARAM_TEXT);
+    $mform->addElement('hidden', 'position');
+    $mform->setType('position', PARAM_TEXT);
+
+    $this->add_action_buttons();
+  }
 }

+ 13 - 13
renderer.php

@@ -15,20 +15,20 @@
 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
 
 class mod_wavefront_renderer extends plugin_renderer_base {
-    /**
-     * Returns html to display the gradeimporter feedbacks
-     * @param object $gradeimporter feedback with which is associated to the user
-     */
-    public function display_feedback($gradeimporter, $editing = false) {
-        global $DB;
+  /**
+   * Returns html to display the gradeimporter feedbacks
+   * @param object $gradeimporter feedback with which is associated to the user
+   */
+  public function display_feedback($gradeimporter, $editing = false) {
+    global $DB;
 
-        $output = '';
+    $output = '';
 
-        if ($gradeimporter->intro && !editing) {
-            $output .= $this->output->box(format_module_intro('gradeimporter',
-                                            $gradeimporter, $this->page->cm->id),
-                                            'generalbox', 'intro'
-                                        );
-        }
+    if ($gradeimporter->intro && !editing) {
+      $output .= $this->output->box(format_module_intro('gradeimporter',
+                      $gradeimporter, $this->page->cm->id),
+                      'generalbox', 'intro'
+                    );
     }
+  }
 }

+ 62 - 61
view.php

@@ -21,40 +21,41 @@ require_once('locallib.php');
 require_once('libs/student_viewlib.php');
 require_once('libs/teacher_viewlib.php');
 
-  global $DB;
-
-  $id = optional_param('id', 0, PARAM_INT); // Course_module ID.
-  $g  = optional_param('g', 0, PARAM_INT);  // Gradeimporter instance ID, should be named as the first character of the module.
-  $action = optional_param('action', 0, PARAM_INT);
-  $fileid     = optional_param('fileid', 0, PARAM_INT);
-  $filename   = optional_param('filename', 'a', PARAM_TEXT);
+global $DB;
+$id = optional_param('id', 0, PARAM_INT); // Course_module ID.
+$g  = optional_param('g', 0, PARAM_INT);  // Gradeimporter instance ID, should be named as the first character of the module.
+$action = optional_param('action', 0, PARAM_INT);
+$fileid   = optional_param('fileid', 0, PARAM_INT);
+$filename   = optional_param('filename', 'a', PARAM_TEXT);
 
 
 
 if ($id) {
-    if (! $cm = get_coursemodule_from_id('gradeimporter', $id)) {
-        error('Course Module ID was incorrect');
-    }
-
-    if (! $course = $DB->get_record('course', array('id' => $cm->course))) {
-        error('Course is misconfigured');
-    }
-
-    if (! $gradeimporter = $DB->get_record('gradeimporter', array('id' => $cm->instance))) {
-        error('Course module is incorrect');
-    }
+  // ABC
+  if (! $cm = get_coursemodule_from_id('gradeimporter', $id)) {
+    error('Course Module ID was incorrect');
+  }
+  $cm;
+
+  if (! $course = $DB->get_record('course', array('id' => $cm->course))) {
+    error('Course is misconfigured');
+  }
+
+  if (! $gradeimporter = $DB->get_record('gradeimporter', array('id' => $cm->instance))) {
+    error('Course module is incorrect');
+  }
 } else if ($g) {
-    if (! $gradeimporter = $DB->get_record('gradeimporter', array('id' => $g))) {
-        error('Course module is incorrect');
-    }
-    if (! $course = $DB->get_record('course', array('id' => $gradeimporter->course))) {
-        error('Course is misconfigured');
-    }
-    if (! $cm = get_coursemodule_from_instance('gradeimporter', $gradeimporter->id, $course->id)) {
-        error('Course Module ID was incorrect');
-    }
+  if (! $gradeimporter = $DB->get_record('gradeimporter', array('id' => $g))) {
+    error('Course module is incorrect');
+  }
+  if (! $course = $DB->get_record('course', array('id' => $gradeimporter->course))) {
+    error('Course is misconfigured');
+  }
+  if (! $cm = get_coursemodule_from_instance('gradeimporter', $gradeimporter->id, $course->id)) {
+    error('Course Module ID was incorrect');
+  }
 } else {
-    error('You must specify a course_module ID or an instance ID');
+  error('You must specify a course_module ID or an instance ID');
 }
 
 require_login($course, true, $cm);
@@ -64,15 +65,15 @@ $context = context_module::instance($cm->id);
 
 
 if ($action == 1 && has_capability('mod/gradeimporter:view', $context)) {
-    // Download feedback file.
-    $fs = get_file_storage();
-    $file = $fs->get_file($context->id, 'mod_gradeimporter', 'gradeimporter_feedback', $fileid, '/', $filename);
-    if ($file) {
-        send_stored_file($file, 86400, 0, true);
-    }
+  // Download feedback file.
+  $fs = get_file_storage();
+  $file = $fs->get_file($context->id, 'mod_gradeimporter', 'gradeimporter_feedback', $fileid, '/', $filename);
+  if ($file) {
+    send_stored_file($file, 86400, 0, true);
+  }
 } else if ($action == 2 && has_capability('mod/gradeimporter:edit', $context)) {
-    // Download students csv with their id.
-    exportCSV($context);
+  // Download students csv with their id.
+  exportcsv($context);
 }
 
 
@@ -93,22 +94,22 @@ echo $output->heading($heading);
 
 // Button to add new submission.
 if (has_capability('mod/gradeimporter:edit', $context)) {
-    $url = new moodle_url('/mod/gradeimporter/forms/submission/submission.php');
-    $newbutton = '<form action="'. $url . '">'.
-          '<input type="hidden" name="id" value="'. $gradeimporter->id .'" />'.
-          '<input type="hidden" name="cmid" value="'.$cm->id.'" />'.
-          '<input type="submit" Value="'.get_string('newsubmission', 'gradeimporter').'" />'.
-          '</form>';
-    echo $newbutton;
-
-    $url = new moodle_url("/mod/gradeimporter/view.php", array('id' => $id, 'cmid' => $cm->id, 'action' => 2));
-    $newbutton = '<form action="'. $url . '">'.
-        '<input type="hidden" name="id" value="'. $id .'" />'.
-        '<input type="hidden" name="cmid" value="'.$cm->id.'" />'.
-        '<input type="hidden" name="action" value="2" />'.
-        '<input type="submit" Value="'.get_string('downloadconfigcsv', 'gradeimporter').'" />'.
-        '</form>';
-    echo $newbutton;
+  $url = new moodle_url('/mod/gradeimporter/forms/submission/submission.php');
+  $newbutton = '<form action="'. $url . '">'.
+      '<input type="hidden" name="id" value="'. $gradeimporter->id .'" />'.
+      '<input type="hidden" name="cmid" value="'.$cm->id.'" />'.
+      '<input type="submit" Value="'.get_string('newsubmission', 'gradeimporter').'" />'.
+      '</form>';
+  echo $newbutton;
+
+  $url = new moodle_url("/mod/gradeimporter/view.php", array('id' => $id, 'cmid' => $cm->id, 'action' => 2));
+  $newbutton = '<form action="'. $url . '">'.
+    '<input type="hidden" name="id" value="'. $id .'" />'.
+    '<input type="hidden" name="cmid" value="'.$cm->id.'" />'.
+    '<input type="hidden" name="action" value="2" />'.
+    '<input type="submit" Value="'.get_string('downloadconfigcsv', 'gradeimporter').'" />'.
+    '</form>';
+  echo $newbutton;
 }
 
 // Tabela com as notas vem aqui.
@@ -117,17 +118,17 @@ require_once($CFG->libdir . '/tablelib.php');
 require_once(dirname(__FILE__).'/locallib.php');
 
 if (has_capability('mod/gradeimporter:edit', $context)) {
-    // Loads teacher view.
-    // get_teacher_view($cm->id, $gradeimporter->id);
-    $teacherview = new Teacherview($cm->id, $gradeimporter->id);
-    $teachertable = $teacherview->make_table();
-    echo $teachertable;
+  // Loads teacher view.
+  // get_teacher_view($cm->id, $gradeimporter->id);
+  $teacherview = new Teacherview($cm->id, $gradeimporter->id);
+  $teachertable = $teacherview->make_table();
+  echo $teachertable;
 } else {
-    // Load student view
+  // Load student view
 
-    // Query database to find student feedbacks
-    $feedbacks = query_feedbacks($cm->id, $gradeimporter->id);
-    make_feedback_table($feedbacks, $cm->id);
+  // Query database to find student feedbacks
+  $feedbacks = query_feedbacks($gradeimporter->id);
+  make_feedback_table($feedbacks, $cm->id);
 }
 
 // Finishes the page!