serviceconfig.php 14.8 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
 *
 */

define('INTERNAL', 1);
define('ADMIN', 1);
14
define('MENUITEM', 'webservices');
15 16 17 18
require(dirname(dirname(dirname(__FILE__))) . '/init.php');
define('TITLE', get_string('pluginadmin', 'admin'));

$service  = param_integer('service', 0);
19 20 21 22 23 24
$dbservice = get_record(
    'external_services',
    'id', $service,
    null, null, null, null,
    'id, name, shortname, component, restrictedusers, tokenusers, enabled'
);
25 26
if (empty($dbservice)) {
    $SESSION->add_error_msg(get_string('invalidservice', 'auth.webservice'));
27
    redirect('/webservice/admin/index.php?open=webservices_function_groups');
28 29 30 31
}
$enabled = $dbservice->enabled;
$restrictedusers = ($dbservice->restrictedusers <= 0 ? 0 : 1);
$tokenusers = ($dbservice->tokenusers <= 0 ? 0 : 1);
32
$ispluginservice = ('' !== $dbservice->component);
33

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
$functions = array(
    'elements' => array(
        'enabledname' => array(
            'title' => ' ',
            'class' => 'heading',
            'type'  => 'html',
            'value' => get_string('enabled'),
        ),
        'classname' => array(
            'title' => ' ',
            'class' => 'heading',
            'type'  => 'html',
            'value' => get_string('classname', 'auth.webservice'),
        ),
        'methodname' => array(
            'title' => ' ',
            'class' => 'heading',
            'type'  => 'html',
            'value' => get_string('methodname', 'auth.webservice'),
        ),
    ),
);
56

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
if (!$ispluginservice) {
    // Custom service - let the user add/remove functions
    $dbfunctions = get_records_array('external_functions', null, null, 'name');
}
else {
    // In a non-custom service, the list of functions can't be changed. So
    // only display the ones that are actually included in this service.
    $dbfunctions = get_records_sql_array(
        'SELECT ef.*
        FROM
            {external_services_functions} esf
            INNER JOIN {external_functions} ef
                ON esf.functionname = ef.name
        WHERE esf.externalserviceid = ?
        ORDER BY ef.name',
        array($dbservice->id)
    );
}
75 76 77 78
foreach ($dbfunctions as $function) {
    $sfexists = record_exists('external_services_functions', 'externalserviceid', $dbservice->id, 'functionname', $function->name);
    $functions['elements']['id' . $function->id . '_enabled'] = array(
        'defaultvalue' => ($sfexists ? 'checked' : ''),
79
        'type'         => 'switchbox',
80
        'disabled'     => $ispluginservice,
81 82 83 84 85 86 87 88 89 90
        'title'        => $function->name,
    );

    $functions['elements']['id' . $function->id . '_class'] = array(
        'value'        =>  $function->classname,
        'type'         => 'html',
        'title'        => $function->name,
    );

    $functions['elements']['id' . $function->id . '_method'] = array(
91
        'value'        =>  '<a class="dialogue" href="' . get_config('wwwroot') . 'webservice/wsdoc.php?id=' . $function->id . '">' . $function->methodname . '</a>',
92 93 94 95 96 97
        'type'         => 'html',
        'title'        => $function->name,
    );
}

$functions['elements']['submit'] = array(
98
            'type'  => 'submitcancel',
99
            'class' => 'btn-primary submitcancel',
100 101 102
            'value' => array(get_string('save'), get_string('back')),
            'goto'  => get_config('wwwroot') . 'webservice/admin/index.php?open=webservices_function_groups',
        );
103
$heading = get_string('servicegroup', 'auth.webservice', $dbservice->name);
104 105

$elements = array(
106 107 108 109
    'service' => array(
        'type' => 'hidden',
        'value' => $dbservice->id
    ),
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    // fieldset of name & shortname
    'namefieldset' => array(
        'legend' => $heading,
        'type' => 'fieldset',
        'elements' => array(
            'name' => array(
                'type'         => 'text',
                'title'        => get_string('servicenamelabel', 'auth.webservice'),
                'rules'        => array(
                    'required' => !$ispluginservice,
                    'maxlength' => 200
                ),
                'description'  => get_string('servicenamedesc', 'auth.webservice'),
                'defaultvalue' => $dbservice->name,
                'disabled' => $ispluginservice,
            ),
            'shortname' => array(
                'type' => 'text',
                'title' => get_string('serviceshortnamelabel', 'auth.webservice'),
                'rules' => array(
                    'maxlength' => 200
                ),
                'description' => get_string('serviceshortnamedesc', 'auth.webservice'),
                'defaultvalue' => $dbservice->shortname,
                'disabled' => $ispluginservice,
            ),
        ),
        'collapsible' => true,
        'collapsed' => false,
    ),
140 141
    // fieldset of master switch
    'webservicesmaster' => array(
142 143 144 145 146 147 148 149 150
        'type' => 'fieldset',
        'legend' => get_string('enableservice', 'auth.webservice'),
        'elements' =>  array(
            'enabled' => array(
                'type' => 'switchbox',
                'defaultvalue' => $enabled,
                'on_label' => get_string('enabled'),
                'off_label' => get_string('disabled'),
                'wrapperclass' => 'switch-wrapper-inline',
Naomi Guyer's avatar
Naomi Guyer committed
151
                'labelhtml' => '<span class="pseudolabel">' . get_string('servicename', 'auth.webservice') .'</span>',
152 153 154 155 156 157 158
            ),
            'restrictedusers' => array(
                'type' => 'switchbox',
                'defaultvalue' => $restrictedusers,
                'on_label' => get_string('usersonly', 'auth.webservice'),
                'off_label' => get_string('tokensonly', 'auth.webservice'),
                'wrapperclass' => 'switch-wrapper-inline',
Naomi Guyer's avatar
Naomi Guyer committed
159
                'labelhtml' => '<span class="pseudolabel">' . get_string('restrictedusers', 'auth.webservice') .'</span>',
160 161 162 163 164 165 166
            ),
            'tokenusers' => array(
                'type' => 'switchbox',
                'defaultvalue' => $tokenusers,
                'on_label' => get_string('enabled'),
                'off_label' => get_string('disabled'),
                'wrapperclass' => 'switch-wrapper-inline',
Naomi Guyer's avatar
Naomi Guyer committed
167
                'labelhtml' => '<span class="pseudolabel">' . get_string('fortokenusers', 'auth.webservice') .'</span>',
168 169 170 171
            ),
        ),
        'collapsible' => true,
        'collapsed'   => false,
172 173 174 175
    ),
    // fieldset for managing service function list
    'functions' => array(
        'type' => 'fieldset',
Naomi Guyer's avatar
Naomi Guyer committed
176
        'class' => 'last',
177 178
        'renderer' => 'multicolumnfieldsettable',
        'columns' => array('enabledname', 'classname', 'methodname'),
Naomi Guyer's avatar
Naomi Guyer committed
179
        'footer' => array('submit'),
180
        'legend' => get_string('servicefunctionlist', 'auth.webservice'),
181 182 183 184
        'comment' => get_string('sfldescription', 'auth.webservice'),
        'elements' => $functions['elements'],
        'collapsible' => true,
        'collapsed'   => false,
185 186
    ),
);
187

188 189 190 191 192 193 194
if ($ispluginservice) {
    $elements['namefieldset']['elements']['component'] = array(
        'type' => 'html',
        'value' => get_string('servicecomponentnote', 'auth.webservice', $dbservice->component)
    );
}

195
$form = array(
Naomi Guyer's avatar
Naomi Guyer committed
196
    'renderer' => 'div',
197 198 199
    'type' => 'div',
    'id' => 'maintable',
    'elements' => $elements,
200
    'jsform' => false,
201 202
);

203
$heading = get_string('servicegroup', 'auth.webservice', $dbservice->name);
204 205 206
$form['name'] = 'serviceconfig';
$form['successcallback'] = 'serviceconfig_submit';
$form = pieform($form);
207
$inlinejs = <<<EOF
208
<script type="application/javascript">
209 210
jQuery(function($) {
    $(".dialogue").click(function(e) {
211
        e.preventDefault();
212
        e.stopPropagation();
213
        // fetch the info for the method
214
        $.ajax({
215 216 217
            url: e.currentTarget.href + '&dialog=1',
        }).done(function(data) {
            // close any open dialogs
218 219 220
            $(".js-page-modal .modal-body").html(data).css("max-height", "80vh");
            $(".js-page-modal .modal-dialog").css("width", "80vw");
            $(".js-page-modal").modal('show');
221 222 223 224 225 226 227
        });
    });
});
</script>
EOF;
$headers[] = $inlinejs;
$smarty = smarty(array(), $headers, array('Close' => 'mahara', 'wsdoc' => 'auth.webservice'));
228 229 230 231 232
safe_require('auth', 'webservice');
$smarty->assign('form', $form);
$smarty->assign('PAGEHEADING', $heading);
$smarty->display('form.tpl');

233 234 235 236 237 238 239 240 241 242 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 281 282 283 284 285 286 287 288 289 290 291
function serviceconfig_validate(Pieform $form, $values) {
    // Some fields can't be edited on a plugin's service. So don't bother validating
    // any inputs relating to them.
    $ispluginservice = ('' !== get_field('external_services', 'component', 'id', $values['service']));
    if (!$ispluginservice) {

        // name must be unique
        if (
            isset($values['name'])
            && record_exists_select(
                'external_services',
                'name = ? AND id <> ?',
                array($values['name'], $values['service'])
            )
        ) {
            $form->set_error('name', get_string('servicenamemustbeunique', 'auth.webservice'));
        }

        // component and shortname together must be unique
        if (
            isset($values['shortname'])
            && $values['shortname'] !== ''
            && record_exists_select(
                'external_services',
                'shortname = ? AND (component = \'\' OR component IS NULL) AND id <> ?',
                array($values['shortname'], $values['service'])
            )
        ) {
            $form->set_error('shortname', get_string('serviceshortnamemustbeunique', 'auth.webservice'));
        }
    }
}

/**
 * HACK: This function was not written following normal Mahara coding standards.
 * The following things should be cleaned up at some point:
 *
 * 1. It mixes submission and validation (throwing exceptions in the case of
 * a validation failure). The validation should be moved to a separate
 * Pieforms validation handler.
 *
 * 2. Remove the global $service. Instead, use $values['service'].
 *
 * 3. Use a clean "$todb" object to update only the changed fields in the
 * database (instead of using the global $dbservice, which is a whole-row record.
 *
 * 4. Remove the global $dbservice once it's not needed.
 *
 * 5. Instead of the backwards check for form fields that look like function
 * names and then checking the DB to see if each one exists; just do one
 * query to get all the functions, then check for a form field that looks like
 * each one.
 *
 * 6. Do one "update_record()" call at the end of the function, instead
 * of a separate one for each form field.
 *
 * @param Pieform $form
 * @param array $values
 */
292 293 294
function serviceconfig_submit(Pieform $form, $values) {
    global $SESSION, $service, $dbservice;

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
    // Indicates whether this service was generated by a plugin (in which case
    // the admin can change access to it, but can't change its function list
    // or its name & shortname
    $ispluginservice = ('' !== $dbservice->component);

    // Can't edit name of plugin-provided services
    if (!$ispluginservice && isset($values['name'])) {
        $dbservice->name = $values['name'];
        update_record('external_services', $dbservice);
    }

    // Can't edit shortname of plugin-provided services
    if (!$ispluginservice && isset($values['shortname'])) {
        $dbservice->shortname = $values['shortname'];
        update_record('external_services', $dbservice);
    }

312
    if (isset($values['enabled'])) {
313
        $enabled = $values['enabled'] ? 1 : 0;
314 315 316
        $dbservice->enabled = $enabled;
        update_record('external_services', $dbservice);
    }
317
    $tokenwarning = false;
318 319
    if (isset($values['tokenusers'])) {
        $tokenusers = $values['tokenusers'] ? 1 : 0;
320 321 322 323
        // We may need to issue a warning that this will cut off some users' access
        if ($dbservice->tokenusers && !$tokenusers) {
            $tokenwarning = true;
        }
324 325 326
        $dbservice->tokenusers = $tokenusers;
        update_record('external_services', $dbservice);
    }
327
    $restrictwarning = false;
328
    if (isset($values['restrictedusers'])) {
329
        // flip flop
330
        $restrict = ($values['restrictedusers'] <= 0 ? 0 : 1);
331 332 333
        // We may need to issue a warning that this will cut off some users' access
        if (!$dbservice->restrictedusers && $restrict) {
            $restrictwarning = true;
334 335 336 337 338
        }
        $dbservice->restrictedusers = $restrict;
        update_record('external_services', $dbservice);
    }

339 340 341 342 343 344
    if ($tokenwarning || $restrictwarning) {
        // Warn if disabling token users
        $cnt = count_records('external_tokens', 'externalserviceid', $service);
        if ($cnt > 0) {
            if ($tokenwarning) {
                $SESSION->add_error_msg(get_string('tokenuserswarning', 'auth.webservice', get_string('fortokenusers', 'auth.webservice')));
345
            }
346 347
            if ($restrictwarning) {
                $SESSION->add_error_msg(get_string('restricteduserswarning', 'auth.webservice', get_string('restrictedusers', 'auth.webservice')));
348
            }
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
        }
    }

    // Can't add/remove functions from a plugin's service
    if (!$ispluginservice) {
        foreach (array_keys($values) as $key) {
            if (preg_match('/^id(\d+)\_enabled$/', $key, $matches)) {
                $function = $matches[1];
                $dbfunction = get_record('external_functions', 'id', $function);
                if (empty($dbfunction)) {
                    $SESSION->add_error_msg(get_string('invalidinput', 'auth.webservice'));
                    redirect('/webservice/admin/serviceconfig.php?service=' . $service);
                }
                $service_function = record_exists('external_services_functions', 'externalserviceid', $service, 'functionname',$dbfunction->name);
                // record should exist - so create if necessary
                if ($values[$key]) {
                    if (!$service_function) {
                        $service_function = array('externalserviceid' => $service, 'functionname' => $dbfunction->name);
                        insert_record('external_services_functions', $service_function);
                        $dbservice->mtime = db_format_timestamp(time());
                        update_record('external_services', $dbservice);
                    }
                }
                else {
                    // disabled - record should not exist
                    if ($service_function) {
                        delete_records('external_services_functions', 'externalserviceid', $service, 'functionname',$dbfunction->name);
                        $dbservice->mtime = db_format_timestamp(time());
                        update_record('external_services', $dbservice);
                    }
379 380 381 382 383 384
                }
            }
        }
    }
    $SESSION->add_ok_msg(get_string('configsaved', 'auth.webservice'));
    redirect('/webservice/admin/serviceconfig.php?service=' . $service);
385
}