当前位置: 首页>>代码示例>>PHP>>正文


PHP get_roles_with_capability函数代码示例

本文整理汇总了PHP中get_roles_with_capability函数的典型用法代码示例。如果您正苦于以下问题:PHP get_roles_with_capability函数的具体用法?PHP get_roles_with_capability怎么用?PHP get_roles_with_capability使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了get_roles_with_capability函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: xmldb_forum_upgrade

function xmldb_forum_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    /// And upgrade begins here. For each one, you'll need one
    /// block of code similar to the next one. Please, delete
    /// this comment lines once this file start handling proper
    /// upgrade code.
    /// if ($result && $oldversion < YYYYMMDD00) { //New version in version.php
    ///     $result = result of "/lib/ddllib.php" function calls
    /// }
    if ($result && $oldversion < 2007101000) {
        /// Define field timemodified to be added to forum_queue
        $table = new XMLDBTable('forum_queue');
        $field = new XMLDBField('timemodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'postid');
        /// Launch add field timemodified
        $result = $result && add_field($table, $field);
    }
    //===== 1.9.0 upgrade line ======//
    if ($result and $oldversion < 2007101511) {
        notify('Processing forum grades, this may take a while if there are many forums...', 'notifysuccess');
        //MDL-13866 - send forum ratins to gradebook again
        require_once $CFG->dirroot . '/mod/forum/lib.php';
        // too much debug output
        $db->debug = false;
        forum_update_grades();
        $db->debug = true;
    }
    if ($result && $oldversion < 2007101512) {
        /// Cleanup the forum subscriptions
        notify('Removing stale forum subscriptions', 'notifysuccess');
        $roles = get_roles_with_capability('moodle/course:view', CAP_ALLOW);
        $roles = array_keys($roles);
        $roles = implode(',', $roles);
        $sql = "SELECT fs.userid, f.id AS forumid\n                  FROM {$CFG->prefix}forum f\n                       JOIN {$CFG->prefix}course c                 ON c.id = f.course\n                       JOIN {$CFG->prefix}context ctx              ON (ctx.instanceid = c.id AND ctx.contextlevel = " . CONTEXT_COURSE . ")\n                       JOIN {$CFG->prefix}forum_subscriptions fs   ON fs.forum = f.id\n                       LEFT JOIN {$CFG->prefix}role_assignments ra ON (ra.contextid = ctx.id AND ra.userid = fs.userid AND ra.roleid IN ({$roles}))\n                 WHERE ra.id IS NULL";
        if ($rs = get_recordset_sql($sql)) {
            $db->debug = false;
            while ($remove = rs_fetch_next_record($rs)) {
                delete_records('forum_subscriptions', 'userid', $remove->userid, 'forum', $remove->forumid);
                echo '.';
            }
            $db->debug = true;
            rs_close($rs);
        }
    }
    if ($result && $oldversion < 2007101513) {
        delete_records('forum_ratings', 'post', 0);
        /// Clean existing wrong rates. MDL-18227
    }
    return $result;
}
开发者ID:nadavkav,项目名称:MoodleTAO,代码行数:52,代码来源:upgrade.php

示例2: get_options

 /**
  * Add appropriate new criteria options to the form
  *
  */
 public function get_options(&$mform)
 {
     global $PAGE;
     $options = '';
     $none = true;
     $roles = get_roles_with_capability('moodle/badges:awardbadge', CAP_ALLOW, $PAGE->context);
     $roleids = array_map(create_function('$o', 'return $o->id;'), $roles);
     $existing = array();
     $missing = array();
     if ($this->id !== 0) {
         $existing = array_keys($this->params);
         $missing = array_diff($existing, $roleids);
     }
     if (!empty($missing)) {
         $mform->addElement('header', 'category_errors', get_string('criterror', 'badges'));
         $mform->addHelpButton('category_errors', 'criterror', 'badges');
         foreach ($missing as $m) {
             $this->config_options($mform, array('id' => $m, 'checked' => true, 'name' => get_string('error:nosuchrole', 'badges'), 'error' => true));
             $none = false;
         }
     }
     if (!empty($roleids)) {
         $mform->addElement('header', 'first_header', $this->get_title());
         $mform->addHelpButton('first_header', 'criteria_' . $this->criteriatype, 'badges');
         foreach ($roleids as $rid) {
             $checked = false;
             if (in_array($rid, $existing)) {
                 $checked = true;
             }
             $this->config_options($mform, array('id' => $rid, 'checked' => $checked, 'name' => self::get_role_name($rid), 'error' => false));
             $none = false;
         }
     }
     // Add aggregation.
     if (!$none) {
         $mform->addElement('header', 'aggregation', get_string('method', 'badges'));
         $agg = array();
         $agg[] =& $mform->createElement('radio', 'agg', '', get_string('allmethodmanual', 'badges'), 1);
         $agg[] =& $mform->createElement('static', 'none_break', null, '<br/>');
         $agg[] =& $mform->createElement('radio', 'agg', '', get_string('anymethodmanual', 'badges'), 2);
         $mform->addGroup($agg, 'methodgr', '', array(' '), false);
         if ($this->id !== 0) {
             $mform->setDefault('agg', $this->method);
         } else {
             $mform->setDefault('agg', BADGE_CRITERIA_AGGREGATION_ANY);
         }
     }
     return array($none, get_string('noparamstoadd', 'badges'));
 }
开发者ID:abhilash1994,项目名称:moodle,代码行数:53,代码来源:award_criteria_manual.php

示例3: xmldb_glossary_upgrade

function xmldb_glossary_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    /// And upgrade begins here. For each one, you'll need one
    /// block of code similar to the next one. Please, delete
    /// this comment lines once this file start handling proper
    /// upgrade code.
    /// if ($result && $oldversion < YYYYMMDD00) { //New version in version.php
    ///     $result = result of "/lib/ddllib.php" function calls
    /// }
    if ($result && $oldversion < 2006111400) {
        /// MDL-10475, set override for legacy:student before dropping studentcanpost
        /// if the glossary disables student postings
        if ($glossaries = get_records('glossary', 'studentcanpost', '0')) {
            foreach ($glossaries as $glossary) {
                if ($cm = get_coursemodule_from_instance('glossary', $glossary->id)) {
                    // add student override in this instance
                    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
                    // find all roles with legacy:student
                    if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
                        foreach ($studentroles as $studentrole) {
                            assign_capability('mod/glossary:write', CAP_PREVENT, $studentrole->id, $context->id);
                        }
                    }
                }
            }
        }
        /// Define field studentcanpost to be dropped from glossary
        $table = new XMLDBTable('glossary');
        $field = new XMLDBField('studentcanpost');
        /// Launch drop field studentcanpost
        $result = $result && drop_field($table, $field);
    }
    if ($result && $oldversion < 2007072200) {
        require_once $CFG->dirroot . '/mod/glossary/lib.php';
        // too much debug output
        $db->debug = false;
        glossary_update_grades();
        $db->debug = true;
    }
    //===== 1.9.0 upgrade line ======//
    return $result;
}
开发者ID:JackCanada,项目名称:moodle-hacks,代码行数:44,代码来源:upgrade.php

示例4: isteacherinanycourse

/**
 * Determines if a user is a teacher in any course, or an admin
 *
 * @global object
 * @global object
 * @global object
 * @uses CAP_ALLOW
 * @uses CONTEXT_SYSTEM
 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
 * @param bool $includeadmin Include anyone wo is an admin as well
 * @return bool
 */
function isteacherinanycourse($userid = 0, $includeadmin = true)
{
    global $USER, $CFG, $DB;
    if (!$userid) {
        if (empty($USER->id)) {
            return false;
        }
        $userid = $USER->id;
    }
    if (!$DB->record_exists('role_assignments', array('userid' => $userid))) {
        // Has no roles anywhere
        return false;
    }
    /// If this user is assigned as an editing teacher anywhere then return true
    if ($roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW)) {
        foreach ($roles as $role) {
            if ($DB->record_exists('role_assignments', array('roleid' => $role->id, 'userid' => $userid))) {
                return true;
            }
        }
    }
    /// If this user is assigned as a non-editing teacher anywhere then return true
    if ($roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW)) {
        foreach ($roles as $role) {
            if ($DB->record_exists('role_assignments', array('roleid' => $role->id, 'userid' => $userid))) {
                return true;
            }
        }
    }
    /// Include admins if required
    if ($includeadmin) {
        $context = get_context_instance(CONTEXT_SYSTEM);
        if (has_capability('moodle/legacy:admin', $context, $userid, false)) {
            return true;
        }
    }
    return false;
}
开发者ID:ajv,项目名称:Offline-Caching,代码行数:50,代码来源:deprecatedlib.php

示例5: role_unassigned

 public function role_unassigned($ra)
 {
     global $DB;
     if (!enrol_is_enabled('category')) {
         return true;
     }
     // only category level roles are interesting
     $parentcontext = get_context_instance_by_id($ra->contextid);
     if ($parentcontext->contextlevel != CONTEXT_COURSECAT) {
         return true;
     }
     // now this is going to be a bit slow, take all enrolments in child courses and verify each separately
     $syscontext = get_context_instance(CONTEXT_SYSTEM);
     if (!($roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext))) {
         return true;
     }
     $plugin = enrol_get_plugin('category');
     $sql = "SELECT e.*\n                  FROM {course} c\n                  JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :courselevel AND ctx.path LIKE :match)\n                  JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'category')\n                  JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)";
     $params = array('courselevel' => CONTEXT_COURSE, 'match' => $parentcontext->path . '/%', 'userid' => $ra->userid);
     $rs = $DB->get_recordset_sql($sql, $params);
     list($roleids, $params) = $DB->get_in_or_equal(array_keys($roles), SQL_PARAMS_NAMED, 'r');
     $params['userid'] = $ra->userid;
     foreach ($rs as $instance) {
         $coursecontext = get_context_instance(CONTEXT_COURSE, $instance->courseid);
         $contextids = get_parent_contexts($coursecontext);
         array_pop($contextids);
         // remove system context, we are interested in categories only
         list($contextids, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'c');
         $params = array_merge($params, $contextparams);
         $sql = "SELECT ra.id\n                      FROM {role_assignments} ra\n                     WHERE ra.userid = :userid AND ra.contextid {$contextids} AND ra.roleid {$roleids}";
         if (!$DB->record_exists_sql($sql, $params)) {
             // user does not have any interesting role in any parent context, let's unenrol
             $plugin->unenrol_user($instance, $ra->userid);
         }
     }
     $rs->close();
     return true;
 }
开发者ID:raymondAntonio,项目名称:moodle,代码行数:38,代码来源:locallib.php

示例6: require_capability

    require_capability('moodle/course:viewparticipants', $context);
} else {
    require_capability('moodle/site:viewparticipants', $systemcontext);
    // override the default on frontpage
    $roleid = optional_param('roleid', -1, PARAM_INT);
}
/// front page course is different
$rolenames = array();
$avoidroles = array();
if ($roles = get_roles_used_in_context($context, true)) {
    // We should ONLY allow roles with moodle/course:view because otherwise we get little niggly issues
    // like MDL-8093
    // We should further exclude "admin" users (those with "doanything" at site level) because
    // Otherwise they appear in every participant list
    $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
    $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext);
    if ($context->id == $frontpagectx->id) {
        //we want admins listed on frontpage too
        foreach ($doanythingroles as $dar) {
            $canviewroles[$dar->id] = $dar;
        }
        $doanythingroles = array();
    }
    foreach ($roles as $role) {
        if (!isset($canviewroles[$role->id])) {
            // Avoid this role (eg course creator)
            $avoidroles[] = $role->id;
            unset($roles[$role->id]);
            continue;
        }
        if (isset($doanythingroles[$role->id])) {
开发者ID:nicolasconnault,项目名称:moodle2.0,代码行数:31,代码来源:index.php

示例7: array

                    echo '<td><input type="checkbox"   name="check[]" class="check" value="' . $stu->id . '" /></td>';
            } else
                echo '<td><input type="checkbox"   name="check[]" class="check" value="' . $stu->id . '" /></td>';
            $studentservice_id = $DB->get_record('local_userdata', array('userid' => $stu->id));
            echo '<td>' . $studentservice_id->serviceid . '</td>';
            echo '<td>' . $stu->firstname . ' ' . $stu->lastname . '</td>';

            echo '<td>' . $stu->year . '</td>';
            echo'</tr>';
        }
        echo '</tbody>';
        echo '</table>';

        /* ---after select asignee role only...another dropdwon(filter is will be enabled)--- */
        $mentorlevel = "local/clclasses:approvemystudentclclasses";
        $roleid = get_roles_with_capability($mentorlevel, $permissions = NULL, $context = '');
        if (empty($roleid)) {
            $e = get_string('assigncap', 'local_assignmentor');
            throw new Exception($e);
        }
        foreach ($roleid as $roles) {
            if ($roles->shortname == 'mentor')
                $assignee_roleid = $roles->id;
        }

        $out = array();
        $out[0] = get_string('assignadvisor', 'local_assignmentor');
        if($assignee_roleid){
        $mentor_parentlist = $DB->get_records_sql("select u.id,u.firstname from {$CFG->prefix}local_school_permissions AS per
			JOIN {$CFG->prefix}user AS u ON u.id=per.userid	 where u.deleted<>1 and u.suspended<>1 and per.schoolid=$sid and per.roleid=$assignee_roleid ");
        
开发者ID:anilch,项目名称:Personel,代码行数:30,代码来源:assign_mentor.php

示例8: main_upgrade


//.........这里部分代码省略.........
        table_column('user', '', 'ajax', 'integer', '1', 'unsigned', '1', 'not null', 'htmleditor');
    }
    if ($oldversion < 2006082900) {
        execute_sql("DROP TABLE {$CFG->prefix}sessions", true);
        execute_sql("\n            CREATE TABLE {$CFG->prefix}sessions2 (\n                sesskey VARCHAR(64) NOT NULL default '',\n                expiry DATETIME NOT NULL,\n                expireref VARCHAR(250),\n                created DATETIME NOT NULL,\n                modified DATETIME NOT NULL,\n                sessdata TEXT,\n                CONSTRAINT  PRIMARY KEY (sesskey)\n            ) COMMENT='Optional database session storage in new format, not used by default';", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp_ix ON {$CFG->prefix}sessions2 (expiry);", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp2_ix ON {$CFG->prefix}sessions2 (expireref);", true);
    }
    if ($oldversion < 2006083001) {
        table_column('sessions2', 'sessdata', 'sessdata', 'LONGTEXT', '', '', '', '', '');
    }
    if ($oldversion < 2006083002) {
        table_column('capabilities', '', 'riskbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006083100) {
        execute_sql("ALTER TABLE {$CFG->prefix}course CHANGE modinfo modinfo longtext NULL AFTER showgrades");
    }
    if ($oldversion < 2006083101) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_categories CHANGE description description text NULL AFTER name");
    }
    if ($oldversion < 2006083102) {
        execute_sql("ALTER TABLE {$CFG->prefix}user CHANGE description description text NULL AFTER url");
    }
    if ($oldversion < 2006090200) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections CHANGE summary summary text NULL AFTER section");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections CHANGE sequence sequence text NULL AFTER section");
    }
    // table to keep track of course page access times, used in online participants block, and participants list
    if ($oldversion < 2006091200) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_lastaccess ( \n                    `id` int(10) unsigned NOT NULL auto_increment, \n                    `userid` int(10) unsigned NOT NULL default '0',\n                    `courseid` int(10) unsigned NOT NULL default '0', \n                    `timeaccess` int(10) unsigned NOT NULL default '0', \n                    KEY `userid` (`userid`),\n                    KEY `courseid` (`courseid`),\n                    UNIQUE KEY `userid-courseid` (`userid`, `courseid`),\n                    PRIMARY KEY (`id`) \n                    )TYPE=MYISAM COMMENT ='time user last accessed any page in a course';", true);
    }
    if ($oldversion < 2006091212) {
        // Reload the guest roles completely with new defaults
        if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
            delete_records('capabilities');
            $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
            foreach ($guestroles as $guestrole) {
                delete_records('role_capabilities', 'roleid', $guestrole->id);
                assign_capability('moodle/legacy:guest', CAP_ALLOW, $guestrole->id, $sitecontext->id);
            }
        }
    }
    if ($oldversion < 2006091700) {
        table_column('course', '', 'defaultrole', 'integer', '10', 'unsigned', '0', 'not null');
    }
    if ($oldversion < 2006091800) {
        delete_records('config', 'name', 'showsiteparticipantslist');
        delete_records('config', 'name', 'requestedteachername');
        delete_records('config', 'name', 'requestedteachersname');
        delete_records('config', 'name', 'requestedstudentname');
        delete_records('config', 'name', 'requestedstudentsname');
    }
    if ($oldversion < 2006091901) {
        if ($roles = get_records('role')) {
            $first = array_shift($roles);
            if (!empty($first->shortname)) {
                // shortnames already exist
            } else {
                table_column('role', '', 'shortname', 'varchar', '100', '', '', 'not null', 'name');
                $legacy_names = array('admin', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest');
                foreach ($legacy_names as $name) {
                    if ($roles = get_roles_with_capability('moodle/legacy:' . $name, CAP_ALLOW)) {
                        $i = '';
                        foreach ($roles as $role) {
                            if (empty($role->shortname)) {
                                $updated = new object();
开发者ID:veritech,项目名称:pare-project,代码行数:67,代码来源:mysql.php

示例9: display


//.........这里部分代码省略.........
                                         $attempt = $quba->get_question_attempt($slot);
                                         $order = $slotquestion->get_order($attempt);
                                         // Order of the answers.
                                         $tempstr = ",";
                                         $letters = array();
                                         $counter = 0;
                                         foreach ($order as $key => $answerid) {
                                             $fraction = $DB->get_field('question_answers', 'fraction', array('id' => $answerid));
                                             if ($fraction > 0) {
                                                 $letters[] = $answerletters[$counter];
                                             }
                                             $counter++;
                                         }
                                         if (empty($letters)) {
                                             $tempstr .= '99';
                                         } else {
                                             $tempstr .= implode('/', $letters);
                                         }
                                         echo $tempstr;
                                     }
                                 }
                                 echo "\n";
                             }
                         }
                     }
                 }
             }
         }
     }
     $coursecontext = context_course::instance($course->id);
     $contextids = $coursecontext->get_parent_context_ids(true);
     // Construct the SQL
     // First get roleids for students from leagcy.
     if (!($roles = get_roles_with_capability('mod/offlinequiz:attempt', CAP_ALLOW, $systemcontext))) {
         error("No roles with capability 'moodle/offlinequiz:attempt' defined in system context");
     }
     $roleids = array();
     foreach ($roles as $role) {
         $roleids[] = $role->id;
     }
     $rolelist = implode(',', $roleids);
     $select = "SELECT " . $DB->sql_concat('u.id', "'#'", "COALESCE(qa.usageid, 0)") . " AS uniqueid,\n        qa.id AS resultid, u.id, qa.usageid, qa.offlinegroupid, qa.status,\n        u.id AS userid, u.firstname, u.lastname,\n        u.alternatename, u.middlename, u.firstnamephonetic, u.lastnamephonetic,\n        u.picture, u." . $offlinequizconfig->ID_field . ",\n        qa.sumgrades, qa.timefinish, qa.timestart, qa.timefinish - qa.timestart AS duration ";
     $result = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
     list($contexttest, $cparams) = $result;
     list($roletest, $rparams) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED, 'role');
     $from = "FROM {user} u\n                  JOIN {role_assignments} ra ON ra.userid = u.id\n             LEFT JOIN {offlinequiz_results} qa ON u.id = qa.userid AND qa.offlinequizid = :offlinequizid\n             ";
     $where = " WHERE ra.contextid {$contexttest} AND ra.roleid {$roletest} ";
     $params = array('offlinequizid' => $offlinequiz->id);
     $params = array_merge($params, $cparams, $rparams);
     if ($groupid) {
         $from .= " JOIN {groups_members} gm ON gm.userid = u.id ";
         $where .= " AND gm.groupid = :groupid ";
         $params['groupid'] = $groupid;
     }
     if (empty($noresults)) {
         $where = $where . " AND qa.userid IS NOT NULL\n                                AND qa.status = 'complete'";
         // Show ONLY students with results.
     } else {
         if ($noresults == 1) {
             // The value noresults = 1 means only no results, so make the left join ask for only records
             // where the right is null (no results).
             $where .= ' AND qa.userid IS NULL';
             // Show ONLY students without results.
         } else {
             if ($noresults == 3) {
                 // We want all results, also the partial ones.
开发者ID:frankkoch,项目名称:moodle-mod_offlinequiz,代码行数:67,代码来源:report.php

示例10: groups_get_potential_members

/**
 * Gets potential group members for grouping
 * @param int $courseid The id of the course
 * @param int $roleid The role to select users from
 * @param string $orderby The colum to sort users by
 * @return array An array of the users
 */
function groups_get_potential_members($courseid, $roleid = null, $orderby = 'lastname,firstname')
{
    global $CFG;
    $context = get_context_instance(CONTEXT_COURSE, $courseid);
    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    $rolenames = array();
    $avoidroles = array();
    if ($roles = get_roles_used_in_context($context, true)) {
        $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
        $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
        foreach ($roles as $role) {
            if (!isset($canviewroles[$role->id])) {
                // Avoid this role (eg course creator)
                $avoidroles[] = $role->id;
                unset($roles[$role->id]);
                continue;
            }
            if (isset($doanythingroles[$role->id])) {
                // Avoid this role (ie admin)
                $avoidroles[] = $role->id;
                unset($roles[$role->id]);
                continue;
            }
            $rolenames[$role->id] = strip_tags(role_get_name($role, $context));
            // Used in menus etc later on
        }
    }
    $select = 'SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber ';
    $from = "FROM {$CFG->prefix}user u INNER JOIN\n               {$CFG->prefix}role_assignments r on u.id=r.userid ";
    if ($avoidroles) {
        $adminroles = 'AND r.roleid NOT IN (';
        $adminroles .= implode(',', $avoidroles);
        $adminroles .= ')';
    } else {
        $adminroles = '';
    }
    // we are looking for all users with this role assigned in this context or higher
    if ($usercontexts = get_parent_contexts($context)) {
        $listofcontexts = '(' . implode(',', $usercontexts) . ')';
    } else {
        $listofcontexts = '(' . $sitecontext->id . ')';
        // must be site
    }
    if ($roleid) {
        $selectrole = " AND r.roleid = {$roleid} ";
    } else {
        $selectrole = " ";
    }
    $where = "WHERE (r.contextid = {$context->id} OR r.contextid in {$listofcontexts})\n                     AND u.deleted = 0 {$selectrole}\n                     AND u.username != 'guest'\n                     {$adminroles} ";
    $order = "ORDER BY {$orderby} ";
    return get_records_sql($select . $from . $where . $order);
}
开发者ID:nadavkav,项目名称:MoodleTAO,代码行数:59,代码来源:lib.php

示例11: capabilities_cleanup

/**
 * Deletes cached capabilities that are no longer needed by the component.
 * Also unassigns these capabilities from any roles that have them.
 *
 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
 * @param array $newcapdef array of the new capability definitions that will be
 *                     compared with the cached capabilities
 * @return int number of deprecated capabilities that have been removed
 */
function capabilities_cleanup($component, $newcapdef = null)
{
    global $DB;
    $removedcount = 0;
    if ($cachedcaps = get_cached_capabilities($component)) {
        foreach ($cachedcaps as $cachedcap) {
            if (empty($newcapdef) || array_key_exists($cachedcap->name, $newcapdef) === false) {
                // Remove from capabilities cache.
                $DB->delete_records('capabilities', array('name' => $cachedcap->name));
                $removedcount++;
                // Delete from roles.
                if ($roles = get_roles_with_capability($cachedcap->name)) {
                    foreach ($roles as $role) {
                        if (!unassign_capability($cachedcap->name, $role->id)) {
                            print_error('cannotunassigncap', 'error', '', (object) array('cap' => $cachedcap->name, 'role' => $role->name));
                        }
                    }
                }
            }
            // End if.
        }
    }
    return $removedcount;
}
开发者ID:rolandovanegas,项目名称:moodle,代码行数:33,代码来源:accesslib.php

示例12: get_default_course_role

/**
 *  Returns a role object that is the default role for new enrolments
 *  in a given course
 *
 *  @param object $course
 *  @return object $role
 */
function get_default_course_role($course)
{
    global $DB, $CFG;
    /// First let's take the default role the course may have
    if (!empty($course->defaultrole)) {
        if ($role = $DB->get_record('role', array('id' => $course->defaultrole))) {
            return $role;
        }
    }
    /// Otherwise the site setting should tell us
    if ($CFG->defaultcourseroleid) {
        if ($role = $DB->get_record('role', array('id' => $CFG->defaultcourseroleid))) {
            return $role;
        }
    }
    /// It's unlikely we'll get here, but just in case, try and find a student role
    if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
        return array_shift($studentroles);
        /// Take the first one
    }
    return NULL;
}
开发者ID:nicolasconnault,项目名称:moodle2.0,代码行数:29,代码来源:accesslib.php

示例13: offlinequiz_create_pdf_participants

/**
 * Creates a PDF document for a list of participants
 *
 * @param unknown_type $offlinequiz
 * @param unknown_type $courseid
 * @param unknown_type $list
 * @param unknown_type $context
 * @return boolean|stored_file
 */
function offlinequiz_create_pdf_participants($offlinequiz, $courseid, $list, $context)
{
    global $CFG, $DB;
    $coursecontext = context_course::instance($courseid);
    // Course context.
    $systemcontext = context_system::instance();
    $offlinequizconfig = get_config('offlinequiz');
    $listname = $list->name;
    // First get roleids for students.
    if (!($roles = get_roles_with_capability('mod/offlinequiz:attempt', CAP_ALLOW, $systemcontext))) {
        print_error("No roles with capability 'mod/offlinequiz:attempt' defined in system context");
    }
    $roleids = array();
    foreach ($roles as $role) {
        $roleids[] = $role->id;
    }
    list($csql, $cparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
    list($rsql, $rparams) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED, 'role');
    $params = array_merge($cparams, $rparams);
    $sql = "SELECT DISTINCT u.id, u." . $offlinequizconfig->ID_field . ", u.firstname, u.lastname\n              FROM {user} u,\n                   {offlinequiz_participants} p,\n                   {role_assignments} ra,\n                   {offlinequiz_p_lists} pl\n             WHERE ra.userid = u.id\n               AND p.listid = :listid\n               AND p.listid = pl.id\n               AND pl.offlinequizid = :offlinequizid\n               AND p.userid = u.id\n               AND ra.roleid {$rsql} AND ra.contextid {$csql}\n          ORDER BY u.lastname, u.firstname";
    $params['offlinequizid'] = $offlinequiz->id;
    $params['listid'] = $list->id;
    $participants = $DB->get_records_sql($sql, $params);
    if (empty($participants)) {
        return false;
    }
    $pdf = new offlinequiz_participants_pdf('P', 'mm', 'A4');
    $pdf->listno = $list->number;
    $title = offlinequiz_str_html_pdf($offlinequiz->name);
    // Add the list name to the title.
    $title .= ', ' . offlinequiz_str_html_pdf($listname);
    $pdf->set_title($title);
    $pdf->SetMargins(15, 25, 15);
    $pdf->SetAutoPageBreak(true, 20);
    $pdf->AddPage();
    $pdf->Ln(9);
    $position = 1;
    $pdf->SetFont('FreeSans', '', 10);
    foreach ($participants as $participant) {
        $pdf->Cell(9, 3.5, "{$position}. ", 0, 0, 'R');
        $pdf->Cell(1, 3.5, '', 0, 0, 'C');
        $x = $pdf->GetX();
        $y = $pdf->GetY();
        $pdf->Rect($x, $y + 0.6, 3.5, 3.5);
        $pdf->Cell(3, 3.5, '', 0, 0, 'C');
        $pdf->Cell(6, 3.5, '', 0, 0, 'C');
        $userkey = substr($participant->{$offlinequizconfig->ID_field}, strlen($offlinequizconfig->ID_prefix), $offlinequizconfig->ID_digits);
        $pdf->Cell(13, 3.5, $userkey, 0, 0, 'R');
        $pdf->Cell(12, 3.5, '', 0, 0, 'L');
        if ($pdf->GetStringWidth($participant->firstname) > 40) {
            $participant->firstname = substr($participant->firstname, 0, 20);
        }
        if ($pdf->GetStringWidth($participant->lastname) > 55) {
            $participant->lastname = substr($participant->lastname, 0, 25);
        }
        $pdf->Cell(55, 3.5, $participant->lastname, 0, 0, 'L');
        $pdf->Cell(40, 3.5, $participant->firstname, 0, 0, 'L');
        $pdf->Cell(10, 3.5, '', 0, 1, 'R');
        // Print barcode.
        $value = substr('000000000000000000000000' . base_convert($participant->id, 10, 2), -25);
        $y = $pdf->GetY() - 3.5;
        $x = 170;
        $pdf->Rect($x, $y, 0.2, 3.5, 'F');
        $pdf->Rect($x, $y, 0.7, 0.2, 'F');
        $pdf->Rect($x, $y + 3.5, 0.7, 0.2, 'F');
        $x += 0.7;
        for ($i = 0; $i < 25; $i++) {
            if ($value[$i] == '1') {
                $pdf->Rect($x, $y, 0.7, 3.5, 'F');
                $pdf->Rect($x, $y, 1.2, 0.2, 'F');
                $pdf->Rect($x, $y + 3.5, 1.2, 0.2, 'F');
                $x += 1.2;
            } else {
                $pdf->Rect($x, $y, 0.2, 3.5, 'F');
                $pdf->Rect($x, $y, 0.7, 0.2, 'F');
                $pdf->Rect($x, $y + 3.5, 0.7, 0.2, 'F');
                $x += 0.7;
            }
        }
        $pdf->Rect($x, $y, 0.2, 3.7, 'F');
        $pdf->Rect(15, $pdf->GetY() + 1, 175, 0.2, 'F');
        if ($position % NUMBERS_PER_PAGE != 0) {
            $pdf->Ln(3.6);
        } else {
            $pdf->AddPage();
            $pdf->Ln(9);
        }
        $position++;
    }
    $fs = get_file_storage();
    // Prepare file record object.
//.........这里部分代码省略.........
开发者ID:frankkoch,项目名称:moodle-mod_offlinequiz,代码行数:101,代码来源:pdflib.php

示例14: data_restore_mods

function data_restore_mods($mod, $restore)
{
    global $CFG;
    $status = true;
    $data = backup_getid($restore->backup_unique_code, $mod->modtype, $mod->id);
    if ($data) {
        //Now get completed xmlized object
        $info = $data->info;
        // if necessary, write to restorelog and adjust date/time fields
        if ($restore->course_startdateoffset) {
            restore_log_date_changes('Database', $restore, $info['MOD']['#'], array('TIMEAVAILABLEFROM', 'TIMEAVAILABLETO', 'TIMEVIEWFROM', 'TIMEVIEWTO'));
        }
        //traverse_xmlize($info);                                                                     //Debug
        //print_object ($GLOBALS['traverse_array']);                                                  //Debug
        //$GLOBALS['traverse_array']="";                                                              //Debug
        $database->course = $restore->course_id;
        $database->name = backup_todb($info['MOD']['#']['NAME']['0']['#']);
        $database->intro = backup_todb($info['MOD']['#']['INTRO']['0']['#']);
        // Only relevant for restoring backups from 1.6 in a 1.7 install.
        if (isset($info['MOD']['#']['RATINGS']['0']['#'])) {
            $database->ratings = backup_todb($info['MOD']['#']['RATINGS']['0']['#']);
        }
        $database->comments = backup_todb($info['MOD']['#']['COMMENTS']['0']['#']);
        $database->timeavailablefrom = backup_todb($info['MOD']['#']['TIMEAVAILABLEFROM']['0']['#']);
        $database->timeavailableto = backup_todb($info['MOD']['#']['TIMEAVAILABLETO']['0']['#']);
        $database->timeviewfrom = backup_todb($info['MOD']['#']['TIMEVIEWFROM']['0']['#']);
        $database->timeviewto = backup_todb($info['MOD']['#']['TIMEVIEWTO']['0']['#']);
        // Only relevant for restoring backups from 1.6 in a 1.7 install.
        if (isset($info['MOD']['#']['PARTICIPANTS']['0']['#'])) {
            $database->participants = backup_todb($info['MOD']['#']['PARTICIPANTS']['0']['#']);
        }
        $database->requiredentries = backup_todb($info['MOD']['#']['REQUIREDENTRIES']['0']['#']);
        $database->requiredentriestoview = backup_todb($info['MOD']['#']['REQUIREDENTRIESTOVIEW']['0']['#']);
        $database->maxentries = backup_todb($info['MOD']['#']['MAXENTRIES']['0']['#']);
        $database->rssarticles = backup_todb($info['MOD']['#']['RSSARTICLES']['0']['#']);
        $database->singletemplate = backup_todb($info['MOD']['#']['SINGLETEMPLATE']['0']['#']);
        $database->listtemplate = backup_todb($info['MOD']['#']['LISTTEMPLATE']['0']['#']);
        $database->listtemplateheader = backup_todb($info['MOD']['#']['LISTTEMPLATEHEADER']['0']['#']);
        $database->listtemplatefooter = backup_todb($info['MOD']['#']['LISTTEMPLATEFOOTER']['0']['#']);
        $database->addtemplate = backup_todb($info['MOD']['#']['ADDTEMPLATE']['0']['#']);
        $database->rsstemplate = backup_todb($info['MOD']['#']['RSSTEMPLATE']['0']['#']);
        $database->rsstitletemplate = backup_todb($info['MOD']['#']['RSSTITLETEMPLATE']['0']['#']);
        $database->csstemplate = backup_todb($info['MOD']['#']['CSSTEMPLATE']['0']['#']);
        $database->jstemplate = backup_todb($info['MOD']['#']['JSTEMPLATE']['0']['#']);
        $database->asearchtemplate = backup_todb($info['MOD']['#']['ASEARCHTEMPLATE']['0']['#']);
        $database->approval = backup_todb($info['MOD']['#']['APPROVAL']['0']['#']);
        $database->scale = backup_todb($info['MOD']['#']['SCALE']['0']['#']);
        $database->assessed = backup_todb($info['MOD']['#']['ASSESSED']['0']['#']);
        // Only relevant for restoring backups from 1.6 in a 1.7 install.
        if (isset($info['MOD']['#']['ASSESSPUBLIC']['0']['#'])) {
            $database->assesspublic = backup_todb($info['MOD']['#']['ASSESSPUBLIC']['0']['#']);
        }
        $database->defaultsort = backup_todb($info['MOD']['#']['DEFAULTSORT']['0']['#']);
        $database->defaultsortdir = backup_todb($info['MOD']['#']['DEFAULTSORTDIR']['0']['#']);
        $database->editany = backup_todb($info['MOD']['#']['EDITANY']['0']['#']);
        $database->notification = backup_todb($info['MOD']['#']['NOTIFICATION']['0']['#']);
        // We have to recode the scale field if it's <0 (positive is a grade, not a scale)
        if ($database->scale < 0) {
            $scale = backup_getid($restore->backup_unique_code, 'scale', abs($database->scale));
            if ($scale) {
                $database->scale = -$scale->new_id;
            }
        }
        $newid = insert_record('data', $database);
        //Do some output
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("modulename", "data") . " \"" . format_string(stripslashes($database->name), true) . "\"</li>";
        }
        if ($newid) {
            //We have the newid, update backup_ids
            backup_putid($restore->backup_unique_code, $mod->modtype, $mod->id, $newid);
            //Now check if want to restore user data and do it.
            if (function_exists('restore_userdata_selected')) {
                // Moodle 1.6
                $restore_userdata_selected = restore_userdata_selected($restore, 'data', $mod->id);
            } else {
                // Moodle 1.5
                $restore_userdata_selected = $restore->mods['data']->userinfo;
            }
            global $fieldids;
            //Restore data_fields first!!! need to hold an array of [oldid]=>newid due to double dependencies
            $status = $status and data_fields_restore_mods($mod->id, $newid, $info, $restore);
            // now use the new field in the defaultsort
            $newdefaultsort = empty($fieldids[$database->defaultsort]) ? 0 : $fieldids[$database->defaultsort];
            set_field('data', 'defaultsort', $newdefaultsort, 'id', $newid);
            if ($restore_userdata_selected) {
                $status = $status and data_records_restore_mods($mod->id, $newid, $info, $restore);
            }
            // If the backup contained $data->participants, $data->assesspublic
            // and $data->groupmode, we need to convert the data to use Roles.
            // It means the backup was made pre Moodle 1.7. We check the
            // backup_version to make sure.
            if (isset($database->participants) && isset($database->assesspublic)) {
                if (!($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW))) {
                    notice('Default teacher role was not found. Roles and permissions ' . 'for your database modules will have to be manually set.');
                }
                if (!($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW))) {
                    notice('Default student role was not found. Roles and permissions ' . 'for all your database modules will have to be manually set.');
                }
                if (!($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW))) {
//.........这里部分代码省略.........
开发者ID:JackCanada,项目名称:moodle-hacks,代码行数:101,代码来源:restorelib.php

示例15: test_get_roles_with_capability

 /**
  * Test role queries.
  */
 public function test_get_roles_with_capability()
 {
     global $DB;
     $this->resetAfterTest();
     $syscontext = context_system::instance();
     $frontcontext = context_course::instance(SITEID);
     $manager = $DB->get_record('role', array('shortname' => 'manager'), '*', MUST_EXIST);
     $teacher = $DB->get_record('role', array('shortname' => 'teacher'), '*', MUST_EXIST);
     $this->assertTrue($DB->record_exists('capabilities', array('name' => 'moodle/backup:backupcourse')));
     // Any capability is ok.
     $DB->delete_records('role_capabilities', array('capability' => 'moodle/backup:backupcourse'));
     $roles = get_roles_with_capability('moodle/backup:backupcourse');
     $this->assertEquals(array(), $roles);
     assign_capability('moodle/backup:backupcourse', CAP_ALLOW, $manager->id, $syscontext->id);
     assign_capability('moodle/backup:backupcourse', CAP_PROHIBIT, $manager->id, $frontcontext->id);
     assign_capability('moodle/backup:backupcourse', CAP_PREVENT, $teacher->id, $frontcontext->id);
     $roles = get_roles_with_capability('moodle/backup:backupcourse');
     $this->assertEquals(array($teacher->id, $manager->id), array_keys($roles), '', 0, 10, true);
     $roles = get_roles_with_capability('moodle/backup:backupcourse', CAP_ALLOW);
     $this->assertEquals(array($manager->id), array_keys($roles), '', 0, 10, true);
     $roles = get_roles_with_capability('moodle/backup:backupcourse', null, $syscontext);
     $this->assertEquals(array($manager->id), array_keys($roles), '', 0, 10, true);
 }
开发者ID:sumitnegi933,项目名称:Moodle_lms_New,代码行数:26,代码来源:accesslib_test.php


注:本文中的get_roles_with_capability函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。