Developer Documentation

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
  • Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 37 and 311] [Versions 38 and 311] [Versions 39 and 311]

    Support for external API

    Copyright: 2009 Petr Skodak
    License: GNU GPL v3 or later
    File Size: 1577 lines (62 kb)
    Included or required:0 times
    Referenced: 2 times
    Includes or requires: 0 files

    Defines 12 classes

    restricted_context_exception:: (1 method):

    external_api:: (9 methods):

    external_description:: (1 method):

    external_value:: (1 method):

    external_single_structure:: (1 method):

    external_multiple_structure:: (1 method):

    external_function_parameters:: (4 methods):

    external_warnings:: (1 method):

    external_format_value:: (6 methods):

    external_settings:: (14 methods):

    external_util:: (2 methods):

    external_files:: (2 methods):

    Class: restricted_context_exception  - X-Ref

    Exception indicating user is not allowed to use external function in the current context.

    __construct()   X-Ref

    Class: external_api  - X-Ref

    Base class for external api methods.

    external_function_info($function, $strictness=MUST_EXIST)   X-Ref
    Returns detailed function information

    param: string|object $function name of external function or record from external_function
    param: int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
    return: stdClass description or false if not found or exception thrown

    call_external_function($function, $args, $ajaxonly=false)   X-Ref
    Call an external function validating all params/returns correctly.

    Note that an external function may modify the state of the current page, so this wrapper
    saves and restores tha PAGE and COURSE global variables before/after calling the external function.

    param: string $function A webservice function name.
    param: array $args Params array (named params)
    param: boolean $ajaxonly If true, an extra check will be peformed to see if ajax is required.
    return: array containing keys for error (bool), exception and data.

    set_context_restriction($context)   X-Ref
    Set context restriction for all following subsequent function calls.

    param: stdClass $context the context restriction

    set_timeout($seconds=360)   X-Ref
    This method has to be called before every operation
    that takes a longer time to finish!

    param: int $seconds max expected time the next operation needs

    validate_parameters(external_description $description, $params)   X-Ref
    Validates submitted function parameters, if anything is incorrect
    invalid_parameter_exception is thrown.
    This is a simple recursive method which is intended to be called from
    each implementation method of external API.

    param: external_description $description description of parameters
    param: mixed $params the actual parameters
    return: mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found

    clean_returnvalue(external_description $description, $response)   X-Ref
    Clean response
    If a response attribute is unknown from the description, we just ignore the attribute.
    If a response attribute is incorrect, invalid_response_exception is thrown.
    Note: this function is similar to validate parameters, however it is distinct because
    parameters validation must be distinct from cleaning return values.

    param: external_description $description description of the return values
    param: mixed $response the actual response
    return: mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
    author: 2010 Jerome Mouneyrac

    validate_context($context)   X-Ref
    Makes sure user may execute functions in this context.

    param: stdClass $context

    get_context_from_params($param)   X-Ref
    Get context from passed parameters.
    The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
    For example, the context level can be "course" and instanceid can be courseid.

    See context_helper::get_all_levels() for a list of valid context levels.

    param: array $param
    return: context

    get_context_parameters()   X-Ref
    Returns a prepared structure to use a context parameters.

    return: external_single_structure

    Class: external_description  - X-Ref

    Common ancestor of all parameter description classes

    __construct($desc, $required, $default)   X-Ref

    param: string $desc
    param: bool $required
    param: mixed $default

    Class: external_value  - X-Ref

    Scalar value description class

    __construct($type, $desc='', $required=VALUE_REQUIRED,$default=null, $allownull=NULL_ALLOWED)   X-Ref

    param: mixed $type
    param: string $desc
    param: bool $required
    param: mixed $default
    param: bool $allownull

    Class: external_single_structure  - X-Ref

    Associative array description class

    __construct(array $keys, $desc='',$required=VALUE_REQUIRED, $default=null)   X-Ref

    param: array $keys
    param: string $desc
    param: bool $required
    param: array $default

    Class: external_multiple_structure  - X-Ref

    Bulk array description class.

    __construct(external_description $content, $desc='',$required=VALUE_REQUIRED, $default=null)   X-Ref

    param: external_description $content
    param: string $desc
    param: bool $required
    param: array $default

    Class: external_function_parameters  - X-Ref

    Description of top level - PHP function parameters.

    __construct(array $keys, $desc='', $required=VALUE_REQUIRED, $default=null)   X-Ref
    Constructor - does extra checking to prevent top level optional parameters.

    param: array $keys
    param: string $desc
    param: bool $required
    param: array $default

    external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction='')   X-Ref
    Generate a token

    param: stdClass|int $serviceorid service linked to the token
    param: int $userid user linked to the token
    param: stdClass|int $contextorid
    param: int $validuntil date when the token expired
    param: string $iprestriction allowed ip - if 0 or empty then all ips are allowed
    return: string generated token
    author: 2010 Jamie Pratt

    external_create_service_token($servicename, $context)   X-Ref
    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.

    param: string $servicename name of the web service. Service name as defined in db/services.php
    param: int $context context within which the web service can operate.
    return: int returns token id.

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

    param: string $component name of component (moodle, mod_assignment, etc.)

    Class: external_warnings  - X-Ref

    Standard Moodle web service warnings

    __construct($itemdesc = 'item', $itemiddesc = 'item id',$warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour')   X-Ref

    Class: external_format_value  - X-Ref

    A pre-filled external_value class for text format.

    Default is FORMAT_HTML
    This should be used all the time in external xxx_params()/xxx_returns functions
    as it is the standard way to implement text format param/return values.

    __construct($textfieldname, $required = VALUE_REQUIRED, $default = null)   X-Ref

    param: string $textfieldname Name of the text field
    param: int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
    param: int $default Default value.

    external_validate_format($format)   X-Ref
    Validate text field format against known FORMAT_XXX

    param: array $format the format to validate
    return: the validated format

    external_format_string($str, $contextorid, $striplinks = true, $options = array()   X-Ref
    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 {@link format_string()} with some changes:
    filter      : Can be set to false to force filters off, else observes {@link external_settings}.

    param: string $str The string to be filtered. Should be plain text, expect
    param: boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
    param: context|int $contextorid The id of the context for the string or the context (affects filters).
    param: array $options options array/object or courseid
    return: string text

    external_format_text($text, $textformat, $contextorid, $component = null, $filearea = null, $itemid = null,$options = null)   X-Ref
    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 {@link format_text()} 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 {@link external_settings}.
    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 <a> tags will have target="_blank" added unless target is explicitly specified.

    param: string $text The content that may contain ULRs in need of rewriting.
    param: int $textformat The text format.
    param: context|int $contextorid This parameter and the next two identify the file area to use.
    param: string $component
    param: string $filearea helps identify the file area.
    param: int $itemid helps identify the file area.
    param: object/array $options text formatting options
    return: array text + textformat

    external_generate_token_for_current_user($service)   X-Ref
    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

    external_log_token_request($token)   X-Ref
    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.

    param: stdClass $token token object

    Class: external_settings  - X-Ref

    Singleton to handle the external settings.

    We use singleton to encapsulate the "logic"

    __construct()   X-Ref
    Constructor - protected - can not be instanciated

    get_instance()   X-Ref
    Return only one instance

    return: \external_settings

    set_raw($raw)   X-Ref
    Set raw

    param: boolean $raw

    get_raw()   X-Ref
    Get raw

    return: boolean

    set_filter($filter)   X-Ref
    Set filter

    param: boolean $filter

    get_filter()   X-Ref
    Get filter

    return: boolean

    set_fileurl($fileurl)   X-Ref
    Set fileurl

    param: boolean $fileurl

    get_fileurl()   X-Ref
    Get fileurl

    return: boolean

    set_file($file)   X-Ref
    Set file

    param: string $file

    get_file()   X-Ref
    Get file

    return: string

    set_lang($lang)   X-Ref
    Set lang

    param: string $lang

    get_lang()   X-Ref
    Get lang

    return: string

    set_timezone($timezone)   X-Ref
    Set timezone

    param: string $timezone

    get_timezone()   X-Ref
    Get timezone

    return: string

    Class: external_util  - X-Ref

    Utility functions for the external API.

    validate_courses($courseids, $courses = array()   X-Ref
    Validate a list of courses, returning the complete course objects for valid courses.

    Each course has an additional 'contextvalidated' field, this will be set to true unless
    you set $keepfails, in which case it will be false if validation fails for a course.

    param: array $courseids A list of course ids
    param: array $courses   An array of courses already pre-fetched, indexed by course id.
    param: bool $addcontext True if the returned course object should include the full context object.
    param: bool $keepfails  True to keep all the course objects even if validation fails
    return: array            An array of courses and the validation warnings

    get_area_files($contextid, $component, $filearea, $itemid = false, $useitemidinurl = true)   X-Ref
    Returns all area files (optionally limited by itemid).

    param: int $contextid context ID
    param: string $component component
    param: string $filearea file area
    param: int $itemid item ID or all files if not specified
    param: bool $useitemidinurl wether to use the item id in the file URL (modules intro don't use it)
    return: array of files, compatible with the external_files structure.

    Class: external_files  - X-Ref

    External structure representing a set of files.

    __construct($desc = 'List of files.', $required = VALUE_REQUIRED)   X-Ref

    param: string $desc Description for the multiple structure.
    param: int $required The type of value (VALUE_REQUIRED OR VALUE_OPTIONAL).

    get_properties_for_exporter()   X-Ref
    Return the properties ready to be used by an exporter.

    return: array properties