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


PHP address_in_subnet函数代码示例

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


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

示例1: get_content

 public function get_content()
 {
     global $CFG, $USER, $OUTPUT;
     if (has_capability('block/papercut:view', $this->context)) {
         $this->content = new stdClass();
         $this->content->footer = '';
         $this->content->items = array();
         $this->content->icons = array();
         $serverip = explode('.', $_SERVER['SERVER_ADDR']);
         $internal = address_in_subnet(getremoteaddr(), $serverip[0] . '.' . $serverip[1]);
         $strnobalance = get_string('nobalance', 'block_papercut');
         $image = $OUTPUT->pix_icon('balance_not_available', $strnobalance, 'block_papercut');
         $http = $CFG->block_papercut_https ? 'https://' : 'http://';
         $serverurl = $http . $CFG->block_papercut_server_url . ':' . $CFG->block_papercut_server_port;
         $scriptattrs = array('type' => 'text/javascript');
         $wisgetsattrs = $scriptattrs;
         $widgetsattrs['src'] = $serverurl . '/content/widgets/widgets.js';
         $script1 = "var pcUsername = '{$USER->username}';" . "var pcServerURL = '{$serverurl}'; pcGetUserDetails();";
         $script2 = "pcInitUserEnvironmentalImpactWidget('widgetEnvironment');" . "pcInitUserBalanceWidget('widgetBalance');";
         if ($internal) {
             $this->content->text .= html_writer::tag('script', '', $widgetsattrs);
         }
         $this->content->text .= html_writer::tag('script', $script1, $scriptattrs);
         $this->content->text .= html_writer::tag('div', $image, array('id' => 'widgetBalance'));
         $this->content->text .= html_writer::tag('div', '', array('id' => 'widgetEnvironment'));
         if ($internal) {
             $this->content->text .= html_writer::tag('script', $script2, $scriptattrs);
         }
         return $this->content;
     }
 }
开发者ID:rtsfc,项目名称:moodle-block_papercut,代码行数:31,代码来源:block_papercut.php

示例2: test_address_in_subnet

 function test_address_in_subnet()
 {
     $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1'));
     $this->assertFalse(address_in_subnet('123.121.234.2', '123.121.234.1'));
     $this->assertFalse(address_in_subnet('123.121.134.1', '123.121.234.1'));
     $this->assertFalse(address_in_subnet('113.121.234.1', '123.121.234.1'));
     $this->assertTrue(address_in_subnet('123.121.234.0', '123.121.234.2/28'));
     $this->assertTrue(address_in_subnet('123.121.234.15', '123.121.234.2/28'));
     $this->assertFalse(address_in_subnet('123.121.234.16', '123.121.234.2/28'));
     $this->assertFalse(address_in_subnet('123.121.234.255', '123.121.234.2/28'));
     $this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.0/'));
     $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.0/'));
     $this->assertTrue(address_in_subnet('232.232.232.232', '123.121.234.0/0'));
     $this->assertFalse(address_in_subnet('123.122.234.1', '123.121.'));
     $this->assertFalse(address_in_subnet('223.121.234.1', '123.121.'));
     $this->assertTrue(address_in_subnet('123.121.234.1', '123.121'));
     $this->assertFalse(address_in_subnet('123.122.234.1', '123.121'));
     $this->assertFalse(address_in_subnet('223.121.234.1', '123.121'));
     $this->assertFalse(address_in_subnet('123.121.234.100', '123.121.234.10'));
     $this->assertFalse(address_in_subnet('123.121.234.9', '123.121.234.10-20'));
     $this->assertTrue(address_in_subnet('123.121.234.10', '123.121.234.10-20'));
     $this->assertTrue(address_in_subnet('123.121.234.15', '123.121.234.10-20'));
     $this->assertTrue(address_in_subnet('123.121.234.20', '123.121.234.10-20'));
     $this->assertFalse(address_in_subnet('123.121.234.21', '123.121.234.10-20'));
     $this->assertTrue(address_in_subnet('  123.121.234.1  ', '  123.121.234.1  , 1.1.1.1/16,2.2.,3.3.3.3-6  '));
     $this->assertTrue(address_in_subnet('  1.1.2.3 ', '  123.121.234.1  , 1.1.1.1/16,2.2.,3.3.3.3-6  '));
     $this->assertTrue(address_in_subnet('  2.2.234.1  ', '  123.121.234.1  , 1.1.1.1/16,2.2.,3.3.3.3-6  '));
     $this->assertTrue(address_in_subnet('  3.3.3.4  ', '  123.121.234.1  , 1.1.1.1/16,2.2.,3.3.3.3-6  '));
     $this->assertFalse(address_in_subnet('  123.121.234.2  ', '  123.121.234.1  , 1.1.1.1/16,2.2.,3.3.3.3-6  '));
     $this->assertFalse(address_in_subnet('  2.1.2.3 ', '  123.121.234.1  , 1.1.1.1/16,2.2.,3.3.3.3-6  '));
     $this->assertFalse(address_in_subnet('  2.3.234.1  ', '  123.121.234.1  , 1.1.1.1/16,2.2.,3.3.3.3-6  '));
     $this->assertFalse(address_in_subnet('  3.3.3.7  ', '  123.121.234.1  , 1.1.1.1/16,2.2.,3.3.3.3-6  '));
     $this->assertFalse(address_in_subnet('172.16.1.142', '172.16.1.143/148'));
 }
开发者ID:JackCanada,项目名称:moodle-hacks,代码行数:34,代码来源:testmoodlelib.php

示例3: prevent_access

 public function prevent_access()
 {
     if (address_in_subnet(getremoteaddr(), $this->quiz->subnet)) {
         return false;
     } else {
         return get_string('subnetwrong', 'quizaccess_ipaddress');
     }
 }
开发者ID:evltuma,项目名称:moodle,代码行数:8,代码来源:rule.php

示例4: plaintext_is_ok

 function plaintext_is_ok()
 {
     global $CFG;
     $trusted_hosts = explode(',', get_config('mnet', 'mnet_trusted_hosts'));
     foreach ($trusted_hosts as $host) {
         if (address_in_subnet(getremoteaddr(), $host)) {
             return true;
         }
     }
     return false;
 }
开发者ID:evltuma,项目名称:moodle,代码行数:11,代码来源:remote_client.php

示例5: find_lms_user

function find_lms_user($installid, $username, $signature, $confirmaction = null, $firstname = null, $lastname = null, $email = null)
{
    global $CFG;
    // find this host from the installid
    if (empty($CFG->lmshosts) || !is_array($CFG->lmshosts) || !array_key_exists($installid, $CFG->lmshosts)) {
        return LMS_NO_SUCH_HOST;
    }
    $host = $CFG->lmshosts[$installid];
    // validate our md5 hash
    if ($confirmaction == 'signupconfirmation') {
        $stringtohash = $installid . '|' . $username . '|' . $firstname . '|' . $lastname . '|' . $email . '|' . $host['token'];
    } else {
        $stringtohash = $installid . '|' . $username . '|' . $host['token'];
        // firstname, lastname and email cannot be relied upon not to change
        // so we only want to add them to the hash on signup, not for auth or anything else.
    }
    $checksig = md5($stringtohash);
    if ($checksig != $signature) {
        return LMS_INVALID_HASH;
    }
    // if we have an ip address, check it.
    if (array_key_exists('networkaddress', $host) && empty($confirmaction)) {
        if (!address_in_subnet(getremoteaddr(), $host['networkaddress'])) {
            return LMS_INVALID_NETWORK;
        }
    }
    if (!empty($confirmaction) && !empty($host['confirmurl'])) {
        $client = new Snoopy();
        $client->agent = LMS_SNOOPY_USER_AGENT;
        $client->read_timeout = 5;
        $client->use_gzip = true;
        $postdata = array('action' => $confirmaction, 'username' => $username, 'signature' => $signature);
        @$client->submit($host['confirmurl'], $postdata);
        if ($client->results != 'OK') {
            return clean_param($client->results, PARAM_CLEAN);
        }
    }
    // find our user (we only want to check username and installid, the others could potentially change..
    if (!($user = get_record_sql('SELECT u.* FROM ' . $CFG->prefix . 'users u 
                        JOIN ' . $CFG->prefix . 'users_alias ua ON ua.user_id = u.ident
                        WHERE ua.installid = ? AND ua.username = ?', array($installid, $username)))) {
        return LMS_NO_SUCH_USER;
    }
    return $user;
}
开发者ID:BackupTheBerlios,项目名称:tulipan-svn,代码行数:45,代码来源:lmslib.php

示例6: loginpage_hook

 /**
  * Will get called before the login page is shown, if NTLM SSO
  * is enabled, and the user is in the right network, we'll redirect
  * to the magic NTLM page for SSO...
  *
  */
 function loginpage_hook()
 {
     global $CFG;
     if ($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($this->config->ntlmsso_enabled) && !empty($this->config->ntlmsso_subnet) && empty($_GET['authldap_skipntlmsso']) && (isguestuser() || !isloggedin()) && address_in_subnet($_SERVER['REMOTE_ADDR'], $this->config->ntlmsso_subnet)) {
         redirect("{$CFG->wwwroot}/auth/ldap/ntlmsso_attempt.php");
     }
 }
开发者ID:r007,项目名称:PMoodle,代码行数:13,代码来源:auth.php

示例7: remoteip_in_list

/**
 * Is current ip in give list?
 *
 * @param string $list
 * @return bool
 */
function remoteip_in_list($list)
{
    $inlist = false;
    $clientip = getremoteaddr(null);
    if (!$clientip) {
        // Ensure access on cli.
        return true;
    }
    $list = explode("\n", $list);
    foreach ($list as $subnet) {
        $subnet = trim($subnet);
        if (address_in_subnet($clientip, $subnet)) {
            $inlist = true;
            break;
        }
    }
    return $inlist;
}
开发者ID:lucaboesch,项目名称:moodle,代码行数:24,代码来源:moodlelib.php

示例8: session_get_instance

         $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 (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
         $token = new stdClass();
开发者ID:GordonAlexander,项目名称:local_ombieltoken,代码行数:31,代码来源:token.php

示例9: __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

示例10: init_service_class

    /**
     * Load the virtual class needed for the web service.
     *
     * Initialises the virtual class that contains the web service functions that the user is allowed to use.
     * The web service function will be available if the user:
     * - is validly registered in the external_services_users table.
     * - has the required capability.
     * - meets the IP restriction requirement.
     * This virtual class can be used by web service protocols such as SOAP, especially when generating WSDL.
     * NOTE: The implementation of this method has been mostly copied from webservice_zend_server::init_server_class().
     */
    protected function init_service_class()
    {
        global $USER, $DB;
        // Initialise service methods and struct classes.
        $this->servicemethods = array();
        $this->servicestructs = array();
        $params = array();
        $wscond1 = '';
        $wscond2 = '';
        if ($this->restricted_serviceid) {
            $params = array('sid1' => $this->restricted_serviceid, 'sid2' => $this->restricted_serviceid);
            $wscond1 = 'AND s.id = :sid1';
            $wscond2 = 'AND s.id = :sid2';
        }
        $sql = "SELECT s.*, NULL AS iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)\n                 WHERE s.enabled = 1 {$wscond1}\n\n                 UNION\n\n                SELECT s.*, su.iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)\n                  JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)\n                 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) {$wscond2}";
        $params = array_merge($params, array('userid' => $USER->id, 'now' => time()));
        $serviceids = array();
        $remoteaddr = getremoteaddr();
        // Query list of external services for the user.
        $rs = $DB->get_recordset_sql($sql, $params);
        // Check which service ID to include.
        foreach ($rs as $service) {
            if (isset($serviceids[$service->id])) {
                continue;
                // Service already added.
            }
            if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
                continue;
                // Cap required, sorry.
            }
            if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
                continue;
                // Wrong request source ip, sorry.
            }
            $serviceids[$service->id] = $service->id;
        }
        $rs->close();
        // Generate the virtual class name.
        $classname = 'webservices_virtual_class_000000';
        while (class_exists($classname)) {
            $classname++;
        }
        $this->serviceclass = $classname;
        // Get the list of all available external functions.
        $wsmanager = new webservice();
        $functions = $wsmanager->get_external_functions($serviceids);
        // Generate code for the virtual methods for this web service.
        $methods = '';
        foreach ($functions as $function) {
            $methods .= $this->get_virtual_method_code($function);
        }
        $code = <<<EOD
/**
 * Virtual class web services for user id {$USER->id} in context {$this->restricted_context->id}.
 */
class {$classname} {
{$methods}
}
EOD;
        // Load the virtual class definition into memory.
        eval($code);
    }
开发者ID:rushi963,项目名称:moodle,代码行数:73,代码来源:lib.php

示例11: load_function_info

 /**
  * Fetches the function description from database,
  * verifies user is allowed to use this function and
  * loads all paremeters and return descriptions.
  * @return void
  */
 protected function load_function_info()
 {
     global $DB, $USER, $CFG;
     if (empty($this->functionname)) {
         throw new invalid_parameter_exception('Missing function name');
     }
     // function must exist
     $function = external_function_info($this->functionname);
     if ($this->restricted_serviceid) {
         $params = array('sid1' => $this->restricted_serviceid, 'sid2' => $this->restricted_serviceid);
         $wscond1 = 'AND s.id = :sid1';
         $wscond2 = 'AND s.id = :sid2';
     } else {
         $params = array();
         $wscond1 = '';
         $wscond2 = '';
     }
     // now let's verify access control
     // now make sure the function is listed in at least one service user is allowed to use
     // allow access only if:
     //  1/ entry in the external_services_users table if required
     //  2/ validuntil not reached
     //  3/ has capability if specified in service desc
     //  4/ iprestriction
     $sql = "SELECT s.*, NULL AS iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)\n                 WHERE s.enabled = 1 {$wscond1}\n\n                 UNION\n\n                SELECT s.*, su.iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)\n                  JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)\n                 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now {$wscond2}";
     $params = array_merge($params, array('userid' => $USER->id, 'name1' => $function->name, 'name2' => $function->name, 'now' => time()));
     $rs = $DB->get_recordset_sql($sql, $params);
     // now make sure user may access at least one service
     $remoteaddr = getremoteaddr();
     $allowed = false;
     foreach ($rs as $service) {
         if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
             continue;
             // cap required, sorry
         }
         if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
             continue;
             // wrong request source ip, sorry
         }
         $allowed = true;
         break;
         // one service is enough, no need to continue
     }
     $rs->close();
     if (!$allowed) {
         throw new webservice_access_exception('Access to external function not allowed');
     }
     // we have all we need now
     $this->function = $function;
 }
开发者ID:vuchannguyen,项目名称:web,代码行数:56,代码来源:lib.php

示例12: require_subnet

 /**
  * require_subnet
  *
  * @return xxx
  */
 function require_subnet()
 {
     if (!$this->subnet) {
         return false;
     }
     if (address_in_subnet(getremoteaddr(), $this->subnet)) {
         return false;
     }
     // user's IP address is missing or does not match required subnet mask
     return get_string('subnetwrong', 'quiz');
 }
开发者ID:hapaxapah,项目名称:moodle-mod_hotpot,代码行数:16,代码来源:locallib.php

示例13: load_function_info

 /**
  * Fetches the function description from database,
  * verifies user is allowed to use this function and
  * loads all paremeters and return descriptions.
  * @return void
  */
 protected function load_function_info()
 {
     global $USER;
     if (empty($this->functionname)) {
         throw new WebserviceInvalidParameterException(get_string('missingfuncname', 'webserivce'));
     }
     // function must exist
     $function = webservice_function_info($this->functionname);
     if (!$function) {
         throw new WebserviceAccessException(get_string('accessextfunctionnotconf', 'auth.webservice'));
     }
     // first ofall get a complete list of services user is allowed to access
     if ($this->restricted_serviceid) {
         $wscond1 = 'AND s.id = ? ';
         $wscond2 = 'AND s.id = ? ';
     } else {
         $wscond1 = '';
         $wscond2 = '';
     }
     // now let's verify access control
     // now make sure the function is listed in at least one service user is allowed to use
     // allow access only if:
     //  1/ entry in the external_services_users table if required
     //  2/ validuntil not reached
     //  3/ has capability if specified in service desc
     //  4/ iprestriction
     $sql = "SELECT s.*, NULL AS iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND (s.restrictedusers = ? OR s.tokenusers = ?) AND sf.functionname = ?)\n                 WHERE s.enabled = ? {$wscond1}\n\n                 UNION\n\n                SELECT s.*, su.iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = ? AND sf.functionname = ?)\n                  JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = ?)\n                 WHERE s.enabled = ? AND su.validuntil IS NULL OR su.validuntil < ? {$wscond2}";
     $params = array(0, 1, $function->name, 1);
     $wscond1 && ($params[] = $this->restricted_serviceid);
     $params[] = 1;
     $params[] = $function->name;
     $params[] = $USER->get('id');
     $params[] = 1;
     $params[] = time();
     $wscond2 && ($params[] = $this->restricted_serviceid);
     $rs = get_recordset_sql($sql, $params);
     // now make sure user may access at least one service
     $remoteaddr = getremoteaddr();
     $allowed = false;
     $serviceids = array();
     foreach ($rs as $service) {
         $serviceids[] = $service['id'];
         if ($service['iprestriction'] and !address_in_subnet($remoteaddr, $service['iprestriction'])) {
             // wrong request source ip, sorry
             continue;
         }
         $allowed = true;
         // one service is enough, no need to continue
         break;
     }
     $rs->close();
     if (!$allowed) {
         throw new WebserviceAccessException(get_string('accesstofunctionnotallowed', 'auth.webservice', $this->functionname));
     }
     // now get the list of all functions - this triggers the stashing of
     // functions in the context
     $wsmanager = new webservice();
     $functions = $wsmanager->get_external_functions($serviceids);
     // we have all we need now
     $this->function = $function;
 }
开发者ID:rboyatt,项目名称:mahara,代码行数:67,代码来源:lib.php

示例14: external_generate_token_for_current_user

/**
 * Generate or return an existing token for the current authenticated user.
 * This function is used for creating a valid token for users authenticathing via login/token.php or admin/tool/mobile/launch.php.
 *
 * @param stdClass $service external service object
 * @return stdClass token object
 * @since Moodle 3.2
 * @throws moodle_exception
 */
function external_generate_token_for_current_user($service)
{
    global $DB, $USER;
    core_user::require_active_user($USER, true, true);
    // Check if there is any required system capability.
    if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance())) {
        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', '', $service->shortname);
        }
        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.
    $conditions = array('userid' => $USER->id, 'externalserviceid' => $service->id, 'tokentype' => EXTERNAL_TOKEN_PERMANENT);
    $tokens = $DB->get_records('external_tokens', $conditions, 'timecreated ASC');
    // 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)) {
            if (!\core\session\manager::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 is not valid anymore.
        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 {
        $context = context_system::instance();
        $isofficialservice = $service->shortname == MOODLE_OFFICIAL_MOBILE_SERVICE;
        if ($isofficialservice and has_capability('moodle/webservice:createmobiletoken', $context) or !is_siteadmin($USER) && has_capability('moodle/webservice:createtoken', $context)) {
            // Create a new token.
            $token = new stdClass();
            $token->token = md5(uniqid(rand(), 1));
            $token->userid = $USER->id;
            $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
            $token->contextid = context_system::instance()->id;
            $token->creatorid = $USER->id;
            $token->timecreated = time();
            $token->externalserviceid = $service->id;
            // MDL-43119 Token valid for 3 months (12 weeks).
            $token->validuntil = $token->timecreated + 12 * WEEKSECS;
            $token->iprestriction = null;
            $token->sid = null;
            $token->lastaccess = null;
            // Generate the private token, it must be transmitted only via https.
            $token->privatetoken = random_string(64);
            $token->id = $DB->insert_record('external_tokens', $token);
            $eventtoken = clone $token;
            $eventtoken->privatetoken = null;
            $params = array('objectid' => $eventtoken->id, 'relateduserid' => $USER->id, 'other' => array('auto' => true));
            $event = \core\event\webservice_token_created::create($params);
            $event->add_record_snapshot('external_tokens', $eventtoken);
            $event->trigger();
        } else {
            throw new moodle_exception('cannotcreatetoken', 'webservice', '', $service->shortname);
        }
    }
    return $token;
}
开发者ID:lucaboesch,项目名称:moodle,代码行数:94,代码来源:externallib.php

示例15: load_function_info

 /**
  * Fetches the function description from database,
  * verifies user is allowed to use this function and
  * loads all paremeters and return descriptions.
  */
 protected function load_function_info()
 {
     global $DB, $USER, $CFG;
     if (empty($this->functionname)) {
         throw new invalid_parameter_exception('Missing function name');
     }
     // function must exist
     $function = external_function_info($this->functionname);
     if ($this->restricted_serviceid) {
         $params = array('sid1' => $this->restricted_serviceid, 'sid2' => $this->restricted_serviceid);
         $wscond1 = 'AND s.id = :sid1';
         $wscond2 = 'AND s.id = :sid2';
     } else {
         $params = array();
         $wscond1 = '';
         $wscond2 = '';
     }
     // now let's verify access control
     // now make sure the function is listed in at least one service user is allowed to use
     // allow access only if:
     //  1/ entry in the external_services_users table if required
     //  2/ validuntil not reached
     //  3/ has capability if specified in service desc
     //  4/ iprestriction
     $sql = "SELECT s.*, NULL AS iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)\n                 WHERE s.enabled = 1 {$wscond1}\n\n                 UNION\n\n                SELECT s.*, su.iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)\n                  JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)\n                 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) {$wscond2}";
     $params = array_merge($params, array('userid' => $USER->id, 'name1' => $function->name, 'name2' => $function->name, 'now' => time()));
     $rs = $DB->get_recordset_sql($sql, $params);
     // now make sure user may access at least one service
     $remoteaddr = getremoteaddr();
     $allowed = false;
     foreach ($rs as $service) {
         if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
             continue;
             // cap required, sorry
         }
         if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
             continue;
             // wrong request source ip, sorry
         }
         $allowed = true;
         break;
         // one service is enough, no need to continue
     }
     $rs->close();
     if (!$allowed) {
         throw new webservice_access_exception('Access to the function ' . $this->functionname . '() is not allowed.
                  There could be multiple reasons for this:
                  1. The service linked to the user token does not contain the function.
                  2. The service is user-restricted and the user is not listed.
                  3. The service is IP-restricted and the user IP is not listed.
                  4. The service is time-restricted and the time has expired.
                  5. The token is time-restricted and the time has expired.
                  6. The service requires a specific capability which the user does not have.
                  7. The function is called with username/password (no user token is sent)
                  and none of the services has the function to allow the user.
                  These settings can be found in Administration > Site administration
                  > Plugins > Web services > External services and Manage tokens.');
     }
     // we have all we need now
     $this->function = $function;
 }
开发者ID:alanaipe2015,项目名称:moodle,代码行数:66,代码来源:lib.php


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