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


PHP context_helper类代码示例

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


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

示例1: get_courses

    /**
     * Return all courses this rule applies to.
     *
     * @return array A list of courses.
     */
    public function get_courses()
    {
        global $CFG, $DB;
        if (isset($this->courses)) {
            return $this->courses;
        }
        require_once $CFG->libdir . '/coursecatlib.php';
        $coursecat = \coursecat::get($this->id);
        $courselist = $coursecat->get_courses(array('recursive' => true, 'idonly' => true));
        // Generate the SQL.
        list($sql, $params) = $DB->get_in_or_equal($courselist);
        $ctxlevel = \CONTEXT_COURSE;
        $preload = \context_helper::get_preload_record_columns_sql('ctx');
        $sql = <<<SQL
            SELECT c.*, {$preload}
            FROM {course} c
            INNER JOIN {context} ctx
                ON ctx.instanceid = c.id AND ctx.contextlevel = {$ctxlevel}
            WHERE c.id {$sql}
SQL;
        // Get the courses and preload contexts.
        $this->courses = $DB->get_records_sql($sql, $params);
        foreach ($this->courses as $course) {
            \context_helper::preload_from_record($course);
        }
        return $this->courses;
    }
开发者ID:unikent,项目名称:moodle-tool_cat,代码行数:32,代码来源:category.php

示例2: block_course_overview_get_child_shortnames

/**
 * Returns shortname of activities in course
 *
 * @param int $courseid id of course for which activity shortname is needed
 * @return string|bool list of child shortname
 */
function block_course_overview_get_child_shortnames($courseid)
{
    global $DB;
    $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
    $sql = "SELECT c.id, c.shortname, {$ctxselect}\n            FROM {enrol} e\n            JOIN {course} c ON (c.id = e.customint1)\n            JOIN {context} ctx ON (ctx.instanceid = e.customint1)\n            WHERE e.courseid = :courseid AND e.enrol = :method AND ctx.contextlevel = :contextlevel ORDER BY e.sortorder";
    $params = array('method' => 'meta', 'courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
    if ($results = $DB->get_records_sql($sql, $params)) {
        $shortnames = array();
        // Preload the context we will need it to format the category name shortly.
        foreach ($results as $res) {
            context_helper::preload_from_record($res);
            $context = context_course::instance($res->id);
            $shortnames[] = format_string($res->shortname, true, $context);
        }
        $total = count($shortnames);
        $suffix = '';
        if ($total > 10) {
            $shortnames = array_slice($shortnames, 0, 10);
            $diff = $total - count($shortnames);
            if ($diff > 1) {
                $suffix = get_string('shortnamesufixprural', 'block_course_overview', $diff);
            } else {
                $suffix = get_string('shortnamesufixsingular', 'block_course_overview', $diff);
            }
        }
        $shortnames = get_string('shortnameprefix', 'block_course_overview', implode('; ', $shortnames));
        $shortnames .= $suffix;
    }
    return isset($shortnames) ? $shortnames : false;
}
开发者ID:JP-Git,项目名称:moodle,代码行数:36,代码来源:locallib.php

示例3: definition

 function definition()
 {
     global $CFG, $DB;
     $mform = $this->_form;
     $course = $this->_customdata;
     $this->course = $course;
     $existing = $DB->get_records('enrol', array('enrol' => 'meta', 'courseid' => $course->id), '', 'customint1, id');
     // TODO: this has to be done via ajax or else it will fail very badly on large sites!
     $courses = array('' => get_string('choosedots'));
     list($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
     $sql = "SELECT c.id, c.fullname, c.shortname, c.visible {$select} FROM {course} c {$join} ORDER BY c.sortorder ASC";
     $rs = $DB->get_recordset_sql($sql);
     foreach ($rs as $c) {
         if ($c->id == SITEID or $c->id == $course->id or isset($existing[$c->id])) {
             continue;
         }
         context_helper::preload_from_record($c);
         $coursecontext = context_course::instance($c->id);
         if (!$c->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
             continue;
         }
         if (!has_capability('enrol/meta:selectaslinked', $coursecontext)) {
             continue;
         }
         $courses[$c->id] = $coursecontext->get_context_name(false);
     }
     $rs->close();
     $mform->addElement('header', 'general', get_string('pluginname', 'enrol_meta'));
     $mform->addElement('select', 'link', get_string('linkedcourse', 'enrol_meta'), $courses);
     $mform->addRule('link', get_string('required'), 'required', null, 'client');
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
     $this->add_action_buttons(true, get_string('addinstance', 'enrol'));
     $this->set_data(array('id' => $course->id));
 }
开发者ID:Burick,项目名称:moodle,代码行数:35,代码来源:addinstance_form.php

示例4: costcenter_custom_contexts_setup

    /**
     * Test case for custom context classes
     */
    public function costcenter_custom_contexts_setup() {
     
        global $CFG;
        static $customcontexts = array(
            27 => 'context_costcenter'
       
        );

        // save any existing custom contexts
        $existingcustomcontexts = get_config(null, 'custom_context_classes');

        set_config('custom_context_classes', serialize($customcontexts));
        initialise_cfg();
        context_helper::reset_levels();
        $alllevels = context_helper::get_all_levels();
        
      ///  $this->assertEquals($alllevels[11], 'context_costcenter');
        

        // clean-up & restore any custom contexts
        //set_config('custom_context_classes', ($existingcustomcontexts === false) ? null : $existingcustomcontexts);
       // initialise_cfg();
       // context_helper::reset_levels();
      //  $alllevels = context_helper::get_all_levels();
        
      //  print_object($alllevels);
    }
开发者ID:narasimhaeabyas,项目名称:tataaiapro,代码行数:30,代码来源:costcenter_contextlib.php

示例5: get_capabitity_optgroups

 protected function get_capabitity_optgroups()
 {
     if (!empty($this->_optGroups)) {
         // I have absolutely no idea why this is necessary, but it does seem to be.
         // Bloody formslib. Somehow it is calling the constructor twice.
         return array();
     }
     $optgroups = array();
     $capabilities = context_system::instance()->get_capabilities();
     $contextlevel = 0;
     $component = '';
     $currentgroup = array();
     $currentgroupname = '';
     foreach ($capabilities as $capability) {
         // Start a new optgroup if the componentname or context level has changed.
         if (component_level_changed($capability, $component, $contextlevel)) {
             if ($currentgroup) {
                 $optgroups[$currentgroupname] = $currentgroup;
             }
             $currentgroup = array();
             $currentgroupname = context_helper::get_level_name($capability->contextlevel) . ': ' . get_component_string($capability->component, $capability->contextlevel);
         }
         $contextlevel = $capability->contextlevel;
         $component = $capability->component;
         $a = new stdClass();
         $a->name = get_capability_string($capability->name);
         $a->capabilityname = $capability->name;
         $currentgroup[$capability->name] = get_string('capabilityandname', 'tool_editrolesbycap', $a);
     }
     // Remeber to add the currently open optgroup.
     if ($currentgroup) {
         $optgroups[$currentgroupname] = $currentgroup;
     }
     return $optgroups;
 }
开发者ID:Keneth1212,项目名称:moodle,代码行数:35,代码来源:capabilityformfield.php

示例6: execute

 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     // Context maintenance stuff.
     \context_helper::cleanup_instances();
     mtrace(' Cleaned up context instances');
     \context_helper::build_all_paths(false);
     // If you suspect that the context paths are somehow corrupt
     // replace the line below with: context_helper::build_all_paths(true).
 }
开发者ID:evltuma,项目名称:moodle,代码行数:13,代码来源:context_cleanup_task.php

示例7: definition

    public function definition()
    {
        global $CFG, $DB;
        $mform = $this->_form;
        $course = $this->_customdata['course'];
        $instance = $this->_customdata['instance'];
        $this->course = $course;
        $existing = array();
        if ($instance) {
            $existing = $DB->get_records('enrol_metaplus', array('enrolid' => $instance->id), '', 'courseid, id');
        }
        $courses = array();
        $select = context_helper::get_preload_record_columns_sql('ctx');
        $sql = <<<SQL
            SELECT c.id, c.fullname, c.shortname, c.visible, {$select}
            FROM {course} c
            LEFT JOIN {context} ctx
                ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)
SQL;
        $rs = $DB->get_recordset_sql($sql, array('contextlevel' => CONTEXT_COURSE));
        foreach ($rs as $c) {
            if ($c->id == SITEID || $c->id == $course->id) {
                continue;
            }
            context_helper::preload_from_record($c);
            $coursecontext = context_course::instance($c->id);
            if (!$c->visible && !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
                continue;
            }
            if (!has_capability('enrol/meta:selectaslinked', $coursecontext)) {
                continue;
            }
            $courses[$c->id] = $coursecontext->get_context_name(false);
        }
        $rs->close();
        $mform->addElement('header', 'general', get_string('pluginname', 'enrol_meta'));
        $mform->addElement('select', 'link', get_string('linkedcourse', 'enrol_metaplus'), $courses, array('multiple' => 'multiple', 'class' => 'chosen'));
        $mform->addRule('link', get_string('required'), 'required', null, 'server');
        // Add role sync list.
        $coursecontext = \context_course::instance($course->id);
        $roles = get_assignable_roles($coursecontext);
        $mform->addElement('select', 'roleexclusions', get_string('roleexclusions', 'enrol_metaplus'), $roles, array('multiple' => 'multiple'));
        $mform->addElement('hidden', 'id', null);
        $mform->setType('id', PARAM_INT);
        $mform->addElement('hidden', 'enrolid');
        $mform->setType('enrolid', PARAM_INT);
        $data = array('id' => $course->id);
        if ($instance) {
            $data['link'] = implode(',', array_keys($existing));
            $data['enrolid'] = $instance->id;
            $data['roleexclusions'] = $instance->customtext1;
            $this->add_action_buttons();
        } else {
            $this->add_add_buttons();
        }
        $this->set_data($data);
    }
开发者ID:unikent,项目名称:moodle-enrol_metaplus,代码行数:57,代码来源:addinstance_form.php

示例8: __construct

 public function __construct($context, $roleid)
 {
     $this->roleid = $roleid;
     parent::__construct($context, 'defineroletable', $roleid);
     $this->displaypermissions = $this->allpermissions;
     $this->strperms[$this->allpermissions[CAP_INHERIT]] = get_string('notset', 'core_role');
     $this->allcontextlevels = array();
     $levels = context_helper::get_all_levels();
     foreach ($levels as $level => $classname) {
         $this->allcontextlevels[$level] = context_helper::get_level_name($level);
     }
 }
开发者ID:Gavinthisisit,项目名称:Moodle,代码行数:12,代码来源:define_role_table_advanced.php

示例9: xmldb_local_elisprogram_install

/**
 * ELIS(TM): Enterprise Learning Intelligence Suite
 * Copyright (C) 2008-2013 Remote-Learner.net Inc (http://www.remote-learner.net)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    local_elisprogram
 * @author     Remote-Learner.net Inc
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @copyright  (C) 2008-2013 Remote Learner.net Inc http://www.remote-learner.net
 *
 */
function xmldb_local_elisprogram_install()
{
    global $CFG, $DB;
    $elisadminblockinstalled = file_exists($CFG->dirroot . '/local/elisprogram/lib/setup.php') && $DB->record_exists('block', array('name' => 'elisadmin'));
    if ($elisadminblockinstalled) {
        require_once $CFG->dirroot . '/blocks/elisadmin/lib.php';
    }
    require_once $CFG->dirroot . '/local/elisprogram/lib/lib.php';
    // Install custom context levels.
    \local_eliscore\context\helper::set_custom_levels(\local_elisprogram\context\contextinfo::get_contextinfo());
    \local_eliscore\context\helper::install_custom_levels();
    // Initialize custom context levels.
    context_helper::reset_levels();
    \local_eliscore\context\helper::reset_levels();
    \local_eliscore\context\helper::init_levels();
    // Migrate component.
    $migrator = new \local_elisprogram\install\migration\elis26();
    if ($migrator->old_component_installed() === true) {
        $migrator->migrate();
    }
    //make sure the site has exactly one curr admin block instance
    //that is viewable everywhere
    if ($elisadminblockinstalled) {
        block_elisadmin_create_instance();
    }
    // make sure that the manager role can be assigned to all PM context levels
    update_capabilities('local_elisprogram');
    // load context levels
    pm_ensure_role_assignable('manager');
    pm_ensure_role_assignable('curriculumadmin');
    // Migrate dataroot files
    pm_migrate_certificate_files();
    // These notifications are default-on.
    pm_set_config('notify_addedtowaitlist_user', 1);
    pm_set_config('notify_enroledfromwaitlist_user', 1);
    pm_set_config('notify_incompletecourse_user', 1);
    // Ensure ELIS scheduled tasks is initialized.
    require_once $CFG->dirroot . '/local/eliscore/lib/tasklib.php';
    elis_tasks_update_definition('local_elisprogram');
    // Remove some lingering subplugins that were renamed
    unset_all_config_for_plugin('usersetenrol_manual');
    unset_all_config_for_plugin('usersetenrol_moodle_profile');
}
开发者ID:jamesmcq,项目名称:elis,代码行数:66,代码来源:install.php

示例10: get_courses_with_competency_and_user

 /**
  * Return the courses where both competency and user are.
  *
  * A user is considered being in a course when they are enrolled, the enrolment is valid,
  * the enrolment instance is enabled, and the enrolment plugin is enabled..
  *
  * @param int $competencyid The competency ID.
  * @param int $userid The user ID.
  * @return array Indexed by course ID.
  */
 public static function get_courses_with_competency_and_user($competencyid, $userid)
 {
     global $CFG, $DB;
     if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
         return array();
     }
     $ctxfields = \context_helper::get_preload_record_columns_sql('ctx');
     list($plugins, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee');
     $params['competencyid'] = $competencyid;
     $params['userid'] = $userid;
     $params['enabled'] = ENROL_INSTANCE_ENABLED;
     $params['active'] = ENROL_USER_ACTIVE;
     $params['contextlevel'] = CONTEXT_COURSE;
     // Heavily based on enrol_get_shared_courses().
     $sql = "SELECT c.*, {$ctxfields}\n                  FROM {course} c\n                  JOIN {" . static::TABLE . "} cc\n                    ON cc.courseid = c.id\n                   AND cc.competencyid = :competencyid\n                  JOIN (\n                    SELECT DISTINCT c.id\n                      FROM {enrol} e\n                      JOIN {user_enrolments} ue\n                        ON ue.enrolid = e.id\n                       AND ue.status = :active\n                       AND ue.userid = :userid\n                      JOIN {course} c\n                        ON c.id = e.courseid\n                     WHERE e.status = :enabled\n                       AND e.enrol {$plugins}\n                  ) ec ON ec.id = c.id\n             LEFT JOIN {context} ctx\n                    ON ctx.instanceid = c.id\n                   AND ctx.contextlevel = :contextlevel\n              ORDER BY c.id";
     $courses = $DB->get_records_sql($sql, $params);
     array_map('context_helper::preload_from_record', $courses);
     return $courses;
 }
开发者ID:evltuma,项目名称:moodle,代码行数:29,代码来源:course_competency.php

示例11: get_context

    /**
     * Gets the internal context id from the context reference.
     *
     * The context reference changes depending on the context
     * level, it can be the system, a user, a category, a course or
     * a module.
     *
     * @throws Exception
     * @param string $levelname The context level string introduced by the test writer
     * @param string $contextref The context reference introduced by the test writer
     * @return context
     */
    protected function get_context($levelname, $contextref) {
        global $DB;

        // Getting context levels and names (we will be using the English ones as it is the test site language).
        $contextlevels = context_helper::get_all_levels();
        $contextnames = array();
        foreach ($contextlevels as $level => $classname) {
            $contextnames[context_helper::get_level_name($level)] = $level;
        }

        if (empty($contextnames[$levelname])) {
            throw new Exception('The specified "' . $levelname . '" context level does not exist');
        }
        $contextlevel = $contextnames[$levelname];

        // Return it, we don't need to look for other internal ids.
        if ($contextlevel == CONTEXT_SYSTEM) {
            return context_system::instance();
        }

        switch ($contextlevel) {

            case CONTEXT_USER:
                $instanceid = $DB->get_field('user', 'id', array('username' => $contextref));
                break;

            case CONTEXT_COURSECAT:
                $instanceid = $DB->get_field('course_categories', 'id', array('idnumber' => $contextref));
                break;

            case CONTEXT_COURSE:
                $instanceid = $DB->get_field('course', 'id', array('shortname' => $contextref));
                break;

            case CONTEXT_MODULE:
                $instanceid = $DB->get_field('course_modules', 'id', array('idnumber' => $contextref));
                break;

            default:
                break;
        }

        $contextclass = $contextlevels[$contextlevel];
        if (!$context = $contextclass::instance($instanceid, IGNORE_MISSING)) {
            throw new Exception('The specified "' . $contextref . '" context reference does not exist');
        }

        return $context;
    }
开发者ID:nagyistoce,项目名称:moodle,代码行数:61,代码来源:behat_data_generators.php

示例12: process_course_group_node


//.........这里部分代码省略.........
             if ($end) {
                 $coursemanagement->enddate = $end->nodeValue;
             }
             if (isset($coursemanagement->startdate) && $coursemanagement->startdate > 0 && isset($coursemanagement->enddate) && $coursemanagement->enddate > 0) {
                 // The course validly has both start and end dates.
                 $coursemanagement->courseid = $course->id;
                 $coursemanagement->timemodified = time();
                 $DB->insert_record("eclass_course_management", $coursemanagement);
             } else {
                 if (isset($coursemanagement->startdate) || isset($coursemanagement->enddate)) {
                     // Something isn't right with the start or end date.
                     throw new Exception('UAIMS: Course Creation without valid start or end date');
                 }
             }
             // No else needed. No actions required if the course is validly lacking both start and end dates.
         } else {
             // Update existing Course, if corresponding eclass_course_management exist. Otherwise, create a
             // corresponding eclass_course_management entry.
             $ecourse = $DB->get_record('course', array('idnumber' => $course->idnumber), '*', MUST_EXIST);
             $enableqrtoggle = $this->get_config('enableqrvisibilitytoggle');
             // Disable or enable QR toggling.
             if (!isset($enableqrtoggle) || !$enableqrtoggle) {
                 unset($course->visible);
             } else {
                 // Otherwise update the startend dates in the eclass_course_management table from uaims documents.
                 $coursemanagement = $DB->get_record('eclass_course_management', array('courseid' => $ecourse->id), $fields = 'id', $strictness = IGNORE_MISSING);
                 // Get the start and end date for the course.
                 $begin = $xpath->evaluate("timeframe/begin", $groupnode)->item(0);
                 $end = $xpath->evaluate("timeframe/end", $groupnode)->item(0);
                 // To avoid errors when course is created outside of uaims (doesn't have eclass_course_management entry),
                 // create and set appropriate attributes of $coursemanagement that matches eclass_course_management
                 // database schema (or atleast NOT NULL fields).
                 $coursemanagementexist = $coursemanagement != false;
                 if (!$coursemanagementexist) {
                     $enrol = enrol_get_plugin('manual');
                     if ($audroleid = $DB->get_field('role', 'id', array('shortname' => 'auditor'))) {
                         $enrol->add_instance($ecourse, array('roleid' => $audroleid));
                     } else {
                         $enrol->add_instance($ecourse);
                     }
                     $coursemanagement = new stdClass();
                     // The test process_imsdoc_test::test_process_imsdoc_should_update_course_with_minimal_imsdoc
                     // implies that one of the requirement of this module is to ignore updates/insert in the case where
                     // course exist, yet no start/end date. (Note this differ from the case where the course don't exist
                     // in which case the requirements of this module requires it to throw an exception.
                     if ($begin and $end) {
                         // Set appropriate eclass_course_management row attributes and finally insert it to db.
                         $coursemanagement->courseid = $ecourse->id;
                         $coursemanagement->startdate = $begin->nodeValue;
                         $coursemanagement->enddate = $end->nodeValue;
                         $coursemanagement->timemodified = time();
                         $DB->insert_record("eclass_course_management", $coursemanagement);
                     }
                 } else {
                     // Since corresponding eclass_course_management entry exist, only we don't need all parameters
                     // to be present. Either/both $begin/$end dates is/are sufficient.
                     if ($begin) {
                         $coursemanagement->startdate = $begin->nodeValue;
                     }
                     if ($end) {
                         $coursemanagement->enddate = $end->nodeValue;
                     }
                     if (isset($coursemanagement->startdate) || isset($coursemanagement->enddate)) {
                         // If one of them is there then do the update.
                         if ($coursemanagement->startdate || $coursemanagement->enddate) {
                             $coursemanagement->timemodified = time();
                             $DB->update_record("eclass_course_management", $coursemanagement);
                         }
                     }
                 }
             }
             // The $course var should never have an 'id' attribute, but lets make sure.
             if (isset($course->id)) {
                 unset($course->id);
             }
             $ecourse = $this->extend($ecourse, $course);
             $DB->update_record('course', $ecourse);
             $classname = context_helper::get_class_for_level(CONTEXT_COURSE);
             $context = $classname::instance($ecourse->id, IGNORE_MISSING);
             $classname = context_helper::get_class_for_level(CONTEXT_COURSECAT);
             $newparent = $classname::instance($ecourse->category, IGNORE_MISSING);
             $context->update_moved($newparent);
             if (!($instanceid = $DB->get_field('enrol', 'id', array('enrol' => 'manual', 'courseid' => $ecourse->id)))) {
                 $enrol = enrol_get_plugin('manual');
                 if ($audroleid = $DB->get_field('role', 'id', array('shortname' => 'auditor'))) {
                     $enrol->add_instance($ecourse, array('roleid' => $audroleid));
                 } else {
                     $enrol->add_instance(${$ecourse});
                 }
             }
         }
     } else {
         $idnumber = $xpath->evaluate("sourcedid/id", $groupnode)->item(0);
         if ($idnumber) {
             $idnumber = htmlspecialchars_decode($idnumber->nodeValue);
             $course = $DB->get_record('course', array('idnumber' => $idnumber));
             delete_course($course, false);
         }
     }
 }
开发者ID:MoodleMetaData,项目名称:MoodleMetaData,代码行数:101,代码来源:lib.php

示例13: cron

 /**
  * Finds all assignment notifications that have yet to be mailed out, and mails them.
  *
  * Cron function to be run periodically according to the moodle cron.
  *
  * @return bool
  */
 public static function cron()
 {
     global $DB;
     // Only ever send a max of one days worth of updates.
     $yesterday = time() - 24 * 3600;
     $timenow = time();
     $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));
     // Collect all submissions that require mailing.
     // Submissions are included if all are true:
     //   - The assignment is visible in the gradebook.
     //   - No previous notification has been sent.
     //   - If marking workflow is not enabled, the grade was updated in the past 24 hours, or
     //     if marking workflow is enabled, the workflow state is at 'released'.
     $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities,\n                       g.*, g.timemodified as lastmodified, cm.id as cmid\n                 FROM {assign} a\n                 JOIN {assign_grades} g ON g.assignment = a.id\n            LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid\n                 JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id\n                 JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'\n                 JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name\n                 WHERE ((a.markingworkflow = 0 AND g.timemodified >= :yesterday AND g.timemodified <= :today) OR\n                        (a.markingworkflow = 1 AND uf.workflowstate = :wfreleased)) AND\n                       uf.mailed = 0 AND gri.hidden = 0\n              ORDER BY a.course, cm.id";
     $params = array('yesterday' => $yesterday, 'today' => $timenow, 'wfreleased' => ASSIGN_MARKING_WORKFLOW_STATE_RELEASED);
     $submissions = $DB->get_records_sql($sql, $params);
     if (!empty($submissions)) {
         mtrace('Processing ' . count($submissions) . ' assignment submissions ...');
         // Preload courses we are going to need those.
         $courseids = array();
         foreach ($submissions as $submission) {
             $courseids[] = $submission->course;
         }
         // Filter out duplicates.
         $courseids = array_unique($courseids);
         $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
         list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
         $sql = 'SELECT c.*, ' . $ctxselect . ' FROM {course} c
              LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
                  WHERE c.id ' . $courseidsql;
         $params['contextlevel'] = CONTEXT_COURSE;
         $courses = $DB->get_records_sql($sql, $params);
         // Clean up... this could go on for a while.
         unset($courseids);
         unset($ctxselect);
         unset($courseidsql);
         unset($params);
         // Message students about new feedback.
         foreach ($submissions as $submission) {
             mtrace("Processing assignment submission {$submission->id} ...");
             // Do not cache user lookups - could be too many.
             if (!($user = $DB->get_record('user', array('id' => $submission->userid)))) {
                 mtrace('Could not find user ' . $submission->userid);
                 continue;
             }
             // Use a cache to prevent the same DB queries happening over and over.
             if (!array_key_exists($submission->course, $courses)) {
                 mtrace('Could not find course ' . $submission->course);
                 continue;
             }
             $course = $courses[$submission->course];
             if (isset($course->ctxid)) {
                 // Context has not yet been preloaded. Do so now.
                 context_helper::preload_from_record($course);
             }
             // Override the language and timezone of the "current" user, so that
             // mail is customised for the receiver.
             cron_setup_user($user, $course);
             // Context lookups are already cached.
             $coursecontext = context_course::instance($course->id);
             if (!is_enrolled($coursecontext, $user->id)) {
                 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
                 mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
                 continue;
             }
             if (!($grader = $DB->get_record('user', array('id' => $submission->grader)))) {
                 mtrace('Could not find grader ' . $submission->grader);
                 continue;
             }
             $modinfo = get_fast_modinfo($course, $user->id);
             $cm = $modinfo->get_cm($submission->cmid);
             // Context lookups are already cached.
             $contextmodule = context_module::instance($cm->id);
             if (!$cm->uservisible) {
                 // Hold mail notification for assignments the user cannot access until later.
                 continue;
             }
             // Need to send this to the student.
             $messagetype = 'feedbackavailable';
             $eventtype = 'assign_notification';
             $updatetime = $submission->lastmodified;
             $modulename = get_string('modulename', 'assign');
             $uniqueid = 0;
             if ($submission->blindmarking && !$submission->revealidentities) {
                 $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $user->id);
             }
             $showusers = $submission->blindmarking && !$submission->revealidentities;
             self::send_assignment_notification($grader, $user, $messagetype, $eventtype, $updatetime, $cm, $contextmodule, $course, $modulename, $submission->name, $showusers, $uniqueid);
             $flags = $DB->get_record('assign_user_flags', array('userid' => $user->id, 'assignment' => $submission->assignment));
             if ($flags) {
                 $flags->mailed = 1;
                 $DB->update_record('assign_user_flags', $flags);
             } else {
//.........这里部分代码省略.........
开发者ID:mercysmart,项目名称:naikelas,代码行数:101,代码来源:locallib.php

示例14: get_level_name

 /**
  * Returns the name of specified context level
  *
  * @static
  * @param int $contextlevel
  * @return string name of the context level
  */
 public static function get_level_name($contextlevel)
 {
     $classname = context_helper::get_class_for_level($contextlevel);
     return $classname::get_level_name();
 }
开发者ID:rolandovanegas,项目名称:moodle,代码行数:12,代码来源:accesslib.php

示例15: cron_run

/**
 * Execute cron tasks
 */
function cron_run()
{
    global $DB, $CFG, $OUTPUT;
    if (CLI_MAINTENANCE) {
        echo "CLI maintenance mode active, cron execution suspended.\n";
        exit(1);
    }
    if (moodle_needs_upgrading()) {
        echo "Moodle upgrade pending, cron execution suspended.\n";
        exit(1);
    }
    require_once $CFG->libdir . '/adminlib.php';
    require_once $CFG->libdir . '/gradelib.php';
    if (!empty($CFG->showcronsql)) {
        $DB->set_debug(true);
    }
    if (!empty($CFG->showcrondebugging)) {
        set_debugging(DEBUG_DEVELOPER, true);
    }
    set_time_limit(0);
    $starttime = microtime();
    // Increase memory limit
    raise_memory_limit(MEMORY_EXTRA);
    // Emulate normal session - we use admin accoutn by default
    cron_setup_user();
    // Start output log
    $timenow = time();
    mtrace("Server Time: " . date('r', $timenow) . "\n\n");
    // Run cleanup core cron jobs, but not every time since they aren't too important.
    // These don't have a timer to reduce load, so we'll use a random number
    // to randomly choose the percentage of times we should run these jobs.
    $random100 = rand(0, 100);
    if ($random100 < 20) {
        // Approximately 20% of the time.
        mtrace("Running clean-up tasks...");
        cron_trace_time_and_memory();
        // Delete users who haven't confirmed within required period
        if (!empty($CFG->deleteunconfirmed)) {
            $cuttime = $timenow - $CFG->deleteunconfirmed * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 0 AND firstaccess > 0\n                                                  AND firstaccess < ?", array($cuttime));
            foreach ($rs as $user) {
                delete_user($user);
                // we MUST delete user properly first
                $DB->delete_records('user', array('id' => $user->id));
                // this is a bloody hack, but it might work
                mtrace(" Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})");
            }
            $rs->close();
        }
        // Delete users who haven't completed profile within required period
        if (!empty($CFG->deleteincompleteusers)) {
            $cuttime = $timenow - $CFG->deleteincompleteusers * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 1 AND lastaccess > 0\n                                                  AND lastaccess < ? AND deleted = 0\n                                                  AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime));
            foreach ($rs as $user) {
                if (isguestuser($user) or is_siteadmin($user)) {
                    continue;
                }
                delete_user($user);
                mtrace(" Deleted not fully setup user {$user->username} ({$user->id})");
            }
            $rs->close();
        }
        // Delete old logs to save space (this might need a timer to slow it down...)
        if (!empty($CFG->loglifetime)) {
            // value in days
            $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24;
            $DB->delete_records_select("log", "time < ?", array($loglifetime));
            mtrace(" Deleted old log records");
        }
        // Delete old backup_controllers and logs.
        $loglifetime = get_config('backup', 'loglifetime');
        if (!empty($loglifetime)) {
            // Value in days.
            $loglifetime = $timenow - $loglifetime * 3600 * 24;
            // Delete child records from backup_logs.
            $DB->execute("DELETE FROM {backup_logs}\n                           WHERE EXISTS (\n                               SELECT 'x'\n                                 FROM {backup_controllers} bc\n                                WHERE bc.backupid = {backup_logs}.backupid\n                                  AND bc.timecreated < ?)", array($loglifetime));
            // Delete records from backup_controllers.
            $DB->execute("DELETE FROM {backup_controllers}\n                          WHERE timecreated < ?", array($loglifetime));
            mtrace(" Deleted old backup records");
        }
        // Delete old cached texts
        if (!empty($CFG->cachetext)) {
            // Defined in config.php
            $cachelifetime = time() - $CFG->cachetext - 60;
            // Add an extra minute to allow for really heavy sites
            $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
            mtrace(" Deleted old cache_text records");
        }
        if (!empty($CFG->usetags)) {
            require_once $CFG->dirroot . '/tag/lib.php';
            tag_cron();
            mtrace(' Executed tag cron');
        }
        // Context maintenance stuff
        context_helper::cleanup_instances();
        mtrace(' Cleaned up context instances');
        context_helper::build_all_paths(false);
//.........这里部分代码省略.........
开发者ID:tyleung,项目名称:CMPUT401MoodleExams,代码行数:101,代码来源:cronlib.php


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