index.php 53.4 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
 *
 */

define('INTERNAL', 1);
define('ADMIN', 1);
require(dirname(dirname(dirname(__FILE__))) . '/init.php');
15
define('MENUITEM', 'webservices/config');
16 17 18 19 20 21 22

$path = get_config('docroot') . 'lib/zend';
set_include_path($path . PATH_SEPARATOR . get_include_path());
require_once(get_config('docroot').'webservice/lib.php');
require_once(get_config('docroot') . 'api/xmlrpc/lib.php');
define('TITLE', get_string('webservices_title', 'auth.webservice'));

23 24
safe_require('auth', 'webservice');
$heading = get_string('webservices_title', 'auth.webservice');
25
$form = webservice_admin_main_form();
26 27
$serviceenabled = get_string('webservicesenabled', 'auth.webservice');
$servicenotenabled = get_string('webservicesnotenabled', 'auth.webservice');
28

29 30
$inlinejs = <<<JS
    jQuery(function ($) {
31 32
        var webservicesenabled = '$serviceenabled';
        var webservicesnotenabled = '$servicenotenabled';
33

34 35
        if (!$('#needprotocolsreq').length) {
            $('#webservice_requester_enabled_form_enabled_container').append('<span id="needprotocolsreq" class="form-message-inline"></span>');
36 37
        }

38 39 40
        if (!$('#needprotocolspro').length) {
            $('#webservice_provider_enabled_form_enabled_container').append('<span id="needprotocolspro" class="form-message-inline"></span>');
        }
41

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
        function update_warning_message(){
          var target = $('.webservice-provider-protocol-form').find('input:checkbox');
          var masterreq = $('#webservice_requester_enabled_form').find('input:checkbox');//requester
          var masterpro = $('#webservice_provider_enabled_form').find('input:checkbox');//provider
          if ($(masterreq).filter(':checked').length) {
              if (target.filter(':checked').length === 0) {
                  $('#needprotocolsreq').removeClass('text-success').addClass('text-danger').text(webservicesnotenabled);
              }
              else {
                  $('#needprotocolsreq').removeClass('text-danger').addClass('text-success').text(webservicesenabled);
              }
          }
          else {
              $('#needprotocolsreq').removeClass('text-danger').removeClass('text-success').text('');
          }
          if ($(masterpro).filter(':checked').length) {
              if (target.filter(':checked').length === 0) {
                  $('#needprotocolspro').removeClass('text-success').addClass('text-danger').text(webservicesnotenabled);
              }
              else {
                  $('#needprotocolspro').removeClass('text-danger').addClass('text-success').text(webservicesenabled);
              }
          }
          else {
              $('#needprotocolspro').removeClass('text-danger').removeClass('text-success').text('');
          }
        }
69

70 71 72
        function save_protos_switch(name) {
            // at least one of the master switches is on
            update_warning_message()
73
            // Save new state
74
            if (!$('#ajax_' + name).length) {
75
                $('#webservice_provider_protocols_' + name).append('<input id="ajax_' + name + '" type="hidden" name="ajax" value="1">');
76
            }
77
            $.post('index.php', $('#webservice_provider_protocols_' + name).serialize());
78 79
        }

80 81 82 83 84 85 86 87 88 89 90 91 92 93
        // saving the form when switching the protocols
        $('#webservice_provider_protocols_soap_enabled').change(function() {
            save_protos_switch('soap');
        });
        $('#webservice_provider_protocols_xmlrpc_enabled').change(function() {
            save_protos_switch('xmlrpc');
        });
        $('#webservice_provider_protocols_rest_enabled').change(function() {
            save_protos_switch('rest');
        });
        $('#webservice_provider_protocols_oauth_enabled').change(function() {
            save_protos_switch('oauth');
        });

94 95 96 97 98 99
        $('#webservice_provider_enabled_form_enabled').on('change', function(){
            update_webservice_status();
            // save master switch form
            $('#webservice_provider_enabled_form').append('<input type="hidden" name="ajax" value="1">');
            $.post('index.php', $('#webservice_provider_enabled_form').serialize());
        });
100
        $('#webservice_requester_enabled_form_enabled').on('change', function() {
101
            update_webservice_status();
102 103 104 105
            // save master connection switch form
            $('#webservice_requester_enabled_form').append('<input type="hidden" name="ajax" value="1">');
            $.post('index.php', $('#webservice_requester_enabled_form').serialize());
        });
106

107
        function update_webservice_status() {
108
            var target = $('.webservice-provider-protocol-form').find('input:checkbox');
109 110 111 112
            if ($('#webservice_requester_enabled_form_enabled').is(':checked') ||
                $('#webservice_provider_enabled_form_enabled').is(':checked')) {
                // enable all protocols
                target.prop('disabled', false);
113
                // alert user to switch protocols on if none are active
114
                update_warning_message();
115 116
            }
            else {
117 118
                // turn all protocols off
                target.prop('checked', false);
119
                // if main switch is off, remove message
120
                $('#webservice_provider_enabled_form_pseudofieldset .form-message-inline').text('');
121 122 123 124 125
                // disable all protocols
                target.prop('disabled', true);
                // remove the needprotocols error message
                $('#needprotocolsreq').removeClass('text-danger').text('');
                $('#needprotocolspro').removeClass('text-danger').text('');
126
            }
127
        }
128
        update_webservice_status();
129 130 131
    });
JS;

132 133 134
$smarty = smarty();
setpageicon($smarty, 'icon-puzzle-piece');

135
$smarty->assign('form', $form);
136
$smarty->assign('opened', param_alphanumext('open', ''));
137
$smarty->assign('PAGEHEADING', $heading);
138
$smarty->assign('INLINEJAVASCRIPT', $inlinejs);
139 140
$smarty->assign('pagedescription', get_string('webservicesconfigdesc', 'auth.webservice'));
$smarty->display('auth:webservice:configform.tpl');
141

142 143 144 145 146 147 148 149
/**
 *  Custom webservices config page
 *  - activate/deactivate webservices comletely
 *  - activate/deactivat protocols - SOAP/XML-RPC/REST
 *  - manage service clusters
 *  - manage users and access tokens
 *
 *  @return pieforms $element array
150
 */
151
function webservice_admin_main_form() {
152

153 154 155 156 157
    $protosform = array(
        'name'            => 'webservice_provider_protocols_form',
        'elements'        => webservice_provider_protocols_form(),
    );
    $protos = pieform_instance($protosform);
158

159 160
    // certificate values from MNet
    $openssl = OpenSslRepo::singleton();
161

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    $elements = array(
        // fieldset of master switch
        'webservicesmaster' => array(
            'name' => 'webservice_master_switches',
            'type' => 'fieldset',
            'legend' => get_string('webservice_master_switches', 'auth.webservice'),
            'elements' =>  array(
                'webservice_requester_enabled_label' =>  array(
                    'type' => 'html',
                    'value' => '<h4>' . get_string('webservice_requester_enabled_label', 'auth.webservice') . '</h4>',
                ),
                'webservice_requester_enabled_fieldset' => webservice_requester_enabled_form(),
                'webservice_provider_enabled_label' =>  array(
                    'type' => 'html',
                    'value' => '<h4>' . get_string('webservice_provider_enabled_label', 'auth.webservice') . '</h4>',
                ),
                'webservice_provider_enabled_fieldset' => webservice_provider_enabled_form(),
                'protos_help' =>  array(
                    'type' => 'html',
                    'value' => '<div><p>' . get_string('manage_protocols1', 'auth.webservice') . '</p></div>',
                ),
                'webservice_provider_protocols_form' =>  array(
                    'type' => 'html',
                    'value' => $protos->build(false),
                )
            ),
            'collapsible' => true,
            'collapsed'   => true,
        ),

        // System Certificates
        'certificates' => array(
            'name' => 'activate_webservices_networking',
            'type' => 'fieldset',
            'legend' => get_string('certificates', 'auth.webservice'),
            'elements' =>  array(
                'protos_help' =>  array(
                    'type' => 'html',
                    'value' => '<div><p>' . get_string('manage_certificates', 'auth.webservice', get_config('wwwroot') . 'admin/site/networking.php') . '</p></div>',
                ),
202

203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
                'pubkey' => array(
                    'type'         => 'html',
                    'value'        => '<h3 class="title">' . get_string('publickey','admin') . '</h3>'
                                      . '<div class="detail">' . get_string('publickeydescription2', 'admin', 365) . '</div>'
                                      . '<pre style="font-size: 0.7em; white-space: pre;">' . $openssl->certificate . '</pre>'
                ),
                'sha1fingerprint' => array(
                    'type'         => 'html',
                    'value'        => '<div><p>' . get_string('sha1fingerprint', 'auth.webservice', $openssl->sha1_fingerprint) . '</p></div>',
                ),
                'md5fingerprint' => array(
                    'type'         => 'html',
                    'value'        => '<div><p>' . get_string('md5fingerprint', 'auth.webservice', $openssl->md5_fingerprint) . '</p></div>',
                ),
                'expires' => array(
                    'type'         => 'html',
                    'value'        => '<div><p>' . get_string('publickeyexpireson','auth.webservice', format_date($openssl->expires)) . '</p></div>'
                ),
            ),
            'collapsible' => true,
            'collapsed'   => true,
        ),

        // fieldset for managing service function groups
        'servicefunctiongroups' => array(
            'name' => 'webservices_function_groups',
            'type' => 'fieldset',
            'legend' => get_string('servicefunctiongroups', 'auth.webservice'),
            'elements' => array(
                'sfgdescription' => array(
                    'value' => '<div><p>' . get_string('sfgdescription', 'auth.webservice') . '</p></div>'
                ),
                'webservicesservicecontainer' => array(
                    'type'         => 'html',
                    'value' => webservice_function_groups_form(),
                )
            ),
            'collapsible' => true,
            'collapsed'   => true,
        ),
243 244


245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
        // fieldset for managing service tokens
        'servicetokens' => array(
            'name' => 'webservices_token',
            'type' => 'fieldset',
            'legend' => get_string('servicetokens', 'auth.webservice'),
            'elements' => array(
                'stdescription' => array(
                    'value' => '<div><p>' . get_string('stdescription', 'auth.webservice') . '</p></div>'
                ),
                'webservicestokenscontainer' => array(
                    'type'         => 'html',
                    'value' => webservice_tokens_form()
                )
            ),
            'collapsible' => true,
            'collapsed'   => false,
        ),

        // fieldset for managing service tokens
        'serviceusers' => array(
            'name' => 'webservices_user',
            'type' => 'fieldset',
            'legend' => get_string('manageserviceusers', 'auth.webservice'),
            'elements' => array(
                'sudescription' => array(
                    'value' => '<div><p>' . get_string('sudescription', 'auth.webservice') . '</p></div>'
                ),
                'webservicesuserscontainer' => array(
                    'type'         => 'html',
                    'value' => webservice_users_form(),
                )
            ),
            'collapsible' => true,
            'collapsed'   => false,
        ),
    );
281

282 283 284 285 286
    $form = array(
        'renderer' => 'div',
        'type' => 'div',
        'elements' => $elements,
    );
287

288 289
    return $form;
}
290 291


292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
/**
 * Form layout for the master switch to control whether this site can
 * use webservices provided by an external server.
 *
 * @return pieforms $element array
 */
function webservice_requester_enabled_form() {
    // enable/disable webservices completely
    $enabled = (get_config('webservice_requester_enabled') || 0);
    $element = array(
        'type'  => 'html',
        'value' =>
            pieform(
                array(
                    'name' => 'webservice_requester_enabled_form',
                    'elementclasses' => false,
                    'class'           => 'form-switch form-group',
                    'successcallback' => 'webservice_requester_enabled_submit',
                    'renderer' => 'div',
                    'jsform' => false,
                    'checkdirtychange' => false,
                    'elements' => array(
                        'plugintype' => array('type' => 'hidden', 'value' => 'auth'),
                        'type' => array('type' => 'hidden', 'value' => 'webservice'),
                        'pluginname' => array('type' => 'hidden', 'value' => 'webservice'),
                        'enabled' => array('type' => 'switchbox',
                            'class' => 'switchbox last',
                            'value' => $enabled,
                            'labelhtml' => '<span class="pseudolabel">'. get_string('webservice_requester_enabled_label2', 'auth.webservice') .'</span>',
                        ),
                    ),
                )
            ),
    );

    return $element;
328 329 330
}


331 332 333 334
/**
 * Pieforms submit callback for Webservices Requester form
 */
function webservice_requester_enabled_submit(Pieform $form, $values) {
335

336 337 338 339
    $enabled = $values['enabled'] ? 0 : 1;
    set_config('webservice_requester_enabled', $enabled);
    // Don't reload the page if this was submitted via ajax.
    if (param_boolean('ajax')) {
340 341 342 343 344 345
        if (!get_config('webservice_provider_enabled')) {
            $protos = array('soap','xmlrpc','rest','oauth');
            foreach ($protos as $proto) {
                set_config('webservice_provider_'.$proto.'_enabled', 0);
            }
        }
346 347 348
        exit;
    }
    redirect('/webservice/admin/index.php');
349 350
}

351

352
/**
353 354 355
 * Pieform for the master switch that controls whether Mahara will
 * be a webservices provider (i.e. allow incoming webservices requests
 * from other systems.)
356
 */
357
function webservice_provider_enabled_form() {
358
    // enable/disable webservices completely
359
    $enabled = (get_config('webservice_provider_enabled') || 0);
360 361 362 363
    $element = array(
        'type'  => 'html',
        'value' =>
            pieform(
364
                array(
365
                    'name' => 'webservice_provider_enabled_form',
366 367
                    'elementclasses' => false,
                    'class'           => 'form-switch',
368
                    'successcallback' => 'webservice_provider_enabled_submit',
369 370 371 372 373 374 375 376
                    'renderer' => 'div',
                    'jsform' => false,
                    'checkdirtychange' => false,
                    'elements' => array(
                        'plugintype' => array('type' => 'hidden', 'value' => 'auth'),
                        'type' => array('type' => 'hidden', 'value' => 'webservice'),
                        'pluginname' => array('type' => 'hidden', 'value' => 'webservice'),
                        'enabled' => array('type' => 'switchbox',
Robert Lyon's avatar
Robert Lyon committed
377
                            'class' => 'switchbox last',
378
                            'value' => $enabled,
379
                            'labelhtml' => '<span class="pseudolabel">'. get_string('webservice_provider_enabled_label2', 'auth.webservice') .'</span>',
380
                        ),
381 382 383 384
                    ),
                )
            ),
    );
385

386
    return $element;
387 388
}

389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
/**
 * Pieform callback function for the "Publish webservices" master switch
 */
function webservice_provider_enabled_submit(Pieform $form, $values) {

    $enabled = $values['enabled'] ? 0 : 1;
    set_config('webservice_provider_enabled', $enabled);

    // reload/upgrade the web services configuration
    if ($enabled) {
        // ensure that we have a webservice auth_instance
        $authinstance = get_record('auth_instance', 'institution', 'mahara', 'authname', 'webservice');
        if (empty($authinstance)) {
            $authinstance = (object)array(
               'instancename' => 'webservice',
                'priority'     => 2,
                'institution'  => 'mahara',
                'authname'     => 'webservice',
            );
            insert_record('auth_instance', $authinstance);
        }
        external_reload_webservices();
    }
    if (param_boolean('ajax')) {
413 414 415 416 417
        if (!get_config('webservice_requester_enabled')) {
            $protos = array('soap','xmlrpc','rest','oauth');
            foreach ($protos as $proto) {
                set_config('webservice_provider_'.$proto.'_enabled', 0);
            }
418 419 420 421 422 423
        }
        exit;
    }
    redirect('/webservice/admin/index.php');
}

424 425 426 427 428
/**
 * Form layout for webservices protocol switch fieldset
 *
 * @return pieforms $element array
 */
429
function webservice_provider_protocols_form() {
430 431
    // enable/disable separate protocols of SOAP/XML-RPC/REST
    $elements = array();
432 433 434 435
    $elements['label'] = array(
        'title' => ' ',
        'type' => 'html',
        'class' => 'fake-form',
436
        'value' => '<h4 class="title">' . get_string('protocol', 'auth.webservice') . '</h4>'
437
    );
438 439

    foreach (array('soap', 'xmlrpc', 'rest', 'oauth') as $proto) {
440 441
        $enabled = (get_config('webservice_provider_' . $proto . '_enabled') || 0);
        $elements[$proto] = array(
442 443
            'title' => ' ',
            'type' => 'html',
Naomi Guyer's avatar
Naomi Guyer committed
444
            'class'            => 'fake-form',
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
            'value' => pieform(array(
                'name'            => 'webservice_provider_protocols_' . $proto,
                'elementclasses'  => false,
                'class'           => 'form-switch webservice-provider-protocol-form',
                'renderer'        => 'div',
                'successcallback' => 'webservice_provider_protocols_submit',
                'jsform'          => false,
                'checkdirtychange' => false,
                'elements' => array(
                    'plugintype' => array('type' => 'hidden', 'value' => 'auth'),
                    'type'       => array('type' => 'hidden', 'value' => 'webservice'),
                    'pluginname' => array('type' => 'hidden', 'value' => 'webservice'),
                    'protocol'   => array('type' => 'hidden', 'value' => $proto),
                    'enabled'    => array('type' => 'switchbox',
                        'class' => 'switchbox',
                        'value' => $enabled,
                        'labelhtml' => '<span class="pseudolabel">' .get_string($proto, 'auth.webservice') . ': </span>',
                    ),
                ),
            ))
        );
466 467 468 469 470
    }

    return $elements;
}

471 472 473 474 475 476 477 478

/**
 * Pieform callback function for the per-protocol master switches
 */
function webservice_provider_protocols_submit(Pieform $form, $values) {
    $enabled = $values['enabled'] ? 0 : 1;
    $proto = $values['protocol'];
    set_config('webservice_provider_'.$proto.'_enabled', $enabled);
479 480
    // Show/hide the account settings webservice tokens page
    clear_menu_cache();
481 482 483 484 485 486 487
    if (param_boolean('ajax')) {
        exit;
    }
    redirect('/webservice/admin/index.php');
}


488 489 490 491 492
/**
 * Service Function Groups edit form
 *
 * @return html
 */
493
function webservice_function_groups_form() {
494
    global $THEME;
495

496 497
    $editicon = 'icon icon-pencil left';
    $deleteicon = 'icon icon-trash left text-danger';
498

499 500 501
    $form = array(
        'name'            => 'webservices_function_groups',
        'elementclasses'  => false,
502
        'successcallback' => 'webservice_function_groups_submit',
503 504
        'renderer'   => 'multicolumntable',
        'elements'   => array(
505 506 507 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
            'servicegroup' => array(
                'title' => ' ',
                'datatable' => true,
                'type'  => 'html',
                'value' => get_string('service', 'auth.webservice'),
            ),
            'component' => array(
                'title' => ' ',
                'datatable' => true,
                'type'  => 'html',
                'value' => get_string('component', 'auth.webservice'),
            ),
            'enabled' => array(
                'title' => ' ',
                'datatable' => true,
                'type'  => 'html',
                'value' => get_string('enabled'),
            ),
            'restricted' => array(
                'title' => ' ',
                'datatable' => true,
                'type'  => 'html',
                'value' => get_string('restrictedusers', 'auth.webservice'),
            ),
            'tokenusers' => array(
                'title' => ' ',
                'datatable' => true,
                'type'  => 'html',
                'value' => get_string('fortokenusers', 'auth.webservice'),
            ),
            'functions' => array(
                'title' => ' ',
                'datatable' => true,
                'type'  => 'html',
                'value' => get_string('functions', 'auth.webservice'),
            ),
            'actions' => array(
                'title' => ' ',
                'datatable' => true,
                'type'  => 'html',
                'value' => '',
            ),
        ),
548 549
        );

550 551 552 553 554 555 556
    $dbservices = get_records_array(
        'external_services',
        null,
        null,
        'component, name',
        'id, name, shortname, component, enabled, restrictedusers, tokenusers'
    );
557 558
    if ($dbservices) {
        foreach ($dbservices as $service) {
559
            $iscustomservice = ($service->component === '');
560
            $form['elements']['id'. $service->id . '_service'] = array(
561 562
                'value'        =>  $service->name .
                    ($service->shortname ? ' (' . $service->shortname . ')' : ''),
563 564 565 566
                'type'         => 'html',
                'key'          => $service->name,
            );
            $form['elements']['id'. $service->id . '_component'] = array(
567
                'value'        => ($iscustomservice ? get_string('customservicegroup', 'auth.webservice') : $service->component),
568 569 570 571
                'type'         => 'html',
                'key'          => $service->name,
            );
            $form['elements']['id'. $service->id . '_enabled'] = array(
572 573 574
                'value'        => (($service->enabled == 1) ? display_icon('enabled') : display_icon('disabled')),
                'type'         => 'html',
                'class'        => 'center',
575 576 577
                'key'          => $service->name,
            );
            $form['elements']['id'. $service->id . '_restricted'] = array(
578 579 580
                'value' => (($service->restrictedusers == 1) ?  display_icon('enabled') : display_icon('disabled')),
                'type'         => 'html',
                'class'        => 'center',
581 582 583
                'key'          => $service->name,
            );
            $form['elements']['id'. $service->id . '_tokenusers'] = array(
584 585 586
                'value' => (($service->tokenusers == 1) ?  display_icon('enabled') : display_icon('disabled')),
                'type'         => 'html',
                'class'        => 'center',
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
                'key'          => $service->name,
            );
            $functions = get_records_array('external_services_functions', 'externalserviceid', $service->id);
            $function_list = array();
            if ($functions) {
                foreach ($functions as $function) {
                    $dbfunction = get_record('external_functions', 'name', $function->functionname);
                    $function_list[]= '<a href="' . get_config('wwwroot') . 'webservice/wsdoc.php?id=' . $dbfunction->id . '">' . $function->functionname . '</a>';
                }
            }
            $form['elements']['id'. $service->id . '_functions'] = array(
                'value'        =>  implode(', ', $function_list),
                'type'         => 'html',
                'key'          => $service->name,
            );

            // edit and delete buttons
            $form['elements']['id'. $service->id . '_actions'] = array(
605
                'value'        => pieform(array(
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
                    'name'            => 'webservices_function_groups_edit_' . $service->id,
                    'renderer'        => 'div',
                    'class'  => 'form-as-button pull-left',
                    'successcallback' => 'webservice_function_groups_submit',
                    'jsform'          => false,
                    'action'          => get_config('wwwroot') . 'webservice/admin/index.php',
                    'elements' => array(
                        'service'    => array('type' => 'hidden', 'value' => $service->id),
                        'action'     => array('type' => 'hidden', 'value' => 'edit'),
                        'submit'     => array(
                            'type'  => 'button',
                            'class' => 'btn-default btn-sm',
                            'usebuttontag' => true,
                            'value'   => '<span class="'.$editicon.'"></span>' . get_string('edit', 'mahara'),
                            'elementtitle' => get_string('edit'),
                        ),
                    ),
                ))
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
                . (
                    $iscustomservice ?
                        pieform(array(
                            'name'            => 'webservices_function_groups_delete_' . $service->id,
                            'renderer'        => 'div',
                            'class'  => 'form-as-button pull-left',
                            'successcallback' => 'webservice_function_groups_submit',
                            'jsform'          => false,
                            'action'          => get_config('wwwroot') . 'webservice/admin/index.php',
                            'elements' => array(
                                'service'    => array('type' => 'hidden', 'value' => $service->id),
                                'action'     => array('type' => 'hidden', 'value' => 'delete'),
                                'submit'     => array(
                                    'type'  => 'button',
                                    'usebuttontag' => true,
                                    'class' => 'btn-default btn-sm',
                                    'value'   => '<span class="'.$deleteicon.'"></span>' . get_string('delete', 'mahara'),
                                    'elementtitle' => get_string('delete'),
                                ),
                            ),
                        ))
                        : ''
                ),
647 648
                'type'         => 'html',
                'key'          => $service->name,
649
                'class'        => 'webserviceconfigcontrols btn-group',
650 651 652
            );
        }
    }
653

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
    $pieform = pieform_instance($form);
    return $pieform->build(false) . '<div class="function_add">' .
        pieform(array(
            'name'            => 'webservices_function_groups_add',
            'renderer'        => 'div',
            'successcallback' => 'webservice_function_groups_submit',
            'class'           => 'form-inline',
            'jsform'          => false,
            'action'          => get_config('wwwroot') . 'webservice/admin/index.php',
            'elements' => array(
                'service'    => array(
                    'type' => 'text',
                    'class' => 'last'
                ),
                'action'     => array('type' => 'hidden', 'value' => 'add'),
                'submit'     => array(
                    'type'  => 'submit',
                    'class' => 'submit btn-primary last',
                    'value' => get_string('add')
                ),
            ),
        )) .
        '</div>';
}


/**
 * Pieform callback for the "function groups" section
 */
function webservice_function_groups_submit(Pieform $form, $values) {
    global $SESSION;

    if ($values['action'] == 'add') {
        $service = preg_replace('/[^a-zA-Z0-9_ ]+/', '', $values['service']);
        $service = trim($service);
        if (empty($service) || record_exists('external_services', 'name', $service)) {
            $SESSION->add_error_msg(get_string('invalidinput', 'auth.webservice'));
        }
        else {
693
            $service = array('name' => $service, 'restrictedusers' => 0, 'enabled' => 0, 'tokenusers' => 0, 'component' => '', 'ctime' => db_format_timestamp(time()));
694 695 696 697 698 699 700 701 702 703 704
            insert_record('external_services', $service);
            $SESSION->add_ok_msg(get_string('configsaved', 'auth.webservice'));
        }
    }
    else {
        $service = get_record('external_services', 'id', $values['service']);
        if (!empty($service)) {
            if ($values['action'] == 'edit') {
                redirect('/webservice/admin/serviceconfig.php?service=' . $values['service']);
            }
            else if ($values['action'] == 'delete') {
705 706 707 708 709 710 711 712 713 714 715
                $component = get_field('external_services', 'component', 'id', $values['service']);
                // Can't manually delete plugin-provided services; only disable them.
                if ($component === '') {
                    // remove everything associated with a service
                    $params = array($values['service']);
                    delete_records_select('external_tokens', "externalserviceid  = ?", $params);
                    delete_records_select('external_services_users', "externalserviceid  = ?", $params);
                    delete_records_select('external_services_functions', "externalserviceid  = ?", $params);
                    delete_records('external_services', 'id', $values['service']);
                    $SESSION->add_ok_msg(get_string('configsaved', 'auth.webservice'));
                }
716 717 718 719 720 721
            }
        }
    }

    // default back to where we came from
    redirect('/webservice/admin/index.php?open=webservices_function_groups');
722 723
}

724

725 726 727 728 729
/**
 * Service Tokens Groups edit form
 *
 * @return html
 */
730
function webservice_tokens_form() {
731 732
    global $THEME, $USER;

733 734
    $editicon = 'icon icon-pencil left';
    $deleteicon = 'icon icon-trash left text-danger';
735

736 737 738
    $form = array(
        'name'            => 'webservices_tokens',
        'elementclasses'  => false,
739
        'successcallback' => 'webservice_tokens_submit',
740
        'renderer'   => 'multicolumntable',
741
        'elements'   => array(
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
            'token' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('token', 'auth.webservice'),
            ),
            'institution' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('institution'),
            ),
            'username' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('username', 'auth.webservice'),
            ),
            'servicename' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('servicename', 'auth.webservice'),
            ),
            'enabled' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('enabled'),
            ),
            'wssigenc' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('titlewssigenc', 'auth.webservice'),
            ),
            'functions' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('functions', 'auth.webservice'),
            ),
            'actions' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => '',
            ),
        ),
    );
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823

    $dbtokens = get_records_sql_array('SELECT et.id as tokenid, et.wssigenc AS wssigenc, et.externalserviceid as externalserviceid, et.institution as institution, u.id as userid, u.username as username, et.token as token, es.name as name, es.enabled as enabled FROM {external_tokens} AS et LEFT JOIN {usr} AS u ON et.userid = u.id LEFT JOIN {external_services} AS es ON et.externalserviceid = es.id WHERE et.tokentype = ? ORDER BY u.username', array(EXTERNAL_TOKEN_PERMANENT));
    if (!empty($dbtokens)) {
        foreach ($dbtokens as $token) {
            $form['elements']['id'. $token->tokenid . '_token'] = array(
                'value'        =>  $token->token,
                'type'         => 'html',
                'key'          => $token->token,
            );
            $dbinstitution = get_record('institution', 'name', $token->institution);
            $form['elements']['id'. $token->tokenid . '_institution'] = array(
                'value'        =>  $dbinstitution->displayname,
                'type'         => 'html',
                'key'          => $token->token,
            );
            if ($USER->is_admin_for_user($token->userid)) {
                $user_url = get_config('wwwroot') . 'admin/users/edit.php?id=' . $token->userid;
            }
            else {
                $user_url = get_config('wwwroot') . 'user/view.php?id=' . $token->userid;
            }
            $form['elements']['id'. $token->tokenid . '_username'] = array(
                'value'        =>  '<a href="' . $user_url . '">' . $token->username . '</a>',
                'type'         => 'html',
                'key'          => $token->token,
            );
            $form['elements']['id'. $token->tokenid . '_servicename'] = array(
                'value'        =>  $token->name,
                'type'         => 'html',
                'key'          => $token->token,
            );
            $form['elements']['id'. $token->tokenid . '_enabled'] = array(
824 825 826
                'value' => (($token->enabled == 1) ? display_icon('enabled') : display_icon('disabled')),
                'type'         => 'html',
                'class'        => 'center',
827 828 829
                'key'          => $token->token,
            );
            $form['elements']['id'. $token->tokenid . '_wssigenc'] = array(
830 831 832
                'value' => (($token->wssigenc == 1) ? display_icon('enabled') : display_icon('disabled')),
                'type'         => 'html',
                'class'        => 'center',
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
                'key'          => $token->token,
            );

            $functions = get_records_array('external_services_functions', 'externalserviceid', $token->externalserviceid);
            $function_list = array();
            if ($functions) {
                foreach ($functions as $function) {
                    $dbfunction = get_record('external_functions', 'name', $function->functionname);
                    $function_list[]= '<a href="' . get_config('wwwroot') . 'webservice/wsdoc.php?id=' . $dbfunction->id . '">' . $function->functionname . '</a>';
                }
            }
            $form['elements']['id'. $token->tokenid . '_functions'] = array(
                'value'        =>  implode(', ', $function_list),
                'type'         => 'html',
                'key'          => $token->token,
            );

            // edit and delete buttons
            $form['elements']['id'. $token->tokenid . '_actions'] = array(
852
                'value'        => pieform(array(
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
                    'name'            => 'webservices_token_edit_' . $token->tokenid,
                    'renderer'        => 'div',
                    'elementclasses'  => false,
                    'successcallback' => 'webservice_token_submit',
                    'class'           => 'form-as-button pull-left',
                    'jsform'          => false,
                    'elements' => array(
                        'token'      => array('type' => 'hidden', 'value' => $token->tokenid),
                        'action'     => array('type' => 'hidden', 'value' => 'edit'),
                        'submit'     => array(
                            'type'  => 'button',
                            'usebuttontag' => true,
                            'class' => 'btn-default btn-sm',
                            'value'   => '<span class="'.$editicon.'"></span>' . get_string('edit'),
                            'elementtitle' => get_string('editspecific', 'mahara', $token->tokenid),
                        ),
                    ),
                ))
                . pieform(array(
                    'name'            => 'webservices_token_delete_' . $token->tokenid,
                    'renderer'        => 'div',
                    'elementclasses'  => false,
                    'successcallback' => 'webservice_token_submit',
                    'class'           => 'form-as-button pull-left',
                    'jsform'          => false,
                    'elements' => array(
                        'token'      => array('type' => 'hidden', 'value' => $token->tokenid),
                        'action'     => array('type' => 'hidden', 'value' => 'delete'),
                        'submit'     => array(
                            'type'  => 'button',
                            'usebuttontag' => true,
                            'class' => 'btn-default btn-sm',
                            'value'   => '<span class="'.$deleteicon.'"></span>' . get_string('delete'),
                            'elementtitle' => get_string('deletespecific', 'mahara', $token->tokenid),
                        ),
                    ),
                )),
890 891
                'type'         => 'html',
                'key'          => $token->token,
892
                'class'        => 'webserviceconfigcontrols btn-group',
893 894 895
            );
        }
    }
896 897 898 899
    else {
        // no results so hide headings
        $form['elements'] = array();
    }
900 901 902 903 904 905 906 907 908 909 910

    $username = '';
    if ($user  = param_integer('user', 0)) {
        $dbuser = get_record('usr', 'id', $user);
        if (!empty($dbuser)) {
            $username = $dbuser->username;
        }
    }
    else {
        $username = param_alphanum('username', '');
    }
911
    $pieform = pieform_instance($form);
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
    return $pieform->build(false) . '<div class="function_add">'
        . pieform(array(
            'name'            => 'webservices_token_generate',
            'renderer'        => 'div',
            'successcallback' => 'webservice_token_submit',
            'jsform'          => false,
            'action'          => get_config('wwwroot') . 'webservice/admin/index.php',
            'elements' => array(
                'userid' => array(
                    'type' => 'autocomplete',
                    'title' => get_string('username') . ': ',
                    'ajaxurl' => get_config('wwwroot') . 'webservice/admin/users.json.php',
                    'multiple' => true,
                    'allowclear' => true,
                    'ajaxextraparams' => array(),
                    'extraparams' => array(
                        'maximumSelectionLength' => 1
                    ),
                    'width' => '280px',
                ),
                'action'     => array('type' => 'hidden', 'value' => 'generate'),
                'submit'     => array(
                    'type'  => 'submit',
                    'class' => 'submit btn-primary last',
                    'value' => get_string('generate', 'auth.webservice')
                ),
            ),
        ))
        . '</div>';
941 942 943

}

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995

/**
 * Pieform callback for the webservices token management form
 */
function webservice_token_submit(Pieform $form, $values) {
    global $SESSION, $USER;

    if ($values['action'] == 'generate') {
        if (!empty($values['userid'][0])) {
            $dbuser = get_record('usr', 'id', $values['userid'][0]);
            if (!empty($dbuser)) {
                $services = get_records_array('external_services', 'restrictedusers', 0);
                if (empty($services)) {
                    $SESSION->add_error_msg(get_string('noservices', 'auth.webservice'));
                }
                else {
                    // just pass the first one for the moment
                    $service = array_shift($services);
                    $token = webservice_generate_token(EXTERNAL_TOKEN_PERMANENT, $service, $dbuser->id);
                    $dbtoken = get_record('external_tokens', 'token', $token);
                    redirect('/webservice/admin/tokenconfig.php?token=' . $dbtoken->id);
                }
            }
            else {
                $SESSION->add_error_msg(get_string('invaliduserselected', 'auth.webservice'));
            }
        }
        else {
            $SESSION->add_error_msg(get_string('nouser', 'auth.webservice'));
        }

    }
    else {
        $token = get_record('external_tokens', 'id', $values['token']);
        if (!empty($token)) {
            if ($values['action'] == 'edit') {
                redirect('/webservice/admin/tokenconfig.php?token=' . $values['token']);
            }
            else if ($values['action'] == 'delete') {
                // remove everything associated with a service
                $params = array($values['token']);
                delete_records_select('external_tokens', "id = ?", $params);
                $SESSION->add_ok_msg(get_string('configsaved', 'auth.webservice'));
            }
        }
    }

    // default back to where we came from
    redirect('/webservice/admin/index.php?open=webservices_token');
}


996 997 998 999 1000
/**
 * Service Users edit form
 *
 * @return html
 */
1001
function webservice_users_form() {
1002 1003
    global $THEME, $USER;

1004 1005
    $editicon = 'icon icon-pencil left';
    $deleteicon = 'icon icon-trash left text-danger';
1006

1007 1008 1009
    $form = array(
        'name'            => 'webservices_users',
        'elementclasses'  => false,
1010
        'successcallback' => 'webservice_users_submit',
1011 1012
        'renderer'   => 'multicolumntable',
        'elements'   => array(
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
            'username' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('username', 'auth.webservice'),
            ),
            'institution' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('institution'),
            ),
            'servicename' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('servicename', 'auth.webservice'),
            ),
            'enabled' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('enabled'),
            ),
            'wssigenc' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('titlewssigenc', 'auth.webservice'),
            ),
            'functions' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => get_string('functions', 'auth.webservice'),
            ),
            'actions' => array(
                'title' => ' ',
                'datatable'  => true,
                'type'  => 'html',
                'value' => '',
            ),
        ),
    );
1057

1058
    $dbusers = get_records_sql_array('SELECT eu.id as id, eu.userid as userid, eu.wssigenc AS wssigenc, eu.externalserviceid as externalserviceid, eu.institution as institution, u.username as username, es.name as name, es.enabled as enabled FROM {external_services_users} AS eu LEFT JOIN {usr} AS u ON eu.userid = u.id LEFT JOIN {external_services} AS es ON eu.externalserviceid = es.id ORDER BY eu.id', array());
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    if (!empty($dbusers)) {
        foreach ($dbusers as $user) {
            $dbinstitution = get_record('institution', 'name', $user->institution);
            if ($USER->is_admin_for_user($user->id)) {
                $user_url = get_config('wwwroot') . 'admin/users/edit.php?id=' . $user->userid;
            }
            else {
                $user_url = get_config('wwwroot') . 'user/view.php?id=' . $user->userid;
            }
            $form['elements']['id'. $user->id . '_username'] = array(
                'value'        =>  '<a href="' . $user_url . '">' . $user->username . '</a>',
                'type'         => 'html',
                'key'          => $user->id,
            );
            $form['elements']['id'. $user->id . '_institution'] = array(
                'value'        =>  $dbinstitution->displayname,
                'type'         => 'html',
                'key'          => $user->id,
            );
            $form['elements']['id'. $user->id . '_servicename'] = array(
                'value'        =>  $user->name,
                'type'         => 'html',
                'key'          => $user->id,
            );
            $form['elements']['id'. $user->id . '_enabled'] = array(
1084 1085 1086
                'value' => (($user->enabled == 1) ?  display_icon('enabled') : display_icon('disabled')),
                'type'         => 'html',
                'class'        => 'center',
1087 1088 1089
                'key'          => $user->id,
            );
            $form['elements']['id'. $user->id . '_wssigenc'] = array(
1090 1091 1092
                'value' => (($user->wssigenc == 1) ?  display_icon('enabled') : display_icon('disabled')),
                'type'         => 'html',
                'class'        => 'center',
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
                'key'          => $user->id,
            );

            $functions = get_records_array('external_services_functions', 'externalserviceid', $user->externalserviceid);
            $function_list = array();
            if ($functions) {
                foreach ($functions as $function) {
                    $dbfunction = get_record('external_functions', 'name', $function->functionname);
                    $function_list[]= '<a href="' . get_config('wwwroot') . 'webservice/wsdoc.php?id=' . $dbfunction->id . '">' . $function->functionname . '</a>';
                }
            }
            $form['elements']['id'. $user->id . '_functions'] = array(
                'value'        =>  implode(', ', $function_list),
                'type'         => 'html',
                'key'          => $user->id,
            );

            // edit and delete buttons
            $form['elements']['id'. $user->id . '_actions'] = array(
1112
                'value'        => pieform(array(
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
                    'name'            => 'webservices_user_edit_' . $user->id,
                    'renderer'        => 'div',
                    'elementclasses'  => false,
                    'successcallback' => 'webservice_users_submit',
                    'class'           => 'form-as-button pull-left',
                    'jsform'          => false,
                    'elements' => array(
                        'suid'       => array('type' => 'hidden', 'value' => $user->id),
                        'action'     => array('type' => 'hidden', 'value' => 'edit'),
                        'submit'     => array(
                            'type'  => 'button',
                            'usebuttontag' => true,
                            'class' => 'btn-default btn-sm',
                            'value'   => '<span class="'. $editicon.'" role="presentation" aria-hidden="true"></span>' . get_string('edit'),
                            'elementtitle' => get_string('editspecific', 'mahara', $user->username),
                        ),
                    ),
                ))
                . pieform(array(
                    'name'            => 'webservices_user_delete_' . $user->id,
                    'renderer'        => 'div',
                    'elementclasses'  => false,
                    'successcallback' => 'webservice_users_submit',
                    'class'           => 'form-as-button pull-left',
                    'jsform'          => false,
                    'elements' => array(
                        'suid'       => array('type' => 'hidden', 'value' => $user->id),
                        'action'     => array('type' => 'hidden', 'value' => 'delete'),
                        'submit'     => array(
                            'type'  => 'button',
                            'usebuttontag' => true,
                            'class' => 'btn-default btn-sm',
                            'value'   => '<span class="'.$deleteicon.'" role="presentation" aria-hidden="true"></span>' . get_string('delete'),
                            'elementtitle' => get_string('deletespecific', 'mahara', $user->username),
                        ),
                    ),
                )),
1150 1151
                'type'         => 'html',
                'key'          => $user->id,
1152
                'class'        => 'webserviceconfigcontrols btn-group',
1153 1154 1155
            );
        }
    }
1156 1157 1158 1159
    else {
        // no results so hide headings
        $form['elements'] = array();
    }
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170

    $username = '';
    if ($user  = param_integer('user', 0)) {
        $dbuser = get_record('usr', 'id', $user);
        if (!empty($dbuser)) {
            $username = $dbuser->username;
        }
    }
    else {
        $username = param_alphanum('username', '');
    }
1171

1172
    $pieform = pieform_instance($form);
1173
    return $pieform->build(false) . '<div id="user_add">' .
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
        pieform(array(
            'name'            => 'webservices_user_generate',
            'renderer'        => 'div',
            'successcallback' => 'webservice_users_submit',
            'jsform'          => false,
            'action'          => get_config('wwwroot') . 'webservice/admin/index.php',
            'elements' => array(
                'userid' => array(
                    'type' => 'autocomplete',
                    'title' => get_string('username') . ': ',
                    'ajaxurl' => get_config('wwwroot') . 'webservice/admin/users.json.php',
                    'multiple' => true,
                    'allowclear' => true,
                    'ajaxextraparams' => array(),
                    'extraparams' => array(
                        'maximumSelectionLength' => 1
1190
                    ),
1191 1192 1193 1194 1195 1196 1197 1198
                    'width' => '280px',
                ),
                'action'     => array('type' => 'hidden', 'value' => 'add'),
                'submit'     => array(
                    'type'  => 'submit',
                    'class' => 'submit btn-primary last',
                    'value' => get_string('add')
                ),
1199
            ),
1200 1201
        ))
        . '</div>';
1202 1203 1204
}


1205
/**
1206
 * Pieform callback for the user permissions section
1207
 */
1208 1209
function webservice_users_submit(Pieform $form, $values) {
    global $SESSION, $USER;
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
    if ($values['action'] == 'add') {
        if (!empty($values['userid'][0])) {
            $dbuser = get_record('usr', 'id', $values['userid'][0]);
            if ($auth_instance = webservice_validate_user($dbuser)) {
                // make sure that this account is not already in use
                $existing = get_record('external_services_users', 'userid', $dbuser->id);
                if (empty($existing)) {
                    $services = get_records_array('external_services', 'restrictedusers', 1);
                    if (empty($services)) {
                      $SESSION->add_error_msg(get_string('noservices', 'auth.webservice'));
                    }
                    else {
                        // just pass the first one for the moment
                        $service = array_shift($services);
                        $dbserviceuser = (object) array(
                            'externalserviceid' => $service->id,
                            'userid' => $dbuser->id,
                            'institution' => $auth_instance->institution,
                            'ctime' => db_format_timestamp(time()),
                            'publickeyexpires' => time(),
                            'wssigenc' => 0,
                            'publickey' => '');
                        $dbserviceuser->id = insert_record('external_services_users', $dbserviceuser, 'id', true);
                        redirect('/webservice/admin/userconfig.php?suid=' . $dbserviceuser->id);
                    }
                }
                else {
                    $SESSION->add_error_msg(get_string('duplicateuser', 'auth.webservice'));
                }
            }
            else {
                $SESSION->add_error_msg(get_string('invaliduserselected', 'auth.webservice'));
            }
        }
        else {
            $SESSION->add_error_msg(get_string('nouser', 'auth.webservice'));
        }
    }
    else {
        $dbserviceuser = get_record('external_services_users', 'id', $values['suid']);
        if (!empty($dbserviceuser)) {
            if ($values['action'] == 'edit') {
                redirect('/webservice/admin/userconfig.php?suid=' . $values['suid']);
            }
            else if ($values['action'] == 'delete') {
                // remove everything associated with a service
                $params = array($values['suid']);
                delete_records_select('external_services_users', "id = ?", $params);
                $SESSION->add_ok_msg(get_string('configsaved', 'auth.webservice'));
            }
        }
    }
1263

1264 1265
    // default back to where we came from
    redirect('/webservice/admin/index.php?open=webservices_user');
1266
}