mahara_user_external.php 57 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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
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
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
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
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
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
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
1057
1058
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
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
<?php
/**
 *
 * @package    mahara
 * @subpackage auth-webservice
 * @author     Catalyst IT Ltd
 * @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.
 *
 */

/**
 * External user API
 *
 * @package    auth
 * @subpackage webservice
 * @copyright  2009 Moodle Pty Ltd (http://moodle.com)
 * @copyright  Copyright (C) 2011 Catalyst IT Ltd (http://www.catalyst.net.nz)
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @author     Piers Harding
 */

require_once(get_config('docroot') . 'webservice/lib.php');
require_once(get_config('docroot') . 'webservice/rest/locallib.php');
require_once(get_config('docroot') . 'lib/user.php');
require_once(get_config('docroot') . 'lib/group.php');
require_once(get_config('docroot') . 'lib/institution.php');
require_once(get_config('docroot') . 'lib/searchlib.php');

global $WEBSERVICE_OAUTH_USER;

/**
* Class container for core Mahara user related API calls
*/
class mahara_user_external extends external_api {

    static private $ALLOWEDKEYS = array(
            'remoteuser',
            'introduction',
            'officialwebsite',
            'personalwebsite',
            'blogaddress',
            'address',
            'town',
            'city',
            'country',
            'homenumber',
            'businessnumber',
            'mobilenumber',
            'faxnumber',
            'icqnumber',
            'msnnumber',
            'aimscreenname',
            'yahoochat',
            'skypeusername',
            'jabberusername',
            'occupation',
            'industry',
        );

    /**
     * parameter definition for input of create_users method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function create_users_parameters() {

        return new external_function_parameters(
            array(
                'users' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'username'        => new external_value(PARAM_RAW, 'Username policy is defined in Mahara security config'),
                            'password'        => new external_value(PARAM_RAW, 'Plain text password consisting of any characters'),
                            'firstname'       => new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
                            'lastname'        => new external_value(PARAM_NOTAGS, 'The family name of the user'),
                            'email'           => new external_value(PARAM_EMAIL, 'A valid and unique email address'),
                            'institution'     => new external_value(PARAM_SAFEDIR, 'Mahara institution', VALUE_DEFAULT, 'mahara', NULL_NOT_ALLOWED),
                            'auth'            => new external_value(PARAM_SAFEDIR, 'Auth plugins include manual, ldap, imap, etc', VALUE_DEFAULT, 'internal', NULL_NOT_ALLOWED),
                            'quota'           => new external_value(PARAM_INTEGER, 'Option storage quota', VALUE_OPTIONAL),
                            'forcepasswordchange' => new external_value(PARAM_INTEGER, 'Boolean 1/0 for forcing password change on first login', VALUE_DEFAULT, '0'),
                            'studentid'       => new external_value(PARAM_RAW, 'An arbitrary ID code number for the student', VALUE_DEFAULT, ''),
                            'remoteuser'      => new external_value(PARAM_RAW, 'Remote user Id', VALUE_DEFAULT, ''),
                            'preferredname'   => new external_value(PARAM_TEXT, 'Userpreferred name', VALUE_OPTIONAL),
                            'address'         => new external_value(PARAM_RAW, 'Introduction text', VALUE_OPTIONAL),
                            'town'            => new external_value(PARAM_NOTAGS, 'Home town of the user', VALUE_OPTIONAL),
                            'city'            => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
                            'country'         => new external_value(PARAM_ALPHA, 'Home country code of the user, such as NZ', VALUE_OPTIONAL),
                            'homenumber'      => new external_value(PARAM_RAW, 'Home phone number', VALUE_OPTIONAL),
                            'businessnumber'  => new external_value(PARAM_RAW, 'business phone number', VALUE_OPTIONAL),
                            'mobilenumber'    => new external_value(PARAM_RAW, 'mobile phone number', VALUE_OPTIONAL),
                            'faxnumber'       => new external_value(PARAM_RAW, 'fax number', VALUE_OPTIONAL),
                            'introduction'    => new external_value(PARAM_RAW, 'Introduction text', VALUE_OPTIONAL),
                            'officialwebsite' => new external_value(PARAM_RAW, 'Official user website', VALUE_OPTIONAL),
                            'personalwebsite' => new external_value(PARAM_RAW, 'Personal website', VALUE_OPTIONAL),
                            'blogaddress'     => new external_value(PARAM_RAW, 'Blog web address', VALUE_OPTIONAL),
                            'aimscreenname'   => new external_value(PARAM_ALPHANUMEXT, 'AIM screen name', VALUE_OPTIONAL),
                            'icqnumber'       => new external_value(PARAM_ALPHANUMEXT, 'ICQ Number', VALUE_OPTIONAL),
                            'msnnumber'       => new external_value(PARAM_ALPHANUMEXT, 'MSN Number', VALUE_OPTIONAL),
                            'yahoochat'       => new external_value(PARAM_ALPHANUMEXT, 'Yahoo chat', VALUE_OPTIONAL),
                            'skypeusername'   => new external_value(PARAM_ALPHANUMEXT, 'Skype username', VALUE_OPTIONAL),
                            'jabberusername'  => new external_value(PARAM_RAW, 'Jabber/XMPP username', VALUE_OPTIONAL),
                            'occupation'      => new external_value(PARAM_TEXT, 'Occupation', VALUE_OPTIONAL),
                            'industry'        => new external_value(PARAM_TEXT, 'Industry', VALUE_OPTIONAL),
                        )
                    )
                )
            )
        );
    }

    /**
     * Create one or more users in the authorised institution
     *
     * @param array $users  An array of users to create.
     * @return array An array of arrays
     */
    public static function create_users($users) {
        global $USER, $WEBSERVICE_INSTITUTION, $WEBSERVICE_OAUTH_USER;

        // Do basic automatic PARAM checks on incoming data, using params description
        // If any problems are found then exceptions are thrown with helpful error messages
        $params = self::validate_parameters(self::create_users_parameters(), array('users'=>$users));
        db_begin();
        $userids = array();
        foreach ($params['users'] as $user) {
            // Make sure that the username doesn't already exist
            if (get_record('usr', 'username', $user['username'])) {
                throw new WebserviceInvalidParameterException(get_string('usernameexists', 'auth.webservice', $user['username']));
            }

            // check the institution is allowed
            // basic check authorisation to edit for the current institution
            if (!$USER->can_edit_institution($user['institution'])) {
                throw new WebserviceInvalidParameterException('create_users | ' . get_string('accessdeniedforinst', 'auth.webservice', $user['institution']));
            }

            // Make sure auth is valid
            if (!$authinstance = get_record('auth_instance', 'institution', $user['institution'], 'authname', $user['auth'])) {
                throw new WebserviceInvalidParameterException(get_string('invalidauthtype', 'auth.webservice', $user['institution'] . '/' . $user['auth']));
            }

            $institution = new Institution($authinstance->institution);

            $maxusers = $institution->maxuseraccounts;
            if (!empty($maxusers)) {
                $members = count_records_sql('
                    SELECT COUNT(*) FROM {usr} u INNER JOIN {usr_institution} i ON u.id = i.usr
                    WHERE i.institution = ? AND u.deleted = ?', array($institution->name, 0));
                if ($members + 1 > $maxusers) {
                    throw new WebserviceInvalidParameterException(get_string('instexceedmax', 'auth.webservice', $institution->name));
                }
            }

            // build up the user object to create
            $new_user = new StdClass;
            $new_user->authinstance = $authinstance->id;
            $new_user->username     = $user['username'];
            $new_user->firstname    = $user['firstname'];
            $new_user->lastname     = $user['lastname'];
            $new_user->password     = $user['password'];
            $new_user->email        = $user['email'];
            if (isset($user['quota'])) {
                $new_user->quota        = $user['quota'];
            }
            if (isset($user['forcepasswordchange'])) {
                $new_user->passwordchange = (int)$user['forcepasswordchange'];
            }

            if (isset($user['studentid'])) {
                $new_user->studentid = $user['studentid'];
            }
            if (isset($user['preferredname'])) {
                $new_user->preferredname = $user['preferredname'];
            }

            // handle profile fields
            $profilefields = new StdClass;
            $remoteuser = null;
            foreach (self::$ALLOWEDKEYS as $field) {
                if (isset($user[$field])) {
                    if ($field == 'remoteuser') {
                        $remoteuser = $user[$field];
                        continue;
                    }
                    $profilefields->{$field} = $user[$field];
                }
            }
            $new_user->id = create_user($new_user, $profilefields, $institution, $authinstance, $remoteuser);
            $addedusers[] = $new_user;
            $userids[] = array('id'=> $new_user->id, 'username'=>$user['username']);
        }
        db_commit();

        return $userids;
    }

   /**
    * parameter definition for output of create_users method
    *
    * Returns description of method result value
    * @return external_description
    */
    public static function create_users_returns() {
        return new external_multiple_structure(
            new external_single_structure(
                array(
                    'id'       => new external_value(PARAM_INT, 'user id'),
                    'username' => new external_value(PARAM_RAW, 'user name'),
                )
            )
        );
    }

    /**
     * parameter definition for input of delete_users method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function delete_users_parameters() {
       return new external_function_parameters(
            array(
                'users' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'id'              => new external_value(PARAM_NUMBER, 'ID of the favourites owner', VALUE_OPTIONAL),
                            'username'        => new external_value(PARAM_RAW, 'Username of the favourites owner', VALUE_OPTIONAL),
                            )
                        )
                    )
                )
            );
    }

    /**
     * Delete one or more users
     *
     * @param array $users
     */
    public static function delete_users($users) {
        global $USER, $WEBSERVICE_INSTITUTION, $WEBSERVICE_OAUTH_USER;

        require_once(get_config('docroot') . 'artefact/lib.php');

        $params = self::validate_parameters(self::delete_users_parameters(), array('users'=>$users));

        $users = array();
        foreach ($params['users'] as $user) {
            $users[]= self::checkuser($user);
        }

        db_begin();
        foreach ($users as $user) {
            // Make sure auth is valid
            if (!$authinstance = get_record('auth_instance', 'id', $user->authinstance)) {
                throw new WebserviceInvalidParameterException(get_string('invalidauthtype', 'auth.webservice', $user->authinstance));
            }
            // check the institution is allowed
            // basic check authorisation to edit for the current institution
            if (!$USER->can_edit_institution($authinstance->institution)) {
                throw new WebserviceInvalidParameterException('delete_users | ' . get_string('accessdeniedforinstuser', 'auth.webservice', $authinstance->institution, $user->id));
            }

            // only allow deletion of users that have not signed in
            if (!empty($user->lastlogin) && !$user->suspendedcusr) {
                throw new WebserviceInvalidParameterException('delete_users | ' . get_string('cannotdeleteaccount', 'auth.webservice', $user->id));
            }

            // must not allow deleting of admins or self!!!
            if ($user->admin) {
                throw new MaharaException('useradminodelete', 'error');
            }
            if ($USER->get('id') == $user->id) {
                throw new MaharaException('usernotdeletederror', 'error');
            }
            delete_user($user->id);
        }
        db_commit();

        return null;
    }

   /**
    * parameter definition for output of delete_users method
    *
    * Returns description of method result value
    * @return external_description
    */
    public static function delete_users_returns() {
        return null;
    }

    /**
     * parameter definition for input of update_users method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function update_users_parameters() {

       return new external_function_parameters(
            array(
                'users' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'id'              => new external_value(PARAM_NUMBER, 'ID of the user', VALUE_OPTIONAL),
                            'username'        => new external_value(PARAM_RAW, 'Username policy is defined in Mahara security config', VALUE_OPTIONAL),
                            'password'        => new external_value(PARAM_RAW, 'Plain text password consisting of any characters', VALUE_OPTIONAL),
                            'firstname'       => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
                            'lastname'        => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
                            'email'           => new external_value(PARAM_EMAIL, 'A valid and unique email address', VALUE_OPTIONAL),
                            'institution'     => new external_value(PARAM_TEXT, 'Mahara institution', VALUE_OPTIONAL),
                            'auth'            => new external_value(PARAM_TEXT, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL),
                            'quota'           => new external_value(PARAM_INTEGER, 'Option storage quota', VALUE_OPTIONAL),
                            'forcepasswordchange' => new external_value(PARAM_INTEGER, 'Boolean 1/0 for forcing password change on first login', VALUE_OPTIONAL),
                            'studentid'       => new external_value(PARAM_RAW, 'An arbitrary ID code number for the student', VALUE_OPTIONAL),
                            'remoteuser'      => new external_value(PARAM_RAW, 'Remote user Id', VALUE_OPTIONAL),
                            'preferredname'   => new external_value(PARAM_TEXT, 'Userpreferred name', VALUE_OPTIONAL),
                            'address'         => new external_value(PARAM_RAW, 'Introduction text', VALUE_OPTIONAL),
                            'town'            => new external_value(PARAM_NOTAGS, 'Home town of the user', VALUE_OPTIONAL),
                            'city'            => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
                            'country'         => new external_value(PARAM_ALPHA, 'Home country code of the user, such as NZ', VALUE_OPTIONAL),
                            'homenumber'      => new external_value(PARAM_RAW, 'Home phone number', VALUE_OPTIONAL),
                            'businessnumber'  => new external_value(PARAM_RAW, 'business phone number', VALUE_OPTIONAL),
                            'mobilenumber'    => new external_value(PARAM_RAW, 'mobile phone number', VALUE_OPTIONAL),
                            'faxnumber'       => new external_value(PARAM_RAW, 'fax number', VALUE_OPTIONAL),
                            'introduction'    => new external_value(PARAM_RAW, 'Introduction text', VALUE_OPTIONAL),
                            'officialwebsite' => new external_value(PARAM_RAW, 'Official user website', VALUE_OPTIONAL),
                            'personalwebsite' => new external_value(PARAM_RAW, 'Personal website', VALUE_OPTIONAL),
                            'blogaddress'     => new external_value(PARAM_RAW, 'Blog web address', VALUE_OPTIONAL),
                            'aimscreenname'   => new external_value(PARAM_ALPHANUMEXT, 'AIM screen name', VALUE_OPTIONAL),
                            'icqnumber'       => new external_value(PARAM_ALPHANUMEXT, 'ICQ Number', VALUE_OPTIONAL),
                            'msnnumber'       => new external_value(PARAM_ALPHANUMEXT, 'MSN Number', VALUE_OPTIONAL),
                            'yahoochat'       => new external_value(PARAM_ALPHANUMEXT, 'Yahoo chat', VALUE_OPTIONAL),
                            'skypeusername'   => new external_value(PARAM_ALPHANUMEXT, 'Skype username', VALUE_OPTIONAL),
                            'jabberusername'  => new external_value(PARAM_RAW, 'Jabber/XMPP username', VALUE_OPTIONAL),
                            'occupation'      => new external_value(PARAM_TEXT, 'Occupation', VALUE_OPTIONAL),
                            'industry'        => new external_value(PARAM_TEXT, 'Industry', VALUE_OPTIONAL),
                            )
                    )
                )
            )
        );
    }

    /**
     * update one or more users
     *
     * @param array $users
     */
    public static function update_users($users) {
        global $USER, $WEBSERVICE_INSTITUTION, $WEBSERVICE_OAUTH_USER;

        $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));

        db_begin();
        foreach ($params['users'] as $user) {
            if (!empty($user['id'])) {
                $dbuser = get_record('usr', 'id', $user['id'], 'deleted', 0);
            }
            else if (!empty($user['username'])) {
                $dbuser = get_record('usr', 'username', $user['username'], 'deleted', 0);
            }
            else {
                throw new WebserviceInvalidParameterException('update_users | ' . get_string('nousernameorid', 'auth.webservice'));
            }
            if (empty($dbuser)) {
                throw new WebserviceInvalidParameterException('update_users | ' . get_string('invaliduser', 'auth.webservice', $user['id'] . '/' . $user['username']));
            }

            // Make sure auth is valid
            if (!$authinstance = get_record('auth_instance', 'id', $dbuser->authinstance)) {
                throw new WebserviceInvalidParameterException(get_string('invalidauthtype', 'auth.webservice', $dbuser->authinstance));
            }
            // check for changed authinstance
            if (isset($user['auth']) && isset($user['institution'])) {
                $ai = get_record('auth_instance', 'institution', $user['institution'], 'authname', $user['auth']);
                if (empty($ai)) {
                    throw new WebserviceInvalidParameterException('update_users | ' . get_string('invalidauthtypeuser', 'auth.webservice', $user['auth'], $dbuser->id));
                }
                $authinstance = $ai;
            }
            else if (isset($user['auth'])) {
                throw new WebserviceInvalidParameterException('update_users | ' . get_string('mustsetauth', 'auth.webservice', $dbuser->id));
            }

            // check the institution is allowed
            // basic check authorisation to edit for the current institution
            if (!$USER->can_edit_institution($authinstance->institution)) {
                throw new WebserviceInvalidParameterException('update_users | ' . get_string('accessdeniedforinstuser', 'auth.webservice', $authinstance->institution, $dbuser->id));
            }

            $updated_user = $dbuser;
            $updated_user->authinstance = $authinstance->id;
            $updated_user->password = (!empty($user['password']) ? $user['password'] : '');
            foreach (array('username', 'firstname', 'lastname', 'email', 'quota', 'studentid', 'preferredname') as $field) {
                if (isset($user[$field])) {
                    $updated_user->{$field} = $user[$field];
                }
            }
            if (isset($user['forcepasswordchange'])) {
                $updated_user->passwordchange = (int)$user['forcepasswordchange'];
            }

            $profilefields = new StdClass;
            $remoteuser = null;
            foreach (self::$ALLOWEDKEYS as $field) {
                if (isset($user[$field])) {
                    if ($field == 'remoteuser') {
                        $remoteuser = $user[$field];
                        continue;
                    }
                    $profilefields->{$field} = $user[$field];
                }
            }
            update_user($updated_user, $profilefields, $remoteuser);
        }
        db_commit();

        return null;
    }

   /**
    * parameter definition for output of update_users method
    *
    * Returns description of method result value
    * @return external_description
    */
    public static function update_users_returns() {
        return null;
    }

    /**
     * parameter definition for input of get_users_by_id method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function get_users_by_id_parameters() {
       return new external_function_parameters(
            array(
                'users' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'id'              => new external_value(PARAM_NUMBER, 'ID of the favourites owner', VALUE_OPTIONAL),
                            'username'        => new external_value(PARAM_RAW, 'Username of the favourites owner', VALUE_OPTIONAL),
                            'remoteuser'      => new external_value(PARAM_RAW, 'Remote username of the favourites owner', VALUE_OPTIONAL),
                            )
                        )
                    )
                )
            );
    }

    /**
     * Check that a user exists
     *
     * @param array $user array('id' => .., 'username' => ..)
     * @return array() of user
     */
    private static function checkuser($user) {
        global $WEBSERVICE_INSTITUTION;

        if (isset($user['id'])) {
            $id = $user['id'];
        }
        else if (isset($user['userid'])) {
            $id = $user['userid'];
        }
        else if (isset($user['username'])) {
            $dbuser = get_record('usr', 'username', $user['username']);
            if (empty($dbuser)) {
                throw new WebserviceInvalidParameterException(get_string('invalidusername', 'auth.webservice', $user['username']));
            }
            $id = $dbuser->id;
        }
        else if (isset($user['remoteuser'])) {
            $dbinstances = get_records_array('auth_instance', 'institution', $WEBSERVICE_INSTITUTION);
            $dbuser = false;
            foreach ($dbinstances as $dbinstance) {
               $user_factory = new User;
               $dbuser = $user_factory->find_by_instanceid_username($dbinstance->id, $user['remoteuser'], true);
               if ($dbuser) {
                   break;
               }
            }
            if (empty($dbuser)) {
                throw new WebserviceInvalidParameterException(get_string('invalidremoteusername', 'auth.webservice', $user['username']));
            }
            $id = $dbuser->id;
        }
        else {
            throw new WebserviceInvalidParameterException(get_string('musthaveid', 'auth.webservice'));
        }
        // now get the user
        if ($user = get_user($id)) {
            if ($user->deleted) {
                throw new WebserviceInvalidParameterException(get_string('invaliduserid', 'auth.webservice', $id));
            }
            // get the remoteuser
            $user->remoteuser = get_field('auth_remote_user', 'remoteusername', 'authinstance', $user->authinstance, 'localusr', $user->id);
            foreach (array('jabberusername', 'introduction', 'country', 'city', 'address',
                           'town', 'homenumber', 'businessnumber', 'mobilenumber', 'faxnumber',
                           'officialwebsite', 'personalwebsite', 'blogaddress', 'aimscreenname',
                           'icqnumber', 'msnnumber', 'yahoochat', 'skypeusername', 'jabberusername',
                           'occupation', 'industry') as $attr) {
                if ($art = get_record('artefact', 'artefacttype', $attr, 'owner', $user->id)) {
                    $user->{$attr} = $art->title;
                }
            }
            return $user;
        }
        else {
            throw new WebserviceInvalidParameterException(get_string('invaliduserid', 'auth.webservice', $id));
        }
    }

    /**
     * Get user information for one or more users
     *
     * @param array $users  array of users
     * @return array An array of arrays describing users
     */
    public static function get_users_by_id($users) {
        global $WEBSERVICE_INSTITUTION, $WEBSERVICE_OAUTH_USER, $USER;

        $params = self::validate_parameters(self::get_users_by_id_parameters(),
                array('users'=>$users));

        // if this is a get all users - then lets get them all
        if (empty($params['users'])) {
            $params['users'] = array();
            $dbusers = get_records_sql_array('SELECT u.id AS id FROM {usr} u
                                                INNER JOIN {auth_instance} ai ON u.authinstance = ai.id
                                                LEFT JOIN {usr_institution} ui ON u.id = ui.usr AND ui.institution = ?
                                                WHERE u.deleted = ? AND (ai.institution = ?
                                                                      OR ui.institution = ?)', array($WEBSERVICE_INSTITUTION, 0, $WEBSERVICE_INSTITUTION, $WEBSERVICE_INSTITUTION));
            if ($dbusers) {
                foreach ($dbusers as $dbuser) {
                    // eliminate bad uid
                    if ($dbuser->id == 0) {
                        continue;
                    }
                    $params['users'][] = array('id' => $dbuser->id);
                }
            }
        }

        //TODO: check if there is any performance issue: we do one DB request to retrieve
        //  all user, then for each user the profile_load_data does at least two DB requests
        $users = array();
        foreach ($params['users'] as $user) {
            $users[]= self::checkuser($user);
        }

        $result = array();
        foreach ($users as $user) {
            if (empty($user->deleted)) {
                // check the institution
                if (!mahara_external_in_institution($user, $WEBSERVICE_INSTITUTION)) {
                    throw new WebserviceInvalidParameterException(get_string('notauthforuseridinstitution', 'auth.webservice', $user->id, $WEBSERVICE_INSTITUTION));
                }

                $auth_instance = get_record('auth_instance', 'id', $user->authinstance);

                $userarray = array();
                // we want to return an array not an object
                // now we transfer all profile_field_xxx into the customfields
                // external_multiple_structure required by description
                $userarray['id'] = $user->id;
                $userarray['username'] = $user->username;
                $userarray['firstname'] = $user->firstname;
                $userarray['lastname'] = $user->lastname;
                $userarray['email'] = $user->email;
                $userarray['auth'] = $auth_instance->authname;
                $userarray['studentid'] = $user->studentid;
                $userarray['preferredname'] = $user->preferredname;
                foreach (self::$ALLOWEDKEYS as $field) {
                    $userarray[$field] = ((isset($user->{$field}) && $user->{$field}) ? $user->{$field} : '');
                }
                $userarray['institution'] = $auth_instance->institution;
                $userarray['auths'] = array();
                $auths = get_records_sql_array('SELECT aru.remoteusername AS remoteusername, ai.authname AS authname FROM {auth_remote_user} aru
                                                  INNER JOIN {auth_instance} ai ON aru.authinstance = ai.id
                                                  WHERE ai.institution = ? AND aru.localusr = ?', array($WEBSERVICE_INSTITUTION, $user->id));
                if ($auths) {
                    foreach ($auths as $auth) {
                        $userarray['auths'][]= array('auth' => $auth->authname, 'remoteuser' => $auth->remoteusername);
                    }
                }
                $result[] = $userarray;
            }
        }

        return $result;
    }

    /**
     * parameter definition for output of get_users_by_id method
     *
     * Returns description of method result value
     * @return external_description
     */
    public static function get_users_by_id_returns() {
        return new external_multiple_structure(
                new external_single_structure(
                        array(
                    'id'              => new external_value(PARAM_NUMBER, 'ID of the user'),
                    'username'        => new external_value(PARAM_RAW, 'Username policy is defined in Mahara security config'),
                    'firstname'       => new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
                    'lastname'        => new external_value(PARAM_NOTAGS, 'The family name of the user'),
                    'email'           => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost'),
                    'auth'            => new external_value(PARAM_SAFEDIR, 'Auth plugins include manual, ldap, imap, etc'),
                    'studentid'       => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution'),
                    'institution'     => new external_value(PARAM_SAFEDIR, 'Mahara institution'),
                    'preferredname'   => new external_value(PARAM_RAW, 'User preferred name'),
                    'introduction'    => new external_value(PARAM_RAW, 'User introduction'),
                    'country'         => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ'),
                    'city'            => new external_value(PARAM_NOTAGS, 'Home city of the user'),
                    'address'         => new external_value(PARAM_RAW, 'Introduction text'),
                    'town'            => new external_value(PARAM_NOTAGS, 'Home town of the user'),
                    'homenumber'      => new external_value(PARAM_RAW, 'Home phone number'),
                    'businessnumber'  => new external_value(PARAM_RAW, 'business phone number'),
                    'mobilenumber'    => new external_value(PARAM_RAW, 'mobile phone number'),
                    'faxnumber'       => new external_value(PARAM_RAW, 'fax number'),
                    'officialwebsite' => new external_value(PARAM_RAW, 'Official user website'),
                    'personalwebsite' => new external_value(PARAM_RAW, 'Personal website'),
                    'blogaddress'     => new external_value(PARAM_RAW, 'Blog web address'),
                    'aimscreenname'   => new external_value(PARAM_ALPHANUMEXT, 'AIM screen name'),
                    'icqnumber'       => new external_value(PARAM_ALPHANUMEXT, 'ICQ Number'),
                    'msnnumber'       => new external_value(PARAM_ALPHANUMEXT, 'MSN Number'),
                    'yahoochat'       => new external_value(PARAM_ALPHANUMEXT, 'Yahoo chat'),
                    'skypeusername'   => new external_value(PARAM_ALPHANUMEXT, 'Skype username'),
                    'jabberusername'  => new external_value(PARAM_RAW, 'Jabber/XMPP username'),
                    'occupation'      => new external_value(PARAM_TEXT, 'Occupation'),
                    'industry'        => new external_value(PARAM_TEXT, 'Industry'),
                    'auths'           => new external_multiple_structure(
                                            new external_single_structure(
                                                array(
                                                    'auth'       => new external_value(PARAM_SAFEDIR, 'Auth plugins include manual, ldap, imap, etc'),
                                                    'remoteuser' => new external_value(PARAM_RAW, 'remote username'),
                                                ), 'Connected Remote Users')
                                        ),
                        )
                )
        );
    }

    /**
     * parameter definition for input of get_users method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function get_users_parameters() {
        return new external_function_parameters(array());
    }

    /**
     * Get user information for all users
     *
     * @param array $userids  array of user ids
     * @return array An array of arrays describing users
     */
    public static function get_users() {
        return self::get_users_by_id(array());
    }

    /**
     * parameter definition for output of get_users method
     *
     * Returns description of method result value
     * @return external_description
     */
    public static function get_users_returns() {
        return self::get_users_by_id_returns();
    }

    /**
     * parameter definition for input of get_online_users method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function get_online_users_parameters() {
        return new external_function_parameters(array());
    }

    /**
     * Get user information for online users
     *
     * @return array An array of arrays describing an atom feed
     */
    public static function get_online_users() {
        global $USER;

        // last 10 active users
        $users = get_onlineusers();

        // now format ready for atom
        $results = array(
                 'id'      => sha1($_SERVER['HTTP_HOST'] . 'get_online_users' . time()),
                 'link'    => get_config('wwwroot'),
                 'email'   => $USER->get('email'),
                 'uri'     => get_config('wwwroot'),
                 'title'   => 'Get Online Users by ' . $USER->username . ' at ' . webservice_rest_server::format_rfc3339_date(time()),
                 'name'    => 'mahara_user_external_get_online_users',
                 'updated' => webservice_rest_server::format_rfc3339_date(time()),
                 'entries' => array(),
        );

        foreach ($users['data'] as $user) {
            $user = get_record('usr', 'id', $user);
            if (empty($user)) {
                continue;
            }
            $results['entries'][] = array(
                             'id'        => get_config('wwwroot') . 'user/view.php?id=' . $user->id,
                             'link'      => get_config('wwwroot') . 'user/view.php?id=' . $user->id,
                             'email'     => $user->email,
                             'name'      => display_name($user),
                             'updated'   => webservice_rest_server::format_rfc3339_date(strtotime($user->lastaccess)),
                             'published' => webservice_rest_server::format_rfc3339_date(time()),
                             'title'     => 'last_access',
            );
        }
        return $results;
    }

    /**
     * parameter definition for output of get_online_users method
     *
     * Returns description of method result value
     * @return external_description
     */
    public static function get_online_users_returns() {
        return mahara_external_atom_returns();
    }

    /**
     * parameter definition for input of get_my_users method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function get_my_user_parameters() {
        return new external_function_parameters(array());
    }

    /**
     * Get my user information - the currently connected user
     *
     * @param array $userids  array of user ids
     * @return array An array of arrays describing users
     */
    public static function get_my_user() {
        global $USER;
        return array_shift(self::get_users_by_id(array(array('id' => $USER->get('id')))));
    }

    /**
     * parameter definition for output of get_my_users method
     *
     * Returns description of method result value
     * @return external_description
     */
    public static function get_my_user_returns() {
        return new external_single_structure(
                 array(
                    'id'              => new external_value(PARAM_NUMBER, 'ID of the user'),
                    'username'        => new external_value(PARAM_RAW, 'Username policy is defined in Mahara security config'),
                    'firstname'       => new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
                    'lastname'        => new external_value(PARAM_NOTAGS, 'The family name of the user'),
                    'email'           => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost'),
                    'auth'            => new external_value(PARAM_SAFEDIR, 'Auth plugins include manual, ldap, imap, etc'),
                    'studentid'       => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution'),
                    'institution'     => new external_value(PARAM_SAFEDIR, 'Mahara institution'),
                    'preferredname'   => new external_value(PARAM_RAW, 'User preferred name'),
                    'introduction'    => new external_value(PARAM_RAW, 'User introduction'),
                    'country'         => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ'),
                    'city'            => new external_value(PARAM_NOTAGS, 'Home city of the user'),
                    'address'         => new external_value(PARAM_RAW, 'Introduction text'),
                    'town'            => new external_value(PARAM_NOTAGS, 'Home town of the user'),
                    'homenumber'      => new external_value(PARAM_RAW, 'Home phone number'),
                    'businessnumber'  => new external_value(PARAM_RAW, 'business phone number'),
                    'mobilenumber'    => new external_value(PARAM_RAW, 'mobile phone number'),
                    'faxnumber'       => new external_value(PARAM_RAW, 'fax number'),
                    'officialwebsite' => new external_value(PARAM_RAW, 'Official user website'),
                    'personalwebsite' => new external_value(PARAM_RAW, 'Personal website'),
                    'blogaddress'     => new external_value(PARAM_RAW, 'Blog web address'),
                    'aimscreenname'   => new external_value(PARAM_ALPHANUMEXT, 'AIM screen name'),
                    'icqnumber'       => new external_value(PARAM_ALPHANUMEXT, 'ICQ Number'),
                    'msnnumber'       => new external_value(PARAM_ALPHANUMEXT, 'MSN Number'),
                    'yahoochat'       => new external_value(PARAM_ALPHANUMEXT, 'Yahoo chat'),
                    'skypeusername'   => new external_value(PARAM_ALPHANUMEXT, 'Skype username'),
                    'jabberusername'  => new external_value(PARAM_RAW, 'Jabber/XMPP username'),
                    'occupation'      => new external_value(PARAM_TEXT, 'Occupation'),
                    'industry'        => new external_value(PARAM_TEXT, 'Industry'),
                    'auths'           => new external_multiple_structure(
                                            new external_single_structure(
                                                array(
                                                    'auth'       => new external_value(PARAM_SAFEDIR, 'Auth plugins include manual, ldap, imap, etc'),
                                                    'remoteuser' => new external_value(PARAM_RAW, 'remote username'),
                                                ), 'Connected Remote Users')
                                        ),
                        )
                );
    }

    /**
     * parameter definition for input of get_context method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function get_context_parameters() {
        return new external_function_parameters(array());
    }

    /**
     * Get the current institution context - this is like a test call
     *
     * @return string the connected institution
     */
    public static function get_context() {
        global $WEBSERVICE_INSTITUTION;
        return $WEBSERVICE_INSTITUTION;
    }

    /**
     * parameter definition for output of get_context method
     *
     * Returns description of method result value
     * @return external_description
     */
    public static function get_context_returns() {
        return new external_value(PARAM_TEXT, 'The INSTITUTION context of the authenticated user');
    }

    /**
     * parameter definition for input of get_extended_context method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function get_extended_context_parameters() {
        return new external_function_parameters(array());
    }

    /**
     * Get my user information
     *
     * @return array of connection context information including:
     *   currently connected institution
     *   the current user - like get_my_user
     *   list of functions that this user/connection can execute
     */
    public static function get_extended_context() {
        global $USER, $WEBSERVICE_INSTITUTION, $WS_FUNCTIONS;
        $functions = array();
        foreach ((empty($WS_FUNCTIONS) ? array() : $WS_FUNCTIONS) as $name => $function) {
            $functions[]= array('function' => $name, 'wsdoc' => get_config('wwwroot') . 'webservice/wsdoc.php?id=' . $function['id']);
        }
        return array('institution' => $WEBSERVICE_INSTITUTION,
                     'institutionname' => get_field('institution', 'displayname', 'name', $WEBSERVICE_INSTITUTION),
                     'sitename' => get_config('sitename'),
                     'siteurl' => get_config('wwwroot'),
                     'userid' => $USER->get('id'),
                     'username' => $USER->get('username'),
                     'firstname' => $USER->get('firstname'),
                     'lastname' => $USER->get('lastname'),
                     'fullname' => display_name($USER, null, true),
                     'functions' => $functions,
                );
    }

    /**
     * parameter definition for output of get_extended_context method
     *
     * Returns description of method result value
     * @return external_description
     */
    public static function get_extended_context_returns() {
        return new external_single_structure(
                array(
                    'institution'     => new external_value(PARAM_TEXT, 'The INSTITUTION context of the authenticated user'),
                    'institutionname' => new external_value(PARAM_TEXT, 'The INSTITUTION FULLNAME context of the authenticated user'),
                    'sitename'        => new external_value(PARAM_RAW, 'Site name', VALUE_OPTIONAL),
                    'siteurl'         => new external_value(PARAM_RAW, 'Site URL', VALUE_OPTIONAL),
                    'userid'          => new external_value(PARAM_NUMBER, 'ID of the authenticated user', VALUE_OPTIONAL),
                    'username'        => new external_value(PARAM_RAW, 'Username of the authenticated user', VALUE_OPTIONAL),
                    'firstname'       => new external_value(PARAM_TEXT, 'Firstname of the authenticated user', VALUE_OPTIONAL),
                    'lastname'        => new external_value(PARAM_TEXT, 'Last of the authenticated user', VALUE_OPTIONAL),
                    'fullname'        => new external_value(PARAM_TEXT, 'Fullname of the authenticated user', VALUE_OPTIONAL),
                    'functions'       => new external_multiple_structure(
                                                    new external_single_structure(
                                                        array(
                                                            'function' => new external_value(PARAM_RAW, 'functon name', VALUE_OPTIONAL),
                                                            'wsdoc'    => new external_value(PARAM_RAW, 'function documentation URI', VALUE_OPTIONAL),
                                                        ), 'Available functions')
                                                ),
                    )
            );

    }

    /**
     * parameter definition for input of update_favourites method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function update_favourites_parameters() {

       return new external_function_parameters(
            array(
                'users' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'id'              => new external_value(PARAM_NUMBER, 'ID of the favourites owner', VALUE_OPTIONAL),
                            'username'        => new external_value(PARAM_RAW, 'Username of the favourites owner', VALUE_OPTIONAL),
                            'shortname'       => new external_value(PARAM_SAFEDIR, 'Favourites shorname', VALUE_DEFAULT, 'favourites', NULL_NOT_ALLOWED),
                            'institution'     => new external_value(PARAM_SAFEDIR, 'Mahara institution', VALUE_DEFAULT, 'mahara', NULL_NOT_ALLOWED),
                            'favourites'      => new external_multiple_structure(
                                                            new external_single_structure(
                                                                array(
                                                                    'id'       => new external_value(PARAM_NUMBER, 'favourite user Id', VALUE_OPTIONAL),
                                                                    'username' => new external_value(PARAM_RAW, 'favourite username', VALUE_OPTIONAL),
                                                                ), 'User favourites')
                                                        ),
                            )
                    )
                )
            )
        );
    }

    /**
     * update one or more user favourites
     *
     * @param array $users
     */
    public static function update_favourites($users) {
        global $USER, $WEBSERVICE_INSTITUTION, $WEBSERVICE_OAUTH_USER;

        $params = self::validate_parameters(self::update_favourites_parameters(), array('users'=>$users));

        db_begin();
        foreach ($params['users'] as $user) {
            $dbuser = self::checkuser($user);

            $ownerid = $dbuser->id;

            // Make sure auth is valid
            if (!$authinstance = get_record('auth_instance', 'id', $dbuser->authinstance)) {
                throw new WebserviceInvalidParameterException('update_favourites | ' . get_string('invalidauthtype', 'auth.webservice', $dbuser->authinstance));
            }
            // check the institution is allowed
            // basic check authorisation to edit for the current institution
            if (!$USER->can_edit_institution($authinstance->institution)) {
                throw new WebserviceInvalidParameterException('update_favourites | ' . get_string('accessdeniedforinstuser', 'auth.webservice', $authinstance->institution, $dbuser->id));
            }

            // are we allowed to delete for this institution
            if ($WEBSERVICE_INSTITUTION != $user['institution'] || !$USER->can_edit_institution($user['institution'])) {
                throw new WebserviceInvalidParameterException('update_favourites | ' . get_string('accessdeniedforinst', 'auth.webservice', $user['institution']));
            }

            // check that the favourites exist and we are allowed to administer them
            $favourites = array();
            foreach ($user['favourites'] as $favourite) {
                $dbuser = self::checkuser($favourite);
                // Make sure auth is valid
                if (!$authinstance = get_record('auth_instance', 'id', $dbuser->authinstance)) {
                    throw new WebserviceInvalidParameterException('update_favourites | ' . get_string('invalidauthtype', 'auth.webservice', $dbuser->authinstance));
                }

                // check the institution is allowed
                // basic check authorisation to edit for the current institution of the user
                if (!$USER->can_edit_institution($authinstance->institution)) {
                    throw new WebserviceInvalidParameterException('update_favourites | ' . get_string('accessdeniedforinstuser', 'auth.webservice', $authinstance->institution, $dbuser->username));
                }
                $favourites[]= $dbuser->id;
            }

            // now do the update
            update_favorites($ownerid, $user['shortname'], $user['institution'], $favourites);
        }
        db_commit();

        return null;
    }

   /**
    * parameter definition for output of update_favourites method
    *
    * Returns description of method result value
    * @return external_description
    */
    public static function update_favourites_returns() {
        return null;
    }

    /**
     * parameter definition for input of get_favourites method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function get_favourites_parameters() {
        return new external_function_parameters(
            array(
                'users'=> new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'shortname' => new external_value(PARAM_SAFEDIR, 'Favourites shorname', VALUE_DEFAULT, 'favourites', NULL_NOT_ALLOWED),
                            'userid'    => new external_value(PARAM_INT, 'user id', VALUE_OPTIONAL),
                            'username'  => new external_value(PARAM_RAW, 'Username of the favourites owner', VALUE_OPTIONAL),
                        )
                    )
                )
            )
        );
    }

    /**
     * Get user favourites for one or more users
     *
     * @param array $userids  array of user ids
     * @return array An array of arrays describing users favourites
     */
    public static function get_favourites($users) {
        global $WEBSERVICE_INSTITUTION, $WEBSERVICE_OAUTH_USER;

        $params = self::validate_parameters(self::get_favourites_parameters(), array('users' => $users));

        // build the final results
        $result = array();
        foreach ($params['users'] as $user) {
            $dbuser = self::checkuser($user);
            // check the institution
            if (!mahara_external_in_institution($dbuser, $WEBSERVICE_INSTITUTION)) {
                throw new WebserviceInvalidParameterException('get_favourites | ' . get_string('notauthforuseridinstitution', 'auth.webservice', $user['userid'], $auth_instance->institution));
            }

            // get the favourite for the shortname for this user
            $favs = array();
            $favourites = get_user_favorites($dbuser->id, 100);
            $dbfavourite = get_record('favorite', 'shortname', $user['shortname'], 'institution', $WEBSERVICE_INSTITUTION, 'owner', $dbuser->id);
            if (empty($dbfavourite)) {
                // create an empty one
                $dbfavourite = (object) array('shortname' => $user['shortname'], 'institution' => $WEBSERVICE_INSTITUTION);
            }
            if (!empty($favourites)) {
                foreach ($favourites as $fav) {
                    $dbfavuser = get_record('usr', 'id', $fav->id, 'deleted', 0);
                    $favs[]= array('id' => $fav->id, 'username' => $dbfavuser->username);
                }
            }

            $result[] = array(
                            'id'            => $dbuser->id,
                            'username'      => $dbuser->username,
                            'shortname'     => $dbfavourite->shortname,
                            'institution'   => $dbfavourite->institution,
                            'favourites'    => $favs,
                            );
        }

        return $result;
    }

    /**
     * parameter definition for output of get_favourites method
     *
     * Returns description of method result value
     * @return external_description
     */
    public static function get_favourites_returns() {
        return new external_multiple_structure(
                new external_single_structure(
                        array(
                            'id'              => new external_value(PARAM_NUMBER, 'ID of the favourites owner'),
                            'username'        => new external_value(PARAM_RAW, 'Username of the favourites owner'),
                            'shortname'       => new external_value(PARAM_SAFEDIR, 'Favourites shorname'),
                            'institution'     => new external_value(PARAM_SAFEDIR, 'Mahara institution'),
                            'favourites'      => new external_multiple_structure(
                                                            new external_single_structure(
                                                                array(
                                                                    'id'       => new external_value(PARAM_NUMBER, 'favourite user Id', VALUE_OPTIONAL),
                                                                    'username' => new external_value(PARAM_RAW, 'favourite username', VALUE_OPTIONAL),
                                                                ), 'User favourites')
                                                        ),
                                                )
                )
        );
    }

    /**
     * parameter definition for input of get_all_favourites method
     *
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function get_all_favourites_parameters() {
        return new external_function_parameters(
            array(
                'shortname' => new external_value(PARAM_SAFEDIR, 'Favourites shorname', VALUE_DEFAULT, 'favourites', NULL_NOT_ALLOWED),
                )
        );
    }

    /**
     * Get all user favourites
     *
     * @param string $shortname  shortname of the favourites
     */
    public static function get_all_favourites($shortname) {
        global $WEBSERVICE_INSTITUTION, $WEBSERVICE_OAUTH_USER;

        $params = self::validate_parameters(self::get_all_favourites_parameters(), array('shortname' => $shortname));

        $dbfavourites = get_records_sql_array('SELECT * from {favorite} WHERE shortname = ? AND institution = ?',array($shortname, $WEBSERVICE_INSTITUTION));
        if (empty($dbfavourites)) {
            throw new WebserviceInvalidParameterException('get_favourites | ' . get_string('invalidfavourite', 'auth.webservice', $shortname . '/' . $WEBSERVICE_INSTITUTION));
        }

        $result = array();
        foreach ($dbfavourites as $dbfavourite) {
            $dbuser = get_record('usr', 'id', $dbfavourite->owner, 'deleted', 0);
            if (empty($dbuser)) {
                continue;
            }
            $favourites = get_user_favorites($dbuser->id, 100);
            $favs = array();
            if (!empty($favourites)) {
                foreach ($favourites as $fav) {
                    $dbfavuser = get_record('usr', 'id', $fav->id, 'deleted', 0);
                    $favs[]= array('id' => $fav->id, 'username' => $dbfavuser->username);
                }
            }

            $result[] = array(
                            'id'            => $dbuser->id,
                            'username'      => $dbuser->username,
                            'shortname'     => $dbfavourite->shortname,
                            'institution'   => $dbfavourite->institution,
                            'favourites'    => $favs,
                            );
        }

        return $result;
    }

    /**
     *  parameter definition for output of get_all_favourites method
     *
     * Returns description of method result value
     * @return external_description
     */
    public static function get_all_favourites_returns() {
        return self::get_favourites_returns();
    }
}