lib.php 29.3 KB
Newer Older
Donal McMullan's avatar
Donal McMullan committed
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
 * Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz)
Donal McMullan's avatar
Donal McMullan committed
5
 *
Francois Marier's avatar
Francois Marier committed
6
7
8
9
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
Donal McMullan's avatar
Donal McMullan committed
10
 *
Francois Marier's avatar
Francois Marier committed
11
12
13
14
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
Donal McMullan's avatar
Donal McMullan committed
15
 *
Francois Marier's avatar
Francois Marier committed
16
17
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
Donal McMullan's avatar
Donal McMullan committed
18
19
20
21
22
 *
 * @package    mahara
 * @subpackage auth-internal
 * @author     Nigel McNie <nigel@catalyst.net.nz>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
23
 * @copyright  (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
Donal McMullan's avatar
Donal McMullan committed
24
25
26
27
 *
 */

defined('INTERNAL') || die();
28
require_once(get_config('docroot') . 'auth/lib.php');
29
require_once(get_config('libroot') . 'peer.php');
30
require_once(get_config('libroot') . 'applicationset.php');
31
require_once(get_config('docroot') . 'api/xmlrpc/lib.php');
Donal McMullan's avatar
Donal McMullan committed
32
33
34
35
36
37
38

/**
 * The XMLRPC authentication method, which authenticates users against the
 * ID Provider's XMLRPC service. This is special - it doesn't extend Auth, it's
 * not static, and it doesn't implement the expected methods. It doesn't replace
 * the user's existing Auth type, whatever that might be; it supplements it.
 */
39
class AuthXmlrpc extends Auth {
Donal McMullan's avatar
Donal McMullan committed
40

41
42
    public $file = null;

43
44
45
46
47
48
49
    /**
     * Get the party started with an optional id
     * TODO: appraise
     * @param int $id   The auth instance id
     */
    public function __construct($id = null) {

50
        $this->has_instance_config = true;
51
52
        $this->type                            = 'xmlrpc';

53
54
        $this->config['wwwroot']               = '';
        $this->config['wwwroot_orig']          = '';
55
56
        $this->config['shortname']             = '';
        $this->config['name']                  = '';
57
        $this->config['portno']                = 80;
58
59
60
        $this->config['xmlrpcserverurl']       = '';
        $this->config['changepasswordurl']     = '';
        $this->config['updateuserinfoonlogin'] = 1;
61
62
        $this->config['weautocreateusers']     = 0;
        $this->config['theyautocreateusers']   = 0;
63
64
65
66
        $this->config['wessoout']              = 1;
        $this->config['theyssoin']             = 0;
        $this->config['parent']                = null;
        $this->file = fopen('/tmp/out.txt', 'w');
67
        if (!empty($id)) {
68
69
70
71
72
73
74
75
76
77
78
79
            return $this->init($id);
        }
        return true;
    }

    /**
     * Get config variables
     */
    public function init($id = null) {
        $this->ready = parent::init($id);
        return $this->ready;
    }
Donal McMullan's avatar
Donal McMullan committed
80

81
82
83
84
85
86
    public function __get($name) {
        if (array_key_exists($name, $this->config)) {
            return $this->config[$name];
        }
    }

87
88
89
90
91
92
93
94
95
96
97
98
    /**
     * The keepalive_client function is tricky to implement in Mahara. Moodle 
     * accomplishes this simply, because that application already updates the user 
     * table once for every page view.
     * I think that we *really* don't want to do that with Mahara. There are heaps of
     * ways that we could implement this that are not very portable, but for now, it's
     * best if we leave this on the todo pile. If it becomes crucially important for a 
     * stakeholder, we can provide some implementation of it.
     */
    public static function keepalive_client() {}
    public static function keepalive_server() {}

Donal McMullan's avatar
Donal McMullan committed
99
100
101
    /**
     * Grab a delegate object for auth stuff
     */
102
    public function request_user_authorise($token, $remotewwwroot) {
103
        global $USER;
104
        $this->must_be_ready();
Donal McMullan's avatar
Donal McMullan committed
105
106
        $peer = get_peer($remotewwwroot);

107
        if ($peer->deleted != 0 || $this->config['theyssoin'] != 1) {
108
            throw new XmlrpcClientException('We don\'t accept SSO connections from ' . $peer->name);
Donal McMullan's avatar
Donal McMullan committed
109
110
111
112
113
114
115
116
117
118
        }

        $client = new Client();
        $client->set_method('auth/mnet/auth.php/user_authorise')
               ->add_param($token)
               ->add_param(sha1($_SERVER['HTTP_USER_AGENT']))
               ->send($remotewwwroot);

        $remoteuser = (object)$client->response;

119
        if (empty($remoteuser) or !property_exists($remoteuser, 'username')) {
120
121
            // Caught by land.php
            throw new AccessDeniedException();
Donal McMullan's avatar
Donal McMullan committed
122
123
124
125
126
        }

        $virgin = false;

        $oldlastlogin = null;
127
128
        $create = false;
        $update = false;
Donal McMullan's avatar
Donal McMullan committed
129

130
        // Retrieve a $user object. If that fails, create a blank one.
131
        try {
132
            $user = new User;
133
            $user->find_by_instanceid_username($this->instanceid, $remoteuser->username, true);
134
135
136
            if ('1' == $this->config['updateuserinfoonlogin']) {
                $update = true;
            }
137
        } catch (AuthUnknownUserException $e) {
138
            if (!empty($this->config['weautocreateusers'])) {
139
140
141
142
                $institution = new Institution($this->institution);
                if ($institution->isFull()) {
                    throw new XmlrpcClientException('SSO attempt from ' . $institution->displayname . ' failed - institution is full');
                }
143
                $user = new User;
144
145
146
147
148
                $create = true;
            } else {
                return false;
            }
        }
149

150
151
152
        /*******************************************/

        if ($create) {
Donal McMullan's avatar
Donal McMullan committed
153

154
155
156
157
158
159
            $user->passwordchange     = 1;
            $user->active             = 1;
            $user->deleted            = 0;

            //TODO: import institution's expiry?:
            //$institution = new Institution($peer->institution);
160
            $user->expiry             = null;
161
162
163
164
165
166
167
168
169
            $user->expirymailsent     = 0;
            $user->lastlogin          = time();
    
            $user->firstname          = $remoteuser->firstname;
            $user->lastname           = $remoteuser->lastname;
            $user->email              = $remoteuser->email;

            //TODO: import institution's per-user-quota?:
            //$user->quota              = $userrecord->quota;
Donal McMullan's avatar
Donal McMullan committed
170
            $user->authinstance       = empty($this->config['parent']) ? $this->instanceid : $this->parent;
171
172
173

            db_begin();
            $user->username           = get_new_username($remoteuser->username);
174
175
            $user->commit();

176
177
178
179
180
181
            insert_record('auth_remote_user', (object) array(
                'authinstance'   => $user->authinstance,
                'remoteusername' => $remoteuser->username,
                'localusr'       => $user->id,
            ));

182
            $user->join_institution($peer->institution);
Donal McMullan's avatar
Donal McMullan committed
183

184
185
186
187
            set_profile_field($user->id, 'firstname', $user->firstname);
            set_profile_field($user->id, 'lastname', $user->lastname);
            set_profile_field($user->id, 'email', $user->email);

188
189
            $this->import_user_settings($user, $remoteuser);

190
191
192
193
194
195
196
197
198
            /*
             * We need to convert the object to a stdclass with its own
             * custom method because it uses overloaders in its implementation
             * and its properties wouldn't be visible to a simple cast operation
             * like (array)$user
             */
            $userobj = $user->to_stdclass();
            $userarray = (array)$userobj;
            handle_event('createuser', $userarray);
199
            db_commit();
200

201
        } elseif ($update) {
202
203
204
205
206
207
            $simplefieldstoimport = array('firstname', 'lastname', 'email');
            foreach ($simplefieldstoimport as $field) {
                if ($user->$field != $remoteuser->$field) {
                    $user->$field = $remoteuser->$field;
                    set_profile_field($user->id, $field, $user->$field);
                }
208
209
            }

210
            $this->import_user_settings($user, $remoteuser);
211
212

            $user->lastlogin          = time();
213

214
215
216
217
            //TODO: import institution's per-user-quota?:
            //$user->quota              = $userrecord->quota;
            $user->commit();
        }
218
219


220
221
222
223
        // See if we need to create/update a profile Icon image
        if ($create || $update) {

            $client->set_method('auth/mnet/auth.php/fetch_user_image')
224
                   ->add_param($remoteuser->username)
225
226
227
228
229
230
231
232
233
234
235
236
237
238
                   ->send($remotewwwroot);

            $imageobject = (object)$client->response;

            $u = preg_replace('/[^A-Za-z0-9 ]/', '', $user->username);
            $filename = '/tmp/'.intval($this->instanceid).'_'.$u;

            if (array_key_exists('f1', $client->response)) {
                $imagecontents = base64_decode($client->response['f1']);
                file_put_contents($filename, $imagecontents);
                $imageexists = false;
                $icons       = false;

                if ($update) {
Donal McMullan's avatar
Donal McMullan committed
239
                    $newchecksum = sha1_file($filename);
240
                    $icons = get_records_select_array('artefact', 'artefacttype = \'profileicon\' AND owner = ? ', array($user->id), '', 'id');
241
242
243
                    if (false != $icons) {
                        foreach ($icons as $icon) {
                            $iconfile = get_config('dataroot') . 'artefact/internal/profileicons/' . ($icon->id % 256) . '/'.$icon->id;
Donal McMullan's avatar
Donal McMullan committed
244
                            $checksum = sha1_file($iconfile);
245
246
247
248
249
250
251
                            if ($newchecksum == $checksum) {
                                $imageexists = true;
                                unlink($filename);
                                break;
                            }
                        }
                    }
252
253
                }

254
255
256
257
                if (false == $imageexists) {
                    $filesize = filesize($filename);
                    if (!$user->quota_allowed($filesize)) {
                        $error = get_string('profileiconuploadexceedsquota', 'artefact.internal', get_config('wwwroot'));
258
                    }
259
260
261
262
263

                    require_once('file.php');
                    $mime = get_mime_type($filename);
                    if (!is_image_mime_type($mime)) {
                        $error = get_string('filenotimage');
264
265
                    }

266
                    list($width, $height) = getimagesize($filename);
267
268
269
270
                    $imagemaxwidth  = get_config('imagemaxwidth');
                    $imagemaxheight = get_config('imagemaxheight');
                    if ($width > $imagemaxwidth || $height > $imagemaxheight) {
                        $error = get_string('profileiconimagetoobig', 'artefact.internal', $width, $height, $imagemaxwidth, $imagemaxheight);
271
                    }
272

273
274
275
276
277
278
279
                    try {
                        $user->quota_add($filesize);
                    }
                    catch (QuotaException $qe) {
                        $error =  get_string('profileiconuploadexceedsquota', 'artefact.internal', get_config('wwwroot'));
                    }

280
281
                    require_once(get_config('docroot') .'/artefact/lib.php');
                    require_once(get_config('docroot') .'/artefact/internal/lib.php');
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301

                    // Entry in artefact table
                    $artefact = new ArtefactTypeProfileIcon();
                    $artefact->set('owner', $user->id);
                    $artefact->set('title', 'Profile Icon');
                    $artefact->set('note', 'Profile Icon');
                    $artefact->commit();

                    $id = $artefact->get('id');

                    // Move the file into the correct place.
                    $directory = get_config('dataroot') . 'artefact/internal/profileicons/' . ($id % 256) . '/';
                    check_dir_exists($directory);
                    rename($filename, $directory . $id);
                    if ($create || empty($icons)) {
                        $user->profileicon = $id;
                    }
                }

                $user->commit();
Donal McMullan's avatar
Donal McMullan committed
302
            }
303
        }
Donal McMullan's avatar
Donal McMullan committed
304

305
306
        /*******************************************/

307
        // We know who our user is now. Bring her back to life.
308
        $USER->reanimate($user->id, $this->instanceid);
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
        return true;
    }

    /**
     * Given a username, returns whether the user exists in the usr table
     *
     * @param string $username The username to attempt to identify
     * @return bool            Whether the username exists
     */
    public function user_exists($username) {
        $this->must_be_ready();
        $userrecord = false;

        // The user is likely to be associated with the parent instance
        if (is_numeric($this->config['parent']) && $this->config['parent'] > 0) {
            $_instanceid = $this->config['parent'];
            $userrecord = get_record('usr', 'LOWER(username)', strtolower($username), 'authinstance', $_instanceid);
Donal McMullan's avatar
Donal McMullan committed
326
        }
327
328
329
330
331
332
333
334
335
336

        if (empty($userrecord)) {
            $_instanceid = $this->instanceid;
            $userrecord = get_record('usr', 'LOWER(username)', strtolower($username), 'authinstance', $_instanceid);
        }

        if ($userrecord != false) {
            return $userrecord;
        }
        throw new AuthUnknownUserException("\"$username\" is not known to Auth");
Donal McMullan's avatar
Donal McMullan committed
337
338
339
    }

    /**
340
341
342
343
     * In practice, I don't think this method needs to return an accurate 
     * answer for this, because XMLRPC authentication doesn't use the standard 
     * authentication mechanisms, instead relying on land.php to handle 
     * everything.
Donal McMullan's avatar
Donal McMullan committed
344
     */
345
346
    public function can_auto_create_users() {
        return (bool)$this->config['weautocreateusers'];
Donal McMullan's avatar
Donal McMullan committed
347
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
379
380
381
382
383
384
385
386
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
    /**
     * Given a user and their remote user record, attempt to populate some of 
     * the user's profile fields and account settings from the remote data.
     *
     * This does not change the first name, last name or e-mail fields, as these are 
     * dealt with differently depending on whether we are creating the user 
     * record or updating it.
     *
     * This method attempts to set:
     *
     * * City
     * * Country
     * * Language
     * * Introduction
     * * WYSIWYG editor setting
     *
     * @param User $user
     * @param stdClass $remoteuser
     */
    private function import_user_settings($user, $remoteuser) {
        // City
        if (!empty($remoteuser->city)) {
            if (get_profile_field($user->id, 'city') != $remoteuser->city) {
                set_profile_field($user->id, 'city', $remoteuser->city);
            }
        }

        // Country
        if (!empty($remoteuser->country)) {
            $validcountries = array_keys(getoptions_country());
            $newcountry = strtolower($remoteuser->country);
            if (in_array($newcountry, $validcountries)) {
                set_profile_field($user->id, 'country', $newcountry);
            }
        }

        // Language
        if (!empty($remoteuser->lang)) {
            $validlanguages = array_keys(get_languages());
            $newlanguage = str_replace('_', '.', strtolower($remoteuser->lang));
            if (in_array($newlanguage, $validlanguages)) {
                set_account_preference($user->id, 'lang', $newlanguage);
                $user->set_account_preference('lang', $newlanguage);
            }
        }

        // Description
        if (isset($remoteuser->description)) {
            if (get_profile_field($user->id, 'introduction') != $remoteuser->description) {
                set_profile_field($user->id, 'introduction', $remoteuser->description);
            }
        }

        // HTML Editor setting
        if (isset($remoteuser->htmleditor)) {
            $htmleditor = ($remoteuser->htmleditor) ? 1 : 0;
            if ($htmleditor != get_account_preference($user->id, 'wysiwyg')) {
                set_account_preference($user->id, 'wysiwyg', $htmleditor);
                $user->set_account_preference('wysiwyg', $htmleditor);
            }
        }
    }

Donal McMullan's avatar
Donal McMullan committed
412
413
414
415
416
}

/**
 * Plugin configuration class
 */
417
class PluginAuthXmlrpc extends PluginAuth {
Donal McMullan's avatar
Donal McMullan committed
418

419
420
421
422
423
424
425
426
    private static $default_config = array(
        'instancename'          => '',
        'wwwroot'               => '',
        'wwwroot_orig'          => '',
        'name'                  => '',
        'appname'               => '',
        'portno'                => 80,
        'updateuserinfoonlogin' => 0, 
427
428
        'weautocreateusers'     => 0,
        'theyautocreateusers'   => 0,
429
430
431
432
        'wessoout'              => 0,
        'theyssoin'             => 0,
        'parent'                => null
    );
433

Donal McMullan's avatar
Donal McMullan committed
434
    public static function has_config() {
435
436
437
438
439
440
441
442
        return false;
    }

    public static function get_config_options() {
        return array();
    }

    public static function has_instance_config() {
443
        return true;
Donal McMullan's avatar
Donal McMullan committed
444
445
    }

446
447
448
449
    public static function is_usable() {
        return extension_loaded('xmlrpc') && extension_loaded('openssl') && extension_loaded('curl');
    }

450
    public static function get_instance_config_options($institution, $instance = 0) {
451

452
453
        $peer = new Peer();

Donal McMullan's avatar
Donal McMullan committed
454
        // TODO : switch to getrecord
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
485
486
487
488
489
490
        // Get a list of applications and make a dropdown from it
        $applicationset = new ApplicationSet();
        $apparray = array();
        foreach ($applicationset as $app) {
            $apparray[$app->name] = $app->displayname;
        }

        /**
         * A parent authority for XML-RPC is the data-source that a remote XML-RPC service
         * communicates with to authenticate a user, for example, the XML-RPC server that 
         * we connect to might be authorising users against an LDAP store. If this is the 
         * case, and we know of the LDAP store, and our users are able to log on to our 
         * system and be authenticated directly against the LDAP store, then we honor that 
         * association.
         * 
         * In this way, the unique relationship is between the username and the authority,
         * not the username and the institution. This allows an institution to have a user
         * 'donal' on server 'LDAP-1' and a different user 'donal' on server 'LDAP-2'.
         * 
         * Get a list of auth instances for this institution, and eliminate those that 
         * would not be valid parents (as they themselves require a parent). These are 
         * eliminated only to provide a saner interface to the admin user. In theory, it's
         * ok to chain authorities.
         */ 
        $instances = auth_get_auth_instances_for_institution($institution);
        $options = array('None');
        if (is_array($instances)) {
            foreach($instances as $someinstance) {
                if ($someinstance->requires_parent == 1) {
                    continue;
                }
                $options[$someinstance->id] = $someinstance->instancename;
            }
        }

        // Get the current data (if any exists) for this auth instance
491
        if ($instance > 0) {
492
            $default = get_record('auth_instance', 'id', $instance);
493
            if ($default == false) {
494
                throw new SystemException(get_string('nodataforinstance', 'auth').$instance);
495
496
497
            }
            $current_config = get_records_menu('auth_instance_config', 'instance', $instance, '', 'field, value');

498
            if ($current_config == false) {
499
                throw new SystemException('No config data for instance: '.$instance);
500
501
502
            }

            foreach (self::$default_config as $key => $value) {
503
                if (array_key_exists($key, $current_config)) {
504
                    self::$default_config[$key] = $current_config[$key];
505
506
507
508
509
510
511
512

                    // We can use the wwwroot to create a Peer object
                    if ('wwwroot' == $key) {
                        $peer->findByWwwroot($current_config[$key]);
                        self::$default_config['wwwroot_orig'] = $current_config[$key];
                    }
                } elseif (property_exists($default, $key)) {
                    self::$default_config[$key] = $default->{$key};
513
514
515
                }
            }
        } else {
516
517
518
519
520
521
522
523
            $max_priority = get_field('auth_instance', 'MAX(priority)', 'institution', $institution);
            self::$default_config['priority'] = ++$max_priority;
        }

        if (empty($peer->application->name)) {
            self::$default_config['appname'] = key(current($applicationset));
        } else {
            self::$default_config['appname'] = $peer->application->name;
524
525
526
527
528
529
530
531
        }

        $elements['instancename'] = array(
            'type' => 'text',
            'title' => get_string('authname','auth'),
            'rules' => array(
                'required' => true
            ),
532
            'defaultvalue' => self::$default_config['instancename'],
533
534
535
536
537
538
539
540
541
542
543
544
545
            'help'   => true
        );

        $elements['instance'] = array(
            'type' => 'hidden',
            'value' => $instance
        );

        $elements['institution'] = array(
            'type' => 'hidden',
            'value' => $institution
        );

546
547
548
549
550
        $elements['deleted'] = array(
            'type' => 'hidden',
            'value' => $peer->deleted
        );

551
552
553
554
555
        $elements['authname'] = array(
            'type' => 'hidden',
            'value' => 'xmlrpc'
        );

556
557
558
559
560
561
562
563
564
565
        $elements['parent'] = array(
            'type'                => 'select',
            'title'               => get_string('parent','auth'),
            'collapseifoneoption' => false,
            'options'             => $options,
            'defaultvalue'        => self::$default_config['parent'],
            'help'   => true
        );

        $elements['wwwroot'] = array(
566
            'type' => 'text',
567
            'title' => get_string('wwwroot', 'auth'),
568
569
570
            'rules' => array(
                'required' => true
            ),
571
            'defaultvalue' => self::$default_config['wwwroot'],
572
573
574
            'help'   => true
        );

575
576
577
578
579
580
581
582
583
584
        $elements['wwwroot_orig'] = array(
            'type' => 'hidden',
            'value' => self::$default_config['wwwroot_orig']
        );

        $elements['oldwwwroot'] = array(
            'type' => 'hidden',
            'value' => 'xmlrpc'
        );

585
586
587
588
589
590
        $elements['name'] = array(
            'type' => 'text',
            'title' => get_string('name', 'auth'),
            'rules' => array(
                'required' => true
            ),
591
            'defaultvalue' => $peer->name,
592
593
594
            'help'   => true
        );

595
596
597
598
599
600
601
602
603
        /**
         * empty($peer->appname) would ALWAYS return true, because the property doesn't really
         * exist. When we try to get $peer->appname, we're actually calling the peer class's
         * __get overloader. Unfortunately, the 'empty' function seems to just check for the
         * existence of the property - it doesn't call the overloader. Bug or feature?
         */
	     
        $tmpappname = $peer->appname;

604
605
606
607
608
609
        $elements['appname'] = array(
            'type'                => 'select',
            'title'               => get_string('application','auth'),
            'collapseifoneoption' => true,
            'multiple'            => false,
            'options'             => $apparray,
610
            'defaultvalue'        => empty($tmpappname)? key($apparray) : $tmpappname,
611
612
613
614
            'help'                => true
        );

        $elements['portno'] = array(
615
            'type' => 'text',
616
            'title' => get_string('port', 'auth'),
617
            'rules' => array(
618
619
                'required' => true,
                'integer'  => true
620
            ),
621
            'defaultvalue' => $peer->portno,
622
623
624
            'help'   => true
        );

625
626
627
628
629
630
631
632
633
634
635
        $elements['wessoout'] = array(
            'type'         => 'checkbox',
            'title'        => get_string('wessoout', 'auth'),
            'defaultvalue' => self::$default_config['wessoout'],
            'help'   => true
        );

        $elements['theyssoin'] = array(
            'type'         => 'checkbox',
            'title'        => get_string('theyssoin', 'auth'),
            'defaultvalue' => self::$default_config['theyssoin'],
636
637
638
639
640
641
642
643
644
645
            'help'   => true
        );

        $elements['updateuserinfoonlogin'] = array(
            'type'         => 'checkbox',
            'title'        => get_string('updateuserinfoonlogin', 'auth'),
            'defaultvalue' => self::$default_config['updateuserinfoonlogin'],
            'help'   => true
        );

646
        $elements['weautocreateusers'] = array(
647
            'type'         => 'checkbox',
648
649
            'title'        => get_string('weautocreateusers', 'auth'),
            'defaultvalue' => self::$default_config['weautocreateusers'],
650
651
652
            'help'   => true
        );

653
654
655
656
657
658
659
        $elements['theyautocreateusers'] = array(
            'type'         => 'checkbox',
            'title'        => get_string('theyautocreateusers', 'auth'),
            'defaultvalue' => self::$default_config['theyautocreateusers'],
            'help'   => true
        );
        
660
661
662
663
        return array(
            'elements' => $elements,
            'renderer' => 'table'
        );
Donal McMullan's avatar
Donal McMullan committed
664
    }
665

666
667
668
669
670
    public static function validate_config_options($values, $form) {

        $authinstance = new stdClass();
        $peer = new Peer();

671
672
673
674
675
676
677
678
        if (false == $peer->findByWwwroot($values['wwwroot'])) {
            try {
                $peer->bootstrap($values['wwwroot'], null, $values['appname'], $values['institution']);
            } catch (RemoteServerException $e) {
                $form->set_error('wwwroot',get_string('cantretrievekey', 'auth'));
            }
        }

Donal McMullan's avatar
WIP    
Donal McMullan committed
679
        //TODO: test values and set appropriate errors on form
680
681
682
    }

    public static function save_config_options($values, $form) {
683

684
        db_begin();
685
        $authinstance = new stdClass();
686
        $peer = new Peer();
687
688
689
690
691

        if ($values['instance'] > 0) {
            $values['create'] = false;
            $current = get_records_assoc('auth_instance_config', 'instance', $values['instance'], '', 'field, value');
            $authinstance->id = $values['instance'];
692

693
694
695
696
697
698
699
700
701
702
703
704
705
706
        } else {
            $values['create'] = true;

            // Get the auth instance with the highest priority number (which is
            // the instance with the lowest priority).
            // TODO: rethink 'priority' as a fieldname... it's backwards!!
            $lastinstance = get_records_array('auth_instance', 'institution', $values['institution'], 'priority DESC', '*', '0', '1');

            if ($lastinstance == false) {
                $authinstance->priority = 0;
            } else {
                $authinstance->priority = $lastinstance[0]->priority + 1;
            }
        }
707
708
709
 
        if (false == $peer->findByWwwroot($values['wwwroot'])) {
            try {
Donal McMullan's avatar
WIP    
Donal McMullan committed
710
                $peer->bootstrap($values['wwwroot'], null, $values['appname'], $values['institution']);
711
712
713
714
715
716
            } catch (RemoteServerException $e) {
                $form->set_error('wwwroot',get_string('cantretrievekey', 'auth'));
                throw new RemoteServerException($e->getMessage(), $e->getCode());
            }
        }

717
        $peer->wwwroot              = preg_replace("|\/+$|", "", $values['wwwroot']);
718
719
720
721
722
723
724
725
726
727
728
729
730
731
        $peer->name                 = $values['name'];
        $peer->deleted              = $values['deleted'];
        $peer->portno               = $values['portno'];
        $peer->appname              = $values['appname'];
        $peer->institution          = $values['institution'];

        /**
         * The following properties are not user-updatable
        $peer->publickey            = $values['publickey'];
        $peer->publickeyexpires     = $values['publickeyexpires'];
        $peer->lastconnecttime      = $values['lastconnecttime'];
         */

        $peer->commit();
Donal McMullan's avatar
WIP    
Donal McMullan committed
732
        
733
734
735
736
737
738
739
740
741
742
743
744
745
746
        $authinstance->instancename = $values['instancename'];
        $authinstance->institution  = $values['institution'];
        $authinstance->authname     = $values['authname'];

        if ($values['create']) {
            $values['instance'] = insert_record('auth_instance', $authinstance, 'id', true);
        } else {
            update_record('auth_instance', $authinstance, array('id' => $values['instance']));
        }

        if (empty($current)) {
            $current = array();
        }

747
        self::$default_config = array(  'wwwroot'               => $values['wwwroot'],
748
                                        'updateuserinfoonlogin' => $values['updateuserinfoonlogin'],
749
750
                                        'weautocreateusers'     => $values['weautocreateusers'],
                                        'theyautocreateusers'   => $values['theyautocreateusers'],
751
752
753
754
                                        'parent'                => $values['parent'],
                                        'wessoout'              => $values['wessoout'],
                                        'theyssoin'             => $values['theyssoin']
                                        );
755
756
757
758
759
760
761

        foreach(self::$default_config as $field => $value) {
            $record = new stdClass();
            $record->instance = $values['instance'];
            $record->field    = $field;
            $record->value    = $value;

762
763
764
765
            if ($field == 'wwwroot') {
                $record->value    = dropslash($value);
            }

766
767
768
769
770
771
772
773
774
            if (empty($value)) {
                delete_records('auth_instance_config', 'field', $field, 'instance', $values['instance']);
            } elseif ($values['create'] || !array_key_exists($field, $current)) {
                insert_record('auth_instance_config', $record);
            } else {
                update_record('auth_instance_config', $record, array('instance' => $values['instance'], 'field' => $field));
            }
        }

775
        db_commit();
776
777
778
        return $values;
    }

Donal McMullan's avatar
Donal McMullan committed
779
780
}

781
?>