lib.php 84 KB
Newer Older
1
2
3
4
<?php
/**
 *
 * @package    mahara
5
 * @subpackage auth-webservice
6
 * @author     Catalyst IT Ltd
7
8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 *
 */

defined('INTERNAL') || die();

$path = get_config('docroot') . 'webservice/libs/zend';
set_include_path($path . PATH_SEPARATOR . get_include_path());
require_once(get_config('docroot') . 'webservice/locallib.php');
require_once(get_config('docroot') . 'artefact/lib.php');
require_once(get_config('docroot') . 'webservice/libs/net.php');
require_once(get_config('docroot') . 'api/xmlrpc/lib.php');

/**
 * The directory within a component that contains the web service files
 */
define('WEBSERVICE_DIRECTORY', 'webservice');

/**
 * Security token used for allowing access
 * from external application such as web services.
 * Scripts do not use any session, performance is relatively
 * low because we need to load access info in each request.
 * Scripts are executed in parallel.
 */
define('EXTERNAL_TOKEN_PERMANENT', 0);

/**
 * Security token used for allowing access
 * of embedded applications, the code is executed in the
 * active user session. Token is invalidated after user logs out.
 * Scripts are executed serially - normal session locking is used.
 */
define('EXTERNAL_TOKEN_EMBEDDED', 1);

/**
 * OAuth Token type for registered applications oauth v1
 */
define('EXTERNAL_TOKEN_OAUTH1', 2);

/**
49
 * Security token self-generated by a normal user
50
51
52
53
 */
define('EXTERNAL_TOKEN_USER', 3);

/**
54
 * Personal User Tokens expiry time (12 weeks)
55
 */
56
define('EXTERNAL_TOKEN_USER_EXPIRES', (12 * 7 * 24 * 60 * 60));
57
58
59
60
61
62
63
64

define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
define('WEBSERVICE_AUTHMETHOD_OAUTH_TOKEN', 3);
define('WEBSERVICE_AUTHMETHOD_USER_TOKEN', 4);

// strictness check
65
define('IGNORE_MISSING', 1);
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
define('MUST_EXIST', 2);

/** Get remote addr constant */
define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');

/** Get remote addr constant */
define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');


/**
 * What debugging state is Web Services in
 *
 * @return boolean true on yes
 */
function ws_debugging() {
    // must be set in config.php
    if (get_config('enablewsdebugging')) {
        return true;
    }
    else {
        return false;
    }
}

/**
 * Check that a user is in the institution
 *
 * @param array $user array('id' => .., 'username' => ..)
 * @param string $institution
 * @return boolean true on yes
 */
function mahara_external_in_institution($user, $institution) {
    $institutions = array_keys(load_user_institutions($user->id));
    $auth_instance = get_record('auth_instance', 'id', $user->authinstance);
    $institutions[]= $auth_instance->institution;
    if (!in_array($institution, $institutions)) {
        return false;
    }
    return true;
}

/**
 * parameter definition for output of any Atom generator
 *
 * Returns description of method result value
 * @return external_description
 */
function mahara_external_atom_returns() {
    return new external_single_structure(
    array(
            'id'      => new external_value(PARAM_RAW, 'Atom document Id'),
            'title'   => new external_value(PARAM_RAW, 'Atom document Title'),
            'link'    => new external_value(PARAM_RAW, 'Atom document Link'),
            'email'   => new external_value(PARAM_RAW, 'Atom document Author Email'),
            'name'    => new external_value(PARAM_RAW, 'Atom document Author Name'),
121
            'updated' => new external_value(PARAM_RAW, 'Atom document Updated date'),
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
            'uri'     => new external_value(PARAM_RAW, 'Atom document URI'),
            'entries' => new external_multiple_structure(
                                new external_single_structure(
                                            array(
                                                    'id'        => new external_value(PARAM_RAW, 'Atom entry Id'),
                                                    'link'      => new external_value(PARAM_RAW, 'Atom entry Link'),
                                                    'email'     => new external_value(PARAM_RAW, 'Atom entry Author Link'),
                                                    'name'      => new external_value(PARAM_RAW, 'Atom entry Author Name'),
                                                    'updated'   => new external_value(PARAM_RAW, 'Atom entry updated date'),
                                                    'published' => new external_value(PARAM_RAW, 'Atom entry published date'),
                                                    'title'     => new external_value(PARAM_RAW, 'Atom entry Title'),
                                                    'summary'   => new external_value(PARAM_RAW, 'Atom entry Summary', VALUE_OPTIONAL),
                                                    'content'   => new external_value(PARAM_RAW, 'Atom entry Content', VALUE_OPTIONAL),
                                                    ), 'Atom entry', VALUE_OPTIONAL)
                    , 'Entries', VALUE_OPTIONAL),
                )
    );
}

/**
 * validate the user for webservices access
 * the account must use the webservice auth plugin
 * the account must have membership for the selected auth_instance
 *
 * @param object $dbuser
147
 * @return object $auth_instance or null if $dbuser is empty
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
 */
function webservice_validate_user($dbuser) {
    global $SESSION;
    if (!empty($dbuser)) {
        $auth_instance = get_record('auth_instance', 'id', $dbuser->authinstance);
        if ($auth_instance->authname == 'webservice') {
            $memberships = count_records('usr_institution', 'usr', $dbuser->id);
            if ($memberships == 0) {
                // auth instance should be a mahara one
                if ($auth_instance->institution == 'mahara') {
                    return $auth_instance;
                }
            }
            else {
                $membership = get_record('usr_institution', 'usr', $dbuser->id, 'institution', $auth_instance->institution);
                if (!empty($membership)) {
                    return $auth_instance;
                }
            }
        }
    }
    return NULL;
}

/**
173
174
 * List all potential webservice locations
 * (i.e. plugins, local, and the "pseudo-module" /webservice).
175
176
177
178
 *
 * @return array of web service plugin directories
 */
function get_ws_subsystems() {
179
    static $plugindirs = false;
180
181

    if (!$plugindirs) {
182
183
184
185
186
187
188
        $plugindirs = [
            'webservice',
            'local'
        ];
        $activeplugins = plugin_all_installed();
        foreach ($activeplugins as $plugindata) {
            $plugindirs[] = "{$plugindata->plugintype}/{$plugindata->name}";
189
190
191
192
193
194
195
196
197
198
199
200
201
202
        }
    }

    return $plugindirs;
}

/**
 *  Generate a web services token
 * @param string $tokentype
 * @param integer $serviceorid
 * @param integer $userid
 * @param string $institution
 * @param integer $validuntil
 * @param string $iprestriction
203
204
205
 * @param string $clientname (Optional) Human-readable name of client program using this token
 * @param string $clientenv (Optional) Human-readable description of device/environment for client
 * @param string $clientguid (Optional) Unique identifier for the client program
206
207
208
 * @throws WebserviceException
 * @return string token
 */
209
function webservice_generate_token($tokentype, $serviceorid, $userid, $institution = 'mahara',  $validuntil = 0, $iprestriction = null, $clientname = null, $clientenv = null, $clientguid = null) {
210
211
212
213
214
215
    global $USER;
    // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
    $numtries = 0;
    do {
        $numtries ++;
        $generatedtoken = md5(uniqid(rand(),1));
216
        if ($numtries > 5) {
217
218
219
220
221
            throw new WebserviceException('tokengenerationfailed');
        }
    } while (record_exists('external_tokens', 'token', $generatedtoken));
    $newtoken = new stdClass();
    $newtoken->token = $generatedtoken;
222
    if (!is_object($serviceorid)) {
223
        $service = get_record('external_services', 'id', $serviceorid);
224
225
    }
    else {
226
227
228
229
230
        $service = $serviceorid;
    }
    $newtoken->externalserviceid = $service->id;
    $newtoken->tokentype = $tokentype;
    $newtoken->userid = $userid;
231
    if ($tokentype == EXTERNAL_TOKEN_EMBEDDED) {
232
233
234
235
236
        $newtoken->sid = session_id();
    }

    $newtoken->institution = $institution;
    $newtoken->creatorid = $USER->get('id');
237
    $newtoken->ctime = db_format_timestamp(time());
238
    $newtoken->timecreated = time();
239
240
241
242
    $newtoken->publickeyexpires = time();
    $newtoken->wssigenc = 0;
    $newtoken->publickey = '';
    $newtoken->validuntil = $validuntil;
243
244
245
246
    $newtoken->clientname = $clientname;
    $newtoken->clientenv = $clientenv;
    $newtoken->clientguid = $clientguid;
    $newtoken->iprestriction = $iprestriction;
247
248
249
250
251
252
253
254
255
256
    insert_record('external_tokens', $newtoken);
    return $newtoken->token;
}

/**
 * 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
257
258
259
260
 * @param integer $userid
 * @param string $institution
 * @param integer $validuntil
 * @param string $iprestriction
261
262
 * @return int returns token id.
 */
263
function webservice_create_service_token($servicename, $userid, $institution = 'mahara',  $validuntil=0, $iprestriction='') {
264
265
266
267
    $service = get_record('external_services', 'name', $servicename, '*');
    return webservice_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $userid, $institution,  $validuntil, $iprestriction);
}

268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/**
 * Calculate where the webservices directory should be, for a given value of
 * "component".
 *
 * There are three general types of "component" value we expect to see.
 * 1. "webservice": Indicates a the "core" webservices, which are in htdocs/webservice
 * 2. "local": Indicates custom webservices under htdocs/local/webservice
 * 3. "{plugintype}/{pluginname}": Indicates webservices for a plugin.
 *
 * @param string $component The component to look for
 * @param reference $plugintype If the component represents a plugin, the plugin's type will
 * be returned via this variable, passed by reference.
 * @param reference $pluginname If the component represents a plugin, the plugin's name will
 * be returned via this variable, passed by reference.
 * @return string Relative path to the component's webservices directory. If the component
 * is a plugin, this path will be relative the plugin's directory. Otherwise, it'll be
 * relative to $CFG->docroot.
 * @throws WebserviceCodingException
 */
function webservice_component_ws_directory($component, &$plugintype, &$pluginname) {
    if ($component == WEBSERVICE_DIRECTORY) {
        $plugintype = false;
        $pluginname = false;
        return WEBSERVICE_DIRECTORY;
    }

    if ($component == 'local') {
        $plugintype = false;
        $pluginname = false;
        return 'local/' . WEBSERVICE_DIRECTORY;
    }

    $bits = explode('/', $component);
    if (count($bits) == 2) {
        list($plugintype, $pluginname) = $bits;
        return WEBSERVICE_DIRECTORY;
    }

    throw new WebserviceCodingException("Invalid component name: '{$component}'");
}

309
310
311
312
313
314
315
/**
 * 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;
 *                        MUST_EXIST means throw exception if no record or multiple records found
 * @return object description or false if not found or exception thrown
 */
316
317
function webservice_function_info($function, $strictness=MUST_EXIST, $component = null) {
    $mustexist = ($strictness === MUST_EXIST);
318
    if (!is_object($function)) {
319
320
321
322
323
324
325
        if ($component) {
            $function = get_record('external_functions', 'name', $function, 'component', $component);
        }
        else {
            $function = get_record('external_functions', 'name', $function);
        }
        if (!$function) {
326
327
            return false;
        }
328
        $component = $function->component;
329
330
331
    }

    //first find and include the ext implementation class
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
    if (!class_exists($function->classname)) {

        $wsdir = webservice_component_ws_directory(
            $function->component,
            $plugintype,
            $pluginname
        );

        if ($plugintype && $pluginname) {
            // Standard plugin; can use safe_require
            $foundfile = safe_require_plugin(
                $plugintype,
                $pluginname,
                $wsdir . '/functions/' . $function->classname . '.php',
                'require_once',
                true
            );
            if (!$foundfile) {
                if ($mustexist) {
                    throw new WebserviceCodingException(get_string('cannotfindimplfile', 'auth.webservice'));
                }
                return false;
            }
        }
        else {
            // Not a plugin, must handle manually
            $filepath = get_config('docroot') . $wsdir . '/functions/' . $function->classname . '.php';
            if (!file_exists($filepath)) {
                if ($mustexist) {
                    throw new WebserviceCodingException(get_string('cannotfindimplfile', 'auth.webservice'));
                }
                return false;
            }
            require_once($filepath);
        }
367
368
369
370
371
372
373
    }

    $function->parameters_method = $function->methodname . '_parameters';
    $function->returns_method    = $function->methodname . '_returns';

    // make sure the implementaion class is ok
    if (!method_exists($function->classname, $function->methodname)) {
374
375
376
377
        if ($mustexist) {
            throw new WebserviceCodingException(get_string('missingimplofmeth', 'auth.webservice', $function->classname . '::' . $function->methodname));
        }
        return false;
378
379
    }
    if (!method_exists($function->classname, $function->parameters_method)) {
380
381
382
383
        if ($mustexist) {
            throw new WebserviceCodingException(get_string('missingparamdesc', 'auth.webservice'));
        }
        return false;
384
385
    }
    if (!method_exists($function->classname, $function->returns_method)) {
386
387
388
389
        if ($mustexist) {
            throw new WebserviceCodingException(get_string('missingretvaldesc', 'auth.webservice'));
        }
        return false;
390
391
392
393
394
    }

    // fetch the parameters description
    $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
    if (!($function->parameters_desc instanceof external_function_parameters)) {
395
396
397
398
        if ($mustexist) {
            throw new WebserviceCodingException(get_string('invalidparamdesc', 'auth.webservice'));
        }
        return false;
399
400
401
402
403
404
    }

    // fetch the return values description
    $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
    // null means void result or result is ignored
    if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
405
406
407
408
        if ($mustexist) {
            throw new WebserviceCodingException(get_string('invalidretdesc', 'auth.webservice'));
        }
        return false;
409
410
411
412
413
414
415
416
    }

    //now get the function description
    //TODO: use localised lang pack descriptions, it would be nice to have
    //      easy to understand descriptions in admin UI,
    //      on the other hand this is still a bit in a flux and we need to find some new naming
    //      conventions for these descriptions in lang packs
    $function->description = null;
417
418
419
420
    $result = webservice_load_services_file($function->component);
    $functionlist = $result['functions'];
    if (isset($functionlist[$function->name]['description'])) {
        $function->description = $functionlist[$function->name]['description'];
421
422
423
424
425
    }

    return $function;
}

426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/**
 * Returns a list of all of the webservice connection definitions declared
 * by all of the installed plugins.
 */
function webservice_connection_definitions() {

    $connections = array();

    $plugins = array();
    $plugins['blocktype'] = array();

    foreach (plugin_types()  as $plugin) {
        // this has to happen first because of broken artefact/blocktype ordering
        $plugins[$plugin] = array();
        $plugins[$plugin]['installed'] = array();
        $plugins[$plugin]['notinstalled'] = array();
    }
    foreach (array_keys($plugins) as $plugin) {
        if (table_exists(new XMLDBTable($plugin . '_installed'))) {
            if ($installed = plugins_installed($plugin, true)) {
                foreach ($installed as $i) {
                    $key = $i->name;
                    if ($plugin == 'blocktype') {
                        $key = blocktype_single_to_namespaced($i->name, $i->artefactplugin);
                    }
                    if (!safe_require_plugin($plugin, $key)) {
                        continue;
                    }
                    if ($i->active) {
                        $classname = generate_class_name($plugin, $key);
                        if (method_exists($classname, 'define_webservice_connections')) {
                            $conns = call_static_method($classname, 'define_webservice_connections');
                            if (!empty($conns)) {
                                $connections[$classname] = array('connections' => $conns, 'type' => $plugin, 'key' => $key);
                            }
                        }
                    }
                    if ($plugin == 'artefact') {
                        safe_require('artefact', $key);
                        if ($types = call_static_method(generate_class_name('artefact', $i->name), 'get_artefact_types')) {
                            foreach ($types as $t) {
                                $classname = generate_artefact_class_name($t);
                                if (method_exists($classname, 'define_webservice_connections')) {
                                    $conns = call_static_method($classname, 'define_webservice_connections');
                                    if (!empty($conns)) {
                                        $connections[$classname] = array('connections' => $conns, 'type' => $plugin, 'key' => $key);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return $connections;
}


485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/**
 * General web service library
 */
class webservice {

    /**
     * Get the list of all functions for given service ids
     * @param array $serviceids
     * @return array functions
     */
    public function get_external_functions($serviceids) {
        global $WS_FUNCTIONS;

        if (!empty($serviceids)) {
            $where = (count($serviceids) == 1 ? ' = '.array_shift($serviceids) : ' IN (' . implode(',', $serviceids) . ')');
            $sql = "SELECT f.*
                      FROM {external_functions} f
                     WHERE f.name IN (SELECT sf.functionname
                                        FROM {external_services_functions} sf
                                       WHERE sf.externalserviceid $where)";
            $functions = get_records_sql_array($sql, array());
506
507
        }
        else {
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
            $functions = array();
        }

        // stash functions for intro spective RPC calls later
        $WS_FUNCTIONS = array();
        foreach ($functions as $function) {
            $WS_FUNCTIONS[$function->name] = array('id' => $function->id);
        }

        return $functions;
    }
}

/**
 * Base class for external api methods.
 */
class external_api {
    private static $contextrestriction;

    /**
     * Set context restriction for all following subsequent function calls.
     * @param stdClass $contex
     * @return void
     */
    public static function set_context_restriction($context) {
        self::$contextrestriction = $context;
    }

    /**
     * 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
     * @return void
     */
    public static function set_timeout($seconds=360) {
        $seconds = ($seconds < 300) ? 300 : $seconds;
        set_time_limit($seconds);
    }

    /**
     * Validates submitted function parameters, if anything is incorrect
     * WebserviceInvalidParameterException 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
     */
    public static function validate_parameters(external_description $description, $params) {
        if ($description instanceof external_value) {
            if (is_array($params) or is_object($params)) {
                throw new WebserviceInvalidParameterException(get_string('errorscalartype', 'auth.webservice'));
            }

            if ($description->type == PARAM_BOOL) {
                // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
                if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
                    return (bool)$params;
                }
            }
            return validate_param($params, $description->type, $description->allownull, get_string('errorinvalidparamsapi', 'auth.webservice'));

571
572
        }
        else if ($description instanceof external_single_structure) {
573
574
575
576
577
578
579
580
581
582
            if (!is_array($params)) {
                throw new WebserviceInvalidParameterException(get_string('erroronlyarray', 'auth.webservice'));
            }
            $result = array();
            foreach ($description->keys as $key=>$subdesc) {
                if (!array_key_exists($key, $params)) {
                    if ($subdesc->required == VALUE_REQUIRED) {
                        throw new WebserviceInvalidParameterException(get_string('errormissingkey', 'auth.webservice', $key));
                    }
                    if ($subdesc->required == VALUE_DEFAULT) {
583
                        $result[$key] = $subdesc->default;
584
                    }
585
586
                }
                else {
587
588
589
590
                    try {
                        $result[$key] = self::validate_parameters($subdesc, $params[$key]);
                    } catch (WebserviceInvalidParameterException $e) {
                        //it's ok to display debug info as here the information is useful for ws client/dev
591
                        throw new WebserviceParameterException('invalidextparam',"key: $key - ".$e->getMessage().(isset($e->debuginfo) ? " (debuginfo: " . $e->debuginfo.") " : ""));
592
593
594
595
596
597
598
                    }
                }
                unset($params[$key]);
            }
            if (!empty($params)) {
                //list all unexpected keys
                $keys = '';
599
                foreach ($params as $key => $value) {
600
601
602
603
604
605
                    $keys .= $key . ',';
                }
                throw new WebserviceInvalidParameterException(get_string('errorunexpectedkey', 'auth.webservice', $keys));
            }
            return $result;

606
607
        }
        else if ($description instanceof external_multiple_structure) {
608
609
610
611
612
613
614
615
616
            if (!is_array($params)) {
                throw new WebserviceInvalidParameterException(get_string('erroronlyarray', 'auth.webservice'));
            }
            $result = array();
            foreach ($params as $param) {
                $result[] = self::validate_parameters($description->content, $param);
            }
            return $result;

617
618
        }
        else {
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
            throw new WebserviceInvalidParameterException(get_string('errorinvalidparamsdesc', 'auth.webservice'));
        }
    }

    /**
     * Clean response
     * If a response attribute is unknown from the description, we just ignore the attribute.
     * If a response attribute is incorrect, WebserviceInvalidResponseException 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, WebserviceInvalidResponseException thrown if any problem found
     */
    public static function clean_returnvalue(external_description $description, $response) {
        if ($description instanceof external_value) {
            if (is_array($response) or is_object($response)) {
                throw new WebserviceInvalidResponseException(get_string('errorscalartype', 'auth.webservice'));
            }

            if ($description->type == PARAM_BOOL) {
                // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
                if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
                    return (bool)$response;
                }
            }
            return validate_param($response, $description->type, $description->allownull, get_string('errorinvalidresponseapi', 'auth.webservice'));

647
648
        }
        else if ($description instanceof external_single_structure) {
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
            if (!is_array($response)) {
                throw new WebserviceInvalidResponseException(get_string('erroronlyarray', 'auth.webservice'));
            }
            $result = array();
            foreach ($description->keys as $key=>$subdesc) {
                if (!array_key_exists($key, $response)) {
                    if ($subdesc->required == VALUE_REQUIRED) {
                        throw new WebserviceParameterException('errorresponsemissingkey', $key);
                    }
                    if ($subdesc instanceof external_value) {
                        if ($subdesc->required == VALUE_DEFAULT) {
                            try {
                                $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
                            } catch (Exception $e) {
                                throw new WebserviceParameterException('invalidextresponse',$key . " (" . $e->getMessage() . ")");
                            }
                        }
                    }
667
668
                }
                else {
669
670
671
672
673
674
675
676
677
678
679
680
                    try {
                        $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
                    } catch (Exception $e) {
                        //it's ok to display debug info as here the information is useful for ws client/dev
                        throw new WebserviceParameterException('invalidextresponse', $key . " (" . $e->getMessage() . ")");
                    }
                }
                unset($response[$key]);
            }

            return $result;

681
682
        }
        else if ($description instanceof external_multiple_structure) {
683
684
685
686
687
688
689
690
691
            if (!is_array($response)) {
                throw new WebserviceInvalidResponseException(get_string('erroronlyarray', 'auth.webservice'));
            }
            $result = array();
            foreach ($response as $param) {
                $result[] = self::clean_returnvalue($description->content, $param);
            }
            return $result;

692
693
        }
        else {
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
            throw new WebserviceInvalidResponseException(get_string('errorinvalidresponsedesc', 'auth.webservice'));
        }
    }
}

/**
 * Common ancestor of all parameter description classes
 */
abstract class external_description {
    /** @property string $description description of element */
    public $desc;
    /** @property bool $required element value required, null not allowed */
    public $required;
    /** @property mixed $default default value */
    public $default;

    /**
     * Contructor
     * @param string $desc
     * @param bool $required
     * @param mixed $default
     */
    public function __construct($desc, $required, $default) {
        $this->desc = $desc;
        $this->required = $required;
        $this->default = $default;
    }
}

/**
 * Scalar alue description class
 */
class external_value extends external_description {
    /** @property mixed $type value type PARAM_XX */
    public $type;
    /** @property bool $allownull allow null values */
    public $allownull;

    /**
     * Constructor
     * @param mixed $type
     * @param string $desc
     * @param bool $required
     * @param mixed $default
     * @param bool $allownull
     */
    public function __construct($type, $desc='', $required=VALUE_REQUIRED,
    $default=null, $allownull=NULL_ALLOWED) {
        parent::__construct($desc, $required, $default);
        $this->type      = $type;
        $this->allownull = $allownull;
    }
}

/**
 * Associative array description class
 */
class external_single_structure extends external_description {
    /** @property array $keys description of array keys key=>external_description */
    public $keys;

    /**
     * Constructor
     * @param array $keys
     * @param string $desc
     * @param bool $required
     * @param array $default
     */
    public function __construct(array $keys, $desc='',
    $required=VALUE_REQUIRED, $default=null) {
        parent::__construct($desc, $required, $default);
        $this->keys = $keys;
    }
}

/**
 * Bulk array description class.
 */
class external_multiple_structure extends external_description {
    /** @property external_description $content */
    public $content;

    /**
     * Constructor
     * @param external_description $content
     * @param string $desc
     * @param bool $required
     * @param array $default
     */
    public function __construct(external_description $content, $desc='',
    $required=VALUE_REQUIRED, $default=null) {
        parent::__construct($desc, $required, $default);
        $this->content = $content;
    }
}

/**
 * Description of top level - PHP function parameters.
 * @author skodak
 *
 */
class external_function_parameters extends external_single_structure {
}
797

798
799
800
801
802
803
/**
 * Is protocol enabled?
 * @param string $protocol name of WS protocol
 * @return bool
 */
function webservice_protocol_is_enabled($protocol) {
804
    if (!get_config('webservice_provider_enabled')) {
805
806
        return false;
    }
807
    return get_config('webservice_provider_'.$protocol.'_enabled');
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
}

//=== WS classes ===

/**
 * Mandatory interface for all test client classes.
 * @author Petr Skoda (skodak)
 */
interface webservice_test_client_interface {
    /**
     * Execute test client WS request
     * @param string $serverurl
     * @param string $function
     * @param array $params
     * @return mixed
     */
    public function simpletest($serverurl, $function, $params);
}

/**
 * Mandatory interface for all web service protocol classes
 * @author Petr Skoda (skodak)
 */
interface webservice_server_interface {
    /**
     * Process request from client.
     * @return void
     */
    public function run();
}

/**
 * Abstract web service base class.
 * @author Petr Skoda (skodak)
 */
abstract class webservice_server implements webservice_server_interface {

    /** @property string $wsname name of the web server plugin */
    protected $wsname = null;

    /** @property string $username name of local user */
    protected $username = null;

    /** @property string $password password of the local user */
    protected $password = null;

    /** @property string $service service for wsdl look up */
    protected $service = null;

    /** @property int $userid the local user */
    protected $userid = null;

    /** @property integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_* */
    protected $authmethod;

    /** @property string $token authentication token*/
    protected $token = null;

    /** @property int restrict call to one service id*/
    protected $restricted_serviceid = null;

    /** @property string info to add to logging*/
    protected $info = null;
    /**
     * Contructor
     * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
     */
    public function __construct($authmethod) {
        $this->authmethod = $authmethod;
    }

    /**
     * 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.
     * @return void
     */
    protected function authenticate_user() {
        global $USER, $SESSION, $WEBSERVICE_INSTITUTION, $WEBSERVICE_OAUTH_USER;
        if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
            $this->auth = 'USER';
            //we check that authentication plugin is enabled
            //it is only required by simple authentication
            $plugin = get_record('auth_installed', 'name', 'webservice');
            if (empty($plugin) || $plugin->active != 1) {
                throw new WebserviceAccessException(get_string('wsauthnotenabled', 'auth.webservice'));
            }

            if (!$this->username) {
                throw new WebserviceAccessException(get_string('missingusername', 'auth.webservice'));
            }

            if (!$this->password) {
                throw new WebserviceAccessException(get_string('missingpassword', 'auth.webservice'));
            }

            // special web service login
            safe_require('auth', 'webservice');

            // get the user
            $user = get_record('usr', 'username', $this->username);
            if (empty($user)) {
                throw new WebserviceAccessException(get_string('wrongusernamepassword', 'auth.webservice'));
            }

            // user account is nolonger validly configured
            if (!$auth_instance = webservice_validate_user($user)) {
                throw new WebserviceAccessException(get_string('invalidaccount', 'auth.webservice'));
            }
            // set the global for the web service users defined institution
            $WEBSERVICE_INSTITUTION = $auth_instance->institution;

            // get the institution from the external user
            $ext_user = get_record('external_services_users', 'userid', $user->id);
            if (empty($ext_user)) {
                throw new WebserviceAccessException(get_string('wrongusernamepassword', 'auth.webservice'));
            }
            // determine the internal auth instance
            $auth_instance = get_record('auth_instance', 'institution', $ext_user->institution, 'authname', 'webservice');
            if (empty($auth_instance)) {
                throw new WebserviceAccessException(get_string('wrongusernamepassword', 'auth.webservice'));
            }

            // authenticate the user
            $auth = new AuthWebservice($auth_instance->id);
            if (!$auth->authenticate_user_account($user, $this->password, 'webservice')) {
                // log failed login attempts
                throw new WebserviceAccessException(get_string('wrongusernamepassword', 'auth.webservice'));
            }

        }
941
        else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN) {
942
943
944
            $this->auth = 'TOKEN';
            $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
        }
945
        else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_OAUTH_TOKEN) {
946
947
948
949
950
951
            //OAuth
            $this->auth = 'OAUTH';
            // special web service login
            safe_require('auth', 'webservice');

            // get the user - the user that authorised the token
952
953
            $user = $this->authenticate_by_token(EXTERNAL_TOKEN_OAUTH1);

954
955
956
957
958
959
960
961
962
963
964
965
            // check user is member of configured OAuth institution
            $institutions = array_keys(load_user_institutions($this->oauth_token_details['user_id']));
            $auth_instance = get_record('auth_instance', 'id', $user->authinstance);
            $institutions[]= $auth_instance->institution;
            if (!in_array($this->oauth_token_details['institution'], $institutions)) {
                throw new WebserviceAccessException(get_string('institutiondenied', 'auth.webservice'));
            }

            // set the global for the web service users defined institution
            $WEBSERVICE_INSTITUTION = $this->oauth_token_details['institution'];
            // set the note of the OAuth service owner
            $WEBSERVICE_OAUTH_USER = $this->oauth_token_details['service_user'];
966
967
        }
        else {
968
969
970
971
972
973
974
975
            $this->auth = 'OTHER';
            $user = $this->authenticate_by_token(EXTERNAL_TOKEN_USER);
        }

        // now fake user login, the session is completely empty too
        $USER->reanimate($user->id, $user->authinstance);
    }

976
977
978
979
980
981
    /**
     * Authenticate by token type
     *
     * @param $tokentype string tokentype constant
     * @return $user object
     */
982
    protected function authenticate_by_token($tokentype) {
983
984
        global $WEBSERVICE_INSTITUTION;

985
986
987
988
989
990
991
        if ($tokentype == EXTERNAL_TOKEN_OAUTH1) {
            $user = get_record('usr', 'id', $this->oauth_token_details['user_id']);
            if (empty($user)) {
                throw new WebserviceAccessException(get_string('wrongusernamepassword', 'auth.webservice'));
            }
            return $user;
        }
992
993
994


        $token = get_record('external_tokens', 'token', $this->token);
995
996
997
998
        if (!$token) {
            // log failed login attempts
            throw new WebserviceAccessException(get_string('invalidtoken', 'auth.webservice'));
        }
999
1000

        // tidy up the auth method - this could be user token or session token
1001
        if ($token->tokentype != EXTERNAL_TOKEN_PERMANENT) {
1002
1003
1004
1005
1006
1007
1008
            if ($token->tokentype === EXTERNAL_TOKEN_USER) {
                // TODO: These should probably be constants, not strings...
                $this->auth = 'TOKEN_USER';
            }
            else {
                $this->auth = 'OTHER';
            }
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
        }

        /**
         * check the valid until date
         */
        if ($token->validuntil and $token->validuntil < time()) {
            delete_records('external_tokens', 'token', $this->token, 'tokentype', $tokentype);
            throw new WebserviceAccessException(get_string('invalidtimedtoken', 'auth.webservice'));
        }

        //assumes that if sid is set then there must be a valid associated session no matter the token type
1020
        if ($token->sid) {
1021
            $session = session_get_instance();
1022
            if (!$session->session_exists($token->sid)) {
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
                delete_records('external_tokens', 'sid', $token->sid);
                throw new WebserviceAccessException(get_string('invalidtokensession', 'auth.webservice'));
            }
        }

        if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
            throw new WebserviceAccessException(get_string('invalidiptoken', 'auth.webservice'));
        }

        $this->restricted_serviceid = $token->externalserviceid;

        $user = get_record('usr', 'id', $token->userid, 'deleted', 0);

        // log token access
1037
        set_field('external_tokens', 'mtime', db_format_timestamp(time()), 'id', $token->id);
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076

        // set the global for the web service users defined institution
        $WEBSERVICE_INSTITUTION = $token->institution;

        return $user;
    }

    /**
     * Intercept some maharawssettingXXX $_GET and $_POST parameter
     * that are related to the web service call and are not the function parameters
     */
    protected function set_web_service_call_settings() {
        global $CFG;

        // Default web service settings.
        // Must be the same XXX key name as the external_settings::set_XXX function.
        // Must be the same XXX ws parameter name as 'maharawssettingXXX'.
        $externalsettings = array(
            'raw' => false,
            'fileurl' => true,
            'filter' =>  false);

        // Load the external settings with the web service settings.
        $settings = external_settings::get_instance();
        foreach ($externalsettings as $name => $default) {

            $wsparamname = 'maharawssetting' . $name;

            // Retrieve and remove the setting parameter from the request.
            // $value = optional_param($wsparamname, $default, PARAM_BOOL);
            $value = param_variable($wsparamname, $default);
            unset($_GET[$wsparamname]);
            unset($_POST[$wsparamname]);

            $functioname = 'set_' . $name;
            $settings->$functioname($value);
        }

    }
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169

    /**
     * Gets information about services the authenticated user is allowed
     * to access.
     * @param string $serviceid (Optional) Only look at this service
     * @param string $functionname (Optional) Services must contain this function
     * @throws WebserviceInvalidParameterException
     */
    protected function get_allowed_services($serviceid = false, $functionname = false) {
        global $USER;

        if ($functionname) {
            $fncond1 = 'AND sf.functionname = ?';
            $fncond2 = 'AND sf.functionname = ?';
        }
        else {
            $fncond1 = '';
            $fncond2 = '';
        }

        if ($serviceid) {
            $wscond1 = 'AND s.id = ? ';
            $wscond2 = 'AND s.id = ? ';
        }
        else {
            $wscond1 = '';
            $wscond2 = '';
        }

        if ($this->auth === 'TOKEN_USER') {
            $tokencond = 'AND s.tokenusers = 1';
        }
        else {
            $tokencond = '';
        }

        // now let's verify access control
        // Allow access only if:
        // - restrictedusers = 0
        // - OR
        //   - restrictedusers = 1
        //   - AND user is on the list for the service
        //   - AND user's listing hasn't expired
        //   - AND user's IP matches any restrictions for their listing
        $sql = "
            SELECT s.*, NULL AS iprestriction
            FROM
                {external_services} s
                INNER JOIN {external_services_functions} sf ON
                    sf.externalserviceid = s.id
                    AND s.restrictedusers = 0
                    $fncond1
            WHERE
                s.enabled = 1
                $tokencond
                $wscond1
        UNION
            SELECT s.*, su.iprestriction
            FROM
                {external_services} s
                INNER JOIN {external_services_functions} sf ON
                    sf.externalserviceid = s.id
                    AND s.restrictedusers = 1
                    $fncond2
                INNER JOIN {external_services_users} su ON
                    su.externalserviceid = s.id
                    AND su.userid = ?
            WHERE
                s.enabled = 1
                AND (su.validuntil IS NULL OR su.validuntil < ?)
                $tokencond
                $wscond2
";
        $params = array();
        $fncond1 && $params[] = $functionname;
        $wscond1 && $params[]= $serviceid;
        $fncond2 && $params[]= $functionname;
        $params[]= $USER->get('id');
        $params[]= time();
        $wscond2 && $params[]= $serviceid;
        $rs = get_records_sql_array($sql, $params);

        $remoteaddr = getremoteaddr();
        $serviceids = array();
        foreach ($rs as $service) {
            if ($service->iprestriction && !address_in_subnet($remoteaddr, $service->iprestriction)) {
                // wrong request source ip, sorry
                continue;
            }
            $serviceids[] = $service->id;
        }
        return $serviceids;
    }
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
}

/**
 * Special abstraction of our srvices that allows
 * interaction with stock Zend ws servers.
 * @author Petr Skoda (skodak)
 */
abstract class webservice_zend_server extends webservice_server {

    /** @property string name of the zend server class : Zend_XmlRpc_Server, Zend_Soap_Server, Zend_Soap_AutoDiscover, ...*/
    protected $zend_class;

    /** @property object Zend server instance */
    protected $zend_server;

    /** @property string $service_class virtual web service class with all functions user name execute, created on the fly */
    protected $service_class;

    /** @property string $functionname the name of the function that is executed */
    protected $functionname = null;

    /**
     * Contructor
     * @param integer $authmethod authentication method - one of WEBSERVICE_AUTHMETHOD_*
     */
    public function __construct($authmethod, $zend_class) {
        parent::__construct($authmethod);
        $this->zend_class = $zend_class;
    }

    /**
     * Process request from client.
     * @param bool $simple use simple authentication
     * @return void
     */
    public function run() {
        global $WEBSERVICE_FUNCTION_RUN, $USER, $WEBSERVICE_INSTITUTION, $WEBSERVICE_START;
        $WEBSERVICE_START = microtime(true);

        // we will probably need a lot of memory in some functions
        raise_memory_limit('128M');

        // set some longer timeout, this script is not sending any output,
        // this means we need to manually extend the timeout operations
        // that need longer time to finish
        external_api::set_timeout();

        // now create the instance of zend server
        $this->init_zend_server();

        // set up exception handler first, we want to sent them back in correct format that
        // the other system understands
        // we do not need to call the original default handler because this ws handler does everything
        set_exception_handler(array($this, 'exception_handler'));

        // init all properties from the request data
        $this->parse_request();

        // process wsdl only, and without a user
        $xml = null;
        if ($this->service && isset($_REQUEST['wsdl'])) {
            $dbservice = get_record('external_services', 'name', $this->service);
            if (empty($dbservice)) {
                // throw error
                throw new WebserviceAccessException(get_string('invalidservice', 'auth.webservice'));
            }
            $serviceids = array($dbservice->id);
            $this->load_services($serviceids);
        }
        else {
            // Manipulate the payload if necessary
            $xml = $this->modify_payload();

            // this sets up $USER and $SESSION and context restrictions
            $this->authenticate_user();
        }

        // make a list of all functions user is allowed to excecute
        $this->init_service_class();

        // tell server what functions are available
        $this->zend_server->setClass($this->service_class);

        // set additional functions
        $this->fixup_functions();

        //send headers
        $this->send_headers();

        // execute and return response, this sends some headers too
        $response = $this->zend_server->handle($xml);
        // store the info of the error
        if (is_object($response) && get_class($response) == 'Zend_XmlRpc_Server_Fault') {
            $ex = $response->getException();
            $this->info = 'exception: ' . get_class($ex) . ' message: ' . $ex->getMessage() . ' debuginfo: ' . (isset($ex->debuginfo) ? $ex->debuginfo : '');
        }

        // session cleanup
        $this->session_cleanup();

        // allready all done if we were doing wsdl
        if (param_variable('wsdl', 0)) {
            die;
        }

        // modify the result
        $response = $this->modify_result($response);

        $time_end = microtime(true);
        $time_taken = $time_end - $WEBSERVICE_START;

        //log the web service request
        if (!isset($_REQUEST['wsdl']) && !empty($WEBSERVICE_FUNCTION_RUN)) {
            $class = get_class($this);
            if (preg_match('/soap/', $class)) {
                $class = 'SOAP';
            }
            else if (preg_match('/xmlrpc/', $class)) {
                $class = 'XML-RPC';
            }
            $log = (object)  array('timelogged' => time(),
                                   'userid' => $USER->get('id'),
                                   'externalserviceid' => $this->restricted_serviceid,
                                   'institution' => $WEBSERVICE_INSTITUTION,
                                   'protocol' => $class,
                                   'auth' => $this->auth,
                                   'functionname' => $WEBSERVICE_FUNCTION_RUN,
                                   'timetaken' => "" . $time_taken,
                                   'uri' => $_SERVER['REQUEST_URI'],
                                   'info' => ($this->info ? $this->info : ''),
                                   'ip' => getremoteaddr());
            insert_record('external_services_logs', $log, 'id', true);
        }
        else {
            // this is WSDL or methodsignature for XML-RPC
        }

        //finally send the result
        // force the content length as this was going wrong
        header('Content-Length: ' . strlen($response));
        echo $response;
        flush();
        die;
    }

    /**
     * Chance for each protocol to modify the function processing list
     *
     */
    protected function fixup_functions() {

        return null;
    }

    /**
     * Chance for each protocol to modify the incoming
     * raw payload - eg: SOAP and auth headers
     *
     * @return content
     */
    protected function modify_payload() {

        return null;
    }

    /**
     * Chance for each protocol to modify the out going
     * raw payload - eg: SOAP encryption and signatures
     *
     * @param string $response The raw response value
     *
     * @return content
     */
    protected function modify_result($response) {

        return $response;
    }

    /**
     * Load virtual class needed for Zend api
     * @return void
     */
    protected function init_service_class() {
        global $USER;

1355
        $serviceids = $this->get_allowed_services($this->restricted_serviceid);
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
        $this->load_services($serviceids);
    }

    /**
     * load service function definitions for service discovery and exectution
     *
     * @param array $serviceids
     */
    protected function load_services($serviceids) {
        global $USER;

        // now get the list of all functions
        $wsmanager = new webservice();
        $functions = $wsmanager->get_external_functions($serviceids);

        // now make the virtual WS class with all the fuctions for this particular user
        $methods = '';
        foreach ($functions as $function) {
            $methods .= $this->get_virtual_method_code($function);
        }

        // let's use unique class name, there might be problem in unit tests
        $classname = 'webservices_virtual_class_000000';
1379
        while (class_exists($classname)) {
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
            $classname++;
        }

        $code = '
/**
 * Virtual class web services for user id ' . $USER->get('id') . '
 */
class ' . $classname . ' {
' . $methods . '

    public function Header ($data) {
        return true;
    }

    public function Security ($data) {
        //throw new WebserviceAccessException(get_string("accessnotallowed", "webservice"));
        return true;
    }
}
';

        // load the virtual class definition into memory
        eval($code);
        $this->service_class = $classname;
    }

    /**
     * returns virtual method code
     * @param object $function
     * @return string PHP code
     */
    protected function get_virtual_method_code($function) {
        $function = webservice_function_info($function);

        //arguments in function declaration line with defaults.
        $paramanddefaults      = array();
        //arguments used as parameters for external lib call.
        $params      = array();
        $params_desc = array();
        foreach ($function->parameters_desc->keys as $name=>$keydesc) {
            $param = '$' . $name;
            $paramanddefault = $param;
            //need to generate the default if there is any
            if ($keydesc instanceof external_value) {
                if ($keydesc->required == VALUE_DEFAULT) {
1425
                    if ($keydesc->default === null) {
1426
                        $paramanddefault .= '=null';
1427
1428
                    }
                    else {
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
                        switch($keydesc->type) {
                            case PARAM_BOOL:
                                $paramanddefault .= '='. (int) $keydesc->default; break;
                            case PARAM_INT:
                                $paramanddefault .= '=' . $keydesc->default; break;
                            case PARAM_FLOAT;
                            $paramanddefault .= '=' . $keydesc->default; break;
                            default:
                                $paramanddefault .= '=\'' . $keydesc->default . '\'';
                        }
                    }
1440
1441
                }
                else if ($keydesc->required == VALUE_OPTIONAL) {
1442
1443
1444
1445
1446
                    //it does make sens to declare a parameter VALUE_OPTIONAL
                    //VALUE_OPTIONAL is used only for array/object key
                    throw new WebserviceException('parametercannotbevalueoptional');
                }
                //for the moment we do not support default for other structure types
1447
1448
            }
            else {
1449
1450
1451
1452
1453
                if ($keydesc->required == VALUE_DEFAULT) {
                    //accept empty array as default
                    if (isset($keydesc->default) and is_array($keydesc->default)
                    and empty($keydesc->default)) {
                        $paramanddefault .= '=array()';
1454
1455
                    }
                    else {
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
                        throw new WebserviceException('errornotemptydefaultparamarray', $name);
                    }
                }
                if ($keydesc->required == VALUE_OPTIONAL) {
                    throw new WebserviceException('erroroptionalparamarray', $name);
                }
            }
            $params[] = $param;
            $paramanddefaults[] = $paramanddefault;
            $type = $this->get_phpdoc_type($keydesc);
            $params_desc[] = '     * @param ' . $type . ' $' . $name . ' ' . $keydesc->desc;
        }
        $params                = implode(', ', $params);
        $paramanddefaults      = implode(', ', $paramanddefaults);
        $params_desc           = implode("\n", $params_desc);

        $serviceclassmethodbody = $this->service_class_method_body($function, $params);

        if (is_null($function->returns_desc)) {
            $return = '     * @return void';
1476
1477
        }
        else {
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
            $type = $this->get_phpdoc_type($function->returns_desc);
            $return = '     * @return ' . $type . ' ' . $function->returns_desc->desc;
        }

        // now crate the virtual method that calls the ext implementation

        $code = '
    /**
     * ' . $function->description . '
     *
' . $params_desc . '
' . $return . '
     */
    public function ' . $function->name . '(' . $paramanddefaults . ') {
        global $WEBSERVICE_FUNCTION_RUN;
        $WEBSERVICE_FUNCTION_RUN = \'' . $function->name . '\';
' . $serviceclassmethodbody . '
    }
';
        return $code;
    }

1500
1501
1502
1503
1504
1505
    /**
     * Get phpdoc type
     *
     * @param object $keydesc
     * @return string $type
     */
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
    protected function get_phpdoc_type($keydesc) {
        if ($keydesc instanceof external_value) {
            switch($keydesc->type) {
                // 0 or 1 only for now
                case PARAM_BOOL:
                case PARAM_INT:
                    $type = 'int'; break;
                case PARAM_FLOAT;
                $type = 'double'; break;
                default:
                    $type = 'string';
            }

1519
1520
        }
        else if ($keydesc instanceof external_single_structure) {
1521
1522
1523
            $classname = $this->generate_simple_struct_class($keydesc);
            $type = $classname;

1524
1525
        }
        else if ($keydesc instanceof external_multiple_structure) {
1526
1527
1528
1529
1530
1531
            $type = 'array';
        }

        return $type;
    }

1532
1533
1534
1535
1536
1537
    /**
     * generate simple structure class
     *
     * @param object $structdesc
     * @return string
     */
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
    protected function generate_simple_struct_class(external_single_structure $structdesc) {
        //only 'object' is supported by SOAP, 'struct' by XML-RPC MDL-23083
        return 'object|struct';
    }

    /**
     * You can override this function in your child class to add extra code into the dynamically
     * created service class. For example it is used in the amf server to cast types of parameters and to
     * cast the return value to the types as specified in the return value description.
     * @param stdClass $function
     * @param array $params
     * @return string body of the method for $function ie. everything within the {} of the method declaration.
     */
1551
    protected function service_class_method_body($function, $params) {
1552
1553
        //cast the param from object to array (validate_parameters except array only)
        $castingcode = '';
1554
        if ($params) {
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
            $paramstocast = explode(',', $params);
            foreach ($paramstocast as $paramtocast) {
                //clean the parameter from any white space
                $paramtocast = trim($paramtocast);
                $castingcode .= $paramtocast .
                '=webservice_zend_server::cast_objects_to_array(' . $paramtocast . ');';
            }

        }

        $descriptionmethod = $function->methodname . '_returns()';
        $callforreturnvaluedesc = $function->classname . '::' . $descriptionmethod;
        return $castingcode . '    if (' . $callforreturnvaluedesc . ' == null)  {' .
        $function->classname . '::' . $function->methodname . '(' . $params . ');
                        return null;
                    }
                    return external_api::clean_returnvalue(' . $callforreturnvaluedesc . ', ' . $function->classname . '::' . $function->methodname . '(' . $params . '));';
    }

    /**
     * Recursive function to recurse down into a complex variable and convert all
     * objects to arrays.
     * @param mixed $param value to cast
     * @return mixed Cast value
     */
1580
1581
    public static function cast_objects_to_array($param) {
        if (is_object($param)) {
1582
1583
            $param = (array)$param;
        }
1584
        if (is_array($param)) {
1585
            $toreturn = array();
1586
            foreach ($param as $key=> $param) {
1587
1588
1589
                $toreturn[$key] = self::cast_objects_to_array($param);
            }
            return $toreturn;
1590
1591
        }
        else {
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
            return $param;
        }
    }

    /**
     * Set up zend service class
     * @return void
     */
    protected function init_zend_server() {
        $this->zend_server = new $this->zend_class();
    }

    /**
     * This method parses the $_POST and $_GET superglobals and looks for
     * the following information:
     *  1/ user authentication - username+password or token (wsusername, wspassword and wstoken parameters)
     *
     * @return void
     */
    protected function parse_request() {

        // We are going to clean the POST/GET parameters from the parameters specific to the server.
        parent::set_web_service_call_settings();

        //Get GET and POST paramters
        $methodvariables = array_merge($_GET,$_POST);

        if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
            //note: some clients have problems with entity encoding :-(
            if (isset($methodvariables['wsusername'])) {
                $this->username = $methodvariables['wsusername'];
            }
            if (isset($methodvariables['wspassword'])) {
                $this->password = $methodvariables['wspassword'];
            }
            if (isset($methodvariables['wsservice'])) {
                $this->service = $methodvariables['wsservice'];
            }
1630
1631
        }
        else {
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
            if (isset($methodvariables['wstoken'])) {
                $this->token = $methodvariables['wstoken'];
            }
        }

        $this->parameters = $methodvariables;
    }

    /**
     * Internal implementation - sending of page headers.
     * @return void
     */
    protected function send_headers() {
        header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
        header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT');
        header('Pragma: no-cache');
        header('Accept-Ranges: none');
    }

    /**
     * Specialised exception handler, we can not use the standard one because
     * it can not just print html to output.
     *
     * @param exception $ex
     * @return void does not return
     */
    public function exception_handler($ex) {
        // detect active db transactions, rollback and log as error
        db_rollback();

        // some hacks might need a cleanup hook
        $this->session_cleanup($ex);

        // now let the plugin send the exception to client
        $this->send_error($ex);

        // not much else we can do now, add some logging later
        exit(1);
    }

    /**
     * Send the error information to the WS client
     * formatted as XML document.
     * @param exception $ex
     * @return void
     */
    protected function send_error($ex=null) {
        $this->send_headers();
        echo $this->zend_server->fault($ex);
    }

    /**
     * Future hook needed for emulated sessions.
     * @param exception $exception null means normal termination, $exception received when WS call failed
     * @return void
     */
    protected function session_cleanup($exception=null) {
        if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
            // nothing needs to be done, there is no persistent session
1691
1692
        }
        else {
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
            // close emulated session if used
        }
    }

}

/**
 * Web Service server base class, this class handles both
 * simple and token authentication.
 * @author Petr Skoda (skodak)
 */
abstract class webservice_base_server extends webservice_server {

    /** @property array $parameters the function parameters - the real values submitted in the request */
    protected $parameters = null;

    /** @property string $functionname the name of the function that is executed */
    protected $functionname = null;

    /** @property object $function full function description */
    protected $function = null;

    /** @property mixed $returns function return value */
    protected $returns = null;

    /**
     * This method parses the request input, it needs to get:
     *  1/ user authentication - username+password or token
     *  2/ function name
     *  3/ function parameters
     *
     * @return void
     */
    abstract protected function parse_request();

    /**
     * Send the result of function call to the WS client.
     * @return void
     */
    abstract protected function send_response();

    /**
     * Send the error information to the WS client.
     * @param exception $ex
     * @return void
     */
    abstract protected function send_error($ex=null);

    /**
     * Process request from client.
     * @return void
     */
    public function run() {
        global $WEBSERVICE_FUNCTION_RUN, $USER, $WEBSERVICE_INSTITUTION, $WEBSERVICE_START;

        $WEBSERVICE_START = microtime(true);

        // we will probably need a lot of memory in some functions
        raise_memory_limit('128M');

        // set some longer timeout, this script is not sending any output,
        // this means we need to manually extend the timeout operations
        // that need longer time to finish
        external_api::set_timeout();

        // set up exception handler first, we want to sent them back in correct format that
        // the other system understands
        // we do not need to call the original default handler because this ws handler does everything
        set_exception_handler(array($this, 'exception_handler'));

        // init all properties from the request data
        $this->parse_request();

        // authenticate user, this has to be done after the request parsing
        // this also sets up $USER and $SESSION
        $this->authenticate_user();

        // find all needed function info and make sure user may actually execute the function
        $this->load_function_info();

        // finally, execute the function - any errors are catched by the default exception handler
        $this->execute();

        $time_end = microtime(true);
        $time_taken = $time_end - $WEBSERVICE_START;

        //log the web service request
        $log = (object)  array('timelogged' => time(),
                               'userid' => $USER->get('id'),
                               'externalserviceid' => $this->restricted_serviceid,
                               'institution' => $WEBSERVICE_INSTITUTION,
                               'protocol' => 'REST',
                               'auth' => $this->auth,
                               'functionname' => $this->functionname,
                               'timetaken' => "" . $time_taken,
                               'uri' => $_SERVER['REQUEST_URI'],
                               'info' => '',
                               'ip' => getremoteaddr());
        insert_record('external_services_logs', $log, 'id', true);

        // send the results back in correct format
        $this->send_response();

        // session cleanup
        $this->session_cleanup();

        die;
    }

    /**
     * Specialised exception handler, we can not use the standard one because
     * it can not just print html to output.
     *
     * @param exception $ex
     * @return void does not return
     */
    public function exception_handler($ex) {
        global $WEBSERVICE_FUNCTION_RUN, $USER, $WEBSERVICE_INSTITUTION, $WEBSERVICE_START;

        // detect active db transactions, rollback and log as error
        db_rollback();

        $time_end = microtime(true);
        $time_taken = $time_end - $WEBSERVICE_START;

        //log the error on the web service request
        $log = (object)  array('timelogged' => time(),
                               'userid' => $USER->get('id'),
                               'externalserviceid' => $this->restricted_serviceid,
                               'institution' => $WEBSERVICE_INSTITUTION,
                               'protocol' => 'REST',
                               'auth' => $this->auth,
                               'functionname' => ($WEBSERVICE_FUNCTION_RUN ? $WEBSERVICE_FUNCTION_RUN : $this->functionname),
                               'timetaken' => '' . $time_taken,
                               'uri' => $_SERVER['REQUEST_URI'],
                               'info' => 'exception: ' . get_class($ex) . ' message: ' . $ex->getMessage() . ' debuginfo: ' . (isset($ex->debuginfo) ? $ex->debuginfo : ''),
                               'ip' => getremoteaddr());
        insert_record('external_services_logs', $log, 'id', true);

        // some hacks might need a cleanup hook
        $this->session_cleanup($ex);

        // now let the plugin send the exception to client
        $this->send_error($ex);

        // not much else we can do now, add some logging later
        exit(1);
    }

    /**
     * Future hook needed for emulated sessions.
     * @param exception $exception null means normal termination, $exception received when WS call failed
     * @return void
     */
    protected function session_cleanup($exception=null) {
        if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
            // nothing needs to be done, there is no persistent session
1850
1851
        }
        else {
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
            // close emulated session if used
        }
    }

    /**
     * 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)) {
1866
            throw new WebserviceInvalidParameterException(get_string('missingfuncname', 'webservice'));
1867
1868
1869
1870
1871
        }

        // function must exist
        $function = webservice_function_info($this->functionname);
        if (!$function) {
1872
            throw new WebserviceInvalidParameterException(get_string('accessextfunctionnotconf', 'auth.webservice'));
1873
        }
1874

1875
1876
1877
1878
        // Check that the function is in a service this user is allowed
        // to access.
        $serviceids = $this->get_allowed_services($this->restricted_serviceid, $this->functionname);
        if (!count($serviceids)) {
1879
1880
            throw new WebserviceAccessException(get_string('accesstofunctionnotallowed', 'auth.webservice', $this->functionname));
        }
1881

1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
        // 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;
    }

    /**
     * Execute previously loaded function using parameters parsed from the request data.
     * @return void
     */
    protected function execute() {
        // validate params, this also sorts the params properly, we need the correct order in the next part
1897
        ksort($this->parameters);
1898
1899
1900
        $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);

        // execute - yay!
1901
        log_debug('executing: ' . $this->function->classname . "/" . $this->function->methodname);
1902
1903
1904
1905
1906
1907
1908
1909
1910
        $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));
    }
}

/**
 * Delete all service and external functions information defined in the specified component.
 * @param string $component name of component (mahara, local, etc.)
 * @return void
 */
1911
function external_delete_descriptions($component) {
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941

    $params = array($component);

    delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
    delete_records_select('external_tokens', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
    delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
    delete_records_select('oauth_server_token', "osr_id_ref IN (SELECT id FROM {oauth_server_registry} WHERE externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?))", $params);
    delete_records_select('oauth_server_registry', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
    delete_records('external_services', 'component', $component);
    delete_records('external_functions', 'component', $component);
}

/**
 * The web services cron callback
 * clean out the old records that are N seconds old
 */
function webservice_clean_webservice_logs() {
    $LOG_AGE = 8 * 24 * 60 * 60; // 8 days
    delete_records_select('external_services_logs', 'timelogged < ?', array(time() - $LOG_AGE));
}

/**
 * Reload the webservice descriptions for all plugins
 *
 * @return bool true = success
 */

function external_reload_webservices() {

    // first - prune all components that are nolonger available/installed
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
    $dead_components = get_records_sql_array(
        'SELECT DISTINCT component AS component
        FROM {external_functions}
        WHERE
            component != \'\'
            AND component NOT IN ('.
                implode(', ', array_fill(1, count(get_ws_subsystems()), '?'))
        .')',
        get_ws_subsystems()
    );
1952
1953
    if ($dead_components) {
        foreach ($dead_components as $component) {
1954
            external_delete_descriptions($component->component);
1955
1956
1957
        }
    }
    foreach (get_ws_subsystems() as $component) {
1958
        external_reload_component($component);
1959
1960
1961
1962
1963
1964
    }

    return true;
}

/**
1965
1966
1967
 * Utility function to load up the $services and $functions arrays
 * from the services.php file for the specified component. (Calling it
 * from its own function in order to avoid polluting the namespace.)
1968
1969
 *
 * @param string $component
1970
 * @return array [$services, $functions]
1971
 */
1972
function webservice_load_services_file($component) {
1973

1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
    $wsdir = webservice_component_ws_directory(
        $component,
        $plugintype,
        $pluginname
    );

    if ($plugintype && $pluginname) {
        // Standard plugin; can use safe_require
        $file = safe_require(
            $plugintype,
            $pluginname,
            WEBSERVICE_DIRECTORY . '/services.php',
            'include',
            true,
            array('services', 'functions')
        );
        $services = $file['services'];
        $functions = $file['functions'];
    }
    else {
        // Not a plugin, must handle manually
        $filepath = get_config('docroot') . $wsdir . '/services.php';
        if (file_exists($filepath . '/services.php')) {
            include($filepath . '/services.php');
        }
    }
2000

2001
2002
    if (empty($services)) {
        $services = array();
2003
    }
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
    if (empty($functions)) {
        $functions = array();
    }
    return array(
        'services' => $services,
        'functions' => $functions
    );
}

/**
 * Reload the webservice descriptions for a single plugins
 *
 * @param string $component ("webservice", "local", or a plugin e.g.
 * "artefact/internal".
 * @return bool Whether or not we found webservices for this component
 */
function external_reload_component($component) {
2021

2022
2023
2024
2025
2026
2027
2028
2029
    // Load arrays $services and $functions from the plugin or component's
    // {path_to_plugin}/webservice/services.php file.
    $result = webservice_load_services_file($component);
    $services = $result['services'];
    $functions = $result['functions'];

    // Does the component have a valid services.php file?
    if (!$services && !$functions) {
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
        external_delete_descriptions($component);
        return false;
    }

    // update all function first
    $dbfunctions = get_records_array('external_functions', 'component', $component);
    if (!empty($dbfunctions)) {
        foreach ($dbfunctions as $dbfunction) {
            if (empty($functions[$dbfunction->name])) {
                // the functions is nolonger available for use
                delete_records('external_services_functions', 'functionname', $dbfunction->name);
                delete_records('external_functions', 'id', $dbfunction->id);
                continue;
            }
            $function = $functions[$dbfunction->name];
            unset($functions[$dbfunction->name]);
2046
2047
2048
2049
2050
2051
2052
2053
2054
            // Fill in default classpath
            if (empty($function['classpath'])) {
                if ($component === WEBSERVICE_DIRECTORY) {
                    $function['classpath'] = WEBSERVICE_DIRECTORY;
                }
                else {
                    $function['classpath'] = $component . '/' . WEBSERVICE_DIRECTORY;
                }
            }
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104

            $update = false;
            if ($dbfunction->classname != $function['classname']) {
                $dbfunction->classname = $function['classname'];
                $update = true;
            }
            if ($dbfunction->methodname != $function['methodname']) {
                $dbfunction->methodname = $function['methodname'];
                $update = true;
            }
            if ($dbfunction->classpath != $function['classpath']) {
                $dbfunction->classpath = $function['classpath'];
                $update = true;
            }
            if ($update) {
                update_record('external_functions', $dbfunction);
            }
        }
    }