/**
  * Constructor should set up all the private variables ready to be pulled
  * @param object $course
  * @param int $groupid id of selected group, 0 means all
  * @param string $itemlist comma separated list of item ids, empty means all
  * @param boolean $export_feedback
  * @param boolean $export_letters
  * @note Exporting as letters will lead to data loss if that exported set it re-imported.
  */
 function grade_export($course, $groupid = 0, $itemlist = '', $export_feedback = false, $updatedgradesonly = false, $displaytype = GRADE_DISPLAY_TYPE_REAL, $decimalpoints = 2)
 {
     $this->course = $course;
     $this->groupid = $groupid;
     $this->grade_items = grade_item::fetch_all(array('courseid' => $this->course->id));
     $this->columns = array();
     if (!empty($itemlist)) {
         $itemids = explode(',', $itemlist);
         // remove items that are not requested
         foreach ($itemids as $itemid) {
             if (array_key_exists($itemid, $this->grade_items)) {
                 $this->columns[$itemid] =& $this->grade_items[$itemid];
             }
         }
     } else {
         foreach ($this->grade_items as $itemid => $unused) {
             $this->columns[$itemid] =& $this->grade_items[$itemid];
         }
     }
     $this->export_feedback = $export_feedback;
     $this->userkey = '';
     $this->previewrows = false;
     $this->updatedgradesonly = $updatedgradesonly;
     $this->displaytype = $displaytype;
     $this->decimalpoints = $decimalpoints;
 }
Exemple #2
0
 protected function get_javascript_init_params($course, \cm_info $cm = null, \section_info $section = null)
 {
     global $DB, $CFG;
     require_once $CFG->libdir . '/gradelib.php';
     require_once $CFG->dirroot . '/course/lib.php';
     // Get grades as basic associative array.
     $gradeoptions = array();
     $items = \grade_item::fetch_all(array('courseid' => $course->id));
     // For some reason the fetch_all things return null if none.
     $items = $items ? $items : array();
     foreach ($items as $id => $item) {
         // Don't include the grade item if it's linked with a module that is being deleted.
         if (course_module_instance_pending_deletion($item->courseid, $item->itemmodule, $item->iteminstance)) {
             continue;
         }
         // Do not include grades for current item.
         if ($cm && $cm->instance == $item->iteminstance && $cm->modname == $item->itemmodule && $item->itemtype == 'mod') {
             continue;
         }
         $gradeoptions[$id] = $item->get_name(true);
     }
     \core_collator::asort($gradeoptions);
     // Change to JS array format and return.
     $jsarray = array();
     foreach ($gradeoptions as $id => $name) {
         $jsarray[] = (object) array('id' => $id, 'name' => $name);
     }
     return array($jsarray);
 }
Exemple #3
0
 /**
  * Constructor should set up all the private variables ready to be pulled
  * @param object $course
  * @param int $groupid id of selected group, 0 means all
  * @param string $itemlist comma separated list of item ids, empty means all
  * @param boolean $export_feedback
  * @param boolean $export_letters
  * @note Exporting as letters will lead to data loss if that exported set it re-imported.
  */
 function grade_export($course, $groupid = 0, $itemlist = '', $export_feedback = false, $updatedgradesonly = false, $displaytype = GRADE_DISPLAY_TYPE_REAL, $decimalpoints = 2)
 {
     $this->course = $course;
     $this->groupid = $groupid;
     $this->grade_items = grade_item::fetch_all(array('courseid' => $this->course->id));
     //Populating the columns here is required by /grade/export/(whatever)/export.php
     //however index.php, when the form is submitted, will construct the collection here
     //with an empty $itemlist then reconstruct it in process_form() using $formdata
     $this->columns = array();
     if (!empty($itemlist)) {
         if ($itemlist == '-1') {
             //user deselected all items
         } else {
             $itemids = explode(',', $itemlist);
             // remove items that are not requested
             foreach ($itemids as $itemid) {
                 if (array_key_exists($itemid, $this->grade_items)) {
                     $this->columns[$itemid] =& $this->grade_items[$itemid];
                 }
             }
         }
     } else {
         foreach ($this->grade_items as $itemid => $unused) {
             $this->columns[$itemid] =& $this->grade_items[$itemid];
         }
     }
     $this->export_feedback = $export_feedback;
     $this->userkey = '';
     $this->previewrows = false;
     $this->updatedgradesonly = $updatedgradesonly;
     $this->displaytype = $displaytype;
     $this->decimalpoints = $decimalpoints;
 }
 public function cleanup()
 {
     // cleanup any clickers before the test
     $user_id = iclicker_service::require_user();
     $results = iclicker_service::get_registrations_by_user($user_id);
     if ($results) {
         echo "cleanup registrations for user: {$user_id}  " . PHP_EOL;
         foreach ($results as $reg) {
             if ($reg->clicker_id == $this->clicker_id) {
                 iclicker_service::remove_registration($reg->id);
                 echo "cleanup: {$reg->id} " . PHP_EOL;
             }
         }
     }
     // cleanup the test grades
     $def_grade_cats = grade_category::fetch_all(array('courseid' => $this->courseid, 'fullname' => iclicker_service::GRADE_CATEGORY_NAME));
     $stuff_grade_cats = grade_category::fetch_all(array('courseid' => $this->courseid, 'fullname' => 'stuff'));
     $grade_cats = $def_grade_cats;
     if (is_array($def_grade_cats) && is_array($stuff_grade_cats)) {
         $grade_cats = array_merge($def_grade_cats, $stuff_grade_cats);
     } else {
         if (is_array($stuff_grade_cats)) {
             $grade_cats = $stuff_grade_cats;
         }
     }
     if ($grade_cats) {
         foreach ($grade_cats as $cat) {
             $grade_items = grade_item::fetch_all(array('courseid' => $this->courseid, 'categoryid' => $cat->id));
             if ($grade_items) {
                 foreach ($grade_items as $item) {
                     $grades = grade_grade::fetch_all(array('itemid' => $item->id));
                     if ($grades) {
                         foreach ($grades as $grade) {
                             $grade->delete("cleanup");
                         }
                     }
                     $item->delete("cleanup");
                 }
             }
             $cat->delete("cleanup");
         }
     }
 }
Exemple #5
0
 /**
  * Sets up the table_log parameters.
  *
  * @param string $uniqueid unique id of table.
  * @param \context_course $context Context of the report.
  * @param \moodle_url $url url of the page where this table would be displayed.
  * @param array $filters options are:
  *                          userids : limit to specific users (default: none)
  *                          itemid : limit to specific grade item (default: all)
  *                          grader : limit to specific graders (default: all)
  *                          datefrom : start of date range
  *                          datetill : end of date range
  *                          revisedonly : only show revised grades (default: false)
  *                          format : page | csv | excel (default: page)
  * @param string $download Represents download format, pass '' no download at this time.
  * @param int $page The current page being displayed.
  * @param int $perpage Number of rules to display per page.
  */
 public function __construct($uniqueid, \context_course $context, $url, $filters = array(), $download = '', $page = 0, $perpage = 100)
 {
     parent::__construct($uniqueid);
     $this->set_attribute('class', 'gradereport_history generaltable generalbox');
     // Set protected properties.
     $this->context = $context;
     $this->courseid = $this->context->instanceid;
     $this->pagesize = $perpage;
     $this->page = $page;
     $this->filters = (object) $filters;
     $this->gradeitems = \grade_item::fetch_all(array('courseid' => $this->courseid));
     $this->cms = get_fast_modinfo($this->courseid);
     $this->useridfield = 'userid';
     // Define columns in the table.
     $this->define_table_columns();
     // Define configs.
     $this->define_table_configs($url);
     // Set download status.
     $this->is_downloading($download, get_string('exportfilename', 'gradereport_history'));
 }
 function definition_after_data()
 {
     global $COURSE;
     $mform =& $this->_form;
     if ($id = $mform->getElementValue('update')) {
         $modulename = $mform->getElementValue('modulename');
         $instance = $mform->getElementValue('instance');
         if ($items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename, 'iteminstance' => $instance, 'courseid' => $COURSE->id))) {
             foreach ($items as $item) {
                 if (!empty($item->outcomeid)) {
                     $elname = 'outcome_' . $item->outcomeid;
                     if ($mform->elementExists($elname)) {
                         $mform->hardFreeze($elname);
                         // prevent removing of existing outcomes
                     }
                 }
             }
         }
     }
     if ($mform->elementExists('groupmode')) {
         if ($COURSE->groupmodeforce) {
             $mform->hardFreeze('groupmode');
             // groupmode can not be changed if forced from course settings
         }
     }
     if ($mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly') and empty($COURSE->groupmodeforce)) {
         $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
     } else {
         if (!$mform->elementExists('groupmode') and $mform->elementExists('groupmembersonly')) {
             $mform->disabledIf('groupingid', 'groupmembersonly', 'notchecked');
         } else {
             if (!$mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly')) {
                 // groupings have no use without groupmode or groupmembersonly
                 if ($mform->elementExists('groupingid')) {
                     $mform->removeElement('groupingid');
                 }
             }
         }
     }
 }
Exemple #7
0
 function definition()
 {
     global $COURSE;
     $mform =& $this->_form;
     $itemid = $this->_customdata['itemid'];
     $this->available = grade_item::fetch_all(array('courseid' => $COURSE->id));
     $this->noidnumbers = array();
     // All items that have no idnumbers are added to a separate section of the form (hidden by default),
     // enabling the user to assign idnumbers to these grade_items.
     foreach ($this->available as $item) {
         if (empty($item->idnumber)) {
             $this->noidnumbers[$item->id] = $item;
             unset($this->available[$item->id]);
         }
         if ($item->id == $itemid) {
             // Do not include the current grade_item in the available section
             unset($this->available[$item->id]);
         }
     }
     /// visible elements
     $mform->addElement('header', 'general', get_string('gradeitem', 'grades'));
     $mform->addElement('static', 'itemname', get_string('itemname', 'grades'));
     $mform->addElement('textarea', 'calculation', get_string('calculation', 'grades'), 'cols="60" rows="5"');
     $mform->addHelpButton('calculation', 'calculation', 'grades');
     $mform->setForceLtr('calculation');
     /// hidden params
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'courseid', 0);
     $mform->setType('courseid', PARAM_INT);
     $mform->addElement('hidden', 'section', 0);
     $mform->setType('section', PARAM_ALPHA);
     $mform->setDefault('section', 'calculation');
     /// add return tracking info
     $gpr = $this->_customdata['gpr'];
     $gpr->add_mform_elements($mform);
     $this->add_action_buttons();
 }
Exemple #8
0
 /**
  * Constructor should set up all the private variables ready to be pulled
  * @param object $course
  * @param int $groupid id of selected group, 0 means all
  * @param string $itemlist comma separated list of item ids, empty means all
  * @param boolean $export_feedback
  * @param boolean $export_letters
  * @note Exporting as letters will lead to data loss if that exported set it re-imported.
  */
 function grade_export($course, $groupid = 0, $itemlist = '', $export_feedback = false, $export_letters = false)
 {
     $this->course = $course;
     $this->groupid = $groupid;
     $this->grade_items = grade_item::fetch_all(array('courseid' => $this->course->id));
     $this->columns = array();
     if (!empty($itemlist)) {
         $itemids = explode(',', $itemlist);
         // remove items that are not requested
         foreach ($itemids as $itemid) {
             if (array_key_exists($itemid, $this->grade_items)) {
                 $this->columns[$itemid] =& $this->grade_items[$itemid];
             }
         }
     } else {
         foreach ($this->grade_items as $itemid => $unused) {
             $this->columns[$itemid] =& $this->grade_items[$itemid];
         }
     }
     $this->export_letters = $export_letters;
     $this->export_feedback = $export_feedback;
     $this->userkey = '';
     $this->previewrows = false;
 }
 public function __construct()
 {
     global $DB;
     parent::__construct(get_string('gradedistributiongroupbar', 'gradereport_visual'));
     $this->layout = visualization::LAYOUT_AXIS;
     $this->layoutsettings = array('false', 'true');
     $this->nodeshape = visualization::SHAPE_VERTICAL_BAR;
     $this->xaxis = 'grade';
     $this->yaxis = 'students';
     $this->xaxislabelformat = '0\\%';
     $this->xaxisxoffset = -27;
     $this->xaxislabel = get_string('grade', 'gradereport_visual');
     if ($this->percent) {
         $this->yaxislabelformat = '0\\%';
         $this->yaxislabel = get_string('percentstudents', 'gradereport_visual');
     } else {
         $this->yaxislabel = get_string('numberstudents', 'gradereport_visual');
     }
     $this->title = get_string('gradedistribution:title', 'gradereport_visual');
     $this->capability = 'gradereport/visual:vis:grade_distribution_group_bar';
     $courseid = required_param('id');
     $options = array();
     $items = grade_item::fetch_all(array('courseid' => $courseid));
     foreach ($items as $item) {
         if (count($item->get_final()) > 0) {
             $options[$item->id] = grade_report_visual::truncate($item->get_name());
         }
     }
     $options['ai'] = 'All Items';
     $this->selector = new selector('item', $options, 'ai');
     $this->selectors = array($this->selector);
     $this->colorencoder = new encoder(encoder::ENCODER_COLOR, 'group');
     $this->encoders = array($this->colorencoder);
     $this->grouplegend = new legend($this->colorencoder);
     $this->legends = array($this->grouplegend);
 }
 protected function define_execution()
 {
     // Fetch all activity grade items
     if ($items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(), 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
         // Annotate them in backup_ids
         foreach ($items as $item) {
             backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
         }
     }
 }
Exemple #11
0
 public function fill_table()
 {
     global $CFG, $DB;
     // MDL-11679, only show 'mycourses' instead of all courses
     if ($courses = get_my_courses($this->user->id, 'c.sortorder ASC', 'id, shortname, showgrades')) {
         $numusers = $this->get_numusers(false);
         foreach ($courses as $course) {
             if (!$course->showgrades) {
                 continue;
             }
             $courselink = '<a href="' . $CFG->wwwroot . '/grade/report/user/index.php?id=' . $course->id . '">' . $course->shortname . '</a>';
             $canviewhidden = has_capability('moodle/grade:viewhidden', get_context_instance(CONTEXT_COURSE, $course->id));
             // Get course grade_item
             $course_item = grade_item::fetch_course_item($course->id);
             // Get the stored grade
             $course_grade = new grade_grade(array('itemid' => $course_item->id, 'userid' => $this->user->id));
             $course_grade->grade_item =& $course_item;
             $finalgrade = $course_grade->finalgrade;
             if (!$canviewhidden and !is_null($finalgrade)) {
                 if ($course_grade->is_hidden()) {
                     $finalgrade = null;
                 } else {
                     // This is a really ugly hack, it will be fixed in 2.0
                     $items = grade_item::fetch_all(array('courseid' => $course->id));
                     $grades = array();
                     $sql = "SELECT g.*\n                                  FROM {grade_grades} g\n                                  JOIN {grade_items} gi ON gi.id = g.itemid\n                                 WHERE g.userid = ? AND gi.courseid = ?";
                     if ($gradesrecords = $DB->get_records_sql($sql, array($this->user->id, $course->id))) {
                         foreach ($gradesrecords as $grade) {
                             $grades[$grade->itemid] = new grade_grade($grade, false);
                         }
                         unset($gradesrecords);
                     }
                     foreach ($items as $itemid => $unused) {
                         if (!isset($grades[$itemid])) {
                             $grade_grade = new grade_grade();
                             $grade_grade->userid = $this->user->id;
                             $grade_grade->itemid = $items[$itemid]->id;
                             $grades[$itemid] = $grade_grade;
                         }
                         $grades[$itemid]->grade_item =& $items[$itemid];
                     }
                     $hiding_affected = grade_grade::get_hiding_affected($grades, $items);
                     if (array_key_exists($course_item->id, $hiding_affected['altered'])) {
                         $finalgrade = $hiding_affected['altered'][$course_item->id];
                     } else {
                         if (!empty($hiding_affected['unknown'][$course_item->id])) {
                             $finalgrade = null;
                         }
                     }
                     unset($hiding_affected);
                     unset($grades);
                     unset($items);
                 }
             }
             $data = array($courselink, grade_format_gradevalue($finalgrade, $course_item, true));
             if (!$this->showrank) {
                 //nothing to do
             } else {
                 if (!is_null($finalgrade)) {
                     /// find the number of users with a higher grade
                     /// please note this can not work if hidden grades involved :-( to be fixed in 2.0
                     $params = array($finalgrade, $course_item->id);
                     $sql = "SELECT COUNT(DISTINCT(userid))\n                              FROM {grade_grades}\n                             WHERE finalgrade IS NOT NULL AND finalgrade > ?\n                                   AND itemid = ?";
                     $rank = $DB->count_records_sql($sql, $params) + 1;
                     $data[] = "{$rank}/{$numusers}";
                 } else {
                     // no grade, no rank
                     $data[] = '-';
                 }
             }
             $this->table->add_data($data);
         }
         return true;
     } else {
         notify(get_string('nocourses', 'grades'));
         return false;
     }
 }
Exemple #12
0
}
$PAGE->set_url($url);
if (!($course = $DB->get_record('course', array('id' => $id)))) {
    print_error('nocourseid');
}
require_login($course);
$context = context_course::instance($id);
require_capability('moodle/grade:import', $context);
require_capability('gradeimport/csv:view', $context);
$separatemode = (groups_get_course_groupmode($COURSE) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context));
$currentgroup = groups_get_course_group($course);
print_grade_page_head($course->id, 'import', 'csv', get_string('importcsv', 'grades'));
// Set up the grade import mapping form.
$gradeitems = array();
if ($id) {
    if ($grade_items = grade_item::fetch_all(array('courseid' => $id))) {
        foreach ($grade_items as $grade_item) {
            // Skip course type and category type.
            if ($grade_item->itemtype == 'course' || $grade_item->itemtype == 'category') {
                continue;
            }
            $displaystring = null;
            if (!empty($grade_item->itemmodule)) {
                $displaystring = get_string('modulename', $grade_item->itemmodule) . get_string('labelsep', 'langconfig') . $grade_item->get_name();
            } else {
                $displaystring = $grade_item->get_name();
            }
            $gradeitems[$grade_item->id] = $displaystring;
        }
    }
}
Exemple #13
0
/**
 * This function will handles the whole deletion process of a module. This includes calling
 * the modules delete_instance function, deleting files, events, grades, conditional data,
 * the data in the course_module and course_sections table and adding a module deletion
 * event to the DB.
 *
 * @param int $cmid the course module id
 * @since 2.5
 */
function course_delete_module($cmid)
{
    global $CFG, $DB;
    require_once $CFG->libdir . '/gradelib.php';
    require_once $CFG->dirroot . '/blog/lib.php';
    require_once $CFG->dirroot . '/calendar/lib.php';
    // Get the course module.
    if (!($cm = $DB->get_record('course_modules', array('id' => $cmid)))) {
        return true;
    }
    // Get the module context.
    $modcontext = context_module::instance($cm->id);
    // Get the course module name.
    $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
    // Get the file location of the delete_instance function for this module.
    $modlib = "{$CFG->dirroot}/mod/{$modulename}/lib.php";
    // Include the file required to call the delete_instance function for this module.
    if (file_exists($modlib)) {
        require_once $modlib;
    } else {
        throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null, "Cannot delete this module as the file mod/{$modulename}/lib.php is missing.");
    }
    $deleteinstancefunction = $modulename . '_delete_instance';
    // Ensure the delete_instance function exists for this module.
    if (!function_exists($deleteinstancefunction)) {
        throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null, "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/{$modulename}/lib.php.");
    }
    // Call the delete_instance function, if it returns false throw an exception.
    if (!$deleteinstancefunction($cm->instance)) {
        throw new moodle_exception('cannotdeletemoduleinstance', '', '', null, "Cannot delete the module {$modulename} (instance).");
    }
    // Remove all module files in case modules forget to do that.
    $fs = get_file_storage();
    $fs->delete_area_files($modcontext->id);
    // Delete events from calendar.
    if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
        foreach ($events as $event) {
            $calendarevent = calendar_event::load($event->id);
            $calendarevent->delete();
        }
    }
    // Delete grade items, outcome items and grades attached to modules.
    if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename, 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
        foreach ($grade_items as $grade_item) {
            $grade_item->delete('moddelete');
        }
    }
    // Delete completion and availability data; it is better to do this even if the
    // features are not turned on, in case they were turned on previously (these will be
    // very quick on an empty table).
    $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
    $DB->delete_records('course_modules_availability', array('coursemoduleid' => $cm->id));
    $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
    $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id, 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
    // Delete the context.
    context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
    // Delete the module from the course_modules table.
    $DB->delete_records('course_modules', array('id' => $cm->id));
    // Delete module from that section.
    if (!delete_mod_from_section($cm->id, $cm->section)) {
        throw new moodle_exception('cannotdeletemodulefromsection', '', '', null, "Cannot delete the module {$modulename} (instance) from section.");
    }
    // Trigger event for course module delete action.
    $event = \core\event\course_module_deleted::create(array('courseid' => $cm->course, 'context' => $modcontext, 'objectid' => $cm->id, 'other' => array('modulename' => $modulename, 'instanceid' => $cm->instance)));
    $event->add_record_snapshot('course_modules', $cm);
    $event->trigger();
    rebuild_course_cache($cm->course, true);
}
/**
 * Reset all course grades, refetch from the activities and recalculate
 *
 * @param int $courseid The course to reset
 * @return bool success
 */
function grade_course_reset($courseid)
{
    // no recalculations
    grade_force_full_regrading($courseid);
    $grade_items = grade_item::fetch_all(array('courseid' => $courseid));
    foreach ($grade_items as $gid => $grade_item) {
        $grade_item->delete_all_grades('reset');
    }
    //refetch all grades
    grade_grab_course_grades($courseid);
    // recalculate all grades
    grade_regrade_final_grades($courseid);
    return true;
}
 /**
  * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
  */
 function definition_after_data()
 {
     global $CFG, $COURSE;
     $mform =& $this->_form;
     if ($id = $mform->getElementValue('update')) {
         $modulename = $mform->getElementValue('modulename');
         $instance = $mform->getElementValue('instance');
         if ($this->_features->gradecat) {
             $gradecat = false;
             if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
                 if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
                     $gradecat = true;
                 }
             }
             if ($items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename, 'iteminstance' => $instance, 'courseid' => $COURSE->id))) {
                 foreach ($items as $item) {
                     if (!empty($item->outcomeid)) {
                         $elname = 'outcome_' . $item->outcomeid;
                         if ($mform->elementExists($elname)) {
                             $mform->hardFreeze($elname);
                             // prevent removing of existing outcomes
                         }
                     }
                 }
                 foreach ($items as $item) {
                     if (is_bool($gradecat)) {
                         $gradecat = $item->categoryid;
                         continue;
                     }
                     if ($gradecat != $item->categoryid) {
                         //mixed categories
                         $gradecat = false;
                         break;
                     }
                 }
             }
             if ($gradecat === false) {
                 // items and outcomes in different categories - remove the option
                 // TODO: it might be better to add a "Mixed categories" text instead
                 if ($mform->elementExists('gradecat')) {
                     $mform->removeElement('gradecat');
                 }
             }
         }
     }
     if ($COURSE->groupmodeforce) {
         if ($mform->elementExists('groupmode')) {
             $mform->hardFreeze('groupmode');
             // groupmode can not be changed if forced from course settings
         }
     }
     if ($mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly') and empty($COURSE->groupmodeforce)) {
         $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
     } else {
         if (!$mform->elementExists('groupmode') and $mform->elementExists('groupmembersonly')) {
             $mform->disabledIf('groupingid', 'groupmembersonly', 'notchecked');
         } else {
             if (!$mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly')) {
                 // groupings have no use without groupmode or groupmembersonly
                 if ($mform->elementExists('groupingid')) {
                     $mform->removeElement('groupingid');
                 }
             }
         }
     }
 }
Exemple #16
0
/**
 * This function creates all the gradebook data from xml
 */
function restore_create_gradebook($restore, $xml_file)
{
    global $CFG;
    $status = true;
    //Check it exists
    if (!file_exists($xml_file)) {
        return false;
    }
    // Get info from xml
    // info will contain the number of record to process
    $info = restore_read_xml_gradebook($restore, $xml_file);
    // If we have info, then process
    if (empty($info)) {
        return $status;
    }
    if (empty($CFG->disablegradehistory) and isset($info->gradebook_histories) and $info->gradebook_histories == "true") {
        $restore_histories = true;
    } else {
        $restore_histories = false;
    }
    // make sure top course category exists
    $course_category = grade_category::fetch_course_category($restore->course_id);
    $course_category->load_grade_item();
    // we need to know if all grade items that were backed up are being restored
    // if that is not the case, we do not restore grade categories nor gradeitems of category type or course type
    // i.e. the aggregated grades of that category
    $restoreall = true;
    // set to false if any grade_item is not selected/restored or already exist
    $importing = !empty($SESSION->restore->importing);
    if ($importing) {
        $restoreall = false;
    } else {
        $prev_grade_items = grade_item::fetch_all(array('courseid' => $restore->course_id));
        $prev_grade_cats = grade_category::fetch_all(array('courseid' => $restore->course_id));
        // if any categories already present, skip restore of categories from backup - course item or category already exist
        if (count($prev_grade_items) > 1 or count($prev_grade_cats) > 1) {
            $restoreall = false;
        }
        unset($prev_grade_items);
        unset($prev_grade_cats);
        if ($restoreall) {
            if ($recs = get_records_select("backup_ids", "table_name = 'grade_items' AND backup_code = {$restore->backup_unique_code}", "", "old_id")) {
                foreach ($recs as $rec) {
                    if ($data = backup_getid($restore->backup_unique_code, 'grade_items', $rec->old_id)) {
                        $info = $data->info;
                        // do not restore if this grade_item is a mod, and
                        $itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']);
                        if ($itemtype == 'mod') {
                            $olditeminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#']);
                            $itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#']);
                            if (empty($restore->mods[$itemmodule]->granular)) {
                                continue;
                            } else {
                                if (!empty($restore->mods[$itemmodule]->instances[$olditeminstance]->restore)) {
                                    continue;
                                }
                            }
                            // at least one activity should not be restored - do not restore categories and manual items at all
                            $restoreall = false;
                            break;
                        }
                    }
                }
            }
        }
    }
    // Start ul
    if (!defined('RESTORE_SILENTLY')) {
        echo '<ul>';
    }
    // array of restored categories - speedup ;-)
    $cached_categories = array();
    $outcomes = array();
    /// Process letters
    $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
    // respect current grade letters if defined
    if ($status and $restoreall and !record_exists('grade_letters', 'contextid', $context->id)) {
        if (!defined('RESTORE_SILENTLY')) {
            echo '<li>' . get_string('gradeletters', 'grades') . '</li>';
        }
        // Fetch recordset_size records in each iteration
        $recs = get_records_select("backup_ids", "table_name = 'grade_letters' AND backup_code = {$restore->backup_unique_code}", "", "old_id");
        if ($recs) {
            foreach ($recs as $rec) {
                // Get the full record from backup_ids
                $data = backup_getid($restore->backup_unique_code, 'grade_letters', $rec->old_id);
                if ($data) {
                    $info = $data->info;
                    $dbrec = new object();
                    $dbrec->contextid = $context->id;
                    $dbrec->lowerboundary = backup_todb($info['GRADE_LETTER']['#']['LOWERBOUNDARY']['0']['#']);
                    $dbrec->letter = backup_todb($info['GRADE_LETTER']['#']['LETTER']['0']['#']);
                    insert_record('grade_letters', $dbrec);
                }
            }
        }
    }
    /// Preprocess outcomes - do not store them yet!
    if ($status and !$importing and $restoreall) {
        if (!defined('RESTORE_SILENTLY')) {
            echo '<li>' . get_string('gradeoutcomes', 'grades') . '</li>';
        }
        $recs = get_records_select("backup_ids", "table_name = 'grade_outcomes' AND backup_code = '{$restore->backup_unique_code}'", "", "old_id");
        if ($recs) {
            foreach ($recs as $rec) {
                //Get the full record from backup_ids
                $data = backup_getid($restore->backup_unique_code, 'grade_outcomes', $rec->old_id);
                if ($data) {
                    $info = $data->info;
                    //first find out if outcome already exists
                    $shortname = backup_todb($info['GRADE_OUTCOME']['#']['SHORTNAME']['0']['#']);
                    if ($candidates = get_records_sql("SELECT *\n                                                             FROM {$CFG->prefix}grade_outcomes\n                                                            WHERE (courseid IS NULL OR courseid = {$restore->course_id})\n                                                                  AND shortname = '{$shortname}'\n                                                         ORDER BY courseid ASC, id ASC")) {
                        $grade_outcome = reset($candidates);
                        $outcomes[$rec->old_id] = $grade_outcome;
                        continue;
                    }
                    $dbrec = new object();
                    if (has_capability('moodle/grade:manageoutcomes', get_context_instance(CONTEXT_SYSTEM))) {
                        $oldoutcome = backup_todb($info['GRADE_OUTCOME']['#']['COURSEID']['0']['#']);
                        if (empty($oldoutcome)) {
                            //site wide
                            $dbrec->courseid = null;
                        } else {
                            //course only
                            $dbrec->courseid = $restore->course_id;
                        }
                    } else {
                        // no permission to add site outcomes
                        $dbrec->courseid = $restore->course_id;
                    }
                    //Get the fields
                    $dbrec->shortname = backup_todb($info['GRADE_OUTCOME']['#']['SHORTNAME']['0']['#'], false);
                    $dbrec->fullname = backup_todb($info['GRADE_OUTCOME']['#']['FULLNAME']['0']['#'], false);
                    $dbrec->scaleid = backup_todb($info['GRADE_OUTCOME']['#']['SCALEID']['0']['#'], false);
                    $dbrec->description = backup_todb($info['GRADE_OUTCOME']['#']['DESCRIPTION']['0']['#'], false);
                    $dbrec->timecreated = backup_todb($info['GRADE_OUTCOME']['#']['TIMECREATED']['0']['#'], false);
                    $dbrec->timemodified = backup_todb($info['GRADE_OUTCOME']['#']['TIMEMODIFIED']['0']['#'], false);
                    $dbrec->usermodified = backup_todb($info['GRADE_OUTCOME']['#']['USERMODIFIED']['0']['#'], false);
                    //Need to recode the scaleid
                    if ($scale = backup_getid($restore->backup_unique_code, 'scale', $dbrec->scaleid)) {
                        $dbrec->scaleid = $scale->new_id;
                    }
                    //Need to recode the usermodified
                    if ($modifier = backup_getid($restore->backup_unique_code, 'user', $dbrec->usermodified)) {
                        $dbrec->usermodified = $modifier->new_id;
                    }
                    $grade_outcome = new grade_outcome($dbrec, false);
                    $outcomes[$rec->old_id] = $grade_outcome;
                }
            }
        }
    }
    /// Process grade items and grades
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo '<li>' . get_string('gradeitems', 'grades') . '</li>';
        }
        $counter = 0;
        //Fetch recordset_size records in each iteration
        $recs = get_records_select("backup_ids", "table_name = 'grade_items' AND backup_code = '{$restore->backup_unique_code}'", "id", "old_id");
        if ($recs) {
            foreach ($recs as $rec) {
                //Get the full record from backup_ids
                $data = backup_getid($restore->backup_unique_code, 'grade_items', $rec->old_id);
                if ($data) {
                    $info = $data->info;
                    // first find out if category or normal item
                    $itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#'], false);
                    if ($itemtype == 'course' or $itemtype == 'category') {
                        if (!$restoreall or $importing) {
                            continue;
                        }
                        $oldcat = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#'], false);
                        if (!($cdata = backup_getid($restore->backup_unique_code, 'grade_categories', $oldcat))) {
                            continue;
                        }
                        $cinfo = $cdata->info;
                        unset($cdata);
                        if ($itemtype == 'course') {
                            $course_category->fullname = backup_todb($cinfo['GRADE_CATEGORY']['#']['FULLNAME']['0']['#'], false);
                            $course_category->aggregation = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATION']['0']['#'], false);
                            $course_category->keephigh = backup_todb($cinfo['GRADE_CATEGORY']['#']['KEEPHIGH']['0']['#'], false);
                            $course_category->droplow = backup_todb($cinfo['GRADE_CATEGORY']['#']['DROPLOW']['0']['#'], false);
                            $course_category->aggregateonlygraded = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEONLYGRADED']['0']['#'], false);
                            $course_category->aggregateoutcomes = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEOUTCOMES']['0']['#'], false);
                            $course_category->aggregatesubcats = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATESUBCATS']['0']['#'], false);
                            $course_category->timecreated = backup_todb($cinfo['GRADE_CATEGORY']['#']['TIMECREATED']['0']['#'], false);
                            $course_category->update('restore');
                            $status = backup_putid($restore->backup_unique_code, 'grade_categories', $oldcat, $course_category->id) && $status;
                            $cached_categories[$oldcat] = $course_category;
                            $grade_item = $course_category->get_grade_item();
                        } else {
                            $oldparent = backup_todb($cinfo['GRADE_CATEGORY']['#']['PARENT']['0']['#'], false);
                            if (empty($cached_categories[$oldparent])) {
                                debugging('parent not found ' . $oldparent);
                                continue;
                                // parent not found, sorry
                            }
                            $grade_category = new grade_category();
                            $grade_category->courseid = $restore->course_id;
                            $grade_category->parent = $cached_categories[$oldparent]->id;
                            $grade_category->fullname = backup_todb($cinfo['GRADE_CATEGORY']['#']['FULLNAME']['0']['#'], false);
                            $grade_category->aggregation = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATION']['0']['#'], false);
                            $grade_category->keephigh = backup_todb($cinfo['GRADE_CATEGORY']['#']['KEEPHIGH']['0']['#'], false);
                            $grade_category->droplow = backup_todb($cinfo['GRADE_CATEGORY']['#']['DROPLOW']['0']['#'], false);
                            $grade_category->aggregateonlygraded = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEONLYGRADED']['0']['#'], false);
                            $grade_category->aggregateoutcomes = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEOUTCOMES']['0']['#'], false);
                            $grade_category->aggregatesubcats = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATESUBCATS']['0']['#'], false);
                            $grade_category->timecreated = backup_todb($cinfo['GRADE_CATEGORY']['#']['TIMECREATED']['0']['#'], false);
                            $grade_category->insert('restore');
                            $status = backup_putid($restore->backup_unique_code, 'grade_categories', $oldcat, $grade_category->id) && $status;
                            $cached_categories[$oldcat] = $grade_category;
                            $grade_item = $grade_category->get_grade_item();
                            // creates grade_item too
                        }
                        unset($cinfo);
                        $idnumber = backup_todb($info['GRADE_ITEM']['#']['IDNUMBER']['0']['#'], false);
                        if (grade_verify_idnumber($idnumber, $restore->course_id)) {
                            $grade_item->idnumber = $idnumber;
                        }
                        $grade_item->itemname = backup_todb($info['GRADE_ITEM']['#']['ITEMNAME']['0']['#'], false);
                        $grade_item->iteminfo = backup_todb($info['GRADE_ITEM']['#']['ITEMINFO']['0']['#'], false);
                        $grade_item->gradetype = backup_todb($info['GRADE_ITEM']['#']['GRADETYPE']['0']['#'], false);
                        $grade_item->calculation = backup_todb($info['GRADE_ITEM']['#']['CALCULATION']['0']['#'], false);
                        $grade_item->grademax = backup_todb($info['GRADE_ITEM']['#']['GRADEMAX']['0']['#'], false);
                        $grade_item->grademin = backup_todb($info['GRADE_ITEM']['#']['GRADEMIN']['0']['#'], false);
                        $grade_item->gradepass = backup_todb($info['GRADE_ITEM']['#']['GRADEPASS']['0']['#'], false);
                        $grade_item->multfactor = backup_todb($info['GRADE_ITEM']['#']['MULTFACTOR']['0']['#'], false);
                        $grade_item->plusfactor = backup_todb($info['GRADE_ITEM']['#']['PLUSFACTOR']['0']['#'], false);
                        $grade_item->aggregationcoef = backup_todb($info['GRADE_ITEM']['#']['AGGREGATIONCOEF']['0']['#'], false);
                        $grade_item->display = backup_todb($info['GRADE_ITEM']['#']['DISPLAY']['0']['#'], false);
                        $grade_item->decimals = backup_todb($info['GRADE_ITEM']['#']['DECIMALS']['0']['#'], false);
                        $grade_item->hidden = backup_todb($info['GRADE_ITEM']['#']['HIDDEN']['0']['#'], false);
                        $grade_item->locked = backup_todb($info['GRADE_ITEM']['#']['LOCKED']['0']['#'], false);
                        $grade_item->locktime = backup_todb($info['GRADE_ITEM']['#']['LOCKTIME']['0']['#'], false);
                        $grade_item->timecreated = backup_todb($info['GRADE_ITEM']['#']['TIMECREATED']['0']['#'], false);
                        if (backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false)) {
                            $scale = backup_getid($restore->backup_unique_code, "scale", backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false));
                            $grade_item->scaleid = $scale->new_id;
                        }
                        if (backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#'], false)) {
                            $outcome = backup_getid($restore->backup_unique_code, "grade_outcomes", backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#'], false));
                            $grade_item->outcomeid = $outcome->new_id;
                        }
                        $grade_item->update('restore');
                        $status = backup_putid($restore->backup_unique_code, "grade_items", $rec->old_id, $grade_item->id) && $status;
                    } else {
                        if ($itemtype != 'mod' and (!$restoreall or $importing)) {
                            // not extra gradebook stuff if restoring individual activities or something already there
                            continue;
                        }
                        $dbrec = new object();
                        $dbrec->courseid = $restore->course_id;
                        $dbrec->itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#'], false);
                        $dbrec->itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#'], false);
                        if ($itemtype == 'mod') {
                            // iteminstance should point to new mod
                            $olditeminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#'], false);
                            $mod = backup_getid($restore->backup_unique_code, $dbrec->itemmodule, $olditeminstance);
                            $dbrec->iteminstance = $mod->new_id;
                            if (!($cm = get_coursemodule_from_instance($dbrec->itemmodule, $mod->new_id))) {
                                // item not restored - no item
                                continue;
                            }
                            // keep in sync with activity idnumber
                            $dbrec->idnumber = $cm->idnumber;
                        } else {
                            $idnumber = backup_todb($info['GRADE_ITEM']['#']['IDNUMBER']['0']['#'], false);
                            if (grade_verify_idnumber($idnumber, $restore->course_id)) {
                                //make sure the new idnumber is unique
                                $dbrec->idnumber = $idnumber;
                            }
                        }
                        $dbrec->itemname = backup_todb($info['GRADE_ITEM']['#']['ITEMNAME']['0']['#'], false);
                        $dbrec->itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#'], false);
                        $dbrec->itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#'], false);
                        $dbrec->itemnumber = backup_todb($info['GRADE_ITEM']['#']['ITEMNUMBER']['0']['#'], false);
                        $dbrec->iteminfo = backup_todb($info['GRADE_ITEM']['#']['ITEMINFO']['0']['#'], false);
                        $dbrec->gradetype = backup_todb($info['GRADE_ITEM']['#']['GRADETYPE']['0']['#'], false);
                        $dbrec->calculation = backup_todb($info['GRADE_ITEM']['#']['CALCULATION']['0']['#'], false);
                        $dbrec->grademax = backup_todb($info['GRADE_ITEM']['#']['GRADEMAX']['0']['#'], false);
                        $dbrec->grademin = backup_todb($info['GRADE_ITEM']['#']['GRADEMIN']['0']['#'], false);
                        $dbrec->gradepass = backup_todb($info['GRADE_ITEM']['#']['GRADEPASS']['0']['#'], false);
                        $dbrec->multfactor = backup_todb($info['GRADE_ITEM']['#']['MULTFACTOR']['0']['#'], false);
                        $dbrec->plusfactor = backup_todb($info['GRADE_ITEM']['#']['PLUSFACTOR']['0']['#'], false);
                        $dbrec->aggregationcoef = backup_todb($info['GRADE_ITEM']['#']['AGGREGATIONCOEF']['0']['#'], false);
                        $dbrec->display = backup_todb($info['GRADE_ITEM']['#']['DISPLAY']['0']['#'], false);
                        $dbrec->decimals = backup_todb($info['GRADE_ITEM']['#']['DECIMALS']['0']['#'], false);
                        $dbrec->hidden = backup_todb($info['GRADE_ITEM']['#']['HIDDEN']['0']['#'], false);
                        $dbrec->locked = backup_todb($info['GRADE_ITEM']['#']['LOCKED']['0']['#'], false);
                        $dbrec->locktime = backup_todb($info['GRADE_ITEM']['#']['LOCKTIME']['0']['#'], false);
                        $dbrec->timecreated = backup_todb($info['GRADE_ITEM']['#']['TIMECREATED']['0']['#'], false);
                        if (backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false)) {
                            $scale = backup_getid($restore->backup_unique_code, "scale", backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false));
                            $dbrec->scaleid = $scale->new_id;
                        }
                        if (backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#'])) {
                            $oldoutcome = backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#']);
                            if (empty($outcomes[$oldoutcome])) {
                                continue;
                                // error!
                            }
                            if (empty($outcomes[$oldoutcome]->id)) {
                                $outcomes[$oldoutcome]->insert('restore');
                                $outcomes[$oldoutcome]->use_in($restore->course_id);
                                backup_putid($restore->backup_unique_code, "grade_outcomes", $oldoutcome, $outcomes[$oldoutcome]->id);
                            }
                            $dbrec->outcomeid = $outcomes[$oldoutcome]->id;
                        }
                        $grade_item = new grade_item($dbrec, false);
                        $grade_item->insert('restore');
                        if ($restoreall) {
                            // set original parent if restored
                            $oldcat = $info['GRADE_ITEM']['#']['CATEGORYID']['0']['#'];
                            if (!empty($cached_categories[$oldcat])) {
                                $grade_item->set_parent($cached_categories[$oldcat]->id);
                            }
                        }
                        $status = backup_putid($restore->backup_unique_code, "grade_items", $rec->old_id, $grade_item->id) && $status;
                    }
                    // no need to restore grades if user data is not selected or importing activities
                    if ($importing or $grade_item->itemtype == 'mod' and !restore_userdata_selected($restore, $grade_item->itemmodule, $olditeminstance)) {
                        // module instance not selected when restored using granular
                        // skip this item
                        continue;
                    }
                    /// now, restore grade_grades
                    if (!empty($info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']['GRADE'])) {
                        //Iterate over items
                        foreach ($info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']['GRADE'] as $g_info) {
                            $grade = new grade_grade();
                            $grade->itemid = $grade_item->id;
                            $olduser = backup_todb($g_info['#']['USERID']['0']['#'], false);
                            $user = backup_getid($restore->backup_unique_code, "user", $olduser);
                            $grade->userid = $user->new_id;
                            $grade->rawgrade = backup_todb($g_info['#']['RAWGRADE']['0']['#'], false);
                            $grade->rawgrademax = backup_todb($g_info['#']['RAWGRADEMAX']['0']['#'], false);
                            $grade->rawgrademin = backup_todb($g_info['#']['RAWGRADEMIN']['0']['#'], false);
                            // need to find scaleid
                            if (backup_todb($g_info['#']['RAWSCALEID']['0']['#'])) {
                                $scale = backup_getid($restore->backup_unique_code, "scale", backup_todb($g_info['#']['RAWSCALEID']['0']['#'], false));
                                $grade->rawscaleid = $scale->new_id;
                            }
                            if (backup_todb($g_info['#']['USERMODIFIED']['0']['#'])) {
                                if ($modifier = backup_getid($restore->backup_unique_code, "user", backup_todb($g_info['#']['USERMODIFIED']['0']['#'], false))) {
                                    $grade->usermodified = $modifier->new_id;
                                }
                            }
                            $grade->finalgrade = backup_todb($g_info['#']['FINALGRADE']['0']['#'], false);
                            $grade->hidden = backup_todb($g_info['#']['HIDDEN']['0']['#'], false);
                            $grade->locked = backup_todb($g_info['#']['LOCKED']['0']['#'], false);
                            $grade->locktime = backup_todb($g_info['#']['LOCKTIME']['0']['#'], false);
                            $grade->exported = backup_todb($g_info['#']['EXPORTED']['0']['#'], false);
                            $grade->overridden = backup_todb($g_info['#']['OVERRIDDEN']['0']['#'], false);
                            $grade->excluded = backup_todb($g_info['#']['EXCLUDED']['0']['#'], false);
                            $grade->feedback = backup_todb($g_info['#']['FEEDBACK']['0']['#'], false);
                            $grade->feedbackformat = backup_todb($g_info['#']['FEEDBACKFORMAT']['0']['#'], false);
                            $grade->information = backup_todb($g_info['#']['INFORMATION']['0']['#'], false);
                            $grade->informationformat = backup_todb($g_info['#']['INFORMATIONFORMAT']['0']['#'], false);
                            $grade->timecreated = backup_todb($g_info['#']['TIMECREATED']['0']['#'], false);
                            $grade->timemodified = backup_todb($g_info['#']['TIMEMODIFIED']['0']['#'], false);
                            $grade->insert('restore');
                            backup_putid($restore->backup_unique_code, "grade_grades", backup_todb($g_info['#']['ID']['0']['#']), $grade->id);
                            $counter++;
                            if ($counter % 20 == 0) {
                                if (!defined('RESTORE_SILENTLY')) {
                                    echo ".";
                                    if ($counter % 400 == 0) {
                                        echo "<br />";
                                    }
                                }
                                backup_flush(300);
                            }
                        }
                    }
                }
            }
        }
    }
    /// add outcomes that are not used when doing full restore
    if ($status and $restoreall) {
        foreach ($outcomes as $oldoutcome => $grade_outcome) {
            if (empty($grade_outcome->id)) {
                $grade_outcome->insert('restore');
                $grade_outcome->use_in($restore->course_id);
                backup_putid($restore->backup_unique_code, "grade_outcomes", $oldoutcome, $grade_outcome->id);
            }
        }
    }
    if ($status and !$importing and $restore_histories) {
        /// following code is very inefficient
        $gchcount = count_records('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_categories_history');
        $gghcount = count_records('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_grades_history');
        $gihcount = count_records('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_items_history');
        $gohcount = count_records('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_outcomes_history');
        // Number of records to get in every chunk
        $recordset_size = 2;
        // process histories
        if ($gchcount && $status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo '<li>' . get_string('gradecategoryhistory', 'grades') . '</li>';
            }
            $counter = 0;
            while ($counter < $gchcount) {
                //Fetch recordset_size records in each iteration
                $recs = get_records_select("backup_ids", "table_name = 'grade_categories_history' AND backup_code = '{$restore->backup_unique_code}'", "old_id", "old_id", $counter, $recordset_size);
                if ($recs) {
                    foreach ($recs as $rec) {
                        //Get the full record from backup_ids
                        $data = backup_getid($restore->backup_unique_code, 'grade_categories_history', $rec->old_id);
                        if ($data) {
                            //Now get completed xmlized object
                            $info = $data->info;
                            //traverse_xmlize($info);                            //Debug
                            //print_object ($GLOBALS['traverse_array']);         //Debug
                            //$GLOBALS['traverse_array']="";                     //Debug
                            $oldobj = backup_getid($restore->backup_unique_code, "grade_categories", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['OLDID']['0']['#']));
                            if (empty($oldobj->new_id)) {
                                // if the old object is not being restored, can't restoring its history
                                $counter++;
                                continue;
                            }
                            $dbrec->oldid = $oldobj->new_id;
                            $dbrec->action = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['ACTION']['0']['#']);
                            $dbrec->source = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['SOURCE']['0']['#']);
                            $dbrec->timemodified = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
                            // loggeduser might not be restored, e.g. admin
                            if ($oldobj = backup_getid($restore->backup_unique_code, "user", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
                                $dbrec->loggeduser = $oldobj->new_id;
                            }
                            // this item might not have a parent at all, do not skip it if no parent is specified
                            if (backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PARENT']['0']['#'])) {
                                $oldobj = backup_getid($restore->backup_unique_code, "grade_categories", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PARENT']['0']['#']));
                                if (empty($oldobj->new_id)) {
                                    // if the parent category not restored
                                    $counter++;
                                    continue;
                                }
                            }
                            $dbrec->parent = $oldobj->new_id;
                            $dbrec->depth = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['DEPTH']['0']['#']);
                            // path needs to be rebuilt
                            if ($path = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PATH']['0']['#'])) {
                                // to preserve the path and make it work, we need to replace the categories one by one
                                // we first get the list of categories in current path
                                if ($paths = explode("/", $path)) {
                                    $newpath = '';
                                    foreach ($paths as $catid) {
                                        if ($catid) {
                                            // find the new corresponding path
                                            $oldpath = backup_getid($restore->backup_unique_code, "grade_categories", $catid);
                                            $newpath .= "/{$oldpath->new_id}";
                                        }
                                    }
                                    $dbrec->path = $newpath;
                                }
                            }
                            $dbrec->fullname = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['FULLNAME']['0']['#']);
                            $dbrec->aggregation = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGRETGATION']['0']['#']);
                            $dbrec->keephigh = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['KEEPHIGH']['0']['#']);
                            $dbrec->droplow = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['DROPLOW']['0']['#']);
                            $dbrec->aggregateonlygraded = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGREGATEONLYGRADED']['0']['#']);
                            $dbrec->aggregateoutcomes = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGREGATEOUTCOMES']['0']['#']);
                            $dbrec->aggregatesubcats = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGREGATESUBCATS']['0']['#']);
                            $dbrec->courseid = $restore->course_id;
                            insert_record('grade_categories_history', $dbrec);
                            unset($dbrec);
                        }
                        //Increment counters
                        $counter++;
                        //Do some output
                        if ($counter % 1 == 0) {
                            if (!defined('RESTORE_SILENTLY')) {
                                echo ".";
                                if ($counter % 20 == 0) {
                                    echo "<br />";
                                }
                            }
                            backup_flush(300);
                        }
                    }
                }
            }
        }
        // process histories
        if ($gghcount && $status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo '<li>' . get_string('gradegradeshistory', 'grades') . '</li>';
            }
            $counter = 0;
            while ($counter < $gghcount) {
                //Fetch recordset_size records in each iteration
                $recs = get_records_select("backup_ids", "table_name = 'grade_grades_history' AND backup_code = '{$restore->backup_unique_code}'", "old_id", "old_id", $counter, $recordset_size);
                if ($recs) {
                    foreach ($recs as $rec) {
                        //Get the full record from backup_ids
                        $data = backup_getid($restore->backup_unique_code, 'grade_grades_history', $rec->old_id);
                        if ($data) {
                            //Now get completed xmlized object
                            $info = $data->info;
                            //traverse_xmlize($info);                            //Debug
                            //print_object ($GLOBALS['traverse_array']);         //Debug
                            //$GLOBALS['traverse_array']="";                     //Debug
                            $oldobj = backup_getid($restore->backup_unique_code, "grade_grades", backup_todb($info['GRADE_GRADES_HISTORY']['#']['OLDID']['0']['#']));
                            if (empty($oldobj->new_id)) {
                                // if the old object is not being restored, can't restoring its history
                                $counter++;
                                continue;
                            }
                            $dbrec->oldid = $oldobj->new_id;
                            $dbrec->action = backup_todb($info['GRADE_GRADES_HISTORY']['#']['ACTION']['0']['#']);
                            $dbrec->source = backup_todb($info['GRADE_GRADES_HISTORY']['#']['SOURCE']['0']['#']);
                            $dbrec->timemodified = backup_todb($info['GRADE_GRADES_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
                            if ($oldobj = backup_getid($restore->backup_unique_code, "user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
                                $dbrec->loggeduser = $oldobj->new_id;
                            }
                            $oldobj = backup_getid($restore->backup_unique_code, "grade_items", backup_todb($info['GRADE_GRADES_HISTORY']['#']['ITEMID']['0']['#']));
                            $dbrec->itemid = $oldobj->new_id;
                            if (empty($dbrec->itemid)) {
                                $counter++;
                                continue;
                                // grade item not being restored
                            }
                            $oldobj = backup_getid($restore->backup_unique_code, "user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['USERID']['0']['#']));
                            $dbrec->userid = $oldobj->new_id;
                            $dbrec->rawgrade = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADE']['0']['#']);
                            $dbrec->rawgrademax = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADEMAX']['0']['#']);
                            $dbrec->rawgrademin = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADEMIN']['0']['#']);
                            if ($oldobj = backup_getid($restore->backup_unique_code, "user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['USERMODIFIED']['0']['#']))) {
                                $dbrec->usermodified = $oldobj->new_id;
                            }
                            if (backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWSCALEID']['0']['#'])) {
                                $scale = backup_getid($restore->backup_unique_code, "scale", backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWSCALEID']['0']['#']));
                                $dbrec->rawscaleid = $scale->new_id;
                            }
                            $dbrec->finalgrade = backup_todb($info['GRADE_GRADES_HISTORY']['#']['FINALGRADE']['0']['#']);
                            $dbrec->hidden = backup_todb($info['GRADE_GRADES_HISTORY']['#']['HIDDEN']['0']['#']);
                            $dbrec->locked = backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOCKED']['0']['#']);
                            $dbrec->locktime = backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOCKTIME']['0']['#']);
                            $dbrec->exported = backup_todb($info['GRADE_GRADES_HISTORY']['#']['EXPORTED']['0']['#']);
                            $dbrec->overridden = backup_todb($info['GRADE_GRADES_HISTORY']['#']['OVERRIDDEN']['0']['#']);
                            $dbrec->excluded = backup_todb($info['GRADE_GRADES_HISTORY']['#']['EXCLUDED']['0']['#']);
                            $dbrec->feedback = backup_todb($info['GRADE_TEXT_HISTORY']['#']['FEEDBACK']['0']['#']);
                            $dbrec->feedbackformat = backup_todb($info['GRADE_TEXT_HISTORY']['#']['FEEDBACKFORMAT']['0']['#']);
                            $dbrec->information = backup_todb($info['GRADE_TEXT_HISTORY']['#']['INFORMATION']['0']['#']);
                            $dbrec->informationformat = backup_todb($info['GRADE_TEXT_HISTORY']['#']['INFORMATIONFORMAT']['0']['#']);
                            insert_record('grade_grades_history', $dbrec);
                            unset($dbrec);
                        }
                        //Increment counters
                        $counter++;
                        //Do some output
                        if ($counter % 1 == 0) {
                            if (!defined('RESTORE_SILENTLY')) {
                                echo ".";
                                if ($counter % 20 == 0) {
                                    echo "<br />";
                                }
                            }
                            backup_flush(300);
                        }
                    }
                }
            }
        }
        // process histories
        if ($gihcount && $status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo '<li>' . get_string('gradeitemshistory', 'grades') . '</li>';
            }
            $counter = 0;
            while ($counter < $gihcount) {
                //Fetch recordset_size records in each iteration
                $recs = get_records_select("backup_ids", "table_name = 'grade_items_history' AND backup_code = '{$restore->backup_unique_code}'", "old_id", "old_id", $counter, $recordset_size);
                if ($recs) {
                    foreach ($recs as $rec) {
                        //Get the full record from backup_ids
                        $data = backup_getid($restore->backup_unique_code, 'grade_items_history', $rec->old_id);
                        if ($data) {
                            //Now get completed xmlized object
                            $info = $data->info;
                            //traverse_xmlize($info);                            //Debug
                            //print_object ($GLOBALS['traverse_array']);         //Debug
                            //$GLOBALS['traverse_array']="";                     //Debug
                            $oldobj = backup_getid($restore->backup_unique_code, "grade_items", backup_todb($info['GRADE_ITEM_HISTORY']['#']['OLDID']['0']['#']));
                            if (empty($oldobj->new_id)) {
                                // if the old object is not being restored, can't restoring its history
                                $counter++;
                                continue;
                            }
                            $dbrec->oldid = $oldobj->new_id;
                            $dbrec->action = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ACTION']['0']['#']);
                            $dbrec->source = backup_todb($info['GRADE_ITEM_HISTORY']['#']['SOURCE']['0']['#']);
                            $dbrec->timemodified = backup_todb($info['GRADE_ITEM_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
                            if ($oldobj = backup_getid($restore->backup_unique_code, "user", backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
                                $dbrec->loggeduser = $oldobj->new_id;
                            }
                            $dbrec->courseid = $restore->course_id;
                            $oldobj = backup_getid($restore->backup_unique_code, 'grade_categories', backup_todb($info['GRADE_ITEM_HISTORY']['#']['CATEGORYID']['0']['#']));
                            $oldobj->categoryid = $category->new_id;
                            if (empty($oldobj->categoryid)) {
                                $counter++;
                                continue;
                                // category not restored
                            }
                            $dbrec->itemname = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMNAME']['0']['#']);
                            $dbrec->itemtype = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMTYPE']['0']['#']);
                            $dbrec->itemmodule = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMMODULE']['0']['#']);
                            // code from grade_items restore
                            $iteminstance = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMINSTANCE']['0']['#']);
                            // do not restore if this grade_item is a mod, and
                            if ($dbrec->itemtype == 'mod') {
                                if (!restore_userdata_selected($restore, $dbrec->itemmodule, $iteminstance)) {
                                    // module instance not selected when restored using granular
                                    // skip this item
                                    $counter++;
                                    continue;
                                }
                                // iteminstance should point to new mod
                                $mod = backup_getid($restore->backup_unique_code, $dbrec->itemmodule, $iteminstance);
                                $dbrec->iteminstance = $mod->new_id;
                            } else {
                                if ($dbrec->itemtype == 'category') {
                                    // the item instance should point to the new grade category
                                    // only proceed if we are restoring all grade items
                                    if ($restoreall) {
                                        $category = backup_getid($restore->backup_unique_code, 'grade_categories', $iteminstance);
                                        $dbrec->iteminstance = $category->new_id;
                                    } else {
                                        // otherwise we can safely ignore this grade item and subsequent
                                        // grade_raws, grade_finals etc
                                        continue;
                                    }
                                } elseif ($dbrec->itemtype == 'course') {
                                    // We don't restore course type to avoid duplicate course items
                                    if ($restoreall) {
                                        // TODO any special code needed here to restore course item without duplicating it?
                                        // find the course category with depth 1, and course id = current course id
                                        // this would have been already restored
                                        $cat = get_record('grade_categories', 'depth', 1, 'courseid', $restore->course_id);
                                        $dbrec->iteminstance = $cat->id;
                                    } else {
                                        $counter++;
                                        continue;
                                    }
                                }
                            }
                            $dbrec->itemnumber = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMNUMBER']['0']['#']);
                            $dbrec->iteminfo = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMINFO']['0']['#']);
                            $dbrec->idnumber = backup_todb($info['GRADE_ITEM_HISTORY']['#']['IDNUMBER']['0']['#']);
                            $dbrec->calculation = backup_todb($info['GRADE_ITEM_HISTORY']['#']['CALCULATION']['0']['#']);
                            $dbrec->gradetype = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADETYPE']['0']['#']);
                            $dbrec->grademax = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEMAX']['0']['#']);
                            $dbrec->grademin = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEMIN']['0']['#']);
                            if ($oldobj = backup_getid($restore->backup_unique_code, "scale", backup_todb($info['GRADE_ITEM_HISTORY']['#']['SCALEID']['0']['#']))) {
                                // scaleid is optional
                                $dbrec->scaleid = $oldobj->new_id;
                            }
                            if ($oldobj = backup_getid($restore->backup_unique_code, "grade_outcomes", backup_todb($info['GRADE_ITEM_HISTORY']['#']['OUTCOMEID']['0']['#']))) {
                                // outcome is optional
                                $dbrec->outcomeid = $oldobj->new_id;
                            }
                            $dbrec->gradepass = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEPASS']['0']['#']);
                            $dbrec->multfactor = backup_todb($info['GRADE_ITEM_HISTORY']['#']['MULTFACTOR']['0']['#']);
                            $dbrec->plusfactor = backup_todb($info['GRADE_ITEM_HISTORY']['#']['PLUSFACTOR']['0']['#']);
                            $dbrec->aggregationcoef = backup_todb($info['GRADE_ITEM_HISTORY']['#']['AGGREGATIONCOEF']['0']['#']);
                            $dbrec->sortorder = backup_todb($info['GRADE_ITEM_HISTORY']['#']['SORTORDER']['0']['#']);
                            $dbrec->display = backup_todb($info['GRADE_ITEM_HISTORY']['#']['DISPLAY']['0']['#']);
                            $dbrec->decimals = backup_todb($info['GRADE_ITEM_HISTORY']['#']['DECIMALS']['0']['#']);
                            $dbrec->hidden = backup_todb($info['GRADE_ITEM_HISTORY']['#']['HIDDEN']['0']['#']);
                            $dbrec->locked = backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOCKED']['0']['#']);
                            $dbrec->locktime = backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOCKTIME']['0']['#']);
                            $dbrec->needsupdate = backup_todb($info['GRADE_ITEM_HISTORY']['#']['NEEDSUPDATE']['0']['#']);
                            insert_record('grade_items_history', $dbrec);
                            unset($dbrec);
                        }
                        //Increment counters
                        $counter++;
                        //Do some output
                        if ($counter % 1 == 0) {
                            if (!defined('RESTORE_SILENTLY')) {
                                echo ".";
                                if ($counter % 20 == 0) {
                                    echo "<br />";
                                }
                            }
                            backup_flush(300);
                        }
                    }
                }
            }
        }
        // process histories
        if ($gohcount && $status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo '<li>' . get_string('gradeoutcomeshistory', 'grades') . '</li>';
            }
            $counter = 0;
            while ($counter < $gohcount) {
                //Fetch recordset_size records in each iteration
                $recs = get_records_select("backup_ids", "table_name = 'grade_outcomes_history' AND backup_code = '{$restore->backup_unique_code}'", "old_id", "old_id", $counter, $recordset_size);
                if ($recs) {
                    foreach ($recs as $rec) {
                        //Get the full record from backup_ids
                        $data = backup_getid($restore->backup_unique_code, 'grade_outcomes_history', $rec->old_id);
                        if ($data) {
                            //Now get completed xmlized object
                            $info = $data->info;
                            //traverse_xmlize($info);                            //Debug
                            //print_object ($GLOBALS['traverse_array']);         //Debug
                            //$GLOBALS['traverse_array']="";                     //Debug
                            $oldobj = backup_getid($restore->backup_unique_code, "grade_outcomes", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['OLDID']['0']['#']));
                            if (empty($oldobj->new_id)) {
                                // if the old object is not being restored, can't restoring its history
                                $counter++;
                                continue;
                            }
                            $dbrec->oldid = $oldobj->new_id;
                            $dbrec->action = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['ACTION']['0']['#']);
                            $dbrec->source = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SOURCE']['0']['#']);
                            $dbrec->timemodified = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
                            if ($oldobj = backup_getid($restore->backup_unique_code, "user", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
                                $dbrec->loggeduser = $oldobj->new_id;
                            }
                            $dbrec->courseid = $restore->course_id;
                            $dbrec->shortname = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SHORTNAME']['0']['#']);
                            $dbrec->fullname = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['FULLNAME']['0']['#']);
                            $oldobj = backup_getid($restore->backup_unique_code, "scale", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SCALEID']['0']['#']));
                            $dbrec->scaleid = $oldobj->new_id;
                            $dbrec->description = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['DESCRIPTION']['0']['#']);
                            insert_record('grade_outcomes_history', $dbrec);
                            unset($dbrec);
                        }
                        //Increment counters
                        $counter++;
                        //Do some output
                        if ($counter % 1 == 0) {
                            if (!defined('RESTORE_SILENTLY')) {
                                echo ".";
                                if ($counter % 20 == 0) {
                                    echo "<br />";
                                }
                            }
                            backup_flush(300);
                        }
                    }
                }
            }
        }
    }
    if (!defined('RESTORE_SILENTLY')) {
        //End ul
        echo '</ul>';
    }
    return $status;
}
Exemple #17
0
 /**
  * Helper function to assert that a module has correctly been made visible, or hidden.
  *
  * @param stdClass $mod module information
  * @param int $visibility the current state of the module
  * @param int $visibleold the current state of the visibleold property
  * @return void
  */
 public function check_module_visibility($mod, $visibility, $visibleold)
 {
     global $DB;
     $cm = get_fast_modinfo($mod->course)->get_cm($mod->cmid);
     $this->assertEquals($visibility, $cm->visible);
     $this->assertEquals($visibleold, $cm->visibleold);
     // Check the module grade items.
     $grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $cm->modname, 'iteminstance' => $cm->instance, 'courseid' => $cm->course));
     if ($grade_items) {
         foreach ($grade_items as $grade_item) {
             if ($visibility) {
                 $this->assertFalse($grade_item->is_hidden(), "{$cm->modname} grade_item not visible");
             } else {
                 $this->assertTrue($grade_item->is_hidden(), "{$cm->modname} grade_item not hidden");
             }
         }
     }
     // Check the events visibility.
     if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $cm->modname))) {
         foreach ($events as $event) {
             $calevent = new calendar_event($event);
             $this->assertEquals($visibility, $calevent->visible, "{$cm->modname} calendar_event visibility");
         }
     }
 }
Exemple #18
0
 /**
  * Sets the grade_item's hidden variable and updates the grade_item.
  * Method named after grade_item::set_hidden().
  * @param int $hidden 0, 1 or a timestamp int(10) after which date the item will be hidden.
  * @param boolean $cascade apply to child objects too
  * @return void
  */
 function set_hidden($hidden, $cascade = false)
 {
     $this->load_grade_item();
     $this->grade_item->set_hidden($hidden);
     if ($cascade) {
         if ($children = grade_item::fetch_all(array('categoryid' => $this->id))) {
             foreach ($children as $child) {
                 $child->set_hidden($hidden, $cascade);
             }
         }
         if ($children = grade_category::fetch_all(array('parent' => $this->id))) {
             foreach ($children as $child) {
                 $child->set_hidden($hidden, $cascade);
             }
         }
     }
 }
Exemple #19
0
 protected function sub_test_grade_item_fetch_all()
 {
     $grade_item = new grade_item();
     $this->assertTrue(method_exists($grade_item, 'fetch_all'));
     $grade_items = grade_item::fetch_all(array('courseid' => $this->courseid));
     $this->assertEquals(count($this->grade_items), count($grade_items) - 1);
     // -1 to account for the course grade item.
 }
Exemple #20
0
 /**
  * Set the grade item categories when editing an instance
  */
 public function definition_after_data()
 {
     $mform =& $this->_form;
     if ($id = $mform->getElementValue('update')) {
         $instance = $mform->getElementValue('instance');
         $gradeitems = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => 'workshop', 'iteminstance' => $instance, 'courseid' => $this->course->id));
         if (!empty($gradeitems)) {
             foreach ($gradeitems as $gradeitem) {
                 // here comes really crappy way how to set the value of the fields
                 // gradecategory and gradinggradecategory - grrr QuickForms
                 $decimalpoints = $gradeitem->get_decimals();
                 if ($gradeitem->itemnumber == 0) {
                     $submissiongradepass = $mform->getElement('submissiongradepass');
                     $submissiongradepass->setValue(format_float($gradeitem->gradepass, $decimalpoints));
                     $group = $mform->getElement('submissiongradegroup');
                     $elements = $group->getElements();
                     foreach ($elements as $element) {
                         if ($element->getName() == 'gradecategory') {
                             $element->setValue($gradeitem->categoryid);
                         }
                     }
                 } else {
                     if ($gradeitem->itemnumber == 1) {
                         $gradinggradepass = $mform->getElement('gradinggradepass');
                         $gradinggradepass->setValue(format_float($gradeitem->gradepass, $decimalpoints));
                         $group = $mform->getElement('gradinggradegroup');
                         $elements = $group->getElements();
                         foreach ($elements as $element) {
                             if ($element->getName() == 'gradinggradecategory') {
                                 $element->setValue($gradeitem->categoryid);
                             }
                         }
                     }
                 }
             }
         }
     }
     parent::definition_after_data();
 }
/**
 * Get and update/create grade item for legacy modules.
 */
function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)
{
    // does it already exist?
    if ($grade_items = grade_item::fetch_all(array('courseid' => $modinstance->course, 'itemtype' => 'mod', 'itemmodule' => $modinstance->modname, 'iteminstance' => $modinstance->id, 'itemnumber' => 0))) {
        if (count($grade_items) > 1) {
            debugging('Multiple legacy grade_items found.');
            return false;
        }
        $grade_item = reset($grade_items);
        if (is_null($grademax) and is_null($scaleid)) {
            $grade_item->gradetype = GRADE_TYPE_NONE;
        } else {
            if ($scaleid) {
                $grade_item->gradetype = GRADE_TYPE_SCALE;
                $grade_item->scaleid = $scaleid;
                $grade_item->grademin = 1;
            } else {
                $grade_item->gradetype = GRADE_TYPE_VALUE;
                $grade_item->grademax = $grademax;
                $grade_item->grademin = 0;
            }
        }
        $grade_item->itemname = $modinstance->name;
        $grade_item->idnumber = $modinstance->cmidnumber;
        $grade_item->update();
        return $grade_item;
    }
    // create new one
    $params = array('courseid' => $modinstance->course, 'itemtype' => 'mod', 'itemmodule' => $modinstance->modname, 'iteminstance' => $modinstance->id, 'itemnumber' => 0, 'itemname' => $modinstance->name, 'idnumber' => $modinstance->cmidnumber);
    if (is_null($grademax) and is_null($scaleid)) {
        $params['gradetype'] = GRADE_TYPE_NONE;
    } else {
        if ($scaleid) {
            $params['gradetype'] = GRADE_TYPE_SCALE;
            $params['scaleid'] = $scaleid;
            $grade_item->grademin = 1;
        } else {
            $params['gradetype'] = GRADE_TYPE_VALUE;
            $params['grademax'] = $grademax;
            $params['grademin'] = 0;
        }
    }
    $grade_item = new grade_item($params);
    $grade_item->insert();
    return $grade_item;
}
Exemple #22
0
 /**
  * Adds all the standard elements to a form to edit the settings for an activity module.
  */
 function standard_coursemodule_elements()
 {
     global $COURSE, $CFG, $DB;
     $mform =& $this->_form;
     $this->_outcomesused = false;
     if ($this->_features->outcomes) {
         if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
             $this->_outcomesused = true;
             $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
             foreach ($outcomes as $outcome) {
                 $mform->addElement('advcheckbox', 'outcome_' . $outcome->id, $outcome->get_name());
             }
         }
     }
     if ($this->_features->rating) {
         require_once $CFG->dirroot . '/rating/lib.php';
         $rm = new rating_manager();
         $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
         $permission = CAP_ALLOW;
         $rolenamestring = null;
         if (!empty($this->_cm)) {
             $context = context_module::instance($this->_cm->id);
             $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/' . $this->_cm->modname . ':rate'));
             $rolenamestring = implode(', ', $rolenames);
         } else {
             $rolenamestring = get_string('capabilitychecknotavailable', 'rating');
         }
         $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring);
         $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
         $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating'), $rm->get_aggregate_types());
         $mform->setDefault('assessed', 0);
         $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
         $mform->addElement('modgrade', 'scale', get_string('scale'), false);
         $mform->disabledIf('scale', 'assessed', 'eq', 0);
         $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
         $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
         $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
         $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
         $mform->disabledIf('assesstimestart', 'ratingtime');
         $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
         $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
         $mform->disabledIf('assesstimefinish', 'ratingtime');
     }
     //doing this here means splitting up the grade related settings on the lesson settings page
     //$this->standard_grading_coursemodule_elements();
     $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
     if ($this->_features->groups) {
         $options = array(NOGROUPS => get_string('groupsnone'), SEPARATEGROUPS => get_string('groupsseparate'), VISIBLEGROUPS => get_string('groupsvisible'));
         $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
         $mform->addHelpButton('groupmode', 'groupmode', 'group');
     }
     if ($this->_features->groupings or $this->_features->groupmembersonly) {
         //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
         $options = array();
         $options[0] = get_string('none');
         if ($groupings = $DB->get_records('groupings', array('courseid' => $COURSE->id))) {
             foreach ($groupings as $grouping) {
                 $options[$grouping->id] = format_string($grouping->name);
             }
         }
         $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
         $mform->addHelpButton('groupingid', 'grouping', 'group');
         $mform->setAdvanced('groupingid');
     }
     if ($this->_features->groupmembersonly) {
         $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group'));
         $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group');
         $mform->setAdvanced('groupmembersonly');
     }
     $mform->addElement('modvisible', 'visible', get_string('visible'));
     if (!empty($this->_cm)) {
         $context = context_module::instance($this->_cm->id);
         if (!has_capability('moodle/course:activityvisibility', $context)) {
             $mform->hardFreeze('visible');
         }
     }
     if ($this->_features->idnumber) {
         $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
         $mform->addHelpButton('cmidnumber', 'idnumbermod');
     }
     if (!empty($CFG->enableavailability)) {
         // String used by conditions
         $strnone = get_string('none', 'condition');
         // Conditional availability
         // Available from/to defaults to midnight because then the display
         // will be nicer where it tells users when they can access it (it
         // shows only the date and not time).
         $date = usergetdate(time());
         $midnight = make_timestamp($date['year'], $date['mon'], $date['mday']);
         // From/until controls
         $mform->addElement('header', 'availabilityconditionsheader', get_string('availabilityconditions', 'condition'));
         $mform->addElement('date_time_selector', 'availablefrom', get_string('availablefrom', 'condition'), array('optional' => true, 'defaulttime' => $midnight));
         $mform->addHelpButton('availablefrom', 'availablefrom', 'condition');
         $mform->addElement('date_time_selector', 'availableuntil', get_string('availableuntil', 'condition'), array('optional' => true, 'defaulttime' => $midnight));
         // Conditions based on grades
         $gradeoptions = array();
         $items = grade_item::fetch_all(array('courseid' => $COURSE->id));
         $items = $items ? $items : array();
         foreach ($items as $id => $item) {
             // Do not include grades for current item
             if (!empty($this->_cm) && $this->_cm->instance == $item->iteminstance && $this->_cm->modname == $item->itemmodule && $item->itemtype == 'mod') {
                 continue;
             }
             $gradeoptions[$id] = $item->get_name();
         }
         asort($gradeoptions);
         $gradeoptions = array(0 => $strnone) + $gradeoptions;
         $grouparray = array();
         $grouparray[] =& $mform->createElement('select', 'conditiongradeitemid', '', $gradeoptions);
         $grouparray[] =& $mform->createElement('static', '', '', ' ' . get_string('grade_atleast', 'condition') . ' ');
         $grouparray[] =& $mform->createElement('text', 'conditiongrademin', '', array('size' => 3));
         $grouparray[] =& $mform->createElement('static', '', '', '% ' . get_string('grade_upto', 'condition') . ' ');
         $grouparray[] =& $mform->createElement('text', 'conditiongrademax', '', array('size' => 3));
         $grouparray[] =& $mform->createElement('static', '', '', '%');
         $group = $mform->createElement('group', 'conditiongradegroup', get_string('gradecondition', 'condition'), $grouparray);
         // Get version with condition info and store it so we don't ask
         // twice
         if (!empty($this->_cm)) {
             $ci = new condition_info($this->_cm, CONDITION_MISSING_EXTRATABLE);
             $this->_cm = $ci->get_full_course_module();
             $count = count($this->_cm->conditionsgrade) + 1;
             $fieldcount = count($this->_cm->conditionsfield) + 1;
         } else {
             $count = 1;
             $fieldcount = 1;
         }
         $this->repeat_elements(array($group), $count, array(), 'conditiongraderepeats', 'conditiongradeadds', 2, get_string('addgrades', 'condition'), true);
         $mform->addHelpButton('conditiongradegroup[0]', 'gradecondition', 'condition');
         // Conditions based on user fields
         $operators = condition_info::get_condition_user_field_operators();
         $useroptions = condition_info::get_condition_user_fields();
         asort($useroptions);
         $useroptions = array(0 => $strnone) + $useroptions;
         $grouparray = array();
         $grouparray[] =& $mform->createElement('select', 'conditionfield', '', $useroptions);
         $grouparray[] =& $mform->createElement('select', 'conditionfieldoperator', '', $operators);
         $grouparray[] =& $mform->createElement('text', 'conditionfieldvalue');
         $mform->setType('conditionfieldvalue', PARAM_RAW);
         $group = $mform->createElement('group', 'conditionfieldgroup', get_string('userfield', 'condition'), $grouparray);
         $this->repeat_elements(array($group), $fieldcount, array(), 'conditionfieldrepeats', 'conditionfieldadds', 2, get_string('adduserfields', 'condition'), true);
         $mform->addHelpButton('conditionfieldgroup[0]', 'userfield', 'condition');
         // Conditions based on completion
         $completion = new completion_info($COURSE);
         if ($completion->is_enabled()) {
             $completionoptions = array();
             $modinfo = get_fast_modinfo($COURSE);
             foreach ($modinfo->cms as $id => $cm) {
                 // Add each course-module if it:
                 // (a) has completion turned on
                 // (b) is not the same as current course-module
                 if ($cm->completion && (empty($this->_cm) || $this->_cm->id != $id)) {
                     $completionoptions[$id] = $cm->name;
                 }
             }
             asort($completionoptions);
             $completionoptions = array(0 => $strnone) + $completionoptions;
             $completionvalues = array(COMPLETION_COMPLETE => get_string('completion_complete', 'condition'), COMPLETION_INCOMPLETE => get_string('completion_incomplete', 'condition'), COMPLETION_COMPLETE_PASS => get_string('completion_pass', 'condition'), COMPLETION_COMPLETE_FAIL => get_string('completion_fail', 'condition'));
             $grouparray = array();
             $grouparray[] =& $mform->createElement('select', 'conditionsourcecmid', '', $completionoptions);
             $grouparray[] =& $mform->createElement('select', 'conditionrequiredcompletion', '', $completionvalues);
             $group = $mform->createElement('group', 'conditioncompletiongroup', get_string('completioncondition', 'condition'), $grouparray);
             $count = empty($this->_cm) ? 1 : count($this->_cm->conditionscompletion) + 1;
             $this->repeat_elements(array($group), $count, array(), 'conditioncompletionrepeats', 'conditioncompletionadds', 2, get_string('addcompletions', 'condition'), true);
             $mform->addHelpButton('conditioncompletiongroup[0]', 'completioncondition', 'condition');
         }
         // Do we display availability info to students?
         $mform->addElement('select', 'showavailability', get_string('showavailability', 'condition'), array(CONDITION_STUDENTVIEW_SHOW => get_string('showavailability_show', 'condition'), CONDITION_STUDENTVIEW_HIDE => get_string('showavailability_hide', 'condition')));
         $mform->setDefault('showavailability', CONDITION_STUDENTVIEW_SHOW);
     }
     // Conditional activities: completion tracking section
     if (!isset($completion)) {
         $completion = new completion_info($COURSE);
     }
     if ($completion->is_enabled()) {
         $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
         // Unlock button for if people have completed it (will
         // be removed in definition_after_data if they haven't)
         $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
         $mform->registerNoSubmitButton('unlockcompletion');
         $mform->addElement('hidden', 'completionunlocked', 0);
         $mform->setType('completionunlocked', PARAM_INT);
         $mform->addElement('select', 'completion', get_string('completion', 'completion'), array(COMPLETION_TRACKING_NONE => get_string('completion_none', 'completion'), COMPLETION_TRACKING_MANUAL => get_string('completion_manual', 'completion')));
         $mform->setDefault('completion', $this->_features->defaultcompletion ? COMPLETION_TRACKING_MANUAL : COMPLETION_TRACKING_NONE);
         $mform->addHelpButton('completion', 'completion', 'completion');
         // Automatic completion once you view it
         $gotcompletionoptions = false;
         if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
             $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'), get_string('completionview_desc', 'completion'));
             $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
             $gotcompletionoptions = true;
         }
         // Automatic completion once it's graded
         if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
             $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'), get_string('completionusegrade_desc', 'completion'));
             $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
             $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
             $gotcompletionoptions = true;
         }
         // Automatic completion according to module-specific rules
         $this->_customcompletionelements = $this->add_completion_rules();
         foreach ($this->_customcompletionelements as $element) {
             $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
         }
         $gotcompletionoptions = $gotcompletionoptions || count($this->_customcompletionelements) > 0;
         // Automatic option only appears if possible
         if ($gotcompletionoptions) {
             $mform->getElement('completion')->addOption(get_string('completion_automatic', 'completion'), COMPLETION_TRACKING_AUTOMATIC);
         }
         // Completion expected at particular date? (For progress tracking)
         $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional' => true));
         $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
         $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
     }
     $this->standard_hidden_coursemodule_elements();
 }
 /**
  * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
  */
 function definition_after_data()
 {
     global $CFG, $COURSE;
     $mform =& $this->_form;
     if ($id = $mform->getElementValue('update')) {
         $modulename = $mform->getElementValue('modulename');
         $instance = $mform->getElementValue('instance');
         if ($this->_features->gradecat) {
             $gradecat = false;
             if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
                 $outcomes = grade_outcome::fetch_all_available($COURSE->id);
                 if (!empty($outcomes)) {
                     $gradecat = true;
                 }
             }
             $hasgradeitems = false;
             $items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename, 'iteminstance' => $instance, 'courseid' => $COURSE->id));
             //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
             if (!empty($items)) {
                 foreach ($items as $item) {
                     if (!empty($item->outcomeid)) {
                         $elname = 'outcome_' . $item->outcomeid;
                         if ($mform->elementExists($elname)) {
                             $mform->hardFreeze($elname);
                             // prevent removing of existing outcomes
                         }
                     } else {
                         $hasgradeitems = true;
                     }
                 }
                 foreach ($items as $item) {
                     if (is_bool($gradecat)) {
                         $gradecat = $item->categoryid;
                         continue;
                     }
                     if ($gradecat != $item->categoryid) {
                         //mixed categories
                         $gradecat = false;
                         break;
                     }
                 }
             }
             if (!$hasgradeitems && $mform->elementExists('gradepass')) {
                 // Remove form element 'Grade to pass' since there are no grade items (when rating not selected).
                 $mform->removeElement('gradepass');
             }
             if ($gradecat === false) {
                 // items and outcomes in different categories - remove the option
                 // TODO: add a "Mixed categories" text instead of removing elements with no explanation
                 if ($mform->elementExists('gradecat')) {
                     $mform->removeElement('gradecat');
                     if ($this->_features->rating && !$mform->elementExists('gradepass')) {
                         //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
                         $mform->removeElement('modstandardgrade');
                     }
                 }
             }
         }
     }
     if ($COURSE->groupmodeforce) {
         if ($mform->elementExists('groupmode')) {
             $mform->hardFreeze('groupmode');
             // groupmode can not be changed if forced from course settings
         }
     }
     // Don't disable/remove groupingid if it is currently set to something,
     // otherwise you cannot turn it off at same time as turning off other
     // option (MDL-30764)
     if (empty($this->_cm) || !$this->_cm->groupingid) {
         if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
             $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
         } else {
             if (!$mform->elementExists('groupmode')) {
                 // Groupings have no use without groupmode.
                 if ($mform->elementExists('groupingid')) {
                     $mform->removeElement('groupingid');
                 }
             }
         }
     }
     // Completion: If necessary, freeze fields
     $completion = new completion_info($COURSE);
     if ($completion->is_enabled()) {
         // If anybody has completed the activity, these options will be 'locked'
         $completedcount = empty($this->_cm) ? 0 : $completion->count_user_data($this->_cm);
         $freeze = false;
         if (!$completedcount) {
             if ($mform->elementExists('unlockcompletion')) {
                 $mform->removeElement('unlockcompletion');
             }
             // Automatically set to unlocked (note: this is necessary
             // in order to make it recalculate completion once the option
             // is changed, maybe someone has completed it now)
             $mform->getElement('completionunlocked')->setValue(1);
         } else {
             // Has the element been unlocked, either by the button being pressed
             // in this request, or the field already being set from a previous one?
             if ($mform->exportValue('unlockcompletion') || $mform->exportValue('completionunlocked')) {
                 // Yes, add in warning text and set the hidden variable
                 $mform->insertElementBefore($mform->createElement('static', 'completedunlocked', get_string('completedunlocked', 'completion'), get_string('completedunlockedtext', 'completion')), 'unlockcompletion');
                 $mform->removeElement('unlockcompletion');
                 $mform->getElement('completionunlocked')->setValue(1);
             } else {
                 // No, add in the warning text with the count (now we know
                 // it) before the unlock button
                 $mform->insertElementBefore($mform->createElement('static', 'completedwarning', get_string('completedwarning', 'completion'), get_string('completedwarningtext', 'completion', $completedcount)), 'unlockcompletion');
                 $freeze = true;
             }
         }
         if ($freeze) {
             $mform->freeze('completion');
             if ($mform->elementExists('completionview')) {
                 $mform->freeze('completionview');
                 // don't use hardFreeze or checkbox value gets lost
             }
             if ($mform->elementExists('completionusegrade')) {
                 $mform->freeze('completionusegrade');
             }
             $mform->freeze($this->_customcompletionelements);
         }
     }
     // Freeze admin defaults if required (and not different from default)
     $this->apply_admin_locked_flags();
 }
Exemple #24
0
/**
 * Update the grade items categories if they are changed via mod_form.php
 *
 * We must do it manually here in the workshop module because modedit supports only
 * single grade item while we use two.
 *
 * @param stdClass $workshop An object from the form in mod_form.php
 */
function workshop_grade_item_category_update($workshop) {

    $gradeitems = grade_item::fetch_all(array(
        'itemtype'      => 'mod',
        'itemmodule'    => 'workshop',
        'iteminstance'  => $workshop->id,
        'courseid'      => $workshop->course));

    if (!empty($gradeitems)) {
        foreach ($gradeitems as $gradeitem) {
            if ($gradeitem->itemnumber == 0) {
                if ($gradeitem->categoryid != $workshop->gradecategory) {
                    $gradeitem->set_parent($workshop->gradecategory);
                }
            } else if ($gradeitem->itemnumber == 1) {
                if ($gradeitem->categoryid != $workshop->gradinggradecategory) {
                    $gradeitem->set_parent($workshop->gradinggradecategory);
                }
            }
        }
    }
}
Exemple #25
0
/**
 * Delete a course module and any associated data at the course level (events)
 * Until 1.5 this function simply marked a deleted flag ... now it
 * deletes it completely.
 *
 */
function delete_course_module($id)
{
    global $CFG, $DB;
    require_once $CFG->libdir . '/gradelib.php';
    require_once $CFG->dirroot . '/blog/lib.php';
    if (!($cm = $DB->get_record('course_modules', array('id' => $id)))) {
        return true;
    }
    $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
    //delete events from calendar
    if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
        foreach ($events as $event) {
            delete_event($event->id);
        }
    }
    //delete grade items, outcome items and grades attached to modules
    if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename, 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
        foreach ($grade_items as $grade_item) {
            $grade_item->delete('moddelete');
        }
    }
    // Delete completion and availability data; it is better to do this even if the
    // features are not turned on, in case they were turned on previously (these will be
    // very quick on an empty table)
    $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
    $DB->delete_records('course_modules_availability', array('coursemoduleid' => $cm->id));
    $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id, 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
    delete_context(CONTEXT_MODULE, $cm->id);
    return $DB->delete_records('course_modules', array('id' => $cm->id));
}
Exemple #26
0
 /**
  * Normalizes the calculation formula to [#giXX#] form
  * @static
  * @param string $formula
  * @return string normalized string
  */
 function normalize_formula($formula, $courseid)
 {
     $formula = trim($formula);
     if (empty($formula)) {
         return NULL;
     }
     // normalize formula - we want grade item ids ##giXXX## instead of [[idnumber]]
     if ($grade_items = grade_item::fetch_all(array('courseid' => $courseid))) {
         foreach ($grade_items as $grade_item) {
             $formula = str_replace('[[' . $grade_item->idnumber . ']]', '##gi' . $grade_item->id . '##', $formula);
         }
     }
     return $formula;
 }
Exemple #27
0
 /**
  * Sets the grade_item's hidden variable and updates the grade_item.
  *
  * Overrides grade_item::set_hidden() to add cascading of the hidden value to grade items in this grade category
  *
  * @param int $hidden 0 mean always visible, 1 means always hidden and a number > 1 is a timestamp to hide until
  * @param bool $cascade apply to child objects too
  */
 public function set_hidden($hidden, $cascade = false)
 {
     $this->load_grade_item();
     //this hides the associated grade item (the course total)
     $this->grade_item->set_hidden($hidden, $cascade);
     //this hides the category itself and everything it contains
     parent::set_hidden($hidden, $cascade);
     if ($cascade) {
         if ($children = grade_item::fetch_all(array('categoryid' => $this->id))) {
             foreach ($children as $child) {
                 if ($child->can_control_visibility()) {
                     $child->set_hidden($hidden, $cascade);
                 }
             }
         }
         if ($children = grade_category::fetch_all(array('parent' => $this->id))) {
             foreach ($children as $child) {
                 $child->set_hidden($hidden, $cascade);
             }
         }
     }
     //if marking category visible make sure parent category is visible MDL-21367
     if (!$hidden) {
         $category_array = grade_category::fetch_all(array('id' => $this->parent));
         if ($category_array && array_key_exists($this->parent, $category_array)) {
             $category = $category_array[$this->parent];
             //call set_hidden on the category regardless of whether it is hidden as its parent might be hidden
             //if($category->is_hidden()) {
             $category->set_hidden($hidden, false);
             //}
         }
     }
 }
Exemple #28
0
 /**
  * Optionally blank out course/category totals if they contain any hidden items
  * @param string $courseid the course id
  * @param string $course_item an instance of grade_item
  * @param string $finalgrade the grade for the course_item
  * @return string The new final grade
  */
 protected function blank_hidden_total($courseid, $course_item, $finalgrade)
 {
     global $CFG, $DB;
     static $hiding_affected = null;
     //array of items in this course affected by hiding
     // If we're dealing with multiple users we need to know when we've moved on to a new user.
     static $previous_userid = null;
     // If we're dealing with multiple courses we need to know when we've moved on to a new course.
     static $previous_courseid = null;
     if (!is_array($this->showtotalsifcontainhidden)) {
         debugging('showtotalsifcontainhidden should be an array', DEBUG_DEVELOPER);
         $this->showtotalsifcontainhidden = array($courseid => $this->showtotalsifcontainhidden);
     }
     if ($this->showtotalsifcontainhidden[$courseid] == GRADE_REPORT_SHOW_REAL_TOTAL_IF_CONTAINS_HIDDEN) {
         return $finalgrade;
     }
     // If we've moved on to another course or user, reload the grades.
     if ($previous_userid != $this->user->id || $previous_courseid != $courseid) {
         $hiding_affected = null;
         $previous_userid = $this->user->id;
         $previous_courseid = $courseid;
     }
     if (!$hiding_affected) {
         $items = grade_item::fetch_all(array('courseid' => $courseid));
         $grades = array();
         $sql = "SELECT g.*\n                      FROM {grade_grades} g\n                      JOIN {grade_items} gi ON gi.id = g.itemid\n                     WHERE g.userid = {$this->user->id} AND gi.courseid = {$courseid}";
         if ($gradesrecords = $DB->get_records_sql($sql)) {
             foreach ($gradesrecords as $grade) {
                 $grades[$grade->itemid] = new grade_grade($grade, false);
             }
             unset($gradesrecords);
         }
         foreach ($items as $itemid => $unused) {
             if (!isset($grades[$itemid])) {
                 $grade_grade = new grade_grade();
                 $grade_grade->userid = $this->user->id;
                 $grade_grade->itemid = $items[$itemid]->id;
                 $grades[$itemid] = $grade_grade;
             }
             $grades[$itemid]->grade_item =& $items[$itemid];
         }
         $hiding_affected = grade_grade::get_hiding_affected($grades, $items);
     }
     //if the item definitely depends on a hidden item
     if (array_key_exists($course_item->id, $hiding_affected['altered'])) {
         if (!$this->showtotalsifcontainhidden[$courseid]) {
             //hide the grade
             $finalgrade = null;
         } else {
             //use reprocessed marks that exclude hidden items
             $finalgrade = $hiding_affected['altered'][$course_item->id];
         }
     } else {
         if (!empty($hiding_affected['unknown'][$course_item->id])) {
             //not sure whether or not this item depends on a hidden item
             if (!$this->showtotalsifcontainhidden[$courseid]) {
                 //hide the grade
                 $finalgrade = null;
             } else {
                 //use reprocessed marks that exclude hidden items
                 $finalgrade = $hiding_affected['unknown'][$course_item->id];
             }
         }
     }
     return $finalgrade;
 }
Exemple #29
0
function import_xml_grades($text, $course, &$error)
{
    global $USER;
    $importcode = get_new_importcode();
    $status = true;
    $content = xmlize($text);
    if (!empty($content['results']['#']['result'])) {
        $results = $content['results']['#']['result'];
        foreach ($results as $i => $result) {
            $gradeidnumber = $result['#']['assignment'][0]['#'];
            if (!($grade_items = grade_item::fetch_all(array('idnumber' => $gradeidnumber, 'courseid' => $course->id)))) {
                // gradeitem does not exist
                // no data in temp table so far, abort
                $status = false;
                $error = get_string('errincorrectgradeidnumber', 'gradeimport_xml', $gradeidnumber);
                break;
            } else {
                if (count($grade_items) != 1) {
                    $status = false;
                    $error = get_string('errduplicategradeidnumber', 'gradeimport_xml', $gradeidnumber);
                    break;
                } else {
                    $grade_item = reset($grade_items);
                }
            }
            // grade item locked, abort
            if ($grade_item->is_locked()) {
                $status = false;
                $error = get_string('gradeitemlocked', 'grades');
                break;
            }
            // check if user exist and convert idnumber to user id
            $useridnumber = $result['#']['student'][0]['#'];
            if (!($user = get_record('user', 'idnumber', addslashes($useridnumber)))) {
                // no user found, abort
                $status = false;
                $error = get_string('errincorrectuseridnumber', 'gradeimport_xml', $useridnumber);
                break;
            }
            // check if grade_grade is locked and if so, abort
            if ($grade_grade = new grade_grade(array('itemid' => $grade_item->id, 'userid' => $user->id))) {
                $grade_grade->grade_item =& $grade_item;
                if ($grade_grade->is_locked()) {
                    // individual grade locked, abort
                    $status = false;
                    $error = get_string('gradegradeslocked', 'grades');
                    break;
                }
            }
            $newgrade = new object();
            $newgrade->itemid = $grade_item->id;
            $newgrade->userid = $user->id;
            $newgrade->importcode = $importcode;
            $newgrade->importer = $USER->id;
            // check grade value exists and is a numeric grade
            if (isset($result['#']['score'][0]['#'])) {
                if (is_numeric($result['#']['score'][0]['#'])) {
                    $newgrade->finalgrade = $result['#']['score'][0]['#'];
                } else {
                    $status = false;
                    $error = get_string('badgrade', 'grades');
                    break;
                }
            } else {
                $newgrade->finalgrade = NULL;
            }
            // check grade feedback exists
            if (isset($result['#']['feedback'][0]['#'])) {
                $newgrade->feedback = $result['#']['feedback'][0]['#'];
            } else {
                $newgrade->feedback = NULL;
            }
            // insert this grade into a temp table
            if (!insert_record('grade_import_values', addslashes_recursive($newgrade))) {
                $status = false;
                // could not insert into temp table
                $error = get_string('importfailed', 'grades');
                break;
            }
        }
    } else {
        // no results section found in xml,
        // assuming bad format, abort import
        $status = false;
        $error = get_string('errbadxmlformat', 'gradeimport_xml');
    }
    if ($status) {
        return $importcode;
    } else {
        import_cleanup($importcode);
        return false;
    }
}
Exemple #30
0
/**
 * Returns all grade items (including outcomes) or main item for a given activity identified by $cm object.
 *
 * @param object $cm A course module object (preferably with modname property)
 * @return mixed - array of grade item instances (one if $only_main_item true), false if error or not found
 */
function grade_get_grade_items_for_activity($cm, $only_main_item = false)
{
    global $CFG, $DB;
    if (!isset($cm->modname)) {
        $params = array($cm->id);
        $cm = $DB->get_record_sql("SELECT cm.*, m.name, md.name as modname\n                                    FROM {course_modules} cm,\n                                         {modules} md,\n                                   WHERE cm.id = ? AND md.id = cm.module", $params);
    }
    if (empty($cm) or empty($cm->instance) or empty($cm->course)) {
        debugging("Incorrect cm parameter in grade_get_grade_items_for_activity()!");
        return false;
    }
    if ($only_main_item) {
        return grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $cm->modname, 'iteminstance' => $cm->instance, 'courseid' => $cm->course, 'itemnumber' => 0));
    } else {
        return grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $cm->modname, 'iteminstance' => $cm->instance, 'courseid' => $cm->course));
    }
}