Exemple #1
0
 /**
  * Form definition.
  *
  * @return void
  */
 function definition()
 {
     global $CFG;
     $mform =& $this->_form;
     $mform->disable_form_change_checker();
     $mform->addElement('header', 'search', get_string('search', 'search'));
     // Help info depends on the selected search engine.
     $mform->addElement('text', 'q', get_string('enteryoursearchquery', 'search'));
     $mform->addHelpButton('q', 'searchinfo', $this->_customdata['searchengine']);
     $mform->setType('q', PARAM_TEXT);
     $mform->addRule('q', get_string('required'), 'required', null, 'client');
     $mform->addElement('header', 'filtersection', get_string('filterheader', 'search'));
     $mform->setExpanded('filtersection', false);
     $mform->addElement('text', 'title', get_string('title', 'search'));
     $mform->setType('title', PARAM_TEXT);
     $search = \core_search\manager::instance();
     $searchareas = \core_search\manager::get_search_areas_list(true);
     $areanames = array();
     foreach ($searchareas as $areaid => $searcharea) {
         $areanames[$areaid] = $searcharea->get_visible_name();
     }
     // Sort the array by the text.
     \core_collator::asort($areanames);
     $options = array('multiple' => true, 'noselectionstring' => get_string('allareas', 'search'));
     $mform->addElement('autocomplete', 'areaids', get_string('searcharea', 'search'), $areanames, $options);
     $options = array('multiple' => true, 'limittoenrolled' => !is_siteadmin(), 'noselectionstring' => get_string('allcourses', 'search'));
     $mform->addElement('course', 'courseids', get_string('courses', 'core'), $options);
     $mform->setType('courseids', PARAM_INT);
     $mform->addElement('date_time_selector', 'timestart', get_string('fromtime', 'search'), array('optional' => true));
     $mform->setDefault('timestart', 0);
     $mform->addElement('date_time_selector', 'timeend', get_string('totime', 'search'), array('optional' => true));
     $mform->setDefault('timeend', 0);
     $this->add_action_buttons(false, get_string('search', 'search'));
 }
Exemple #2
0
 /**
  * Returns a localised list of timezones.
  * @param string $currentvalue
  * @param bool $include99 should the server timezone info be included?
  * @return array
  */
 public static function get_list_of_timezones($currentvalue = null, $include99 = false)
 {
     self::init_zones();
     // Localise first.
     $timezones = array();
     foreach (self::$goodzones as $tzkey => $ignored) {
         $timezones[$tzkey] = self::get_localised_timezone($tzkey);
     }
     core_collator::asort($timezones);
     // Add '99' if requested.
     if ($include99 or $currentvalue == 99) {
         $timezones['99'] = self::get_localised_timezone('99');
     }
     if (!isset($currentvalue) or isset($timezones[$currentvalue])) {
         return $timezones;
     }
     if (is_numeric($currentvalue)) {
         // UTC offset.
         $modifier = $currentvalue > 0 ? '+' : '';
         $a = 'UTC' . $modifier . number_format($currentvalue, 1);
         $timezones[$currentvalue] = get_string('timezoneinvalid', 'core_admin', $a);
     } else {
         // Some string we don't recognise.
         $timezones[$currentvalue] = get_string('timezoneinvalid', 'core_admin', $currentvalue);
     }
     return $timezones;
 }
 function filter($text, array $options = array())
 {
     $coursectx = $this->context->get_course_context(false);
     if (!$coursectx) {
         return $text;
     }
     $courseid = $coursectx->instanceid;
     // Initialise/invalidate our trivial cache if dealing with a different course
     if (!isset(self::$cachedcourseid) || self::$cachedcourseid !== (int) $courseid) {
         self::$activitylist = null;
     }
     self::$cachedcourseid = (int) $courseid;
     /// It may be cached
     if (is_null(self::$activitylist)) {
         self::$activitylist = array();
         $modinfo = get_fast_modinfo($courseid);
         if (!empty($modinfo->cms)) {
             self::$activitylist = array();
             // We will store all the created filters here.
             // Create array of visible activities sorted by the name length (we are only interested in properties name and url).
             $sortedactivities = array();
             foreach ($modinfo->cms as $cm) {
                 // Exclude labels, hidden activities and activities for group members only.
                 if ($cm->visible and empty($cm->groupmembersonly) and $cm->has_view()) {
                     $sortedactivities[] = (object) array('name' => $cm->name, 'url' => $cm->url, 'id' => $cm->id, 'namelen' => strlen($cm->name));
                 }
             }
             core_collator::asort_objects_by_property($sortedactivities, 'namelen', SORT_NUMERIC);
             foreach ($sortedactivities as $cm) {
                 $title = s(trim(strip_tags($cm->name)));
                 $currentname = trim($cm->name);
                 $entitisedname = s($currentname);
                 // Avoid empty or unlinkable activity names.
                 if (!empty($title)) {
                     $href_tag_begin = html_writer::start_tag('a', array('class' => 'autolink', 'title' => $title, 'href' => $cm->url));
                     self::$activitylist[$cm->id] = new filterobject($currentname, $href_tag_begin, '</a>', false, true);
                     if ($currentname != $entitisedname) {
                         // If name has some entity (&amp; &quot; &lt; &gt;) add that filter too. MDL-17545.
                         self::$activitylist[$cm->id . '-e'] = new filterobject($entitisedname, $href_tag_begin, '</a>', false, true);
                     }
                 }
             }
         }
     }
     $filterslist = array();
     if (self::$activitylist) {
         $cmid = $this->context->instanceid;
         if ($this->context->contextlevel == CONTEXT_MODULE && isset(self::$activitylist[$cmid])) {
             // remove filterobjects for the current module
             $filterslist = array_values(array_diff_key(self::$activitylist, array($cmid => 1, $cmid . '-e' => 1)));
         } else {
             $filterslist = array_values(self::$activitylist);
         }
     }
     if ($filterslist) {
         return $text = filter_phrases($text, $filterslist);
     } else {
         return $text;
     }
 }
Exemple #4
0
 protected function get_javascript_init_params($course, \cm_info $cm = null, \section_info $section = null)
 {
     global $DB, $CFG;
     require_once $CFG->libdir . '/gradelib.php';
     require_once $CFG->dirroot . '/course/lib.php';
     // Get grades as basic associative array.
     $gradeoptions = array();
     $items = \grade_item::fetch_all(array('courseid' => $course->id));
     // For some reason the fetch_all things return null if none.
     $items = $items ? $items : array();
     foreach ($items as $id => $item) {
         // Don't include the grade item if it's linked with a module that is being deleted.
         if (course_module_instance_pending_deletion($item->courseid, $item->itemmodule, $item->iteminstance)) {
             continue;
         }
         // Do not include grades for current item.
         if ($cm && $cm->instance == $item->iteminstance && $cm->modname == $item->itemmodule && $item->itemtype == 'mod') {
             continue;
         }
         $gradeoptions[$id] = $item->get_name(true);
     }
     \core_collator::asort($gradeoptions);
     // Change to JS array format and return.
     $jsarray = array();
     foreach ($gradeoptions as $id => $name) {
         $jsarray[] = (object) array('id' => $id, 'name' => $name);
     }
     return array($jsarray);
 }
Exemple #5
0
/**
 * Callback for the "Complete" report - prints the activity summary for the given user
 *
 * @param object $course
 * @param object $user
 * @param object $mod
 * @param object $choice
 */
function choice_user_complete($course, $user, $mod, $choice)
{
    global $DB;
    if ($answers = $DB->get_records('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
        $info = [];
        foreach ($answers as $answer) {
            $info[] = "'" . format_string(choice_get_option_text($choice, $answer->optionid)) . "'";
        }
        core_collator::asort($info);
        echo get_string("answered", "choice") . ": " . join(', ', $info) . ". " . get_string("updated", '', userdate($answer->timemodified));
    } else {
        print_string("notanswered", "choice");
    }
}
Exemple #6
0
 protected function get_javascript_init_params($course, \cm_info $cm = null, \section_info $section = null)
 {
     // Standard user fields.
     $standardfields = array('firstname' => get_user_field_name('firstname'), 'lastname' => get_user_field_name('lastname'), 'email' => get_user_field_name('email'), 'city' => get_user_field_name('city'), 'country' => get_user_field_name('country'), 'url' => get_user_field_name('url'), 'icq' => get_user_field_name('icq'), 'skype' => get_user_field_name('skype'), 'aim' => get_user_field_name('aim'), 'yahoo' => get_user_field_name('yahoo'), 'msn' => get_user_field_name('msn'), 'idnumber' => get_user_field_name('idnumber'), 'institution' => get_user_field_name('institution'), 'department' => get_user_field_name('department'), 'phone1' => get_user_field_name('phone1'), 'phone2' => get_user_field_name('phone2'), 'address' => get_user_field_name('address'));
     \core_collator::asort($standardfields);
     // Custom fields.
     $customfields = array();
     $options = array('context' => \context_course::instance($course->id));
     foreach (condition::get_custom_profile_fields() as $field) {
         $customfields[$field->shortname] = format_string($field->name, true, $options);
     }
     \core_collator::asort($customfields);
     // Make arrays into JavaScript format (non-associative, ordered) and return.
     return array(self::convert_associative_array_for_js($standardfields, 'field', 'display'), self::convert_associative_array_for_js($customfields, 'field', 'display'));
 }
 function get_content()
 {
     global $CFG, $DB, $OUTPUT;
     if ($this->content !== NULL) {
         return $this->content;
     }
     $this->content = new stdClass();
     $this->content->items = array();
     $this->content->icons = array();
     $this->content->footer = '';
     $course = $this->page->course;
     require_once $CFG->dirroot . '/course/lib.php';
     $modinfo = get_fast_modinfo($course);
     $modfullnames = array();
     $archetypes = array();
     foreach ($modinfo->cms as $cm) {
         // Exclude activities which are not visible or have no link (=label)
         if (!$cm->uservisible or !$cm->has_view()) {
             continue;
         }
         if (array_key_exists($cm->modname, $modfullnames)) {
             continue;
         }
         if (!array_key_exists($cm->modname, $archetypes)) {
             $archetypes[$cm->modname] = plugin_supports('mod', $cm->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
         }
         if ($archetypes[$cm->modname] == MOD_ARCHETYPE_RESOURCE) {
             if (!array_key_exists('resources', $modfullnames)) {
                 $modfullnames['resources'] = get_string('resources');
             }
         } else {
             $modfullnames[$cm->modname] = $cm->modplural;
         }
     }
     core_collator::asort($modfullnames);
     foreach ($modfullnames as $modname => $modfullname) {
         if ($modname === 'resources') {
             $icon = $OUTPUT->pix_icon('icon', '', 'mod_page', array('class' => 'icon'));
             $this->content->items[] = '<a href="' . $CFG->wwwroot . '/course/resources.php?id=' . $course->id . '">' . $icon . $modfullname . '</a>';
         } else {
             $icon = '<img src="' . $OUTPUT->pix_url('icon', $modname) . '" class="icon" alt="" />';
             $this->content->items[] = '<a href="' . $CFG->wwwroot . '/mod/' . $modname . '/index.php?id=' . $course->id . '">' . $icon . $modfullname . '</a>';
         }
     }
     return $this->content;
 }
Exemple #8
0
 /**
  * Retrieve the list of available filter options.
  *
  * @return  array                   An array whose keys are the valid options
  *                                  And whose values are the values to display
  */
 public static function get_filter_options()
 {
     $allroles = role_get_names(null, ROLENAME_ALIAS);
     $roles = [];
     foreach ($allroles as $role) {
         if ($role->archetype === 'guest') {
             // No point in including the 'guest' role as it isn't possible to show tours to a guest.
             continue;
         }
         $roles[$role->shortname] = $role->localname;
     }
     // Add the Site Administrator pseudo-role.
     $roles[self::ROLE_SITEADMIN] = get_string('administrator', 'core');
     // Sort alphabetically too.
     \core_collator::asort($roles);
     return $roles;
 }
 /**
  * This function renders the form elements when adding a customcert element.
  *
  * @param mod_customcert_edit_element_form $mform the edit_form instance
  */
 public function render_form_elements($mform)
 {
     // Get the user profile fields.
     $userfields = array('firstname' => get_user_field_name('firstname'), 'lastname' => get_user_field_name('lastname'), 'email' => get_user_field_name('email'), 'city' => get_user_field_name('city'), 'country' => get_user_field_name('country'), 'url' => get_user_field_name('url'), 'icq' => get_user_field_name('icq'), 'skype' => get_user_field_name('skype'), 'aim' => get_user_field_name('aim'), 'yahoo' => get_user_field_name('yahoo'), 'msn' => get_user_field_name('msn'), 'idnumber' => get_user_field_name('idnumber'), 'institution' => get_user_field_name('institution'), 'department' => get_user_field_name('department'), 'phone1' => get_user_field_name('phone1'), 'phone2' => get_user_field_name('phone2'), 'address' => get_user_field_name('address'));
     // Get the user custom fields.
     $arrcustomfields = \availability_profile\condition::get_custom_profile_fields();
     $customfields = array();
     foreach ($arrcustomfields as $key => $customfield) {
         $customfields[$customfield->id] = $key;
     }
     // Combine the two.
     $fields = $userfields + $customfields;
     core_collator::asort($fields);
     // Create the select box where the user field is selected.
     $mform->addElement('select', 'userfield', get_string('userfield', 'customcertelement_userfield'), $fields);
     $mform->setType('userfield', PARAM_ALPHANUM);
     $mform->addHelpButton('userfield', 'userfield', 'customcertelement_userfield');
     parent::render_form_elements($mform);
 }
Exemple #10
0
/**
 * Retrieve the messages between two users
 *
 * @param object $user1 the current user
 * @param object $user2 the other user
 * @param int $limitnum the maximum number of messages to retrieve
 * @param bool $viewingnewmessages are we currently viewing new messages?
 */
function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
    global $DB, $CFG;

    $messages = array();

    //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
    //desc to get the last $limitnum messages then flip the order in php
    $sort = 'asc';
    if ($limitnum>0) {
        $sort = 'desc';
    }

    $notificationswhere = null;
    //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
    if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
        $notificationswhere = 'AND notification=0';
    }

    //prevent notifications of your own actions appearing in your own message history
    $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';

    $sql = "((useridto = ? AND useridfrom = ? AND timeusertodeleted = 0) OR
        (useridto = ? AND useridfrom = ? AND timeuserfromdeleted = 0))";
    if ($messages_read = $DB->get_records_select('message_read', $sql . $notificationswhere . $ownnotificationwhere,
                                                    array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
                                                    "timecreated $sort", '*', 0, $limitnum)) {
        foreach ($messages_read as $message) {
            $messages[] = $message;
        }
    }
    if ($messages_new = $DB->get_records_select('message', $sql . $ownnotificationwhere,
                                                    array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
                                                    "timecreated $sort", '*', 0, $limitnum)) {
        foreach ($messages_new as $message) {
            $messages[] = $message;
        }
    }

    $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);

    //if we only want the last $limitnum messages
    $messagecount = count($messages);
    if ($limitnum > 0 && $messagecount > $limitnum) {
        $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
    }

    return $messages;
}
Exemple #11
0
/**
 * Return a {@link block_contents} representing the add a new block UI, if
 * this user is allowed to see it.
 *
 * @return block_contents an appropriate block_contents, or null if the user
 * cannot add any blocks here.
 */
function block_add_block_ui($page, $output)
{
    global $CFG, $OUTPUT;
    if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
        return null;
    }
    $bc = new block_contents();
    $bc->title = get_string('addblock');
    $bc->add_class('block_adminblock');
    $bc->attributes['data-block'] = 'adminblock';
    $missingblocks = $page->blocks->get_addable_blocks();
    if (empty($missingblocks)) {
        $bc->content = get_string('noblockstoaddhere');
        return $bc;
    }
    $menu = array();
    foreach ($missingblocks as $block) {
        $blockobject = block_instance($block->name);
        if ($blockobject !== false && $blockobject->user_can_addto($page)) {
            $menu[$block->name] = $blockobject->get_title();
        }
    }
    core_collator::asort($menu);
    $actionurl = new moodle_url($page->url, array('sesskey' => sesskey()));
    $select = new single_select($actionurl, 'bui_addblock', $menu, null, array('' => get_string('adddots')), 'add_block');
    $select->set_label(get_string('addblock'), array('class' => 'accesshide'));
    $bc->content = $OUTPUT->render($select);
    return $bc;
}
/**
 * Get list of available import or export formats
 * @param string $type 'import' if import list, otherwise export list assumed
 * @return array sorted list of import/export formats available
 */
function get_import_export_formats($type)
{
    global $CFG;
    require_once $CFG->dirroot . '/question/format.php';
    $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
    $fileformatname = array();
    foreach ($formatclasses as $component => $formatclass) {
        $format = new $formatclass();
        if ($type == 'import') {
            $provided = $format->provide_import();
        } else {
            $provided = $format->provide_export();
        }
        if ($provided) {
            list($notused, $fileformat) = explode('_', $component, 2);
            $fileformatnames[$fileformat] = get_string('pluginname', $component);
        }
    }
    core_collator::asort($fileformatnames);
    return $fileformatnames;
}
Exemple #13
0
 /**
  * Sorts the result of {@link file_storage::get_area_tree()}.
  *
  * @param array $tree Array of results provided by {@link file_storage::get_area_tree()}
  * @return array of sorted results
  */
 protected function sort_area_tree($tree)
 {
     foreach ($tree as $key => &$value) {
         if ($key == 'subdirs') {
             core_collator::ksort($value, core_collator::SORT_NATURAL);
             foreach ($value as $subdirname => &$subtree) {
                 $subtree = $this->sort_area_tree($subtree);
             }
         } else {
             if ($key == 'files') {
                 core_collator::ksort($value, core_collator::SORT_NATURAL);
             }
         }
     }
     return $tree;
 }
Exemple #14
0
 /**
  * View the grading table of all submissions for this assignment.
  *
  * @return string
  */
 protected function view_grading_table()
 {
     global $USER, $CFG;
     // Include grading options form.
     require_once $CFG->dirroot . '/mod/assign/gradingoptionsform.php';
     require_once $CFG->dirroot . '/mod/assign/quickgradingform.php';
     require_once $CFG->dirroot . '/mod/assign/gradingbatchoperationsform.php';
     $o = '';
     $cmid = $this->get_course_module()->id;
     $links = array();
     if (has_capability('gradereport/grader:view', $this->get_course_context()) && has_capability('moodle/grade:viewall', $this->get_course_context())) {
         $gradebookurl = '/grade/report/grader/index.php?id=' . $this->get_course()->id;
         $links[$gradebookurl] = get_string('viewgradebook', 'assign');
     }
     if ($this->is_any_submission_plugin_enabled() && $this->count_submissions()) {
         $downloadurl = '/mod/assign/view.php?id=' . $cmid . '&action=downloadall';
         $links[$downloadurl] = get_string('downloadall', 'assign');
     }
     if ($this->is_blind_marking() && has_capability('mod/assign:revealidentities', $this->get_context())) {
         $revealidentitiesurl = '/mod/assign/view.php?id=' . $cmid . '&action=revealidentities';
         $links[$revealidentitiesurl] = get_string('revealidentities', 'assign');
     }
     foreach ($this->get_feedback_plugins() as $plugin) {
         if ($plugin->is_enabled() && $plugin->is_visible()) {
             foreach ($plugin->get_grading_actions() as $action => $description) {
                 $url = '/mod/assign/view.php' . '?id=' . $cmid . '&plugin=' . $plugin->get_type() . '&pluginsubtype=assignfeedback' . '&action=viewpluginpage&pluginaction=' . $action;
                 $links[$url] = $description;
             }
         }
     }
     // Sort links alphabetically based on the link description.
     core_collator::asort($links);
     $gradingactions = new url_select($links);
     $gradingactions->set_label(get_string('choosegradingaction', 'assign'));
     $gradingmanager = get_grading_manager($this->get_context(), 'mod_assign', 'submissions');
     $perpage = get_user_preferences('assign_perpage', 10);
     $filter = get_user_preferences('assign_filter', '');
     $markerfilter = get_user_preferences('assign_markerfilter', '');
     $workflowfilter = get_user_preferences('assign_workflowfilter', '');
     $controller = $gradingmanager->get_active_controller();
     $showquickgrading = empty($controller);
     $quickgrading = get_user_preferences('assign_quickgrading', false);
     $showonlyactiveenrolopt = has_capability('moodle/course:viewsuspendedusers', $this->context);
     $markingallocation = $this->get_instance()->markingallocation && has_capability('mod/assign:manageallocations', $this->context);
     // Get markers to use in drop lists.
     $markingallocationoptions = array();
     if ($markingallocation) {
         $markers = get_users_by_capability($this->context, 'mod/assign:grade');
         $markingallocationoptions[''] = get_string('filternone', 'assign');
         foreach ($markers as $marker) {
             $markingallocationoptions[$marker->id] = fullname($marker);
         }
     }
     $markingworkflow = $this->get_instance()->markingworkflow;
     // Get marking states to show in form.
     $markingworkflowoptions = array();
     if ($markingworkflow) {
         $notmarked = get_string('markingworkflowstatenotmarked', 'assign');
         $markingworkflowoptions[''] = get_string('filternone', 'assign');
         $markingworkflowoptions[ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED] = $notmarked;
         $markingworkflowoptions = array_merge($markingworkflowoptions, $this->get_marking_workflow_states_for_current_user());
     }
     // Print options for changing the filter and changing the number of results per page.
     $gradingoptionsformparams = array('cm' => $cmid, 'contextid' => $this->context->id, 'userid' => $USER->id, 'submissionsenabled' => $this->is_any_submission_plugin_enabled(), 'showquickgrading' => $showquickgrading, 'quickgrading' => $quickgrading, 'markingworkflowopt' => $markingworkflowoptions, 'markingallocationopt' => $markingallocationoptions, 'showonlyactiveenrolopt' => $showonlyactiveenrolopt, 'showonlyactiveenrol' => $this->show_only_active_users());
     $classoptions = array('class' => 'gradingoptionsform');
     $gradingoptionsform = new mod_assign_grading_options_form(null, $gradingoptionsformparams, 'post', '', $classoptions);
     $batchformparams = array('cm' => $cmid, 'submissiondrafts' => $this->get_instance()->submissiondrafts, 'duedate' => $this->get_instance()->duedate, 'attemptreopenmethod' => $this->get_instance()->attemptreopenmethod, 'feedbackplugins' => $this->get_feedback_plugins(), 'context' => $this->get_context(), 'markingworkflow' => $markingworkflow, 'markingallocation' => $markingallocation);
     $classoptions = array('class' => 'gradingbatchoperationsform');
     $gradingbatchoperationsform = new mod_assign_grading_batch_operations_form(null, $batchformparams, 'post', '', $classoptions);
     $gradingoptionsdata = new stdClass();
     $gradingoptionsdata->perpage = $perpage;
     $gradingoptionsdata->filter = $filter;
     $gradingoptionsdata->markerfilter = $markerfilter;
     $gradingoptionsdata->workflowfilter = $workflowfilter;
     $gradingoptionsform->set_data($gradingoptionsdata);
     $actionformtext = $this->get_renderer()->render($gradingactions);
     $header = new assign_header($this->get_instance(), $this->get_context(), false, $this->get_course_module()->id, get_string('grading', 'assign'), $actionformtext);
     $o .= $this->get_renderer()->render($header);
     $currenturl = $CFG->wwwroot . '/mod/assign/view.php?id=' . $this->get_course_module()->id . '&action=grading';
     $o .= groups_print_activity_menu($this->get_course_module(), $currenturl, true);
     // Plagiarism update status apearring in the grading book.
     if (!empty($CFG->enableplagiarism)) {
         require_once $CFG->libdir . '/plagiarismlib.php';
         $o .= plagiarism_update_status($this->get_course(), $this->get_course_module());
     }
     // Load and print the table of submissions.
     if ($showquickgrading && $quickgrading) {
         $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, true);
         $table = $this->get_renderer()->render($gradingtable);
         $quickformparams = array('cm' => $this->get_course_module()->id, 'gradingtable' => $table);
         $quickgradingform = new mod_assign_quick_grading_form(null, $quickformparams);
         $o .= $this->get_renderer()->render(new assign_form('quickgradingform', $quickgradingform));
     } else {
         $gradingtable = new assign_grading_table($this, $perpage, $filter, 0, false);
         $o .= $this->get_renderer()->render($gradingtable);
     }
     $currentgroup = groups_get_activity_group($this->get_course_module(), true);
     $users = array_keys($this->list_participants($currentgroup, true));
     if (count($users) != 0) {
         // If no enrolled user in a course then don't display the batch operations feature.
         $assignform = new assign_form('gradingbatchoperationsform', $gradingbatchoperationsform);
         $o .= $this->get_renderer()->render($assignform);
     }
     $assignform = new assign_form('gradingoptionsform', $gradingoptionsform, 'M.mod_assign.init_grading_options');
     $o .= $this->get_renderer()->render($assignform);
     return $o;
 }
Exemple #15
0
/**
 * Get the users recent conversations meaning all the people they've recently
 * sent or received a message from plus the most recent message sent to or received from each other user
 *
 * @param object|int $userorid the current user or user id
 * @param int $limitfrom can be used for paging
 * @param int $limitto can be used for paging
 * @return array
 */
function message_get_recent_conversations($userorid, $limitfrom = 0, $limitto = 100) {
    global $DB;

    if (is_object($userorid)) {
        $user = $userorid;
    } else {
        $userid = $userorid;
        $user = new stdClass();
        $user->id = $userid;
    }

    $userfields = user_picture::fields('otheruser', array('lastaccess'));

    // This query retrieves the most recent message received from or sent to
    // seach other user.
    //
    // If two messages have the same timecreated, we take the one with the
    // larger id.
    //
    // There is a separate query for read and unread messages as they are stored
    // in different tables. They were originally retrieved in one query but it
    // was so large that it was difficult to be confident in its correctness.
    $uniquefield = $DB->sql_concat('message.useridfrom', "'-'", 'message.useridto');
    $sql = "SELECT $uniquefield, $userfields,
                   message.id as mid, message.notification, message.useridfrom, message.useridto,
                   message.smallmessage, message.fullmessage, message.fullmessagehtml,
                   message.fullmessageformat, message.timecreated,
                   contact.id as contactlistid, contact.blocked
              FROM {message_read} message
              JOIN (
                        SELECT MAX(id) AS messageid,
                               matchedmessage.useridto,
                               matchedmessage.useridfrom
                         FROM {message_read} matchedmessage
                   INNER JOIN (
                               SELECT MAX(recentmessages.timecreated) timecreated,
                                      recentmessages.useridfrom,
                                      recentmessages.useridto
                                 FROM {message_read} recentmessages
                                WHERE (
                                      (recentmessages.useridfrom = :userid1 AND recentmessages.timeuserfromdeleted = 0) OR
                                      (recentmessages.useridto = :userid2   AND recentmessages.timeusertodeleted = 0)
                                      )
                             GROUP BY recentmessages.useridfrom, recentmessages.useridto
                              ) recent ON matchedmessage.useridto     = recent.useridto
                           AND matchedmessage.useridfrom   = recent.useridfrom
                           AND matchedmessage.timecreated  = recent.timecreated
                           WHERE (
                                 (matchedmessage.useridfrom = :userid6 AND matchedmessage.timeuserfromdeleted = 0) OR
                                 (matchedmessage.useridto = :userid7   AND matchedmessage.timeusertodeleted = 0)
                                 )
                      GROUP BY matchedmessage.useridto, matchedmessage.useridfrom
                   ) messagesubset ON messagesubset.messageid = message.id
              JOIN {user} otheruser ON (message.useridfrom = :userid4 AND message.useridto = otheruser.id)
                OR (message.useridto   = :userid5 AND message.useridfrom   = otheruser.id)
         LEFT JOIN {message_contacts} contact ON contact.userid  = :userid3 AND contact.contactid = otheruser.id
             WHERE otheruser.deleted = 0 AND message.notification = 0
          ORDER BY message.timecreated DESC";
    $params = array(
            'userid1' => $user->id,
            'userid2' => $user->id,
            'userid3' => $user->id,
            'userid4' => $user->id,
            'userid5' => $user->id,
            'userid6' => $user->id,
            'userid7' => $user->id
        );
    $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);

    // We want to get the messages that have not been read. These are stored in the 'message' table. It is the
    // exact same query as the one above, except for the table we are querying. So, simply replace references to
    // the 'message_read' table with the 'message' table.
    $sql = str_replace('{message_read}', '{message}', $sql);
    $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);

    $unreadcountssql = 'SELECT useridfrom, count(*) as count
                          FROM {message}
                         WHERE useridto = :userid
                           AND timeusertodeleted = 0
                           AND notification = 0
                      GROUP BY useridfrom';
    $unreadcounts = $DB->get_records_sql($unreadcountssql, array('userid' => $user->id));

    // Union the 2 result sets together looking for the message with the most
    // recent timecreated for each other user.
    // $conversation->id (the array key) is the other user's ID.
    $conversations = array();
    $conversation_arrays = array($unread, $read);
    foreach ($conversation_arrays as $conversation_array) {
        foreach ($conversation_array as $conversation) {
            // Only consider it unread if $user has unread messages.
            if (isset($unreadcounts[$conversation->useridfrom])) {
                $conversation->isread = 0;
                $conversation->unreadcount = $unreadcounts[$conversation->useridfrom]->count;
            } else {
                $conversation->isread = 1;
            }

            if (!isset($conversations[$conversation->id])) {
                $conversations[$conversation->id] = $conversation;
            } else {
                $current = $conversations[$conversation->id];
                // We need to maintain the isread and unreadcount values from existing
                // parts of the conversation if we're replacing it.
                $conversation->isread = ($conversation->isread && $current->isread);
                if (isset($current->unreadcount) && !isset($conversation->unreadcount)) {
                    $conversation->unreadcount = $current->unreadcount;
                }

                if ($current->timecreated < $conversation->timecreated) {
                    $conversations[$conversation->id] = $conversation;
                } else if ($current->timecreated == $conversation->timecreated) {
                    if ($current->mid < $conversation->mid) {
                        $conversations[$conversation->id] = $conversation;
                    }
                }
            }
        }
    }

    // Sort the conversations by $conversation->timecreated, newest to oldest
    // There may be multiple conversations with the same timecreated
    // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
    $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
    $conversations = array_reverse($conversations);

    return $conversations;
}
Exemple #16
0
 /**
  * Returns the children associated with this category.
  *
  * @return part_of_admin_tree[]
  */
 public function get_children()
 {
     // If we should sort and it hasn't already been sorted.
     if ($this->sort && !$this->sorted) {
         if ($this->sortsplit) {
             $categories = array();
             $pages = array();
             foreach ($this->children as $child) {
                 if ($child instanceof admin_category) {
                     $categories[] = $child;
                 } else {
                     $pages[] = $child;
                 }
             }
             core_collator::asort_objects_by_property($categories, 'visiblename');
             core_collator::asort_objects_by_property($pages, 'visiblename');
             if (!$this->sortasc) {
                 $categories = array_reverse($categories);
                 $pages = array_reverse($pages);
             }
             $this->children = array_merge($pages, $categories);
         } else {
             core_collator::asort_objects_by_property($this->children, 'visiblename');
             if (!$this->sortasc) {
                 $this->children = array_reverse($this->children);
             }
         }
         $this->sorted = true;
     }
     return $this->children;
 }
 /**
  * Resort the courses within this category by the given field.
  *
  * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
  * @param bool $cleanup
  * @return bool True for success.
  * @throws coding_exception
  */
 public function resort_courses($field, $cleanup = true)
 {
     global $DB;
     $desc = false;
     if (substr($field, -4) === "desc") {
         $desc = true;
         $field = substr($field, 0, -4);
         // Remove "desc" from field name.
     }
     if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
         // This is ultra important as we use $field in an SQL statement below this.
         throw new coding_exception('Invalid field requested');
     }
     $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
     $sql = "SELECT c.id, c.sortorder, c.{$field}, {$ctxfields}\n                  FROM {course} c\n             LEFT JOIN {context} ctx ON ctx.instanceid = c.id\n                 WHERE ctx.contextlevel = :ctxlevel AND\n                       c.category = :categoryid";
     $params = array('ctxlevel' => CONTEXT_COURSE, 'categoryid' => $this->id);
     $courses = $DB->get_records_sql($sql, $params);
     if (count($courses) > 0) {
         foreach ($courses as $courseid => $course) {
             context_helper::preload_from_record($course);
             if ($field === 'idnumber') {
                 $course->sortby = $course->idnumber;
             } else {
                 // It'll require formatting.
                 $options = array('context' => context_course::instance($course->id));
                 // We format the string first so that it appears as the user would see it.
                 // This ensures the sorting makes sense to them. However it won't necessarily make
                 // sense to everyone if things like multilang filters are enabled.
                 // We then strip any tags as we don't want things such as image tags skewing the
                 // sort results.
                 $course->sortby = strip_tags(format_string($course->{$field}, true, $options));
             }
             // We set it back here rather than using references as there is a bug with using
             // references in a foreach before passing as an arg by reference.
             $courses[$courseid] = $course;
         }
         // Sort the courses.
         core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
         if (!empty($desc)) {
             $courses = array_reverse($courses);
         }
         $i = 1;
         foreach ($courses as $course) {
             $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
             $i++;
         }
         if ($cleanup) {
             // This should not be needed but we do it just to be safe.
             fix_course_sortorder();
             cache_helper::purge_by_event('changesincourse');
         }
     }
     return true;
 }
Exemple #18
0
function theme_bcu_get_course_activities()
{
    global $CFG, $PAGE, $OUTPUT;
    // A copy of block_activity_modules.
    $course = $PAGE->course;
    $content = new stdClass();
    $modinfo = get_fast_modinfo($course);
    $modfullnames = array();
    $archetypes = array();
    foreach ($modinfo->cms as $cm) {
        // Exclude activities which are not visible or have no link (=label).
        if (!$cm->uservisible or !$cm->has_view()) {
            continue;
        }
        if (array_key_exists($cm->modname, $modfullnames)) {
            continue;
        }
        if (!array_key_exists($cm->modname, $archetypes)) {
            $archetypes[$cm->modname] = plugin_supports('mod', $cm->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
        }
        if ($archetypes[$cm->modname] == MOD_ARCHETYPE_RESOURCE) {
            if (!array_key_exists('resources', $modfullnames)) {
                $modfullnames['resources'] = get_string('resources');
            }
        } else {
            $modfullnames[$cm->modname] = $cm->modplural;
        }
    }
    core_collator::asort($modfullnames);
    return $modfullnames;
}
Exemple #19
0
/**
 * Returns the localised human-readable names of all used modules
 *
 * @param bool $plural if true returns the plural forms of the names
 * @return array where key is the module name (component name without 'mod_') and
 *     the value is the human-readable string. Array sorted alphabetically by value
 */
function get_module_types_names($plural = false)
{
    static $modnames = null;
    global $DB, $CFG;
    if ($modnames === null) {
        $modnames = array(0 => array(), 1 => array());
        if ($allmods = $DB->get_records("modules")) {
            foreach ($allmods as $mod) {
                if (file_exists("{$CFG->dirroot}/mod/{$mod->name}/lib.php") && $mod->visible) {
                    $modnames[0][$mod->name] = get_string("modulename", "{$mod->name}");
                    $modnames[1][$mod->name] = get_string("modulenameplural", "{$mod->name}");
                }
            }
            core_collator::asort($modnames[0]);
            core_collator::asort($modnames[1]);
        }
    }
    return $modnames[(int) $plural];
}
 /**
  * Adds all the standard elements to a form to edit the settings for an activity module.
  */
 function standard_coursemodule_elements()
 {
     global $COURSE, $CFG, $DB;
     $mform =& $this->_form;
     $this->_outcomesused = false;
     if ($this->_features->outcomes) {
         if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
             $this->_outcomesused = true;
             $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
             foreach ($outcomes as $outcome) {
                 $mform->addElement('advcheckbox', 'outcome_' . $outcome->id, $outcome->get_name());
             }
         }
     }
     if ($this->_features->rating) {
         require_once $CFG->dirroot . '/rating/lib.php';
         $rm = new rating_manager();
         $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
         $permission = CAP_ALLOW;
         $rolenamestring = null;
         if (!empty($this->_cm)) {
             $context = context_module::instance($this->_cm->id);
             $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/' . $this->_cm->modname . ':rate'));
             $rolenamestring = implode(', ', $rolenames);
         } else {
             $rolenamestring = get_string('capabilitychecknotavailable', 'rating');
         }
         $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring);
         $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
         $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating'), $rm->get_aggregate_types());
         $mform->setDefault('assessed', 0);
         $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
         $mform->addElement('modgrade', 'scale', get_string('scale'), false);
         $mform->disabledIf('scale', 'assessed', 'eq', 0);
         $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
         $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
         $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
         $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
         $mform->disabledIf('assesstimestart', 'ratingtime');
         $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
         $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
         $mform->disabledIf('assesstimefinish', 'ratingtime');
     }
     //doing this here means splitting up the grade related settings on the lesson settings page
     //$this->standard_grading_coursemodule_elements();
     $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
     $mform->addElement('modvisible', 'visible', get_string('visible'));
     if (!empty($this->_cm)) {
         $context = context_module::instance($this->_cm->id);
         if (!has_capability('moodle/course:activityvisibility', $context)) {
             $mform->hardFreeze('visible');
         }
     }
     if ($this->_features->idnumber) {
         $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
         $mform->setType('cmidnumber', PARAM_RAW);
         $mform->addHelpButton('cmidnumber', 'idnumbermod');
     }
     if ($this->_features->groups) {
         $options = array(NOGROUPS => get_string('groupsnone'), SEPARATEGROUPS => get_string('groupsseparate'), VISIBLEGROUPS => get_string('groupsvisible'));
         $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
         $mform->addHelpButton('groupmode', 'groupmode', 'group');
     }
     if ($this->_features->groupings or $this->_features->groupmembersonly) {
         //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
         $options = array();
         if ($groupings = $DB->get_records('groupings', array('courseid' => $COURSE->id))) {
             foreach ($groupings as $grouping) {
                 $options[$grouping->id] = format_string($grouping->name);
             }
         }
         core_collator::asort($options);
         $options = array(0 => get_string('none')) + $options;
         $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
         $mform->addHelpButton('groupingid', 'grouping', 'group');
     }
     if ($this->_features->groupmembersonly) {
         $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group'));
         $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group');
     }
     if (!empty($CFG->enableavailability)) {
         // String used by conditions
         $strnone = get_string('none', 'condition');
         // Conditional availability
         // Available from/to defaults to midnight because then the display
         // will be nicer where it tells users when they can access it (it
         // shows only the date and not time).
         $date = usergetdate(time());
         $midnight = make_timestamp($date['year'], $date['mon'], $date['mday']);
         // From/until controls
         $mform->addElement('header', 'availabilityconditionsheader', get_string('availabilityconditions', 'condition'));
         $mform->addElement('date_time_selector', 'availablefrom', get_string('availablefrom', 'condition'), array('optional' => true, 'defaulttime' => $midnight));
         $mform->addHelpButton('availablefrom', 'availablefrom', 'condition');
         $mform->addElement('date_time_selector', 'availableuntil', get_string('availableuntil', 'condition'), array('optional' => true, 'defaulttime' => $midnight));
         // Conditions based on grades
         $gradeoptions = array();
         $items = grade_item::fetch_all(array('courseid' => $COURSE->id));
         $items = $items ? $items : array();
         foreach ($items as $id => $item) {
             // Do not include grades for current item
             if (!empty($this->_cm) && $this->_cm->instance == $item->iteminstance && $this->_cm->modname == $item->itemmodule && $item->itemtype == 'mod') {
                 continue;
             }
             $gradeoptions[$id] = $item->get_name();
         }
         asort($gradeoptions);
         $gradeoptions = array(0 => $strnone) + $gradeoptions;
         $grouparray = array();
         $grouparray[] =& $mform->createElement('select', 'conditiongradeitemid', '', $gradeoptions);
         $grouparray[] =& $mform->createElement('static', '', '', ' ' . get_string('grade_atleast', 'condition') . ' ');
         $grouparray[] =& $mform->createElement('text', 'conditiongrademin', '', array('size' => 3));
         $grouparray[] =& $mform->createElement('static', '', '', '% ' . get_string('grade_upto', 'condition') . ' ');
         $grouparray[] =& $mform->createElement('text', 'conditiongrademax', '', array('size' => 3));
         $grouparray[] =& $mform->createElement('static', '', '', '%');
         $group = $mform->createElement('group', 'conditiongradegroup', get_string('gradecondition', 'condition'), $grouparray);
         // Get version with condition info and store it so we don't ask
         // twice
         if (!empty($this->_cm)) {
             $ci = new condition_info($this->_cm, CONDITION_MISSING_EXTRATABLE);
             $this->_cm = $ci->get_full_course_module();
             $count = count($this->_cm->conditionsgrade) + 1;
             $fieldcount = count($this->_cm->conditionsfield) + 1;
         } else {
             $count = 1;
             $fieldcount = 1;
         }
         $this->repeat_elements(array($group), $count, array('conditiongradegroup[conditiongrademin]' => array('type' => PARAM_RAW), 'conditiongradegroup[conditiongrademax]' => array('type' => PARAM_RAW)), 'conditiongraderepeats', 'conditiongradeadds', 2, get_string('addgrades', 'condition'), true);
         $mform->addHelpButton('conditiongradegroup[0]', 'gradecondition', 'condition');
         // Conditions based on user fields
         $operators = condition_info::get_condition_user_field_operators();
         $useroptions = condition_info::get_condition_user_fields(array('context' => $this->context));
         asort($useroptions);
         $useroptions = array(0 => $strnone) + $useroptions;
         $grouparray = array();
         $grouparray[] =& $mform->createElement('select', 'conditionfield', '', $useroptions);
         $grouparray[] =& $mform->createElement('select', 'conditionfieldoperator', '', $operators);
         $grouparray[] =& $mform->createElement('text', 'conditionfieldvalue');
         $group = $mform->createElement('group', 'conditionfieldgroup', get_string('userfield', 'condition'), $grouparray);
         $this->repeat_elements(array($group), $fieldcount, array('conditionfieldgroup[conditionfieldvalue]' => array('type' => PARAM_RAW)), 'conditionfieldrepeats', 'conditionfieldadds', 2, get_string('adduserfields', 'condition'), true);
         $mform->addHelpButton('conditionfieldgroup[0]', 'userfield', 'condition');
         // Conditions based on completion
         $completion = new completion_info($COURSE);
         if ($completion->is_enabled()) {
             $completionoptions = array();
             $modinfo = get_fast_modinfo($COURSE);
             foreach ($modinfo->cms as $id => $cm) {
                 // Add each course-module if it:
                 // (a) has completion turned on
                 // (b) is not the same as current course-module
                 if ($cm->completion && (empty($this->_cm) || $this->_cm->id != $id)) {
                     $completionoptions[$id] = $cm->name;
                 }
             }
             asort($completionoptions);
             $completionoptions = array(0 => $strnone) + $completionoptions;
             $completionvalues = array(COMPLETION_COMPLETE => get_string('completion_complete', 'condition'), COMPLETION_INCOMPLETE => get_string('completion_incomplete', 'condition'), COMPLETION_COMPLETE_PASS => get_string('completion_pass', 'condition'), COMPLETION_COMPLETE_FAIL => get_string('completion_fail', 'condition'));
             $grouparray = array();
             $grouparray[] =& $mform->createElement('select', 'conditionsourcecmid', '', $completionoptions);
             $grouparray[] =& $mform->createElement('select', 'conditionrequiredcompletion', '', $completionvalues);
             $group = $mform->createElement('group', 'conditioncompletiongroup', get_string('completioncondition', 'condition'), $grouparray);
             $count = empty($this->_cm) ? 1 : count($this->_cm->conditionscompletion) + 1;
             $this->repeat_elements(array($group), $count, array(), 'conditioncompletionrepeats', 'conditioncompletionadds', 2, get_string('addcompletions', 'condition'), true);
             $mform->addHelpButton('conditioncompletiongroup[0]', 'completioncondition', 'condition');
         }
         // Do we display availability info to students?
         $mform->addElement('select', 'showavailability', get_string('showavailability', 'condition'), array(CONDITION_STUDENTVIEW_SHOW => get_string('showavailability_show', 'condition'), CONDITION_STUDENTVIEW_HIDE => get_string('showavailability_hide', 'condition')));
         $mform->setDefault('showavailability', CONDITION_STUDENTVIEW_SHOW);
     }
     // Conditional activities: completion tracking section
     if (!isset($completion)) {
         $completion = new completion_info($COURSE);
     }
     if ($completion->is_enabled()) {
         $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
         // Unlock button for if people have completed it (will
         // be removed in definition_after_data if they haven't)
         $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
         $mform->registerNoSubmitButton('unlockcompletion');
         $mform->addElement('hidden', 'completionunlocked', 0);
         $mform->setType('completionunlocked', PARAM_INT);
         $trackingdefault = COMPLETION_TRACKING_NONE;
         // If system and activity default is on, set it.
         if ($CFG->completiondefault && $this->_features->defaultcompletion) {
             $trackingdefault = COMPLETION_TRACKING_MANUAL;
         }
         $mform->addElement('select', 'completion', get_string('completion', 'completion'), array(COMPLETION_TRACKING_NONE => get_string('completion_none', 'completion'), COMPLETION_TRACKING_MANUAL => get_string('completion_manual', 'completion')));
         $mform->setDefault('completion', $trackingdefault);
         $mform->addHelpButton('completion', 'completion', 'completion');
         // Automatic completion once you view it
         $gotcompletionoptions = false;
         if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
             $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'), get_string('completionview_desc', 'completion'));
             $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
             $gotcompletionoptions = true;
         }
         // Automatic completion once it's graded
         if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
             $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'), get_string('completionusegrade_desc', 'completion'));
             $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
             $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
             $gotcompletionoptions = true;
         }
         // Automatic completion according to module-specific rules
         $this->_customcompletionelements = $this->add_completion_rules();
         foreach ($this->_customcompletionelements as $element) {
             $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
         }
         $gotcompletionoptions = $gotcompletionoptions || count($this->_customcompletionelements) > 0;
         // Automatic option only appears if possible
         if ($gotcompletionoptions) {
             $mform->getElement('completion')->addOption(get_string('completion_automatic', 'completion'), COMPLETION_TRACKING_AUTOMATIC);
         }
         // Completion expected at particular date? (For progress tracking)
         $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional' => true));
         $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
         $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
     }
     $this->standard_hidden_coursemodule_elements();
 }
Exemple #21
0
/**
 * Returns a list of valid and compatible themes
 *
 * @return array
 */
function get_list_of_themes()
{
    global $CFG;
    $themes = array();
    if (!empty($CFG->themelist)) {
        // Use admin's list of themes.
        $themelist = explode(',', $CFG->themelist);
    } else {
        $themelist = array_keys(core_component::get_plugin_list("theme"));
    }
    foreach ($themelist as $key => $themename) {
        $theme = theme_config::load($themename);
        $themes[$themename] = $theme;
    }
    core_collator::asort_objects_by_method($themes, 'get_theme_name');
    return $themes;
}
Exemple #22
0
 /**
  * Returns array of localised human-readable module names used in this course
  *
  * @param bool $plural if true returns the plural form of modules names
  * @return array
  */
 public function get_used_module_names($plural = false) {
     $modnames = get_module_types_names($plural);
     $modnamesused = array();
     foreach ($this->get_cms() as $cmid => $mod) {
         if (isset($modnames[$mod->modname]) && $mod->uservisible) {
             $modnamesused[$mod->modname] = $modnames[$mod->modname];
         }
     }
     core_collator::asort($modnamesused);
     return $modnamesused;
 }
 /**
  * Adds all the standard elements to a form to edit the settings for an activity module.
  */
 function standard_coursemodule_elements()
 {
     global $COURSE, $CFG, $DB;
     $mform =& $this->_form;
     $this->_outcomesused = false;
     if ($this->_features->outcomes) {
         if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
             $this->_outcomesused = true;
             $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
             foreach ($outcomes as $outcome) {
                 $mform->addElement('advcheckbox', 'outcome_' . $outcome->id, $outcome->get_name());
             }
         }
     }
     if ($this->_features->rating) {
         require_once $CFG->dirroot . '/rating/lib.php';
         $rm = new rating_manager();
         $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
         $permission = CAP_ALLOW;
         $rolenamestring = null;
         if (!empty($this->_cm)) {
             $context = context_module::instance($this->_cm->id);
             $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/' . $this->_cm->modname . ':rate'));
             $rolenamestring = implode(', ', $rolenames);
         } else {
             $rolenamestring = get_string('capabilitychecknotavailable', 'rating');
         }
         $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring);
         $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
         $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating'), $rm->get_aggregate_types());
         $mform->setDefault('assessed', 0);
         $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
         $mform->addElement('modgrade', 'scale', get_string('scale'), false);
         $mform->disabledIf('scale', 'assessed', 'eq', 0);
         $mform->addHelpButton('scale', 'modgrade', 'grades');
         $mform->setDefault('scale', $CFG->gradepointdefault);
         $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
         $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
         $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
         $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
         $mform->disabledIf('assesstimestart', 'ratingtime');
         $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
         $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
         $mform->disabledIf('assesstimefinish', 'ratingtime');
     }
     //doing this here means splitting up the grade related settings on the lesson settings page
     //$this->standard_grading_coursemodule_elements();
     $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
     $mform->addElement('modvisible', 'visible', get_string('visible'));
     if (!empty($this->_cm)) {
         $context = context_module::instance($this->_cm->id);
         if (!has_capability('moodle/course:activityvisibility', $context)) {
             $mform->hardFreeze('visible');
         }
     }
     if ($this->_features->idnumber) {
         $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
         $mform->setType('cmidnumber', PARAM_RAW);
         $mform->addHelpButton('cmidnumber', 'idnumbermod');
     }
     if ($this->_features->groups) {
         $options = array(NOGROUPS => get_string('groupsnone'), SEPARATEGROUPS => get_string('groupsseparate'), VISIBLEGROUPS => get_string('groupsvisible'));
         $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
         $mform->addHelpButton('groupmode', 'groupmode', 'group');
     }
     if ($this->_features->groupings) {
         // Groupings selector - used to select grouping for groups in activity.
         $options = array();
         if ($groupings = $DB->get_records('groupings', array('courseid' => $COURSE->id))) {
             foreach ($groupings as $grouping) {
                 $options[$grouping->id] = format_string($grouping->name);
             }
         }
         core_collator::asort($options);
         $options = array(0 => get_string('none')) + $options;
         $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
         $mform->addHelpButton('groupingid', 'grouping', 'group');
     }
     if (!empty($CFG->enableavailability)) {
         // Add special button to end of previous section if groups/groupings
         // are enabled.
         if ($this->_features->groups || $this->_features->groupings) {
             $mform->addElement('static', 'restrictgroupbutton', '', html_writer::tag('button', get_string('restrictbygroup', 'availability'), array('id' => 'restrictbygroup', 'disabled' => 'disabled')));
         }
         // Availability field. This is just a textarea; the user interface
         // interaction is all implemented in JavaScript.
         $mform->addElement('header', 'availabilityconditionsheader', get_string('restrictaccess', 'availability'));
         // Note: This field cannot be named 'availability' because that
         // conflicts with fields in existing modules (such as assign).
         // So it uses a long name that will not conflict.
         $mform->addElement('textarea', 'availabilityconditionsjson', get_string('accessrestrictions', 'availability'));
         // The _cm variable may not be a proper cm_info, so get one from modinfo.
         if ($this->_cm) {
             $modinfo = get_fast_modinfo($COURSE);
             $cm = $modinfo->get_cm($this->_cm->id);
         } else {
             $cm = null;
         }
         \core_availability\frontend::include_all_javascript($COURSE, $cm);
     }
     // Conditional activities: completion tracking section
     if (!isset($completion)) {
         $completion = new completion_info($COURSE);
     }
     if ($completion->is_enabled()) {
         $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
         // Unlock button for if people have completed it (will
         // be removed in definition_after_data if they haven't)
         $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
         $mform->registerNoSubmitButton('unlockcompletion');
         $mform->addElement('hidden', 'completionunlocked', 0);
         $mform->setType('completionunlocked', PARAM_INT);
         $trackingdefault = COMPLETION_TRACKING_NONE;
         // If system and activity default is on, set it.
         if ($CFG->completiondefault && $this->_features->defaultcompletion) {
             $trackingdefault = COMPLETION_TRACKING_MANUAL;
         }
         $mform->addElement('select', 'completion', get_string('completion', 'completion'), array(COMPLETION_TRACKING_NONE => get_string('completion_none', 'completion'), COMPLETION_TRACKING_MANUAL => get_string('completion_manual', 'completion')));
         $mform->setDefault('completion', $trackingdefault);
         $mform->addHelpButton('completion', 'completion', 'completion');
         // Automatic completion once you view it
         $gotcompletionoptions = false;
         if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
             $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'), get_string('completionview_desc', 'completion'));
             $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
             $gotcompletionoptions = true;
         }
         // Automatic completion once it's graded
         if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
             $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'), get_string('completionusegrade_desc', 'completion'));
             $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
             $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
             $gotcompletionoptions = true;
             // If using the rating system, there is no grade unless ratings are enabled.
             if ($this->_features->rating) {
                 $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
             }
         }
         // Automatic completion according to module-specific rules
         $this->_customcompletionelements = $this->add_completion_rules();
         foreach ($this->_customcompletionelements as $element) {
             $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
         }
         $gotcompletionoptions = $gotcompletionoptions || count($this->_customcompletionelements) > 0;
         // Automatic option only appears if possible
         if ($gotcompletionoptions) {
             $mform->getElement('completion')->addOption(get_string('completion_automatic', 'completion'), COMPLETION_TRACKING_AUTOMATIC);
         }
         // Completion expected at particular date? (For progress tracking)
         $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional' => true));
         $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
         $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
     }
     $this->standard_hidden_coursemodule_elements();
 }
Exemple #24
0
/**
 * Given a course and a time, this module should find recent activity
 * that has occurred in workshop activities and print it out.
 * Return true if there was output, or false is there was none.
 *
 * @param stdClass $course
 * @param bool $viewfullnames
 * @param int $timestart
 * @return boolean
 */
function workshop_print_recent_activity($course, $viewfullnames, $timestart) {
    global $CFG, $USER, $DB, $OUTPUT;

    $authoramefields = get_all_user_name_fields(true, 'author', null, 'author');
    $reviewerfields = get_all_user_name_fields(true, 'reviewer', null, 'reviewer');

    $sql = "SELECT s.id AS submissionid, s.title AS submissiontitle, s.timemodified AS submissionmodified,
                   author.id AS authorid, $authoramefields, a.id AS assessmentid, a.timemodified AS assessmentmodified,
                   reviewer.id AS reviewerid, $reviewerfields, cm.id AS cmid
              FROM {workshop} w
        INNER JOIN {course_modules} cm ON cm.instance = w.id
        INNER JOIN {modules} md ON md.id = cm.module
        INNER JOIN {workshop_submissions} s ON s.workshopid = w.id
        INNER JOIN {user} author ON s.authorid = author.id
         LEFT JOIN {workshop_assessments} a ON a.submissionid = s.id
         LEFT JOIN {user} reviewer ON a.reviewerid = reviewer.id
             WHERE cm.course = ?
                   AND md.name = 'workshop'
                   AND s.example = 0
                   AND (s.timemodified > ? OR a.timemodified > ?)
          ORDER BY s.timemodified";

    $rs = $DB->get_recordset_sql($sql, array($course->id, $timestart, $timestart));

    $modinfo = get_fast_modinfo($course); // reference needed because we might load the groups

    $submissions = array(); // recent submissions indexed by submission id
    $assessments = array(); // recent assessments indexed by assessment id
    $users       = array();

    foreach ($rs as $activity) {
        if (!array_key_exists($activity->cmid, $modinfo->cms)) {
            // this should not happen but just in case
            continue;
        }

        $cm = $modinfo->cms[$activity->cmid];
        if (!$cm->uservisible) {
            continue;
        }

        // remember all user names we can use later
        if (empty($users[$activity->authorid])) {
            $u = new stdclass();
            $users[$activity->authorid] = username_load_fields_from_object($u, $activity, 'author');
        }
        if ($activity->reviewerid and empty($users[$activity->reviewerid])) {
            $u = new stdclass();
            $users[$activity->reviewerid] = username_load_fields_from_object($u, $activity, 'reviewer');
        }

        $context = context_module::instance($cm->id);
        $groupmode = groups_get_activity_groupmode($cm, $course);

        if ($activity->submissionmodified > $timestart and empty($submissions[$activity->submissionid])) {
            $s = new stdclass();
            $s->title = $activity->submissiontitle;
            $s->authorid = $activity->authorid;
            $s->timemodified = $activity->submissionmodified;
            $s->cmid = $activity->cmid;
            if ($activity->authorid == $USER->id || has_capability('mod/workshop:viewauthornames', $context)) {
                $s->authornamevisible = true;
            } else {
                $s->authornamevisible = false;
            }

            // the following do-while wrapper allows to break from deeply nested if-statements
            do {
                if ($s->authorid === $USER->id) {
                    // own submissions always visible
                    $submissions[$activity->submissionid] = $s;
                    break;
                }

                if (has_capability('mod/workshop:viewallsubmissions', $context)) {
                    if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                        if (isguestuser()) {
                            // shortcut - guest user does not belong into any group
                            break;
                        }

                        // this might be slow - show only submissions by users who share group with me in this cm
                        if (!$modinfo->get_groups($cm->groupingid)) {
                            break;
                        }
                        $authorsgroups = groups_get_all_groups($course->id, $s->authorid, $cm->groupingid);
                        if (is_array($authorsgroups)) {
                            $authorsgroups = array_keys($authorsgroups);
                            $intersect = array_intersect($authorsgroups, $modinfo->get_groups($cm->groupingid));
                            if (empty($intersect)) {
                                break;
                            } else {
                                // can see all submissions and shares a group with the author
                                $submissions[$activity->submissionid] = $s;
                                break;
                            }
                        }

                    } else {
                        // can see all submissions from all groups
                        $submissions[$activity->submissionid] = $s;
                    }
                }
            } while (0);
        }

        if ($activity->assessmentmodified > $timestart and empty($assessments[$activity->assessmentid])) {
            $a = new stdclass();
            $a->submissionid = $activity->submissionid;
            $a->submissiontitle = $activity->submissiontitle;
            $a->reviewerid = $activity->reviewerid;
            $a->timemodified = $activity->assessmentmodified;
            $a->cmid = $activity->cmid;
            if ($activity->reviewerid == $USER->id || has_capability('mod/workshop:viewreviewernames', $context)) {
                $a->reviewernamevisible = true;
            } else {
                $a->reviewernamevisible = false;
            }

            // the following do-while wrapper allows to break from deeply nested if-statements
            do {
                if ($a->reviewerid === $USER->id) {
                    // own assessments always visible
                    $assessments[$activity->assessmentid] = $a;
                    break;
                }

                if (has_capability('mod/workshop:viewallassessments', $context)) {
                    if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                        if (isguestuser()) {
                            // shortcut - guest user does not belong into any group
                            break;
                        }

                        // this might be slow - show only submissions by users who share group with me in this cm
                        if (!$modinfo->get_groups($cm->groupingid)) {
                            break;
                        }
                        $reviewersgroups = groups_get_all_groups($course->id, $a->reviewerid, $cm->groupingid);
                        if (is_array($reviewersgroups)) {
                            $reviewersgroups = array_keys($reviewersgroups);
                            $intersect = array_intersect($reviewersgroups, $modinfo->get_groups($cm->groupingid));
                            if (empty($intersect)) {
                                break;
                            } else {
                                // can see all assessments and shares a group with the reviewer
                                $assessments[$activity->assessmentid] = $a;
                                break;
                            }
                        }

                    } else {
                        // can see all assessments from all groups
                        $assessments[$activity->assessmentid] = $a;
                    }
                }
            } while (0);
        }
    }
    $rs->close();

    $shown = false;

    if (!empty($submissions)) {
        $shown = true;
        echo $OUTPUT->heading(get_string('recentsubmissions', 'workshop'), 3);
        foreach ($submissions as $id => $submission) {
            $link = new moodle_url('/mod/workshop/submission.php', array('id'=>$id, 'cmid'=>$submission->cmid));
            if ($submission->authornamevisible) {
                $author = $users[$submission->authorid];
            } else {
                $author = null;
            }
            print_recent_activity_note($submission->timemodified, $author, $submission->title, $link->out(), false, $viewfullnames);
        }
    }

    if (!empty($assessments)) {
        $shown = true;
        echo $OUTPUT->heading(get_string('recentassessments', 'workshop'), 3);
        core_collator::asort_objects_by_property($assessments, 'timemodified');
        foreach ($assessments as $id => $assessment) {
            $link = new moodle_url('/mod/workshop/assessment.php', array('asid' => $id));
            if ($assessment->reviewernamevisible) {
                $reviewer = $users[$assessment->reviewerid];
            } else {
                $reviewer = null;
            }
            print_recent_activity_note($assessment->timemodified, $reviewer, $assessment->submissiontitle, $link->out(), false, $viewfullnames);
        }
    }

    if ($shown) {
        return true;
    }

    return false;
}
Exemple #25
0
$table->define_baseurl($CFG->wwwroot . '/' . $CFG->admin . '/blocks.php');
$table->set_attribute('class', 'admintable blockstable generaltable');
$table->set_attribute('id', 'compatibleblockstable');
$table->setup();
$tablerows = array();
// Sort blocks using current locale.
$blocknames = array();
foreach ($blocks as $blockid => $block) {
    $blockname = $block->name;
    if (file_exists("{$CFG->dirroot}/blocks/{$blockname}/block_{$blockname}.php")) {
        $blocknames[$blockid] = get_string('pluginname', 'block_' . $blockname);
    } else {
        $blocknames[$blockid] = $blockname;
    }
}
core_collator::asort($blocknames);
foreach ($blocknames as $blockid => $strblockname) {
    $block = $blocks[$blockid];
    $blockname = $block->name;
    $dbversion = get_config('block_' . $block->name, 'version');
    if (!file_exists("{$CFG->dirroot}/blocks/{$blockname}/block_{$blockname}.php")) {
        $blockobject = false;
        $strblockname = '<span class="notifyproblem">' . $strblockname . ' (' . get_string('missingfromdisk') . ')</span>';
        $plugin = new stdClass();
        $plugin->version = $dbversion;
    } else {
        $plugin = new stdClass();
        $plugin->version = '???';
        if (file_exists("{$CFG->dirroot}/blocks/{$blockname}/version.php")) {
            include "{$CFG->dirroot}/blocks/{$blockname}/version.php";
        }
Exemple #26
0
    }
    if ($swapcategory and $movecategory) {
        $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $movecategory->id));
        $DB->set_field('course_categories', 'sortorder', $movecategory->sortorder, array('id' => $swapcategory->id));
        cache_helper::purge_by_event('changesincoursecat');
        add_to_log(SITEID, "category", "move", "editcategory.php?id=$movecategory->id", $movecategory->id);
    }

    // Finally reorder courses.
    fix_course_sortorder();
}

if ($coursecat->id && $canmanage && $resort && confirm_sesskey()) {
    // Resort the category.
    if ($courses = get_courses($coursecat->id, '', 'c.id,c.fullname,c.sortorder')) {
        core_collator::asort_objects_by_property($courses, 'fullname', core_collator::SORT_NATURAL);
        $i = 1;
        foreach ($courses as $course) {
            $DB->set_field('course', 'sortorder', $coursecat->sortorder + $i, array('id' => $course->id));
            $i++;
        }
        // This should not be needed but we do it just to be safe.
        fix_course_sortorder();
        cache_helper::purge_by_event('changesincourse');
    }
}

if (!empty($moveto) && ($data = data_submitted()) && confirm_sesskey()) {
    // Move a specified course to a new category.
    // User must have category update in both cats to perform this.
    require_capability('moodle/category:manage', $context);
Exemple #27
0
 /**
  * Obtains the last unique sufix (numeric) using the test course prefix.
  *
  * @return int The last generated numeric value.
  */
 protected static function get_last_testcourse_id()
 {
     global $DB;
     $params = array();
     $params['shortnameprefix'] = $DB->sql_like_escape(self::SHORTNAMEPREFIX) . '%';
     $like = $DB->sql_like('shortname', ':shortnameprefix');
     if (!($testcourses = $DB->get_records_select('course', $like, $params, '', 'shortname'))) {
         return 0;
     }
     // SQL order by is not appropiate here as is ordering strings.
     $shortnames = array_keys($testcourses);
     core_collator::asort($shortnames, core_collator::SORT_NATURAL);
     $shortnames = array_reverse($shortnames);
     // They come ordered by shortname DESC, so non-numeric values will be the first ones.
     $prefixnchars = strlen(self::SHORTNAMEPREFIX);
     foreach ($shortnames as $shortname) {
         $sufix = substr($shortname, $prefixnchars);
         if (preg_match('/^[\\d]+$/', $sufix)) {
             return $sufix;
         }
     }
     // If all sufixes are not numeric this is the first make test site run.
     return 0;
 }
 private function get_course_activities()
 {
     // A copy of block_activity_modules.
     $course = $this->page->course;
     $modinfo = get_fast_modinfo($course);
     $course = course_get_format($course)->get_course();
     $modfullnames = array();
     $archetypes = array();
     foreach ($modinfo->get_section_info_all() as $section => $thissection) {
         if (!empty($course->numsections) and $section > $course->numsections or empty($modinfo->sections[$section])) {
             // This is a stealth section or is empty.
             continue;
         }
         foreach ($modinfo->sections[$thissection->section] as $modnumber) {
             $cm = $modinfo->cms[$modnumber];
             // Exclude activities which are not visible or have no link (=label).
             if (!$cm->uservisible or !$cm->has_view()) {
                 continue;
             }
             if (array_key_exists($cm->modname, $modfullnames)) {
                 continue;
             }
             if (!array_key_exists($cm->modname, $archetypes)) {
                 $archetypes[$cm->modname] = plugin_supports('mod', $cm->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
             }
             if ($archetypes[$cm->modname] == MOD_ARCHETYPE_RESOURCE) {
                 if (!array_key_exists('resources', $modfullnames)) {
                     $modfullnames['resources'] = get_string('resources');
                 }
             } else {
                 $modfullnames[$cm->modname] = $cm->modplural;
             }
         }
     }
     \core_collator::asort($modfullnames);
     return $modfullnames;
 }
/**
 * Set the global activated state for a text filter.
 *
 * @param string $filtername The filter name, for example 'tex'.
 * @param int $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
 * @param int $move -1 means up, 0 means the same, 1 means down
 */
function filter_set_global_state($filtername, $state, $move = 0)
{
    global $DB;
    // Check requested state is valid.
    if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_DISABLED))) {
        throw new coding_exception("Illegal option '{$state}' passed to filter_set_global_state. " . "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
    }
    if ($move > 0) {
        $move = 1;
    } else {
        if ($move < 0) {
            $move = -1;
        }
    }
    if (strpos($filtername, 'filter/') === 0) {
        //debugging("Old filtername '$filtername' parameter used in filter_set_global_state()", DEBUG_DEVELOPER);
        $filtername = substr($filtername, 7);
    } else {
        if (strpos($filtername, '/') !== false) {
            throw new coding_exception("Invalid filter name '{$filtername}' used in filter_set_global_state()");
        }
    }
    $transaction = $DB->start_delegated_transaction();
    $syscontext = context_system::instance();
    $filters = $DB->get_records('filter_active', array('contextid' => $syscontext->id), 'sortorder ASC');
    $on = array();
    $off = array();
    foreach ($filters as $f) {
        if ($f->active == TEXTFILTER_DISABLED) {
            $off[$f->filter] = $f;
        } else {
            $on[$f->filter] = $f;
        }
    }
    // Update the state or add new record.
    if (isset($on[$filtername])) {
        $filter = $on[$filtername];
        if ($filter->active != $state) {
            add_to_config_log('filter_active', $filter->active, $state, $filtername);
            $filter->active = $state;
            $DB->update_record('filter_active', $filter);
            if ($filter->active == TEXTFILTER_DISABLED) {
                unset($on[$filtername]);
                $off = array($filter->filter => $filter) + $off;
            }
        }
    } else {
        if (isset($off[$filtername])) {
            $filter = $off[$filtername];
            if ($filter->active != $state) {
                add_to_config_log('filter_active', $filter->active, $state, $filtername);
                $filter->active = $state;
                $DB->update_record('filter_active', $filter);
                if ($filter->active != TEXTFILTER_DISABLED) {
                    unset($off[$filtername]);
                    $on[$filter->filter] = $filter;
                }
            }
        } else {
            add_to_config_log('filter_active', '', $state, $filtername);
            $filter = new stdClass();
            $filter->filter = $filtername;
            $filter->contextid = $syscontext->id;
            $filter->active = $state;
            $filter->sortorder = 99999;
            $filter->id = $DB->insert_record('filter_active', $filter);
            $filters[$filter->id] = $filter;
            if ($state == TEXTFILTER_DISABLED) {
                $off[$filter->filter] = $filter;
            } else {
                $on[$filter->filter] = $filter;
            }
        }
    }
    // Move only active.
    if ($move != 0 and isset($on[$filter->filter])) {
        $i = 1;
        foreach ($on as $f) {
            $f->newsortorder = $i;
            $i++;
        }
        $filter->newsortorder = $filter->newsortorder + $move;
        foreach ($on as $f) {
            if ($f->id == $filter->id) {
                continue;
            }
            if ($f->newsortorder == $filter->newsortorder) {
                if ($move == 1) {
                    $f->newsortorder = $f->newsortorder - 1;
                } else {
                    $f->newsortorder = $f->newsortorder + 1;
                }
            }
        }
        core_collator::asort_objects_by_property($on, 'newsortorder', core_collator::SORT_NUMERIC);
    }
    // Inactive are sorted by filter name.
    core_collator::asort_objects_by_property($off, 'filter', core_collator::SORT_NATURAL);
    // Update records if necessary.
    $i = 1;
    foreach ($on as $f) {
        if ($f->sortorder != $i) {
            $DB->set_field('filter_active', 'sortorder', $i, array('id' => $f->id));
        }
        $i++;
    }
    foreach ($off as $f) {
        if ($f->sortorder != $i) {
            $DB->set_field('filter_active', 'sortorder', $i, array('id' => $f->id));
        }
        $i++;
    }
    $transaction->allow_commit();
}
Exemple #30
0
 /**
  * Tests the static ksort method.
  */
 public function test_ksort()
 {
     $arr = array('b' => 'ab', 1 => 'aa', 0 => 'cc');
     $result = core_collator::ksort($arr);
     $this->assertSame(array(0, 1, 'b'), array_keys($arr));
     $this->assertSame(array('cc', 'aa', 'ab'), array_values($arr));
     $this->assertTrue($result);
     $obj = new stdClass();
     $arr = array('1.1.1' => array(), '1.2' => $obj, '1.20.2' => null);
     $result = core_collator::ksort($arr, core_collator::SORT_NATURAL);
     $this->assertSame(array('1.1.1', '1.2', '1.20.2'), array_keys($arr));
     $this->assertSame(array(array(), $obj, null), array_values($arr));
     $this->assertTrue($result);
     $a = array(2 => 'b', 1 => 'c');
     $c =& $a;
     $b =& $a;
     core_collator::ksort($b);
     $this->assertSame($a, $b);
     $this->assertSame($c, $b);
 }