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


PHP session_get_instance函数代码示例

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


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

示例1: block_html_pluginfile

/**
 * Form for editing HTML block instances.
 *
 * @copyright 2010 Petr Skoda (http://skodak.org)
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @package   block_html
 * @category  files
 * @param stdClass $course course object
 * @param stdClass $birecord_or_cm block instance record
 * @param stdClass $context context object
 * @param string $filearea file area
 * @param array $args extra arguments
 * @param bool $forcedownload whether or not force download
 * @param array $options additional options affecting the file serving
 * @return bool
 */
function block_html_pluginfile($course, $birecord_or_cm, $context, $filearea, $args, $forcedownload, array $options = array())
{
    global $SCRIPT;
    if ($context->contextlevel != CONTEXT_BLOCK) {
        send_file_not_found();
    }
    require_course_login($course);
    if ($filearea !== 'content') {
        send_file_not_found();
    }
    $fs = get_file_storage();
    $filename = array_pop($args);
    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
    if (!($file = $fs->get_file($context->id, 'block_html', 'content', 0, $filepath, $filename)) or $file->is_directory()) {
        send_file_not_found();
    }
    if ($parentcontext = get_context_instance_by_id($birecord_or_cm->parentcontextid)) {
        if ($parentcontext->contextlevel == CONTEXT_USER) {
            // force download on all personal pages including /my/
            //because we do not have reliable way to find out from where this is used
            $forcedownload = true;
        }
    } else {
        // weird, there should be parent context, better force dowload then
        $forcedownload = true;
    }
    session_get_instance()->write_close();
    send_stored_file($file, 60 * 60, 0, $forcedownload, $options);
}
开发者ID:nmicha,项目名称:moodle,代码行数:45,代码来源:lib.php

示例2: dbtransfer_transfer_database

function dbtransfer_transfer_database($sourcedb, $targetdb, $feedback = null)
{
    @set_time_limit(0);
    session_get_instance()->write_close();
    // release session
    $var = new database_mover($sourcedb, $targetdb, true, $feedback);
    $var->export_database(null);
}
开发者ID:nigeldaley,项目名称:moodle,代码行数:8,代码来源:locallib.php

示例3: tool_dbtransfer_transfer_database

/**
 * Initiate database transfer.
 * @param moodle_database $sourcedb
 * @param moodle_database $targetdb
 * @param progress_trace $feedback
 * @return void
 */
function tool_dbtransfer_transfer_database(moodle_database $sourcedb, moodle_database $targetdb, progress_trace $feedback = null)
{
    @set_time_limit(0);
    session_get_instance()->write_close();
    // Release session.
    $var = new database_mover($sourcedb, $targetdb, true, $feedback);
    $var->export_database(null);
    tool_dbtransfer_rebuild_target_log_actions($targetdb, $feedback);
}
开发者ID:JP-Git,项目名称:moodle,代码行数:16,代码来源:locallib.php

示例4: block_html_pluginfile

/**
 * Form for editing HTML block instances.
 *
 * @copyright 2010 Petr Skoda (http://skodak.org)
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @package   block_html
 * @category  files
 * @param stdClass $course course object
 * @param stdClass $birecord_or_cm block instance record
 * @param stdClass $context context object
 * @param string $filearea file area
 * @param array $args extra arguments
 * @param bool $forcedownload whether or not force download
 * @param array $options additional options affecting the file serving
 * @return bool
 * @todo MDL-36050 improve capability check on stick blocks, so we can check user capability before sending images.
 */
function block_html_pluginfile($course, $birecord_or_cm, $context, $filearea, $args, $forcedownload, array $options = array())
{
    global $DB, $CFG, $USER;
    if ($context->contextlevel != CONTEXT_BLOCK) {
        send_file_not_found();
    }
    // If block is in course context, then check if user has capability to access course.
    if ($context->get_course_context(false)) {
        require_course_login($course);
    } else {
        if ($CFG->forcelogin) {
            require_login();
        } else {
            // Get parent context and see if user have proper permission.
            $parentcontext = $context->get_parent_context();
            if ($parentcontext->contextlevel === CONTEXT_COURSECAT) {
                // Check if category is visible and user can view this category.
                $category = $DB->get_record('course_categories', array('id' => $parentcontext->instanceid), '*', MUST_EXIST);
                if (!$category->visible) {
                    require_capability('moodle/category:viewhiddencategories', $parentcontext);
                }
            } else {
                if ($parentcontext->contextlevel === CONTEXT_USER && $parentcontext->instanceid != $USER->id) {
                    // The block is in the context of a user, it is only visible to the user who it belongs to.
                    send_file_not_found();
                }
            }
            // At this point there is no way to check SYSTEM context, so ignoring it.
        }
    }
    if ($filearea !== 'content') {
        send_file_not_found();
    }
    $fs = get_file_storage();
    $filename = array_pop($args);
    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
    if (!($file = $fs->get_file($context->id, 'block_html', 'content', 0, $filepath, $filename)) or $file->is_directory()) {
        send_file_not_found();
    }
    if ($parentcontext = context::instance_by_id($birecord_or_cm->parentcontextid, IGNORE_MISSING)) {
        if ($parentcontext->contextlevel == CONTEXT_USER) {
            // force download on all personal pages including /my/
            //because we do not have reliable way to find out from where this is used
            $forcedownload = true;
        }
    } else {
        // weird, there should be parent context, better force dowload then
        $forcedownload = true;
    }
    session_get_instance()->write_close();
    send_stored_file($file, 60 * 60, 0, $forcedownload, $options);
}
开发者ID:masaterutakeno,项目名称:MoodleMobile,代码行数:69,代码来源:lib.php

示例5: tool_generator_pluginfile

/**
 * Files support.
 *
 * Exits if the required permissions are not satisfied.
 *
 * @param stdClass $course course object
 * @param stdClass $cm
 * @param stdClass $context context object
 * @param string $filearea file area
 * @param array $args extra arguments
 * @param bool $forcedownload whether or not force download
 * @param array $options additional options affecting the file serving
 * @return void The file is sent along with it's headers
 */
function tool_generator_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array())
{
    // Only for admins or CLI.
    if (!defined('CLI_SCRIPT') && !is_siteadmin()) {
        die;
    }
    if ($context->contextlevel != CONTEXT_SYSTEM) {
        send_file_not_found();
    }
    $fs = get_file_storage();
    $file = $fs->get_file($context->id, 'tool_generator', $filearea, $args[0], '/', $args[1]);
    // Send the file, always forcing download, we don't want options.
    session_get_instance()->write_close();
    send_stored_file($file, 0, 0, true);
}
开发者ID:EmmanuelYupit,项目名称:educursos,代码行数:29,代码来源:lib.php

示例6: block_course_profile_pluginfile

function block_course_profile_pluginfile($course, $birecord_or_cm, $context, $filearea, $args, $forcedownload, array $options = array())
{
    global $SCRIPT;
    if ($context->contextlevel != CONTEXT_COURSE) {
        send_file_not_found();
    }
    if ($filearea !== 'courseicon') {
        send_file_not_found();
    }
    $fs = get_file_storage();
    $file = $fs->get_file($context->id, 'block_course_profile', 'courseicon', 0, '/', $course->id);
    if (!$file or $file->is_directory()) {
        send_file_not_found();
    }
    session_get_instance()->write_close();
    send_stored_file($file, 60 * 60, 0, false, $options);
}
开发者ID:nanda555,项目名称:TestAppFromAWS,代码行数:17,代码来源:lib.php

示例7: report_rolesmigration_pluginfile

/**
 * Serves rolesexport xml files.
 *
 * @param object $course
 * @param object $cm
 * @param object $context
 * @param string $filearea
 * @param array $args
 * @param bool $forcedownload
 * @return bool false if file not found, does not return if found - just send the file
 */
function report_rolesmigration_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload)
{
    global $USER;
    //require_capability('mod/assignment:view', $this->context);
    $fullpath = "/{$context->id}/report_rolesmigration/{$filearea}/" . implode('/', $args);
    $fs = get_file_storage();
    if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
        send_file_not_found();
    }
    if ($USER->id != $file->get_userid() && !has_capability('moodle/role:manage', $context)) {
        send_file_not_found();
    }
    session_get_instance()->write_close();
    // unlock session during fileserving
    if (!send_stored_file($file, 60 * 60, 0, true)) {
        send_file_not_found();
    }
}
开发者ID:rlorenzo,项目名称:moodle-report_rolesmigration,代码行数:29,代码来源:lib.php

示例8: local_note_pluginfile

function local_note_pluginfile($course, $birecord_or_cm, $context, $filearea, $args, $forcedownload, array $options = array())
{
    global $DB, $CFG;
    if ($context->contextlevel != CONTEXT_SYSTEM) {
        send_file_not_found();
    }
    // If block is in course context, then check if user has capability to access course.
    if ($context->get_course_context(false)) {
        //require_course_login($course);
    } else {
        if ($CFG->forcelogin) {
            //require_login();
        } else {
            // Get parent context and see if user have proper permission.
            $parentcontext = $context->get_parent_context();
            if ($parentcontext->contextlevel === CONTEXT_COURSECAT) {
                // Check if category is visible and user can view this category.
                $category = $DB->get_record('course_categories', array('id' => $parentcontext->instanceid), '*', MUST_EXIST);
                if (!$category->visible) {
                    require_capability('moodle/category:viewhiddencategories', $parentcontext);
                }
            }
            // At this point there is no way to check SYSTEM or USER context, so ignoring it.
        }
    }
    if ($filearea !== 'content') {
        send_file_not_found();
    }
    $fs = get_file_storage();
    $filename = array_pop($args);
    //$filepath = $args ? '/'.implode('/', $args).'/' : '/';
    $filepath = '/';
    $itemid = $args['0'];
    //added by nihar -to get the item id
    if (!($file = $fs->get_file($context->id, 'local_note', 'content', $itemid, $filepath, $filename)) or $file->is_directory()) {
        send_file_not_found();
    }
    session_get_instance()->write_close();
    send_stored_file($file, 60 * 60, 0, $forcedownload, $options);
}
开发者ID:shambhukumar,项目名称:moodle-note,代码行数:40,代码来源:lib.php

示例9: unlock_session

 /**
  * Unlock the session and allow the regrading process to run in the background.
  */
 protected function unlock_session() {
     session_get_instance()->write_close();
     ignore_user_abort(true);
 }
开发者ID:ncsu-delta,项目名称:moodle,代码行数:7,代码来源:report.php

示例10: send_stored_file

/**
 * Handles the sending of file data to the user's browser, including support for
 * byteranges etc.
 *
 * @global object
 * @global object
 * @global object
 * @param object $stored_file local file object
 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
 * @param string $filename Override filename
 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
 *                        if this is passed as true, ignore_user_abort is called.  if you don't want your processing to continue on cancel,
 *                        you must detect this case when control is returned using connection_aborted. Please not that session is closed
 *                        and should not be reopened.
 * @return void no return or void, script execution stopped unless $dontdie is true
 */
function send_stored_file($stored_file, $lifetime = 86400, $filter = 0, $forcedownload = false, $filename = null, $dontdie = false)
{
    global $CFG, $COURSE, $SESSION;
    if (!$stored_file or $stored_file->is_directory()) {
        // nothing to serve
        if ($dontdie) {
            return;
        }
        die;
    }
    if ($dontdie) {
        ignore_user_abort(true);
    }
    session_get_instance()->write_close();
    // unlock session during fileserving
    // Use given MIME type if specified, otherwise guess it using mimeinfo.
    // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
    // only Firefox saves all files locally before opening when content-disposition: attachment stated
    $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
    $isFF = check_browser_version('Firefox', '1.5');
    // only FF > 1.5 properly tested
    $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' : ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
    $lastmodified = $stored_file->get_timemodified();
    $filesize = $stored_file->get_filesize();
    //try to disable automatic sid rewrite in cookieless mode
    @ini_set("session.use_trans_sid", "false");
    if ($lifetime > 0 && !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
        // get unixtime of request header; clip extra junk off first
        $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
        if ($since && $since >= $lastmodified) {
            header('HTTP/1.1 304 Not Modified');
            header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $lifetime) . ' GMT');
            header('Cache-Control: max-age=' . $lifetime);
            header('Content-Type: ' . $mimetype);
            if ($dontdie) {
                return;
            }
            die;
        }
    }
    //do not put '@' before the next header to detect incorrect moodle configurations,
    //error should be better than "weird" empty lines for admins/users
    //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastmodified) . ' GMT');
    // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
    if (check_browser_version('MSIE')) {
        $filename = rawurlencode($filename);
    }
    if ($forcedownload) {
        header('Content-Disposition: attachment; filename="' . $filename . '"');
    } else {
        header('Content-Disposition: inline; filename="' . $filename . '"');
    }
    if ($lifetime > 0) {
        header('Cache-Control: max-age=' . $lifetime);
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $lifetime) . ' GMT');
        header('Pragma: ');
        if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
            header('Accept-Ranges: bytes');
            if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'], 'bytes=') !== FALSE) {
                // byteserving stuff - for acrobat reader and download accelerators
                // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
                // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
                $ranges = false;
                if (preg_match_all('/(\\d*)-(\\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
                    foreach ($ranges as $key => $value) {
                        if ($ranges[$key][1] == '') {
                            //suffix case
                            $ranges[$key][1] = $filesize - $ranges[$key][2];
                            $ranges[$key][2] = $filesize - 1;
                        } else {
                            if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
                                //fix range length
                                $ranges[$key][2] = $filesize - 1;
                            }
                        }
                        if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
                            //invalid byte-range ==> ignore header
                            $ranges = false;
                            break;
                        }
                        //prepare multipart header
//.........这里部分代码省略.........
开发者ID:hatone,项目名称:moodle,代码行数:101,代码来源:filelib.php

示例11: __authenticate

 public function __authenticate($username, $password, $serviceshortname)
 {
     global $CFG, $DB;
     //echo $OUTPUT->header();
     if (!$CFG->enablewebservices) {
         throw new moodle_exception('enablewsdescription', 'webservice');
     }
     $username = trim(textlib::strtolower($username));
     if (is_restored_user($username)) {
         throw new moodle_exception('restoredaccountresetpassword', 'webservice');
     }
     $user = authenticate_user_login($username, $password);
     if (!empty($user)) {
         //Non admin can not authenticate if maintenance mode
         $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
         if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
             throw new moodle_exception('sitemaintenance', 'admin');
         }
         if (isguestuser($user)) {
             throw new moodle_exception('noguest');
         }
         if (empty($user->confirmed)) {
             throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
         }
         // check credential expiry
         $userauth = get_auth_plugin($user->auth);
         if (!empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
             $days2expire = $userauth->password_expire($user->username);
             if (intval($days2expire) < 0) {
                 throw new moodle_exception('passwordisexpired', 'webservice');
             }
         }
         // let enrol plugins deal with new enrolments if necessary
         enrol_check_plugins($user);
         // setup user session to check capability
         session_set_user($user);
         //check if the service exists and is enabled
         $service = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1));
         if (empty($service)) {
             // will throw exception if no token found
             throw new moodle_exception('servicenotavailable', 'webservice');
         }
         //check if there is any required system capability
         if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
             throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
         }
         //specific checks related to user restricted service
         if ($service->restrictedusers) {
             $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));
             if (empty($authoriseduser)) {
                 throw new moodle_exception('usernotallowed', 'webservice', '', $serviceshortname);
             }
             if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
                 throw new moodle_exception('invalidtimedtoken', 'webservice');
             }
             if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
                 throw new moodle_exception('invalidiptoken', 'webservice');
             }
         }
         //Check if a token has already been created for this user and this service
         //Note: this could be an admin created or an user created token.
         //      It does not really matter we take the first one that is valid.
         $tokenssql = "SELECT t.id, t.sid, t.token, t.validuntil, t.iprestriction\n              FROM {external_tokens} t\n             WHERE t.userid = ? AND t.externalserviceid = ? AND t.tokentype = ?\n          ORDER BY t.timecreated ASC";
         $tokens = $DB->get_records_sql($tokenssql, array($user->id, $service->id, EXTERNAL_TOKEN_PERMANENT));
         //A bit of sanity checks
         foreach ($tokens as $key => $token) {
             /// Checks related to a specific token. (script execution continue)
             $unsettoken = false;
             //if sid is set then there must be a valid associated session no matter the token type
             if (!empty($token->sid)) {
                 $session = session_get_instance();
                 if (!$session->session_exists($token->sid)) {
                     //this token will never be valid anymore, delete it
                     $DB->delete_records('external_tokens', array('sid' => $token->sid));
                     $unsettoken = true;
                 }
             }
             //remove token if no valid anymore
             //Also delete this wrong token (similar logic to the web service servers
             //    /webservice/lib.php/webservice_server::authenticate_by_token())
             if (!empty($token->validuntil) and $token->validuntil < time()) {
                 $DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
                 $unsettoken = true;
             }
             // remove token if its ip not in whitelist
             if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
                 $unsettoken = true;
             }
             if ($unsettoken) {
                 unset($tokens[$key]);
             }
         }
         // if some valid tokens exist then use the most recent
         if (count($tokens) > 0) {
             $token = array_pop($tokens);
         } else {
             if ($serviceshortname == MOODLE_OFFICIAL_MOBILE_SERVICE and has_capability('moodle/webservice:createmobiletoken', get_system_context()) or !is_siteadmin($user) && has_capability('moodle/webservice:createtoken', get_system_context())) {
                 // if service doesn't exist, dml will throw exception
                 $service_record = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1), '*', MUST_EXIST);
                 // create a new token
//.........这里部分代码省略.........
开发者ID:vinoth4891,项目名称:clinique,代码行数:101,代码来源:clinique_login_authenticate.php

示例12: send_file

 public function send_file($filearea, $args)
 {
     global $USER;
     require_capability('mod/assignment:view', $this->context);
     $fullpath = "/{$this->context->id}/mod_assignment/{$filearea}/" . implode('/', $args);
     $fs = get_file_storage();
     if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
         send_file_not_found();
     }
     if ($USER->id != $file->get_userid() && !has_capability('mod/assignment:grade', $this->context)) {
         send_file_not_found();
     }
     session_get_instance()->write_close();
     // unlock session during fileserving
     send_stored_file($file, 60 * 60, 0, true);
 }
开发者ID:vuchannguyen,项目名称:web,代码行数:16,代码来源:assignment.class.php

示例13: require_logout

/**
 * This function just makes sure a user is logged out.
 *
 * @global object
 */
function require_logout()
{
    global $USER;
    $params = $USER;
    if (isloggedin()) {
        add_to_log(SITEID, "user", "logout", "view.php?id={$USER->id}&course=" . SITEID, $USER->id, 0, $USER->id);
        $authsequence = get_enabled_auth_plugins();
        // auths, in sequence
        foreach ($authsequence as $authname) {
            $authplugin = get_auth_plugin($authname);
            $authplugin->prelogout_hook();
        }
    }
    events_trigger('user_logout', $params);
    session_get_instance()->terminate_current();
    unset($params);
}
开发者ID:hitphp,项目名称:moodle,代码行数:22,代码来源:moodlelib.php

示例14: session_get_instance

        session_get_instance()->write_close();
        send_stored_file($file, 60*60, 0, $forcedownload);

    } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
        // Backup files that were generated by the automated backup systems.

        require_login($course);
        require_capability('moodle/site:config', $context);

        $filename = array_pop($args);
        $filepath = $args ? '/'.implode('/', $args).'/' : '/';
        if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
            send_file_not_found();
        }

        session_get_instance()->write_close(); // unlock session during fileserving
        send_stored_file($file, 0, 0, $forcedownload);

    } else {
        send_file_not_found();
    }

// ========================================================================================================================
} else if ($component === 'question') {
    require_once($CFG->libdir . '/questionlib.php');
    question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
    send_file_not_found();

// ========================================================================================================================
} else if (strpos($component, 'mod_') === 0) {
    $modname = substr($component, 4);
开发者ID:ravivare,项目名称:moodle-1,代码行数:31,代码来源:pluginfile.php

示例15: test_everything_in_accesslib

 /**
  * A small functional test of accesslib functions and classes.
  */
 public function test_everything_in_accesslib()
 {
     global $USER, $SITE, $CFG, $DB, $ACCESSLIB_PRIVATE;
     // First of all finalize the session, we must not carry over any of this mess to the next page via SESSION!!!
     session_get_instance()->write_close();
     // hack - this is going to take very long time
     set_time_limit(3600);
     // Get rid of current user that would not work anyway,
     // do NOT even think about using $this->switch_global_user_id()!
     if (!isset($this->accesslibprevuser)) {
         $this->accesslibprevuser = clone $USER;
         $USER = new stdClass();
         $USER->id = 0;
     }
     // Backup $SITE global
     if (!isset($this->accesslibprevsite)) {
         $this->accesslibprevsite = $SITE;
     }
     // Switch DB, if it somehow fails or you specified wrong unittest prefix it will nuke real data, you have been warned!
     $this->switch_to_test_db();
     // Let's switch the CFG
     $prevcfg = clone $CFG;
     $this->switch_to_test_cfg();
     $CFG->config_php_settings = $prevcfg->config_php_settings;
     $CFG->noemailever = true;
     $CFG->admin = $prevcfg->admin;
     $CFG->lang = 'en';
     $CFG->tempdir = $prevcfg->tempdir;
     $CFG->cachedir = $prevcfg->cachedir;
     $CFG->directorypermissions = $prevcfg->directorypermissions;
     $CFG->filepermissions = $prevcfg->filepermissions;
     // Reset all caches
     accesslib_clear_all_caches_for_unit_testing();
     // Add some core tables - this is known to break constantly because we keep adding dependencies...
     $tablenames = array('config', 'config_plugins', 'modules', 'course', 'course_modules', 'course_sections', 'course_categories', 'mnet_host', 'mnet_application', 'capabilities', 'context', 'context_temp', 'role', 'role_capabilities', 'role_allow_switch', 'license', 'my_pages', 'block', 'block_instances', 'block_positions', 'role_allow_assign', 'role_allow_override', 'role_assignments', 'role_context_levels', 'enrol', 'user_enrolments', 'filter_active', 'filter_config', 'comments', 'user', 'groups_members', 'cache_flags', 'events_handlers', 'user_lastaccess', 'rating', 'files', 'role_names', 'user_preferences');
     $this->create_test_tables($tablenames, 'lib');
     // Create all core default records and default settings
     require_once "{$CFG->libdir}/db/install.php";
     xmldb_main_install();
     // installs the capabilities too
     // Fake mod_page install
     $tablenames = array('page');
     $this->create_test_tables($tablenames, 'mod/page');
     $module = new stdClass();
     require $CFG->dirroot . '/mod/page/version.php';
     $module->name = 'page';
     $pagemoduleid = $DB->insert_record('modules', $module);
     update_capabilities('mod_page');
     // Fake block_online_users install
     $plugin = new stdClass();
     $plugin->version = NULL;
     $plugin->cron = 0;
     include $CFG->dirroot . '/blocks/online_users/version.php';
     $plugin->name = 'online_users';
     $onlineusersblockid = $DB->insert_record('block', $plugin);
     update_capabilities('block_online_users');
     // Finish roles setup
     set_config('defaultfrontpageroleid', $DB->get_field('role', 'id', array('archetype' => 'frontpage')));
     set_config('defaultuserroleid', $DB->get_field('role', 'id', array('archetype' => 'user')));
     set_config('notloggedinroleid', $DB->get_field('role', 'id', array('archetype' => 'guest')));
     set_config('rolesactive', 1);
     // Init manual enrol
     set_config('status', ENROL_INSTANCE_ENABLED, 'enrol_manual');
     set_config('defaultperiod', 0, 'enrol_manual');
     $manualenrol = enrol_get_plugin('manual');
     // Fill the site with some real data
     $testcategories = array();
     $testcourses = array();
     $testpages = array();
     $testblocks = array();
     $allroles = $DB->get_records_menu('role', array(), 'id', 'archetype, id');
     $systemcontext = context_system::instance();
     $frontpagecontext = context_course::instance(SITEID);
     // Add block to system context
     $bi = new stdClass();
     $bi->blockname = 'online_users';
     $bi->parentcontextid = $systemcontext->id;
     $bi->showinsubcontexts = 1;
     $bi->pagetypepattern = '';
     $bi->subpagepattern = '';
     $bi->defaultregion = '';
     $bi->defaultweight = 0;
     $bi->configdata = '';
     $biid = $DB->insert_record('block_instances', $bi);
     context_block::instance($biid);
     $testblocks[] = $biid;
     // Some users
     $testusers = array();
     for ($i = 0; $i < 20; $i++) {
         $user = new stdClass();
         $user->auth = 'manual';
         $user->firstname = 'user' . $i;
         $user->lastname = 'user' . $i;
         $user->username = 'user' . $i;
         $user->password = 'doesnotexist';
         $user->email = "user{$i}@example.com";
         $user->confirmed = 1;
//.........这里部分代码省略.........
开发者ID:rolandovanegas,项目名称:moodle,代码行数:101,代码来源:fulltestaccesslib.php


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