Moodle PHP Documentation 4.3
Moodle 4.3.5 (Build: 20240610) (7dcfaa79f78)
core\oauth2\client Class Reference

Configurable oauth2 client class. More...

Inheritance diagram for core\oauth2\client:
oauth2_client curl core\oauth2\client\clever core\oauth2\client\linkedin core_badges\oauth2\client repository_dropbox\dropbox

Public Member Functions

 __construct (issuer $issuer, $returnurl, $scopesrequired, $system=false, $autorefresh=false)
 Constructor.
 
 build_post_data ($params)
 Given an array of name value pairs - build a valid HTTP POST application/x-www-form-urlencoded string.
 
 cleanopt ()
 Reset http method.
 
 delete ($url, $param=array(), $options=array())
 HTTP DELETE method.
 
 download ($requests, $options=array())
 Download multiple files in parallel.
 
 download_one ($url, $params, $options=array())
 Downloads one file and writes it to the specified file handler.
 
 get ($url, $params=array(), $options=array())
 HTTP GET method.
 
 get_accesstoken ()
 Get access token object.
 
 get_additional_login_parameters ()
 Override to append additional params to a authentication request.
 
 get_clientid ()
 Get the client ID.
 
 get_clientsecret ()
 Get the client secret.
 
 get_errno ()
 Get curl error code.
 
 get_info ()
 Get curl information.
 
 get_issuer ()
 Get the oauth2 issuer for this client.
 
 get_login_url ()
 Returns the login link for this oauth request.
 
 get_raw_response ()
 Get raw HTTP Response Headers.
 
 get_raw_userinfo ()
 Fetch the user info from the user info endpoint.
 
 get_refresh_token ()
 Get a refresh token!!!
 
 get_security ()
 Returns the current curl security helper.
 
 get_userinfo ()
 Fetch the user info from the user info endpoint and map all the fields back into moodle fields.
 
 getResponse ()
 Get HTTP Response Headers.
 
 head ($url, $options=array())
 HTTP HEAD method.
 
 is_logged_in ()
 Override which in addition to auth code upgrade, also attempts to exchange a refresh token for an access token.
 
 log_out ()
 Override which, in addition to deleting access tokens, also deletes any stored refresh token.
 
 options ($url, $options=array())
 HTTP OPTIONS method.
 
 patch ($url, $params='', $options=array())
 HTTP PATCH method.
 
 post ($url, $params='', $options=array())
 HTTP POST method.
 
 put ($url, $params=array(), $options=array())
 HTTP PUT method.
 
 resetcookie ()
 Reset Cookie.
 
 resetHeader ()
 Resets the HTTP Request headers (to prepare for the new request)
 
 resetopt ()
 Resets the CURL options that have already been set.
 
 set_security ($securityobject)
 Sets the curl security helper.
 
 setHeader ($header)
 Set HTTP Request Header.
 
 setopt ($options=array())
 Set curl options.
 
 trace ($url, $options=array())
 HTTP TRACE method.
 
 upgrade_refresh_token (system_account $systemaccount)
 Upgrade a refresh token from oauth 2.0 to an access token, for system clients only.
 
 upgrade_token ($code)
 Override which upgrades the authorization code to an access token and stores any refresh token in the DB.
 

Static Public Member Functions

static callback_url ()
 Callback url where the request is returned to.
 
static get_cacert ()
 Get the location of ca certificates.
 
static mock_response ($response)
 For use only in unit tests - we can pre-set the next curl response.
 
static strip_double_headers ($input)
 When using a proxy, an additional HTTP response code may appear at the start of the header.
 

Public Attributes

array $_tmp_file_post_params = []
 temporary params value if the value is not belongs to class stored_file.
 
curl_cache false $cache = false
 Caches http request contents.
 
bool $emulateredirects = null
 Perform redirects at PHP level instead of relying on native cURL functionality.
 
int $errno
 error code
 
string $error
 error
 
array $header = array()
 http header
 
array $info
 cURL information
 
bool $proxy = null
 Uses proxy, null means automatic based on URL.
 
array $rawresponse = array()
 Raw response headers, needed for BC in download_file_content().
 
array $response = array()
 http's response
 
string $version = '0.4 dev'
 library version
 

Protected Member Functions

 auth_url ()
 Returns the auth url for OAuth 2.0 request.
 
 can_autorefresh ()
 Whether this client should automatically exchange a refresh token for an access token as part of login checks.
 
 check_securityhelper_blocklist (string $url)
 check_securityhelper_blocklist.
 
 exchange_refresh_token (string $refreshtoken)
 Attempt to exchange a refresh token for a new access token.
 
 get_login_scopes ()
 Override to change the scopes requested with an authentiction request.
 
 get_stored_token ()
 Retrieve a stored token from session (user accounts) or database (system accounts).
 
 get_tokenname ()
 We want a unique key for each issuer / and a different key for system vs user oauth.
 
 get_userinfo_mapping ()
 Get a list of the mapping user fields in an associative array.
 
 map_userinfo_to_fields (stdClass $userinfo)
 Maps the oauth2 response to userfields.
 
 multi ($requests, $options=array())
 Multiple HTTP Requests This function could run multi-requests in parallel.
 
 request ($url, $options=array())
 Single HTTP Request.
 
 request ($url, $options=array(), $acceptheader='application/json')
 Make a HTTP request, adding the access token we have.
 
 reset_request_state_vars ()
 Helper function to reset the request state vars.
 
 store_token ($token)
 Store a token between requests.
 
 store_user_refresh_token (stdClass $token)
 Store the user's refresh token for later use.
 
 token_url ()
 Returns the token url for OAuth 2.0 request.
 
 use_http_get ()
 Should HTTP GET be used instead of POST? Some APIs do not support POST and want oauth to use GET instead (with the auth_token passed as a GET param).
 

Protected Attributes

stdClass $accesstoken = null
 $accesstoken access token object
 
bool $autorefresh = false
 $autorefresh whether this client will use a refresh token to automatically renew access tokens.
 
bool $basicauth = false
 basicauth
 
array $rawuserinfo = []
 $rawuserinfo Keep rawuserinfo from .
 
string $refreshtoken = ''
 $refreshtoken refresh token string
 
string $scope = ''
 $scope of the authentication request
 
bool $system = false
 $system
 

Detailed Description

Configurable oauth2 client class.

URLs come from DB and access tokens from either DB (system accounts) or session (users').

License
http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later

Constructor & Destructor Documentation

◆ __construct()

core\oauth2\client::__construct ( issuer $issuer,
$returnurl,
$scopesrequired,
$system = false,
$autorefresh = false )

Constructor.

Parameters
issuer$issuer
moodle_url | null$returnurl
string$scopesrequired
boolean$system
boolean$autorefreshwhether refresh_token grants are used to allow continued access across sessions.

Member Function Documentation

◆ auth_url()

core\oauth2\client::auth_url ( )
protected

Returns the auth url for OAuth 2.0 request.

Return values
stringthe auth url

Reimplemented from oauth2_client.

Reimplemented in repository_dropbox\dropbox.

◆ build_post_data()

oauth2_client::build_post_data ( $params)
inherited

Given an array of name value pairs - build a valid HTTP POST application/x-www-form-urlencoded string.

Parameters
array$paramsName / value pairs.
Return values
stringPOST data.

◆ callback_url()

static oauth2_client::callback_url ( )
staticinherited

Callback url where the request is returned to.

Return values
moodle_urlurl of callback

Reimplemented in core_badges\oauth2\client.

◆ can_autorefresh()

core\oauth2\client::can_autorefresh ( )
protected

Whether this client should automatically exchange a refresh token for an access token as part of login checks.

Return values
booltrue if supported, false otherwise.

◆ check_securityhelper_blocklist()

curl::check_securityhelper_blocklist ( string $url)
protectedinherited

check_securityhelper_blocklist.

Checks whether the given URL is blocked by checking both plugin's security helpers and core curl security helper or any curl security helper that passed to curl class constructor. If ignoresecurity is set to true, skip checking and consider the url is not blocked. This augments all installed plugin's security helpers if there is any.

Parameters
string$urlthe url to check.
Return values
string- an error message if URL is blocked or null if URL is not blocked.

◆ delete()

curl::delete ( $url,
$param = array(),
$options = array() )
inherited

HTTP DELETE method.

Parameters
string$url
array$param
array$options
Return values
bool

◆ download()

curl::download ( $requests,
$options = array() )
inherited

Download multiple files in parallel.

Calls multi() with specific download headers

$c = new curl(); $file1 = fopen('a', 'wb'); $file2 = fopen('b', 'wb'); $c->download(array( array('url'=>'http://localhost/', 'file'=>$file1), array('url'=>'http://localhost/20/', 'file'=>$file2) )); fclose($file1); fclose($file2);

or

$c = new curl(); $c->download(array( array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'), array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp') ));

Parameters
array$requestsAn array of files to request { url => url to download the file [required] file => file handler, or filepath => file path } If 'file' and 'filepath' parameters are both specified in one request, the open file handle in the 'file' parameter will take precedence and 'filepath' will be ignored.
array$optionsAn array of options to set
Return values
arrayAn array of results

◆ download_one()

curl::download_one ( $url,
$params,
$options = array() )
inherited

Downloads one file and writes it to the specified file handler.

$c = new curl(); $file = fopen('savepath', 'w'); $result = $c->download_one('http://localhost/', null, array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3)); fclose($file); $download_info = $c->get_info(); if ($result === true) { // file downloaded successfully } else { $error_text = $result; $error_code = $c->get_errno(); }

$c = new curl(); $result = $c->download_one('http://localhost/', null, array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3)); // ... see above, no need to close handle and remove file if unsuccessful

Parameters
string$url
array | null$paramskey-value pairs to be added to $url as query string
array$optionsrequest options. Must include either 'file' or 'filepath'
Return values
bool|stringtrue on success or error string on failure

◆ exchange_refresh_token()

core\oauth2\client::exchange_refresh_token ( string $refreshtoken)
protected

Attempt to exchange a refresh token for a new access token.

If successful, will return an array of token objects in the form: Array ( [access_token] => stdClass object ( [token] => 'the_token_string' [expires] => 123456789 [scope] => 'openid files etc' ) [refresh_token] => stdClass object ( [token] => 'the_refresh_token_string' [scope] => 'openid files etc' ) ) where the 'refresh_token' will only be provided if supplied by the auth server in the response.

Parameters
string$refreshtokenthe refresh token to exchange.
Return values
null|arrayarray containing access token and refresh token if provided, null if the exchange was denied.
Exceptions
moodle_exceptionif an invalid response is received or if the response contains errors.

◆ get()

curl::get ( $url,
$params = array(),
$options = array() )
inherited

HTTP GET method.

Parameters
string$url
array$params
array$options
Return values
bool

◆ get_accesstoken()

oauth2_client::get_accesstoken ( )
inherited

Get access token object.

This is just a getter to read the private property.

Return values
stdClass

◆ get_additional_login_parameters()

core\oauth2\client::get_additional_login_parameters ( )

Override to append additional params to a authentication request.

Return values
array(name value pairs).

Reimplemented from oauth2_client.

◆ get_cacert()

static curl::get_cacert ( )
staticinherited

Get the location of ca certificates.

Return values
stringabsolute file path or empty if default used

◆ get_clientid()

oauth2_client::get_clientid ( )
inherited

Get the client ID.

This is just a getter to read the private property.

Return values
string

◆ get_clientsecret()

oauth2_client::get_clientsecret ( )
inherited

Get the client secret.

This is just a getter to read the private property.

Return values
string

◆ get_errno()

curl::get_errno ( )
inherited

Get curl error code.

Return values
int

◆ get_info()

curl::get_info ( )
inherited

Get curl information.

Return values
array

◆ get_issuer()

core\oauth2\client::get_issuer ( )

Get the oauth2 issuer for this client.

Return values
core\oauth2\issuerIssuer

◆ get_login_scopes()

core\oauth2\client::get_login_scopes ( )
protected

Override to change the scopes requested with an authentiction request.

Return values
string

Reimplemented in repository_dropbox\dropbox.

◆ get_login_url()

oauth2_client::get_login_url ( )
inherited

Returns the login link for this oauth request.

Return values
moodle_urllogin url

Reimplemented in core_badges\oauth2\client.

◆ get_raw_response()

curl::get_raw_response ( )
inherited

Get raw HTTP Response Headers.

Return values
arrayof strings

◆ get_raw_userinfo()

core\oauth2\client::get_raw_userinfo ( )

Fetch the user info from the user info endpoint.

Return values
stdClass|falseMoodle user fields for the logged in user (or false if request failed)
Exceptions
moodle_exceptionif the response is empty after decoding it.

◆ get_refresh_token()

oauth2_client::get_refresh_token ( )
inherited

Get a refresh token!!!

Return values
string

◆ get_security()

curl::get_security ( )
inherited

Returns the current curl security helper.

Return values
core\files\curl_security_helperinstance.

◆ get_stored_token()

core\oauth2\client::get_stored_token ( )
protected

Retrieve a stored token from session (user accounts) or database (system accounts).

Return values
stdClass|nulltoken object

Reimplemented from oauth2_client.

Reimplemented in core_badges\oauth2\client.

◆ get_tokenname()

core\oauth2\client::get_tokenname ( )
protected

We want a unique key for each issuer / and a different key for system vs user oauth.

Return values
stringThe unique key for the session value.

Reimplemented from oauth2_client.

◆ get_userinfo()

core\oauth2\client::get_userinfo ( )

Fetch the user info from the user info endpoint and map all the fields back into moodle fields.

Return values
stdClass|falseMoodle user fields for the logged in user (or false if request failed)
Exceptions
moodle_exceptionif the response is empty after decoding it.

Reimplemented in core\oauth2\client\clever, and core\oauth2\client\linkedin.

◆ get_userinfo_mapping()

core\oauth2\client::get_userinfo_mapping ( )
protected

Get a list of the mapping user fields in an associative array.

Return values
array

◆ getResponse()

curl::getResponse ( )
inherited

Get HTTP Response Headers.

Return values
arrayof arrays

◆ head()

curl::head ( $url,
$options = array() )
inherited

HTTP HEAD method.

See also
request()
Parameters
string$url
array$options
Return values
bool

◆ is_logged_in()

core\oauth2\client::is_logged_in ( )

Override which in addition to auth code upgrade, also attempts to exchange a refresh token for an access token.

Return values
booltrue if the user is logged in as a result, false otherwise.

Reimplemented from oauth2_client.

Reimplemented in core_badges\oauth2\client.

◆ log_out()

core\oauth2\client::log_out ( )

Override which, in addition to deleting access tokens, also deletes any stored refresh token.

Reimplemented from oauth2_client.

◆ map_userinfo_to_fields()

core\oauth2\client::map_userinfo_to_fields ( stdClass $userinfo)
protected

Maps the oauth2 response to userfields.

Parameters
stdClass$userinfo
Return values
array

◆ mock_response()

static curl::mock_response ( $response)
staticinherited

For use only in unit tests - we can pre-set the next curl response.

This is useful for unit testing APIs that call external systems.

Parameters
string$response

◆ multi()

oauth2_client::multi ( $requests,
$options = array() )
protectedinherited

Multiple HTTP Requests This function could run multi-requests in parallel.

Parameters
array$requestsAn array of files to request
array$optionsAn array of options to set
Return values
arrayAn array of results

Reimplemented from curl.

◆ options()

curl::options ( $url,
$options = array() )
inherited

HTTP OPTIONS method.

Parameters
string$url
array$options
Return values
bool

◆ patch()

curl::patch ( $url,
$params = '',
$options = array() )
inherited

HTTP PATCH method.

Parameters
string$url
array | string$params
array$options
Return values
bool

◆ post()

curl::post ( $url,
$params = '',
$options = array() )
inherited

HTTP POST method.

Parameters
string$url
array | string$params
array$options
Return values
bool

◆ put()

curl::put ( $url,
$params = array(),
$options = array() )
inherited

HTTP PUT method.

Parameters
string$url
array$params
array$options
Return values
bool

◆ request() [1/2]

curl::request ( $url,
$options = array() )
protectedinherited

Single HTTP Request.

Parameters
string$urlThe URL to request
array$options
Return values
bool

◆ request() [2/2]

oauth2_client::request ( $url,
$options = array(),
$acceptheader = 'application/json' )
protectedinherited

Make a HTTP request, adding the access token we have.

Parameters
string$urlThe URL to request
array$options
mixed$acceptheadermimetype (as string) or false to skip sending an accept header.
Return values
bool

Reimplemented in google_oauth.

◆ reset_request_state_vars()

curl::reset_request_state_vars ( )
protectedinherited

Helper function to reset the request state vars.

Return values
void.

◆ set_security()

curl::set_security ( $securityobject)
inherited

Sets the curl security helper.

Parameters
core\files\curl_security_helper$securityobjectinstance/subclass of the base curl_security_helper class.
Return values
booltrue if the security helper could be set, false otherwise.

◆ setHeader()

curl::setHeader ( $header)
inherited

Set HTTP Request Header.

Parameters
array$header

◆ setopt()

curl::setopt ( $options = array())
inherited

Set curl options.

Do not use the curl constants to define the options, pass a string corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.

Parameters
array$optionsIf array is null, this function will reset the options to default value.
Return values
void
Exceptions
coding_exceptionIf an option uses constant value instead of option name.

◆ store_token()

core\oauth2\client::store_token ( $token)
protected

Store a token between requests.

Uses session named by get_tokenname for user account tokens and a database record for system account tokens.

Parameters
stdClass | null$tokentoken object to store or null to clear

Reimplemented from oauth2_client.

Reimplemented in core_badges\oauth2\client.

◆ store_user_refresh_token()

core\oauth2\client::store_user_refresh_token ( stdClass $token)
protected

Store the user's refresh token for later use.

Parameters
stdClass$tokena refresh token.

◆ strip_double_headers()

static curl::strip_double_headers ( $input)
staticinherited

When using a proxy, an additional HTTP response code may appear at the start of the header.

For example, when using https over a proxy there may be 'HTTP/1.0 200 Connection Established'. Other codes are also possible and some may come with their own headers.

If using the return value containing all headers, this function can be called to remove unwanted doubles.

Note that it is not possible to distinguish this situation from valid data unless you know the actual response part (below the headers) will not be included in this string, or else will not 'look like' HTTP headers. As a result it is not safe to call this function for general data.

Parameters
string$inputInput HTTP response
Return values
stringHTTP response with additional headers stripped if any

◆ token_url()

core\oauth2\client::token_url ( )
protected

Returns the token url for OAuth 2.0 request.

We are overriding the parent function so we get this from the configured endpoint.

Return values
stringthe auth url

Reimplemented from oauth2_client.

Reimplemented in repository_dropbox\dropbox.

◆ trace()

curl::trace ( $url,
$options = array() )
inherited

HTTP TRACE method.

Parameters
string$url
array$options
Return values
bool

◆ upgrade_refresh_token()

core\oauth2\client::upgrade_refresh_token ( system_account $systemaccount)

Upgrade a refresh token from oauth 2.0 to an access token, for system clients only.

Parameters
core\oauth2\system_account$systemaccount
Return values
booleantrue if token is upgraded succesfully

◆ upgrade_token()

core\oauth2\client::upgrade_token ( $code)

Override which upgrades the authorization code to an access token and stores any refresh token in the DB.

Parameters
string$codethe authorisation code
Return values
booltrue if the token could be upgraded
Exceptions
moodle_exception

Reimplemented from oauth2_client.

◆ use_http_get()

oauth2_client::use_http_get ( )
protectedinherited

Should HTTP GET be used instead of POST? Some APIs do not support POST and want oauth to use GET instead (with the auth_token passed as a GET param).

Return values
booltrue if GET should be used

Member Data Documentation

◆ $emulateredirects

bool curl::$emulateredirects = null
inherited

Perform redirects at PHP level instead of relying on native cURL functionality.

Always true now.


The documentation for this class was generated from the following file: