Moodle PHP Documentation 4.2
Moodle 4.2.8 (Build: 20240610) (2d41ac46f45)
core_webservice

Namespaces

namespace  core_external
  
 
namespace  core_webservice
  
 
namespace  core_webservice\privacy
  
 

Classes

class  behat_core_webservice_generator
 
class  core_course_create_categories_testclient_form
 Form class for create_categories() web service function test. More...
 
class  core_course_delete_categories_testclient_form
 Form class for delete_categories() web service function test. More...
 
class  core_course_update_categories_testclient_form
 Form class for create_categories() web service function test. More...
 
class  core_external\external_format_value
 
class  core_external\util
 
class  core_fetch_notifications_testclient_form
 Test class for WS function core_fetch_notifications. More...
 
class  core_get_string_testclient_form
 Test class for WS function core_get_string. More...
 
class  core_webservice\privacy\provider
 
class  core_webservice\token_filter
 Form allowing to filter displayed tokens. More...
 
class  core_webservice\token_form
 Form to create and edit a web service token. More...
 
class  core_webservice\token_table
 Class for the displaying the participants table. More...
 
class  core_webservice_external
 
class  core_webservice_generator
 
class  core_webservice_get_site_info_testclient_form
 Test class for WS function get_site_info. More...
 
class  core_webservice_renderer
 
class  externallib_advanced_testcase
 
class  webservice
 General web service library. More...
 
class  webservice_access_exception
 Exception indicating access control problem in web service call This exception should return general errors about web service setup. More...
 
class  webservice_server
 Abstract web service base class. More...
 
interface  webservice_server_interface
 Mandatory interface for all web service protocol classes. More...
 
class  webservice_test_client_base_form
 
class  webservice_test_client_form
 
interface  webservice_test_client_interface
 Mandatory interface for all test client classes. More...
 

Functions

 webservice_access_exception::__construct ($debuginfo)
 Constructor.
 
 webservice_server::__construct ($authmethod)
 Constructor.
 
 webservice::add_external_function_to_service ($functionname, $serviceid)
 Add a function to a service.
 
 webservice::add_external_service ($service)
 Add a service It generates the timecreated field automatically.
 
 webservice::add_ws_authorised_user ($user)
 Allow user to call a service.
 
 webservice_server::authenticate_by_token ($tokentype)
 User authentication by token.
 
 webservice::authenticate_user ($token)
 Authenticate user (used by download/upload file scripts)
 
 webservice_server::authenticate_user ()
 Authenticate user using username+password or token.
 
 webservice::delete_service ($serviceid)
 Delete a service Also delete function references and authorised user references.
 
 webservice::delete_user_ws_token ($tokenid)
 Delete a token.
 
static webservice::delete_user_ws_tokens ($userid)
 Delete all the tokens belonging to a user.
 
 external_create_service_token ($servicename, $contextid)
 Create and return a session linked token.
 
 external_delete_descriptions ($component)
 Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
 
 external_format_string ($str, $context, $striplinks=true, $options=[])
 Format the string to be returned properly as requested by the either the web service server, either by an internally call.
 
 external_format_text ($text, $textformat, $context, $component=null, $filearea=null, $itemid=null, $options=null)
 Format the text to be returned properly as requested by the either the web service server, either by an internally call.
 
 external_generate_token ($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction='')
 Generate a token.
 
 external_generate_token_for_current_user ($service)
 Generate or return an existing token for the current authenticated user.
 
 external_log_token_request ($token)
 Set the last time a token was sent and trigger the core\event\webservice_token_sent event.
 
 external_validate_format ($format)
 Validate text field format against known FORMAT_XXX.
 
 webservice::generate_user_ws_tokens ($userid)
 Generate all tokens of a specific user.
 
static webservice::get_active_tokens ($userid)
 Return a list with all the valid user tokens for the given user, it only excludes expired tokens.
 
 webservice::get_created_by_user_ws_token ($userid, $tokenid)
 Return a token that has been created by the user (i.e.
 
 webservice::get_external_function_by_id ($functionid, $strictness=IGNORE_MISSING)
 Get an external function for a given function id.
 
 webservice::get_external_functions ($serviceids)
 Get the functions list of a service list (by id)
 
 webservice::get_external_functions_by_enabled_services ($serviceshortnames, $enabledonly=true)
 Get the functions of a service list (by shortname).
 
 webservice::get_external_service_by_id ($serviceid, $strictness=IGNORE_MISSING)
 Get an external service for a given service id.
 
 webservice::get_external_service_by_shortname ($shortname, $strictness=IGNORE_MISSING)
 Get an external service for a given shortname.
 
 webservice::get_missing_capabilities_by_users (array $users, int $serviceid)
 Get missing user capabilities for the given service's functions.
 
 webservice::get_not_associated_external_functions ($serviceid)
 Get functions not included in a service.
 
 webservice::get_service_required_capabilities ($serviceid)
 Get list of required capabilities of a service, sorted by functions Example of returned value: Array ( [core_group_create_groups] => Array ( [0] => moodle/course:managegroups )
 
 webservice::get_token_by_id ($tokenid)
 Return a database token record for a token id.
 
 webservice::get_token_by_id_with_details ($tokenid)
 Return a token of an arbitrary user by tokenid, including details of the associated user and the service name.
 
 webservice::get_user_capabilities ($userid)
 Get user capabilities (with context) Only useful for documentation purpose WARNING: do not use this "broken" function.
 
 webservice::get_user_ws_token ($token)
 Get a full database token record for a given token value.
 
 webservice::get_user_ws_tokens ($userid)
 Return all tokens of a specific user.
 
 webservice::get_ws_authorised_user ($serviceid, $userid)
 Return an authorised user with their options (ip/timecreated / validuntil...)
 
 webservice::get_ws_authorised_users ($serviceid)
 Return list of allowed users with their options (ip/timecreated / validuntil...) for a given service.
 
 webservice::remove_external_function_from_service ($functionname, $serviceid)
 Remove a function from a service.
 
 webservice::remove_ws_authorised_user ($user, $serviceid)
 Disallow a user to call a service.
 
 webservice_server_interface::run ()
 Process request from client.
 
 webservice::service_function_exists ($functionname, $serviceid)
 Test whether an external function is already linked to a service.
 
 webservice_server::set_web_service_call_settings ()
 Intercept some moodlewssettingXXX $_GET and $_POST parameter that are related to the web service call and are not the function parameters.
 
 webservice_test_client_interface::simpletest ($serverurl, $function, $params)
 Execute test client WS request.
 
 webservice::update_external_service ($service)
 Update a service It modifies the timemodified automatically.
 
static webservice::update_token_lastaccess ($token, int $time=0)
 Updates the last access time for a token.
 
 webservice::update_ws_authorised_user ($user)
 Update allowed user settings (ip restriction, valid until...)
 
 webservice_protocol_is_enabled ($protocol)
 Check if a protocol is enabled.
 

Variables

integer webservice_server::$authmethod
 Authentication method one of WEBSERVICE_AUTHMETHOD_*.
 
global $CFG
 
 $functions
 
string webservice_server::$password = null
 Password of the local user.
 
stdClass webservice_server::$restricted_context
 Restricted context.
 
int webservice_server::$restricted_serviceid = null
 Restrict call to one service id.
 
 $services
 
string webservice_server::$token = null
 Authentication token.
 
int webservice_server::$userid = null
 The local user.
 
string webservice_server::$username = null
 Name of local user.
 
string webservice_server::$wsname = null
 Name of the web server plugin.
 
int const webservice::TOKEN_LASTACCESS_UPDATE_SECS = 60
 Only update token last access once per this many seconds.
 
const WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN 1
 WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN - most common token authentication (external app, mobile app...)
 
const WEBSERVICE_AUTHMETHOD_SESSION_TOKEN 2
 WEBSERVICE_AUTHMETHOD_SESSION_TOKEN - token for embedded application (requires Moodle session)
 
const WEBSERVICE_AUTHMETHOD_USERNAME 0
 WEBSERVICE_AUTHMETHOD_USERNAME - username/password authentication (also called simple authentication)
 

Detailed Description

Function Documentation

◆ __construct() [1/2]

webservice_access_exception::__construct ( $debuginfo)

Constructor.

Parameters
string$debuginfothe debug info

◆ __construct() [2/2]

webservice_server::__construct ( $authmethod)

Constructor.

Parameters
integer$authmethodauthentication method one of WEBSERVICE_AUTHMETHOD_*

◆ add_external_function_to_service()

webservice::add_external_function_to_service ( $functionname,
$serviceid )

Add a function to a service.

Parameters
string$functionnamefunction name
int$serviceidservice id

◆ add_external_service()

webservice::add_external_service ( $service)

Add a service It generates the timecreated field automatically.

Parameters
stdClass$service
Return values
serviceidinteger

◆ add_ws_authorised_user()

webservice::add_ws_authorised_user ( $user)

Allow user to call a service.

Parameters
stdClass$usera user

◆ authenticate_by_token()

webservice_server::authenticate_by_token ( $tokentype)
protected

User authentication by token.

Parameters
string$tokentypetoken type (EXTERNAL_TOKEN_EMBEDDED or EXTERNAL_TOKEN_PERMANENT)
Return values
stdClassthe authenticated user
Exceptions
webservice_access_exception

◆ authenticate_user() [1/2]

webservice::authenticate_user ( $token)

Authenticate user (used by download/upload file scripts)

Parameters
string$token
Return values
array- contains the authenticated user, token and service objects

◆ authenticate_user() [2/2]

webservice_server::authenticate_user ( )
protected

Authenticate user using username+password or token.

This function sets up $USER global. It is safe to use has_capability() after this. This method also verifies user is allowed to use this server.

◆ delete_service()

webservice::delete_service ( $serviceid)

Delete a service Also delete function references and authorised user references.

Parameters
int$serviceidservice id

◆ delete_user_ws_token()

webservice::delete_user_ws_token ( $tokenid)

Delete a token.

Parameters
int$tokenidtoken id

◆ delete_user_ws_tokens()

static webservice::delete_user_ws_tokens ( $userid)
static

Delete all the tokens belonging to a user.

Parameters
int$useridthe user id whose tokens must be deleted

◆ external_create_service_token()

external_create_service_token ( $servicename,
$contextid )

Create and return a session linked token.

Token to be used for html embedded client apps that want to communicate with the Moodle server through web services. The token is linked to the current session for the current page request. It is expected this will be called in the script generating the html page that is embedding the client app and that the returned token will be somehow passed into the client app being embedded in the page.

Parameters
string$servicenamename of the web service. Service name as defined in db/services.php
int$contextcontext within which the web service can operate.
Return values
intreturns token id.
Since
Moodle 2.0

◆ external_delete_descriptions()

external_delete_descriptions ( $component)

Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.

Parameters
string$componentname of component (moodle, etc.)

◆ external_format_string()

external_format_string ( $str,
$context,
$striplinks = true,
$options = [] )

Format the string to be returned properly as requested by the either the web service server, either by an internally call.

The caller can change the format (raw) with the external_settings singleton All web service servers must set this singleton when parsing the $_GET and $_POST.

Options are the same that in   with some changes:
     filter      : Can be set to false to force filters off, else observes  .
Parameters
string$strThe string to be filtered. Should be plain text, expect possibly for multilang tags.
boolean$striplinksTo strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
context | int$contextoridThe id of the context for the string or the context (affects filters).
array$optionsoptions array/object or courseid
Return values
stringtext
Since
Moodle 3.0

◆ external_format_text()

external_format_text ( $text,
$textformat,
$context,
$component = null,
$filearea = null,
$itemid = null,
$options = null )

Format the text to be returned properly as requested by the either the web service server, either by an internally call.

The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton All web service servers must set this singleton when parsing the $_GET and $_POST.

Options are the same that in   with some changes in defaults to provide backwards compatibility:
     trusted     :   If true the string won't be cleaned. Default false.
     noclean     :   If true the string won't be cleaned only if trusted is also true. Default false.
     nocache     :   If true the string will not be cached and will be formatted every call. Default false.
     filter      :   Can be set to false to force filters off, else observes  .
     para        :   If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
                     Default changed because div tags are not commonly needed.
     newlines    :   If true then lines newline breaks will be converted to HTML newline breaks. Default true.
     context     :   Not used! Using contextid parameter instead.
     overflowdiv :   If set to true the formatted text will be encased in a div with the class no-overflow before being
                     returned. Default false.
     allowid     :   If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
                     format_text) true. Default changed id attributes are commonly needed.
     blanktarget :   If true all  tags will have target="_blank" added unless target is explicitly specified.
Parameters
string$textThe content that may contain ULRs in need of rewriting.
int$textformatThe text format.
context | int$contextThis parameter and the next two identify the file area to use.
string$component
string$fileareahelps identify the file area.
int$itemidhelps identify the file area.
object/array$options text formatting options
Return values
arraytext + textformat
Since
Moodle 2.3
Moodle 3.2 component, filearea and itemid are optional parameters

◆ external_generate_token()

external_generate_token ( $tokentype,
$serviceorid,
$userid,
$contextorid,
$validuntil = 0,
$iprestriction = '' )

Generate a token.

Parameters
string$tokentypeEXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
stdClass | int$serviceoridservice linked to the token
int$useriduser linked to the token
stdClass | int$contextorid
int$validuntildate when the token expired
string$iprestrictionallowed ip - if 0 or empty then all ips are allowed
Return values
stringgenerated token
Since
Moodle 2.0

◆ external_generate_token_for_current_user()

external_generate_token_for_current_user ( $service)

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.

Parameters
stdClass$serviceexternal service object
Return values
stdClasstoken object
Since
Moodle 3.2

◆ external_log_token_request()

external_log_token_request ( $token)

Set the last time a token was sent and trigger the core\event\webservice_token_sent event.

This function is used when a token is generated by the user via login/token.php or admin/tool/mobile/launch.php. In order to protect the privatetoken, we remove it from the event params.

Parameters
stdClass$tokentoken object
Since
Moodle 3.2

◆ external_validate_format()

external_validate_format ( $format)

Validate text field format against known FORMAT_XXX.

Parameters
array$formatthe format to validate
Return values
thevalidated format
Exceptions
coding_exception
Since
Moodle 2.3

◆ generate_user_ws_tokens()

webservice::generate_user_ws_tokens ( $userid)

Generate all tokens of a specific user.

Parameters
int$useriduser id

◆ get_active_tokens()

static webservice::get_active_tokens ( $userid)
static

Return a list with all the valid user tokens for the given user, it only excludes expired tokens.

Parameters
string$useriduser id to retrieve tokens from
Return values
arrayarray of token entries
Since
Moodle 3.2

◆ get_created_by_user_ws_token()

webservice::get_created_by_user_ws_token ( $userid,
$tokenid )

Return a token that has been created by the user (i.e.

to created by an admin) If no tokens exist an exception is thrown

The returned value is a stdClass: ->id token id ->token ->firstname user firstname ->lastname ->name service name

Parameters
int$useriduser id
int$tokenidtoken id
Return values
stdClass

◆ get_external_function_by_id()

webservice::get_external_function_by_id ( $functionid,
$strictness = IGNORE_MISSING )

Get an external function for a given function id.

Parameters
int$functionidfunction id
int$strictnessIGNORE_MISSING, MUST_EXIST...
Return values
stdClassexternal function

◆ get_external_functions()

webservice::get_external_functions ( $serviceids)

Get the functions list of a service list (by id)

Parameters
array$serviceidsservice ids
Return values
arrayof functions

◆ get_external_functions_by_enabled_services()

webservice::get_external_functions_by_enabled_services ( $serviceshortnames,
$enabledonly = true )

Get the functions of a service list (by shortname).

It can return only enabled functions if required.

Parameters
array$serviceshortnamesservice shortnames
bool$enabledonlyif true then only return functions for services that have been enabled
Return values
arrayfunctions

◆ get_external_service_by_id()

webservice::get_external_service_by_id ( $serviceid,
$strictness = IGNORE_MISSING )

Get an external service for a given service id.

Parameters
int$serviceidservice id
int$strictnessIGNORE_MISSING, MUST_EXIST...
Return values
stdClassexternal service

◆ get_external_service_by_shortname()

webservice::get_external_service_by_shortname ( $shortname,
$strictness = IGNORE_MISSING )

Get an external service for a given shortname.

Parameters
string$shortnameservice shortname
int$strictnessIGNORE_MISSING, MUST_EXIST...
Return values
stdClassexternal service

◆ get_missing_capabilities_by_users()

webservice::get_missing_capabilities_by_users ( array $users,
int $serviceid )

Get missing user capabilities for the given service's functions.

Every external function can declare some required capabilities to allow for easier setup of the web services. However, that is supposed to be used for informational admin report only. There is no automatic evaluation of the declared capabilities and the context of the capability evaluation is ignored. Also, actual capability evaluation is much more complex as it allows for overrides etc.

Returned are capabilities that the given users do not seem to have assigned anywhere at the site and that should be checked by the admin.

Do not use this method for anything else, particularly not for any security related checks. See MDL-29962 for the background of why we have this - there are arguments for dropping this feature completely.

Parameters
array$usersList of users to check, consisting of objects, arrays or integer ids.
int$serviceidThe id of the external service to check.
Return values
arrayList of missing capabilities: (int)userid => array of (string)capabilitynames

◆ get_not_associated_external_functions()

webservice::get_not_associated_external_functions ( $serviceid)

Get functions not included in a service.

Parameters
int$serviceidservice id
Return values
arrayfunctions

◆ get_service_required_capabilities()

webservice::get_service_required_capabilities ( $serviceid)

Get list of required capabilities of a service, sorted by functions Example of returned value: Array ( [core_group_create_groups] => Array ( [0] => moodle/course:managegroups )

[core_enrol_get_enrolled_users] => Array ( [0] => moodle/user:viewdetails [1] => moodle/user:viewhiddendetails [2] => moodle/course:useremail [3] => moodle/user:update [4] => moodle/site:accessallgroups ) )

Parameters
int$serviceidservice id
Return values
array

◆ get_token_by_id()

webservice::get_token_by_id ( $tokenid)

Return a database token record for a token id.

Parameters
int$tokenidtoken id
Return values
objecttoken

◆ get_token_by_id_with_details()

webservice::get_token_by_id_with_details ( $tokenid)

Return a token of an arbitrary user by tokenid, including details of the associated user and the service name.

If no tokens exist an exception is thrown

The returned value is a stdClass: ->id token id ->token ->firstname user firstname ->lastname ->name service name

Parameters
int$tokenidtoken id
Return values
stdClass

◆ get_user_capabilities()

webservice::get_user_capabilities ( $userid)

Get user capabilities (with context) Only useful for documentation purpose WARNING: do not use this "broken" function.

It was created in the goal to display some capabilities required by users. In theory we should not need to display this kind of information as the front end does not display it itself. In pratice, admins would like the info, for more info you can follow: MDL-29962

Deprecated
since Moodle 3.11 in MDL-67748 without a replacement.
Todo
MDL-70187 Please delete this method completely in Moodle 4.3, thank you.
Parameters
int$useriduser id
Return values
array

◆ get_user_ws_token()

webservice::get_user_ws_token ( $token)

Get a full database token record for a given token value.

Parameters
string$token
Exceptions
moodle_exceptionif there is multiple result

◆ get_user_ws_tokens()

webservice::get_user_ws_tokens ( $userid)

Return all tokens of a specific user.

  • the service state (enabled/disabled)
  • the authorised user mode (restricted/not restricted)
Parameters
int$useriduser id
Return values
array

◆ get_ws_authorised_user()

webservice::get_ws_authorised_user ( $serviceid,
$userid )

Return an authorised user with their options (ip/timecreated / validuntil...)

Parameters
int$serviceidthe service id to search against
int$useridthe user to search against
Return values
stdClass

◆ get_ws_authorised_users()

webservice::get_ws_authorised_users ( $serviceid)

Return list of allowed users with their options (ip/timecreated / validuntil...) for a given service.

Parameters
int$serviceidthe service id to search against
Return values
array\$users

◆ remove_external_function_from_service()

webservice::remove_external_function_from_service ( $functionname,
$serviceid )

Remove a function from a service.

Parameters
string$functionnamefunction name
int$serviceidservice id

◆ remove_ws_authorised_user()

webservice::remove_ws_authorised_user ( $user,
$serviceid )

Disallow a user to call a service.

Parameters
stdClass$usera user
int$serviceid

◆ service_function_exists()

webservice::service_function_exists ( $functionname,
$serviceid )

Test whether an external function is already linked to a service.

Parameters
string$functionnamefunction name
int$serviceidservice id
Return values
booltrue if a matching function exists for the service, else false.
Exceptions
dml_exceptionif error

◆ simpletest()

webservice_test_client_interface::simpletest ( $serverurl,
$function,
$params )

Execute test client WS request.

Parameters
string$serverurlserver url (including the token param)
string$functionweb service function name
array$paramsparameters of the web service function
Return values
mixed

Implemented in webservice_rest_test_client, and webservice_soap_test_client.

◆ update_external_service()

webservice::update_external_service ( $service)

Update a service It modifies the timemodified automatically.

Parameters
stdClass$service

◆ update_token_lastaccess()

static webservice::update_token_lastaccess ( $token,
int $time = 0 )
static

Updates the last access time for a token.

Parameters
stdClass$tokenToken object (must include id, lastaccess fields)
int$timeTime of access (0 = use current time)
Exceptions
dml_exceptionIf database error

◆ update_ws_authorised_user()

webservice::update_ws_authorised_user ( $user)

Update allowed user settings (ip restriction, valid until...)

Parameters
stdClass$user

◆ webservice_protocol_is_enabled()

webservice_protocol_is_enabled ( $protocol)

Check if a protocol is enabled.

Parameters
string$protocolname of WS protocol ('rest', 'soap', ...)
Return values
booltrue if the protocol is enabled

Variable Documentation

◆ $functions

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

◆ $services

$services
Initial value:
= array(
'Moodle mobile web service' => array(
'functions' => array(),
'enabled' => 0,
'restrictedusers' => 0,
'downloadfiles' => 1,
'uploadfiles' => 1
),
)
const MOODLE_OFFICIAL_MOBILE_SERVICE
Moodle mobile app service name.
Definition moodlelib.php:530

◆ TOKEN_LASTACCESS_UPDATE_SECS

int const webservice::TOKEN_LASTACCESS_UPDATE_SECS = 60

Only update token last access once per this many seconds.

(This constant controls update of the external tokens last access field. There is a similar define LASTACCESS_UPDATE_SECS which controls update of the web site last access fields.)