Example #1
0
function activities_inuse($id) {
    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");
                }
            }
            collatorlib::asort($modnames[0]);
            collatorlib::asort($modnames[1]);
        }
    }
    $modnames = $modnames[(int) $plural];
    $modulesinuse = array();
    $modulesinuse[null] = '---------Select----------';
    $dbmanager = $DB->get_manager();
    foreach ($modnames as $module => $details) {
        if ($dbmanager->table_exists($module) && $DB->record_exists($module, array('course' => $id))) {
            $modulesinuse[$module] = $details;
        }
    }
    return $modulesinuse;
}
Example #2
0
 static public function cpm_userinfo($a,$b){ //Compare two userinfo fields
     $field = self::$field;
     $adata = $a->userinfo->$field;
     $bdata = $b->userinfo->$field;
     if($adata == $bdata) {
         return self::cpm_userid($a,$b);
     }
     if(is_string($adata) && function_exists('collatorlib::compare')){
         return (collatorlib::compare($adata, $bdata))*(self::$ascending);
     }
     if($adata < $bdata){
         return self::$ascending;
     }else{
         return -self::$ascending;
     }
 }
 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;
         }
     }
     collatorlib::asort($modfullnames);
     foreach ($modfullnames as $modname => $modfullname) {
         if ($modname === 'resources') {
             $icon = '<img src="' . $OUTPUT->pix_url('f/html') . '" class="icon" alt="" />&nbsp;';
             $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="" />&nbsp;';
             $this->content->items[] = '<a href="' . $CFG->wwwroot . '/mod/' . $modname . '/index.php?id=' . $course->id . '">' . $icon . $modfullname . '</a>';
         }
     }
     return $this->content;
 }
Example #4
0
/**
 * Get the names of all the filters installed in this Moodle.
 *
 * @global object
 * @return array path => filter name from the appropriate lang file. e.g.
 * array('mod/glossary' => 'Glossary Auto-linking', 'filter/tex' => 'TeX Notation');
 * sorted in alphabetical order of name.
 */
function filter_get_all_installed()
{
    global $CFG;
    $filternames = array();
    // TODO: deprecated since 2.2, will be out in 2.3, see MDL-29996
    $filterlocations = array('mod', 'filter');
    foreach ($filterlocations as $filterlocation) {
        // TODO: move get_list_of_plugins() to get_plugin_list()
        $filters = get_list_of_plugins($filterlocation);
        foreach ($filters as $filter) {
            // MDL-29994 - Ignore mod/data and mod/glossary filters forever, this will be out in 2.3
            if ($filterlocation == 'mod' && ($filter == 'data' || $filter == 'glossary')) {
                continue;
            }
            $path = $filterlocation . '/' . $filter;
            if (is_readable($CFG->dirroot . '/' . $path . '/filter.php')) {
                $strfiltername = filter_get_name($path);
                $filternames[$path] = $strfiltername;
            }
        }
    }
    collatorlib::asort($filternames);
    return $filternames;
}
Example #5
0
/**
 * Returns a number of useful structures for course displays
 */
function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused)
{
    global $CFG, $DB, $COURSE;
    $mods = array();
    // course modules indexed by id
    $modnames = array();
    // all course module names (except resource!)
    $modnamesplural = array();
    // all course module names (plural form)
    $modnamesused = array();
    // course module names used
    if ($allmods = $DB->get_records("modules")) {
        foreach ($allmods as $mod) {
            if (!file_exists("{$CFG->dirroot}/mod/{$mod->name}/lib.php")) {
                continue;
            }
            if ($mod->visible) {
                $modnames[$mod->name] = get_string("modulename", "{$mod->name}");
                $modnamesplural[$mod->name] = get_string("modulenameplural", "{$mod->name}");
            }
        }
        collatorlib::asort($modnames);
    } else {
        print_error("nomodules", 'debug');
    }
    $course = $courseid == $COURSE->id ? $COURSE : $DB->get_record('course', array('id' => $courseid));
    $modinfo = get_fast_modinfo($course);
    if ($rawmods = $modinfo->cms) {
        foreach ($rawmods as $mod) {
            // Index the mods
            if (empty($modnames[$mod->modname])) {
                continue;
            }
            $mods[$mod->id] = $mod;
            $mods[$mod->id]->modfullname = $modnames[$mod->modname];
            if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
                continue;
            }
            // Check groupings
            if (!groups_course_module_visible($mod)) {
                continue;
            }
            $modnamesused[$mod->modname] = $modnames[$mod->modname];
        }
        if ($modnamesused) {
            collatorlib::asort($modnamesused);
        }
    }
}
Example #6
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;
}
Example #7
0
 /**
  * Sorts list of records by several fields
  *
  * @param array $records array of stdClass objects
  * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
  * @return int
  */
 protected static function sort_records(&$records, $sortfields)
 {
     if (empty($records)) {
         return;
     }
     // If sorting by course display name, calculate it (it may be fullname or shortname+fullname)
     if (array_key_exists('displayname', $sortfields)) {
         foreach ($records as $key => $record) {
             if (!isset($record->displayname)) {
                 $records[$key]->displayname = get_course_display_name_for_list($record);
             }
         }
     }
     // sorting by one field - use collatorlib
     if (count($sortfields) == 1) {
         $property = key($sortfields);
         if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
             $sortflag = collatorlib::SORT_NUMERIC;
         } else {
             if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
                 $sortflag = collatorlib::SORT_STRING;
             } else {
                 $sortflag = collatorlib::SORT_REGULAR;
             }
         }
         collatorlib::asort_objects_by_property($records, $property, $sortflag);
         if ($sortfields[$property] < 0) {
             $records = array_reverse($records, true);
         }
         return;
     }
     $records = coursecat_sortable_records::sort($records, $sortfields);
 }
 /**
  * Tests the static ksort method
  * @return void
  */
 public function test_ksort()
 {
     $arr = array('b' => 'ab', 1 => 'aa', 0 => 'cc');
     $result = collatorlib::ksort($arr);
     $this->assertSame(array_keys($arr), array(0, 1, 'b'));
     $this->assertSame(array_values($arr), array('cc', 'aa', 'ab'));
     $this->assertTrue($result);
     $obj = new stdClass();
     $arr = array('1.1.1' => array(), '1.2' => $obj, '1.20.2' => null);
     $result = collatorlib::ksort($arr, collatorlib::SORT_NATURAL);
     $this->assertSame(array_keys($arr), array('1.1.1', '1.2', '1.20.2'));
     $this->assertSame(array_values($arr), array(array(), $obj, null));
     $this->assertTrue($result);
     $a = array(2 => 'b', 1 => 'c');
     $c =& $a;
     $b =& $a;
     collatorlib::ksort($b);
     $this->assertSame($a, $b);
     $this->assertSame($c, $b);
 }
Example #9
0
 /**
  * Get file listing
  *
  * @param string $path
  * @param string $page
  * @return mixed
  */
 public function get_listing($fullpath = '', $page = '')
 {
     global $OUTPUT;
     $ret = array();
     $ret['list'] = array();
     $ret['manage'] = self::MANAGE_URL;
     $ret['dynload'] = true;
     $crumbs = explode('/', $fullpath);
     $path = array_pop($crumbs);
     if (empty($path)) {
         $type = 'folder';
         $pathid = 0;
         $pathname = get_string('pluginname', 'repository_boxnet');
     } else {
         list($type, $pathid, $pathname) = $this->split_part($path);
     }
     $ret['path'] = $this->build_breadcrumb($fullpath);
     $folders = array();
     $files = array();
     if ($type == 'search') {
         $result = $this->boxnetclient->search($pathname);
     } else {
         $result = $this->boxnetclient->get_folder_items($pathid);
     }
     foreach ($result->entries as $item) {
         if ($item->type == 'folder') {
             $folders[$item->name . ':' . $item->id] = array('title' => $item->name, 'path' => $fullpath . '/' . $this->build_part('folder', $item->id, $item->name), 'date' => strtotime($item->modified_at), 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(64))->out(false), 'thumbnail_height' => 64, 'thumbnail_width' => 64, 'children' => array(), 'size' => $item->size);
         } else {
             $files[$item->name . ':' . $item->id] = array('title' => $item->name, 'source' => $this->build_part('file', $item->id, $item->name), 'size' => $item->size, 'date' => strtotime($item->modified_at), 'thumbnail' => $OUTPUT->pix_url(file_extension_icon($item->name, 64))->out(false), 'thumbnail_height' => 64, 'thumbnail_width' => 64, 'author' => $item->owned_by->name);
         }
     }
     collatorlib::ksort($folders, core_collator::SORT_NATURAL);
     collatorlib::ksort($files, core_collator::SORT_NATURAL);
     $ret['list'] = array_merge($folders, $files);
     $ret['list'] = array_filter($ret['list'], array($this, 'filter'));
     return $ret;
 }
Example #10
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;

    $sql = "SELECT s.id AS submissionid, s.title AS submissiontitle, s.timemodified AS submissionmodified,
                   author.id AS authorid, author.lastname AS authorlastname, author.firstname AS authorfirstname,
                   a.id AS assessmentid, a.timemodified AS assessmentmodified,
                   reviewer.id AS reviewerid, reviewer.lastname AS reviewerlastname, reviewer.firstname AS reviewerfirstname,
                   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();
            $u->lastname = $activity->authorlastname;
            $u->firstname = $activity->authorfirstname;
            $users[$activity->authorid] = $u;
        }
        if ($activity->reviewerid and empty($users[$activity->reviewerid])) {
            $u = new stdclass();
            $u->lastname = $activity->reviewerlastname;
            $u->firstname = $activity->reviewerfirstname;
            $users[$activity->reviewerid] = $u;
        }

        $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);
        collatorlib::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;
}
Example #11
0
    }
    if (!$blockobject) {
        // ignore
        $undeletable = '';
    } else {
        if (in_array($blockname, $undeletableblocktypes)) {
            $undeletable = '<a href="blocks.php?unprotect=' . $blockid . '&amp;sesskey=' . sesskey() . '" title="' . $strunprotect . '">' . '<img src="' . $OUTPUT->pix_url('t/unlock') . '" class="icon" alt="' . $strunprotect . '" /></a>';
        } else {
            $undeletable = '<a href="blocks.php?protect=' . $blockid . '&amp;sesskey=' . sesskey() . '" title="' . $strprotect . '">' . '<img src="' . $OUTPUT->pix_url('t/unlock_gray') . '" class="icon" alt="' . $strprotect . '" /></a>';
        }
    }
    $row = array('<span' . $class . '>' . $strblockname . '</span>', $blocklist, '<span' . $class . '>' . $version . '</span>', $visible, $undeletable, $delete, $settings);
    $tablerows[] = array(strip_tags($strblockname), $row);
    // first element will be used for sorting
}
collatorlib::asort($tablerows);
foreach ($tablerows as $row) {
    $table->add_data($row[1]);
}
$table->print_html();
if (!empty($incompatible)) {
    echo $OUTPUT->heading(get_string('incompatibleblocks', 'blockstable', 'admin'));
    $table = new flexible_table('admin-blocks-incompatible');
    $table->define_columns(array('block', 'delete'));
    $table->define_headers(array($strname, $strdelete));
    $table->define_baseurl($CFG->wwwroot . '/' . $CFG->admin . '/blocks.php');
    $table->set_attribute('class', 'incompatibleblockstable generaltable');
    $table->setup();
    foreach ($incompatible as $block) {
        $table->add_data(array($block->name, '<a href="blocks.php?delete=' . $block->id . '&amp;sesskey=' . sesskey() . '">' . $strdelete . '</a>'));
    }
Example #12
0
/**
 * 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) {
            $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) {
                $filter->active = $state;
                $DB->update_record('filter_active', $filter);
                if ($filter->active != TEXTFILTER_DISABLED) {
                    unset($off[$filtername]);
                    $on[$filter->filter] = $filter;
                }
            }
        } else {
            $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;
                }
            }
        }
        collatorlib::asort_objects_by_property($on, 'newsortorder', collatorlib::SORT_NUMERIC);
    }
    // Inactive are sorted by filter name.
    collatorlib::asort_objects_by_property($off, 'filter', collatorlib::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();
}
 /**
  * Ensures that a collator is available and created
  *
  * @return bool Returns true if collation is available and ready
  */
 protected static function ensure_collator_available()
 {
     $locale = get_string('locale', 'langconfig');
     if (is_null(self::$collator) || $locale != self::$locale) {
         self::$collator = false;
         self::$locale = $locale;
         if (class_exists('Collator', false)) {
             $collator = new Collator($locale);
             if (!empty($collator) && $collator instanceof Collator) {
                 // Check for non fatal error messages. This has to be done immediately
                 // after instantiation as any further calls to collation will cause
                 // it to reset to 0 again (or another error code if one occurred)
                 $errorcode = $collator->getErrorCode();
                 $errormessage = $collator->getErrorMessage();
                 // Check for an error code, 0 means no error occurred
                 if ($errorcode !== 0) {
                     // Get the actual locale being used, e.g. en, he, zh
                     $localeinuse = $collator->getLocale(Locale::ACTUAL_LOCALE);
                     // Check for the common fallback warning error codes. If this occurred
                     // there is normally little to worry about:
                     // - U_USING_DEFAULT_WARNING (127)  - default fallback locale used (pt => UCA)
                     // - U_USING_FALLBACK_WARNING (128) - fallback locale used (de_CH => de)
                     // (UCA: Unicode Collation Algorithm http://unicode.org/reports/tr10/)
                     if ($errorcode === -127 || $errorcode === -128) {
                         // Check if the locale in use is UCA default one ('root') or
                         // if it is anything like the locale we asked for
                         if ($localeinuse !== 'root' && strpos($locale, $localeinuse) !== 0) {
                             // The locale we asked for is completely different to the locale
                             // we have received, let the user know via debugging
                             debugging('Invalid locale: "' . $locale . '", with warning (not fatal) "' . $errormessage . '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
                         } else {
                             // Nothing to do here, this is expected!
                             // The Moodle locale setting isn't what the collator expected but
                             // it is smart enough to match the first characters of our locale
                             // to find the correct locale or to use UCA collation
                         }
                     } else {
                         // We've received some other sort of non fatal warning - let the
                         // user know about it via debugging.
                         debugging('Problem with locale: "' . $locale . '", with message "' . $errormessage . '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
                     }
                 }
                 // Store the collator object now that we can be sure it is in a workable condition
                 self::$collator = $collator;
             } else {
                 // Fatal error while trying to instantiate the collator... something went wrong
                 debugging('Error instantiating collator for locale: "' . $locale . '", with error [' . intl_get_error_code() . '] ' . intl_get_error_message($collator));
             }
         }
     }
     return self::$collator instanceof Collator;
 }
Example #14
0
 /**
  * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
  *
  * @param array $arr array to be sorted (reference)
  * @param int $sortflag One of Collator::SORT_REGULAR, Collator::SORT_NUMERIC, Collator::SORT_STRING
  * @return void modifies parameter
  */
 public static function asort(array &$arr, $sortflag = null)
 {
     debugging('textlib::asort has been superseeded by collatorlib::asort please upgrade your code to use that', DEBUG_DEVELOPER);
     collatorlib::asort($arr, $sortflag);
 }
Example #15
0
 public function test_legacy_collatorlib()
 {
     $arr = array('b' => 'ab', 1 => 'aa', 0 => 'cc');
     $result = collatorlib::asort($arr);
     $this->assertSame(array('aa', 'ab', 'cc'), array_values($arr));
     $this->assertSame(array(1, 'b', 0), array_keys($arr));
     $this->assertTrue($result);
 }
Example #16
0
    }
    $editingon = false;
}

if (!$category->visible) {
    require_capability('moodle/category:viewhiddencategories', $context);
}

$canmanage = has_capability('moodle/category:manage', $context);
$sesskeyprovided = !empty($sesskey) && confirm_sesskey($sesskey);

// Process any category actions.
if ($canmanage && $resort && $sesskeyprovided) {
    // Resort the category if requested
    if ($courses = get_courses($category->id, '', 'c.id,c.fullname,c.sortorder')) {
        collatorlib::asort_objects_by_property($courses, 'fullname', collatorlib::SORT_NATURAL);
        $i = 1;
        foreach ($courses as $course) {
            $DB->set_field('course', 'sortorder', $category->sortorder+$i, array('id'=>$course->id));
            $i++;
        }
        fix_course_sortorder(); // should not be needed
    }
}

// Process any course actions.
if ($editingon && $sesskeyprovided) {

    // Move a specified course to a new category
    if (!empty($moveto) and $data = data_submitted()) {
        // Some courses are being moved
 public function definition_after_data()
 {
     global $CFG, $DB;
     $mform = $this->_form;
     $course = $this->_customdata['course'];
     $context = context_course::instance($course->id);
     if (!empty($CFG->enableavailability)) {
         $mform->addElement('header', 'availabilityconditions', get_string('availabilityconditions', 'condition'));
         $mform->setExpanded('availabilityconditions', false);
         // String used by conditions more than once
         $strcondnone = get_string('none', 'condition');
         // Grouping conditions - only if grouping is enabled at site level
         if (!empty($CFG->enablegroupmembersonly)) {
             $options = array();
             if ($groupings = $DB->get_records('groupings', array('courseid' => $course->id))) {
                 foreach ($groupings as $grouping) {
                     $options[$grouping->id] = format_string($grouping->name, true, array('context' => $context));
                 }
             }
             collatorlib::asort($options);
             $options = array(0 => get_string('none')) + $options;
             $mform->addElement('select', 'groupingid', get_string('groupingsection', 'group'), $options);
             $mform->addHelpButton('groupingid', 'groupingsection', 'group');
         }
         // 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']);
         // Date and time conditions.
         $mform->addElement('date_time_selector', 'availablefrom', get_string('availablefrom', 'condition'), array('optional' => true, 'defaulttime' => $midnight));
         $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) {
             $gradeoptions[$id] = $item->get_name();
         }
         asort($gradeoptions);
         $gradeoptions = array(0 => $strcondnone) + $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 full version (including condition info) of section object
         $ci = new condition_info_section($this->_customdata['cs']);
         $fullcs = $ci->get_full_section();
         $count = count($fullcs->conditionsgrade) + 1;
         // Grade conditions
         $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' => $context));
         asort($useroptions);
         $useroptions = array(0 => $strcondnone) + $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);
         $fieldcount = count($fullcs->conditionsfield) + 1;
         $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) does not belong to current course-section
                 if ($cm->completion && $fullcs->id != $cm->section) {
                     $completionoptions[$id] = $cm->name;
                 }
             }
             asort($completionoptions);
             $completionoptions = array(0 => $strcondnone) + $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 = count($fullcs->conditionscompletion) + 1;
             $this->repeat_elements(array($group), $count, array(), 'conditioncompletionrepeats', 'conditioncompletionadds', 2, get_string('addcompletions', 'condition'), true);
             $mform->addHelpButton('conditioncompletiongroup[0]', 'completionconditionsection', 'condition');
         }
         // Availability conditions - set up form values
         if (!empty($CFG->enableavailability)) {
             $num = 0;
             foreach ($fullcs->conditionsgrade as $gradeitemid => $minmax) {
                 $groupelements = $mform->getElement('conditiongradegroup[' . $num . ']')->getElements();
                 $groupelements[0]->setValue($gradeitemid);
                 $groupelements[2]->setValue(is_null($minmax->min) ? '' : format_float($minmax->min, 5, true, true));
                 $groupelements[4]->setValue(is_null($minmax->max) ? '' : format_float($minmax->max, 5, true, true));
                 $num++;
             }
             $num = 0;
             foreach ($fullcs->conditionsfield as $fieldid => $data) {
                 $groupelements = $mform->getElement('conditionfieldgroup[' . $num . ']')->getElements();
                 $groupelements[0]->setValue($fieldid);
                 $groupelements[1]->setValue(is_null($data->operator) ? '' : $data->operator);
                 $groupelements[2]->setValue(is_null($data->value) ? '' : $data->value);
                 $num++;
             }
             if ($completion->is_enabled()) {
                 $num = 0;
                 foreach ($fullcs->conditionscompletion as $othercmid => $state) {
                     $groupelements = $mform->getElement('conditioncompletiongroup[' . $num . ']')->getElements();
                     $groupelements[0]->setValue($othercmid);
                     $groupelements[1]->setValue($state);
                     $num++;
                 }
             }
         }
         // Do we display availability info to students?
         $showhide = array(CONDITION_STUDENTVIEW_SHOW => get_string('showavailabilitysection_show', 'condition'), CONDITION_STUDENTVIEW_HIDE => get_string('showavailabilitysection_hide', 'condition'));
         $mform->addElement('select', 'showavailability', get_string('showavailabilitysection', 'condition'), $showhide);
     }
     $this->add_action_buttons();
 }
Example #18
0
 public function get_listing($path = '', $page = '') {
     global $CFG, $OUTPUT;
     $list = array();
     $list['list'] = array();
     // process breacrumb trail
     $list['path'] = array(
         array('name'=>get_string('root', 'repository_filesystem'), 'path'=>'')
     );
     $trail = '';
     if (!empty($path)) {
         $parts = explode('/', $path);
         if (count($parts) > 1) {
             foreach ($parts as $part) {
                 if (!empty($part)) {
                     $trail .= ('/'.$part);
                     $list['path'][] = array('name'=>$part, 'path'=>$trail);
                 }
             }
         } else {
             $list['path'][] = array('name'=>$path, 'path'=>$path);
         }
         $this->root_path .= ($path.'/');
     }
     $list['manage'] = false;
     $list['dynload'] = true;
     $list['nologin'] = true;
     $list['nosearch'] = true;
     // retrieve list of files and directories and sort them
     $fileslist = array();
     $dirslist = array();
     if ($dh = opendir($this->root_path)) {
         while (($file = readdir($dh)) != false) {
             if ( $file != '.' and $file !='..') {
                 if (is_file($this->root_path.$file)) {
                     $fileslist[] = $file;
                 } else {
                     $dirslist[] = $file;
                 }
             }
         }
     }
     collatorlib::asort($fileslist, collatorlib::SORT_STRING);
     collatorlib::asort($dirslist, collatorlib::SORT_STRING);
     // fill the $list['list']
     foreach ($dirslist as $file) {
         if (!empty($path)) {
             $current_path = $path . '/'. $file;
         } else {
             $current_path = $file;
         }
         $list['list'][] = array(
             'title' => $file,
             'children' => array(),
             'datecreated' => filectime($this->root_path.$file),
             'datemodified' => filemtime($this->root_path.$file),
             'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false),
             'path' => $current_path
             );
     }
     foreach ($fileslist as $file) {
         $list['list'][] = array(
             'title' => $file,
             'source' => $path.'/'.$file,
             'size' => filesize($this->root_path.$file),
             'datecreated' => filectime($this->root_path.$file),
             'datemodified' => filemtime($this->root_path.$file),
             'thumbnail' => $OUTPUT->pix_url(file_extension_icon($file, 90))->out(false),
             'icon' => $OUTPUT->pix_url(file_extension_icon($file, 24))->out(false)
         );
     }
     $list['list'] = array_filter($list['list'], array($this, 'filter'));
     return $list;
 }
Example #19
0
 /**
  * Returns localised list of installed translations
  *
  * @param bool $returnall return all or just enabled
  * @return array moodle translation code => localised translation name
  */
 public function get_list_of_translations($returnall = false)
 {
     global $CFG;
     $languages = array();
     if (!empty($CFG->langcache) and is_readable($this->menucache)) {
         // try to re-use the cached list of all available languages
         $cachedlist = json_decode(file_get_contents($this->menucache), true);
         if (is_array($cachedlist) and !empty($cachedlist)) {
             // the cache file is restored correctly
             if (!$returnall and !empty($this->translist)) {
                 // return just enabled translations
                 foreach ($cachedlist as $langcode => $langname) {
                     if (in_array($langcode, $this->translist)) {
                         $languages[$langcode] = $langname;
                     }
                 }
                 return $languages;
             } else {
                 // return all translations
                 return $cachedlist;
             }
         }
     }
     // the cached list of languages is not available, let us populate the list
     if (!$returnall and !empty($this->translist)) {
         // return only some translations
         foreach ($this->translist as $lang) {
             $lang = trim($lang);
             //Just trim spaces to be a bit more permissive
             if (strstr($lang, '_local') !== false) {
                 continue;
             }
             if (strstr($lang, '_utf8') !== false) {
                 continue;
             }
             if ($lang !== 'en' and !file_exists("{$this->otherroot}/{$lang}/langconfig.php")) {
                 // some broken or missing lang - can not switch to it anyway
                 continue;
             }
             $string = $this->load_component_strings('langconfig', $lang);
             if (!empty($string['thislanguage'])) {
                 $languages[$lang] = $string['thislanguage'] . ' (' . $lang . ')';
             }
             unset($string);
         }
     } else {
         // return all languages available in system
         $langdirs = get_list_of_plugins('', '', $this->otherroot);
         $langdirs = array_merge($langdirs, array("{$CFG->dirroot}/lang/en" => 'en'));
         // Sort all
         // Loop through all langs and get info
         foreach ($langdirs as $lang) {
             if (strstr($lang, '_local') !== false) {
                 continue;
             }
             if (strstr($lang, '_utf8') !== false) {
                 continue;
             }
             $string = $this->load_component_strings('langconfig', $lang);
             if (!empty($string['thislanguage'])) {
                 $languages[$lang] = $string['thislanguage'] . ' (' . $lang . ')';
             }
             unset($string);
         }
         if (!empty($CFG->langcache) and !empty($this->menucache)) {
             // cache the list so that it can be used next time
             collatorlib::asort($languages);
             check_dir_exists(dirname($this->menucache), true, true);
             file_put_contents($this->menucache, json_encode($languages));
         }
     }
     collatorlib::asort($languages);
     return $languages;
 }
Example #20
0
 function test_asort_objects_by_property()
 {
     $objects = array('b' => new string_test_class('ab'), 1 => new string_test_class('aa'), 0 => new string_test_class('cc'));
     collatorlib::asort_objects_by_property($objects, 'publicname');
     $this->assertIdentical(array_keys($objects), array(1, 'b', 0));
     $this->assertIdentical($this->get_ordered_names($objects, 'publicname'), array('aa', 'ab', 'cc'));
     $objects = array('a' => new string_test_class('áb'), 'b' => new string_test_class('ab'), 1 => new string_test_class('aa'), 0 => new string_test_class('cc'));
     collatorlib::asort_objects_by_property($objects, 'publicname');
     $this->assertIdentical(array_keys($objects), array(1, 'b', 'a', 0), $this->error);
     $this->assertIdentical($this->get_ordered_names($objects, 'publicname'), array('aa', 'ab', 'áb', 'cc'), $this->error);
 }
Example #21
0
$reportsbyname = array();
foreach ($reports as $report => $reportdir) {
    $strreportname = get_string($report . 'report', 'quiz_'.$report);
    $reportsbyname[$strreportname] = $report;
}
collatorlib::ksort($reportsbyname);

// First get a list of quiz reports with there own settings pages. If there none,
// we use a simpler overall menu structure.
$rules = get_plugin_list_with_file('quizaccess', 'settings.php', false);
$rulesbyname = array();
foreach ($rules as $rule => $ruledir) {
    $strrulename = get_string('pluginname', 'quizaccess_' . $rule);
    $rulesbyname[$strrulename] = $rule;
}
collatorlib::ksort($rulesbyname);

// Create the quiz settings page.
if (empty($reportsbyname) && empty($rulesbyname)) {
    $pagetitle = get_string('modulename', 'quiz');
} else {
    $pagetitle = get_string('generalsettings', 'admin');
}
$quizsettings = new admin_settingpage('modsettingquiz', $pagetitle, 'moodle/site:config');

// Introductory explanation that all the settings are defaults for the add quiz form.
$quizsettings->add(new admin_setting_heading('quizintro', '', get_string('configintro', 'quiz')));

// Time limit.
$quizsettings->add(new admin_setting_configtext_with_advanced('quiz/timelimit',
        get_string('timelimitsec', 'quiz'), get_string('configtimelimitsec', 'quiz'),
Example #22
0
/**
 * 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 = 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);
        }
    }
    collatorlib::asort($fileformatnames);
    return $fileformatnames;
}
Example #23
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)';

    if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
                                                    (useridto = ? AND useridfrom = ?)) $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', "((useridto = ? AND useridfrom = ?) OR
                                                    (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
                                                    array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
                                                    "timecreated $sort", '*', 0, $limitnum)) {
        foreach ($messages_new as $message) {
            $messages[] = $message;
        }
    }

    $result = collatorlib::asort_objects_by_property($messages, 'timecreated', collatorlib::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;
}
Example #24
0
 /**
  * Returns:
  *   1 if str1 is greater than str2
  *   0 if str1 is equal to str2
  *  -1 if str1 is less than str2
  *
  * @param mixed $obja The first object to compare
  * @param mixed $objb The second object to compare
  * @return int
  */
 public function compare($obja, $objb) {
     $resulta = $obja->{$this->method}();
     $resultb = $objb->{$this->method}();
     return collatorlib::compare($resulta, $resultb);
 }
Example #25
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');
    $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();
        }
    }
    collatorlib::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;
}
Example #26
0
    /**
     * Sort an array of question types according to the order the admin set up,
     * and then alphabetically for the rest.
     * @param array qtype->name() => qtype->local_name().
     * @return array sorted array.
     */
    public static function sort_qtype_array($qtypes, $config = null) {
        if (is_null($config)) {
            $config = self::get_config();
        }

        $sortorder = array();
        $otherqtypes = array();
        foreach ($qtypes as $name => $localname) {
            $sortvar = $name . '_sortorder';
            if (isset($config->$sortvar)) {
                $sortorder[$config->$sortvar] = $name;
            } else {
                $otherqtypes[$name] = $localname;
            }
        }

        ksort($sortorder);
        collatorlib::asort($otherqtypes);

        $sortedqtypes = array();
        foreach ($sortorder as $name) {
            $sortedqtypes[$name] = $qtypes[$name];
        }
        foreach ($otherqtypes as $name => $notused) {
            $sortedqtypes[$name] = $qtypes[$name];
        }
        return $sortedqtypes;
    }
Example #27
0
$table->define_headers(array($strname, $strcourses, $strversion, $strhide . '/' . $strshow, $strprotecthdr, $strdelete, $strsettings));
$table->define_baseurl($CFG->wwwroot . '/' . $CFG->admin . '/blocks.php');
$table->set_attribute('class', 'compatibleblockstable blockstable generaltable');
$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;
    }
}
collatorlib::asort($blocknames);
foreach ($blocknames as $blockid => $strblockname) {
    $block = $blocks[$blockid];
    $blockname = $block->name;
    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 = $block->version;
    } else {
        $plugin = new stdClass();
        $plugin->version = '???';
        if (file_exists("{$CFG->dirroot}/blocks/{$blockname}/version.php")) {
            include "{$CFG->dirroot}/blocks/{$blockname}/version.php";
        }
        if (!($blockobject = block_instance($block->name))) {
Example #28
0
 function definition_after_data()
 {
     global $DB;
     $mform = $this->_form;
     // add available groupings
     if ($courseid = $mform->getElementValue('id') and $mform->elementExists('defaultgroupingid')) {
         $options = array();
         if ($groupings = $DB->get_records('groupings', array('courseid' => $courseid))) {
             foreach ($groupings as $grouping) {
                 $options[$grouping->id] = format_string($grouping->name);
             }
         }
         collatorlib::asort($options);
         $gr_el =& $mform->getElement('defaultgroupingid');
         $gr_el->load($options);
     }
     // add course format options
     $formatvalue = $mform->getElementValue('format');
     if (is_array($formatvalue) && !empty($formatvalue)) {
         $courseformat = course_get_format((object) array('format' => $formatvalue[0]));
         $elements = $courseformat->create_edit_form_elements($mform);
         for ($i = 0; $i < count($elements); $i++) {
             $mform->insertElementBefore($mform->removeElement($elements[$i]->getName(), false), 'addcourseformatoptionshere');
         }
     }
 }
Example #29
0
 public function definition()
 {
     global $CFG, $USER, $OUTPUT;
     $strrequired = get_string('required');
     $mform =& $this->_form;
     //set default value
     $search = $this->_customdata['search'];
     if (isset($this->_customdata['coverage'])) {
         $coverage = $this->_customdata['coverage'];
     } else {
         $coverage = 'all';
     }
     if (isset($this->_customdata['licence'])) {
         $licence = $this->_customdata['licence'];
     } else {
         $licence = 'all';
     }
     if (isset($this->_customdata['subject'])) {
         $subject = $this->_customdata['subject'];
     } else {
         $subject = 'all';
     }
     if (isset($this->_customdata['audience'])) {
         $audience = $this->_customdata['audience'];
     } else {
         $audience = 'all';
     }
     if (isset($this->_customdata['language'])) {
         $language = $this->_customdata['language'];
     } else {
         $language = current_language();
     }
     if (isset($this->_customdata['educationallevel'])) {
         $educationallevel = $this->_customdata['educationallevel'];
     } else {
         $educationallevel = 'all';
     }
     if (isset($this->_customdata['downloadable'])) {
         $downloadable = $this->_customdata['downloadable'];
     } else {
         $downloadable = 0;
     }
     if (isset($this->_customdata['orderby'])) {
         $orderby = $this->_customdata['orderby'];
     } else {
         $orderby = 'newest';
     }
     if (isset($this->_customdata['huburl'])) {
         $huburl = $this->_customdata['huburl'];
     } else {
         $huburl = HUB_MOODLEORGHUBURL;
     }
     $mform->addElement('header', 'site', get_string('search', 'block_community'));
     //add the course id (of the context)
     $mform->addElement('hidden', 'courseid', $this->_customdata['courseid']);
     $mform->addElement('hidden', 'executesearch', 1);
     //retrieve the hub list on the hub directory by web service
     $function = 'hubdirectory_get_hubs';
     $params = array();
     $serverurl = HUB_HUBDIRECTORYURL . "/local/hubdirectory/webservice/webservices.php";
     require_once $CFG->dirroot . "/webservice/xmlrpc/lib.php";
     $xmlrpcclient = new webservice_xmlrpc_client($serverurl, 'publichubdirectory');
     try {
         $hubs = $xmlrpcclient->call($function, $params);
     } catch (Exception $e) {
         $hubs = array();
         $error = $OUTPUT->notification(get_string('errorhublisting', 'block_community', $e->getMessage()));
         $mform->addElement('static', 'errorhub', '', $error);
     }
     //display list of registered on hub
     $registrationmanager = new registration_manager();
     $registeredhubs = $registrationmanager->get_registered_on_hubs();
     //retrieve some additional hubs that we will add to
     //the hub list got from the hub directory
     $additionalhubs = array();
     foreach ($registeredhubs as $registeredhub) {
         $inthepubliclist = false;
         foreach ($hubs as $hub) {
             if ($hub['url'] == $registeredhub->huburl) {
                 $inthepubliclist = true;
                 $hub['registeredon'] = true;
             }
         }
         if (!$inthepubliclist) {
             $additionalhub = array();
             $additionalhub['name'] = $registeredhub->hubname;
             $additionalhub['url'] = $registeredhub->huburl;
             $additionalhubs[] = $additionalhub;
         }
     }
     if (!empty($additionalhubs)) {
         $hubs = array_merge($hubs, $additionalhubs);
     }
     if (!empty($hubs)) {
         //TODO: sort hubs by trusted/prioritize
         //Public hub list
         $options = array();
         $firsthub = false;
         foreach ($hubs as $hub) {
             if (array_key_exists('id', $hub)) {
                 $params = array('hubid' => $hub['id'], 'filetype' => HUB_HUBSCREENSHOT_FILE_TYPE);
                 $imgurl = new moodle_url(HUB_HUBDIRECTORYURL . "/local/hubdirectory/webservice/download.php", $params);
                 $ascreenshothtml = html_writer::empty_tag('img', array('src' => $imgurl, 'alt' => $hub['name']));
                 $hubdescription = html_writer::tag('a', $hub['name'], array('class' => 'hublink clearfix', 'href' => $hub['url'], 'onclick' => 'this.target="_blank"'));
                 $hubdescription .= html_writer::tag('span', $ascreenshothtml, array('class' => 'hubscreenshot'));
                 $hubdescriptiontext = html_writer::tag('span', format_text($hub['description'], FORMAT_PLAIN), array('class' => 'hubdescription'));
                 if (isset($hub['enrollablecourses'])) {
                     //check needed to avoid warnings for Moodle version < 2011081700
                     $additionaldesc = get_string('enrollablecourses', 'block_community') . ': ' . $hub['enrollablecourses'] . ' - ' . get_string('downloadablecourses', 'block_community') . ': ' . $hub['downloadablecourses'];
                     $hubdescriptiontext .= html_writer::tag('span', $additionaldesc, array('class' => 'hubadditionaldesc'));
                 }
                 if ($hub['trusted']) {
                     $hubtrusted = get_string('hubtrusted', 'block_community');
                     $hubdescriptiontext .= html_writer::tag('span', $hubtrusted . ' ' . $OUTPUT->doc_link('trusted_hubs'), array('class' => 'trusted'));
                 }
                 $hubdescriptiontext = html_writer::tag('span', $hubdescriptiontext, array('class' => 'hubdescriptiontext'));
                 $hubdescription = html_writer::tag('span', $hubdescription . $hubdescriptiontext, array('class' => $hub['trusted'] ? 'hubtrusted' : 'hubnottrusted'));
             } else {
                 $hubdescription = html_writer::tag('a', $hub['name'], array('class' => 'hublink hubtrusted', 'href' => $hub['url']));
             }
             if (empty($firsthub)) {
                 $mform->addElement('radio', 'huburl', get_string('selecthub', 'block_community'), $hubdescription, $hub['url']);
                 $mform->setDefault('huburl', $huburl);
                 $firsthub = true;
             } else {
                 $mform->addElement('radio', 'huburl', '', $hubdescription, $hub['url']);
             }
         }
         //display enrol/download select box if the USER has the download capability on the course
         if (has_capability('moodle/community:download', context_course::instance($this->_customdata['courseid']))) {
             $options = array(0 => get_string('enrollable', 'block_community'), 1 => get_string('downloadable', 'block_community'));
             $mform->addElement('select', 'downloadable', get_string('enroldownload', 'block_community'), $options);
             $mform->addHelpButton('downloadable', 'enroldownload', 'block_community');
         } else {
             $mform->addElement('hidden', 'downloadable', 0);
         }
         $options = array();
         $options['all'] = get_string('any');
         $options[HUB_AUDIENCE_EDUCATORS] = get_string('audienceeducators', 'hub');
         $options[HUB_AUDIENCE_STUDENTS] = get_string('audiencestudents', 'hub');
         $options[HUB_AUDIENCE_ADMINS] = get_string('audienceadmins', 'hub');
         $mform->addElement('select', 'audience', get_string('audience', 'block_community'), $options);
         $mform->setDefault('audience', $audience);
         unset($options);
         $mform->addHelpButton('audience', 'audience', 'block_community');
         $options = array();
         $options['all'] = get_string('any');
         $options[HUB_EDULEVEL_PRIMARY] = get_string('edulevelprimary', 'hub');
         $options[HUB_EDULEVEL_SECONDARY] = get_string('edulevelsecondary', 'hub');
         $options[HUB_EDULEVEL_TERTIARY] = get_string('eduleveltertiary', 'hub');
         $options[HUB_EDULEVEL_GOVERNMENT] = get_string('edulevelgovernment', 'hub');
         $options[HUB_EDULEVEL_ASSOCIATION] = get_string('edulevelassociation', 'hub');
         $options[HUB_EDULEVEL_CORPORATE] = get_string('edulevelcorporate', 'hub');
         $options[HUB_EDULEVEL_OTHER] = get_string('edulevelother', 'hub');
         $mform->addElement('select', 'educationallevel', get_string('educationallevel', 'block_community'), $options);
         $mform->setDefault('educationallevel', $educationallevel);
         unset($options);
         $mform->addHelpButton('educationallevel', 'educationallevel', 'block_community');
         $publicationmanager = new course_publish_manager();
         $options = $publicationmanager->get_sorted_subjects();
         foreach ($options as $key => &$option) {
             $keylength = strlen($key);
             if ($keylength == 10) {
                 $option = "&nbsp;&nbsp;" . $option;
             } else {
                 if ($keylength == 12) {
                     $option = "&nbsp;&nbsp;&nbsp;&nbsp;" . $option;
                 }
             }
         }
         $options = array_merge(array('all' => get_string('any')), $options);
         $mform->addElement('select', 'subject', get_string('subject', 'block_community'), $options, array('id' => 'communitysubject'));
         $mform->setDefault('subject', $subject);
         unset($options);
         $mform->addHelpButton('subject', 'subject', 'block_community');
         $this->init_javascript_enhancement('subject', 'smartselect', array('selectablecategories' => true, 'mode' => 'compact'));
         require_once $CFG->libdir . "/licenselib.php";
         $licensemanager = new license_manager();
         $licences = $licensemanager->get_licenses();
         $options = array();
         $options['all'] = get_string('any');
         foreach ($licences as $license) {
             $options[$license->shortname] = get_string($license->shortname, 'license');
         }
         $mform->addElement('select', 'licence', get_string('licence', 'block_community'), $options);
         unset($options);
         $mform->addHelpButton('licence', 'licence', 'block_community');
         $mform->setDefault('licence', $licence);
         $languages = get_string_manager()->get_list_of_languages();
         collatorlib::asort($languages);
         $languages = array_merge(array('all' => get_string('any')), $languages);
         $mform->addElement('select', 'language', get_string('language'), $languages);
         $mform->setDefault('language', $language);
         $mform->addHelpButton('language', 'language', 'block_community');
         $mform->addElement('radio', 'orderby', get_string('orderby', 'block_community'), get_string('orderbynewest', 'block_community'), 'newest');
         $mform->addElement('radio', 'orderby', null, get_string('orderbyeldest', 'block_community'), 'eldest');
         $mform->addElement('radio', 'orderby', null, get_string('orderbyname', 'block_community'), 'fullname');
         $mform->addElement('radio', 'orderby', null, get_string('orderbypublisher', 'block_community'), 'publisher');
         $mform->addElement('radio', 'orderby', null, get_string('orderbyratingaverage', 'block_community'), 'ratingaverage');
         $mform->setDefault('orderby', $orderby);
         $mform->setType('orderby', PARAM_ALPHA);
         $mform->addElement('text', 'search', get_string('keywords', 'block_community'));
         $mform->addHelpButton('search', 'keywords', 'block_community');
         $mform->addElement('submit', 'submitbutton', get_string('search', 'block_community'));
     }
 }
Example #30
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}");
                }
            }
            collatorlib::asort($modnames[0]);
            collatorlib::asort($modnames[1]);
        }
    }
    return $modnames[(int) $plural];
}