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");
         }
     }
 }
示例#2
0
 function definition()
 {
     global $COURSE, $CFG, $DB;
     $mform =& $this->_form;
     $item = $this->_customdata['current'];
     /// visible elements
     $mform->addElement('header', 'general', get_string('gradeitem', 'grades'));
     $mform->addElement('text', 'itemname', get_string('itemname', 'grades'));
     $mform->addElement('text', 'iteminfo', get_string('iteminfo', 'grades'));
     $mform->setHelpButton('iteminfo', array('iteminfo', get_string('iteminfo', 'grades'), 'grade'), true);
     $mform->addElement('text', 'idnumber', get_string('idnumbermod'));
     $mform->setHelpButton('idnumber', array('idnumber', get_string('idnumber', 'grades'), 'grade'), true);
     $options = array(GRADE_TYPE_NONE => get_string('typenone', 'grades'), GRADE_TYPE_VALUE => get_string('typevalue', 'grades'), GRADE_TYPE_SCALE => get_string('typescale', 'grades'), GRADE_TYPE_TEXT => get_string('typetext', 'grades'));
     $mform->addElement('select', 'gradetype', get_string('gradetype', 'grades'), $options);
     $mform->setHelpButton('gradetype', array('gradetype', get_string('gradetype', 'grades'), 'grade'), true);
     $mform->setDefault('gradetype', GRADE_TYPE_VALUE);
     //$mform->addElement('text', 'calculation', get_string('calculation', 'grades'));
     //$mform->disabledIf('calculation', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     //$mform->disabledIf('calculation', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $options = array(0 => get_string('usenoscale', 'grades'));
     if ($scales = grade_scale::fetch_all_local($COURSE->id)) {
         foreach ($scales as $scale) {
             $options[$scale->id] = $scale->get_name();
         }
     }
     if ($scales = grade_scale::fetch_all_global()) {
         foreach ($scales as $scale) {
             $options[$scale->id] = $scale->get_name();
         }
     }
     // ugly BC hack - it was possbile to use custom scale from other courses :-(
     if (!empty($item->scaleid) and !isset($options[$item->scaleid])) {
         if ($scale = grade_scale::fetch(array('id' => $item->scaleid))) {
             $options[$scale->id] = $scale->get_name() . get_string('incorrectcustomscale', 'grades');
         }
     }
     $mform->addElement('select', 'scaleid', get_string('scale'), $options);
     $mform->setHelpButton('scaleid', array('scaleid', get_string('scaleid', 'grades'), 'grade'), true);
     $mform->disabledIf('scaleid', 'gradetype', 'noteq', GRADE_TYPE_SCALE);
     $mform->addElement('text', 'grademax', get_string('grademax', 'grades'));
     $mform->setHelpButton('grademax', array('grademax', get_string('grademax', 'grades'), 'grade'), true);
     $mform->disabledIf('grademax', 'gradetype', 'noteq', GRADE_TYPE_VALUE);
     $mform->addElement('text', 'grademin', get_string('grademin', 'grades'));
     $mform->setHelpButton('grademin', array('grademin', get_string('grademin', 'grades'), 'grade'), true);
     $mform->disabledIf('grademin', 'gradetype', 'noteq', GRADE_TYPE_VALUE);
     $mform->addElement('text', 'gradepass', get_string('gradepass', 'grades'));
     $mform->setHelpButton('gradepass', array('gradepass', get_string('gradepass', 'grades'), 'grade'), true);
     $mform->disabledIf('gradepass', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('gradepass', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     $mform->addElement('text', 'multfactor', get_string('multfactor', 'grades'));
     $mform->setHelpButton('multfactor', array('multfactor', get_string('multfactor', 'grades'), 'grade'), true);
     $mform->setAdvanced('multfactor');
     $mform->disabledIf('multfactor', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('multfactor', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     $mform->addElement('text', 'plusfactor', get_string('plusfactor', 'grades'));
     $mform->setHelpButton('plusfactor', array('plusfactor', get_string('plusfactor', 'grades'), 'grade'), true);
     $mform->setAdvanced('plusfactor');
     $mform->disabledIf('plusfactor', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('plusfactor', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     /// grade display prefs
     $default_gradedisplaytype = grade_get_setting($COURSE->id, 'displaytype', $CFG->grade_displaytype);
     $options = array(GRADE_DISPLAY_TYPE_DEFAULT => get_string('default', 'grades'), GRADE_DISPLAY_TYPE_REAL => get_string('real', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE => get_string('percentage', 'grades'), GRADE_DISPLAY_TYPE_LETTER => get_string('letter', 'grades'), GRADE_DISPLAY_TYPE_REAL_PERCENTAGE => get_string('realpercentage', 'grades'), GRADE_DISPLAY_TYPE_REAL_LETTER => get_string('realletter', 'grades'), GRADE_DISPLAY_TYPE_LETTER_REAL => get_string('letterreal', 'grades'), GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE => get_string('letterpercentage', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER => get_string('percentageletter', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE_REAL => get_string('percentagereal', 'grades'));
     asort($options);
     foreach ($options as $key => $option) {
         if ($key == $default_gradedisplaytype) {
             $options[GRADE_DISPLAY_TYPE_DEFAULT] = get_string('defaultprev', 'grades', $option);
             break;
         }
     }
     $mform->addElement('select', 'display', get_string('gradedisplaytype', 'grades'), $options);
     $mform->setHelpButton('display', array('gradedisplaytype', get_string('gradedisplaytype', 'grades'), 'grade'), true);
     $default_gradedecimals = grade_get_setting($COURSE->id, 'decimalpoints', $CFG->grade_decimalpoints);
     $options = array(-1 => get_string('defaultprev', 'grades', $default_gradedecimals), 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
     $mform->addElement('select', 'decimals', get_string('decimalpoints', 'grades'), $options);
     $mform->setHelpButton('decimals', array('decimalpoints', get_string('decimalpoints', 'grades'), 'grade'), true);
     $mform->setDefault('decimals', -1);
     $mform->disabledIf('decimals', 'display', 'eq', GRADE_DISPLAY_TYPE_LETTER);
     if ($default_gradedisplaytype == GRADE_DISPLAY_TYPE_LETTER) {
         $mform->disabledIf('decimals', 'display', "eq", GRADE_DISPLAY_TYPE_DEFAULT);
     }
     /// hiding
     // advcheckbox is not compatible with disabledIf!
     $mform->addElement('checkbox', 'hidden', get_string('hidden', 'grades'));
     $mform->setHelpButton('hidden', array('hidden', get_string('hidden', 'grades'), 'grade'));
     $mform->addElement('date_time_selector', 'hiddenuntil', get_string('hiddenuntil', 'grades'), array('optional' => true));
     $mform->setHelpButton('hiddenuntil', array('hiddenuntil', get_string('hiddenuntil', 'grades'), 'grade'));
     $mform->disabledIf('hidden', 'hiddenuntil[off]', 'notchecked');
     /// locking
     $mform->addElement('advcheckbox', 'locked', get_string('locked', 'grades'));
     $mform->setHelpButton('locked', array('locked', get_string('locked', 'grades'), 'grade'));
     $mform->addElement('date_time_selector', 'locktime', get_string('locktime', 'grades'), array('optional' => true));
     $mform->setHelpButton('locktime', array('lockedafter', get_string('locktime', 'grades'), 'grade'));
     $mform->disabledIf('locktime', 'gradetype', 'eq', GRADE_TYPE_NONE);
     /// parent category related settings
     $mform->addElement('header', 'headerparent', get_string('parentcategory', 'grades'));
     $options = array();
     $coefstring = '';
     $categories = grade_category::fetch_all(array('courseid' => $COURSE->id));
     foreach ($categories as $cat) {
         $cat->apply_forced_settings();
         $options[$cat->id] = $cat->get_name();
     }
     if (count($categories) > 1) {
         $mform->addElement('select', 'parentcategory', get_string('gradecategory', 'grades'), $options);
     }
     /// hidden params
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'courseid', $COURSE->id);
     $mform->setType('courseid', PARAM_INT);
     $mform->addElement('hidden', 'itemtype', 'manual');
     // all new items are manual only
     $mform->setType('itemtype', PARAM_ALPHA);
     /// add return tracking info
     $gpr = $this->_customdata['gpr'];
     $gpr->add_mform_elements($mform);
     /// mark advanced according to site settings
     if (isset($CFG->grade_item_advanced)) {
         $advanced = explode(',', $CFG->grade_item_advanced);
         foreach ($advanced as $el) {
             if ($mform->elementExists($el)) {
                 $mform->setAdvanced($el);
             }
         }
     }
     //-------------------------------------------------------------------------------
     // buttons
     $this->add_action_buttons();
     //-------------------------------------------------------------------------------
     $this->set_data($item);
 }
示例#3
0
/**
 * Fetch all grade categories from the specified course.
 *
 * @param int $courseid the course id
 * @return array
 */
function certificate_get_grade_categories($courseid)
{
    $grade_category_options = array();
    if ($grade_categories = grade_category::fetch_all(array('courseid' => $courseid))) {
        foreach ($grade_categories as $grade_category) {
            if (!$grade_category->is_course_category()) {
                $grade_category_options[-$grade_category->id] = get_string('category') . ' : ' . $grade_category->get_name();
            }
        }
    }
    return $grade_category_options;
}
 protected function sub_test_grade_category_fetch_all()
 {
     $grade_category = new grade_category();
     $this->assertTrue(method_exists($grade_category, 'fetch_all'));
     $grade_categories = grade_category::fetch_all(array('courseid' => $this->courseid));
     $this->assertEquals(count($this->grade_categories), count($grade_categories) - 1);
 }
示例#5
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);
             }
         }
     }
 }
 /**
  * Set the hidden status of grade_item and all grades, 0 mean visible, 1 always hidden, number means date to hide until.
  * @param int $hidden new hidden status
  * @param boolean $cascade apply to child objects too
  * @return void
  */
 function set_hidden($hidden, $cascade = false)
 {
     $this->hidden = $hidden;
     $this->update();
     if ($cascade) {
         if ($grades = grade_grade::fetch_all(array('itemid' => $this->id))) {
             foreach ($grades as $grade) {
                 $grade->grade_item =& $this;
                 $grade->set_hidden($hidden, $cascade);
             }
         }
     }
     //if marking item visible make sure category is visible MDL-21367
     if (!$hidden) {
         $category_array = grade_category::fetch_all(array('id' => $this->categoryid));
         if ($category_array && array_key_exists($this->categoryid, $category_array)) {
             $category = $category_array[$this->categoryid];
             //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);
             //}
         }
     }
 }
 /**
  * Adds the grade item to the category specified by fullname.
  * If the category does not it is first created. This may create a performance hit
  * as the service call locks the database table until it completes adding the category.
  * Adding the category is delegated to an ad-hoc task.
  * If desired the code can be adjusted to queue the task for cron instead of executing
  * it here. This can consist of a mode switch by a config setting and when in background
  * mode, calling \core\task\manager::queue_adhoc_task($addcat) to queue the task.
  *
  * @param \grade_item $gitem
  * @param string $catnam
  * @return void.
  */
 protected static function update_grade_item_category($gitem, $catname)
 {
     $courseid = $gitem->courseid;
     // Fetch the grade category item that matches the target grade category by fullname.
     // There could be more than one grade category with the same name, so fetch all and
     // sort by id so that we always use the oldest one.
     $fetchparams = array('fullname' => $catname, 'courseid' => $courseid);
     if ($categories = \grade_category::fetch_all($fetchparams)) {
         // Categories found.
         if (count($categories) > 1) {
             // Sort by key which is the category id,
             // to put the oldest first.
             ksort($categories);
         }
         // Take the first.
         $category = reset($categories);
         if ($gitem->categoryid != $category->id) {
             // Item needs update.
             $gitem->categoryid = $category->id;
             $gitem->update();
         }
     } else {
         // Category not found so we task it.
         $addcat = new \block_mhaairs\task\add_grade_category_task();
         // We don't set blocking by set_blocking(true).
         // We add custom data.
         $addcat->set_custom_data(array('catname' => $catname, 'courseid' => $courseid, 'itemid' => $gitem->id));
         // We execute the task.
         // This will throw an exception if fails to create the category.
         $addcat->execute();
     }
 }
示例#8
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);
             //}
         }
     }
 }
示例#9
0
 function definition()
 {
     global $CFG, $COURSE, $DB;
     $mform =& $this->_form;
     $category = $this->_customdata['current'];
     $this->aggregation_options = array(GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'), GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'), GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'), GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'), GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'), GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'), GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'), GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'), GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades'));
     // visible elements
     $mform->addElement('header', 'headercategory', get_string('gradecategory', 'grades'));
     $mform->addElement('text', 'fullname', get_string('categoryname', 'grades'));
     $mform->addRule('fullname', null, 'required', null, 'client');
     $mform->addElement('select', 'aggregation', get_string('aggregation', 'grades'), $this->aggregation_options);
     $mform->addHelpButton('aggregation', 'aggregation', 'grades');
     if ((int) $CFG->grade_aggregation_flag & 2) {
         $mform->setAdvanced('aggregation');
     }
     $mform->addElement('checkbox', 'aggregateonlygraded', get_string('aggregateonlygraded', 'grades'));
     $mform->addHelpButton('aggregateonlygraded', 'aggregateonlygraded', 'grades');
     $mform->disabledIf('aggregateonlygraded', 'aggregation', 'eq', GRADE_AGGREGATE_SUM);
     if ((int) $CFG->grade_aggregateonlygraded_flag & 2) {
         $mform->setAdvanced('aggregateonlygraded');
     }
     if (empty($CFG->enableoutcomes)) {
         $mform->addElement('hidden', 'aggregateoutcomes');
         $mform->setType('aggregateoutcomes', PARAM_INT);
     } else {
         $mform->addElement('checkbox', 'aggregateoutcomes', get_string('aggregateoutcomes', 'grades'));
         $mform->addHelpButton('aggregateoutcomes', 'aggregateoutcomes', 'grades');
         if ((int) $CFG->grade_aggregateoutcomes_flag & 2) {
             $mform->setAdvanced('aggregateoutcomes');
         }
     }
     $mform->addElement('advcheckbox', 'aggregatesubcats', get_string('aggregatesubcats', 'grades'));
     $mform->addHelpButton('aggregatesubcats', 'aggregatesubcats', 'grades');
     if ((int) $CFG->grade_aggregatesubcats_flag & 2) {
         $mform->setAdvanced('aggregatesubcats');
     }
     $options = array(0 => get_string('none'));
     for ($i = 1; $i <= 20; $i++) {
         $options[$i] = $i;
     }
     $mform->addElement('select', 'keephigh', get_string('keephigh', 'grades'), $options);
     $mform->addHelpButton('keephigh', 'keephigh', 'grades');
     if ((int) $CFG->grade_keephigh_flag & 2) {
         $mform->setAdvanced('keephigh');
     }
     $mform->addElement('select', 'droplow', get_string('droplow', 'grades'), $options);
     $mform->addHelpButton('droplow', 'droplow', 'grades');
     $mform->disabledIf('droplow', 'keephigh', 'noteq', 0);
     if ((int) $CFG->grade_droplow_flag & 2) {
         $mform->setAdvanced('droplow');
     }
     $mform->disabledIf('keephigh', 'droplow', 'noteq', 0);
     $mform->disabledIf('droplow', 'keephigh', 'noteq', 0);
     // Grade item settings
     // Displayed as Category total to avoid confusion between grade items requiring marking and category totals
     $mform->addElement('header', 'general', get_string('categorytotal', 'grades'));
     $mform->addElement('text', 'grade_item_itemname', get_string('categorytotalname', 'grades'));
     $mform->setAdvanced('grade_item_itemname');
     $mform->addElement('text', 'grade_item_iteminfo', get_string('iteminfo', 'grades'));
     $mform->addHelpButton('grade_item_iteminfo', 'iteminfo', 'grades');
     $mform->addElement('text', 'grade_item_idnumber', get_string('idnumbermod'));
     $mform->addHelpButton('grade_item_idnumber', 'idnumbermod');
     $options = array(GRADE_TYPE_NONE => get_string('typenone', 'grades'), GRADE_TYPE_VALUE => get_string('typevalue', 'grades'), GRADE_TYPE_SCALE => get_string('typescale', 'grades'), GRADE_TYPE_TEXT => get_string('typetext', 'grades'));
     $mform->addElement('select', 'grade_item_gradetype', get_string('gradetype', 'grades'), $options);
     $mform->addHelpButton('grade_item_gradetype', 'gradetype', 'grades');
     $mform->setDefault('grade_item_gradetype', GRADE_TYPE_VALUE);
     $mform->disabledIf('grade_item_gradetype', 'aggregation', 'eq', GRADE_AGGREGATE_SUM);
     //$mform->addElement('text', 'calculation', get_string('calculation', 'grades'));
     //$mform->disabledIf('calculation', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     //$mform->disabledIf('calculation', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $options = array(0 => get_string('usenoscale', 'grades'));
     if ($scales = grade_scale::fetch_all_local($COURSE->id)) {
         foreach ($scales as $scale) {
             $options[$scale->id] = $scale->get_name();
         }
     }
     if ($scales = grade_scale::fetch_all_global()) {
         foreach ($scales as $scale) {
             $options[$scale->id] = $scale->get_name();
         }
     }
     // ugly BC hack - it was possible to use custom scale from other courses :-(
     if (!empty($category->grade_item_scaleid) and !isset($options[$category->grade_item_scaleid])) {
         if ($scale = grade_scale::fetch(array('id' => $category->grade_item_scaleid))) {
             $options[$scale->id] = $scale->get_name() . ' ' . get_string('incorrectcustomscale', 'grades');
         }
     }
     $mform->addElement('select', 'grade_item_scaleid', get_string('scale'), $options);
     $mform->addHelpButton('grade_item_scaleid', 'typescale', 'grades');
     $mform->disabledIf('grade_item_scaleid', 'grade_item_gradetype', 'noteq', GRADE_TYPE_SCALE);
     $mform->disabledIf('grade_item_scaleid', 'aggregation', 'eq', GRADE_AGGREGATE_SUM);
     $mform->addElement('text', 'grade_item_grademax', get_string('grademax', 'grades'));
     $mform->addHelpButton('grade_item_grademax', 'grademax', 'grades');
     $mform->disabledIf('grade_item_grademax', 'grade_item_gradetype', 'noteq', GRADE_TYPE_VALUE);
     $mform->disabledIf('grade_item_grademax', 'aggregation', 'eq', GRADE_AGGREGATE_SUM);
     $mform->addElement('text', 'grade_item_grademin', get_string('grademin', 'grades'));
     $mform->addHelpButton('grade_item_grademin', 'grademin', 'grades');
     $mform->disabledIf('grade_item_grademin', 'grade_item_gradetype', 'noteq', GRADE_TYPE_VALUE);
     $mform->disabledIf('grade_item_grademin', 'aggregation', 'eq', GRADE_AGGREGATE_SUM);
     $mform->addElement('text', 'grade_item_gradepass', get_string('gradepass', 'grades'));
     $mform->addHelpButton('grade_item_gradepass', 'gradepass', 'grades');
     $mform->disabledIf('grade_item_gradepass', 'grade_item_gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('grade_item_gradepass', 'grade_item_gradetype', 'eq', GRADE_TYPE_TEXT);
     /// grade display prefs
     $default_gradedisplaytype = grade_get_setting($COURSE->id, 'displaytype', $CFG->grade_displaytype);
     $options = array(GRADE_DISPLAY_TYPE_DEFAULT => get_string('default', 'grades'), GRADE_DISPLAY_TYPE_REAL => get_string('real', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE => get_string('percentage', 'grades'), GRADE_DISPLAY_TYPE_LETTER => get_string('letter', 'grades'), GRADE_DISPLAY_TYPE_REAL_PERCENTAGE => get_string('realpercentage', 'grades'), GRADE_DISPLAY_TYPE_REAL_LETTER => get_string('realletter', 'grades'), GRADE_DISPLAY_TYPE_LETTER_REAL => get_string('letterreal', 'grades'), GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE => get_string('letterpercentage', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER => get_string('percentageletter', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE_REAL => get_string('percentagereal', 'grades'));
     asort($options);
     foreach ($options as $key => $option) {
         if ($key == $default_gradedisplaytype) {
             $options[GRADE_DISPLAY_TYPE_DEFAULT] = get_string('defaultprev', 'grades', $option);
             break;
         }
     }
     $mform->addElement('select', 'grade_item_display', get_string('gradedisplaytype', 'grades'), $options);
     $mform->addHelpButton('grade_item_display', 'gradedisplaytype', 'grades');
     $default_gradedecimals = grade_get_setting($COURSE->id, 'decimalpoints', $CFG->grade_decimalpoints);
     $options = array(-1 => get_string('defaultprev', 'grades', $default_gradedecimals), 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
     $mform->addElement('select', 'grade_item_decimals', get_string('decimalpoints', 'grades'), $options);
     $mform->addHelpButton('grade_item_decimals', 'decimalpoints', 'grades');
     $mform->setDefault('grade_item_decimals', -1);
     $mform->disabledIf('grade_item_decimals', 'grade_item_display', 'eq', GRADE_DISPLAY_TYPE_LETTER);
     if ($default_gradedisplaytype == GRADE_DISPLAY_TYPE_LETTER) {
         $mform->disabledIf('grade_item_decimals', 'grade_item_display', "eq", GRADE_DISPLAY_TYPE_DEFAULT);
     }
     /// hiding
     // advcheckbox is not compatible with disabledIf!
     $mform->addElement('checkbox', 'grade_item_hidden', get_string('hidden', 'grades'));
     $mform->addHelpButton('grade_item_hidden', 'hidden', 'grades');
     $mform->addElement('date_time_selector', 'grade_item_hiddenuntil', get_string('hiddenuntil', 'grades'), array('optional' => true));
     $mform->disabledIf('grade_item_hidden', 'grade_item_hiddenuntil[off]', 'notchecked');
     /// locking
     $mform->addElement('checkbox', 'grade_item_locked', get_string('locked', 'grades'));
     $mform->addHelpButton('grade_item_locked', 'locked', 'grades');
     $mform->addElement('date_time_selector', 'grade_item_locktime', get_string('locktime', 'grades'), array('optional' => true));
     $mform->disabledIf('grade_item_locktime', 'grade_item_gradetype', 'eq', GRADE_TYPE_NONE);
     /// parent category related settings
     $mform->addElement('header', 'headerparent', get_string('parentcategory', 'grades'));
     $options = array();
     $default = '';
     $categories = grade_category::fetch_all(array('courseid' => $COURSE->id));
     foreach ($categories as $cat) {
         $cat->apply_forced_settings();
         $options[$cat->id] = $cat->get_name();
         if ($cat->is_course_category()) {
             $default = $cat->id;
         }
     }
     if (count($categories) > 1) {
         $mform->addElement('select', 'parentcategory', get_string('parentcategory', 'grades'), $options);
         $mform->addElement('static', 'currentparentaggregation', get_string('currentparentaggregation', 'grades'));
     }
     // hidden params
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'courseid', 0);
     $mform->setType('courseid', PARAM_INT);
     /// add return tracking info
     $gpr = $this->_customdata['gpr'];
     $gpr->add_mform_elements($mform);
     /// mark advanced according to site settings
     if (isset($CFG->grade_item_advanced)) {
         $advanced = explode(',', $CFG->grade_item_advanced);
         foreach ($advanced as $el) {
             $el = 'grade_item_' . $el;
             if ($mform->elementExists($el)) {
                 $mform->setAdvanced($el);
             }
         }
     }
     //-------------------------------------------------------------------------------
     // buttons
     $this->add_action_buttons();
     //-------------------------------------------------------------------------------
     $this->set_data($category);
 }
示例#10
0
/**
 * Updates all final grades in course.
 *
 * @param int $courseid The course ID
 * @param int $userid If specified try to do a quick regrading of the grades of this user only
 * @param object $updated_item Optional grade item to be marked for regrading
 * @return bool true if ok, array of errors if problems found. Grade item id => error message
 */
function grade_regrade_final_grades($courseid, $userid = null, $updated_item = null)
{
    // This may take a very long time.
    \core_php_time_limit::raise();
    $course_item = grade_item::fetch_course_item($courseid);
    if ($userid) {
        // one raw grade updated for one user
        if (empty($updated_item)) {
            print_error("cannotbenull", 'debug', '', "updated_item");
        }
        if ($course_item->needsupdate) {
            $updated_item->force_regrading();
            return array($course_item->id => 'Can not do fast regrading after updating of raw grades');
        }
    } else {
        if (!$course_item->needsupdate) {
            // nothing to do :-)
            return true;
        }
    }
    // Categories might have to run some processing before we fetch the grade items.
    // This gives them a final opportunity to update and mark their children to be updated.
    // We need to work on the children categories up to the parent ones, so that, for instance,
    // if a category total is updated it will be reflected in the parent category.
    $cats = grade_category::fetch_all(array('courseid' => $courseid));
    $flatcattree = array();
    foreach ($cats as $cat) {
        if (!isset($flatcattree[$cat->depth])) {
            $flatcattree[$cat->depth] = array();
        }
        $flatcattree[$cat->depth][] = $cat;
    }
    krsort($flatcattree);
    foreach ($flatcattree as $depth => $cats) {
        foreach ($cats as $cat) {
            $cat->pre_regrade_final_grades();
        }
    }
    $grade_items = grade_item::fetch_all(array('courseid' => $courseid));
    $depends_on = array();
    // first mark all category and calculated items as needing regrading
    // this is slower, but 100% accurate
    foreach ($grade_items as $gid => $gitem) {
        if (!empty($updated_item) and $updated_item->id == $gid) {
            $grade_items[$gid]->needsupdate = 1;
        } else {
            if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
                $grade_items[$gid]->needsupdate = 1;
            }
        }
        // construct depends_on lookup array
        $depends_on[$gid] = $grade_items[$gid]->depends_on();
    }
    $errors = array();
    $finalids = array();
    $gids = array_keys($grade_items);
    $failed = 0;
    while (count($finalids) < count($gids)) {
        // work until all grades are final or error found
        $count = 0;
        foreach ($gids as $gid) {
            if (in_array($gid, $finalids)) {
                continue;
                // already final
            }
            if (!$grade_items[$gid]->needsupdate) {
                $finalids[] = $gid;
                // we can make it final - does not need update
                continue;
            }
            $doupdate = true;
            foreach ($depends_on[$gid] as $did) {
                if (!in_array($did, $finalids)) {
                    $doupdate = false;
                    continue;
                    // this item depends on something that is not yet in finals array
                }
            }
            //oki - let's update, calculate or aggregate :-)
            if ($doupdate) {
                $result = $grade_items[$gid]->regrade_final_grades($userid);
                if ($result === true) {
                    $grade_items[$gid]->regrading_finished();
                    $grade_items[$gid]->check_locktime();
                    // do the locktime item locking
                    $count++;
                    $finalids[] = $gid;
                } else {
                    $grade_items[$gid]->force_regrading();
                    $errors[$gid] = $result;
                }
            }
        }
        if ($count == 0) {
            $failed++;
        } else {
            $failed = 0;
        }
        if ($failed > 1) {
            foreach ($gids as $gid) {
                if (in_array($gid, $finalids)) {
                    continue;
                    // this one is ok
                }
                $grade_items[$gid]->force_regrading();
                $errors[$grade_items[$gid]->id] = get_string('errorcalculationbroken', 'grades');
            }
            break;
            // Found error.
        }
    }
    if (count($errors) == 0) {
        if (empty($userid)) {
            // do the locktime locking of grades, but only when doing full regrading
            grade_grade::check_locktime_all($gids);
        }
        return true;
    } else {
        return $errors;
    }
}
示例#11
0
 function definition()
 {
     global $CFG, $COURSE;
     $mform =& $this->_form;
     $options = array(GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'), GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'), GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'), GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'), GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'), GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'), GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'), GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'), GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades'));
     // visible elements
     $mform->addElement('header', 'headercategory', get_string('gradecategory', 'grades'));
     $mform->addElement('text', 'fullname', get_string('categoryname', 'grades'));
     $mform->addRule('fullname', null, 'required', null, 'client');
     $mform->addElement('select', 'aggregation', get_string('aggregation', 'grades'), $options);
     $mform->setHelpButton('aggregation', array('aggregation', get_string('aggregation', 'grades'), 'grade'));
     if ((int) $CFG->grade_aggregation_flag & 2) {
         $mform->setAdvanced('aggregation');
     }
     $mform->addElement('checkbox', 'aggregateonlygraded', get_string('aggregateonlygraded', 'grades'));
     $mform->setHelpButton('aggregateonlygraded', array('aggregateonlygraded', get_string('aggregateonlygraded', 'grades'), 'grade'), true);
     $mform->disabledIf('aggregateonlygraded', 'aggregation', 'eq', GRADE_AGGREGATE_SUM);
     if ((int) $CFG->grade_aggregateonlygraded_flag & 2) {
         $mform->setAdvanced('aggregateonlygraded');
     }
     if (empty($CFG->enableoutcomes)) {
         $mform->addElement('hidden', 'aggregateoutcomes');
         $mform->setType('aggregateoutcomes', PARAM_INT);
     } else {
         $mform->addElement('checkbox', 'aggregateoutcomes', get_string('aggregateoutcomes', 'grades'));
         $mform->setHelpButton('aggregateoutcomes', array('aggregateoutcomes', get_string('aggregateoutcomes', 'grades'), 'grade'), true);
         if ((int) $CFG->grade_aggregateoutcomes_flag & 2) {
             $mform->setAdvanced('aggregateoutcomes');
         }
     }
     $mform->addElement('advcheckbox', 'aggregatesubcats', get_string('aggregatesubcats', 'grades'));
     $mform->setHelpButton('aggregatesubcats', array('aggregatesubcats', get_string('aggregatesubcats', 'grades'), 'grade'), true);
     if ((int) $CFG->grade_aggregatesubcats_flag & 2) {
         $mform->setAdvanced('aggregatesubcats');
     }
     $options = array(0 => get_string('none'));
     for ($i = 1; $i <= 20; $i++) {
         $options[$i] = $i;
     }
     $mform->addElement('select', 'keephigh', get_string('keephigh', 'grades'), $options);
     $mform->setHelpButton('keephigh', array('keephigh', get_string('keephigh', 'grades'), 'grade'), true);
     if ((int) $CFG->grade_keephigh_flag & 2) {
         $mform->setAdvanced('keephigh');
     }
     $mform->addElement('select', 'droplow', get_string('droplow', 'grades'), $options);
     $mform->setHelpButton('droplow', array('droplow', get_string('droplow', 'grades'), 'grade'), true);
     $mform->disabledIf('droplow', 'keephigh', 'noteq', 0);
     if ((int) $CFG->grade_droplow_flag & 2) {
         $mform->setAdvanced('droplow');
     }
     $mform->disabledIf('keephigh', 'droplow', 'noteq', 0);
     $mform->disabledIf('droplow', 'keephigh', 'noteq', 0);
     /// parent category related settings
     $mform->addElement('header', 'headerparent', get_string('parentcategory', 'grades'));
     $options = array();
     $default = '';
     $coefstring = '';
     $categories = grade_category::fetch_all(array('courseid' => $COURSE->id));
     foreach ($categories as $cat) {
         $cat->apply_forced_settings();
         $options[$cat->id] = $cat->get_name();
         if ($cat->is_course_category()) {
             $default = $cat->id;
         }
         if ($cat->is_aggregationcoef_used()) {
             if ($cat->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
                 $coefstring = ($coefstring == '' or $coefstring == 'aggregationcoefweight') ? 'aggregationcoefweight' : 'aggregationcoef';
             } else {
                 if ($cat->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
                     $coefstring = ($coefstring == '' or $coefstring == 'aggregationcoefextra') ? 'aggregationcoefextra' : 'aggregationcoef';
                 } else {
                     $coefstring = 'aggregationcoef';
                 }
             }
         } else {
             $mform->disabledIf('aggregationcoef', 'parentcategory', 'eq', $cat->id);
         }
     }
     if (count($categories) > 1) {
         $mform->addElement('select', 'parentcategory', get_string('gradecategory', 'grades'), $options);
     }
     if ($coefstring !== '') {
         $mform->addElement('text', 'aggregationcoef', get_string($coefstring, 'grades'));
         $mform->setHelpButton('aggregationcoef', array('aggregationcoef', get_string('aggregationcoef', 'grades'), 'grade'), true);
     }
     /// user preferences
     $mform->addElement('header', 'headerpreferences', get_string('myreportpreferences', 'grades'));
     $options = array(GRADE_REPORT_PREFERENCE_DEFAULT => get_string('default', 'grades'), GRADE_REPORT_AGGREGATION_VIEW_FULL => get_string('fullmode', 'grades'), GRADE_REPORT_AGGREGATION_VIEW_AGGREGATES_ONLY => get_string('aggregatesonly', 'grades'), GRADE_REPORT_AGGREGATION_VIEW_GRADES_ONLY => get_string('gradesonly', 'grades'));
     $label = get_string('aggregationview', 'grades') . ' (' . get_string('default', 'grades') . ': ' . $options[$CFG->grade_report_aggregationview] . ')';
     $mform->addElement('select', 'pref_aggregationview', $label, $options);
     $mform->setHelpButton('pref_aggregationview', array('aggregationview', get_string('aggregationview', 'grades'), 'grade'), true);
     $mform->setDefault('pref_aggregationview', GRADE_REPORT_PREFERENCE_DEFAULT);
     $mform->setAdvanced('pref_aggregationview');
     // hidden params
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'courseid', 0);
     $mform->setType('courseid', PARAM_INT);
     /// add return tracking info
     $gpr = $this->_customdata['gpr'];
     $gpr->add_mform_elements($mform);
     //-------------------------------------------------------------------------------
     // buttons
     $this->add_action_buttons();
 }
 /**
  * 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);
             }
         }
     }
     //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);
             //}
         }
     }
 }
示例#13
0
 function definition()
 {
     global $COURSE, $CFG, $DB;
     $mform =& $this->_form;
     $item = $this->_customdata['current'];
     /// visible elements
     $mform->addElement('header', 'general', get_string('gradeitem', 'grades'));
     $mform->addElement('text', 'itemname', get_string('itemname', 'grades'));
     $mform->setType('itemname', PARAM_TEXT);
     $mform->addElement('text', 'iteminfo', get_string('iteminfo', 'grades'));
     $mform->addHelpButton('iteminfo', 'iteminfo', 'grades');
     $mform->setType('iteminfo', PARAM_TEXT);
     $mform->addElement('text', 'idnumber', get_string('idnumbermod'));
     $mform->addHelpButton('idnumber', 'idnumbermod');
     $mform->setType('idnumber', PARAM_RAW);
     if (!empty($item->id)) {
         $gradeitem = new grade_item(array('id' => $item->id, 'courseid' => $item->courseid));
         // If grades exist set a message so the user knows why they can not alter the grade type or scale.
         // We could never change the grade type for external items, so only need to show this for manual grade items.
         if ($gradeitem->has_grades() && !$gradeitem->is_external_item()) {
             // Set a message so the user knows why they can not alter the grade type or scale.
             if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
                 $gradesexistmsg = get_string('modgradecantchangegradetyporscalemsg', 'grades');
             } else {
                 $gradesexistmsg = get_string('modgradecantchangegradetypemsg', 'grades');
             }
             $gradesexisthtml = '<div class=\'alert\'>' . $gradesexistmsg . '</div>';
             $mform->addElement('static', 'gradesexistmsg', '', $gradesexisthtml);
         }
     }
     // Manual grade items cannot have grade type GRADE_TYPE_NONE.
     $options = array(GRADE_TYPE_VALUE => get_string('typevalue', 'grades'), GRADE_TYPE_SCALE => get_string('typescale', 'grades'), GRADE_TYPE_TEXT => get_string('typetext', 'grades'));
     $mform->addElement('select', 'gradetype', get_string('gradetype', 'grades'), $options);
     $mform->addHelpButton('gradetype', 'gradetype', 'grades');
     $mform->setDefault('gradetype', GRADE_TYPE_VALUE);
     //$mform->addElement('text', 'calculation', get_string('calculation', 'grades'));
     //$mform->disabledIf('calculation', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     //$mform->disabledIf('calculation', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $options = array(0 => get_string('usenoscale', 'grades'));
     if ($scales = grade_scale::fetch_all_local($COURSE->id)) {
         foreach ($scales as $scale) {
             $options[$scale->id] = $scale->get_name();
         }
     }
     if ($scales = grade_scale::fetch_all_global()) {
         foreach ($scales as $scale) {
             $options[$scale->id] = $scale->get_name();
         }
     }
     // ugly BC hack - it was possible to use custom scale from other courses :-(
     if (!empty($item->scaleid) and !isset($options[$item->scaleid])) {
         if ($scale = grade_scale::fetch(array('id' => $item->scaleid))) {
             $options[$scale->id] = $scale->get_name() . get_string('incorrectcustomscale', 'grades');
         }
     }
     $mform->addElement('select', 'scaleid', get_string('scale'), $options);
     $mform->addHelpButton('scaleid', 'typescale', 'grades');
     $mform->disabledIf('scaleid', 'gradetype', 'noteq', GRADE_TYPE_SCALE);
     $choices = array();
     $choices[''] = get_string('choose');
     $choices['no'] = get_string('no');
     $choices['yes'] = get_string('yes');
     $mform->addElement('select', 'rescalegrades', get_string('modgraderescalegrades', 'grades'), $choices);
     $mform->addHelpButton('rescalegrades', 'modgraderescalegrades', 'grades');
     $mform->disabledIf('rescalegrades', 'gradetype', 'noteq', GRADE_TYPE_VALUE);
     $mform->addElement('text', 'grademax', get_string('grademax', 'grades'));
     $mform->addHelpButton('grademax', 'grademax', 'grades');
     $mform->disabledIf('grademax', 'gradetype', 'noteq', GRADE_TYPE_VALUE);
     $mform->setType('grademax', PARAM_RAW);
     if ((bool) get_config('moodle', 'grade_report_showmin')) {
         $mform->addElement('text', 'grademin', get_string('grademin', 'grades'));
         $mform->addHelpButton('grademin', 'grademin', 'grades');
         $mform->disabledIf('grademin', 'gradetype', 'noteq', GRADE_TYPE_VALUE);
         $mform->setType('grademin', PARAM_RAW);
     }
     $mform->addElement('text', 'gradepass', get_string('gradepass', 'grades'));
     $mform->addHelpButton('gradepass', 'gradepass', 'grades');
     $mform->disabledIf('gradepass', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('gradepass', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     $mform->setType('gradepass', PARAM_RAW);
     $mform->addElement('text', 'multfactor', get_string('multfactor', 'grades'));
     $mform->addHelpButton('multfactor', 'multfactor', 'grades');
     $mform->setAdvanced('multfactor');
     $mform->disabledIf('multfactor', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('multfactor', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     $mform->setType('multfactor', PARAM_RAW);
     $mform->addElement('text', 'plusfactor', get_string('plusfactor', 'grades'));
     $mform->addHelpButton('plusfactor', 'plusfactor', 'grades');
     $mform->setAdvanced('plusfactor');
     $mform->disabledIf('plusfactor', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('plusfactor', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     $mform->setType('plusfactor', PARAM_RAW);
     /// grade display prefs
     $default_gradedisplaytype = grade_get_setting($COURSE->id, 'displaytype', $CFG->grade_displaytype);
     $options = array(GRADE_DISPLAY_TYPE_DEFAULT => get_string('default', 'grades'), GRADE_DISPLAY_TYPE_REAL => get_string('real', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE => get_string('percentage', 'grades'), GRADE_DISPLAY_TYPE_LETTER => get_string('letter', 'grades'), GRADE_DISPLAY_TYPE_REAL_PERCENTAGE => get_string('realpercentage', 'grades'), GRADE_DISPLAY_TYPE_REAL_LETTER => get_string('realletter', 'grades'), GRADE_DISPLAY_TYPE_LETTER_REAL => get_string('letterreal', 'grades'), GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE => get_string('letterpercentage', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER => get_string('percentageletter', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE_REAL => get_string('percentagereal', 'grades'));
     asort($options);
     foreach ($options as $key => $option) {
         if ($key == $default_gradedisplaytype) {
             $options[GRADE_DISPLAY_TYPE_DEFAULT] = get_string('defaultprev', 'grades', $option);
             break;
         }
     }
     $mform->addElement('select', 'display', get_string('gradedisplaytype', 'grades'), $options);
     $mform->addHelpButton('display', 'gradedisplaytype', 'grades');
     $default_gradedecimals = grade_get_setting($COURSE->id, 'decimalpoints', $CFG->grade_decimalpoints);
     $options = array(-1 => get_string('defaultprev', 'grades', $default_gradedecimals), 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
     $mform->addElement('select', 'decimals', get_string('decimalpoints', 'grades'), $options);
     $mform->addHelpButton('decimals', 'decimalpoints', 'grades');
     $mform->setDefault('decimals', -1);
     $mform->disabledIf('decimals', 'display', 'eq', GRADE_DISPLAY_TYPE_LETTER);
     if ($default_gradedisplaytype == GRADE_DISPLAY_TYPE_LETTER) {
         $mform->disabledIf('decimals', 'display', "eq", GRADE_DISPLAY_TYPE_DEFAULT);
     }
     /// hiding
     if ($item->cancontrolvisibility) {
         // advcheckbox is not compatible with disabledIf!
         $mform->addElement('checkbox', 'hidden', get_string('hidden', 'grades'));
         $mform->addElement('date_time_selector', 'hiddenuntil', get_string('hiddenuntil', 'grades'), array('optional' => true));
         $mform->disabledIf('hidden', 'hiddenuntil[off]', 'notchecked');
     } else {
         $mform->addElement('static', 'hidden', get_string('hidden', 'grades'), get_string('componentcontrolsvisibility', 'grades'));
         // Unset hidden to avoid data override.
         unset($item->hidden);
     }
     $mform->addHelpButton('hidden', 'hidden', 'grades');
     /// locking
     $mform->addElement('advcheckbox', 'locked', get_string('locked', 'grades'));
     $mform->addHelpButton('locked', 'locked', 'grades');
     $mform->addElement('date_time_selector', 'locktime', get_string('locktime', 'grades'), array('optional' => true));
     $mform->disabledIf('locktime', 'gradetype', 'eq', GRADE_TYPE_NONE);
     /// parent category related settings
     $mform->addElement('header', 'headerparent', get_string('parentcategory', 'grades'));
     $mform->addElement('advcheckbox', 'weightoverride', get_string('adjustedweight', 'grades'));
     $mform->addHelpButton('weightoverride', 'weightoverride', 'grades');
     $mform->disabledIf('weightoverride', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('weightoverride', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     $mform->addElement('text', 'aggregationcoef2', get_string('weight', 'grades'));
     $mform->addHelpButton('aggregationcoef2', 'weight', 'grades');
     $mform->setType('aggregationcoef2', PARAM_RAW);
     $mform->disabledIf('aggregationcoef2', 'weightoverride');
     $mform->disabledIf('aggregationcoef2', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('aggregationcoef2', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     $options = array();
     $coefstring = '';
     $categories = grade_category::fetch_all(array('courseid' => $COURSE->id));
     foreach ($categories as $cat) {
         $cat->apply_forced_settings();
         $options[$cat->id] = $cat->get_name();
     }
     if (count($categories) > 1) {
         $mform->addElement('select', 'parentcategory', get_string('gradecategory', 'grades'), $options);
     }
     /// hidden params
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'courseid', $COURSE->id);
     $mform->setType('courseid', PARAM_INT);
     $mform->addElement('hidden', 'itemtype', 'manual');
     // all new items are manual only
     $mform->setType('itemtype', PARAM_ALPHA);
     /// add return tracking info
     $gpr = $this->_customdata['gpr'];
     $gpr->add_mform_elements($mform);
     /// mark advanced according to site settings
     if (isset($CFG->grade_item_advanced)) {
         $advanced = explode(',', $CFG->grade_item_advanced);
         foreach ($advanced as $el) {
             if ($mform->elementExists($el)) {
                 $mform->setAdvanced($el);
             }
         }
     }
     //-------------------------------------------------------------------------------
     // buttons
     $this->add_action_buttons();
     //-------------------------------------------------------------------------------
     $this->set_data($item);
 }
示例#14
0
 function definition()
 {
     global $COURSE, $CFG;
     $mform =& $this->_form;
     /// visible elements
     $mform->addElement('header', 'general', get_string('gradeitem', 'grades'));
     $mform->addElement('text', 'itemname', get_string('itemname', 'grades'));
     $mform->addElement('text', 'iteminfo', get_string('iteminfo', 'grades'));
     $mform->setHelpButton('iteminfo', array('iteminfo', get_string('iteminfo', 'grades'), 'grade'), true);
     $mform->addElement('text', 'idnumber', get_string('idnumbermod'));
     $mform->setHelpButton('idnumber', array('idnumber', get_string('idnumber', 'grades'), 'grade'), true);
     $options = array(GRADE_TYPE_NONE => get_string('typenone', 'grades'), GRADE_TYPE_VALUE => get_string('typevalue', 'grades'), GRADE_TYPE_SCALE => get_string('typescale', 'grades'), GRADE_TYPE_TEXT => get_string('typetext', 'grades'));
     $mform->addElement('select', 'gradetype', get_string('gradetype', 'grades'), $options);
     $mform->setHelpButton('gradetype', array('gradetype', get_string('gradetype', 'grades'), 'grade'), true);
     $mform->setDefault('gradetype', GRADE_TYPE_VALUE);
     //$mform->addElement('text', 'calculation', get_string('calculation', 'grades'));
     //$mform->disabledIf('calculation', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     //$mform->disabledIf('calculation', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $options = array(0 => get_string('usenoscale', 'grades'));
     if ($scales = get_records('scale')) {
         foreach ($scales as $scale) {
             $options[$scale->id] = format_string($scale->name);
         }
     }
     $mform->addElement('select', 'scaleid', get_string('scale'), $options);
     $mform->setHelpButton('scaleid', array('scaleid', get_string('scaleid', 'grades'), 'grade'), true);
     $mform->disabledIf('scaleid', 'gradetype', 'noteq', GRADE_TYPE_SCALE);
     $mform->addElement('text', 'grademax', get_string('grademax', 'grades'));
     $mform->setHelpButton('grademax', array('grademax', get_string('grademax', 'grades'), 'grade'), true);
     $mform->disabledIf('grademax', 'gradetype', 'noteq', GRADE_TYPE_VALUE);
     $mform->addElement('text', 'grademin', get_string('grademin', 'grades'));
     $mform->setHelpButton('grademin', array('grademin', get_string('grademin', 'grades'), 'grade'), true);
     $mform->disabledIf('grademin', 'gradetype', 'noteq', GRADE_TYPE_VALUE);
     $mform->addElement('text', 'gradepass', get_string('gradepass', 'grades'));
     $mform->setHelpButton('gradepass', array('gradepass', get_string('gradepass', 'grades'), 'grade'), true);
     $mform->disabledIf('gradepass', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('gradepass', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     $mform->addElement('text', 'multfactor', get_string('multfactor', 'grades'));
     $mform->setHelpButton('multfactor', array('multfactor', get_string('multfactor', 'grades'), 'grade'), true);
     $mform->setAdvanced('multfactor');
     $mform->disabledIf('multfactor', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('multfactor', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     $mform->addElement('text', 'plusfactor', get_string('plusfactor', 'grades'));
     $mform->setHelpButton('plusfactor', array('plusfactor', get_string('plusfactor', 'grades'), 'grade'), true);
     $mform->setAdvanced('plusfactor');
     $mform->disabledIf('plusfactor', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('plusfactor', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     /// grade display prefs
     $default_gradedisplaytype = grade_get_setting($COURSE->id, 'displaytype', $CFG->grade_displaytype);
     $options = array(GRADE_DISPLAY_TYPE_DEFAULT => get_string('default', 'grades'), GRADE_DISPLAY_TYPE_REAL => get_string('real', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE => get_string('percentage', 'grades'), GRADE_DISPLAY_TYPE_LETTER => get_string('letter', 'grades'));
     foreach ($options as $key => $option) {
         if ($key == $default_gradedisplaytype) {
             $options[GRADE_DISPLAY_TYPE_DEFAULT] = get_string('defaultprev', 'grades', $option);
             break;
         }
     }
     $mform->addElement('select', 'display', get_string('gradedisplaytype', 'grades'), $options);
     $mform->setHelpButton('display', array('gradedisplaytype', get_string('gradedisplaytype', 'grades'), 'grade'), true);
     $default_gradedecimals = grade_get_setting($COURSE->id, 'decimalpoints', $CFG->grade_decimalpoints);
     $options = array(-1 => get_string('defaultprev', 'grades', $default_gradedecimals), 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
     $mform->addElement('select', 'decimals', get_string('decimalpoints', 'grades'), $options);
     $mform->setHelpButton('decimals', array('decimalpoints', get_string('decimalpoints', 'grades'), 'grade'), true);
     $mform->setDefault('decimals', -1);
     $mform->disabledIf('decimals', 'display', 'eq', GRADE_DISPLAY_TYPE_LETTER);
     if ($default_gradedisplaytype == GRADE_DISPLAY_TYPE_LETTER) {
         $mform->disabledIf('decimals', 'display', "eq", GRADE_DISPLAY_TYPE_DEFAULT);
     }
     /// hiding
     // advcheckbox is not compatible with disabledIf!
     $mform->addElement('checkbox', 'hidden', get_string('hidden', 'grades'));
     $mform->setHelpButton('hidden', array('hidden', get_string('hidden', 'grades'), 'grade'));
     $mform->addElement('date_time_selector', 'hiddenuntil', get_string('hiddenuntil', 'grades'), array('optional' => true));
     $mform->setHelpButton('hiddenuntil', array('hiddenuntil', get_string('hiddenuntil', 'grades'), 'grade'));
     $mform->disabledIf('hidden', 'hiddenuntil[off]', 'notchecked');
     /// locking
     $mform->addElement('advcheckbox', 'locked', get_string('locked', 'grades'));
     $mform->setHelpButton('locked', array('locked', get_string('locked', 'grades'), 'grade'));
     $mform->addElement('date_time_selector', 'locktime', get_string('locktime', 'grades'), array('optional' => true));
     $mform->setHelpButton('locktime', array('lockedafter', get_string('locktime', 'grades'), 'grade'));
     $mform->disabledIf('locktime', 'gradetype', 'eq', GRADE_TYPE_NONE);
     /// parent category related settings
     $mform->addElement('header', 'headerparent', get_string('parentcategory', 'grades'));
     $options = array();
     $default = '';
     $coefstring = '';
     $categories = grade_category::fetch_all(array('courseid' => $COURSE->id));
     foreach ($categories as $cat) {
         $cat->apply_forced_settings();
         $options[$cat->id] = $cat->get_name();
         if ($cat->is_course_category()) {
             $default = $cat->id;
         }
         if ($cat->is_aggregationcoef_used()) {
             if ($cat->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
                 $coefstring = ($coefstring == '' or $coefstring == 'aggregationcoefweight') ? 'aggregationcoefweight' : 'aggregationcoef';
             } else {
                 if ($cat->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
                     $coefstring = ($coefstring == '' or $coefstring == 'aggregationcoefextra') ? 'aggregationcoefextra' : 'aggregationcoef';
                 } else {
                     if ($cat->aggregation == GRADE_AGGREGATE_SUM) {
                         $coefstring = ($coefstring == '' or $coefstring == 'aggregationcoefextrasum') ? 'aggregationcoefextrasum' : 'aggregationcoef';
                     } else {
                         $coefstring = 'aggregationcoef';
                     }
                 }
             }
         } else {
             $mform->disabledIf('aggregationcoef', 'parentcategory', 'eq', $cat->id);
         }
     }
     if (count($categories) > 1) {
         $mform->addElement('select', 'parentcategory', get_string('gradecategory', 'grades'), $options);
     }
     if ($coefstring !== '') {
         if ($coefstring == 'aggregationcoefextrasum') {
             // advcheckbox is not compatible with disabledIf!
             $mform->addElement('checkbox', 'aggregationcoef', get_string($coefstring, 'grades'));
         } else {
             $mform->addElement('text', 'aggregationcoef', get_string($coefstring, 'grades'));
         }
         $mform->setHelpButton('aggregationcoef', array($coefstring, get_string($coefstring, 'grades'), 'grade'), true);
     }
     /// hidden params
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'courseid', $COURSE->id);
     $mform->setType('courseid', PARAM_INT);
     $mform->addElement('hidden', 'itemtype', 'manual');
     // all new items are manual only
     $mform->setType('itemtype', PARAM_ALPHA);
     /// add return tracking info
     $gpr = $this->_customdata['gpr'];
     $gpr->add_mform_elements($mform);
     /// mark advanced according to site settings
     if (isset($CFG->grade_item_advanced)) {
         $advanced = explode(',', $CFG->grade_item_advanced);
         foreach ($advanced as $el) {
             if ($mform->elementExists($el)) {
                 $mform->setAdvanced($el);
             }
         }
     }
     //-------------------------------------------------------------------------------
     // buttons
     $this->add_action_buttons();
 }
示例#15
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;
}
示例#16
0
 function definition()
 {
     global $CFG, $COURSE, $DB, $OUTPUT;
     $mform =& $this->_form;
     $category = $this->_customdata['current'];
     $this->aggregation_options = grade_helper::get_aggregation_strings();
     // visible elements
     $mform->addElement('header', 'headercategory', get_string('gradecategory', 'grades'));
     $mform->addElement('text', 'fullname', get_string('categoryname', 'grades'));
     $mform->setType('fullname', PARAM_TEXT);
     $mform->addRule('fullname', null, 'required', null, 'client');
     $mform->addElement('select', 'aggregation', get_string('aggregation', 'grades'), $this->aggregation_options);
     $mform->addHelpButton('aggregation', 'aggregation', 'grades');
     if ((int) $CFG->grade_aggregation_flag & 2) {
         $mform->setAdvanced('aggregation');
     }
     $mform->addElement('checkbox', 'aggregateonlygraded', get_string('aggregateonlygraded', 'grades'));
     $mform->addHelpButton('aggregateonlygraded', 'aggregateonlygraded', 'grades');
     if ((int) $CFG->grade_aggregateonlygraded_flag & 2) {
         $mform->setAdvanced('aggregateonlygraded');
     }
     if (empty($CFG->enableoutcomes)) {
         $mform->addElement('hidden', 'aggregateoutcomes');
         $mform->setType('aggregateoutcomes', PARAM_INT);
     } else {
         $mform->addElement('checkbox', 'aggregateoutcomes', get_string('aggregateoutcomes', 'grades'));
         $mform->addHelpButton('aggregateoutcomes', 'aggregateoutcomes', 'grades');
         if ((int) $CFG->grade_aggregateoutcomes_flag & 2) {
             $mform->setAdvanced('aggregateoutcomes');
         }
     }
     $mform->addElement('text', 'keephigh', get_string('keephigh', 'grades'), 'size="3"');
     $mform->setType('keephigh', PARAM_INT);
     $mform->addHelpButton('keephigh', 'keephigh', 'grades');
     if ((int) $CFG->grade_keephigh_flag & 2) {
         $mform->setAdvanced('keephigh');
     }
     $mform->addElement('text', 'droplow', get_string('droplow', 'grades'), 'size="3"');
     $mform->setType('droplow', PARAM_INT);
     $mform->addHelpButton('droplow', 'droplow', 'grades');
     $mform->disabledIf('droplow', 'keephigh', 'noteq', 0);
     if ((int) $CFG->grade_droplow_flag & 2) {
         $mform->setAdvanced('droplow');
     }
     $mform->disabledIf('keephigh', 'droplow', 'noteq', 0);
     $mform->disabledIf('droplow', 'keephigh', 'noteq', 0);
     // Grade item settings
     // Displayed as Category total to avoid confusion between grade items requiring marking and category totals
     $mform->addElement('header', 'general', get_string('categorytotal', 'grades'));
     $mform->addElement('text', 'grade_item_itemname', get_string('categorytotalname', 'grades'));
     $mform->setType('grade_item_itemname', PARAM_TEXT);
     $mform->setAdvanced('grade_item_itemname');
     $mform->addElement('text', 'grade_item_iteminfo', get_string('iteminfo', 'grades'));
     $mform->addHelpButton('grade_item_iteminfo', 'iteminfo', 'grades');
     $mform->setType('grade_item_iteminfo', PARAM_TEXT);
     $mform->addElement('text', 'grade_item_idnumber', get_string('idnumbermod'));
     $mform->addHelpButton('grade_item_idnumber', 'idnumbermod');
     $mform->setType('grade_item_idnumber', PARAM_RAW);
     if (!empty($category->id)) {
         $gradecategory = grade_category::fetch(array('id' => $category->id));
         $gradeitem = $gradecategory->load_grade_item();
         // If grades exist set a message so the user knows why they can not alter the grade type or scale.
         // We could never change the grade type for external items, so only need to show this for manual grade items.
         if ($gradeitem->has_overridden_grades()) {
             // Set a message so the user knows why the can not alter the grade type or scale.
             if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
                 $gradesexistmsg = get_string('modgradecategorycantchangegradetyporscalemsg', 'grades');
             } else {
                 $gradesexistmsg = get_string('modgradecategorycantchangegradetypemsg', 'grades');
             }
             $notification = new \core\output\notification($gradesexistmsg, \core\output\notification::NOTIFY_INFO);
             $notification->set_show_closebutton(false);
             $mform->addElement('static', 'gradesexistmsg', '', $OUTPUT->render($notification));
         }
     }
     $options = array(GRADE_TYPE_NONE => get_string('typenone', 'grades'), GRADE_TYPE_VALUE => get_string('typevalue', 'grades'), GRADE_TYPE_SCALE => get_string('typescale', 'grades'), GRADE_TYPE_TEXT => get_string('typetext', 'grades'));
     $mform->addElement('select', 'grade_item_gradetype', get_string('gradetype', 'grades'), $options);
     $mform->addHelpButton('grade_item_gradetype', 'gradetype', 'grades');
     $mform->setDefault('grade_item_gradetype', GRADE_TYPE_VALUE);
     $mform->disabledIf('grade_item_gradetype', 'aggregation', 'eq', GRADE_AGGREGATE_SUM);
     //$mform->addElement('text', 'calculation', get_string('calculation', 'grades'));
     //$mform->disabledIf('calculation', 'gradetype', 'eq', GRADE_TYPE_TEXT);
     //$mform->disabledIf('calculation', 'gradetype', 'eq', GRADE_TYPE_NONE);
     $options = array(0 => get_string('usenoscale', 'grades'));
     if ($scales = grade_scale::fetch_all_local($COURSE->id)) {
         foreach ($scales as $scale) {
             $options[$scale->id] = $scale->get_name();
         }
     }
     if ($scales = grade_scale::fetch_all_global()) {
         foreach ($scales as $scale) {
             $options[$scale->id] = $scale->get_name();
         }
     }
     // ugly BC hack - it was possible to use custom scale from other courses :-(
     if (!empty($category->grade_item_scaleid) and !isset($options[$category->grade_item_scaleid])) {
         if ($scale = grade_scale::fetch(array('id' => $category->grade_item_scaleid))) {
             $options[$scale->id] = $scale->get_name() . ' ' . get_string('incorrectcustomscale', 'grades');
         }
     }
     $mform->addElement('select', 'grade_item_scaleid', get_string('scale'), $options);
     $mform->addHelpButton('grade_item_scaleid', 'typescale', 'grades');
     $mform->disabledIf('grade_item_scaleid', 'grade_item_gradetype', 'noteq', GRADE_TYPE_SCALE);
     $mform->disabledIf('grade_item_scaleid', 'aggregation', 'eq', GRADE_AGGREGATE_SUM);
     $choices = array();
     $choices[''] = get_string('choose');
     $choices['no'] = get_string('no');
     $choices['yes'] = get_string('yes');
     $mform->addElement('select', 'grade_item_rescalegrades', get_string('modgradecategoryrescalegrades', 'grades'), $choices);
     $mform->addHelpButton('grade_item_rescalegrades', 'modgradecategoryrescalegrades', 'grades');
     $mform->disabledIf('grade_item_rescalegrades', 'grade_item_gradetype', 'noteq', GRADE_TYPE_VALUE);
     $mform->addElement('text', 'grade_item_grademax', get_string('grademax', 'grades'));
     $mform->setType('grade_item_grademax', PARAM_RAW);
     $mform->addHelpButton('grade_item_grademax', 'grademax', 'grades');
     $mform->disabledIf('grade_item_grademax', 'grade_item_gradetype', 'noteq', GRADE_TYPE_VALUE);
     $mform->disabledIf('grade_item_grademax', 'aggregation', 'eq', GRADE_AGGREGATE_SUM);
     if ((bool) get_config('moodle', 'grade_report_showmin')) {
         $mform->addElement('text', 'grade_item_grademin', get_string('grademin', 'grades'));
         $mform->setType('grade_item_grademin', PARAM_RAW);
         $mform->addHelpButton('grade_item_grademin', 'grademin', 'grades');
         $mform->disabledIf('grade_item_grademin', 'grade_item_gradetype', 'noteq', GRADE_TYPE_VALUE);
         $mform->disabledIf('grade_item_grademin', 'aggregation', 'eq', GRADE_AGGREGATE_SUM);
     }
     $mform->addElement('text', 'grade_item_gradepass', get_string('gradepass', 'grades'));
     $mform->setType('grade_item_gradepass', PARAM_RAW);
     $mform->addHelpButton('grade_item_gradepass', 'gradepass', 'grades');
     $mform->disabledIf('grade_item_gradepass', 'grade_item_gradetype', 'eq', GRADE_TYPE_NONE);
     $mform->disabledIf('grade_item_gradepass', 'grade_item_gradetype', 'eq', GRADE_TYPE_TEXT);
     /// grade display prefs
     $default_gradedisplaytype = grade_get_setting($COURSE->id, 'displaytype', $CFG->grade_displaytype);
     $options = array(GRADE_DISPLAY_TYPE_DEFAULT => get_string('default', 'grades'), GRADE_DISPLAY_TYPE_REAL => get_string('real', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE => get_string('percentage', 'grades'), GRADE_DISPLAY_TYPE_LETTER => get_string('letter', 'grades'), GRADE_DISPLAY_TYPE_REAL_PERCENTAGE => get_string('realpercentage', 'grades'), GRADE_DISPLAY_TYPE_REAL_LETTER => get_string('realletter', 'grades'), GRADE_DISPLAY_TYPE_LETTER_REAL => get_string('letterreal', 'grades'), GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE => get_string('letterpercentage', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER => get_string('percentageletter', 'grades'), GRADE_DISPLAY_TYPE_PERCENTAGE_REAL => get_string('percentagereal', 'grades'));
     asort($options);
     foreach ($options as $key => $option) {
         if ($key == $default_gradedisplaytype) {
             $options[GRADE_DISPLAY_TYPE_DEFAULT] = get_string('defaultprev', 'grades', $option);
             break;
         }
     }
     $mform->addElement('select', 'grade_item_display', get_string('gradedisplaytype', 'grades'), $options);
     $mform->addHelpButton('grade_item_display', 'gradedisplaytype', 'grades');
     $default_gradedecimals = grade_get_setting($COURSE->id, 'decimalpoints', $CFG->grade_decimalpoints);
     $options = array(-1 => get_string('defaultprev', 'grades', $default_gradedecimals), 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
     $mform->addElement('select', 'grade_item_decimals', get_string('decimalpoints', 'grades'), $options);
     $mform->addHelpButton('grade_item_decimals', 'decimalpoints', 'grades');
     $mform->setDefault('grade_item_decimals', -1);
     $mform->disabledIf('grade_item_decimals', 'grade_item_display', 'eq', GRADE_DISPLAY_TYPE_LETTER);
     if ($default_gradedisplaytype == GRADE_DISPLAY_TYPE_LETTER) {
         $mform->disabledIf('grade_item_decimals', 'grade_item_display', "eq", GRADE_DISPLAY_TYPE_DEFAULT);
     }
     /// hiding
     // advcheckbox is not compatible with disabledIf!
     $mform->addElement('checkbox', 'grade_item_hidden', get_string('hidden', 'grades'));
     $mform->addHelpButton('grade_item_hidden', 'hidden', 'grades');
     $mform->addElement('date_time_selector', 'grade_item_hiddenuntil', get_string('hiddenuntil', 'grades'), array('optional' => true));
     $mform->disabledIf('grade_item_hidden', 'grade_item_hiddenuntil[off]', 'notchecked');
     /// locking
     $mform->addElement('checkbox', 'grade_item_locked', get_string('locked', 'grades'));
     $mform->addHelpButton('grade_item_locked', 'locked', 'grades');
     $mform->addElement('date_time_selector', 'grade_item_locktime', get_string('locktime', 'grades'), array('optional' => true));
     $mform->disabledIf('grade_item_locktime', 'grade_item_gradetype', 'eq', GRADE_TYPE_NONE);
     /// parent category related settings
     $mform->addElement('header', 'headerparent', get_string('parentcategory', 'grades'));
     $mform->addElement('advcheckbox', 'grade_item_weightoverride', get_string('adjustedweight', 'grades'));
     $mform->addHelpButton('grade_item_weightoverride', 'weightoverride', 'grades');
     $mform->addElement('text', 'grade_item_aggregationcoef2', get_string('weight', 'grades'));
     $mform->addHelpButton('grade_item_aggregationcoef2', 'weight', 'grades');
     $mform->setType('grade_item_aggregationcoef2', PARAM_RAW);
     $mform->disabledIf('grade_item_aggregationcoef2', 'grade_item_weightoverride');
     $options = array();
     $default = -1;
     $categories = grade_category::fetch_all(array('courseid' => $COURSE->id));
     foreach ($categories as $cat) {
         $cat->apply_forced_settings();
         $options[$cat->id] = $cat->get_name();
         if ($cat->is_course_category()) {
             $default = $cat->id;
         }
     }
     if (count($categories) > 1) {
         $mform->addElement('select', 'parentcategory', get_string('parentcategory', 'grades'), $options);
         $mform->setDefault('parentcategory', $default);
         $mform->addElement('static', 'currentparentaggregation', get_string('currentparentaggregation', 'grades'));
     }
     // hidden params
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'courseid', 0);
     $mform->setType('courseid', PARAM_INT);
     /// add return tracking info
     $gpr = $this->_customdata['gpr'];
     $gpr->add_mform_elements($mform);
     /// mark advanced according to site settings
     if (isset($CFG->grade_item_advanced)) {
         $advanced = explode(',', $CFG->grade_item_advanced);
         foreach ($advanced as $el) {
             $el = 'grade_item_' . $el;
             if ($mform->elementExists($el)) {
                 $mform->setAdvanced($el);
             }
         }
     }
     //-------------------------------------------------------------------------------
     // buttons
     $this->add_action_buttons();
     //-------------------------------------------------------------------------------
     $this->set_data($category);
 }
示例#17
0
/**
 * Returns grade options for gradebook grade category menu
 *
 * @param int $courseid The course ID
 * @param bool $includenew Include option for new category at array index -1
 * @return array of grade categories in course
 */
function grade_get_categories_menu($courseid, $includenew = false)
{
    $result = array();
    if (!($categories = grade_category::fetch_all(array('courseid' => $courseid)))) {
        //make sure course category exists
        if (!grade_category::fetch_course_category($courseid)) {
            debugging('Can not create course grade category!');
            return $result;
        }
        $categories = grade_category::fetch_all(array('courseid' => $courseid));
    }
    foreach ($categories as $key => $category) {
        if ($category->is_course_category()) {
            $result[$category->id] = get_string('uncategorised', 'grades');
            unset($categories[$key]);
        }
    }
    if ($includenew) {
        $result[-1] = get_string('newcategory', 'grades');
    }
    $cats = array();
    foreach ($categories as $category) {
        $cats[$category->id] = $category->get_name();
    }
    collatorlib::asort($cats);
    return $result + $cats;
}
示例#18
0
/**
 * Updates all final grades in course.
 *
 * @param int $courseid The course ID
 * @param int $userid If specified try to do a quick regrading of the grades of this user only
 * @param object $updated_item Optional grade item to be marked for regrading
 * @param \core\progress\base $progress If provided, will be used to update progress on this long operation.
 * @return bool true if ok, array of errors if problems found. Grade item id => error message
 */
function grade_regrade_final_grades($courseid, $userid = null, $updated_item = null, $progress = null)
{
    // This may take a very long time.
    \core_php_time_limit::raise();
    $course_item = grade_item::fetch_course_item($courseid);
    if ($progress == null) {
        $progress = new \core\progress\none();
    }
    if ($userid) {
        // one raw grade updated for one user
        if (empty($updated_item)) {
            print_error("cannotbenull", 'debug', '', "updated_item");
        }
        if ($course_item->needsupdate) {
            $updated_item->force_regrading();
            return array($course_item->id => 'Can not do fast regrading after updating of raw grades');
        }
    } else {
        if (!$course_item->needsupdate) {
            // nothing to do :-)
            return true;
        }
    }
    // Categories might have to run some processing before we fetch the grade items.
    // This gives them a final opportunity to update and mark their children to be updated.
    // We need to work on the children categories up to the parent ones, so that, for instance,
    // if a category total is updated it will be reflected in the parent category.
    $cats = grade_category::fetch_all(array('courseid' => $courseid));
    $flatcattree = array();
    foreach ($cats as $cat) {
        if (!isset($flatcattree[$cat->depth])) {
            $flatcattree[$cat->depth] = array();
        }
        $flatcattree[$cat->depth][] = $cat;
    }
    krsort($flatcattree);
    foreach ($flatcattree as $depth => $cats) {
        foreach ($cats as $cat) {
            $cat->pre_regrade_final_grades();
        }
    }
    $progresstotal = 0;
    $progresscurrent = 0;
    $grade_items = grade_item::fetch_all(array('courseid' => $courseid));
    $depends_on = array();
    foreach ($grade_items as $gid => $gitem) {
        if ((!empty($updated_item) and $updated_item->id == $gid) || $gitem->is_course_item() || $gitem->is_category_item() || $gitem->is_calculated()) {
            $grade_items[$gid]->needsupdate = 1;
        }
        // We load all dependencies of these items later we can discard some grade_items based on this.
        if ($grade_items[$gid]->needsupdate) {
            $depends_on[$gid] = $grade_items[$gid]->depends_on();
            $progresstotal++;
        }
    }
    $progress->start_progress('regrade_course', $progresstotal);
    $errors = array();
    $finalids = array();
    $updatedids = array();
    $gids = array_keys($grade_items);
    $failed = 0;
    while (count($finalids) < count($gids)) {
        // work until all grades are final or error found
        $count = 0;
        foreach ($gids as $gid) {
            if (in_array($gid, $finalids)) {
                continue;
                // already final
            }
            if (!$grade_items[$gid]->needsupdate) {
                $finalids[] = $gid;
                // we can make it final - does not need update
                continue;
            }
            $thisprogress = $progresstotal;
            foreach ($grade_items as $item) {
                if ($item->needsupdate) {
                    $thisprogress--;
                }
            }
            // Clip between $progresscurrent and $progresstotal.
            $thisprogress = max(min($thisprogress, $progresstotal), $progresscurrent);
            $progress->progress($thisprogress);
            $progresscurrent = $thisprogress;
            foreach ($depends_on[$gid] as $did) {
                if (!in_array($did, $finalids)) {
                    // This item depends on something that is not yet in finals array.
                    continue 2;
                }
            }
            // If this grade item has no dependancy with any updated item at all, then remove it from being recalculated.
            // When we get here, all of this grade item's decendents are marked as final so they would be marked as updated too
            // if they would have been regraded. We don't need to regrade items which dependants (not only the direct ones
            // but any dependant in the cascade) have not been updated.
            // If $updated_item was specified we discard the grade items that do not depend on it or on any grade item that
            // depend on $updated_item.
            // Here we check to see if the direct decendants are marked as updated.
            if (!empty($updated_item) && $gid != $updated_item->id && !in_array($updated_item->id, $depends_on[$gid])) {
                // We need to ensure that none of this item's dependencies have been updated.
                // If we find that one of the direct decendants of this grade item is marked as updated then this
                // grade item needs to be recalculated and marked as updated.
                // Being marked as updated is done further down in the code.
                $updateddependencies = false;
                foreach ($depends_on[$gid] as $dependency) {
                    if (in_array($dependency, $updatedids)) {
                        $updateddependencies = true;
                        break;
                    }
                }
                if ($updateddependencies === false) {
                    // If no direct descendants are marked as updated, then we don't need to update this grade item. We then mark it
                    // as final.
                    $finalids[] = $gid;
                    continue;
                }
            }
            // Let's update, calculate or aggregate.
            $result = $grade_items[$gid]->regrade_final_grades($userid);
            if ($result === true) {
                // We should only update the database if we regraded all users.
                if (empty($userid)) {
                    $grade_items[$gid]->regrading_finished();
                    // Do the locktime item locking.
                    $grade_items[$gid]->check_locktime();
                } else {
                    $grade_items[$gid]->needsupdate = 0;
                }
                $count++;
                $finalids[] = $gid;
                $updatedids[] = $gid;
            } else {
                $grade_items[$gid]->force_regrading();
                $errors[$gid] = $result;
            }
        }
        if ($count == 0) {
            $failed++;
        } else {
            $failed = 0;
        }
        if ($failed > 1) {
            foreach ($gids as $gid) {
                if (in_array($gid, $finalids)) {
                    continue;
                    // this one is ok
                }
                $grade_items[$gid]->force_regrading();
                $errors[$grade_items[$gid]->id] = get_string('errorcalculationbroken', 'grades');
            }
            break;
            // Found error.
        }
    }
    $progress->end_progress();
    if (count($errors) == 0) {
        if (empty($userid)) {
            // do the locktime locking of grades, but only when doing full regrading
            grade_grade::check_locktime_all($gids);
        }
        return true;
    } else {
        return $errors;
    }
}
 function definition()
 {
     global $COURSE, $CFG;
     $mform =& $this->_form;
     /// visible elements
     $mform->addElement('header', 'general', get_string('gradeoutcomeitem', 'grades'));
     $mform->addElement('text', 'itemname', get_string('itemname', 'grades'));
     $mform->addRule('itemname', get_string('required'), 'required', null, 'client');
     $mform->addElement('text', 'iteminfo', get_string('iteminfo', 'grades'));
     $mform->setHelpButton('iteminfo', array('iteminfo', get_string('iteminfo', 'grades'), 'grade'), true);
     $mform->addElement('text', 'idnumber', get_string('idnumbermod'));
     $mform->setHelpButton('idnumber', array('idnumber', get_string('idnumber', 'grades'), 'grade'), true);
     // allow setting of outcomes on module items too
     $options = array();
     if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
         foreach ($outcomes as $outcome) {
             $options[$outcome->id] = $outcome->get_name();
         }
     }
     $mform->addElement('selectwithlink', 'outcomeid', get_string('outcome', 'grades'), $options, null, array('link' => $CFG->wwwroot . '/grade/edit/outcome/course.php?id=' . $COURSE->id, 'label' => get_string('outcomeassigntocourse', 'grades')));
     $mform->setHelpButton('outcomeid', array('outcomeid', get_string('outcomeid', 'grades'), 'grade'), true);
     $mform->addRule('outcomeid', get_string('required'), 'required');
     $options = array(0 => get_string('none'));
     if ($coursemods = get_course_mods($COURSE->id)) {
         foreach ($coursemods as $coursemod) {
             if ($mod = get_coursemodule_from_id($coursemod->modname, $coursemod->id)) {
                 $options[$coursemod->id] = format_string($mod->name);
             }
         }
     }
     $mform->addElement('select', 'cmid', get_string('linkedactivity', 'grades'), $options);
     $mform->setHelpButton('cmid', array('linkedactivity', get_string('linkedactivity', 'grades'), 'grade'), true);
     $mform->setDefault('cmid', 0);
     /*$mform->addElement('text', 'gradepass', get_string('gradepass', 'grades'));
       $mform->setHelpButton('gradepass', array(false, get_string('gradepass', 'grades'),
               false, true, false, get_string('gradepasshelp', 'grades')));*/
     /// hiding
     /// advcheckbox is not compatible with disabledIf !!
     $mform->addElement('checkbox', 'hidden', get_string('hidden', 'grades'));
     $mform->setHelpButton('hidden', array('hidden', get_string('hidden', 'grades'), 'grade'));
     $mform->addElement('date_time_selector', 'hiddenuntil', get_string('hiddenuntil', 'grades'), array('optional' => true));
     $mform->setHelpButton('hiddenuntil', array('hiddenuntil', get_string('hiddenuntil', 'grades'), 'grade'));
     $mform->disabledIf('hidden', 'hiddenuntil[off]', 'notchecked');
     //locking
     $mform->addElement('advcheckbox', 'locked', get_string('locked', 'grades'));
     $mform->setHelpButton('locked', array('locked', get_string('locked', 'grades'), 'grade'));
     $mform->addElement('date_time_selector', 'locktime', get_string('locktime', 'grades'), array('optional' => true));
     $mform->setHelpButton('locktime', array('lockedafter', get_string('locktime', 'grades'), 'grade'));
     /// parent category related settings
     $mform->addElement('header', 'headerparent', get_string('parentcategory', 'grades'));
     $options = array();
     $default = '';
     $coefstring = '';
     $categories = grade_category::fetch_all(array('courseid' => $COURSE->id));
     foreach ($categories as $cat) {
         $cat->apply_forced_settings();
         $options[$cat->id] = $cat->get_name();
         if ($cat->is_course_category()) {
             $default = $cat->id;
         }
         if ($cat->is_aggregationcoef_used()) {
             if ($cat->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN) {
                 $coefstring = ($coefstring == '' or $coefstring == 'aggregationcoefweight') ? 'aggregationcoefweight' : 'aggregationcoef';
             } else {
                 if ($cat->aggregation == GRADE_AGGREGATE_WEIGHTED_MEAN2) {
                     $coefstring = ($coefstring == '' or $coefstring == 'aggregationcoefextrasum') ? 'aggregationcoefextrasum' : 'aggregationcoef';
                 } else {
                     if ($cat->aggregation == GRADE_AGGREGATE_EXTRACREDIT_MEAN) {
                         $coefstring = ($coefstring == '' or $coefstring == 'aggregationcoefextra') ? 'aggregationcoefextra' : 'aggregationcoef';
                     } else {
                         if ($cat->aggregation == GRADE_AGGREGATE_SUM) {
                             $coefstring = ($coefstring == '' or $coefstring == 'aggregationcoefextrasum') ? 'aggregationcoefextrasum' : 'aggregationcoef';
                         } else {
                             $coefstring = 'aggregationcoef';
                         }
                     }
                 }
             }
         } else {
             $mform->disabledIf('aggregationcoef', 'parentcategory', 'eq', $cat->id);
         }
     }
     if (count($categories) > 1) {
         $mform->addElement('select', 'parentcategory', get_string('gradecategory', 'grades'), $options);
         $mform->disabledIf('parentcategory', 'cmid', 'noteq', 0);
     }
     if ($coefstring !== '') {
         if ($coefstring == 'aggregationcoefextrasum') {
             // advcheckbox is not compatible with disabledIf!
             $mform->addElement('checkbox', 'aggregationcoef', get_string($coefstring, 'grades'));
         } else {
             $mform->addElement('text', 'aggregationcoef', get_string($coefstring, 'grades'));
         }
         $mform->setHelpButton('aggregationcoef', array($coefstring, get_string($coefstring, 'grades'), 'grade'), true);
     }
     /// hidden params
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'courseid', $COURSE->id);
     $mform->setType('courseid', PARAM_INT);
     /// add return tracking info
     $gpr = $this->_customdata['gpr'];
     $gpr->add_mform_elements($mform);
     /// mark advanced according to site settings
     if (isset($CFG->grade_item_advanced)) {
         $advanced = explode(',', $CFG->grade_item_advanced);
         foreach ($advanced as $el) {
             if ($mform->elementExists($el)) {
                 $mform->setAdvanced($el);
             }
         }
     }
     //-------------------------------------------------------------------------------
     // buttons
     $this->add_action_buttons();
 }
/**
 * taskchain_navigation_accesscontrol_form
 *
 * @param xxx $course
 * @param xxx $block_instance
 */
function taskchain_navigation_accesscontrol_form($course, $block_instance, $action)
{
    global $CFG, $DB, $OUTPUT, $PAGE;
    // site and system contexts
    if (class_exists('context')) {
        $sitecontext = context_course::instance(SITEID);
        $systemcontext = context_system::instance();
    } else {
        $sitecontext = get_context_instance(CONTEXT_COURSE, SITEID);
        $systemcontext = get_context_instance(CONTEXT_SYSTEM);
    }
    $hassiteconfig = has_capability('moodle/site:config', $systemcontext);
    // decode block config settings, in case they are needed later
    $block_instance->config = unserialize(base64_decode($block_instance->configdata));
    // we need the DB manager to check which
    // DB tables and fields are available
    $dbman = $DB->get_manager();
    $plugin = 'block_taskchain_navigation';
    $select_size = 5;
    $cm_namelength = 40;
    $cm_headlength = 10;
    $cm_taillength = 10;
    $section_namelength = 48;
    $section_headlength = 18;
    $section_taillength = 18;
    // get previous or default form values
    $sections_array = optional_param_array('sections', array(), PARAM_INT);
    $modules_array = optional_param_array('modules', array(), PARAM_ALPHA);
    $cmids_array = optional_param_array('cmids', array(), PARAM_INT);
    $include = optional_param('include', '', PARAM_TEXT);
    $exclude = optional_param('exclude', '', PARAM_TEXT);
    $visibility = optional_param('visibility', -1, PARAM_INT);
    // available from/until dates
    $time = time();
    $fromdisable = optional_param('fromdisable', 0, PARAM_INT);
    $untildisable = optional_param('untildisable', 0, PARAM_INT);
    $cutoffdisable = optional_param('cutoffdisable', 0, PARAM_INT);
    list($availablefrom, $fromdate) = get_timestamp_and_date('from', null, $time, $fromdisable);
    list($availableuntil, $untildate) = get_timestamp_and_date('until', null, $time, $untildisable);
    list($availablecutoff, $cutoffdate) = get_timestamp_and_date('cutoff', null, $time, $cutoffdisable);
    $sortgradeitems = optional_param('sortgradeitems', 0, PARAM_INT);
    $creategradecats = optional_param('creategradecats', 0, PARAM_INT);
    $removegradecats = optional_param('removegradecats', 0, PARAM_INT);
    $rating = optional_param('rating', 0, PARAM_INT);
    $maxgrade = optional_param('maxgrade', 100, PARAM_INT);
    $gradepass = optional_param('gradepass', 60, PARAM_INT);
    $gradecat = optional_param('gradecat', 0, PARAM_INT);
    $gradeitemhidden = optional_param('gradeitemhidden', 0, PARAM_INT);
    $extracredit = optional_param('extracredit', 0, PARAM_INT);
    $regrade = optional_param('regrade', 0, PARAM_INT);
    $groupmode = optional_param('groupmode', 0, PARAM_INT);
    $groupingid = optional_param('groupingid', 0, PARAM_INT);
    $groupmembersonly = optional_param('groupmembersonly', 0, PARAM_INT);
    $sortactivities = optional_param('sortactivities', 0, PARAM_INT);
    $visible = optional_param('visible', 1, PARAM_INT);
    $indent = optional_param('indent', 0, PARAM_INT);
    $section = optional_param('section', 0, PARAM_INT);
    $position = optional_param('position', 0, PARAM_INT);
    $uploadlimit = optional_param('uploadlimit', 0, PARAM_INT);
    $siteuploadlimit = get_config(null, 'maxbytes');
    $courseuploadlimit = $course->maxbytes;
    $uploadlimitmenu = get_max_upload_sizes($siteuploadlimit, $courseuploadlimit);
    $removeconditions = optional_param('removeconditions', 0, PARAM_INT);
    $removecompletion = optional_param('removecompletion', 0, PARAM_INT);
    $erasecompletion = optional_param('erasecompletion', 0, PARAM_INT);
    // course_modules_availability OR course_modules.availability
    $conditiondatedirection = optional_param_array('conditiondatedirection', array(0), PARAM_INT);
    $conditiongradeitemid = optional_param_array('conditiongradeitemid', array(0), PARAM_INT);
    $conditiongrademin = optional_param_array('conditiongrademin', array(60), PARAM_INT);
    $conditiongrademax = optional_param_array('conditiongrademax', array(100), PARAM_INT);
    $conditionfieldname = optional_param_array('conditionfieldname', array(''), PARAM_ALPHANUM);
    $conditionfieldoperator = optional_param_array('conditionfieldoperator', array(''), PARAM_ALPHANUM);
    $conditionfieldvalue = optional_param_array('conditionfieldvalue', array(''), PARAM_ALPHANUM);
    $conditiongroupid = optional_param_array('conditiongroupid', array(0), PARAM_INT);
    $conditiongroupingid = optional_param_array('conditiongroupingid', array(0), PARAM_INT);
    $conditioncmid = optional_param_array('conditioncmid', array(0), PARAM_INT);
    // may be negative NEXT/PREVIOUS_ANY_COURSE/SECTION
    $conditioncmungraded = optional_param_array('conditioncmungraded', array(0), PARAM_INT);
    // 0=skip, 1=include ungraded activities
    $conditioncmresources = optional_param_array('conditioncmresources', array(0), PARAM_INT);
    // 0=skip, 1=include resources
    $conditioncmlabels = optional_param_array('conditioncmlabels', array(0), PARAM_INT);
    // 0=skip, 1=include labels
    $conditioncmcompletion = optional_param_array('conditioncmcompletion', array(1), PARAM_INT);
    // 0=incomplete, 1=complete, 2=pass, 3=fail
    $conditionaction = optional_param_array('conditionaction', array(1), PARAM_INT);
    // 0=hide, 1=show(greyed out)
    // course_modules.xxx
    $completiontracking = optional_param('completiontracking', 0, PARAM_INT);
    $completionday = optional_param('completionday', 0, PARAM_INT);
    $completionmonth = optional_param('completionmonth', 0, PARAM_INT);
    $completionyear = optional_param('completionyear', 0, PARAM_INT);
    // there may also be a number of activity-specific completion fields
    // (e.g. the "completionpass" field used by the Quiz and TaskChain modules)
    // there may also be a number of fields to enable/disable filters
    // (e.g. "filterglossary", "filtermediaplugin")
    // Competency settings
    $competencyrule = optional_param('competencyrule', 0, PARAM_INT);
    $conditiondate = array();
    $conditiondatetime = array();
    foreach ($conditiondatedirection as $i => $d) {
        switch ($d) {
            case 1:
                $d = '>=';
                break;
            case 2:
                $d = '<=';
                break;
            default:
                continue;
        }
        list($t, $date) = get_timestamp_and_date('conditiondatetime', $i, $time);
        $conditiondate[$i] = (object) array('type' => 'date', 'd' => $d, 't' => $t);
        $conditiondatetime[$i] = $date;
    }
    $conditiongrade = array();
    foreach ($conditiongradeitemid as $i => $id) {
        if ($id == 0) {
            continue;
        }
        $conditiongrade[] = (object) array('type' => 'grade', 'id' => $id, 'min' => empty($conditiongrademin[$i]) ? 0 : $conditiongrademin[$i], 'max' => empty($conditiongrademax[$i]) ? 100 : $conditiongrademax[$i]);
    }
    $conditionfield = array();
    foreach ($conditionfieldname as $i => $name) {
        if ($name == '') {
            continue;
        }
        $conditionfield[] = (object) array('type' => 'profile', 'sf' => $name, 'op' => empty($conditionfieldoperator[$i]) ? '' : $conditionfieldoperator[$i], 'v' => empty($conditionfieldvalue[$i]) ? '' : $conditionfieldvalue[$i]);
    }
    $conditiongroup = array();
    foreach ($conditiongroupid as $i => $id) {
        if ($id == 0) {
            continue;
        }
        $conditiongroup[] = (object) array('type' => 'group', 'id' => $id);
    }
    $conditiongrouping = array();
    foreach ($conditiongroupingid as $i => $id) {
        if ($id == 0) {
            continue;
        }
        $conditiongrouping[] = (object) array('type' => 'grouping', 'id' => $id);
    }
    $conditioncm = array();
    foreach ($conditioncmid as $i => $id) {
        if ($id == 0) {
            continue;
        }
        $conditioncm[] = (object) array('type' => 'completion', 'cm' => $id, 'e' => isset($conditioncmcompletion[$i]) ? $conditioncmcompletion[$i] : 1, 'ungraded' => empty($conditioncmungraded[$i]) ? 0 : 1, 'resources' => empty($conditioncmresources[$i]) ? 0 : 1, 'labels' => empty($conditioncmlabels[$i]) ? 0 : 1);
    }
    if ($completionday && $completionmonth && $completionyear) {
        $completiondate = make_timestamp($completionyear, $completionmonth, $completionday, 0, 0, 0, 99, false);
    } else {
        $completiondate = 0;
    }
    // add standard settings
    $settings = array('availablefrom', 'availableuntil', 'availablecutoff', 'rating', 'maxgrade', 'gradepass', 'gradecat', 'gradeitemhidden', 'extracredit', 'regrade', 'groupmode', 'groupingid', 'groupmembersonly', 'visible', 'indent', 'section', 'uploadlimit');
    // add switches to enable/disable filters
    $filters = filter_get_available_in_context($course->context);
    foreach (array_keys($filters) as $filter) {
        $setting = 'filter' . $filter;
        echo $setting;
        $settings[] = $setting;
        ${$setting} = optional_param($setting, null, PARAM_INT);
    }
    // add "availability" settings, if enabled
    if (empty($CFG->enableavailability)) {
        $enableavailability = false;
    } else {
        $enableavailability = true;
    }
    if ($enableavailability) {
        array_push($settings, 'removeconditions', 'conditiondate', 'conditiongrade', 'conditionfield', 'conditiongroup', 'conditiongrouping', 'conditioncm', 'conditionaction');
    }
    // add "completion" settings, if enabled
    if (empty($CFG->enablecompletion) || empty($course->enablecompletion)) {
        $enablecompletion = false;
    } else {
        $enablecompletion = true;
    }
    if ($enablecompletion) {
        array_push($settings, 'removecompletion', 'erasecompletion', 'completiontracking', 'completiondate');
    }
    // are we using competencies
    // (available in Moodle >= 3.1)
    if (get_config('core_competency', 'enabled')) {
        $enablecompetency = true;
    } else {
        $enablecompetency = false;
    }
    if ($enablecompetency) {
        array_push($settings, 'competencyrule');
    }
    // custom html tags that delimit section title in the section summary
    $sectiontags = $block_instance->config->sectiontitletags;
    $sectiontags = optional_param('sectiontags', $sectiontags, PARAM_TEXT);
    // set course section type
    if ($course->format == 'weeks') {
        $sectiontype = 'week';
    } else {
        if ($course->format == 'topics') {
            $sectiontype = 'topic';
        } else {
            $sectiontype = 'section';
        }
    }
    if (count($sections_array) || count($modules_array) || $include || $exclude || $visibility >= 0 || count($cmids_array)) {
        $select_defaultvalue = true;
    } else {
        $select_defaultvalue = false;
    }
    // set date format for course sections
    $weekdateformat = '%b %d';
    // get_string('strftimedateshort');
    if ($sortactivities) {
        $select = 'cm.id, gi.sortorder';
        $from = '{grade_items} gi ' . 'JOIN {modules} m ON gi.itemmodule = m.name ' . 'JOIN {course_modules} cm ON cm.module = m.id AND cm.instance = gi.iteminstance';
        $where = 'gi.courseid = ? AND gi.itemtype = ?';
        $order = 'gi.sortorder';
        $params = array($course->id, 'mod');
        $items = $DB->get_records_sql("SELECT {$select} FROM {$from} WHERE {$where} ORDER BY {$order}", $params);
        $select = 'id,sequence,section,summary';
        $from = '{course_sections}';
        $where = 'course = ? AND sequence IS NOT NULL AND sequence <> ?';
        $order = 'section';
        $params = array($course->id, '');
        $sections = $DB->get_records_sql("SELECT {$select} FROM {$from} WHERE {$where} ORDER BY {$order}", $params);
        if ($items && $sections) {
            $modinfo = get_fast_modinfo($course);
            $rebuild_course_cache = false;
            foreach (array_keys($sections) as $id) {
                $sequence = explode(',', $sections[$id]->sequence);
                $sequence = array_flip($sequence);
                foreach (array_keys($sequence) as $cmid) {
                    if (array_key_exists($cmid, $items)) {
                        // assign new sortorder to activity
                        $sequence[$cmid] = $items[$cmid]->sortorder;
                    } else {
                        if (isset($modinfo->cms[$cmid])) {
                            // no grade book item (e.g. label)
                            $name = urldecode($modinfo->cms[$cmid]->name);
                            $name = block_taskchain_navigation::filter_text($name);
                            $name = trim(strip_tags($name));
                            $sequence[$cmid] = $name;
                            unset($modinfo->cms[$cmid]);
                        } else {
                            unset($sequence[$cmid]);
                            // shouldn't happen !!
                        }
                    }
                }
                uasort($sequence, 'activity_sequence_uasort');
                $sequence = array_keys($sequence);
                $sequence = implode(',', $sequence);
                if ($sequence != $sections[$id]->sequence) {
                    $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $id));
                    $rebuild_course_cache = true;
                }
            }
            if ($rebuild_course_cache) {
                rebuild_course_cache($course->id);
                if (class_exists('course_modinfo')) {
                    // Moodle >= 2.4
                    get_fast_modinfo($course, 0, true);
                } else {
                    // Moodle <= 2.3
                    get_fast_modinfo('reset');
                }
                $course = $DB->get_record('course', array('id' => $course->id));
            }
        }
        unset($items, $sections, $modinfo, $sequence, $name, $cmid, $id);
    }
    $cms = array();
    $modules = array();
    $sections = array();
    $filemods = array();
    $labelmods = array();
    $ratingmods = array();
    $resourcemods = array();
    $gradingmods = array();
    $cutoffdatemods = array();
    $completionfields = array();
    $durationfields = array('completiontimespent');
    $count_cmids = 0;
    $selected_cmids = array();
    $strman = get_string_manager();
    // cache of section visibility by sectionnum
    // Note: could be ommited if we are not bothered about visibility
    // if ($visibility>=0 || array_key_exists('visible', $selected_settings)) {
    // }
    $section_visible = $DB->get_records_menu('course_sections', array('course' => $course->id), 'section', 'section, visible');
    $section_visible = array_map('intval', $section_visible);
    $section_visible[0] = 1;
    // intro is always visible
    $modinfo = get_fast_modinfo($course);
    foreach ($modinfo->sections as $sectionnum => $cmids) {
        // loop through the course modules
        foreach ($cmids as $cmid) {
            if (empty($modinfo->cms[$cmid])) {
                continue;
                // shouldn't happen
            }
            // shortcut to current course modules
            $cm = $modinfo->cms[$cmid];
            $count_cmids++;
            $sections[$sectionnum] = true;
            if (empty($modules[$cm->modname])) {
                $modules[$cm->modname] = get_string('modulename', $cm->modname);
                if ($modhaslibfile = file_exists("{$CFG->dirroot}/mod/{$cm->modname}/lib.php")) {
                    $modcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES, false);
                } else {
                    $modcompletion = false;
                }
                // get completion fields
                if ($enablecompletion) {
                    if ($modcompletion) {
                        $fields = $DB->get_columns($cm->modname);
                        $names = array_keys($fields);
                        $names = preg_grep('/^completion.+$/', $names);
                        $names = array_values($names);
                        // re-index the array
                    } else {
                        $names = array();
                        // no module-specific fields
                        $fields = array();
                    }
                    if ($modhaslibfile) {
                        // fields that are common to all modules - see "lib/moodleform_mod.php"
                        if (plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE, false)) {
                            array_unshift($names, 'completiongrade');
                        }
                        if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
                            array_unshift($names, 'completionview');
                        }
                    }
                    foreach ($names as $name) {
                        if (empty($completionfields[$name])) {
                            $settings[] = $name;
                            if (isset($_POST[$name]) && is_array($_POST[$name])) {
                                ${$name} = optional_param_array($name, array(), PARAM_INT);
                                ${$name} = array_sum(${$name});
                                // i.e. same as logical AND
                            } else {
                                ${$name} = optional_param($name, 0, PARAM_INT);
                            }
                            if (in_array($name, $durationfields)) {
                                ${$name} *= optional_param($name . '_unit', 1, PARAM_INT);
                            }
                            $completionfields[$name] = get_completionfield($strman, $plugin, $cm->modname, $name, ${$name}, $fields);
                        }
                        $completionfields[$name]->mods[$cm->modname] = $modules[$cm->modname];
                    }
                    unset($fields, $names, $name);
                }
                // get file sitewide upload limits, if any, for this module
                switch ($cm->modname) {
                    case 'assign':
                        $filemods[$cm->modname] = get_config('assignsubmission_file', 'maxbytes');
                        break;
                    case 'assignment':
                        $filemods[$cm->modname] = get_config(null, 'assignment_maxbytes');
                        break;
                    case 'forum':
                        $filemods[$cm->modname] = get_config(null, 'forum_maxbytes');
                        break;
                    case 'workshop':
                        $filemods[$cm->modname] = get_config('workshop', 'maxbytes');
                        break;
                }
                if ($modhaslibfile) {
                    $is_label = plugin_supports('mod', $cm->modname, FEATURE_NO_VIEW_LINK, false) == true;
                    $is_resource = plugin_supports('mod', $cm->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER) == MOD_ARCHETYPE_RESOURCE;
                    $has_rating = plugin_supports('mod', $cm->modname, FEATURE_RATE, false) == true;
                } else {
                    $is_label = in_array($cm->modname, array('label'));
                    $is_resource = in_array($cm->modname, array('book', 'folder', 'imscp', 'page', 'resource', 'url'));
                    $has_rating = in_array($cm->modname, array('data', 'forum', 'glossary'));
                }
                if ($has_grading = defined('FEATURE_ADVANCED_GRADING')) {
                    // Moodle >= 2.2
                    if ($modhaslibfile) {
                        $has_grading = plugin_supports('mod', $cm->modname, FEATURE_ADVANCED_GRADING, false) == true;
                    } else {
                        $has_grading = in_array($cm->modname, array('assign'));
                    }
                }
                if ($is_label) {
                    $labelmods[] = $cm->modname;
                } else {
                    if ($is_resource) {
                        $resourcemods[] = $cm->modname;
                    }
                }
                if ($has_rating) {
                    $ratingmods[$cm->modname] = $modules[$cm->modname];
                }
                // ==================================
                // disabled until fully functional
                // ==================================
                // if ($has_grading) {
                //     $gradingareas[$cm->modname] = grading_manager::available_areas('mod_'.$cm->modname);
                //     if (empty($gradingareas[$cm->modname])) {
                //         unset($gradingareas[$cm->modname]);
                //     } else {
                //         $gradingmods[$cm->modname] = $modules[$cm->modname];
                //     }
                // }
                if (in_array($cm->modname, array('assign'))) {
                    $cutoffdatemods[$cm->modname] = $modules[$cm->modname];
                }
                unset($is_label, $is_resource, $has_rating, $has_grading, $modhaslibfile, $modcompletion);
            }
            if (empty($cms[$sectionnum])) {
                $cms[$sectionnum] = array();
            }
            if (in_array($cmid, $cmids_array)) {
                $selected = ' selected="selected"';
            } else {
                $selected = '';
            }
            $url = $PAGE->theme->pix_url('icon', $cm->modname)->out();
            $style = ' style="background-image: url(' . $url . '); background-repeat: no-repeat; background-position: 1px 2px; min-height: 20px; padding-left: 12px;"';
            $name = urldecode($cm->name);
            $name = block_taskchain_navigation::filter_text($name);
            $name = trim(strip_tags($name));
            $name = block_taskchain_navigation::trim_text($name, $cm_namelength, $cm_headlength, $cm_taillength);
            $cms[$sectionnum][] = '<option value="' . $cm->id . '"' . $selected . $style . '>' . $name . '</option>';
            $select = $select_defaultvalue;
            if ($select && count($sections_array)) {
                $select = in_array($cm->sectionnum, $sections_array);
            }
            if ($select && count($modules_array)) {
                $select = in_array($cm->modname, $modules_array);
            }
            if ($select && $include) {
                $select = preg_match('/' . $include . '/', $cm->name);
            }
            if ($select && $exclude) {
                $select = !preg_match('/' . $exclude . '/', $cm->name);
            }
            if ($select && $visibility >= 0) {
                if ($section_visible[$cm->sectionnum]) {
                    $select = $visibility == $cm->visible;
                } else {
                    // in a hidden section, we need to check the activity module's "visibleold" setting
                    $select = $visibility == $DB->get_field('course_modules', 'visibleold', array('id' => $cm->id));
                }
            }
            if ($select && count($cmids_array)) {
                $select = in_array($cm->id, $cmids_array);
            }
            if ($select) {
                $selected_cmids[$cm->id] = $cm;
            }
        }
    }
    // $completionfields now contains additional "completion"
    // fields used by activity modules on this Moodle site
    // these fields have also been added to $settings
    $selected_settings = array();
    if ($action == 'apply') {
        foreach ($settings as $setting) {
            $select = 'select_' . $setting;
            if (optional_param($select, 0, PARAM_INT)) {
                $selected_settings[] = $setting;
            }
        }
    }
    $sectionmenu = array(-1 => get_string('currentsection', $plugin), '-' => '-----');
    // separator
    $sectionnums = array_keys($sections);
    if ($sections = $DB->get_records('course_sections', array('course' => $course->id), 'section', 'section,name,summary')) {
        foreach ($sections as $sectionnum => $sectioninfo) {
            // extract section title from section name or summary
            if ($text = block_taskchain_navigation::filter_text($sectioninfo->name)) {
                $text = block_taskchain_navigation::trim_text($text, $section_namelength, $section_headlength, $section_taillength);
            } else {
                if ($text = block_taskchain_navigation::filter_text($sectioninfo->summary)) {
                    // remove script and style blocks
                    $select = '/\\s*<(script|style)[^>]*>.*?<\\/\\1>\\s*/is';
                    $text = preg_replace($select, '', $text);
                    if ($tags = $sectiontags) {
                        $tags = preg_split('/[^a-zA-Z0-9]+/', $tags);
                        $tags = array_map('trim', $tags);
                        $tags = array_filter($tags);
                        $tags = implode('|', $tags);
                        if ($tags) {
                            $tags .= '|';
                        }
                    }
                    $tags .= 'h1|h2|h3|h4|h5|h6';
                    if (preg_match('/<(' . $tags . ')\\b[^>]*>(.*?)<\\/\\1>/is', $text, $matches)) {
                        $text = $matches[2];
                    } else {
                        // otherwise, get first line of text
                        $text = preg_split('/<br[^>]*>/', $text);
                        $text = array_map('strip_tags', $text);
                        $text = array_map('trim', $text);
                        $text = array_filter($text);
                        if (empty($text)) {
                            $text = '';
                        } else {
                            $text = reset($text);
                        }
                    }
                    $text = trim(strip_tags($text));
                    $text = block_taskchain_navigation::trim_text($text, $section_namelength, $section_taillength, $section_taillength);
                }
            }
            // set default section title, if necessary
            if ($text == '') {
                $format = 'format_' . $course->format;
                switch (true) {
                    case $sectiontype == 'week' && $sectionnum > 0:
                        $date = $course->startdate + 7200 + ($sectionnum - 1) * 604800;
                        $text = userdate($date, $weekdateformat) . ' - ' . userdate($date + 518400, $weekdateformat);
                        break;
                    case $strman->string_exists('section' . $sectionnum . 'name', $format):
                        $text = get_string('section' . $sectionnum . 'name', $format);
                        break;
                    case $strman->string_exists('sectionname', $format):
                        $text = get_string('sectionname', $format) . ' ' . $sectionnum;
                        break;
                    case $strman->string_exists($sectiontype, 'moodle'):
                        $text = get_string('sectionname') . ' ' . $sectionnum;
                        break;
                    default:
                        $text = $sectiontype . ' ' . $sectionnum;
                }
            }
            // assign section title
            if (in_array($sectionnum, $sectionnums)) {
                $sections[$sectionnum] = $text;
            } else {
                unset($sections[$sectionnum]);
            }
            $sectionmenu[$sectionnum] = $text;
        }
    }
    foreach ($cms as $sectionnum => $options) {
        unset($cms[$sectionnum]);
        $text = $sections[$sectionnum];
        $cms[$text] = '<optgroup label="' . $text . '">' . "\n" . implode("\n", $options) . '</optgroup>';
    }
    $cms = implode("\n", $cms);
    $cms = '<select id="id_cmids" name="cmids[]" size="' . min($select_size, $count_cmids) . '" multiple="multiple">' . "\n" . $cms . "\n" . '</select>' . "\n";
    foreach ($sections as $sectionnum => $text) {
        if (in_array($sectionnum, $sections_array)) {
            $selected = ' selected="selected"';
        } else {
            $selected = '';
        }
        $sections[$sectionnum] = '<option value="' . $sectionnum . '"' . $selected . '>' . $text . '</option>';
    }
    $count_sections = count($sections);
    $sections = implode("\n", $sections);
    $sections = '<select id="id_sections" name="sections[]" size="' . min($select_size, $count_sections) . '" multiple="multiple">' . "\n" . $sections . "\n" . '</select>' . "\n";
    asort($modules);
    foreach ($modules as $module => $text) {
        if (in_array($module, $modules_array)) {
            $selected = ' selected="selected"';
        } else {
            $selected = '';
        }
        if (empty($CFG->modpixpath)) {
            $style = '';
            // shouldn't happen
        } else {
            $url = $CFG->modpixpath . '/' . $module . '/icon.gif';
            $style = ' style="background-image: url(' . $url . '); background-repeat: no-repeat; background-position: 1px 2px; min-height: 20px; padding-left: 20px;"';
        }
        $modules[$module] = '<option value="' . $module . '"' . $selected . $style . '>' . $text . '</option>';
    }
    $count_modules = count($modules);
    $modules = implode("\n", $modules);
    $modules = '<select id="id_modules" name="modules[]" size="' . min($select_size, $count_modules) . '" multiple="multiple">' . "\n" . $modules . "\n" . '</select>' . "\n";
    $days = array();
    for ($i = 1; $i <= 31; $i++) {
        $days[$i] = $i;
    }
    $months = array();
    for ($i = 1; $i <= 12; $i++) {
        $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
    }
    $years = array();
    for ($i = 1970; $i <= 2020; $i++) {
        $years[$i] = $i;
    }
    $hours = array();
    for ($i = 0; $i <= 23; $i++) {
        $hours[$i] = sprintf('%02d', $i);
    }
    $minutes = array();
    for ($i = 0; $i < 60; $i += 5) {
        $minutes[$i] = sprintf('%02d', $i);
    }
    $visibilitymenu = array(-1 => '', 0 => get_string('hidden', 'grades'), 1 => get_string('visible'));
    $visiblemenu = array(0 => get_string('hide'), 1 => get_string('show'));
    $ratings = new rating_manager();
    $ratings = $ratings->get_aggregate_types();
    $gradings = array();
    $maxgrades = array();
    $gradepassmenu = array();
    for ($i = 100; $i >= 1; $i--) {
        $maxgrades[$i] = $i . '%';
        $gradepassmenu[$i] = $i . '%';
    }
    $maxgrades[0] = get_string('nograde');
    $gradecategories = grade_get_categories_menu($course->id);
    $groupmodes = array(NOGROUPS => get_string('groupsnone'), SEPARATEGROUPS => get_string('groupsseparate'), VISIBLEGROUPS => get_string('groupsvisible'));
    //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
    $groupings = array();
    if ($records = $DB->get_records('groupings', array('courseid' => $course->id))) {
        $groupings = array(0 => get_string('none'));
        foreach ($records as $record) {
            $groupings[$record->id] = format_string($record->name);
        }
    }
    $indentmenu = array();
    for ($i = -5; $i <= 5; $i++) {
        if ($i == 0) {
            $indentmenu[$i] = get_string('reset');
        } else {
            $indentmenu[$i] = ($i < 0 ? '-' : '+') . abs($i);
        }
    }
    $positionmenu = array(1 => get_string('startofsection', $plugin), 2 => get_string('endofsection', $plugin));
    if ($strman->string_exists('direction_from', 'availability_date')) {
        // Moodle >= 2.7
        $conditiondatedirectionmenu = array(1 => get_string('direction_from', 'availability_date'), 2 => get_string('direction_until', 'availability_date'));
    } else {
        // Moodle >= 2.6
        $conditiondatedirectionmenu = array(1 => get_string('from'), 2 => get_string('durationuntil', 'calendar'));
    }
    $conditiongradeitemidmenu = array();
    $conditioncmidmenu = array();
    $conditionfieldnamemenu = array();
    $conditionfieldoperatormenu = array();
    $conditiongroupidmenu = array();
    $conditiongroupingidmenu = array();
    $conditionactionmenu = array();
    $conditioncmcompletionmenu = array();
    if ($enableavailability) {
        $basemenuitems = array('0' => get_string('none', 'moodle'), '00' => '=====', PREVIOUS_ANY_COURSE => get_string('previousanycourse', $plugin), PREVIOUS_ANY_SECTION => get_string('previousanysection', $plugin), PREVIOUS_SAME_COURSE => get_string('previoussamecourse', $plugin), PREVIOUS_SAME_SECTION => get_string('previoussamesection', $plugin), '000' => '=====', NEXT_ANY_COURSE => get_string('nextanycourse', $plugin), NEXT_ANY_SECTION => get_string('nextanysection', $plugin), NEXT_SAME_COURSE => get_string('nextsamecourse', $plugin), NEXT_SAME_SECTION => get_string('nextsamesection', $plugin), '0000' => '=====');
        $categories = grade_category::fetch_all(array('courseid' => $course->id));
        if ($items = grade_item::fetch_all(array('courseid' => $course->id))) {
            uasort($items, 'grade_items_uasort');
            $spaces = '';
            $space = '│ ';
            $ids = array_keys($items);
            foreach ($ids as $i => $id) {
                $item = $items[$id];
                if ($item->is_course_item()) {
                    $depth = 0;
                    $index = '';
                } else {
                    if ($item->is_category_item()) {
                        if ($depth = $DB->get_field('grade_categories', 'depth', array('id' => $item->iteminstance))) {
                            if ($depth > 1) {
                                $depth--;
                            }
                        }
                        $spaces = str_repeat($space, $depth - 1);
                    } else {
                        $spaces = str_repeat($space, $depth);
                    }
                }
                $name = $spaces . get_tree_char($depth, $i, $ids, $items, $categories) . $item->get_name(true);
                $name = block_taskchain_navigation::trim_text($name, $cm_namelength, $cm_headlength + strlen($spaces), $cm_taillength);
                $items[$id] = $name;
            }
            if (count($items)) {
                $conditiongradeitemidmenu = $basemenuitems + $items;
            }
        }
        if ($enablecompletion) {
            $items = array();
            $modinfo = get_fast_modinfo($course);
            foreach ($modinfo->cms as $id => $cm) {
                if ($cm->completion) {
                    $items[$id] = $cm->name;
                }
            }
            if (count($items)) {
                asort($items);
                $conditioncmidmenu = $basemenuitems + $items;
            }
        }
        $conditionfieldnamemenu = array('' => get_string('none', 'moodle'));
        $conditionfieldoperatormenu = array();
        $filepath = $CFG->dirroot . '/availability/condition/profile/classes/frontend.php';
        if (file_exists($filepath)) {
            // Moodle >= 2.7
            $contents = file_get_contents($filepath);
            $search = "/'([a-zA-Z0-9]+)' => get_user_field_name\\('\\1'\\)/";
            if (preg_match_all($search, $contents, $items)) {
                foreach ($items[1] as $item) {
                    $conditionfieldnamemenu[$item] = get_user_field_name($item);
                }
            }
            $search = "/(?<=')op_([a-zA-Z0-9]+)(?=')/";
            if (preg_match_all($search, $contents, $items)) {
                foreach ($items[1] as $i => $item) {
                    $conditionfieldoperatormenu[$item] = get_string($items[0][$i], 'availability_profile');
                }
            }
            require_once $CFG->dirroot . '/user/profile/lib.php';
            if ($items = profile_get_custom_fields(true)) {
                foreach ($items as $item) {
                    $conditionfieldnamemenu[$item->shortname] = $item->name;
                }
            }
        } else {
            if (method_exists('condition_info', 'get_condition_user_fields')) {
                // Moodle >= 2.4
                if ($items = condition_info::get_condition_user_fields(array('context' => $course->context))) {
                    $conditionfieldnamemenu += $items;
                }
                $conditionfieldoperatormenu = condition_info::get_condition_user_field_operators();
            } else {
                // Moodle <= 2.3 doesn't have conditional user fields
                $conditionfieldnamemenu = array();
            }
        }
        if ($dbman->field_exists('course_modules', 'availability')) {
            // Moodle >= 2.7
            if ($items = groups_get_all_groups($course->id)) {
                foreach ($items as $item) {
                    $name = $item->name;
                    $name = block_taskchain_navigation::filter_text($name);
                    $name = block_taskchain_navigation::trim_text($name);
                    $conditiongroupidmenu[$item->id] = $name;
                }
            }
            if ($items = groups_get_all_groupings($course->id)) {
                foreach ($items as $item) {
                    $name = $item->name;
                    $name = block_taskchain_navigation::filter_text($name);
                    $name = block_taskchain_navigation::trim_text($name);
                    $conditiongroupingidmenu[$item->id] = $name;
                }
            }
        }
        $str = new stdClass();
        if ($strman->string_exists('accessrestrictions', 'availability')) {
            // Moodle >= 2.7
            $str->accessrestrictions = get_string('accessrestrictions', 'availability');
            $str->datetitle = get_string('title', 'availability_date');
            $str->userfield = get_string('conditiontitle', 'availability_profile');
            $str->gradetitle = get_string('title', 'availability_grade');
            $str->grademin = get_string('option_min', 'availability_grade');
            $str->grademax = get_string('option_max', 'availability_grade');
            $str->activitycompletion = get_string('activitycompletion', 'completion');
            $conditioncmcompletionmenu = array(COMPLETION_COMPLETE => get_string('option_complete', 'availability_completion'), COMPLETION_INCOMPLETE => get_string('option_incomplete', 'availability_completion'), COMPLETION_COMPLETE_PASS => get_string('option_pass', 'availability_completion'), COMPLETION_COMPLETE_FAIL => get_string('option_fail', 'availability_completion'));
            $str->showavailability = get_string('display', 'form');
            // Note: CONDITION_STUDENTVIEW_xxx constants are not defined in Moodle >= 2.9
            $hide = defined('CONDITION_STUDENTVIEW_HIDE') ? CONDITION_STUDENTVIEW_HIDE : 0;
            $show = defined('CONDITION_STUDENTVIEW_SHOW') ? CONDITION_STUDENTVIEW_SHOW : 1;
            $conditionactionmenu = array($hide => get_string('hidden_all', 'availability'), $show => get_string('shown_all', 'availability'));
        } else {
            // Moodle <= 2.6
            $str->accessrestrictions = get_string('availabilityconditions', 'condition');
            $str->datetitle = get_string('date');
            if ($strman->string_exists('userfield', 'condition')) {
                // Moodle >= 2.4
                $str->userfield = get_string('userfield', 'condition');
            }
            $str->gradetitle = get_string('gradecondition', 'condition');
            $str->grademin = get_string('grade_atleast', 'condition');
            $str->grademax = get_string('grade_upto', 'condition');
            $str->activitycompletion = get_string('completioncondition', 'condition');
            $conditioncmcompletionmenu = 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'));
            $str->showavailability = get_string('showavailability', 'condition');
            $conditionactionmenu = array(CONDITION_STUDENTVIEW_HIDE => get_string('showavailability_hide', 'condition'), CONDITION_STUDENTVIEW_SHOW => get_string('showavailability_show', 'condition'));
        }
        $icon = new pix_icon('i/hide', '');
        $icon = $OUTPUT->render($icon);
        $str->showavailability = $icon . ' ' . $str->showavailability;
        if ($enablecompletion) {
            $str->conditioncmungraded = get_string('conditioncmungraded', $plugin);
            $str->conditioncmresources = get_string('conditioncmresources', $plugin);
            $str->conditioncmlabels = get_string('conditioncmlabels', $plugin);
        }
    }
    if ($enablecompletion) {
        $completiontrackingmenu = array(0 => get_string('completion_none', 'completion'), 1 => get_string('completion_manual', 'completion'), 2 => get_string('completion_automatic', 'completion'));
    } else {
        $completiontrackingmenu = array();
    }
    if (class_exists('core_competency\\course_module_competency')) {
        // Moodle >= 3.1
        $competencyrulemenu = \core_competency\course_module_competency::get_ruleoutcome_list();
    } else {
        $competencyrulemenu = array();
    }
    $filtermenu = array(TEXTFILTER_INHERIT => '', TEXTFILTER_OFF => get_string('off', 'filters'), TEXTFILTER_ON => get_string('on', 'filters'));
    $filterdefaulton = get_string('defaultx', 'filters', $filtermenu[TEXTFILTER_ON]);
    $filterdefaultoff = get_string('defaultx', 'filters', $filtermenu[TEXTFILTER_OFF]);
    // initialize state flags
    $success = null;
    $started_list = false;
    $reset_filter_caches = false;
    $rebuild_course_cache = false;
    $regrade_course_grades = false;
    // create grade categories, if necessary
    if ($creategradecats) {
        $modinfo = get_fast_modinfo($course);
        // default aggregate is "simple weighted mean of grades"
        // TODO: set default aggregate from form
        $aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
        // get max sortorder from database
        if ($sortorder = $DB->get_field('grade_items', 'MAX(sortorder)', array('courseid' => $course->id))) {
            $sortorder++;
        } else {
            $sortorder = 1;
        }
        // create course grade category - not usually necessary
        $fullname = '?';
        // special name for course grade category
        $params = array('courseid' => $course->id, 'depth' => 1, 'fullname' => $fullname);
        if ($course_grade_category_id = $DB->get_field('grade_categories', 'id', $params)) {
            $DB->set_field('grade_categories', 'aggregation', $aggregation, $params);
        } else {
            $course_grade_category_id = create_grade_category($course, $fullname, null, $aggregation, 0.0, $sortorder++, GRADE_DISPLAY_TYPE_PERCENTAGE);
        }
        // create/update section grade categories
        foreach ($sectionmenu as $sectionnum => $sectiontext) {
            if (empty($modinfo->sections[$sectionnum])) {
                continue;
            }
            $grade_category_id = 0;
            foreach ($modinfo->sections[$sectionnum] as $cmid) {
                if (empty($modinfo->cms[$cmid])) {
                    continue;
                }
                $params = array('courseid' => $course->id, 'itemtype' => 'mod', 'itemmodule' => $modinfo->cms[$cmid]->modname, 'iteminstance' => $modinfo->cms[$cmid]->instance);
                if (!($grade_items = $DB->get_records('grade_items', $params))) {
                    continue;
                }
                // note that some activities can have more than on grade item per instance
                // e.g. mod_workshop creates both "submission" and "assessment" grade items
                foreach ($grade_items as $grade_item) {
                    if ($grade_category_id == 0) {
                        $fullname = $sectiontext;
                        $params = array('courseid' => $course->id, 'depth' => 2, 'fullname' => $fullname);
                        if ($grade_category_id = $DB->get_field('grade_categories', 'id', $params)) {
                            $DB->set_field('grade_categories', 'aggregation', $aggregation, array('id' => $grade_category_id));
                        } else {
                            $grade_category_id = create_grade_category($course, $fullname, $course_grade_category_id, $aggregation, 0.0, $sortorder++);
                        }
                    }
                    $DB->set_field('grade_items', 'categoryid', $grade_category_id, array('id' => $grade_item->id));
                    $DB->set_field('grade_items', 'sortorder', $sortorder++, array('id' => $grade_item->id));
                }
            }
        }
        $regrade_course_grades = true;
    }
    // remove grade categories, if necessary
    if ($removegradecats) {
        $select = 'DISTINCT categoryid';
        $from = '{grade_items}';
        $where = 'courseid = ? AND itemtype <> ? AND itemtype <> ?';
        $params = array($course->id, 'course', 'category');
        $select = "id IN (SELECT {$select} FROM {$from} WHERE {$where})";
        if ($ids = $DB->get_records_select('grade_categories', $select, $params, 'id', 'id,path')) {
            foreach (array_keys($ids) as $id) {
                $ids[$id] = trim($ids[$id]->path, '/');
            }
            $ids = array_filter($ids);
            $ids = implode('/', $ids);
            $ids = explode('/', $ids);
            $ids = array_unique($ids);
        } else {
            if ($ids = $DB->get_records('grade_categories', array('courseid' => $course->id, 'depth' => 1, 'fullname' => '?'))) {
                $ids = array(key($ids));
                // the course category
            }
        }
        if (empty($ids)) {
            $ids = '';
            $params = array();
        } else {
            list($ids, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_QM, '', false);
            // i.e. NOT IN
        }
        $select = 'courseid = ?' . ($ids == '' ? '' : " AND id {$ids}");
        array_unshift($params, $course->id);
        if ($DB->delete_records_select('grade_categories', $select, $params)) {
            $regrade_course_grades = true;
        }
        $select = 'itemtype = ? AND courseid = ?' . ($ids == '' ? '' : " AND iteminstance {$ids}");
        array_unshift($params, 'category');
        if ($DB->delete_records_select('grade_items', $select, $params)) {
            $regrade_course_grades = true;
        }
        unset($select, $from, $where, $params, $ids, $id);
    }
    // sort grade categories, if necessary
    if ($sortgradeitems) {
        $select = 'courseid = ? AND itemtype = ?';
        $params = array($course->id, 'mod');
        if ($items = $DB->get_records_select('grade_items', $select, $params, 'sortorder')) {
            $categories = array();
            foreach ($items as $item) {
                $categoryid = $item->categoryid;
                $cmid = 0;
                foreach ($modinfo->cms as $cmid => $cm) {
                    if ($item->itemmodule == $cm->modname && $item->iteminstance == $cm->instance) {
                        $cmid = $cm->id;
                        break;
                    }
                }
                if ($cmid) {
                    if (empty($categories[$categoryid])) {
                        $categories[$categoryid] = array();
                    }
                    $categories[$categoryid][$cmid] = $item->sortorder;
                }
            }
            $modinfo_cmids = array_keys($modinfo->cms);
            foreach (array_keys($categories) as $categoryid) {
                // get available cm ids and sortorder numbers
                $cmids = array_keys($categories[$categoryid]);
                $sortorder = array_values($categories[$categoryid]);
                // get course page sort order for each cm
                $cmids = array_flip($cmids);
                foreach (array_keys($cmids) as $cmid) {
                    $cmids[$cmid] = array_search($cmid, $modinfo_cmids);
                }
                // sort cmids according to course page order
                asort($cmids);
                // remove course page order info
                $cmids = array_keys($cmids);
                // assign an available sort order to each cm's grade item
                $select = 'courseid = ? AND itemtype = ? AND itemmodule = ? AND iteminstance = ?';
                foreach ($cmids as $i => $cmid) {
                    $params = array($course->id, 'mod', $modinfo->cms[$cmid]->modname, $modinfo->cms[$cmid]->instance);
                    $DB->set_field_select('grade_items', 'sortorder', $sortorder[$i], $select, $params);
                }
            }
        }
        unset($items, $categories, $cmids, $sortorder, $modinfo_cmids);
    }
    // update activities, if necessary
    if (count($selected_cmids) && (count($selected_settings) || $action == 'delete')) {
        $success = true;
        $fields = array('assign' => array('availablefrom' => 'allowsubmissionsfromdate', 'availableuntil' => 'duedate', 'maxgrade' => 'grade', 'rating' => ''), 'assignment' => array('availablefrom' => 'timeavailable', 'availableuntil' => 'timedue', 'maxgrade' => 'grade', 'rating' => ''), 'attendance' => array('availablefrom' => '', 'availableuntil' => '', 'maxgrade' => 'grade', 'rating' => ''), 'choice' => array('availablefrom' => 'timeopen', 'availableuntil' => 'timeclose', 'maxgrade' => '', 'rating' => ''), 'data' => array('availablefrom' => 'timeavailablefrom', 'availableuntil' => 'timeavailableto', 'maxgrade' => 'scale', 'rating' => 'assessed'), 'feedback' => array('availablefrom' => 'timeopen', 'availableuntil' => 'timeclose', 'maxgrade' => '', 'rating' => ''), 'forum' => array('availablefrom' => 'assesstimestart', 'availableuntil' => 'assesstimefinish', 'maxgrade' => 'scale', 'rating' => 'assessed'), 'glossary' => array('availablefrom' => 'assesstimestart', 'availableuntil' => 'assesstimefinish', 'maxgrade' => 'scale', 'rating' => 'assessed'), 'hotpot' => array('availablefrom' => 'timeopen', 'availableuntil' => 'timeclose', 'maxgrade' => 'grade', 'rating' => ''), 'lesson' => array('availablefrom' => 'available', 'availableuntil' => 'deadline', 'maxgrade' => 'grade', 'rating' => ''), 'questionnaire' => array('availablefrom' => 'opendate', 'availableuntil' => 'closedate', 'maxgrade' => 'grade', 'rating' => ''), 'quiz' => array('availablefrom' => 'timeopen', 'availableuntil' => 'timeclose', 'maxgrade' => 'grade', 'rating' => ''), 'reader' => array('availablefrom' => 'timeopen', 'availableuntil' => 'timeclose', 'maxgrade' => 'maxgrade', 'rating' => ''), 'scorm' => array('availablefrom' => 'timeopen', 'availableuntil' => 'timeclose', 'maxgrade' => 'maxgrade', 'rating' => ''), 'taskchain' => array('availablefrom' => 'timeopen', 'availableuntil' => 'timeclose', 'maxgrade' => 'gradelimit', 'rating' => ''), 'workshop' => array('availablefrom' => 'assessmentstart', 'availableuntil' => 'assessmentend', 'maxgrade' => 'grade ', 'rating' => ''));
        $table_columns = array();
        // make sure mod pix path is set
        if (empty($CFG->modpixpath)) {
            $CFG->modpixpath = $CFG->dirroot . '/mod';
        }
        foreach ($selected_cmids as $cmid => $cm) {
            $updated = false;
            $skipped = false;
            $regrade_item_id = 0;
            $modhaslibfile = file_exists("{$CFG->dirroot}/mod/{$cm->modname}/lib.php");
            // get the $instance of this $cm (include idnumber for grading)
            $instance = $DB->get_record($cm->modname, array('id' => $cm->instance));
            $instance->cmidnumber = $cm->idnumber;
            // get module context
            $modulecontext = context_module::instance($cm->id);
            if ($action == 'delete') {
                if (function_exists('course_delete_module')) {
                    // Moodle >= 2.5
                    course_delete_module($cm->id);
                } else {
                    // Moodle <= 2.4
                    $filepath = $CFG->dirroot . '/mod/' . $cm->modname . '/lib.php';
                    if (!file_exists($filepath)) {
                        $msg = "{$cm->modname} lib.php not found at {$filepath}";
                        echo $OUTPUT->notification($msg);
                    }
                    require_once $filepath;
                    $deleteinstancefunction = $cm->modname . '_delete_instance';
                    if (!function_exists($deleteinstancefunction)) {
                        $msg = "{$cm->modname} delete function not found ({$deleteinstancefunction})";
                        echo $OUTPUT->notification($msg);
                    }
                    // copied from "course/mod.php"
                    if (!$deleteinstancefunction($cm->instance)) {
                        $msg = "Could not delete the {$cm->modname} (instance id={$cm->instance})";
                        echo $OUTPUT->notification($msg);
                    }
                    if (!delete_course_module($cm->id)) {
                        $msg = "Could not delete the {$cm->modname} (coursemodule, id={$cm->id})";
                        echo $OUTPUT->notification($msg);
                    }
                    if (!($sectionid = $DB->get_field('course_sections', 'id', array('course' => $cm->course, 'section' => $cm->sectionnum)))) {
                        $msg = "Could not get section id (course id={$cm->course}, section num={$cm->sectionnum})";
                        echo $OUTPUT->notification($msg);
                    }
                    if (!delete_mod_from_section($cm->id, $sectionid)) {
                        $msg = "Could not delete the {$cm->modname} (id={$cm->id}) from that section (id={$sectionid})";
                        echo $OUTPUT->notification($msg);
                    }
                    add_to_log($cm->course, 'course', 'delete mod', "view.php?id={$cm->course}", "{$cm->modname} {$cm->instance}", $cm->id);
                }
                $rebuild_course_cache = true;
                $updated = true;
            }
            // only check completion/conditions once per $cm
            $conditions_checked = false;
            $completion_updated = false;
            // Note: $selected_settings should only contain anything if $action=='apply'
            foreach ($selected_settings as $setting) {
                switch ($setting) {
                    // activity instance settings
                    case 'availablefrom':
                    case 'availableuntil':
                    case 'availablecutoff':
                    case 'maxgrade':
                    case 'rating':
                        if ($cm->modname == 'taskchain') {
                            $table = 'taskchain_chains';
                            $id = $DB->get_field($table, 'id', array('parenttype' => 0, 'parentid' => $cm->instance));
                        } else {
                            $table = $cm->modname;
                            $id = $cm->instance;
                        }
                        // get list of fields in this $table
                        if (empty($table_columns[$table])) {
                            $table_columns[$table] = $DB->get_columns($table);
                            foreach (array_keys($table_columns[$table]) as $field) {
                                $table_columns[$table][$field] = true;
                            }
                        }
                        // convert setting name to database field name
                        if (isset($fields[$cm->modname][$setting])) {
                            $field = $fields[$cm->modname][$setting];
                        } else {
                            if ($setting == 'availablecutoff') {
                                $field = 'cutoffdate';
                            } else {
                                $field = $setting;
                            }
                        }
                        // update activity instance record, if field exists
                        if (empty($table_columns[$table][$field])) {
                            $skipped = true;
                        } else {
                            if ($DB->set_field($table, $field, ${$setting}, array('id' => $id))) {
                                // $$ is on purpose
                                $updated = true;
                            } else {
                                $success = false;
                            }
                        }
                        break;
                        // course_module settings
                    // course_module settings
                    case 'visible':
                        if ($section_visible[$cm->sectionnum]) {
                            $rebuild_course_cache = true;
                            $field = 'visible';
                        } else {
                            // hidden section - use "visibleold" field
                            // Note: there is no need to rebuild cache
                            $field = 'visibleold';
                        }
                        if ($DB->set_field('course_modules', $field, ${$setting}, array('id' => $cm->id))) {
                            $updated = true;
                        } else {
                            $success = false;
                        }
                        break;
                    case 'indent':
                        switch (true) {
                            case $indent == 0:
                                $set = 'indent = 0';
                                break;
                            case $indent > 0:
                                $set = "indent = (indent + {$indent})";
                                break;
                            case $indent < 0:
                                $set = "indent = (CASE WHEN indent < ABS({$indent}) THEN 0 ELSE indent - ABS({$indent}) END)";
                                break;
                        }
                        if ($DB->execute("UPDATE {$CFG->prefix}course_modules SET {$set} WHERE id = {$cm->id}")) {
                            $rebuild_course_cache = true;
                            $updated = true;
                        } else {
                            $success = false;
                        }
                        break;
                    case 'section':
                        if ($cm->sectionnum == $section) {
                            $skipped = true;
                        } else {
                            // remove cm from old section
                            $params = array('course' => $course->id, 'section' => $cm->sectionnum);
                            if ($sectionid = $DB->get_field('course_sections', 'id', $params)) {
                                $sequence = $DB->get_field('course_sections', 'sequence', $params);
                                if (is_string($sequence)) {
                                    $sequence = explode(',', $sequence);
                                    $sequence = array_filter($sequence);
                                    // remove blanks
                                    $sequence = preg_grep('/^' . $cm->id . '$/', $sequence, PREG_GREP_INVERT);
                                    $sequence = implode(',', $sequence);
                                    $DB->set_field('course_sections', 'sequence', $sequence, $params);
                                }
                                // add cm to target $section
                                if ($position == 1) {
                                    $add_cm_to_sequence = 'array_unshift';
                                    // prepend to start of section
                                } else {
                                    $add_cm_to_sequence = 'array_push';
                                    // append to end of section
                                }
                                $params = array('course' => $course->id, 'section' => $section >= 0 ? $section : $cm->sectionnum);
                                $sectionid = $DB->get_field('course_sections', 'id', $params);
                                $sequence = $DB->get_field('course_sections', 'sequence', $params);
                                if (is_string($sequence)) {
                                    $sequence = explode(',', $sequence);
                                    $sequence = array_filter($sequence);
                                    // remove blanks
                                    $sequence = preg_grep('/^' . $cm->id . '$/', $sequence, PREG_GREP_INVERT);
                                } else {
                                    $sequence = array();
                                    // shouldn't happen !!
                                }
                                $add_cm_to_sequence($sequence, $cm->id);
                                $sequence = implode(',', $sequence);
                                $DB->set_field('course_sections', 'sequence', $sequence, $params);
                                $DB->set_field('course_modules', 'section', $sectionid, array('id' => $cm->id));
                                $updated = true;
                                $rebuild_course_cache = true;
                            }
                        }
                        break;
                        // uploadlimit
                    // uploadlimit
                    case 'uploadlimit':
                        switch ($cm->modname) {
                            case 'assign':
                                // Moodle >= 2.3
                                $table = 'assign_plugin_config';
                                $params = array('assignment' => $cm->instance, 'subtype' => 'assignsubmission', 'plugin' => 'file', 'name' => 'maxsubmissionsizebytes');
                                if ($DB->record_exists($table, $params)) {
                                    if ($DB->set_field($table, 'value', ${$setting}, $params)) {
                                        $updated = true;
                                    } else {
                                        $success = false;
                                    }
                                } else {
                                    $params['value'] = ${$setting};
                                    if ($DB->insert_record($table, $params)) {
                                        $updated = true;
                                    } else {
                                        $success = false;
                                    }
                                }
                                break;
                            case 'assignment':
                                // Moodle <= 2.2
                            // Moodle <= 2.2
                            case 'forum':
                            case 'workshop':
                                if ($DB->set_field($cm->modname, 'maxbytes', ${$setting}, array('id' => $cm->instance))) {
                                    $updated = true;
                                } else {
                                    $success = false;
                                }
                                break;
                                // skip all other modules
                            // skip all other modules
                            default:
                                $skipped = true;
                        }
                        break;
                        // course module settings
                    // course module settings
                    case 'groupmode':
                    case 'groupingid':
                    case 'groupmembersonly':
                        if ($DB->set_field('course_modules', $setting, ${$setting}, array('id' => $cm->id))) {
                            $updated = true;
                            $rebuild_course_cache = true;
                        } else {
                            $success = false;
                        }
                        break;
                        // gradebook settings
                    // gradebook settings
                    case 'gradecat':
                    case 'gradeitemhidden':
                    case 'gradepass':
                        $select = 'courseid = ? AND itemtype = ? AND itemmodule = ? AND iteminstance = ?';
                        $params = array($course->id, 'mod', $cm->modname, $cm->instance);
                        switch ($setting) {
                            case 'gradecat':
                                $field = 'categoryid';
                                break;
                            case 'gradeitemhidden':
                                $field = 'hidden';
                                break;
                            default:
                                $field = $setting;
                        }
                        if ($DB->set_field_select('grade_items', $field, ${$setting}, $select, $params)) {
                            $updated = true;
                            $regrade_item_id = $DB->get_field_select('grade_items', 'id', $select, $params);
                        } else {
                            $success = false;
                        }
                        break;
                        // extra credit
                    // extra credit
                    case 'extracredit':
                        $skipped = true;
                        $select = 'courseid = ? AND itemtype = ? AND itemmodule = ? AND iteminstance = ?';
                        $params = array($course->id, 'mod', $cm->modname, $cm->instance);
                        if ($grade_item = $DB->get_record_select('grade_items', $select, $params)) {
                            $select = 'id = ? AND aggregation IN (?, ?, ?)';
                            $params = array($grade_item->categoryid, GRADE_AGGREGATE_WEIGHTED_MEAN2, GRADE_AGGREGATE_EXTRACREDIT_MEAN, GRADE_AGGREGATE_SUM);
                            if ($grade_category = $DB->get_record_select('grade_categories', $select, $params)) {
                                $skipped = false;
                                if ($DB->set_field('grade_items', 'aggregationcoef', $extracredit, array('id' => $grade_item->id))) {
                                    $updated = true;
                                    $regrade_item_id = $grade_item->id;
                                } else {
                                    $success = false;
                                }
                            }
                        }
                        break;
                        // regrade activity
                    // regrade activity
                    case 'regrade':
                        // Note: the lib.php for this mod was included earlier
                        // if we use just the "update_grades" function,
                        // we cannot know if it is successful or not ...
                        // $update_grades = $cm->modname.'_update_grades';
                        // ... so we use the following functions instead:
                        $get_user_grades = $cm->modname . '_get_user_grades';
                        $grade_item_update = $cm->modname . '_grade_item_update';
                        if (function_exists($get_user_grades) && function_exists($grade_item_update)) {
                            $grades = $get_user_grades($instance);
                            if ($grade_item_update($instance, $grades) == GRADE_UPDATE_OK) {
                                // GRADE_UPDATE_OK = 0
                                $updated = true;
                            } else {
                                $success = false;
                            }
                            $skipped = false;
                        } else {
                            $skipped = true;
                        }
                        break;
                    case 'removeconditions':
                        if ($removeconditions) {
                            if ($dbman->field_exists('course_modules', 'availability')) {
                                // Moodle >= 2.7
                                $DB->set_field('course_modules', 'availability', '', array('id' => $cm->id));
                                $updated = true;
                            } else {
                                // Moodle <= 2.6
                                if ($dbman->field_exists('course_modules', 'availablefrom')) {
                                    $DB->set_field('course_modules', 'availablefrom', 0, array('id' => $cm->id));
                                    $DB->set_field('course_modules', 'availableuntil', 0, array('id' => $cm->id));
                                    $DB->set_field('course_modules', 'showavailability', 0, array('id' => $cm->id));
                                    $updated = true;
                                }
                                if ($dbman->table_exists('course_modules_availability')) {
                                    $DB->delete_records('course_modules_availability', array('coursemoduleid' => $cm->id));
                                    $updated = true;
                                }
                                if ($dbman->table_exists('course_modules_avail_fields')) {
                                    $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
                                    $updated = true;
                                }
                            }
                            $rebuild_course_cache = true;
                        }
                        break;
                    case 'conditiondate':
                    case 'conditiongrade':
                    case 'conditionfield':
                    case 'conditiongroup':
                    case 'conditiongrouping':
                    case 'conditioncm':
                    case 'conditionaction':
                        if ($conditions_checked == false) {
                            $conditions_checked = true;
                            $conditions = array_merge($conditiondate, $conditiongrade, $conditionfield, $conditiongroup, $conditiongrouping, $conditioncm);
                            update_course_module_availability($labelmods, $resourcemods, $course, $cm, $conditions, $conditionaction, $updated, $skipped);
                            if ($updated) {
                                $rebuild_course_cache = true;
                            }
                        }
                        break;
                    case 'removecompletion':
                        if ($removecompletion) {
                            $table = 'course_modules';
                            $params = array('id' => $cm->id);
                            $names = array('completion' => 0, 'completionview' => 0, 'completionexpected' => 0, 'completiongradeitemnumber' => null);
                            foreach ($names as $name => $disabled) {
                                $value = $DB->get_field($table, $name, $params);
                                if (isset($value)) {
                                    $value = intval($value);
                                }
                                if ($value === $disabled) {
                                    $skipped = true;
                                } else {
                                    $updated = $DB->set_field($table, $name, $disabled, $params);
                                }
                            }
                            $params = array('id' => $cm->instance);
                            foreach ($completionfields as $name => $field) {
                                if ($field->cmfield) {
                                    continue;
                                    // e.g. completionview/grade
                                }
                                if (array_key_exists($cm->modname, $field->mods)) {
                                    if ($DB->get_field($cm->modname, $name, $params)) {
                                        $updated = $DB->set_field($cm->modname, $name, 0, $params);
                                    } else {
                                        $skipped = true;
                                    }
                                }
                            }
                            if ($updated) {
                                $completion_updated = true;
                            }
                        }
                        break;
                    case 'erasecompletion':
                        if ($erasecompletion) {
                            $completion_updated = true;
                            $updated = true;
                        } else {
                            $skipped = true;
                        }
                        break;
                    case 'completiontracking':
                        update_course_module_completion('course_modules', $cm->id, 'completion', $completiontracking, $updated, $skipped, $completion_updated);
                        break;
                    case 'completiondate':
                        update_course_module_completion('course_modules', $cm->id, $setting, $completiondate, $updated, $skipped, $completion_updated);
                        break;
                    case 'completionview':
                        if (array_key_exists($cm->modname, $completionfields[$setting]->mods)) {
                            update_course_module_completion('course_modules', $cm->id, $setting, $completionview, $updated, $skipped, $completion_updated);
                        }
                        break;
                    case 'completiongrade':
                        if (array_key_exists($cm->modname, $completionfields[$setting]->mods)) {
                            // course_modules.completiongradeitemnumber
                            // see "set_moduleinfo_defaults()" in "course/modlib.php"
                            // null=disabled, 0=enabled (i.e. require grade)
                            $completiongradeitemnumber = $completiongrade ? 0 : null;
                            update_course_module_completion('course_modules', $cm->id, 'completiongradeitemnumber', $completiongradeitemnumber, $updated, $skipped, $completion_updated);
                        }
                        break;
                    case 'competencyrule':
                        $data = (object) array('coursemodule' => $cm->id, 'competencies' => array(), 'competency_rule' => $competencyrule);
                        // see "admin/tool/lp/lib.php"
                        $data = tool_lp_coursemodule_edit_post_actions($data, $course);
                        $updated = true;
                        break;
                    default:
                        if (array_key_exists($setting, $completionfields)) {
                            $field = $completionfields[$setting];
                            if (array_key_exists($cm->modname, $field->mods)) {
                                update_course_module_completion($cm->modname, $cm->instance, $setting, ${$setting}, $updated, $skipped, $completion_updated);
                            }
                        } else {
                            if (substr($setting, 0, 6) == 'filter') {
                                $filter = substr($setting, 6);
                                if (in_array(${$setting}, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_INHERIT))) {
                                    filter_set_local_state($filter, $modulecontext->id, ${$setting});
                                    $reset_filter_caches = true;
                                    $updated = true;
                                } else {
                                    $skipped = true;
                                }
                            } else {
                                // unexpected setting - shouldn't happen !!
                                echo 'Unknown setting, ' . $setting . ', not processed' . html_writer::empty_tag('br');
                            }
                        }
                }
                // end switch
            }
            // end foreach $selected_settings
            if ($completion_updated) {
                $completion = $completiontracking;
                // if automatic completion (=2) is requested,
                // check that some completion conditions are set
                if ($completion == 2) {
                    $completion = 0;
                    $table = 'course_modules';
                    $params = array('id' => $cm->id);
                    $names = array('completionview' => 0, 'completionexpected' => 0, 'completiongradeitemnumber' => null);
                    foreach ($names as $name => $disabled) {
                        $value = $DB->get_field($table, $name, $params);
                        if (isset($value)) {
                            $value = intval($value);
                        }
                        if ($value !== $disabled) {
                            $completion = $completiontracking;
                        }
                    }
                    foreach ($completionfields as $field) {
                        $name = $field->name;
                        if (property_exists($instance, $name) && $instance->{$name}) {
                            $completion = $completiontracking;
                        }
                    }
                }
                // force completion to be something sensible
                update_course_module_completion('course_modules', $cm->id, 'completion', $completion, $updated, $skipped, $completion_updated);
                // get full $cm record
                if (method_exists($cm, 'get_course_module_record')) {
                    // Moodle >= 2.7
                    $cm = $cm->get_course_module_record(true);
                } else {
                    // Moodle <= 2.6
                    $cm = get_coursemodule_from_id($cm->modname, $cm->id, $cm->course, true);
                }
                // prevent "Cannot find grade item" error in "lib/completionlib.php"
                $params = array('courseid' => $cm->course, 'itemtype' => 'mod', 'itemmodule' => $cm->modname, 'iteminstance' => $cm->instance);
                if (!grade_item::fetch($params)) {
                    $cm->completiongradeitemnumber = null;
                    // disable grade completion
                }
                $completion = new completion_info($course);
                $completion->reset_all_state($cm);
                $rebuild_course_cache = true;
            }
            if ($regrade_item_id) {
                $regrade_course_grades = true;
                $DB->set_field('grade_items', 'needsupdate', 1, array('id' => $regrade_item_id));
                $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $course->id, 'itemtype' => 'course'));
            }
            if ($started_list == false) {
                $started_list = true;
                echo '<table border="0" cellpadding="4" cellspacing="4" class="selectedactivitylist"><tbody>' . "\n";
                echo '<tr><th colspan="2">' . get_string('settingsselected', $plugin) . '</th></tr>' . "\n";
                foreach ($selected_settings as $setting) {
                    list($name, $value) = format_setting($setting, ${$setting}, $ratings, $gradecategories, $groupmodes, $groupings, $indentmenu, $sectionmenu, $positionmenu, $uploadlimitmenu, $conditiongradeitemidmenu, $conditioncmidmenu, $conditioncmcompletionmenu, $conditionfieldnamemenu, $conditionfieldoperatormenu, $conditiongroupidmenu, $conditiongroupingidmenu, $conditionactionmenu, $completiontrackingmenu, $completionfields, $competencyrulemenu, $filters, $filtermenu, $filterdefaulton, $filterdefaultoff);
                    echo '<tr><td class="itemname">' . $name . ':</td><td class="itemvalue">' . $value . '</td></tr>' . "\n";
                }
                echo '<tr><th colspan="2">' . get_string('activitiesselected', $plugin) . '</th></tr>' . "\n";
            }
            echo '<tr><td class="itemname">';
            if ($updated) {
                echo '<span class="updated">' . get_string('updated', 'moodle', $cm->modname) . '</span>';
            } else {
                if ($skipped) {
                    echo '<span class="skipped">' . get_string('skipped') . ' ' . $cm->modname . '</span>';
                } else {
                    echo '<span class="failure">' . get_string('fail', 'install') . ' ' . $cm->modname . '</span>';
                }
            }
            echo '</td><td class="itemvalue">';
            $url = $PAGE->theme->pix_url('icon', $cm->modname)->out();
            echo '<img src="' . $url . '" class="icon" title="' . s(get_string('modulename', $cm->modname)) . '"></img> ';
            $name = urldecode($cm->name);
            $name = block_taskchain_navigation::filter_text($name);
            $name = trim(strip_tags($name));
            $name = block_taskchain_navigation::trim_text($name, $cm_namelength, $cm_headlength, $cm_taillength);
            echo $name;
            echo '</td></tr>' . "\n";
        }
    }
    if ($sortgradeitems || $creategradecats || $removegradecats || $reset_filter_caches || $rebuild_course_cache || $regrade_course_grades || isset($success)) {
        if ($started_list == false) {
            $started_list = true;
            echo '<table border="0" cellpadding="4" cellspacing="4" class="selectedactivitylist"><tbody>' . "\n";
        }
        if ($sortgradeitems) {
            echo '<tr><td class="notifymessage" colspan="2">';
            $msg = get_string('sortedgradeitems', $plugin);
            echo $OUTPUT->notification($msg, 'notifysuccess');
            echo '</td></tr>' . "\n";
        }
        if ($creategradecats) {
            echo '<tr><td class="notifymessage" colspan="2">';
            $msg = get_string('createdgradecategories', $plugin);
            echo $OUTPUT->notification($msg, 'notifysuccess');
            echo '</td></tr>' . "\n";
        }
        if ($removegradecats) {
            echo '<tr><td class="notifymessage" colspan="2">';
            $msg = get_string('removedgradecategories', $plugin);
            echo $OUTPUT->notification($msg, 'notifysuccess');
            echo '</td></tr>' . "\n";
        }
        if ($reset_filter_caches) {
            echo '<tr><td class="notifymessage" colspan="2">';
            echo get_string('resettingfiltercache', $plugin) . ' ... ';
            filter_manager::reset_caches();
            //unset($FILTERLIB_PRIVATE->active[$context->id]);
            echo get_string('ok') . '</td></tr>' . "\n";
        }
        if ($rebuild_course_cache) {
            echo '<tr><td class="notifymessage" colspan="2">';
            echo get_string('rebuildingcoursecache', $plugin) . ' ... ';
            rebuild_course_cache($course->id);
            echo get_string('ok') . '</td></tr>' . "\n";
        }
        if ($regrade_course_grades) {
            echo '<tr><td class="notifymessage" colspan="2">';
            echo get_string('recalculatingcoursegrades', $plugin) . ' ... ';
            grade_regrade_final_grades($course->id);
            echo get_string('ok') . '</td></tr>' . "\n";
        }
        if ($success === true) {
            echo '<tr><td class="notifymessage" colspan="2">';
            $msg = get_string('success');
            echo $OUTPUT->notification($msg, 'notifysuccess');
            echo '</td></tr>' . "\n";
        }
        if ($success === false) {
            echo '<tr><td class="notifymessage" colspan="2">';
            $msg = get_string('activityupdatefailure', $plugin);
            echo $OUTPUT->notification($msg, 'notifyproblem');
            echo '</td></tr>' . "\n";
        }
    }
    if ($started_list) {
        $started_list = false;
        echo '</tbody></table>' . "\n";
    }
    echo '<script type="text/javascript">' . "\n";
    echo "//<![CDATA[\n";
    echo "function reset_all_in(elTagName, elNamePrefix, parentTagName, parentClass, parentId, resetValues) {\n";
    echo "    var obj = document.getElementsByTagName(elTagName);\n";
    echo "    obj = filterByParent(obj, function(el) {return findParentNode(el, parentTagName, parentClass, parentId);});\n";
    echo "    for (var i=0; i<obj.length; i++) {\n";
    echo "        var elName = obj[i].name;\n";
    echo "        if (elName && (elNamePrefix=='' || elName.substr(0, elNamePrefix.length)==elNamePrefix)) {\n";
    echo "            switch (obj[i].type) {\n";
    echo "                case 'checkbox':\n";
    echo "                case 'radio':\n";
    echo "                    if (typeof(resetValues)=='string') {\n";
    echo "                        obj[i].checked = (resetValues=='all' ? true : false);\n";
    echo "                    } else {\n";
    echo "                        obj[i].checked = (resetValues[elName] ? true : false);\n";
    echo "                    }\n";
    echo "                    if (obj[i].onclick) {\n";
    echo "                        obj[i].onclick()\n";
    echo "                    }\n";
    echo "                    break;\n";
    echo "                case 'select':\n";
    echo "                case 'select-multiple':\n";
    echo "                    for (var ii=0; ii<obj[i].options.length; ii++) {\n";
    echo "                        if (typeof(resetValues)=='string') {\n";
    echo "                            obj[i].options[ii].selected = (resetValues=='all' ? true : false);\n";
    echo "                        } else {\n";
    echo "                            var elValue = obj[i].options[ii].value;\n";
    echo "                            obj[i].options[ii].selected = (resetValues[elValue] ? true : false);\n";
    echo "                        }\n";
    echo "                    }\n";
    echo "                    break;\n";
    echo "            }\n";
    echo "        }\n";
    echo "    }\n";
    echo "}\n";
    echo "function set_disabled(frm, names, value, sync_checkbox) {\n";
    echo "    var fixed_color = false;\n";
    echo "    if (frm) {\n";
    echo "        var i_max = names.length;\n";
    echo "        for (var i=0; i<i_max; i++) {\n";
    echo "            if (frm.elements[names[i]]) {\n";
    echo "                frm.elements[names[i]].disabled = value;\n";
    echo "                if (sync_checkbox) {\n";
    echo "                    if (frm.elements[names[i]].type=='checkbox') {\n";
    echo "                        frm.elements[names[i]].checked = (! value);\n";
    echo "                    }\n";
    echo "                }\n";
    echo "                if (fixed_color==false) {\n";
    echo "                    fixed_color = true;\n";
    echo "                    var obj = frm.elements[names[i]].parentNode;\n";
    echo "                    if (obj) {\n";
    echo "                        obj.style.color = (value ? '#999999' : 'inherit');\n";
    echo "                    }\n";
    echo "                }\n";
    echo "            }\n";
    echo "        }\n";
    echo "    }\n";
    echo "    return true;\n";
    echo "}\n";
    echo "function init_disabled(frm, names, value) {\n";
    echo "    var obj = document.getElementsByTagName('input');\n";
    echo "    if (obj) {\n";
    echo "        var i_max = obj.length;\n";
    echo "        for (var i=0; i<i_max; i++) {\n";
    echo "            if (obj[i].name && obj[i].name.substr(0, 7)=='select_' && obj[i].onclick) {\n";
    echo "                obj[i].id = 'id_' + obj[i].name;\n";
    echo "                obj[i].onclick();\n";
    echo "            }\n";
    echo "        }\n";
    echo "    }\n";
    echo "    return true;\n";
    echo "}\n";
    echo "function confirm_action(msg, checksettings) {\n";
    echo "    var ok = false;\n";
    echo "    var obj = null;\n";
    echo "    if (obj = document.getElementById('id_sections')) {\n";
    echo "        if (obj.selectedIndex >= 0) {\n";
    echo "            ok = true;\n";
    echo "        }\n";
    echo "    }\n";
    echo "    if (obj = document.getElementById('id_modules')) {\n";
    echo "        if (obj.selectedIndex >= 0) {\n";
    echo "            ok = true;\n";
    echo "        }\n";
    echo "    }\n";
    echo "    if (obj = document.getElementById('id_include')) {\n";
    echo "        if (obj.value) {\n";
    echo "            ok = true;\n";
    echo "        }\n";
    echo "    }\n";
    echo "    if (obj = document.getElementById('id_exclude')) {\n";
    echo "        if (obj.value) {\n";
    echo "            ok = true;\n";
    echo "        }\n";
    echo "    }\n";
    echo "    if (obj = document.getElementById('menuvisibility')) {\n";
    echo "        if (obj.selectedIndex >= 1) {\n";
    echo "            ok = true;\n";
    echo "        }\n";
    echo "    }\n";
    echo "    if (obj = document.getElementById('id_cmids')) {\n";
    echo "        if (obj.selectedIndex >= 0) {\n";
    echo "            ok = true;\n";
    echo "        }\n";
    echo "    }\n";
    echo "    if (ok==false) {\n";
    echo "        alert('" . js(get_string('noactivitiesselected', $plugin)) . "');\n";
    echo "        return ok;\n";
    echo "    }\n";
    echo "    if (checksettings) {\n";
    echo "        ok = false;\n";
    echo "        var settings = new Array('id_select_" . implode("', 'id_select_", $settings) . "');\n";
    echo "        for (var i=0; i<settings.length; i++) {\n";
    echo "            if (obj = document.getElementById(settings[i])) {\n";
    echo "                if (obj.checked) {\n";
    echo "                    ok = true;\n";
    echo "                }\n";
    echo "            }\n";
    echo "        }\n";
    echo "    }\n";
    echo "    if (ok==false) {\n";
    echo "        alert('" . js(get_string('nosettingsselected', $plugin)) . "');\n";
    echo "        return ok;\n";
    echo "    }\n";
    echo "    return confirm(msg);\n";
    echo "}\n";
    echo "if (window.addEventListener) {\n";
    echo "    window.addEventListener('load', init_disabled, false);\n";
    echo "} else if (window.attachEvent) {\n";
    echo "    window.attachEvent('onload', init_disabled)\n";
    echo "} else {\n";
    echo "    window.onload = init_disabled;\n";
    echo "}\n";
    echo "//]]>\n";
    echo '</script>' . "\n";
    echo '<form method="post" action="accesscontrol.php" enctype="multipart/form-data">' . "\n";
    echo '<table border="0" cellpadding="4" cellspacing="4" width="720" style="margin: auto;" class="blockconfigtable">' . "\n";
    echo '<tr>' . "\n";
    echo '<td colspan="2" class="blockdescription">' . nl2br(get_string('accesspagedescription', $plugin)) . '</td>' . "\n";
    echo '<td class="itemselect">';
    echo get_string('select') . ' ';
    echo $OUTPUT->help_icon('selectsettings', $plugin);
    echo '<br />';
    echo '<a href="' . "javascript:reset_all_in('INPUT','select_','TD','itemselect',null,'all');" . '">' . get_string('all') . '</a>';
    echo ' / ';
    echo '<a href="' . "javascript:reset_all_in('INPUT','select_','TD','itemselect',null,'none');" . '">' . get_string('none') . '</a>';
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    // ============================
    // Activity filters
    // ============================
    //
    print_sectionheading(get_string('activityfilters', $plugin), 'activityfilters', false);
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('sectiontags', $plugin) . ':</td>';
    echo '<td class="itemvalue">';
    echo '<input id="id_sectiontags" type="text" name="sectiontags" size="15" value="' . $sectiontags . '" />';
    echo ' ' . $OUTPUT->help_icon('sectiontitletags', $plugin);
    echo '</td>' . "\n";
    echo '<td class="itemselect">&nbsp;</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('sections', $plugin) . ':';
    echo '<div class="smalltext">';
    echo '<a href="' . "javascript:reset_all_in('SELECT','sections','','',null,'all');" . '">' . get_string('all') . '</a>';
    echo ' / ';
    echo '<a href="' . "javascript:reset_all_in('SELECT','sections','','',null,'none');" . '">' . get_string('none') . '</a>';
    echo '</div>';
    echo '</td>' . "\n";
    echo '<td class="itemvalue">' . $sections . '</td>' . "\n";
    echo '<td class="itemselect">&nbsp;</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('activitytypes', $plugin) . ':';
    echo '<div class="smalltext">';
    echo '<a href="' . "javascript:reset_all_in('SELECT','modules','','',null,'all');" . '">' . get_string('all') . '</a>';
    echo ' / ';
    echo '<a href="' . "javascript:reset_all_in('SELECT','modules','','',null,'none');" . '">' . get_string('none') . '</a>';
    echo '</div>';
    echo '</td>' . "\n";
    echo '<td class="itemvalue">' . $modules . '</td>' . "\n";
    echo '<td class="itemselect">&nbsp;</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('activitynamefilters', $plugin) . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo '    <div class="subitem">';
    echo '        <div class="subname">' . get_string('include', $plugin) . ':</div>';
    echo '        <input id="id_include" type="text" name="include" size="15" value="' . $include . '" />';
    echo '    </div>';
    echo '    <div class="subitem">';
    echo '        <div class="subname">' . get_string('exclude', $plugin) . ':</div>';
    echo '        <input id="id_exclude" type="text" name="exclude" size="15" value="' . $exclude . '" />';
    echo '    </div>';
    echo '</td>' . "\n";
    echo '<td class="itemselect">&nbsp;</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('visibility', $plugin) . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo html_writer::select($visibilitymenu, 'visibility', $visibility, '');
    echo '</td>' . "\n";
    echo '<td class="itemselect">&nbsp;</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('activityids', $plugin) . ':';
    echo '<div class="smalltext">';
    echo '<a href="' . "javascript:reset_all_in('SELECT','cmids','','',null,'all');" . '">' . get_string('all') . '</a>';
    echo ' / ';
    echo '<a href="' . "javascript:reset_all_in('SELECT','cmids','','',null,'none');" . '">' . get_string('none') . '</a>';
    echo '</div>';
    echo '</td>' . "\n";
    echo '<td class="itemvalue">' . $cms . '</td>' . "\n";
    echo '<td class="itemselect">&nbsp;</td>' . "\n";
    echo '</tr>' . "\n";
    // ============================
    // Availability dates
    // ============================
    //
    print_sectionheading(get_string('dates', $plugin), 'dates', true);
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('availablefrom', $plugin) . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    $fromdate['minutes'] = intval($fromdate['minutes']) - intval($fromdate['minutes']) % 5;
    echo html_writer::select($days, 'fromday', intval($fromdate['mday']), '') . ' ';
    echo html_writer::select($months, 'frommonth', intval($fromdate['mon']), '') . ' ';
    echo html_writer::select($years, 'fromyear', intval($fromdate['year']), '') . ' ';
    echo html_writer::select($hours, 'fromhours', intval($fromdate['hours']), '') . ' ';
    echo html_writer::select($minutes, 'fromminutes', intval($fromdate['minutes']), '') . ' ';
    $names = "'menufromday', 'menufrommonth', 'menufromyear', 'menufromhours', 'menufromminutes'";
    $script = "return set_disabled(this.form, new Array({$names}), (this.disabled || this.checked))";
    echo html_writer::checkbox('fromdisable', '1', $fromdisable, get_string('disable'), array('onclick' => $script));
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('fromdisable'), (! this.checked)) && this.form.fromdisable.onclick()";
    $checked = optional_param('select_availablefrom', 0, PARAM_INT);
    echo html_writer::checkbox('select_availablefrom', 1, $checked, '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('availableuntil', $plugin) . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    $untildate['minutes'] = intval($untildate['minutes']) - intval($untildate['minutes']) % 5;
    echo html_writer::select($days, 'untilday', intval($untildate['mday']), '') . ' ';
    echo html_writer::select($months, 'untilmonth', intval($untildate['mon']), '') . ' ';
    echo html_writer::select($years, 'untilyear', intval($untildate['year']), '') . ' ';
    echo html_writer::select($hours, 'untilhours', intval($untildate['hours']), '') . ' ';
    echo html_writer::select($minutes, 'untilminutes', intval($untildate['minutes']), '') . ' ';
    $names = "'menuuntilday', 'menuuntilmonth', 'menuuntilyear', 'menuuntilhours', 'menuuntilminutes'";
    $script = "return set_disabled(this.form, new Array({$names}), (this.disabled || this.checked))";
    echo html_writer::checkbox('untildisable', '1', $untildisable, get_string('disable'), array('onclick' => $script));
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('untildisable'), (! this.checked)) && this.form.untildisable.onclick()";
    $checked = optional_param('select_availableuntil', 0, PARAM_INT);
    echo html_writer::checkbox('select_availableuntil', 1, $checked, '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    if ($modnames = implode(', ', $cutoffdatemods)) {
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('cutoffdate', 'assign') . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        $cutoffdate['minutes'] = intval($cutoffdate['minutes']) - intval($cutoffdate['minutes']) % 5;
        echo html_writer::select($days, 'cutoffday', intval($cutoffdate['mday']), '') . ' ';
        echo html_writer::select($months, 'cutoffmonth', intval($cutoffdate['mon']), '') . ' ';
        echo html_writer::select($years, 'cutoffyear', intval($cutoffdate['year']), '') . ' ';
        echo html_writer::select($hours, 'cutoffhours', intval($cutoffdate['hours']), '') . ' ';
        echo html_writer::select($minutes, 'cutoffminutes', intval($cutoffdate['minutes']), '') . ' ';
        $names = "'menucutoffday', 'menucutoffmonth', 'menucutoffyear', 'menucutoffhours', 'menucutoffminutes'";
        $script = "return set_disabled(this.form, new Array({$names}), (this.disabled || this.checked))";
        echo html_writer::checkbox('cutoffdisable', '1', $cutoffdisable, get_string('disable'), array('onclick' => $script));
        echo html_writer::empty_tag('br') . '(' . get_string('completionfieldactivities', $plugin, $modnames) . ')';
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('cutoffdisable'), (! this.checked)) && this.form.cutoffdisable.onclick()";
        $checked = optional_param('select_availablecutoff', 0, PARAM_INT);
        echo html_writer::checkbox('select_availablecutoff', 1, $checked, '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
    }
    // ============================
    // Grades
    // ============================
    //
    echo '<tr class="sectionheading" id="id_section_dates">' . "\n";
    echo '<th colspan="2">';
    echo get_string('grades');
    echo ' &nbsp; <span class="sortgradeitems">';
    if ($sortgradeitems) {
        echo ' ' . get_string('sortedgradeitems', $plugin);
    } else {
        $href = $CFG->wwwroot . '/blocks/taskchain_navigation/accesscontrol.php?id=' . $block_instance->id . '&sortgradeitems=1&sesskey=' . sesskey();
        $onclick = 'return confirm("' . js(get_string('confirmsortgradeitems', $plugin)) . '")';
        echo '<a href="' . s($href) . '" onclick="' . s($onclick) . '">' . get_string('sortgradeitems', $plugin) . '</a> ';
        echo $OUTPUT->help_icon('sortgradeitems', $plugin);
    }
    echo '</span>';
    echo ' &nbsp; <span class="creategradecategories">';
    if ($creategradecats) {
        echo ' ' . get_string('createdgradecategories', $plugin);
    } else {
        $href = $CFG->wwwroot . '/blocks/taskchain_navigation/accesscontrol.php?id=' . $block_instance->id . '&creategradecats=1&sesskey=' . sesskey();
        $onclick = 'return confirm("' . js(get_string('confirmcreategradecategories', $plugin)) . '")';
        echo '<a href="' . s($href) . '" onclick="' . s($onclick) . '">' . get_string('creategradecategories', $plugin) . '</a> ';
        echo $OUTPUT->help_icon('creategradecategories', $plugin);
    }
    echo '</span>';
    echo ' &nbsp; <span class="removegradecategories">';
    if ($removegradecats) {
        echo ' ' . get_string('removedgradecategories', $plugin);
    } else {
        $href = $CFG->wwwroot . '/blocks/taskchain_navigation/accesscontrol.php?id=' . $block_instance->id . '&removegradecats=1&sesskey=' . sesskey();
        $onclick = 'return confirm("' . js(get_string('confirmremovegradecategories', $plugin)) . '")';
        echo '<a href="' . s($href) . '" onclick="' . s($onclick) . '">' . get_string('removegradecategories', $plugin) . '</a> ';
        echo $OUTPUT->help_icon('removegradecategories', $plugin);
    }
    echo '</span>';
    echo '</th>' . "\n";
    echo '<th class="toggle"></th>' . "\n";
    echo '</tr>' . "\n";
    if ($modnames = implode(', ', $ratingmods)) {
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('rating', 'rating') . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        echo html_writer::select($ratings, 'rating', $rating, '') . ' ';
        echo '(' . get_string('completionfieldactivities', $plugin, $modnames) . ')';
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('rating'), (! this.checked))";
        echo html_writer::checkbox('select_rating', 1, optional_param('select_rating', 0, PARAM_INT), '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
    }
    if ($modnames = implode(', ', $gradingmods)) {
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('grade') . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        foreach ($gradingmods as $modname => $modtext) {
            echo "<p>{$modname} - {$modtext}<br />";
            foreach ($gradingareas[$modname] as $areaname => $areatext) {
                echo " == {$areaname} - {$areatext}<br />";
            }
            echo "</p>\n";
        }
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('grading'), (! this.checked))";
        echo html_writer::checkbox('select_grading', 1, optional_param('select_grading', 0, PARAM_INT), '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
    }
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('maximumgrade', $plugin) . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo html_writer::select($maxgrades, 'maxgrade', $maxgrade, '');
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('maxgrade'), (! this.checked))";
    echo html_writer::checkbox('select_maxgrade', 1, optional_param('select_maxgrade', 0, PARAM_INT), '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('gradepass', 'grades') . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo html_writer::select($gradepassmenu, 'gradepass', $gradepass, '');
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('gradepass'), (! this.checked))";
    echo html_writer::checkbox('select_gradepass', 1, optional_param('select_gradepass', 0, PARAM_INT), '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('gradecategory', 'grades') . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo html_writer::select($gradecategories, 'gradecat', $gradecat, '');
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('gradecat'), (! this.checked))";
    echo html_writer::checkbox('select_gradecat', 1, optional_param('select_gradecat', 0, PARAM_INT), '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('gradeitemhidden', $plugin) . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo html_writer::select_yes_no('gradeitemhidden', $gradeitemhidden);
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('gradeitemhidden'), (! this.checked))";
    echo html_writer::checkbox('select_gradeitemhidden', 1, optional_param('select_gradeitemhidden', 0, PARAM_INT), '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('aggregationcoefextra', 'grades') . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo html_writer::select_yes_no('extracredit', $extracredit);
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('extracredit'), (! this.checked))";
    echo html_writer::checkbox('select_extracredit', 1, optional_param('select_extracredit', 0, PARAM_INT), '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('regrade', $plugin) . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo html_writer::select_yes_no('regrade', $regrade);
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('regrade'), (! this.checked))";
    echo html_writer::checkbox('select_regrade', 1, optional_param('select_regrade', 0, PARAM_INT), '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    // ============================
    // Groups
    // ============================
    //
    print_sectionheading(get_string('groups'), 'groups', true);
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('groupmode') . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo html_writer::select($groupmodes, 'groupmode', $groupmode, '');
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('groupmode'), (! this.checked))";
    echo html_writer::checkbox('select_groupmode', 1, optional_param('select_groupmode', 0, PARAM_INT), '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    if (count($groupings)) {
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('grouping', 'group') . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        echo html_writer::select($groupings, 'groupingid', $groupingid, '');
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('groupingid'), (! this.checked))";
        echo html_writer::checkbox('select_groupingid', 1, optional_param('select_groupingid', 0, PARAM_INT), '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
        if ($strman->string_exists('groupmembersonly', 'group')) {
            echo '<tr>' . "\n";
            echo '<td class="itemname groupmembersonly">' . get_string('groupmembersonly', 'group') . ':</td>' . "\n";
            echo '<td class="itemvalue">';
            echo html_writer::checkbox('groupmembersonly', 1, $groupmembersonly);
            echo '</td>' . "\n";
            echo '<td class="itemselect">';
            $script = "return set_disabled(this.form, new Array('groupmembersonly'), (! this.checked))";
            echo html_writer::checkbox('select_groupmembersonly', 1, optional_param('select_groupmembersonly', 0, PARAM_INT), '', array('onclick' => $script));
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
    }
    // ============================
    // Course page
    // ============================
    //
    echo '<tr class="sectionheading" id="id_section_coursepage">' . "\n";
    echo '<th colspan="2">';
    echo get_string('coursepage', $plugin);
    echo ' &nbsp; <span class="sortgradeitems">';
    if ($sortactivities) {
        echo ' ' . get_string('sortedactivities', $plugin);
    } else {
        $href = $CFG->wwwroot . '/blocks/taskchain_navigation/accesscontrol.php?id=' . $block_instance->id . '&sortactivities=1&sesskey=' . sesskey();
        $onclick = 'return confirm("' . get_string('confirmsortactivities', $plugin) . '")';
        echo '<a href="' . s($href) . '" onclick="' . js($onclick) . '">' . get_string('sortactivities', $plugin) . '</a> ';
        echo $OUTPUT->help_icon('sortactivities', $plugin);
    }
    echo '</span>';
    echo '</th>' . "\n";
    echo '<th class="toggle"></th>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('visible') . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo html_writer::select($visiblemenu, 'visible', $visible, '');
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('visible'), (! this.checked))";
    echo html_writer::checkbox('select_visible', 1, optional_param('select_visible', 0, PARAM_INT), '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . get_string('indent', $plugin) . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo html_writer::select($indentmenu, 'indent', $indent, '');
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('indent'), (! this.checked))";
    echo html_writer::checkbox('select_indent', 1, optional_param('select_indent', 0, PARAM_INT), '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    if ($strman->string_exists('moveto', 'question')) {
        // Moodle >= 2.2
        $moveto = get_string('moveto', 'question');
    } else {
        // Moodle <= 2.1
        $moveto = get_string('movehere');
    }
    echo '<tr>' . "\n";
    echo '<td class="itemname">' . $moveto . ':</td>' . "\n";
    echo '<td class="itemvalue">';
    echo html_writer::select($sectionmenu, 'section', $section, '');
    echo ' ';
    echo html_writer::select($positionmenu, 'position', $position, '');
    echo '</td>' . "\n";
    echo '<td class="itemselect">';
    $script = "return set_disabled(this.form, new Array('section', 'position'), (! this.checked))";
    echo html_writer::checkbox('select_section', 1, optional_param('select_section', 0, PARAM_INT), '', array('onclick' => $script));
    echo '</td>' . "\n";
    echo '</tr>' . "\n";
    // ============================
    // Files and uploads
    // ============================
    //
    if (count($filemods)) {
        print_sectionheading(get_string('fileuploads', 'install'), 'files', true);
        $href = 'http://php.net/manual/' . substr(current_language(), 0, 2) . '/ini.core.php';
        $icon = html_writer::empty_tag('img', array('src' => $PAGE->theme->pix_url('i/info', ''), 'title' => get_string('info')));
        $params = array('onclick' => 'this.target="_blank"');
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('phpuploadlimit', $plugin) . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        if ($limit = ini_get('upload_max_filesize')) {
            $limit = display_size(get_real_size($limit)) . ' upload_max_filesize ';
            echo html_writer::tag('span', $limit, array('class' => 'uploadlimit'));
            echo html_writer::link($href . '#ini.upload-max-filesize', $icon, $params);
            echo html_writer::empty_tag('br');
        }
        if ($limit = ini_get('post_max_size')) {
            $limit = display_size(get_real_size($limit)) . ' post_max_size ';
            echo html_writer::tag('span', $limit, array('class' => 'uploadlimit'));
            echo html_writer::link($href . '#ini.post-max-size', $icon, $params);
        }
        echo '</td>' . "\n";
        echo '<td class="itemselect"></td>' . "\n";
        echo '</tr>' . "\n";
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('siteuploadlimit', $plugin) . ':' . '</td>' . "\n";
        echo '<td class="itemvalue">';
        // Site administration -> Security -> Site policies: Maximum uploaded file size
        if ($siteuploadlimit) {
            $limit = display_size($siteuploadlimit);
        } else {
            $limit = get_string('phpuploadlimit', $plugin);
            $limit = get_string('sameas', $plugin, $limit);
            $limit = html_writer::tag('i', $limit);
        }
        echo html_writer::tag('span', $limit, array('class' => 'uploadlimit'));
        if (has_capability('moodle/course:update', $sitecontext)) {
            $href = new moodle_url('/admin/settings.php', array('section' => 'sitepolicies'));
            $icon = html_writer::empty_tag('img', array('src' => $PAGE->theme->pix_url('i/settings', ''), 'title' => get_string('update')));
            echo html_writer::link($href, $icon, array('onclick' => 'this.target="_blank"'));
        }
        echo '</td>' . "\n";
        echo '<td class="itemselect"></td>' . "\n";
        echo '</tr>' . "\n";
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('courseuploadlimit', $plugin) . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        if ($courseuploadlimit) {
            $limit = display_size($courseuploadlimit);
        } else {
            $limit = get_string('siteuploadlimit', $plugin);
            $limit = get_string('sameas', $plugin, $limit);
            $limit = html_writer::tag('i', $limit);
        }
        echo html_writer::tag('span', $limit, array('class' => 'uploadlimit'));
        if (has_capability('moodle/course:update', $course->context)) {
            $href = new moodle_url('/course/edit.php', array('id' => $course->id));
            $icon = html_writer::empty_tag('img', array('src' => $PAGE->theme->pix_url('i/settings', ''), 'title' => get_string('update')));
            echo html_writer::link($href, $icon, array('onclick' => 'this.target="_blank"'));
        }
        echo '</td>' . "\n";
        echo '<td class="itemselect"></td>' . "\n";
        echo '</tr>' . "\n";
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('pluginuploadlimits', $plugin) . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        foreach ($filemods as $name => $limit) {
            if ($limit) {
                $limit = display_size($limit);
            } else {
                $limit = get_string('courseuploadlimit', $plugin);
                $limit = get_string('sameas', $plugin, $limit);
                $limit = html_writer::tag('i', $limit);
            }
            $limit .= ': ' . get_string('pluginname', $name);
            echo html_writer::tag('span', $limit, array('class' => 'uploadlimit'));
            if ($hassiteconfig) {
                if ($name == 'assign') {
                    $href = $name . 'submission_file';
                } else {
                    $href = 'modsetting' . $name;
                }
                $href = new moodle_url('/admin/settings.php', array('section' => $href));
                $icon = html_writer::empty_tag('img', array('src' => $PAGE->theme->pix_url('i/settings', ''), 'title' => get_string('update')));
                echo html_writer::link($href, $icon, array('onclick' => 'this.target="_blank"'));
            }
            echo html_writer::empty_tag('br');
        }
        echo '</td>' . "\n";
        echo '<td class="itemselect"></td>' . "\n";
        echo '</tr>' . "\n";
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('activityuploadlimit', $plugin) . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        echo html_writer::select($uploadlimitmenu, 'uploadlimit', $uploadlimit, '');
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('uploadlimit'), (! this.checked))";
        echo html_writer::checkbox('select_uploadlimit', 1, optional_param('select_uploadlimit', 0, PARAM_INT), '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
    }
    // ============================
    // Active filters
    // ============================
    //
    if (count($filters)) {
        print_sectionheading(get_string('actfilterhdr', 'filters'), 'filters', true);
        foreach ($filters as $filter => $filterinfo) {
            if ($filterinfo->inheritedstate == TEXTFILTER_ON) {
                $filtermenu[TEXTFILTER_INHERIT] = $filterdefaulton;
            } else {
                $filtermenu[TEXTFILTER_INHERIT] = $filterdefaultoff;
            }
            $setting = 'filter' . $filter;
            echo '<tr>' . "\n";
            echo '<td class="itemname">' . filter_get_name($filter) . ':</td>' . "\n";
            echo '<td class="itemvalue">';
            echo html_writer::select($filtermenu, $setting, ${$setting}, '');
            echo '</td>' . "\n";
            echo '<td class="itemselect">';
            $script = "return set_disabled(this.form, new Array('{$setting}'), (! this.checked))";
            echo html_writer::checkbox('select_' . $setting, 1, optional_param('select_' . $setting, 0, PARAM_INT), '', array('onclick' => $script));
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
    }
    // ============================
    // Access restrictions (Moodle >= 2.7)
    // Restrict access     (Moodle <= 2.6)
    // ============================
    //
    if ($enableavailability) {
        echo '<tr class="sectionheading" id ="id_section_availability">' . "\n";
        echo '<th colspan="2">' . $str->accessrestrictions . '</th>' . "\n";
        echo '<th class="toggle"></th>' . "\n";
        echo '</tr>' . "\n";
        echo '<tr>' . "\n";
        echo '<td class="itemname removeconditions">' . get_string('removeconditions', $plugin) . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        echo html_writer::checkbox('removeconditions', 1, $removeconditions, get_string('removeconditions_help', $plugin));
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('removeconditions'), (! this.checked), true)";
        echo html_writer::checkbox('select_removeconditions', 1, optional_param('select_removeconditions', 0, PARAM_INT), '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
        // =====================
        // condition dates
        // =====================
        //
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . $str->datetitle . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        $names = array();
        $i_max = count($conditiondatedirection);
        for ($i = 0; $i < $i_max; $i++) {
            $conditiondatetime[$i]['minutes'] = intval($conditiondatetime[$i]['minutes']) - intval($conditiondatetime[$i]['minutes']) % 5;
            echo html_writer::start_tag('p');
            echo html_writer::select($conditiondatedirectionmenu, "conditiondatedirection[{$i}]", $conditiondatedirection[$i], '') . ' ';
            echo html_writer::select($days, "conditiondatetimeday[{$i}]", intval($conditiondatetime[$i]['mday']), '') . ' ';
            echo html_writer::select($months, "conditiondatetimemonth[{$i}]", intval($conditiondatetime[$i]['mon']), '') . ' ';
            echo html_writer::select($years, "conditiondatetimeyear[{$i}]", intval($conditiondatetime[$i]['year']), '') . ' ';
            echo html_writer::select($hours, "conditiondatetimehours[{$i}]", intval($conditiondatetime[$i]['hours']), '') . ' ';
            echo html_writer::select($minutes, "conditiondatetimeminutes[{$i}]", intval($conditiondatetime[$i]['minutes']), '') . ' ';
            echo html_writer::end_tag('p');
            $names[] = "conditiondatedirection[{$i}]";
            $names[] = "conditiondatetimeday[{$i}]";
            $names[] = "conditiondatetimemonth[{$i}]";
            $names[] = "conditiondatetimeyear[{$i}]";
            $names[] = "conditiondatetimehours[{$i}]";
            $names[] = "conditiondatetimeminutes[{$i}]";
        }
        $names = implode("', '", $names);
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('{$names}'), (! this.checked))";
        echo html_writer::checkbox('select_conditiondate', 1, optional_param('select_conditiondate', 0, PARAM_INT), '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
        // =====================
        // condition grades
        // =====================
        //
        if (count($conditiongradeitemidmenu)) {
            echo '<tr>' . "\n";
            echo '<td class="itemname">' . $str->gradetitle . ':</td>' . "\n";
            echo '<td class="itemvalue">';
            $names = array();
            $i_max = count($conditiongradeitemid);
            for ($i = 0; $i < $i_max; $i++) {
                echo html_writer::start_tag('p');
                echo html_writer::select($conditiongradeitemidmenu, 'conditiongradeitemid[' . $i . ']', $conditiongradeitemid[$i], '', array('class' => 'conditiongradeitemid')) . ' ';
                echo html_writer::empty_tag('br');
                echo $str->grademin . ' ';
                echo ' <input id="id_conditiongrademin[' . $i . ']" type="text" name="conditiongrademin[' . $i . ']" size="3" value="' . $conditiongrademin[$i] . '" />% ';
                echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('spacer'), 'class' => 'spacer', 'width' => '30px'));
                echo $str->grademax . ' ';
                echo ' <input id="id_conditiongrademax[' . $i . ']" type="text" name="conditiongrademax[' . $i . ']" size="3" value="' . $conditiongrademax[$i] . '" />% ';
                echo html_writer::end_tag('p');
                $names[] = 'conditiongradeitemid[' . $i . ']';
                $names[] = 'conditiongrademin[' . $i . ']';
                $names[] = 'conditiongrademax[' . $i . ']';
            }
            $names = implode("', '", $names);
            echo '</td>' . "\n";
            echo '<td class="itemselect">';
            $script = "return set_disabled(this.form, new Array('{$names}'), (! this.checked))";
            echo html_writer::checkbox('select_conditiongrade', 1, optional_param('select_conditiongrade', 0, PARAM_INT), '', array('onclick' => $script));
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
        // =====================
        // condition userfields
        // =====================
        //
        if (count($conditionfieldnamemenu)) {
            echo '<tr>' . "\n";
            echo '<td class="itemname">' . $str->userfield . ':</td>' . "\n";
            echo '<td class="itemvalue">';
            $names = array();
            $i_max = count($conditionfieldname);
            for ($i = 0; $i < $i_max; $i++) {
                echo html_writer::start_tag('p');
                echo html_writer::select($conditionfieldnamemenu, 'conditionfieldname[' . $i . ']', $conditionfieldname[$i], '', array('class' => 'conditionfieldname')) . ' ';
                echo html_writer::select($conditionfieldoperatormenu, 'conditionfieldoperator[' . $i . ']', $conditionfieldoperator[$i], '', array('class' => 'conditionfieldoperator')), ' ';
                echo '<input id="id_conditionfieldvalue[' . $i . ']" type="text" name="conditionfieldvalue[' . $i . ']" size="15" value="' . $conditionfieldvalue[$i] . '" />';
                echo html_writer::end_tag('p');
                $names[] = 'conditionfieldname[' . $i . ']';
                $names[] = 'conditionfieldoperator[' . $i . ']';
                $names[] = 'conditionfieldvalue[' . $i . ']';
            }
            $names = implode("', '", $names);
            echo '</td>' . "\n";
            echo '<td class="itemselect">';
            $script = "return set_disabled(this.form, new Array('{$names}'), (! this.checked))";
            echo html_writer::checkbox('select_conditionfield', 1, optional_param('select_conditionfield', 0, PARAM_INT), '', array('onclick' => $script));
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
        // =====================
        // condition groups
        // =====================
        //
        if (count($conditiongroupidmenu)) {
            echo '<tr>' . "\n";
            echo '<td class="itemname">' . get_string('group') . ':</td>' . "\n";
            echo '<td class="itemvalue">';
            $names = array();
            $i_max = count($conditiongroupid);
            for ($i = 0; $i < $i_max; $i++) {
                echo html_writer::start_tag('p');
                echo html_writer::select($conditiongroupidmenu, 'conditiongroupid[' . $i . ']', $conditiongroupid[$i], '', array('class' => 'conditiongroupid'));
                echo html_writer::end_tag('p');
                $names[] = 'conditiongroupid[' . $i . ']';
            }
            $names = implode("', '", $names);
            echo '</td>' . "\n";
            echo '<td class="itemselect">';
            $script = "return set_disabled(this.form, new Array('{$names}'), (! this.checked))";
            echo html_writer::checkbox('select_conditiongroup', 1, optional_param('select_conditiongroup', 0, PARAM_INT), '', array('onclick' => $script));
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
        // =====================
        // condition groupings
        // =====================
        //
        if (count($conditiongroupingidmenu)) {
            echo '<tr>' . "\n";
            echo '<td class="itemname">' . get_string('grouping', 'group') . ':</td>' . "\n";
            echo '<td class="itemvalue">';
            $names = array();
            $i_max = count($conditiongroupingid);
            for ($i = 0; $i < $i_max; $i++) {
                echo html_writer::start_tag('p');
                echo html_writer::select($conditiongroupingidmenu, 'conditiongroupingid[' . $i . ']', $conditiongroupingid[$i], '', array('class' => 'conditiongroupingid'));
                echo html_writer::end_tag('p');
                $names[] = 'conditiongroupingid[' . $i . ']';
            }
            $names = implode("', '", $names);
            echo '</td>' . "\n";
            echo '<td class="itemselect">';
            $script = "return set_disabled(this.form, new Array('{$names}'), (! this.checked))";
            echo html_writer::checkbox('select_conditiongrouping', 1, optional_param('select_conditiongrouping', 0, PARAM_INT), '', array('onclick' => $script));
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
        // =====================
        // conditions completion
        // of other activities
        // =====================
        //
        if (count($conditioncmidmenu)) {
            echo '<tr>' . "\n";
            echo '<td class="itemname">' . $str->activitycompletion . ':</td>' . "\n";
            echo '<td class="itemvalue">';
            $names = array();
            $i_max = count($conditioncmid);
            for ($i = 0; $i < $i_max; $i++) {
                echo html_writer::start_tag('p');
                echo html_writer::select($conditioncmidmenu, 'conditioncmid[' . $i . ']', $conditioncmid[$i], '', array('class' => 'conditioncmid'));
                echo html_writer::empty_tag('br');
                echo html_writer::checkbox('conditioncmungraded[' . $i . ']', 1, $conditioncmungraded[$i], $str->conditioncmungraded, array('class' => 'conditioncmungraded'));
                echo html_writer::empty_tag('br');
                echo html_writer::checkbox('conditioncmresources[' . $i . ']', 1, $conditioncmresources[$i], $str->conditioncmresources, array('class' => 'conditioncmresources'));
                echo html_writer::empty_tag('br');
                echo html_writer::checkbox('conditioncmlabels[' . $i . ']', 1, $conditioncmlabels[$i], $str->conditioncmlabels, array('class' => 'conditioncmlabels'));
                echo html_writer::empty_tag('br');
                echo html_writer::select($conditioncmcompletionmenu, 'conditioncmcompletion[' . $i . ']', $conditioncmcompletion[$i], '', array('class' => 'conditioncmcompletion'));
                echo html_writer::end_tag('p');
                $names[] = 'conditioncmid[' . $i . ']';
                $names[] = 'conditioncmungraded[' . $i . ']';
                $names[] = 'conditioncmresources[' . $i . ']';
                $names[] = 'conditioncmlabels[' . $i . ']';
                $names[] = 'conditioncmcompletion[' . $i . ']';
            }
            $names = implode("', '", $names);
            echo '</td>' . "\n";
            echo '<td class="itemselect">';
            $script = "return set_disabled(this.form, new Array('{$names}'), (! this.checked))";
            echo html_writer::checkbox('select_conditioncm', 1, optional_param('select_conditioncm', 0, PARAM_INT), '', array('onclick' => $script));
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
        // =====================
        // conditions actions
        // =====================
        //
        if (count($conditionactionmenu)) {
            echo '<tr>' . "\n";
            echo '<td class="itemname">' . $str->showavailability . ':</td>' . "\n";
            echo '<td class="itemvalue">';
            $names = array();
            $i_max = count($conditionaction);
            for ($i = 0; $i < $i_max; $i++) {
                echo html_writer::start_tag('p');
                echo html_writer::select($conditionactionmenu, 'conditionaction[' . $i . ']', $conditionaction[$i], '', array('class' => 'conditionaction'));
                echo html_writer::end_tag('p');
                $names[] = 'conditionaction[' . $i . ']';
            }
            $names = implode("', '", $names);
            echo '</td>' . "\n";
            echo '<td class="itemselect">';
            $script = "return set_disabled(this.form, new Array('{$names}'), (! this.checked))";
            echo html_writer::checkbox('select_conditionaction', 1, optional_param('select_conditionaction', 0, PARAM_INT), '', array('onclick' => $script));
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
    }
    // ============================
    // Activity completion
    // ============================
    //
    if ($enablecompletion) {
        print_sectionheading(get_string('activitycompletion', 'completion'), 'completion', true);
        echo '<tr>' . "\n";
        echo '<td class="itemname removecompletion">' . get_string('removecompletion', $plugin) . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        echo html_writer::checkbox('removecompletion', 1, $removecompletion, get_string('removecompletion_help', $plugin));
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('removecompletion'), (! this.checked), true)";
        echo html_writer::checkbox('select_removecompletion', 1, optional_param('select_removecompletion', 0, PARAM_INT), '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
        echo '<tr>' . "\n";
        echo '<td class="itemname erasecompletion">' . get_string('erasecompletion', $plugin) . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        echo html_writer::checkbox('erasecompletion', 1, $erasecompletion, get_string('erasecompletion_help', $plugin));
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('erasecompletion'), (! this.checked), true)";
        echo html_writer::checkbox('select_erasecompletion', 1, optional_param('select_erasecompletion', 0, PARAM_INT), '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
        // =====================
        // completion type
        // none/manual/automatic
        // =====================
        //
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('completion', 'completion') . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        echo html_writer::select($completiontrackingmenu, 'completiontracking', $completiontracking, '');
        echo html_writer::empty_tag('br') . '(' . get_string('usedbyall', $plugin) . ')';
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('completiontracking'), (! this.checked))";
        echo html_writer::checkbox('select_completiontracking', 1, optional_param('select_completiontracking', 0, PARAM_INT), '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
        // =====================
        // require view
        // =====================
        //
        //echo '<tr>'."\n";
        //echo '<td class="itemname">'.get_string('completionview', 'completion').':</td>'."\n";
        //echo '<td class="itemvalue">';
        //echo html_writer::checkbox('completionview', 1, $completionview, get_string('completionview_desc', 'completion'));
        //echo '</td>'."\n";
        //echo '<td class="itemselect">';
        //$script = "return set_disabled(this.form, new Array('completionview'), (! this.checked), true)";
        //echo html_writer::checkbox('select_completionview', 1, optional_param('select_completionview', 0, PARAM_INT), '', array('onclick' => $script));
        //echo '</td>'."\n";
        //echo '</tr>'."\n";
        // =====================
        // require grade
        // =====================
        //
        //echo '<tr>'."\n";
        //echo '<td class="itemname">'.get_string('completionusegrade', 'completion').':</td>'."\n";
        //echo '<td class="itemvalue">';
        //echo html_writer::checkbox('completiongrade', 1, $completiongrade, get_string('completionusegrade_desc', 'completion'));
        //echo '</td>'."\n";
        //echo '<td class="itemselect">';
        //$script = "return set_disabled(this.form, new Array('completiongrade'), (! this.checked), true)";
        //echo html_writer::checkbox('select_completiongrade', 1, optional_param('select_completiongrade', 0, PARAM_INT), '', array('onclick' => $script));
        //echo '</td>'."\n";
        //echo '</tr>'."\n";
        // =====================
        // completion date
        // =====================
        //
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('completionexpected', 'completion') . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        echo html_writer::select_time('days', 'completionday', $completiondate, 1) . ' ';
        echo html_writer::select_time('months', 'completionmonth', $completiondate, 1) . ' ';
        echo html_writer::select_time('years', 'completionyear', $completiondate, 1);
        echo html_writer::empty_tag('br') . '(' . get_string('usedbyall', $plugin) . ')';
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('completionday', 'completionmonth', 'completionyear'), (! this.checked))";
        echo html_writer::checkbox('select_completiondate', 1, optional_param('select_completiondate', 0, PARAM_INT), '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
        // =====================
        // activity-specific
        // completion settings
        // =====================
        //
        foreach ($completionfields as $name => $field) {
            $text = $field->text;
            $desc = $field->desc;
            $type = $field->type;
            if ($text == $desc) {
                $desc = '';
            }
            if (empty($field->params['name'])) {
                $fieldname = $name;
            } else {
                $fieldname = $field->params['name'];
            }
            if ($modnames = implode(', ', $field->mods)) {
                $modnames = get_string('completionfieldactivities', $plugin, $modnames);
                $modnames = html_writer::tag('span', "({$modnames})", array('class' => 'completionfieldmodnames'));
                if ($desc) {
                    $modnames = html_writer::empty_tag('br') . $modnames;
                }
            }
            echo '<tr>' . "\n";
            echo '<td class="itemname">' . $text . ':</td>' . "\n";
            echo '<td class="itemvalue">';
            switch ($type) {
                case 'checkbox':
                    echo html_writer::checkbox($name, 1, ${$name}, ' ' . $desc . $modnames, $field->params);
                    break;
                case 'duration':
                    $options = implode('', $field->options);
                    echo $desc . ' ' . html_writer::empty_tag('input', $field->params['number']) . ' ' . html_writer::tag('select', $options, $field->params['unit']) . ' ' . $modnames;
                    break;
                case 'select':
                    $options = implode('', $field->options);
                    echo $desc . ' ' . html_writer::tag('select', $options, $field->params) . $modnames;
                    break;
                case 'textbox':
                    echo $desc . ' ' . html_writer::empty_tag('input', $field->params) . ' ' . $modnames;
                    break;
            }
            echo '</td>' . "\n";
            echo '<td class="itemselect">';
            $fieldnames = "'{$fieldname}'";
            if ($type == 'duration') {
                $fieldnames .= ",'" . $fieldname . "_unit'";
            }
            $script = $type == 'checkbox' ? 'true' : 'false';
            // sync_checkbox
            $script = "return set_disabled(this.form, new Array({$fieldnames}), (! this.checked), {$script})";
            echo html_writer::checkbox('select_' . $name, 1, optional_param('select_' . $name, 0, PARAM_INT), '', array('onclick' => $script));
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
    }
    // ============================
    // Activity competency
    // ============================
    //
    if ($enablecompetency) {
        print_sectionheading(get_string('competencies', 'competency'), 'competency', true);
        echo '<tr>' . "\n";
        echo '<td class="itemname">' . get_string('uponcoursemodulecompletion', 'tool_lp') . ':</td>' . "\n";
        echo '<td class="itemvalue">';
        echo html_writer::select($competencyrulemenu, 'competencyrule', $competencyrule, '');
        echo html_writer::empty_tag('br') . '(' . get_string('usedbyall', $plugin) . ')';
        echo '</td>' . "\n";
        echo '<td class="itemselect">';
        $script = "return set_disabled(this.form, new Array('competencyrule'), (! this.checked))";
        echo html_writer::checkbox('select_competencyrule', 1, optional_param('select_competencyrule', 0, PARAM_INT), '', array('onclick' => $script));
        echo '</td>' . "\n";
        echo '</tr>' . "\n";
    }
    // ============================
    // Actions
    // ============================
    //
    print_sectionheading(get_string('actions'), 'actions', false);
    echo '<tr>' . "\n";
    echo '<td class="itemname">&nbsp;</td>' . "\n";
    echo '<td class="itemvalue">' . "\n";
    $btn = get_string('applysettings', $plugin);
    $msg = js(get_string('confirmapply', $plugin));
    echo '<input type="submit" name="apply" value="' . $btn . '" onclick="return confirm_action(' . "'{$msg}'" . ', true)" />' . "\n";
    echo ' &nbsp; &nbsp; ' . "\n";
    echo '<input type="submit" name="cancel" value="' . get_string('cancel') . '" />' . "\n";
    echo ' &nbsp; &nbsp; ' . "\n";
    $btn = get_string('delete');
    $msg = js(get_string('confirmdelete', $plugin));
    echo '<input type="submit" name="delete" value="' . $btn . '" onclick="return confirm_action(' . "'{$msg}'" . ')" />' . "\n";
    echo '<input type="hidden" name="id" value="' . $block_instance->id . '" />' . "\n";
    echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />' . "\n";
    echo '</td><td></td>' . "\n";
    echo '</tr>' . "\n";
    echo '</table>' . "\n";
    echo '</form>' . "\n";
}