Completed
Push — master ( bdb7fb...d3d147 )
by Julito
25:16
created

WSHelperActionOnUsers()   C

Complexity

Conditions 12
Paths 86

Size

Total Lines 51
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 35
nc 86
nop 2
dl 0
loc 51
rs 5.6668
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
5
use Chamilo\UserBundle\Entity\User;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, User. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
7
/**
8
 * @package chamilo.webservices
9
 */
10
require_once __DIR__.'/../inc/global.inc.php';
11
$debug = true;
12
13
define('WS_ERROR_SECRET_KEY', 1);
14
define('WS_ERROR_NOT_FOUND_RESULT', 2);
15
define('WS_ERROR_INVALID_INPUT', 3);
16
define('WS_ERROR_SETTING', 4);
17
define('DEFAULT_ADMIN_USER_ID', 1);
18
19
/**
20
 * @param string $code
21
 * @return null|soap_fault
22
 */
23
function returnError($code)
24
{
25
    $fault = null;
26
    switch ($code) {
27
        case WS_ERROR_SECRET_KEY:
28
            $fault = new soap_fault(
29
                'Server',
30
                '',
31
                'Secret key is not correct or params are not correctly set'
32
            );
33
            break;
34
        case WS_ERROR_NOT_FOUND_RESULT:
35
            $fault = new soap_fault(
36
                'Server',
37
                '',
38
                'No result was found for this query'
39
            );
40
            break;
41
        case WS_ERROR_INVALID_INPUT:
42
            $fault = new soap_fault(
43
                'Server',
44
                '',
45
                'The input variables are invalid o are not correctly set'
46
            );
47
            break;
48
        case WS_ERROR_SETTING:
49
            $fault = new soap_fault(
50
                'Server',
51
                '',
52
                'Please check the configuration for this webservice'
53
            );
54
            break;
55
    }
56
    return $fault;
57
}
58
59
/**
60
 * @param array $params
61
 * @return bool
62
 */
63
function WSHelperVerifyKey($params)
64
{
65
    global $_configuration, $debug;
66
    if (is_array($params)) {
67
        $secret_key = $params['secret_key'];
68
    } else {
69
        $secret_key = $params;
70
    }
71
    //error_log(print_r($params,1));
72
    $check_ip = false;
73
    $ip_matches = false;
74
    $ip = trim($_SERVER['REMOTE_ADDR']);
75
    // if we are behind a reverse proxy, assume it will send the
76
    // HTTP_X_FORWARDED_FOR header and use this IP instead
77
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
78
        list($ip1) = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
79
        $ip = trim($ip1);
80
    }
81
    if ($debug) {
82
        error_log("ip: $ip");
83
    }
84
    // Check if a file that limits access from webservices exists and contains
85
    // the restraining check
86
    if (is_file('webservice-auth-ip.conf.php')) {
87
        include 'webservice-auth-ip.conf.php';
88
        if ($debug) {
89
            error_log("webservice-auth-ip.conf.php file included");
90
        }
91
        if (!empty($ws_auth_ip)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ws_auth_ip seems to never exist and therefore empty should always be true.
Loading history...
92
            $check_ip = true;
93
            $ip_matches = api_check_ip_in_range($ip, $ws_auth_ip);
94
            if ($debug) {
95
                error_log("ip_matches: $ip_matches");
96
            }
97
        }
98
    }
99
100
    if ($debug) {
101
        error_log("checkip ".intval($check_ip));
102
    }
103
104
    if ($check_ip) {
105
        $security_key = $_configuration['security_key'];
106
    } else {
107
        $security_key = $ip.$_configuration['security_key'];
108
        //error_log($ip.'-'.$secret_key.'-'.$security_key);
109
    }
110
111
    $result = api_is_valid_secret_key($secret_key, $security_key);
112
113
    if ($debug) {
114
        error_log('WSHelperVerifyKey result: '.intval($result));
115
    }
116
    return $result;
117
}
118
119
// Create the server instance
120
$server = new soap_server();
121
122
/** @var HookWSRegistration $hook */
123
$hook = HookWSRegistration::create();
124
if (!empty($hook)) {
125
    $hook->setEventData(['server' => $server]);
126
    $res = $hook->notifyWSRegistration(HOOK_EVENT_TYPE_PRE);
127
    if (!empty($res['server'])) {
128
        $server = $res['server'];
129
    }
130
}
131
132
$server->soap_defencoding = 'UTF-8';
133
134
// Initialize WSDL support
135
$server->configureWSDL('WSRegistration', 'urn:WSRegistration');
136
137
/* Register WSCreateUsers function */
138
// Register the data structures used by the service
139
140
// Prepare input params
141
$server->wsdl->addComplexType(
142
    'extras',
143
    'complexType',
144
    'struct',
145
    'all',
146
    '',
147
    [
148
        'field_name'  => ['name' => 'field_name', 'type' => 'xsd:string'],
149
        'field_value' => ['name' => 'field_value', 'type' => 'xsd:string']
150
    ]
151
);
152
153
$server->wsdl->addComplexType(
154
    'extrasList',
155
    'complexType',
156
    'array',
157
    '',
158
    'SOAP-ENC:Array',
159
    [],
160
    [['ref'=>'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:extras[]']],
161
    'tns:extras'
162
);
163
164
$server->wsdl->addComplexType(
165
    'usersParams',
166
    'complexType',
167
    'struct',
168
    'all',
169
    '',
170
    [
171
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
172
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
173
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
174
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
175
        'loginname' => ['name' => 'loginname', 'type' => 'xsd:string'],
176
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
177
        'language' => ['name' => 'language', 'type' => 'xsd:string'],
178
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
179
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
180
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
181
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
182
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
183
    ]
184
);
185
186
$server->wsdl->addComplexType(
187
    'usersParamsList',
188
    'complexType',
189
    'array',
190
    '',
191
    'SOAP-ENC:Array',
192
    [],
193
    [['ref'=>'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:usersParams[]']],
194
    'tns:usersParams'
195
);
196
197
$server->wsdl->addComplexType(
198
    'createUsers',
199
    'complexType',
200
    'struct',
201
    'all',
202
    '',
203
    [
204
        'users' => ['name' => 'users', 'type' => 'tns:usersParamsList'],
205
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
206
    ]
207
);
208
209
// Prepare output params, in this case will return an array
210
$server->wsdl->addComplexType(
211
    'result_createUsers',
212
    'complexType',
213
    'struct',
214
    'all',
215
    '',
216
    [
217
        'original_user_id_value' => [
218
            'name' => 'original_user_id_value',
219
            'type' => 'xsd:string',
220
        ],
221
        'result' => ['name' => 'result', 'type' => 'xsd:string']
222
    ]
223
);
224
225
$server->wsdl->addComplexType(
226
    'results_createUsers',
227
    'complexType',
228
    'array',
229
    '',
230
    'SOAP-ENC:Array',
231
    [],
232
    [
233
        [
234
            'ref' => 'SOAP-ENC:arrayType',
235
            'wsdl:arrayType' => 'tns:result_createUsers[]'
236
        ]
237
    ],
238
    'tns:result_createUsers'
239
);
240
241
// Register the method to expose
242
$server->register(
243
    'WSCreateUsers', // method name
244
    ['createUsers' => 'tns:createUsers'], // input parameters
245
    ['return' => 'tns:results_createUsers'], // output parameters
246
    'urn:WSRegistration', // namespace
247
    'urn:WSRegistration#WSCreateUsers', // soapaction
248
    'rpc', // style
249
    'encoded', // use
250
    'This service adds a user'                     // documentation
251
);
252
253
254
// Define the method WSCreateUsers
255
function WSCreateUsers($params)
256
{
257
    if (!WSHelperVerifyKey($params)) {
258
        return returnError(WS_ERROR_SECRET_KEY);
259
    }
260
261
    $users_params = $params['users'];
262
    $results = [];
263
    $orig_user_id_value = [];
264
265
    $userManager = UserManager::getManager();
266
    $userRepository = UserManager::getRepository();
267
268
    foreach ($users_params as $user_param) {
269
        $firstName = $user_param['firstname'];
270
        $lastName = $user_param['lastname'];
271
        $status = $user_param['status'];
272
        $email = $user_param['email'];
273
        $loginName = $user_param['loginname'];
274
        $password = $user_param['password'];
275
        $official_code = '';
276
        $language = '';
277
        $phone = '';
278
        $picture_uri = '';
279
        $auth_source = PLATFORM_AUTH_SOURCE;
280
        $expiration_date = '';
281
        $active = 1;
282
        $hr_dept_id = 0;
283
        $extra = null;
284
        $original_user_id_name = $user_param['original_user_id_name'];
285
        $original_user_id_value = $user_param['original_user_id_value'];
286
        $orig_user_id_value[] = $user_param['original_user_id_value'];
287
        $extra_list = $user_param['extra'];
288
        if (!empty($user_param['language'])) {
289
            $language = $user_param['language'];
290
        }
291
        if (!empty($user_param['phone'])) {
292
            $phone = $user_param['phone'];
293
        }
294
        if (!empty($user_param['expiration_date'])) {
295
            $expiration_date = $user_param['expiration_date'];
296
        }
297
298
        // Check if exits x_user_id into user_field_values table.
299
        $user_id = UserManager::get_user_id_from_original_id(
300
            $original_user_id_value,
301
            $original_user_id_name
302
        );
303
        if ($user_id > 0) {
304
            /** @var User $user */
305
            $user = $userRepository->find($user_id);
306
307
            if ($user && $user->isActive() == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
308
                if (!is_null($password)) {
309
                    $user->setPlainPassword($password);
310
                }
311
                if (!is_null($auth_source)) {
312
                    $user->setAuthSource($auth_source);
313
                }
314
315
                if (!empty($user_param['expiration_date'])) {
316
                    $expiration_date = new DateTime($user_param['expiration_date']);
317
                }
318
319
                $user->setLastname($lastName)
320
                    ->setFirstname($firstName)
321
                    ->setUsername($loginName)
322
                    ->setEmail($email)
323
                    ->setStatus($status)
324
                    ->setOfficialCode($official_code)
325
                    ->setPhone($phone)
326
                    ->setExpirationDate($expiration_date)
327
                    ->setHrDeptId($hr_dept_id)
328
                    ->setActive(true);
329
                $userManager->updateUser($user, true);
330
                $results[] = $user_id;
331
                continue;
332
            //return $r_check_user[0];
333
            } else {
334
                $results[] = 0;
335
                continue;
336
                //return 0;
337
                // user id already exits.
338
            }
339
        }
340
341
        // Default language.
342
        if (empty($language)) {
343
            $language = api_get_setting('platformLanguage');
344
        }
345
346
        $creatorId = DEFAULT_ADMIN_USER_ID;
347
348
        // First check wether the login already exists.
349
        if (!UserManager::is_username_available($loginName)) {
350
            $results[] = 0;
351
            continue;
352
        }
353
354
        $userId = UserManager::create_user(
355
            $firstName,
356
            $lastName,
357
            $status,
358
            $email,
359
            $loginName,
360
            $password,
361
            $official_code,
362
            $language,
363
            $phone,
364
            $picture_uri,
365
            $auth_source,
366
            $expiration_date,
367
            $active,
368
            $hr_dept_id,
369
            [],
370
            '',
371
            false,
372
            false,
373
            '',
374
            false,
375
            null,
376
            $creatorId
377
        );
378
379
        if ($userId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $userId of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
380
            if (api_is_multiple_url_enabled()) {
381
                if (api_get_current_access_url_id() != -1) {
382
                    UrlManager::add_user_to_url(
383
                        $userId,
384
                        api_get_current_access_url_id()
385
                    );
386
                } else {
387
                    UrlManager::add_user_to_url($userId, 1);
388
                }
389
            } else {
390
                // We add by default the access_url_user table with access_url_id = 1
391
                UrlManager::add_user_to_url($userId, 1);
392
            }
393
394
            // Save new field label into user_field table.
395
            UserManager::create_extra_field(
396
                $original_user_id_name,
397
                1,
398
                $original_user_id_name,
399
                ''
400
            );
401
            // Save the external system's id into user_field_value table.
402
            UserManager::update_extra_field_value(
403
                $userId,
404
                $original_user_id_name,
405
                $original_user_id_value
406
            );
407
408
            if (is_array($extra_list) && count($extra_list) > 0) {
409
                foreach ($extra_list as $extra) {
410
                    $extra_field_name = $extra['field_name'];
411
                    $extra_field_value = $extra['field_value'];
412
                    // Save new field label into user_field table.
413
                    UserManager::create_extra_field(
414
                        $extra_field_name,
415
                        1,
416
                        $extra_field_name,
417
                        ''
418
                    );
419
                    // Save the external system's id into user_field_value table.
420
                    UserManager::update_extra_field_value(
421
                        $userId,
422
                        $extra_field_name,
423
                        $extra_field_value
424
                    );
425
                }
426
            }
427
        } else {
428
            $results[] = 0;
429
            continue;
430
        }
431
432
        $results[] = $userId;
433
    } // end principal foreach
434
435
    $count_results = count($results);
436
    $output = [];
437
    for ($i = 0; $i < $count_results; $i++) {
438
        $output[] = [
439
            'original_user_id_value' => $orig_user_id_value[$i],
440
            'result' => $results[$i]
441
        ];
442
    }
443
444
    return $output;
445
}
446
447
/* Register WSCreateUser function */
448
// Register the data structures used by the service
449
$server->wsdl->addComplexType(
450
    'createUser',
451
    'complexType',
452
    'struct',
453
    'all',
454
    '',
455
    [
456
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
457
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
458
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
459
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
460
        'loginname' => ['name' => 'loginname', 'type' => 'xsd:string'],
461
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
462
        'language' => ['name' => 'language', 'type' => 'xsd:string'],
463
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
464
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
465
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
466
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
467
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList'],
468
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
469
        'active' => ['name' => 'extra', 'type' => 'xsd:string']
470
    ]
471
);
472
473
// Register the method to expose
474
$server->register(
475
    'WSCreateUser', // method name
476
    ['createUser' => 'tns:createUser'], // input parameters
477
    ['return' => 'xsd:string'], // output parameters
478
    'urn:WSRegistration', // namespace
479
    'urn:WSRegistration#WSCreateUser', // soapaction
480
    'rpc', // style
481
    'encoded', // use
482
    'This service adds a user'                   // documentation
483
);
484
485
// Define the method WSCreateUser
486
function WSCreateUser($params)
487
{
488
    global $debug;
489
490
    if (!WSHelperVerifyKey($params)) {
491
        return returnError(WS_ERROR_SECRET_KEY);
492
    }
493
494
    $firstName = $params['firstname'];
495
    $lastName = $params['lastname'];
496
    $status = $params['status'];
497
    $email = $params['email'];
498
    $loginName = $params['loginname'];
499
    $password = $params['password'];
500
    $official_code = '';
501
    $language = '';
502
    $phone = '';
503
    $picture_uri = '';
504
    $auth_source = PLATFORM_AUTH_SOURCE;
505
    $expiration_date = null;
506
    $active = !isset($params['active']) || !intval($params['active']) ? 0 : 1;
507
    $hr_dept_id = 0;
508
    $extra = null;
509
    $original_user_id_name = $params['original_user_id_name'];
510
    $original_user_id_value = $params['original_user_id_value'];
511
    $extra_list = $params['extra'];
512
    if (!empty($params['language'])) {
513
        $language = $params['language'];
514
    }
515
    if (!empty($params['phone'])) {
516
        $phone = $params['phone'];
517
    }
518
    if (!empty($params['expiration_date'])) {
519
        $expiration_date = $params['expiration_date'];
520
    }
521
522
    // check if exits x_user_id into user_field_values table
523
    $user_id = UserManager::get_user_id_from_original_id(
524
        $original_user_id_value,
525
        $original_user_id_name
526
    );
527
528
    $userManager = UserManager::getManager();
529
    $userRepository = UserManager::getRepository();
530
531
    if ($user_id > 0) {
532
        /** @var User $user */
533
        $user = $userRepository->find($user_id);
534
        if ($user && $user->isActive() == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
535
            if (!is_null($password)) {
536
                $user->setPlainPassword($password);
537
            }
538
            if (!is_null($auth_source)) {
539
                $user->setAuthSource($auth_source);
540
            }
541
542
            if (!empty($params['expiration_date'])) {
543
                $expiration_date = new DateTime($params['expiration_date']);
544
                $user->setExpirationDate($expiration_date);
545
            }
546
547
            $user->setLastname($lastName)
548
                ->setFirstname($firstName)
549
                ->setUsername($loginName)
550
                ->setEmail($email)
551
                ->setStatus($status)
552
                ->setOfficialCode($official_code)
553
                ->setPhone($phone)
554
                ->setHrDeptId($hr_dept_id)
555
                ->setActive(true);
556
            $userManager->updateUser($user, true);
557
558
            return $user_id;
559
        } else {
560
            return 0;
561
        }
562
    }
563
564
    // Default language
565
    if (empty($language)) {
566
        $language = api_get_setting('platformLanguage');
567
    }
568
569
    $creatorId = DEFAULT_ADMIN_USER_ID;
570
571
    // First check wether the login already exists
572
    if (!UserManager::is_username_available($loginName)) {
573
        if ($debug) {
574
            error_log("Username $loginName is not available");
575
        }
576
        return 0;
577
    }
578
579
    if (isset($original_user_id_name) && isset($original_user_id_value)) {
580
        $_SESSION['ws_'.$original_user_id_name] = $original_user_id_value;
581
    }
582
583
    /** @var User $user */
584
    $userId = UserManager::create_user(
585
        $firstName,
586
        $lastName,
587
        $status,
588
        $email,
589
        $loginName,
590
        $password,
591
        $official_code,
592
        $language,
593
        $phone,
594
        $picture_uri,
595
        $auth_source,
596
        $expiration_date,
597
        $active,
598
        $hr_dept_id,
599
        [],
600
        '',
601
        false,
602
        false,
603
        '',
604
        false,
605
        null,
606
        $creatorId
607
    );
608
609
    if ($userId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $userId of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
610
        if (api_is_multiple_url_enabled()) {
611
            if (api_get_current_access_url_id() != -1) {
612
                UrlManager::add_user_to_url($userId, api_get_current_access_url_id());
613
            } else {
614
                UrlManager::add_user_to_url($userId, 1);
615
            }
616
        } else {
617
            // We add by default the access_url_user table with access_url_id = 1
618
            UrlManager::add_user_to_url($userId, 1);
619
        }
620
621
        // Save new fieldlabel into user_field table.
622
        UserManager::create_extra_field(
623
            $original_user_id_name,
624
            1,
625
            $original_user_id_name,
626
            ''
627
        );
628
        // Save the external system's id into user_field_value table.
629
        UserManager::update_extra_field_value(
630
            $userId,
631
            $original_user_id_name,
632
            $original_user_id_value
633
        );
634
635
        if (isset($original_user_id_name) && isset($original_user_id_value)) {
636
            unset($_SESSION['ws_'.$original_user_id_name]);
637
        }
638
639
        if (is_array($extra_list) && count($extra_list) > 0) {
640
            foreach ($extra_list as $extra) {
641
                $extra_field_name = $extra['field_name'];
642
                $extra_field_value = $extra['field_value'];
643
                // Save new field label into user_field table.
644
                UserManager::create_extra_field(
645
                    $extra_field_name,
646
                    1,
647
                    $extra_field_name,
648
                    ''
649
                );
650
                // Save the external system's id into user_field_value table.
651
                UserManager::update_extra_field_value(
652
                    $userId,
653
                    $extra_field_name,
654
                    $extra_field_value
655
                );
656
            }
657
        }
658
    } else {
659
        return 0;
660
    }
661
662
    return  $userId;
663
}
664
665
/* Register WSCreateUsersPasswordCrypted function */
666
// Register the data structures used by the service
667
// Prepare input params.
668
669
// Input params for editing users
670
$server->wsdl->addComplexType(
671
    'createUsersPassEncryptParams',
672
    'complexType',
673
    'struct',
674
    'all',
675
    '',
676
    [
677
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
678
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
679
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
680
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
681
        'loginname' => ['name' => 'loginname', 'type' => 'xsd:string'],
682
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
683
        'encrypt_method' => ['name' => 'encrypt_method', 'type' => 'xsd:string'],
684
        'language' => ['name' => 'language', 'type' => 'xsd:string'],
685
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
686
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
687
        'official_code' => ['name' => 'official_code', 'type' => 'xsd:string'],
688
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
689
        'original_user_id_value'=> ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
690
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
691
    ]
692
);
693
694
$server->wsdl->addComplexType(
695
    'createUsersPassEncryptParamsList',
696
    'complexType',
697
    'array',
698
    '',
699
    'SOAP-ENC:Array',
700
    [],
701
    [
702
        [
703
            'ref' => 'SOAP-ENC:arrayType',
704
            'wsdl:arrayType' => 'tns:createUsersPassEncryptParams[]'
705
        ]
706
    ],
707
    'tns:createUsersPassEncryptParams'
708
);
709
710
// Register the data structures used by the service
711
$server->wsdl->addComplexType(
712
    'createUsersPasswordCrypted',
713
    'complexType',
714
    'struct',
715
    'all',
716
    '',
717
    [
718
        'users' => [
719
            'name' => 'users',
720
            'type' => 'tns:createUsersPassEncryptParamsList'
721
        ],
722
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
723
    ]
724
);
725
726
// Prepare output params, in this case will return an array
727
$server->wsdl->addComplexType(
728
    'result_createUsersPassEncrypt',
729
    'complexType',
730
    'struct',
731
    'all',
732
    '',
733
    [
734
        'original_user_id_value' => [
735
            'name' => 'original_user_id_value',
736
            'type' => 'xsd:string'
737
        ],
738
        'result' => ['name' => 'result', 'type' => 'xsd:string']
739
    ]
740
);
741
742
$server->wsdl->addComplexType(
743
    'results_createUsersPassEncrypt',
744
    'complexType',
745
    'array',
746
    '',
747
    'SOAP-ENC:Array',
748
    [],
749
    [
750
        [
751
            'ref' => 'SOAP-ENC:arrayType',
752
            'wsdl:arrayType' => 'tns:result_createUsersPassEncrypt[]'
753
        ]
754
    ],
755
    'tns:result_createUsersPassEncrypt'
756
);
757
758
// Register the method to expose
759
$server->register(
760
    'WSCreateUsersPasswordCrypted', // method name
761
    ['createUsersPasswordCrypted' => 'tns:createUsersPasswordCrypted'], // input parameters
762
    ['return' => 'tns:results_createUsersPassEncrypt'], // output parameters
763
    'urn:WSRegistration', // namespace
764
    'urn:WSRegistration#WSCreateUsersPasswordCrypted', // soapaction
765
    'rpc', // style
766
    'encoded', // use
767
    'This service adds users to the system'                                  // documentation
768
);
769
770
// Define the method WSCreateUsersPasswordCrypted
771
function WSCreateUsersPasswordCrypted($params)
772
{
773
    global $_configuration;
774
    if (!WSHelperVerifyKey($params)) {
775
        return returnError(WS_ERROR_SECRET_KEY);
776
    }
777
778
    // database table definition
779
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
780
    $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
781
    $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
782
783
    $users_params = $params['users'];
784
    $results = [];
785
    $orig_user_id_value = [];
786
787
    foreach ($users_params as $user_param) {
788
        $password = $user_param['password'];
789
        $encrypt_method = $user_param['encrypt_method'];
790
        $firstName = $user_param['firstname'];
791
        $lastName = $user_param['lastname'];
792
        $status = $user_param['status'];
793
        $email = $user_param['email'];
794
        $loginName = $user_param['loginname'];
795
        $official_code = $user_param['official_code'];
796
        $language = '';
797
        $phone = '';
798
        $picture_uri = '';
799
        $auth_source = PLATFORM_AUTH_SOURCE;
800
        $expiration_date = '';
801
        $active = 1;
802
        $hr_dept_id = 0;
803
        $extra = null;
804
        $original_user_id_name = $user_param['original_user_id_name'];
805
        $original_user_id_value = $user_param['original_user_id_value'];
806
        $orig_user_id_value[] = $user_param['original_user_id_value'];
807
        $extra_list = $user_param['extra'];
808
        $salt = '';
809
810
        if (!empty($_configuration['password_encryption'])) {
811
            if ($_configuration['password_encryption'] === $encrypt_method) {
812
                if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
813
                    $msg = "Encryption $encrypt_method is invalid";
814
                    $results[] = $msg;
815
                    continue;
816
                } elseif ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
817
                    $msg = "Encryption $encrypt_method is invalid";
818
                    $results[] = $msg;
819
                    continue;
820
                }
821
            } else {
822
                $msg = "This encryption $encrypt_method is not configured";
823
                $results[] = $msg;
824
                continue;
825
            }
826
        } else {
827
            $msg = 'The chamilo setting $_configuration["password_encryption"] is not configured';
828
            $results[] = $msg;
829
            continue;
830
        }
831
832
        if (is_array($extra_list) && count($extra_list) > 0) {
833
            foreach ($extra_list as $extra) {
834
                if ($extra['field_name'] == 'salt') {
835
                    $salt = $extra['field_value'];
836
                    break;
837
                }
838
            }
839
        }
840
841
        if (!empty($user_param['language'])) {
842
            $language = $user_param['language'];
843
        }
844
        if (!empty($user_param['phone'])) {
845
            $phone = $user_param['phone'];
846
        }
847
        if (!empty($user_param['expiration_date'])) {
848
            $expiration_date = $user_param['expiration_date'];
849
        }
850
851
        $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
852
853
        // Check whether x_user_id exists into user_field_values table.
854
        $sql = "SELECT value as field_value,item_id as user_id
855
                FROM $t_uf uf, $t_ufv ufv
856
                WHERE
857
                    uf.extra_field_type = $extraFieldType
858
                    ufv.field_id=uf.id AND
859
                    variable='$original_user_id_name' AND
860
                    value ='$original_user_id_value'";
861
        $res = Database::query($sql);
862
        $row = Database::fetch_row($res);
863
        $count_row = Database::num_rows($res);
864
        if ($count_row > 0) {
865
            // Check if user is not active.
866
            $sql = "SELECT user_id FROM $table_user 
867
                    WHERE user_id ='".$row[1]."' AND active= '0'";
868
            $resu = Database::query($sql);
869
            $r_check_user = Database::fetch_row($resu);
870
            $count_check_user = Database::num_rows($resu);
871
            if ($count_check_user > 0) {
872
                $sql = "UPDATE $table_user SET
873
                        lastname='".Database::escape_string($lastName)."',
874
                        firstname='".Database::escape_string($firstName)."',
875
                        username='".Database::escape_string($loginName)."',";
876
877
                if (!is_null($auth_source)) {
878
                    $sql .= " auth_source='".Database::escape_string($auth_source)."',";
879
                }
880
                $sql .= "
881
                        password='".Database::escape_string($password)."',
882
                        email='".Database::escape_string($email)."',
883
                        status='".Database::escape_string($status)."',
884
                        official_code='".Database::escape_string($official_code)."',
885
                        phone='".Database::escape_string($phone)."',
886
                        expiration_date='".Database::escape_string($expiration_date)."',
887
                        active='1',
888
                        hr_dept_id=".intval($hr_dept_id);
889
890
                $sql .= " WHERE user_id='".$r_check_user[0]."'";
891
                Database::query($sql);
892
893
                if (is_array($extra_list) && count($extra_list) > 0) {
894
                    foreach ($extra_list as $extra) {
895
                        $extra_field_name = $extra['field_name'];
896
                        $extra_field_value = $extra['field_value'];
897
                        // Save the external system's id into user_field_value table.
898
                        $res = UserManager::update_extra_field_value(
899
                            $r_check_user[0],
900
                            $extra_field_name,
901
                            $extra_field_value
902
                        );
903
                    }
904
                }
905
906
                $results[] = $r_check_user[0];
907
                continue;
908
            } else {
909
                $results[] = 0;
910
                continue; // User id already exits.
911
            }
912
        }
913
914
        // Default language.
915
        if (empty($language)) {
916
            $language = api_get_setting('platformLanguage');
917
        }
918
919
        $creator_id = DEFAULT_ADMIN_USER_ID;
920
921
        // First check wether the login already exists
922
        if (!UserManager::is_username_available($loginName)) {
923
            $results[] = 0;
924
            continue;
925
        }
926
927
        $sql = "INSERT INTO $table_user SET
928
                    lastname = '".Database::escape_string(trim($lastName))."',
929
                    firstname = '".Database::escape_string(trim($firstName))."',
930
                    username = '".Database::escape_string(trim($loginName))."',
931
                    status = '".Database::escape_string($status)."',
932
                    password = '".Database::escape_string($password)."',
933
                    email = '".Database::escape_string($email)."',
934
                    official_code    = '".Database::escape_string($official_code)."',
935
                    picture_uri     = '".Database::escape_string($picture_uri)."',
936
                    creator_id      = '".Database::escape_string($creator_id)."',
937
                    auth_source = '".Database::escape_string($auth_source)."',
938
                    phone = '".Database::escape_string($phone)."',
939
                    language = '".Database::escape_string($language)."',
940
                    registration_date = now(),
941
                    expiration_date = '".Database::escape_string($expiration_date)."',
942
                    hr_dept_id = '".Database::escape_string($hr_dept_id)."',
943
                    active = '".Database::escape_string($active)."'";
944
        $result = Database::query($sql);
945
        if ($result) {
946
            //echo "id returned";
947
            $return = Database::insert_id();
948
949
            $sql = "UPDATE $table_user SET user_id = id WHERE id = $return";
950
            Database::query($sql);
951
952
            if (api_is_multiple_url_enabled()) {
953
                if (api_get_current_access_url_id() != -1) {
954
                    UrlManager::add_user_to_url(
955
                        $return,
956
                        api_get_current_access_url_id()
957
                    );
958
                } else {
959
                    UrlManager::add_user_to_url($return, 1);
960
                }
961
            } else {
962
                // We add by default the access_url_user table with access_url_id = 1
963
                UrlManager::add_user_to_url($return, 1);
964
            }
965
            // Save new fieldlabel into user_field table.
966
            UserManager::create_extra_field(
967
                $original_user_id_name,
968
                1,
969
                $original_user_id_name,
970
                ''
971
            );
972
            // Save the remote system's id into user_field_value table.
973
            UserManager::update_extra_field_value(
974
                $return,
975
                $original_user_id_name,
976
                $original_user_id_value
977
            );
978
979
            if (is_array($extra_list) && count($extra_list) > 0) {
980
                foreach ($extra_list as $extra) {
981
                    $extra_field_name = $extra['field_name'];
982
                    $extra_field_value = $extra['field_value'];
983
                    // Save new fieldlabel into user_field table.
984
                    UserManager::create_extra_field(
985
                        $extra_field_name,
986
                        1,
987
                        $extra_field_name,
988
                        ''
989
                    );
990
                    // Save the external system's id into user_field_value table.
991
                    UserManager::update_extra_field_value(
992
                        $return,
993
                        $extra_field_name,
994
                        $extra_field_value
995
                    );
996
                }
997
            }
998
        } else {
999
            $results[] = 0;
1000
            continue;
1001
        }
1002
        $results[] = $return;
1003
    } // end principal foreach
1004
1005
    $count_results = count($results);
1006
    $output = [];
1007
    for ($i = 0; $i < $count_results; $i++) {
1008
        $output[] = [
1009
            'original_user_id_value' => $orig_user_id_value[$i],
1010
            'result' => $results[$i]
1011
        ];
1012
    }
1013
1014
    return $output;
1015
}
1016
1017
// Subscribe / Unsubscribe Teacher to Session Course
1018
// Prepare Input params for Subscribe Teacher to SC
1019
$server->wsdl->addComplexType(
1020
    'TeacherToSessionCourse',
1021
    'complexType',
1022
    'struct',
1023
    'all',
1024
    '',
1025
    [
1026
        'user_id' => ['name' => 'course', 'type' => 'xsd:string'], // Chamilo user Id
1027
        'session_id' => ['name' => 'user_id', 'type' => 'xsd:string'], // Current Session course ID
1028
        'course_id' =>['name' => 'courseId', 'type' => 'xsd:string'], // Course Real Id
1029
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
1030
        // optional
1031
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
1032
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
1033
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
1034
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
1035
        'original_session_id_name' => ['name' => 'original_session_id_name', 'type' => 'xsd:string'],
1036
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string']
1037
    ]
1038
);
1039
1040
/**
1041
 * @param array $params
1042
 * @return array
1043
 */
1044
function parseCourseSessionUserParams($params)
1045
{
1046
    global $debug;
1047
1048
    $userId = isset($params['user_id']) ? $params['user_id'] : 0; // Chamilo user Id
1049
    $sessionId = isset($params['session_id']) ? $params['session_id'] : 0; // Current Session course ID
1050
    $courseId = isset($params['course_id']) ? $params['course_id'] : 0; // Course Real Id
1051
1052
    if (empty($userId) && empty($sessionId) && empty($courseId)) {
1053
        // try original values
1054
        if ($debug) {
1055
            error_log('try original values');
1056
        }
1057
1058
        $userIdName = isset($params['original_user_id_name']) ? $params['original_user_id_name'] : 0;
1059
        $userIdValue = isset($params['original_user_id_value']) ? $params['original_user_id_value'] : 0;
1060
        $courseIdName = isset($params['original_course_id_name']) ? $params['original_course_id_name'] : 0;
1061
        $courseIdValue = isset($params['original_course_id_value']) ? $params['original_course_id_value'] : 0;
1062
        $sessionIdName = isset($params['original_session_id_name']) ? $params['original_session_id_name'] : 0;
1063
        $sessionIdValue = isset($params['original_session_id_value']) ? $params['original_session_id_value'] : 0;
1064
1065
        // Check if exits x_user_id into user_field_values table.
1066
        $userId = UserManager::get_user_id_from_original_id(
1067
            $userIdValue,
1068
            $userIdName
1069
        );
1070
1071
        // Check whether exits $x_course_code into user_field_values table.
1072
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
1073
            $courseIdValue,
1074
            $courseIdName
1075
        );
1076
1077
        $courseId = 0;
1078
        if ($courseInfo) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $courseInfo of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1079
            $courseId = $courseInfo['real_id'];
1080
        }
1081
1082
        $sessionId = SessionManager::getSessionIdFromOriginalId(
1083
            $sessionIdValue,
1084
            $sessionIdName
1085
        );
1086
    }
1087
1088
    if ($debug) {
1089
        error_log('$userId found: '.$userId);
1090
        error_log('$courseId found: '.$courseId);
1091
        error_log('$sessionId found: '.$sessionId);
1092
    }
1093
1094
    return [
1095
        'user_id' => $userId,
1096
        'course_id' => $courseId,
1097
        'session_id' => $sessionId,
1098
    ];
1099
}
1100
1101
$server->register(
1102
    'WSSubscribeTeacherToSessionCourse',
1103
    ['SubscribeTeacherToSessionCourse' => 'tns:TeacherToSessionCourse'],
1104
    ['return' => 'xsd:string'],
1105
    'urn:WSRegistration',
1106
    'urn:WSRegistration#WSSubscribeTeacherToSessionCourse',
1107
    'rpc',
1108
    'encoded',
1109
    'This webservice subscribe a teacher to a session course'
1110
);
1111
1112
/**
1113
 * Subscribe teacher to a session course
1114
 *
1115
 * @param array $params - WSFunction parameters (include VerifyKey)
1116
 * @return bool|null|soap_fault A simple boolean (true if teacher successful subscribed, false otherwise)
1117
 */
1118
function WSSubscribeTeacherToSessionCourse($params)
1119
{
1120
    global $debug;
1121
    if ($debug) {
1122
        error_log('WSSubscribeTeacherToSessionCourse');
1123
    }
1124
1125
    if (!WSHelperVerifyKey($params)) {
1126
        return returnError(WS_ERROR_SECRET_KEY);
1127
    }
1128
1129
    if ($debug) {
1130
        error_log('Params '.print_r($params, 1));
1131
    }
1132
1133
    $params = parseCourseSessionUserParams($params);
1134
1135
    $userId = $params['user_id'];
1136
    $courseId = $params['course_id'];
1137
    $sessionId = $params['session_id'];
1138
    SessionManager::set_coach_to_course_session($userId, $sessionId, $courseId);
1139
    $coaches = SessionManager::getCoachesByCourseSession($sessionId, $courseId);
1140
1141
    $result = 0;
1142
1143
    if (!empty($coaches)) {
1144
        if ($debug) {
1145
            error_log('Coaches:  '.print_r($coaches, 1));
1146
        }
1147
        if (in_array($userId, $coaches)) {
1148
            $result = 1;
1149
        }
1150
    }
1151
1152
    if ($debug) {
1153
        error_log('Result:  '.$result);
1154
    }
1155
1156
    return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result returns the type integer which is incompatible with the documented return type null|boolean|soap_fault.
Loading history...
1157
}
1158
1159
$server->register(
1160
    'WSUnsubscribeTeacherFromSessionCourse',
1161
    ['UnsubscribeTeacherFromSessionCourse' => 'tns:TeacherToSessionCourse'],
1162
    ['return' => 'xsd:string'],
1163
    'urn:WSRegistration',
1164
    'urn:WSRegistration#WSUnsubscribeTeacherFromSessionCourse',
1165
    'rpc',
1166
    'encoded',
1167
    'This webservice unsubscribe a teacher from a session course'
1168
);
1169
1170
/**
1171
 * Subscribe teacher to a session course
1172
 *
1173
 *  @param array $params - WSFunction parameters (include VerifyKey)
1174
 *  @return bool|null|soap_fault A simple boolean (true if teacher successful unsubscribed, false otherwise)
1175
 */
1176
function WSUnsubscribeTeacherFromSessionCourse($params)
1177
{
1178
    global $debug;
1179
1180
    if ($debug) {
1181
        error_log('WSSubscribeTeacherToSessionCourse');
1182
    }
1183
1184
    if (!WSHelperVerifyKey($params)) {
1185
        return returnError(WS_ERROR_SECRET_KEY);
1186
    }
1187
1188
    if ($debug) {
1189
        error_log('Params '.print_r($params, 1));
1190
    }
1191
1192
    $params = parseCourseSessionUserParams($params);
1193
1194
    $userId = $params['user_id'];
1195
    $courseId = $params['course_id'];
1196
    $sessionId = $params['session_id'];
1197
1198
    SessionManager::removeUsersFromCourseSession([$userId], $sessionId, $courseId);
1199
    $coaches = SessionManager::getCoachesByCourseSession($sessionId, $courseId);
1200
1201
    $result = 0;
1202
1203
    if (!empty($coaches)) {
1204
        if ($debug) {
1205
            error_log('Coaches:  '.print_r($coaches, 1));
1206
        }
1207
        if (!in_array($userId, $coaches)) {
1208
            $result = 1;
1209
        }
1210
    } else {
1211
        $result = 1;
1212
    }
1213
1214
    if ($debug) {
1215
        error_log('Final Result: '.$result);
1216
    }
1217
1218
    return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result returns the type integer which is incompatible with the documented return type null|boolean|soap_fault.
Loading history...
1219
}
1220
1221
/* Register WSCreateUserPasswordCrypted function */
1222
// Register the data structures used by the service
1223
1224
//prepare input params
1225
1226
// Input params for editing users
1227
$server->wsdl->addComplexType(
1228
    'createUserPasswordCrypted',
1229
    'complexType',
1230
    'struct',
1231
    'all',
1232
    '',
1233
    [
1234
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
1235
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
1236
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
1237
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
1238
        'loginname' => ['name' => 'loginname', 'type' => 'xsd:string'],
1239
        'password' => ['name' => 'password', 'type' => 'xsd:string'], //encripted password using the encrypt_method
1240
        'encrypt_method' => ['name' => 'encrypt_method', 'type' => 'xsd:string'],
1241
        'language' => ['name' => 'language', 'type' => 'xsd:string'],
1242
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
1243
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
1244
        'official_code' => ['name' => 'official_code', 'type' => 'xsd:string'],
1245
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
1246
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
1247
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList'],
1248
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
1249
    ]
1250
);
1251
1252
// Register the method to expose
1253
$server->register(
1254
    'WSCreateUserPasswordCrypted', // method name
1255
    ['createUserPasswordCrypted' => 'tns:createUserPasswordCrypted'], // input parameters
1256
    ['return' => 'xsd:string'], // output parameters
1257
    'urn:WSRegistration', // namespace
1258
    'urn:WSRegistration#WSCreateUserPasswordCrypted', // soapaction
1259
    'rpc', // style
1260
    'encoded', // use
1261
    'This service adds users'                                               // documentation
1262
);
1263
1264
// Define the method WSCreateUserPasswordCrypted
1265
function WSCreateUserPasswordCrypted($params)
1266
{
1267
    global $_configuration, $debug;
1268
    $debug = 1;
1269
    if ($debug) {
1270
        error_log('WSCreateUserPasswordCrypted');
1271
        error_log(print_r($params, 1));
1272
    }
1273
    if (!WSHelperVerifyKey($params)) {
1274
        return returnError(WS_ERROR_SECRET_KEY);
1275
    }
1276
1277
    // Database table definition.
1278
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1279
    $password = $params['password'];
1280
    $encrypt_method = $params['encrypt_method'];
1281
    $firstName = $params['firstname'];
1282
    $lastName = $params['lastname'];
1283
    $status = $params['status'];
1284
    $email = $params['email'];
1285
    $loginName = $params['loginname'];
1286
    $official_code = isset($params['official_code']) ? $params['official_code'] : '';
1287
    $language = '';
1288
    $phone = isset($params['phone']) ? $params['phone'] : '';
1289
    $picture_uri = '';
1290
    $auth_source = PLATFORM_AUTH_SOURCE;
1291
    $expiration_date = '';
1292
    $active = 1;
1293
    $hr_dept_id = 0;
1294
    $extra = null;
1295
    $original_user_id_name = $params['original_user_id_name'];
1296
    $original_user_id_value = $params['original_user_id_value'];
1297
    $extra_list = isset($params['extra']) ? $params['extra'] : '';
1298
1299
    if (!empty($_configuration['password_encryption'])) {
1300
        if ($_configuration['password_encryption'] === $encrypt_method) {
1301
            if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
1302
                $msg = "Encryption $encrypt_method is invalid";
1303
                if ($debug) {
1304
                    error_log($msg);
1305
                }
1306
                return $msg;
1307
            } elseif ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
1308
                $msg = "Encryption $encrypt_method is invalid";
1309
                if ($debug) {
1310
                    error_log($msg);
1311
                }
1312
                return $msg;
1313
            }
1314
        } else {
1315
            $msg = "This encryption $encrypt_method is not configured";
1316
            if ($debug) {
1317
                error_log($msg);
1318
            }
1319
            return $msg;
1320
        }
1321
    } else {
1322
        $msg = 'The chamilo setting $_configuration["password_encryption"] is not configured';
1323
        if ($debug) {
1324
            error_log($msg);
1325
        }
1326
        return $msg;
1327
    }
1328
1329
    if (!empty($params['language'])) {
1330
        $language = $params['language'];
1331
    }
1332
    if (!empty($params['phone'])) {
1333
        $phone = $params['phone'];
1334
    }
1335
    if (!empty($params['expiration_date'])) {
1336
        $expiration_date = $params['expiration_date'];
1337
    }
1338
1339
    // Check whether x_user_id exists into user_field_values table.
1340
    $user_id = UserManager::get_user_id_from_original_id(
1341
        $original_user_id_value,
1342
        $original_user_id_name
1343
    );
1344
1345
    if ($debug) {
1346
        error_log('Ready to create user');
1347
    }
1348
1349
    if ($user_id > 0) {
1350
        if ($debug) {
1351
            error_log('User found with id: '.$user_id);
1352
        }
1353
1354
        // Check whether user is not active
1355
        //@todo why this condition exists??
1356
        $sql = "SELECT user_id FROM $table_user
1357
                WHERE user_id ='".$user_id."' AND active= '0' ";
1358
        $resu = Database::query($sql);
1359
        $r_check_user = Database::fetch_row($resu);
1360
        $count_check_user = Database::num_rows($resu);
1361
        if ($count_check_user > 0) {
1362
            if ($debug) {
1363
                error_log('User id: '.$user_id.' exists and is NOT active. Updating user and setting setting active = 1');
1364
            }
1365
            $sql = "UPDATE $table_user SET
1366
                    lastname='".Database::escape_string($lastName)."',
1367
                    firstname='".Database::escape_string($firstName)."',
1368
                    username='".Database::escape_string($loginName)."',";
1369
1370
            if (!is_null($auth_source)) {
1371
                $sql .= " auth_source='".Database::escape_string($auth_source)."',";
1372
            }
1373
            $sql .= "
1374
                    password='".Database::escape_string($password)."',
1375
                    email='".Database::escape_string($email)."',
1376
                    status='".Database::escape_string($status)."',
1377
                    official_code='".Database::escape_string($official_code)."',
1378
                    phone='".Database::escape_string($phone)."',
1379
                    expiration_date='".Database::escape_string($expiration_date)."',
1380
                    active='1',
1381
                    hr_dept_id=".intval($hr_dept_id)." 
1382
                WHERE user_id='".$r_check_user[0]."'";
1383
1384
            Database::query($sql);
1385
1386
            if (is_array($extra_list) && count($extra_list) > 0) {
1387
                foreach ($extra_list as $extra) {
1388
                    $extra_field_name = $extra['field_name'];
1389
                    $extra_field_value = $extra['field_value'];
1390
                    // Save the external system's id into user_field_value table.
1391
                    UserManager::update_extra_field_value(
1392
                        $r_check_user[0],
1393
                        $extra_field_name,
1394
                        $extra_field_value
1395
                    );
1396
                }
1397
            }
1398
            return $r_check_user[0];
1399
        } else {
1400
            if ($debug) {
1401
                error_log('User exists but is active. Cant be updated');
1402
            }
1403
            return 0;
1404
        }
1405
    } else {
1406
        if ($debug) {
1407
            error_log(
1408
                "User not found with original_id = $original_user_id_value and original_name = $original_user_id_name"
1409
            );
1410
        }
1411
    }
1412
1413
    // Default language.
1414
    if (empty($language)) {
1415
        $language = api_get_setting('platformLanguage');
1416
    }
1417
1418
    $creator_id = DEFAULT_ADMIN_USER_ID;
1419
1420
    // First check wether the login already exists
1421
    if (!UserManager::is_username_available($loginName)) {
1422
        if ($debug) {
1423
            error_log("Username $loginName is not available");
1424
        }
1425
        return 0;
1426
    }
1427
1428
    $queryExpirationDate = '';
1429
    if (!empty($params['expiration_date'])) {
1430
        $queryExpirationDate = "expiration_date     = '".Database::escape_string($expiration_date)."', ";
1431
    }
1432
1433
    $sql = "INSERT INTO $table_user SET
1434
            lastname            = '".Database::escape_string(trim($lastName))."',
1435
            firstname           = '".Database::escape_string(trim($firstName))."',
1436
            username            = '".Database::escape_string(trim($loginName))."',
1437
            username_canonical  = '".Database::escape_string(api_strtolower(trim($loginName)))."',
1438
            status              = '".Database::escape_string($status)."',
1439
            password            = '".Database::escape_string($password)."',
1440
            email               = '".Database::escape_string($email)."',
1441
            official_code       = '".Database::escape_string($official_code)."',
1442
            picture_uri         = '".Database::escape_string($picture_uri)."',
1443
            creator_id          = '".Database::escape_string($creator_id)."',
1444
            auth_source         = '".Database::escape_string($auth_source)."',
1445
            phone               = '".Database::escape_string($phone)."',
1446
            language            = '".Database::escape_string($language)."',
1447
            registration_date   = '".api_get_utc_datetime()."',
1448
            roles = 'a:0:{}', 
1449
            ".$queryExpirationDate."
1450
            hr_dept_id          = '".Database::escape_string($hr_dept_id)."',
1451
            active              = '".Database::escape_string($active)."'";
1452
1453
    Database::query($sql);
1454
    $return = Database::insert_id();
1455
    if ($return) {
1456
        if ($debug) {
1457
            error_log("New user created. user_id = $return");
1458
        }
1459
        $sql = "UPDATE $table_user SET user_id = id WHERE id = $return";
1460
        Database::query($sql);
1461
1462
        $url_id = api_get_current_access_url_id();
1463
        UrlManager::add_user_to_url($return, $url_id);
1464
        if ($debug) {
1465
            error_log("Adding user_id = $return to URL id $url_id ");
1466
        }
1467
1468
        // Create extra field for the original_user_id_name
1469
        UserManager::create_extra_field(
1470
            $original_user_id_name,
1471
            1,
1472
            $original_user_id_name,
1473
            ''
1474
        );
1475
        // Save the remote system's id into user_field_value table.
1476
        UserManager::update_extra_field_value(
1477
            $return,
1478
            $original_user_id_name,
1479
            $original_user_id_value
1480
        );
1481
1482
        // Create extra fields
1483
        if (is_array($extra_list) && count($extra_list) > 0) {
1484
            foreach ($extra_list as $extra) {
1485
                $extra_field_name = $extra['field_name'];
1486
                $extra_field_value = $extra['field_value'];
1487
                // save new fieldlabel into user_field table
1488
                UserManager::create_extra_field(
1489
                    $extra_field_name,
1490
                    1,
1491
                    $extra_field_name,
1492
                    ''
1493
                );
1494
                // save the external system's id into user_field_value table'
1495
                UserManager::update_extra_field_value(
1496
                    $return,
1497
                    $extra_field_name,
1498
                    $extra_field_value
1499
                );
1500
            }
1501
        }
1502
    } else {
1503
        if ($debug) {
1504
            error_log('Error while inserting a user');
1505
        }
1506
1507
        return 0;
1508
    }
1509
    if ($debug) {
1510
        error_log("Return value: $return");
1511
    }
1512
    return $return;
1513
}
1514
1515
/* Register WSEditUsers function */
1516
// Register the data structures used by the service
1517
$server->wsdl->addComplexType(
1518
    'editUsersParams',
1519
    'complexType',
1520
    'struct',
1521
    'all',
1522
    '',
1523
    [
1524
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
1525
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
1526
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
1527
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
1528
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
1529
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
1530
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
1531
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
1532
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
1533
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
1534
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
1535
    ]
1536
);
1537
1538
$server->wsdl->addComplexType(
1539
    'editUsersParamsList',
1540
    'complexType',
1541
    'array',
1542
    '',
1543
    'SOAP-ENC:Array',
1544
    [],
1545
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:editUsersParams[]']],
1546
    'tns:editUsersParams'
1547
);
1548
1549
$server->wsdl->addComplexType(
1550
    'editUsers',
1551
    'complexType',
1552
    'struct',
1553
    'all',
1554
    '',
1555
    [
1556
        'users' => ['name' => 'users', 'type' => 'tns:editUsersParamsList'],
1557
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
1558
    ]
1559
);
1560
1561
/* Register WSEditUserCredentials function */
1562
// Register the data structures used by the service
1563
$server->wsdl->addComplexType(
1564
    'editUserCredentials',
1565
    'complexType',
1566
    'struct',
1567
    'all',
1568
    '',
1569
    [
1570
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
1571
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
1572
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
1573
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
1574
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string']
1575
    ]
1576
);
1577
1578
// Register the method to expose
1579
$server->register(
1580
    'WSEditUserCredentials', // method name
1581
    ['editUserCredentials' => 'tns:editUserCredentials'], // input parameters
1582
    ['return' => 'xsd:string'], // output parameters
1583
    'urn:WSRegistration', // namespace
1584
    'urn:WSRegistration#WSEditUserCredentials', // soapaction
1585
    'rpc', // style
1586
    'encoded', // use
1587
    'This service edits the username and password of a user'    // documentation
1588
);
1589
1590
/**
1591
 * Define the method WSEditUser
1592
 * @param array $params
1593
 * @return bool|int|null|soap_fault
1594
 * @throws \Doctrine\DBAL\DBALException
1595
 */
1596
function WSEditUserCredentials($params)
1597
{
1598
    if (!WSHelperVerifyKey($params)) {
1599
        return returnError(WS_ERROR_SECRET_KEY);
1600
    }
1601
1602
    $userManager = UserManager::getManager();
1603
    $userRepository = UserManager::getRepository();
1604
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1605
    $original_user_id_value = $params['original_user_id_value'];
1606
    $original_user_id_name = $params['original_user_id_name'];
1607
    $username = $params['username'];
1608
    $password = null;
1609
1610
    if (!empty($params['password'])) {
1611
        $password = $params['password'];
1612
    }
1613
1614
    // Get user id from the other system ID
1615
    $user_id = UserManager::get_user_id_from_original_id(
1616
        $original_user_id_value,
1617
        $original_user_id_name
1618
    );
1619
1620
    if ($user_id == 0) {
1621
        return 0;
1622
    } else {
1623
        $sql = "SELECT user_id FROM $table_user
1624
                WHERE user_id ='$user_id' AND active= '0'";
1625
        $resu = Database::query($sql);
1626
        $r_check_user = Database::fetch_row($resu);
1627
        if (!empty($r_check_user[0])) {
1628
            return 0;
1629
        }
1630
    }
1631
1632
    // Check whether username already exits.
1633
    $sql = "SELECT username FROM $table_user
1634
            WHERE username = '$username' AND user_id <> '$user_id'";
1635
    $res_un = Database::query($sql);
1636
    $r_username = Database::fetch_row($res_un);
1637
1638
    if (!empty($r_username[0])) {
1639
        return 0;
1640
    }
1641
1642
    /** @var User $user */
1643
    $user = $userRepository->find($user_id);
1644
    if ($user) {
1645
        $user->setUsername($username);
1646
        if (!is_null($password)) {
1647
            $user->setPlainPassword($password);
1648
        }
1649
1650
        $userManager->updateUser($user, true);
1651
1652
        return true;
1653
    }
1654
1655
    return false;
1656
}
1657
1658
// Prepare output params, in this case will return an array
1659
$server->wsdl->addComplexType(
1660
    'result_editUsers',
1661
    'complexType',
1662
    'struct',
1663
    'all',
1664
    '',
1665
    [
1666
        'original_user_id_value' => [
1667
            'name' => 'original_user_id_value',
1668
            'type' => 'xsd:string'
1669
        ],
1670
        'result' => ['name' => 'result', 'type' => 'xsd:string']
1671
    ]
1672
);
1673
1674
$server->wsdl->addComplexType(
1675
    'results_editUsers',
1676
    'complexType',
1677
    'array',
1678
    '',
1679
    'SOAP-ENC:Array',
1680
    [],
1681
    [
1682
        [
1683
            'ref' => 'SOAP-ENC:arrayType',
1684
            'wsdl:arrayType' => 'tns:result_editUsers[]'
1685
        ]
1686
    ],
1687
    'tns:result_editUsers'
1688
);
1689
1690
// Register the method to expose
1691
$server->register(
1692
    'WSEditUsers', // method name
1693
    ['editUsers' => 'tns:editUsers'], // input parameters
1694
    ['return' => 'tns:results_editUsers'], // output parameters
1695
    'urn:WSRegistration', // namespace
1696
    'urn:WSRegistration#WSEditUsers', // soapaction
1697
    'rpc', // style
1698
    'encoded', // use
1699
    'This service edits a user from wiener'     // documentation
1700
);
1701
1702
// Define the method WSEditUsers
1703
function WSEditUsers($params)
1704
{
1705
    if (!WSHelperVerifyKey($params)) {
1706
        return returnError(WS_ERROR_SECRET_KEY);
1707
    }
1708
1709
    $userManager = UserManager::getManager();
1710
    $userRepository = UserManager::getRepository();
1711
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1712
1713
    $users_params = $params['users'];
1714
    $results = [];
1715
    $orig_user_id_value = [];
1716
1717
    foreach ($users_params as $user_param) {
1718
        $original_user_id_value = $user_param['original_user_id_value'];
1719
        $original_user_id_name = $user_param['original_user_id_name'];
1720
        $orig_user_id_value[] = $original_user_id_value;
1721
        $firstname = $user_param['firstname'];
1722
        $lastname = $user_param['lastname'];
1723
        $username = $user_param['username'];
1724
        $password = null;
1725
        $auth_source = null;
1726
        $email = $user_param['email'];
1727
        $status = $user_param['status'];
1728
        $official_code = '';
1729
        $phone = $user_param['phone'];
1730
        $expiration_date = $user_param['expiration_date'];
1731
        $creator_id = null;
1732
        $hr_dept_id = 0;
1733
        $extra = null;
1734
        $extra_list = $user_param['extra'];
1735
1736
        if (!empty($user_param['password'])) {
1737
            $password = $user_param['password'];
1738
        }
1739
1740
        // Get user id
1741
        $user_id = UserManager::get_user_id_from_original_id(
1742
            $original_user_id_value,
1743
            $original_user_id_name
1744
        );
1745
1746
        if ($user_id == 0) {
1747
            $results[] = 0; // Original_user_id_value doesn't exist.
1748
            continue;
1749
        } else {
1750
            $sql = "SELECT user_id FROM $table_user
1751
                    WHERE user_id ='$user_id' AND active= '0'";
1752
            $resu = Database::query($sql);
1753
            $r_check_user = Database::fetch_row($resu);
1754
            if (!empty($r_check_user[0])) {
1755
                $results[] = 0; // user_id is not active.
1756
                continue;
1757
            }
1758
        }
1759
1760
        // Check whether username already exits.
1761
        $sql = "SELECT username FROM $table_user
1762
                WHERE username = '$username' AND user_id <> '$user_id'";
1763
        $res_un = Database::query($sql);
1764
        $r_username = Database::fetch_row($res_un);
1765
1766
        if (!empty($r_username[0])) {
1767
            $results[] = 0; // username already exits.
1768
            continue;
1769
        }
1770
        // Edit lastname and firstname only if not empty
1771
1772
        /** @var User $user */
1773
        $user = $userRepository->find($user_id);
1774
1775
        if (!empty($lastname)) {
1776
            $user->setLastname($lastname);
1777
        }
1778
        if (!empty($firstname)) {
1779
            $user->setFirstname($firstname);
1780
        }
1781
        $user->setUsername($username);
1782
        if (!is_null($password)) {
1783
            $user->setPlainPassword($password);
1784
        }
1785
        if (!is_null($auth_source)) {
1786
            $user->setAuthSource($auth_source);
1787
        }
1788
1789
        // Exception for admins in case no status is provided in WS call...
1790
        $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
1791
        $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
1792
        $resadmin = Database::query($sqladmin);
1793
        $is_admin = Database::num_rows($resadmin);
1794
1795
        if (empty($status)) {
1796
            $status = 5;
1797
        }
1798
1799
        if ($is_admin) {
1800
            $status = 1;
1801
        }
1802
1803
        if (!empty($expiration_date)) {
1804
            $expiration_date = new DateTime($expiration_date);
1805
        }
1806
1807
        $user
1808
            ->setEmail($email)
1809
            ->setStatus($status)
1810
            ->setOfficialCode($official_code)
1811
            ->setPhone($phone)
1812
            ->setExpirationDate($expiration_date)
1813
            ->setHrDeptId($hr_dept_id)
1814
            ->setActive(true);
1815
1816
        if (!is_null($creator_id)) {
1817
            $user->setCreatorId($creator_id);
1818
        }
1819
1820
        $userManager->updateUser($user, true);
1821
1822
        if (is_array($extra_list) && count($extra_list) > 0) {
1823
            foreach ($extra_list as $extra) {
1824
                $extra_field_name = $extra['field_name'];
1825
                $extra_field_value = $extra['field_value'];
1826
                // Save the external system's id into user_field_value table.
1827
                UserManager::update_extra_field_value(
1828
                    $user_id,
1829
                    $extra_field_name,
1830
                    $extra_field_value
1831
                );
1832
            }
1833
        }
1834
1835
        $results[] = $user->getId();
1836
        continue;
1837
    }
1838
1839
    $count_results = count($results);
1840
    $output = [];
1841
    for ($i = 0; $i < $count_results; $i++) {
1842
        $output[] = [
1843
            'original_user_id_value' => $orig_user_id_value[$i],
1844
            'result' => $results[$i],
1845
        ];
1846
    }
1847
1848
    return $output;
1849
}
1850
1851
/* Register WSEditUser function */
1852
// Register the data structures used by the service
1853
$server->wsdl->addComplexType(
1854
    'editUser',
1855
    'complexType',
1856
    'struct',
1857
    'all',
1858
    '',
1859
    [
1860
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
1861
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
1862
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
1863
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
1864
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
1865
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
1866
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
1867
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
1868
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
1869
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
1870
        'enable' => ['name' => 'enable', 'type' => 'xsd:boolean'],
1871
        'language' => ['name' => 'language', 'type' => 'xsd:string'],
1872
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList'],
1873
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
1874
    ]
1875
);
1876
1877
// Register the method to expose
1878
$server->register(
1879
    'WSEditUser', // method name
1880
    ['editUser' => 'tns:editUser'], // input parameters
1881
    ['return' => 'xsd:string'], // output parameters
1882
    'urn:WSRegistration', // namespace
1883
    'urn:WSRegistration#WSEditUser', // soapaction
1884
    'rpc', // style
1885
    'encoded', // use
1886
    'This service edits a user from wiener'  // documentation
1887
);
1888
1889
// Define the method WSEditUser
1890
function WSEditUser($params)
1891
{
1892
    if (!WSHelperVerifyKey($params)) {
1893
        return returnError(WS_ERROR_SECRET_KEY);
1894
    }
1895
1896
    $userManager = UserManager::getManager();
1897
    $userRepository = UserManager::getRepository();
1898
1899
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1900
1901
    $original_user_id_value = $params['original_user_id_value'];
1902
    $original_user_id_name = $params['original_user_id_name'];
1903
    $firstname = $params['firstname'];
1904
    $lastname = $params['lastname'];
1905
    $username = $params['username'];
1906
    $password = null;
1907
    $auth_source = null;
1908
    $email = $params['email'];
1909
    $status = $params['status'];
1910
    $official_code = '';
1911
    $phone = $params['phone'];
1912
    $picture_uri = '';
1913
    $expiration_date = $params['expiration_date'];
1914
    $enable = $params['enable'];
1915
    $language = $params['language'];
1916
    $creator_id = null;
1917
    $hr_dept_id = 0;
1918
    $extra = null;
1919
    $extra_list = $params['extra'];
1920
1921
    if (!empty($params['password'])) {
1922
        $password = $params['password'];
1923
    }
1924
1925
    // Get user id from id wiener
1926
    $user_id = UserManager::get_user_id_from_original_id(
1927
        $original_user_id_value,
1928
        $original_user_id_name
1929
    );
1930
1931
    if ($user_id == 0) {
1932
        return 0;
1933
    } elseif (empty($enable)) {
1934
        $sql = "SELECT user_id FROM $table_user
1935
                WHERE user_id ='$user_id' AND active= '0'";
1936
        $resu = Database::query($sql);
1937
        $r_check_user = Database::fetch_row($resu);
1938
        if (!empty($r_check_user[0])) {
1939
            return 0;
1940
        }
1941
    }
1942
1943
    // Check whether username already exits.
1944
    $sql = "SELECT username FROM $table_user
1945
            WHERE username = '$username' AND user_id <> '$user_id'";
1946
    $res_un = Database::query($sql);
1947
    $r_username = Database::fetch_row($res_un);
1948
1949
    if (!empty($r_username[0])) {
1950
        return 0;
1951
    }
1952
1953
    /** @var User $user */
1954
    $user = $userRepository->find($user_id);
1955
1956
    if (!empty($lastname)) {
1957
        $user->setLastname($lastname);
1958
    }
1959
    if (!empty($firstname)) {
1960
        $user->setFirstname($firstname);
1961
    }
1962
    $user->setUsername($username);
1963
    if (!is_null($password)) {
1964
        $user->setPlainPassword($password);
1965
    }
1966
    if (!is_null($auth_source)) {
1967
        $user->setAuthSource($auth_source);
1968
    }
1969
1970
    // Exception for admins in case no status is provided in WS call...
1971
    $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
1972
    $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
1973
    $resadmin = Database::query($sqladmin);
1974
    $is_admin = Database::num_rows($resadmin);
1975
1976
    if (empty($status)) {
1977
        $status = 5;
1978
    }
1979
1980
    if ($is_admin) {
1981
        $status = 1;
1982
    }
1983
1984
    if (!empty($expiration_date)) {
1985
        $expiration_date = new DateTime($expiration_date);
1986
        $user->setExpirationDate($expiration_date);
1987
    }
1988
    if (!empty($language)) {
1989
        $user->setLanguage($language);
1990
    }
1991
1992
    $user
1993
        ->setEmail($email)
1994
        ->setStatus($status)
1995
        ->setOfficialCode($official_code)
1996
        ->setPhone($phone)
1997
        ->setPictureUri($picture_uri)
1998
        ->setHrDeptId($hr_dept_id)
1999
        ->setActive(true);
2000
2001
    if (!is_null($creator_id)) {
2002
        $user->setCreatorId($creator_id);
2003
    }
2004
2005
    $userManager->updateUser($user, true);
2006
2007
    if (is_array($extra_list) && count($extra_list) > 0) {
2008
        foreach ($extra_list as $extra) {
2009
            $extra_field_name = $extra['field_name'];
2010
            $extra_field_value = $extra['field_value'];
2011
            // Save the external system's id into user_field_value table.
2012
            UserManager::update_extra_field_value(
2013
                $user_id,
2014
                $extra_field_name,
2015
                $extra_field_value
2016
            );
2017
        }
2018
    }
2019
2020
    return  $user_id;
2021
}
2022
2023
/* Register WSEditUserWithPicture function */
2024
// Register the data structures used by the service
2025
$server->wsdl->addComplexType(
2026
    'editUserWithPicture',
2027
    'complexType',
2028
    'struct',
2029
    'all',
2030
    '',
2031
    [
2032
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2033
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
2034
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
2035
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
2036
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
2037
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
2038
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
2039
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
2040
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
2041
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
2042
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList'],
2043
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
2044
        'picture_url' => ['name' => 'picture_url', 'type' => 'xsd:string']
2045
    ]
2046
);
2047
2048
// Register the method to expose
2049
$server->register(
2050
    'WSEditUserWithPicture', // method name
2051
    ['editUserWithPicture' => 'tns:editUserWithPicture'], // input parameters
2052
    ['return' => 'xsd:string'], // output parameters
2053
    'urn:WSRegistration', // namespace
2054
    'urn:WSRegistration#WSEditUserWithPicture', // soapaction
2055
    'rpc', // style
2056
    'encoded', // use
2057
    'This service edits a user from wiener'             // documentation
2058
);
2059
2060
// Define the method WSEditUserWithPicture
2061
function WSEditUserWithPicture($params)
2062
{
2063
    if (!WSHelperVerifyKey($params)) {
2064
        return returnError(WS_ERROR_SECRET_KEY);
2065
    }
2066
2067
    $userManager = UserManager::getManager();
2068
    $userRepository = UserManager::getRepository();
2069
2070
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
2071
2072
    $original_user_id_value = $params['original_user_id_value'];
2073
    $original_user_id_name = $params['original_user_id_name'];
2074
    $firstname = $params['firstname'];
2075
    $lastname = $params['lastname'];
2076
    $username = $params['username'];
2077
    $password = null;
2078
    $auth_source = null;
2079
    $email = $params['email'];
2080
    $expiration_date = null;
2081
    $status = $params['status'];
2082
    $phone = $params['phone'];
2083
    $picture_url = $params['picture_url'];
2084
    $pictureUri = '';
2085
    $creator_id = null;
2086
    $hr_dept_id = 0;
2087
    $extra = null;
2088
    $extra_list = $params['extra'];
2089
    if (!empty($params['expiration_date'])) {
2090
        $expiration_date = $params['expiration_date'];
2091
    }
2092
2093
    if (!empty($params['password'])) {
2094
        $password = $params['password'];
2095
    }
2096
2097
    // Get user id from external id
2098
    $user_id = UserManager::get_user_id_from_original_id(
2099
        $original_user_id_value,
2100
        $original_user_id_name
2101
    );
2102
2103
    // Get picture and generate uri.
2104
    $filename = basename($picture_url);
2105
    $tempDir = api_get_path(SYS_ARCHIVE_PATH);
2106
    // Make sure the file download was OK by checking the HTTP headers for OK
2107
    if (strpos(get_headers($picture_url)[0], "OK")) {
2108
        file_put_contents($tempDir.$filename, file_get_contents($picture_url));
2109
        $pictureUri = UserManager::update_user_picture($user_id, $filename, $tempDir.$filename);
2110
    }
2111
2112
    if ($user_id == 0) {
2113
        return 0;
2114
    } else {
2115
        $sql = "SELECT id FROM $table_user WHERE id =$user_id AND active= 0";
2116
        $resu = Database::query($sql);
2117
        $r_check_user = Database::fetch_row($resu);
2118
        if (!empty($r_check_user[0])) {
2119
            return 0;
2120
        }
2121
    }
2122
2123
    // Check whether username already exits.
2124
    $sql = "SELECT username FROM $table_user 
2125
            WHERE username = '$username' AND id <> $user_id";
2126
    $res_un = Database::query($sql);
2127
    $r_username = Database::fetch_row($res_un);
2128
2129
    if (!empty($r_username[0])) {
2130
        return 0;
2131
    }
2132
2133
    /** @var User $user */
2134
    $user = $userRepository->find($user_id);
2135
2136
    if (!empty($lastname)) {
2137
        $user->setLastname($lastname);
2138
    }
2139
    if (!empty($firstname)) {
2140
        $user->setFirstname($firstname);
2141
    }
2142
    $user->setUsername($username);
2143
    if (!is_null($password)) {
2144
        $user->setPlainPassword($password);
2145
    }
2146
    if (!is_null($auth_source)) {
2147
        $user->setAuthSource($auth_source);
2148
    }
2149
2150
    // Exception for admins in case no status is provided in WS call...
2151
    $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
2152
    $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
2153
    $resadmin = Database::query($sqladmin);
2154
    $is_admin = Database::num_rows($resadmin);
2155
2156
    if (empty($status)) {
2157
        $status = $user->getStatus();
2158
    }
2159
2160
    if ($is_admin) {
2161
        $status = 1;
2162
    }
2163
2164
    if (!empty($expiration_date)) {
2165
        $expiration_date = new DateTime($expiration_date);
2166
    }
2167
2168
    $user
2169
        ->setEmail($email)
2170
        ->setStatus($status)
2171
        ->setPhone($phone)
2172
        ->setExpirationDate($expiration_date)
2173
        ->setHrDeptId($hr_dept_id)
2174
        ->setActive(true)
2175
        ->setPictureUri($pictureUri);
2176
2177
    if (!is_null($creator_id)) {
2178
        $user->setCreatorId($creator_id);
2179
    }
2180
2181
    $userManager->updateUser($user, true);
2182
2183
    if (is_array($extra_list) && count($extra_list) > 0) {
2184
        foreach ($extra_list as $extra) {
2185
            $extra_field_name = $extra['field_name'];
2186
            $extra_field_value = $extra['field_value'];
2187
            // Save the external system's id into user_field_value table.
2188
            UserManager::update_extra_field_value(
2189
                $user_id,
2190
                $extra_field_name,
2191
                $extra_field_value
2192
            );
2193
        }
2194
    }
2195
2196
    return $user_id;
2197
}
2198
2199
/* Register WSEditUsersPasswordCrypted function */
2200
// Register the data structures used by the service
2201
$server->wsdl->addComplexType(
2202
    'editUsersPasswordCryptedParams',
2203
    'complexType',
2204
    'struct',
2205
    'all',
2206
    '',
2207
    [
2208
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2209
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
2210
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
2211
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
2212
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
2213
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
2214
        'encrypt_method' => ['name' => 'encrypt_method', 'type' => 'xsd:string'],
2215
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
2216
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
2217
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
2218
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
2219
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
2220
    ]
2221
);
2222
2223
$server->wsdl->addComplexType(
2224
    'editUsersPasswordCryptedParamsList',
2225
    'complexType',
2226
    'array',
2227
    '',
2228
    'SOAP-ENC:Array',
2229
    [],
2230
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:editUsersPasswordCryptedParams[]']],
2231
    'tns:editUsersPasswordCryptedParams'
2232
);
2233
2234
$server->wsdl->addComplexType(
2235
    'editUsersPasswordCrypted',
2236
    'complexType',
2237
    'struct',
2238
    'all',
2239
    '',
2240
    [
2241
        'users' => ['name' => 'users', 'type' => 'tns:editUsersPasswordCryptedParamsList'],
2242
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
2243
    ]
2244
);
2245
2246
// Prepare output params, in this case will return an array
2247
$server->wsdl->addComplexType(
2248
    'result_editUsersPasswordCrypted',
2249
    'complexType',
2250
    'struct',
2251
    'all',
2252
    '',
2253
    [
2254
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2255
        'result' => ['name' => 'result', 'type' => 'xsd:string']
2256
    ]
2257
);
2258
2259
$server->wsdl->addComplexType(
2260
    'results_editUsersPasswordCrypted',
2261
    'complexType',
2262
    'array',
2263
    '',
2264
    'SOAP-ENC:Array',
2265
    [],
2266
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_editUsersPasswordCrypted[]']],
2267
    'tns:result_editUsersPasswordCrypted'
2268
);
2269
2270
// Register the method to expose
2271
$server->register(
2272
    'WSEditUsersPasswordCrypted', // method name
2273
    ['editUsersPasswordCrypted' => 'tns:editUsersPasswordCrypted'], // input parameters
2274
    ['return' => 'tns:results_editUsersPasswordCrypted'], // output parameters
2275
    'urn:WSRegistration', // namespace
2276
    'urn:WSRegistration#WSEditUsersPasswordCrypted', // soapaction
2277
    'rpc', // style
2278
    'encoded', // use
2279
    'This service edits a user'                                           // documentation
2280
);
2281
2282
// Define the method WSEditUsersPasswordCrypted
2283
function WSEditUsersPasswordCrypted($params)
2284
{
2285
    global $_configuration;
2286
2287
    if (!WSHelperVerifyKey($params)) {
2288
        return returnError(WS_ERROR_SECRET_KEY);
2289
    }
2290
2291
    // get user id from id of remote system
2292
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
2293
    $users_params = $params['users'];
2294
    $results = [];
2295
    $orig_user_id_value = [];
2296
2297
    foreach ($users_params as $user_param) {
2298
        $original_user_id_value = $user_param['original_user_id_value'];
2299
        $original_user_id_name = $user_param['original_user_id_name'];
2300
        $orig_user_id_value[] = $original_user_id_value;
2301
        $firstname = $user_param['firstname'];
2302
        $lastname = $user_param['lastname'];
2303
        $username = $user_param['username'];
2304
        $password = null;
2305
        $auth_source = null;
2306
        $email = $user_param['email'];
2307
        $status = $user_param['status'];
2308
        $official_code = '';
2309
        $phone = $user_param['phone'];
2310
        $picture_uri = '';
2311
        $expiration_date = $user_param['expiration_date'];
2312
        $active = 1;
2313
        $creator_id = null;
2314
        $hr_dept_id = 0;
2315
        $extra = null;
2316
        $extra_list = $user_param['extra'];
2317
2318
        if (!empty($user_param['password']) && !empty($user_param['encrypt_method'])) {
2319
            $password = $user_param['password'];
2320
            $encrypt_method = $user_param['encrypt_method'];
2321
            if ($_configuration['password_encryption'] === $encrypt_method) {
2322
                if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
2323
                    $msg = "Encryption $encrypt_method is invalid";
2324
                    $results[] = $msg;
2325
                    continue;
2326
                } elseif ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
2327
                    $msg = "Encryption $encrypt_method is invalid";
2328
                    $results[] = $msg;
2329
                    continue;
2330
                }
2331
            } else {
2332
                $msg = "This encryption $encrypt_method is not configured";
2333
                $results[] = $msg;
2334
                continue;
2335
            }
2336
        } elseif (!empty($user_param['password']) && empty($user_param['encrypt_method'])) {
2337
            $msg = "If password is not empty the encrypt_method param is required ";
2338
            $results[] = $msg;
2339
            continue;
2340
        } elseif (empty($user_param['password']) && !empty($user_param['encrypt_method'])) {
2341
            $msg = "If encrypt_method is not empty the password param is required ";
2342
            $results[] = $msg;
2343
            continue;
2344
        }
2345
2346
        $user_id = UserManager::get_user_id_from_original_id(
2347
            $original_user_id_value,
2348
            $original_user_id_name
2349
        );
2350
2351
        if ($user_id == 0) {
2352
            $results[] = 0; // Original_user_id_value doesn't exist.
2353
            continue;
2354
        } else {
2355
            $sql = "SELECT user_id FROM $table_user
2356
                    WHERE user_id ='$user_id' AND active= '0'";
2357
            $resu = Database::query($sql);
2358
            $r_check_user = Database::fetch_row($resu);
2359
            if (!empty($r_check_user[0])) {
2360
                $results[] = 0; // user_id is not active
2361
                continue;
2362
            }
2363
        }
2364
2365
        // Check if username already exits.
2366
        $sql = "SELECT username FROM $table_user
2367
                WHERE username ='$username' AND user_id <> '$user_id'";
2368
        $res_un = Database::query($sql);
2369
        $r_username = Database::fetch_row($res_un);
2370
2371
        if (!empty($r_username[0])) {
2372
            $results[] = 0;
2373
            continue; // username already exits
2374
        }
2375
2376
        $sql = "UPDATE $table_user SET ";
2377
        if (!empty($lastname)) {
2378
            $sql .= " lastname='".Database::escape_string($lastname)."', ";
2379
        }
2380
        if (!empty($firstname)) {
2381
            $sql .= " firstname='".Database::escape_string($firstname)."', ";
2382
        }
2383
        $sql .= " username='".Database::escape_string($username)."',";
2384
        if (!is_null($password)) {
2385
            $sql .= " password='".Database::escape_string($password)."',";
2386
        }
2387
        if (!is_null($auth_source)) {
2388
            $sql .= " auth_source='".Database::escape_string($auth_source)."',";
2389
        }
2390
2391
        // Exception for admins in case no status is provided in WS call...
2392
        $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
2393
        $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
2394
        $resadmin = Database::query($sqladmin);
2395
        $is_admin = Database::num_rows($resadmin);
2396
2397
        if (empty($status)) {
2398
            $status = 5;
2399
        }
2400
2401
        if ($is_admin) {
2402
            $status = 1;
2403
        }
2404
2405
        $sql .= "
2406
                email='".Database::escape_string($email)."',
2407
                status='".Database::escape_string($status)."',
2408
                official_code='".Database::escape_string($official_code)."',
2409
                phone='".Database::escape_string($phone)."',
2410
                picture_uri='".Database::escape_string($picture_uri)."',
2411
                expiration_date='".Database::escape_string($expiration_date)."',
2412
                active='".Database::escape_string($active)."',
2413
                hr_dept_id=".intval($hr_dept_id);
2414
2415
        if (!is_null($creator_id)) {
2416
            $sql .= ", creator_id='".Database::escape_string($creator_id)."'";
2417
        }
2418
        $sql .= " WHERE user_id='$user_id'";
2419
        $return = @Database::query($sql);
2420
2421
        if (is_array($extra_list) && count($extra_list) > 0) {
2422
            foreach ($extra_list as $extra) {
2423
                $extra_field_name = $extra['field_name'];
2424
                $extra_field_value = $extra['field_value'];
2425
                // Save the external system's id into user_field_value table.
2426
                UserManager::update_extra_field_value(
2427
                    $user_id,
2428
                    $extra_field_name,
2429
                    $extra_field_value
2430
                );
2431
            }
2432
        }
2433
2434
        $results[] = $return;
2435
        continue;
2436
    } //end principal foreach
2437
2438
    $count_results = count($results);
2439
    $output = [];
2440
    for ($i = 0; $i < $count_results; $i++) {
2441
        $output[] = [
2442
            'original_user_id_value' => $orig_user_id_value[$i],
2443
            'result' => $results[$i]
2444
        ];
2445
    }
2446
2447
    return $output;
2448
}
2449
2450
/* Register WSEditUserPasswordCrypted function */
2451
// Register the data structures used by the service
2452
$server->wsdl->addComplexType(
2453
    'editUserPasswordCrypted',
2454
    'complexType',
2455
    'struct',
2456
    'all',
2457
    '',
2458
    [
2459
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2460
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
2461
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
2462
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
2463
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
2464
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
2465
        'encrypt_method' => ['name' => 'encrypt_method', 'type' => 'xsd:string'],
2466
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
2467
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
2468
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
2469
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
2470
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList'],
2471
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
2472
    ]
2473
);
2474
2475
// Register the method to expose
2476
$server->register(
2477
    'WSEditUserPasswordCrypted', // method name
2478
    ['editUserPasswordCrypted' => 'tns:editUserPasswordCrypted'], // input parameters
2479
    ['return' => 'xsd:string'], // output parameters
2480
    'urn:WSRegistration', // namespace
2481
    'urn:WSRegistration#WSEditUserPasswordCrypted', // soapaction
2482
    'rpc', // style
2483
    'encoded', // use
2484
    'This service edits a user'                                        // documentation
2485
);
2486
2487
// Define the method WSEditUserPasswordCrypted
2488
function WSEditUserPasswordCrypted($params)
2489
{
2490
    global $_configuration, $debug;
2491
    if (!WSHelperVerifyKey($params)) {
2492
        return returnError(WS_ERROR_SECRET_KEY);
2493
    }
2494
2495
    if ($debug) {
2496
        error_log('WSEditUserPasswordCrypted');
2497
    }
2498
2499
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
2500
2501
    $original_user_id_value = $params['original_user_id_value'];
2502
    $original_user_id_name = $params['original_user_id_name'];
2503
2504
    $firstname = isset($params['firstname']) ? $params['firstname'] : '';
2505
    $lastname = isset($params['lastname']) ? $params['lastname'] : '';
2506
    $username = isset($params['username']) ? $params['username'] : '';
2507
    $password = null;
2508
    $auth_source = null;
2509
    $email = isset($params['email']) ? $params['email'] : '';
2510
    $status = isset($params['status']) ? $params['status'] : '';
2511
    $official_code = '';
2512
    $phone = isset($params['phone']) ? $params['phone'] : '';
2513
    $picture_uri = '';
2514
    $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : '';
2515
    $active = 1;
2516
    $creator_id = null;
2517
    $hr_dept_id = 0;
2518
    $extra = null;
2519
    $extra_list = isset($params['extra']) ? $params['extra'] : '';
2520
    $params['password'] = isset($params['password']) ? $params['password'] : '';
2521
    $params['encrypt_method'] = isset($params['encrypt_method']) ? $params['encrypt_method'] : '';
2522
2523
    if (!empty($params['password']) && !empty($params['encrypt_method'])) {
2524
        $password = $params['password'];
2525
        $encrypt_method = $params['encrypt_method'];
2526
        if ($_configuration['password_encryption'] === $encrypt_method) {
2527
            if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
2528
                $msg = "Encryption $encrypt_method is invalid";
2529
                return $msg;
2530
            } elseif ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
2531
                $msg = "Encryption $encrypt_method is invalid";
2532
                return $msg;
2533
            }
2534
        } else {
2535
            $msg = "This encryption $encrypt_method is not configured";
2536
            return $msg;
2537
        }
2538
    } elseif (!empty($params['password']) && empty($params['encrypt_method'])) {
2539
        $msg = "If password is not empty the encrypt_method param is required ";
2540
2541
        return $msg;
2542
    } elseif (empty($params['password']) && !empty($params['encrypt_method'])) {
2543
        $msg = "If encrypt_method is not empty the password param is required ";
2544
2545
        return $msg;
2546
    }
2547
2548
    $user_id = UserManager::get_user_id_from_original_id(
2549
        $original_user_id_value,
2550
        $original_user_id_name
2551
    );
2552
2553
    if ($debug) {
2554
        error_log("user: $user_id");
2555
    }
2556
2557
    if ($user_id == 0) {
2558
        return 0;
2559
    } else {
2560
        $sql = "SELECT user_id FROM $table_user
2561
                WHERE user_id ='$user_id' AND active= '0'";
2562
        $resu = Database::query($sql);
2563
        $r_check_user = Database::fetch_row($resu);
2564
        if (!empty($r_check_user[0])) {
2565
            return 0;
2566
        }
2567
    }
2568
2569
    // Check whether username already exits.
2570
    $sql = "SELECT username FROM $table_user
2571
            WHERE username ='$username' AND user_id <> '$user_id'";
2572
    $res_un = Database::query($sql);
2573
    $r_username = Database::fetch_row($res_un);
2574
2575
    if (!empty($r_username[0])) {
2576
        return 0;
2577
    }
2578
    // Edit lastname and firstname only if not empty
2579
    $sql = "UPDATE $table_user SET ";
2580
    if (!empty($lastname)) {
2581
        $sql .= " lastname='".Database::escape_string($lastname)."', ";
2582
    }
2583
    if (!empty($firstname)) {
2584
        $sql .= " firstname='".Database::escape_string($firstname)."', ";
2585
    }
2586
    $sql .= " username='".Database::escape_string($username)."',";
2587
2588
    if (!empty($password)) {
2589
        $sql .= " password='".Database::escape_string($password)."',";
2590
    }
2591
2592
    if (!empty($auth_source)) {
2593
        $sql .= " auth_source='".Database::escape_string($auth_source)."',";
2594
    }
2595
2596
    // Exception for admins in case no status is provided in WS call...
2597
    $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
2598
    $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
2599
    $resadmin = Database::query($sqladmin);
2600
    $is_admin = Database::num_rows($resadmin);
2601
2602
    if (empty($status)) {
2603
        $status = 5;
2604
    }
2605
2606
    if ($is_admin) {
2607
        $status = 1;
2608
    }
2609
2610
    $sql .= "
2611
            email='".Database::escape_string($email)."',
2612
            status='".Database::escape_string($status)."',
2613
            official_code='".Database::escape_string($official_code)."',
2614
            phone='".Database::escape_string($phone)."',
2615
            picture_uri='".Database::escape_string($picture_uri)."',
2616
            expiration_date='".Database::escape_string($expiration_date)."',
2617
            active='".Database::escape_string($active)."',
2618
            hr_dept_id=".intval($hr_dept_id);
2619
2620
    if (!is_null($creator_id)) {
2621
        $sql .= ", creator_id='".Database::escape_string($creator_id)."'";
2622
    }
2623
2624
    $sql .= " WHERE user_id='$user_id'";
2625
    $return = @Database::query($sql);
2626
2627
    if ($debug) {
2628
        error_log("SQL: $sql");
2629
    }
2630
2631
    if (is_array($extra_list) && count($extra_list) > 0) {
2632
        foreach ($extra_list as $extra) {
2633
            $extra_field_name = $extra['field_name'];
2634
            $extra_field_value = $extra['field_value'];
2635
            // save the external system's id into user_field_value table'
2636
            UserManager::update_extra_field_value(
2637
                $user_id,
2638
                $extra_field_name,
2639
                $extra_field_value
2640
            );
2641
        }
2642
    }
2643
2644
    if ($return) {
2645
        return 1;
2646
    }
2647
2648
    return 0;
2649
}
2650
2651
// Prepare output params for actions on users (delete, disable, enable), will return an array
2652
$server->wsdl->addComplexType(
2653
    'result_actionUsers',
2654
    'complexType',
2655
    'struct',
2656
    'all',
2657
    '',
2658
    [
2659
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2660
        'result' => ['name' => 'result', 'type' => 'xsd:string']
2661
    ]
2662
);
2663
2664
$server->wsdl->addComplexType(
2665
    'results_actionUsers',
2666
    'complexType',
2667
    'array',
2668
    '',
2669
    'SOAP-ENC:Array',
2670
    [],
2671
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_actionUsers[]']],
2672
    'tns:result_actionUsers'
2673
);
2674
2675
/** WSDeleteUsers **/
2676
$server->wsdl->addComplexType(
2677
    'user_id',
2678
    'complexType',
2679
    'struct',
2680
    'all',
2681
    '',
2682
    [
2683
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2684
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string']
2685
    ]
2686
);
2687
2688
$server->wsdl->addComplexType(
2689
    'user_ids_array',
2690
    'complexType',
2691
    'array',
2692
    '',
2693
    'SOAP-ENC:Array',
2694
    [],
2695
    [
2696
        [
2697
            'ref' => 'SOAP-ENC:arrayType',
2698
            'wsdl:arrayType' => 'tns:user_id[]',
2699
        ],
2700
    ],
2701
    'tns:user_id'
2702
);
2703
2704
$server->wsdl->addComplexType(
2705
    'user_ids',
2706
    'complexType',
2707
    'struct',
2708
    'all',
2709
    '',
2710
    [
2711
        'ids' => ['name' => 'user_ids', 'type' => 'tns:user_ids_array'],
2712
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
2713
    ]
2714
);
2715
2716
function WSHelperActionOnUsers($params, $type)
2717
{
2718
    $debug = 1;
2719
    if ($debug) {
2720
        error_log("WSHelperActionOnUsers");
2721
        error_log(print_r($params, 1));
2722
    }
2723
2724
    if (!WSHelperVerifyKey($params)) {
2725
        return returnError(WS_ERROR_SECRET_KEY);
2726
    }
2727
2728
    $results = [];
2729
    $orig_user_id_value = [];
2730
    $original_user_ids = $params['ids'];
2731
    foreach ($original_user_ids as $original_user_id) {
2732
        $result = false;
2733
        $orig_user_id_value[] = $original_user_id['original_user_id_value'];
2734
        $user_id = UserManager::get_user_id_from_original_id(
2735
            $original_user_id['original_user_id_value'],
2736
            $original_user_id['original_user_id_name']
2737
        );
2738
        if ($user_id > 0) {
2739
            if ($debug) {
2740
                error_log("User found: $user_id");
2741
            }
2742
            if ($type == 'delete') {
2743
                $result = UserManager::delete_user($user_id);
2744
            } elseif ($type == "disable") {
2745
                $result = UserManager::disable($user_id);
2746
            } elseif ($type == "enable") {
2747
                $result = UserManager::enable($user_id);
2748
            }
2749
        } else {
2750
            if ($debug) {
2751
                error_log("User id not found: $user_id");
2752
            }
2753
        }
2754
        $results[] = $result ? 1 : 0;
2755
    }
2756
2757
    $count_results = count($results);
2758
    $output = [];
2759
    for ($i = 0; $i < $count_results; $i++) {
2760
        $output[] = [
2761
            'original_user_id_value' => $orig_user_id_value[$i],
2762
            'result' => $results[$i]
2763
        ];
2764
    }
2765
2766
    return $output;
2767
}
2768
2769
$server->register(
2770
    'WSDeleteUsers', // method name
2771
    ['user_ids' => 'tns:user_ids'], // input parameters
2772
    ['return' => 'tns:results_actionUsers'], // output parameters
2773
    'urn:WSRegistration', // namespace
2774
    'urn:WSRegistration#WSDeleteUsers', // soapaction
2775
    'rpc', // style
2776
    'encoded', // use
2777
    'Deletes users provided as parameters from the system' // documentation
2778
);
2779
2780
function WSDeleteUsers($params)
2781
{
2782
    return WSHelperActionOnUsers($params, 'delete');
2783
}
2784
2785
/** WSDisableUsers **/
2786
$server->register(
2787
    'WSDisableUsers', // method name
2788
    ['user_ids' => 'tns:user_ids'], // input parameters
2789
    ['return' => 'tns:results_actionUsers'], // output parameters
2790
    'urn:WSRegistration', // namespace
2791
    'urn:WSRegistration#WSDisableUsers', // soapaction
2792
    'rpc', // style
2793
    'encoded', // use
2794
    'Disables users provided as parameters from the system' // documentation
2795
);
2796
2797
function WSDisableUsers($params)
2798
{
2799
    return WSHelperActionOnUsers($params, "disable");
2800
}
2801
2802
/** WSEnableUsers **/
2803
$server->register(
2804
    'WSEnableUsers', // method name
2805
    ['user_ids' => 'tns:user_ids'], // input parameters
2806
    ['return' => 'tns:results_actionUsers'], // output parameters
2807
    'urn:WSRegistration', // namespace
2808
    'urn:WSRegistration#WSEnableUsers', // soapaction
2809
    'rpc', // style
2810
    'encoded', // use
2811
    'Enables users provided as parameters'    // documentation
2812
);
2813
2814
function WSEnableUsers($params)
2815
{
2816
    return WSHelperActionOnUsers($params, "enable");
2817
}
2818
2819
/* Register WSCreateCourse function */
2820
// Register the data structures used by the service
2821
2822
$server->wsdl->addComplexType(
2823
    'course_id',
2824
    'complexType',
2825
    'struct',
2826
    'all',
2827
    '',
2828
    [
2829
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
2830
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string']
2831
    ]
2832
);
2833
2834
$server->wsdl->addComplexType(
2835
    'createCourseParams',
2836
    'complexType',
2837
    'struct',
2838
    'all',
2839
    '',
2840
    [
2841
        'title' => ['name' => 'title', 'type' => 'xsd:string'],
2842
        'category_code' => ['name' => 'category_code', 'type' => 'xsd:string'],
2843
        'wanted_code' => ['name' => 'wanted_code', 'type' => 'xsd:string'],
2844
        'tutor_name' => ['name' => 'tutor_name', 'type' => 'xsd:string'],
2845
        'course_language' => ['name' => 'course_language', 'type' => 'xsd:string'],
2846
        'disk_quota' => ['name' => 'disk_quota', 'type' => 'xsd:string'], // disk_quota in MB
2847
        'subscribe' => ['name' => 'subscribe', 'type' => 'xsd:string'],
2848
        'unsubscribe' => ['name' => 'unsubscribe', 'type' => 'xsd:string'],
2849
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
2850
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
2851
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
2852
    ]
2853
);
2854
2855
$server->wsdl->addComplexType(
2856
    'createCourseParamsList',
2857
    'complexType',
2858
    'array',
2859
    '',
2860
    'SOAP-ENC:Array',
2861
    [],
2862
    [
2863
        [
2864
            'ref' => 'SOAP-ENC:arrayType',
2865
            'wsdl:arrayType' => 'tns:createCourseParams[]',
2866
        ],
2867
    ],
2868
    'tns:createCourseParams'
2869
);
2870
2871
// Register the data structures used by the service
2872
$server->wsdl->addComplexType(
2873
    'createCourse',
2874
    'complexType',
2875
    'struct',
2876
    'all',
2877
    '',
2878
    [
2879
        'courses' => ['name' => 'courses', 'type' => 'tns:createCourseParamsList'],
2880
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
2881
    ]
2882
);
2883
2884
// Prepare output params, in this case will return an array
2885
$server->wsdl->addComplexType(
2886
    'result_createCourse',
2887
    'complexType',
2888
    'struct',
2889
    'all',
2890
    '',
2891
    [
2892
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
2893
        'result' => ['name' => 'result', 'type' => 'xsd:string']
2894
    ]
2895
);
2896
2897
$server->wsdl->addComplexType(
2898
    'results_createCourse',
2899
    'complexType',
2900
    'array',
2901
    '',
2902
    'SOAP-ENC:Array',
2903
    [],
2904
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_createCourse[]']],
2905
    'tns:result_createCourse'
2906
);
2907
2908
// Register the method to expose
2909
$server->register(
2910
    'WSCreateCourse', // method name
2911
    ['createCourse' => 'tns:createCourse'], // input parameters
2912
    ['return' => 'tns:results_createCourse'], // output parameters
2913
    'urn:WSRegistration', // namespace
2914
    'urn:WSRegistration#WSCreateCourse', // soapaction
2915
    'rpc', // style
2916
    'encoded', // use
2917
    'This service adds a course'                   // documentation
2918
);
2919
2920
// Define the method WSCreateCourse
2921
function WSCreateCourse($params)
2922
{
2923
    if (!WSHelperVerifyKey($params)) {
2924
        return returnError(WS_ERROR_SECRET_KEY);
2925
    }
2926
    $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
2927
    $courses_params = $params['courses'];
2928
    $results = [];
2929
    $sessionAdminId = DEFAULT_ADMIN_USER_ID;
2930
    $orig_course_id_value = [];
2931
    foreach ($courses_params as $course_param) {
2932
        $title = $course_param['title'];
2933
        $category_code = isset($course_param['category_code']) ? $course_param['category_code'] : '';
2934
        $wanted_code = $course_param['wanted_code'];
2935
        $tutor_name = isset($course_param['tutor_name']) ? $course_param['tutor_name'] : '';
2936
        $diskQuota = isset($course_param['disk_quota']) ? $course_param['disk_quota'] : '100';
2937
        // Convert to MB
2938
        $diskQuota = $diskQuota * 1024 * 1024;
2939
2940
        $course_language = 'english'; // TODO: A hard-coded value.
2941
        $original_course_id_name = $course_param['original_course_id_name'];
2942
        $original_course_id_value = $course_param['original_course_id_value'];
2943
        $orig_course_id_value[] = $course_param['original_course_id_value'];
2944
        $visibility = null;
2945
        $subscribe = $course_param['subscribe'];
2946
        $unsubscribe = $course_param['unsubscribe'];
2947
2948
        if (isset($course_param['visibility'])) {
2949
            if ($course_param['visibility'] &&
2950
                $course_param['visibility'] >= 0 &&
2951
                $course_param['visibility'] <= 3
2952
            ) {
2953
                $visibility = $course_param['visibility'];
2954
            }
2955
        }
2956
        $extra_list = isset($course_param['extra']) ? $course_param['extra'] : '';
2957
2958
2959
        // Check whether exits $x_course_code into user_field_values table.
2960
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
2961
            $course_param['original_course_id_value'],
2962
            $course_param['original_course_id_name']
2963
        );
2964
2965
        if (!empty($courseInfo)) {
2966
            if ($courseInfo['visibility'] != 0) {
2967
                $sql = "UPDATE $table_course SET
2968
                            course_language='".Database::escape_string($course_language)."',
2969
                            title='".Database::escape_string($title)."',
2970
                            category_code='".Database::escape_string($category_code)."',
2971
                            tutor_name='".Database::escape_string($tutor_name)."',
2972
                            visual_code='".Database::escape_string($wanted_code)."'";
2973
                if ($visibility !== null) {
2974
                    $sql .= ", visibility = '$visibility' ";
2975
                }
2976
                $sql .= " WHERE id='".$courseInfo['real_id']."'";
2977
                Database::query($sql);
2978
                if (is_array($extra_list) && count($extra_list) > 0) {
2979
                    foreach ($extra_list as $extra) {
2980
                        $extra_field_name = $extra['field_name'];
2981
                        $extra_field_value = $extra['field_value'];
2982
                        // Save the external system's id into course_field_value table.
2983
                        CourseManager::update_course_extra_field_value(
2984
                            $courseInfo['code'],
2985
                            $extra_field_name,
2986
                            $extra_field_value
2987
                        );
2988
                    }
2989
                }
2990
                $results[] = $courseInfo['code'];
2991
                continue;
2992
            } else {
2993
                $results[] = 0;
2994
                continue; // Original course id already exits.
2995
            }
2996
        }
2997
2998
        if (!empty($course_param['course_language'])) {
2999
            $course_language = $course_param['course_language'];
3000
        }
3001
3002
        $params = [];
3003
        $params['title'] = $title;
3004
        $params['wanted_code'] = $wanted_code;
3005
        $params['category_code'] = $category_code;
3006
        $params['course_category'] = $category_code;
3007
        $params['tutor_name'] = $tutor_name;
3008
        $params['course_language'] = $course_language;
3009
        $params['user_id'] = $sessionAdminId;
3010
        $params['visibility'] = $visibility;
3011
        $params['disk_quota'] = $diskQuota;
3012
3013
        if (isset($subscribe) && $subscribe != '') { // Valid values: 0, 1
3014
            $params['subscribe'] = $subscribe;
3015
        }
3016
        if (isset($unsubscribe) && $subscribe != '') { // Valid values: 0, 1
3017
            $params['unsubscribe'] = $unsubscribe;
3018
        }
3019
3020
        $course_info = CourseManager::create_course($params, $sessionAdminId);
3021
3022
        if (!empty($course_info)) {
3023
            $course_code = $course_info['code'];
3024
3025
            // Save new field label into course_field table
3026
            CourseManager::create_course_extra_field(
3027
                $original_course_id_name,
3028
                1,
3029
                $original_course_id_name,
3030
                ''
3031
            );
3032
3033
            // Save the external system's id into user_field_value table.
3034
            CourseManager::update_course_extra_field_value(
3035
                $course_code,
3036
                $original_course_id_name,
3037
                $original_course_id_value
3038
            );
3039
3040
            if (is_array($extra_list) && count($extra_list) > 0) {
3041
                foreach ($extra_list as $extra) {
3042
                    $extra_field_name  = $extra['field_name'];
3043
                    $extra_field_value = $extra['field_value'];
3044
                    // Save new fieldlabel into course_field table.
3045
                    CourseManager::create_course_extra_field(
3046
                        $extra_field_name,
3047
                        1,
3048
                        $extra_field_name,
3049
                        ''
3050
                    );
3051
                    // Save the external system's id into course_field_value table.
3052
                    CourseManager::update_course_extra_field_value(
3053
                        $course_code,
3054
                        $extra_field_name,
3055
                        $extra_field_value
3056
                    );
3057
                }
3058
            }
3059
            $results[] = $course_code;
3060
        } else {
3061
            $results[] = 0;
3062
        }
3063
    } // end principal foreach
3064
3065
    $count_results = count($results);
3066
    $output = [];
3067
    for ($i = 0; $i < $count_results; $i++) {
3068
        $output[] = [
3069
            'original_course_id_value' => $orig_course_id_value[$i],
3070
            'result' => $results[$i],
3071
        ];
3072
    }
3073
3074
    return $output;
3075
}
3076
3077
/* Register WSCreateCourseByTitle function */
3078
// Register the data structures used by the service
3079
$server->wsdl->addComplexType(
3080
    'createCourseByTitleParams',
3081
    'complexType',
3082
    'struct',
3083
    'all',
3084
    '',
3085
    [
3086
        'title' => ['name' => 'title', 'type' => 'xsd:string'],
3087
        'tutor_name' => ['name' => 'tutor_name', 'type' => 'xsd:string'],
3088
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
3089
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3090
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
3091
    ]
3092
);
3093
3094
$server->wsdl->addComplexType(
3095
    'createCourseByTitleParamsList',
3096
    'complexType',
3097
    'array',
3098
    '',
3099
    'SOAP-ENC:Array',
3100
    [],
3101
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:createCourseByTitleParams[]']],
3102
    'tns:createCourseByTitleParams'
3103
);
3104
3105
// Register the data structures used by the service
3106
$server->wsdl->addComplexType(
3107
    'createCourseByTitle',
3108
    'complexType',
3109
    'struct',
3110
    'all',
3111
    '',
3112
    [
3113
        'courses' => ['name' => 'courses', 'type' => 'tns:createCourseByTitleParamsList'],
3114
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3115
    ]
3116
);
3117
3118
// Prepare output params, in this case will return an array
3119
$server->wsdl->addComplexType(
3120
    'result_createCourseByTitle',
3121
    'complexType',
3122
    'struct',
3123
    'all',
3124
    '',
3125
    [
3126
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3127
        'result' => ['name' => 'result', 'type' => 'xsd:string']
3128
    ]
3129
);
3130
3131
$server->wsdl->addComplexType(
3132
    'results_createCourseByTitle',
3133
    'complexType',
3134
    'array',
3135
    '',
3136
    'SOAP-ENC:Array',
3137
    [],
3138
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_createCourseByTitle[]']],
3139
    'tns:result_createCourseByTitle'
3140
);
3141
3142
3143
// Register the method to expose
3144
$server->register(
3145
    'WSCreateCourseByTitle', // method name
3146
    ['createCourseByTitle' => 'tns:createCourseByTitle'], // input parameters
3147
    ['return' => 'tns:results_createCourseByTitle'], // output parameters
3148
    'urn:WSRegistration', // namespace
3149
    'urn:WSRegistration#WSCreateCourseByTitle', // soapaction
3150
    'rpc', // style
3151
    'encoded', // use
3152
    'This service adds a course by title'                      // documentation
3153
);
3154
3155
// Define the method WSCreateCourseByTitle
3156
function WSCreateCourseByTitle($params)
3157
{
3158
    global $_configuration;
3159
    if (!WSHelperVerifyKey($params)) {
3160
        return returnError(WS_ERROR_SECRET_KEY);
3161
    }
3162
3163
    $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
3164
    $sessionAdminId = DEFAULT_ADMIN_USER_ID;
3165
    $courses_params = $params['courses'];
3166
    $results = [];
3167
    $orig_course_id_value = [];
3168
3169
    foreach ($courses_params as $course_param) {
3170
        $title = $course_param['title'];
3171
        $category_code = 'LANG'; // TODO: A hard-coded value.
3172
        $wanted_code = '';
3173
        $tutor_firstname = api_get_setting('administratorName');
3174
        $tutor_lastname = api_get_setting('administratorSurname');
3175
        $course_language = 'spanish'; // TODO: Incorrect default value, it should 'english'.
3176
        if (!empty($course_param['course_language'])) {
3177
            $course_language = $course_param['course_language'];
3178
        }
3179
        $tutor_name = api_get_person_name($tutor_firstname, $tutor_lastname, null, null, $course_language);
3180
        if (!empty($course_param['tutor_name'])) {
3181
            $tutor_name = $course_param['tutor_name'];
3182
        }
3183
        $original_course_id_name = $course_param['original_course_id_name'];
3184
        $original_course_id_value = $course_param['original_course_id_value'];
3185
        $orig_course_id_value[] = $course_param['original_course_id_value'];
3186
        $extra_list = $course_param['extra'];
3187
3188
        // Ensure the database prefix + database name do not get over 40 characters
3189
        $maxlength = 40;
3190
        if (empty($wanted_code)) {
3191
            $wanted_code = CourseManager::generate_course_code(substr($title, 0, $maxlength));
3192
        }
3193
3194
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
3195
            $original_course_id_value,
3196
            $original_course_id_name
3197
        );
3198
3199
        if (!empty($courseInfo)) {
3200
            if ($courseInfo['visibility'] != 0) {
3201
                $sql = "UPDATE $table_course SET
3202
                            course_language='".Database::escape_string($course_language)."',
3203
                            title='".Database::escape_string($title)."',
3204
                            category_code='".Database::escape_string($category_code)."',
3205
                            tutor_name='".Database::escape_string($tutor_name)."',
3206
                            visual_code='".Database::escape_string($wanted_code)."',
3207
                            visibility = '3'
3208
                        WHERE id ='".$courseInfo['real_id']."'";
3209
                Database::query($sql);
3210
                $results[] = $courseInfo['real_id'];
3211
                continue;
3212
            } else {
3213
                $results[] = 0;
3214
                continue;
3215
            }
3216
        }
3217
3218
        $values['course_language'] = api_get_setting('platformLanguage');
3219
3220
        $keys = AddCourse::define_course_keys($wanted_code, '', $_configuration['db_prefix']);
3221
3222
        $sql_check = sprintf('SELECT * FROM '.$table_course.' WHERE visual_code = "%s"', Database :: escape_string($wanted_code));
3223
        $result_check = Database::query($sql_check); // I don't know why this api function doesn't work...
3224
        if (Database::num_rows($result_check) < 1) {
3225
            $params = [];
3226
            $params['title'] = $title;
3227
            $params['wanted_code'] = $wanted_code;
3228
            $params['category_code'] = $category_code;
3229
            $params['tutor_name'] = $tutor_name;
3230
            $params['course_language'] = $course_language;
3231
            $params['user_id'] = $sessionAdminId;
3232
            $course_info = CourseManager::create_course($params, $sessionAdminId);
3233
            if (!empty($course_info)) {
3234
                $course_code = $course_info['code'];
3235
3236
                // Save new fieldlabel into course_field table.
3237
                CourseManager::create_course_extra_field(
3238
                    $original_course_id_name,
3239
                    1,
3240
                    $original_course_id_name,
3241
                    ''
3242
                );
3243
3244
                // Save the external system's id into user_field_value table.
3245
                CourseManager::update_course_extra_field_value(
3246
                    $course_code,
3247
                    $original_course_id_name,
3248
                    $original_course_id_value
3249
                );
3250
3251
                if (is_array($extra_list) && count($extra_list) > 0) {
3252
                    foreach ($extra_list as $extra) {
3253
                        $extra_field_name = $extra['field_name'];
3254
                        $extra_field_value = $extra['field_value'];
3255
                        // Save new fieldlabel into course_field table.
3256
                        CourseManager::create_course_extra_field(
3257
                            $extra_field_name,
3258
                            1,
3259
                            $extra_field_name,
3260
                            ''
3261
                        );
3262
                        // Save the external system's id into course_field_value table.
3263
                        CourseManager::update_course_extra_field_value(
3264
                            $course_code,
3265
                            $extra_field_name,
3266
                            $extra_field_value
3267
                        );
3268
                    }
3269
                }
3270
            }
3271
            $results[] = $course_code;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $course_code does not seem to be defined for all execution paths leading up to this point.
Loading history...
3272
            continue;
3273
        } else {
3274
            $results[] = 0;
3275
            continue;
3276
        }
3277
    } // end principal foreach
3278
3279
    $count_results = count($results);
3280
    $output = [];
3281
    for ($i = 0; $i < $count_results; $i++) {
3282
        $output[] = [
3283
            'original_course_id_value' => $orig_course_id_value[$i],
3284
            'result' => $results[$i],
3285
        ];
3286
    }
3287
3288
    return $output;
3289
}
3290
3291
/* Register WSEditCourse function */
3292
// Register the data structures used by the service
3293
3294
$server->wsdl->addComplexType(
3295
    'editCourseParams',
3296
    'complexType',
3297
    'struct',
3298
    'all',
3299
    '',
3300
    [
3301
        'tutor_id' => ['name' => 'tutor_id', 'type' => 'xsd:string'],
3302
        'title' => ['name' => 'title', 'type' => 'xsd:string'],
3303
        'category_code' => ['name' => 'category_code', 'type' => 'xsd:string'],
3304
        'department_name' => ['name' => 'department_name', 'type' => 'xsd:string'],
3305
        'department_url' => ['name' => 'department_url', 'type' => 'xsd:string'],
3306
        'course_language' => ['name' => 'course_language', 'type' => 'xsd:string'],
3307
        'visibility' => ['name' => 'visibility', 'type' => 'xsd:string'],
3308
        'subscribe' => ['name' => 'subscribe', 'type' => 'xsd:string'],
3309
        'unsubscribe' => ['name' => 'unsubscribe', 'type' => 'xsd:string'],
3310
        'visual_code' => ['name' => 'visual_code', 'type' => 'xsd:string'],
3311
        'disk_quota' => ['name' => 'disk_quota', 'type' => 'xsd:string'], // disk_quota in MB
3312
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
3313
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3314
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
3315
    ]
3316
);
3317
3318
$server->wsdl->addComplexType(
3319
    'editCourseParamsList',
3320
    'complexType',
3321
    'array',
3322
    '',
3323
    'SOAP-ENC:Array',
3324
    [],
3325
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:editCourseParams[]']],
3326
    'tns:editCourseParams'
3327
);
3328
3329
$server->wsdl->addComplexType(
3330
    'editCourse',
3331
    'complexType',
3332
    'struct',
3333
    'all',
3334
    '',
3335
    [
3336
        'courses' => ['name' => 'courses', 'type' => 'tns:editCourseParamsList'],
3337
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3338
    ]
3339
);
3340
3341
// Prepare output params, in this case will return an array
3342
$server->wsdl->addComplexType(
3343
    'result_editCourse',
3344
    'complexType',
3345
    'struct',
3346
    'all',
3347
    '',
3348
    [
3349
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3350
        'result' => ['name' => 'result', 'type' => 'xsd:string']
3351
    ]
3352
);
3353
3354
$server->wsdl->addComplexType(
3355
    'results_editCourse',
3356
    'complexType',
3357
    'array',
3358
    '',
3359
    'SOAP-ENC:Array',
3360
    [],
3361
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_editCourse[]']],
3362
    'tns:result_editCourse'
3363
);
3364
3365
// Register the method to expose
3366
$server->register(
3367
    'WSEditCourse', // method name
3368
    ['editCourse' => 'tns:editCourse'], // input parameters
3369
    ['return' => 'tns:results_editCourse'], // output parameters
3370
    'urn:WSRegistration', // namespace
3371
    'urn:WSRegistration#WSEditCourse', // soapaction
3372
    'rpc', // style
3373
    'encoded', // use
3374
    'This service edits a course'                // documentation
3375
);
3376
3377
// Define the method WSEditCourse
3378
function WSEditCourse($params)
3379
{
3380
    global $_configuration;
3381
    if (!WSHelperVerifyKey($params)) {
3382
        return returnError(WS_ERROR_SECRET_KEY);
3383
    }
3384
3385
    $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
3386
3387
    $courses_params = $params['courses'];
3388
    $results = [];
3389
    $orig_course_id_value = [];
3390
3391
    foreach ($courses_params as $course_param) {
3392
        $tutor_id = isset($course_param['tutor_id']) ? $course_param['tutor_id'] : '';
3393
        $title = $course_param['title'];
3394
        $category_code = isset($course_param['category_code']) ? $course_param['category_code'] : '';
3395
        $department_name = isset($course_param['department_name']) ? $course_param['department_name'] : '';
3396
        $department_url = isset($course_param['department_url']) ? $course_param['department_url'] : '';
3397
        $course_language = $course_param['course_language'];
3398
        $visibility = $course_param['visibility'];
3399
        $subscribe = $course_param['subscribe'];
3400
        $unsubscribe = $course_param['unsubscribe'];
3401
        $visual_code = $course_param['visual_code'];
3402
        $diskQuota = isset($course_param['disk_quota']) ? $course_param['disk_quota'] : '100';
3403
        // Convert to MB
3404
        $diskQuota = $diskQuota * 1024 * 1024;
3405
3406
        $original_course_id_name = $course_param['original_course_id_name'];
3407
        $original_course_id_value = $course_param['original_course_id_value'];
3408
        $orig_course_id_value[] = $original_course_id_value;
3409
        $extra_list = isset($course_param['extra']) ? $course_param['extra'] : null;
3410
3411
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
3412
            $original_course_id_value,
3413
            $original_course_id_name
3414
        );
3415
3416
        if (empty($courseInfo)) {
3417
            $results[] = 0; // Original_course_id_value doesn't exist.
3418
            continue;
3419
        }
3420
3421
        $course_code = $courseInfo['code'];
3422
        $courseId = $courseInfo['real_id'];
3423
3424
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
3425
        $sql = "SELECT concat(lastname,'',firstname) as tutor_name
3426
                FROM $table_user WHERE status='1' AND user_id = '$tutor_id'
3427
                ORDER BY lastname,firstname";
3428
        $res = Database::query($sql);
3429
        $tutor_name = Database::fetch_row($res);
3430
3431
        $dbnamelength = strlen($_configuration['db_prefix']);
3432
        $maxlength = 40 - $dbnamelength;
3433
3434
        if (empty($visual_code)) {
3435
            $visual_code = CourseManager::generate_course_code(substr($title, 0, $maxlength));
3436
        }
3437
        $tutor_name = $tutor_name[0];
3438
        $sql = "UPDATE $course_table SET
3439
                    course_language='".Database::escape_string($course_language)."',
3440
                    title='".Database::escape_string($title)."',
3441
                    category_code='".Database::escape_string($category_code)."',
3442
                    tutor_name='".Database::escape_string($tutor_name)."',
3443
                    visual_code='".Database::escape_string($visual_code)."',
3444
                    department_name='".Database::escape_string($department_name)."',
3445
                    department_url='".Database::escape_string($department_url)."',
3446
                    visibility = '".Database::escape_string($visibility)."',
3447
                    subscribe = '".Database::escape_string($subscribe)."',
3448
                    disk_quota='".Database::escape_string($diskQuota)."',
3449
                    unsubscribe='".Database::escape_string($unsubscribe)."'
3450
                WHERE id ='".Database::escape_string($courseId)."'";
3451
        $res = Database::query($sql);
3452
3453
        if (is_array($extra_list) && count($extra_list) > 0) {
3454
            foreach ($extra_list as $extra) {
3455
                $extra_field_name = $extra['field_name'];
3456
                $extra_field_value = $extra['field_value'];
3457
                // Save the external system's id into course_field_value table.
3458
                $res = CourseManager::update_course_extra_field_value(
3459
                    $course_code,
3460
                    $extra_field_name,
3461
                    $extra_field_value
3462
                );
3463
            }
3464
        }
3465
3466
        if ($res) {
3467
            $results[] = 1;
3468
            continue;
3469
        } else {
3470
            $results[] = 0;
3471
            continue;
3472
        }
3473
    } // end principal foreach
3474
3475
    $count_results = count($results);
3476
    $output = [];
3477
    for ($i = 0; $i < $count_results; $i++) {
3478
        $output[] = [
3479
            'original_course_id_value' => $orig_course_id_value[$i],
3480
            'result' => $results[$i],
3481
        ];
3482
    }
3483
3484
    return $output;
3485
}
3486
3487
/* Register WSCourseDescription function */
3488
// Register the data structures used by the service
3489
3490
$server->wsdl->addComplexType(
3491
    'courseDescription',
3492
    'complexType',
3493
    'struct',
3494
    'all',
3495
    '',
3496
    [
3497
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
3498
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3499
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3500
    ]
3501
);
3502
3503
// Prepare output params, in this case will return an array
3504
$server->wsdl->addComplexType(
3505
    'fields_course_desc',
3506
    'complexType',
3507
    'struct',
3508
    'all',
3509
    '',
3510
    [
3511
        'course_desc_id' => ['name' => 'course_desc_id', 'type' => 'xsd:string'],
3512
        'course_desc_default_title' => ['name' => 'course_desc_default_title', 'type' => 'xsd:string'],
3513
        'course_desc_title' => ['name' => 'course_desc_title', 'type' => 'xsd:string'],
3514
        'course_desc_content' => ['name' => 'course_desc_content', 'type' => 'xsd:string']
3515
    ]
3516
);
3517
3518
$server->wsdl->addComplexType(
3519
    'fields_course_desc_list',
3520
    'complexType',
3521
    'array',
3522
    '',
3523
    'SOAP-ENC:Array',
3524
    [],
3525
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:fields_course_desc[]']],
3526
    'tns:fields_course_desc'
3527
);
3528
3529
3530
// Register the method to expose
3531
$server->register(
3532
    'WSCourseDescription', // method name
3533
    ['courseDescription' => 'tns:courseDescription'], // input parameters
3534
    ['return' => 'tns:fields_course_desc_list'], // output parameters
3535
    'urn:WSRegistration', // namespace
3536
    'urn:WSRegistration#WSCourseDescription', // soapaction
3537
    'rpc', // style
3538
    'encoded', // use
3539
    'This service edits a course description'               // documentation
3540
);
3541
3542
// Define the method WSCourseDescription
3543
function WSCourseDescription($params)
3544
{
3545
    if (!WSHelperVerifyKey($params)) {
3546
        return returnError(WS_ERROR_SECRET_KEY);
3547
    }
3548
3549
    $array_course_desc_id = [];
3550
    $array_course_desc_title = [];
3551
    $array_course_desc_content = [];
3552
3553
    $original_course_id_name = $params['original_course_id_name'];
3554
    $original_course_id_value = $params['original_course_id_value'];
3555
3556
    $courseInfo = CourseManager::getCourseInfoFromOriginalId(
3557
        $original_course_id_value,
3558
        $original_course_id_name
3559
    );
3560
3561
    if (empty($courseInfo) || (isset($courseInfo) && $courseInfo['visibility'] == 0)) {
3562
        return 0; // Original_course_id_value doesn't exist.
3563
    }
3564
3565
    $t_course_desc = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
3566
    $sql = "SELECT * FROM $t_course_desc WHERE c_id = {$courseInfo['real_id']} ";
3567
    $result = Database::query($sql);
3568
3569
    $default_titles = [
3570
        get_lang('GeneralDescription'),
3571
        get_lang('Objectives'),
3572
        get_lang('Topics'),
3573
        get_lang('Methodology'),
3574
        get_lang('CourseMaterial'),
3575
        get_lang('HumanAndTechnicalResources'),
3576
        get_lang('Assessment'),
3577
        get_lang('AddCategory')
3578
    ];
3579
3580
    for ($x = 1; $x < 9; $x++) {
3581
        $array_course_desc_id[$x] = $x;
3582
        $array_course_desc_default_title[$x] = $default_titles[$x - 1];
3583
        $array_course_desc_title[$x] = '';
3584
        $array_course_desc_content[$x] = '';
3585
    }
3586
3587
    while ($row = Database::fetch_array($result)) {
3588
        $ind = (int) $row['id'];
3589
        $array_course_desc_title[$ind] = $row['title'];
3590
        $array_course_desc_content[$ind] = $row['content'];
3591
    }
3592
3593
    $count_results = count($default_titles);
3594
    $output = [];
3595
    for ($i = 1; $i <= $count_results; $i++) {
3596
        $output[] = [
3597
            'course_desc_id' => $array_course_desc_id[$i],
3598
            'course_desc_default_title' => $array_course_desc_default_title[$i],
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $array_course_desc_default_title does not seem to be defined for all execution paths leading up to this point.
Loading history...
3599
            'course_desc_title' => $array_course_desc_title[$i],
3600
            'course_desc_content' => $array_course_desc_content[$i]
3601
        ];
3602
    }
3603
3604
    return $output;
3605
}
3606
3607
/* Register WSEditCourseDescription function */
3608
// Register the data structures used by the service
3609
3610
$server->wsdl->addComplexType(
3611
    'editCourseDescriptionParams',
3612
    'complexType',
3613
    'struct',
3614
    'all',
3615
    '',
3616
    [
3617
        'course_desc_id' => ['name' => 'course_desc_id', 'type' => 'xsd:string'],
3618
        'course_desc_title' => ['name' => 'course_desc_title', 'type' => 'xsd:string'],
3619
        'course_desc_content' => ['name' => 'course_desc_content', 'type' => 'xsd:string'],
3620
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
3621
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string']
3622
    ]
3623
);
3624
3625
$server->wsdl->addComplexType(
3626
    'editCourseDescriptionParamsList',
3627
    'complexType',
3628
    'array',
3629
    '',
3630
    'SOAP-ENC:Array',
3631
    [],
3632
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:editCourseDescriptionParams[]']],
3633
    'tns:editCourseDescriptionParams'
3634
);
3635
3636
$server->wsdl->addComplexType(
3637
    'editCourseDescription',
3638
    'complexType',
3639
    'struct',
3640
    'all',
3641
    '',
3642
    [
3643
        'course_desc' => ['name' => 'course_desc', 'type' => 'tns:editCourseDescriptionParamsList'],
3644
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3645
    ]
3646
);
3647
3648
// Prepare output params, in this case will return an array
3649
$server->wsdl->addComplexType(
3650
    'result_editCourseDescription',
3651
    'complexType',
3652
    'struct',
3653
    'all',
3654
    '',
3655
    [
3656
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3657
        'course_desc_id' => ['name' => 'course_desc_id', 'type' => 'xsd:string'],
3658
        'result' => ['name' => 'result', 'type' => 'xsd:string']
3659
    ]
3660
);
3661
3662
$server->wsdl->addComplexType(
3663
    'results_editCourseDescription',
3664
    'complexType',
3665
    'array',
3666
    '',
3667
    'SOAP-ENC:Array',
3668
    [],
3669
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_editCourseDescription[]']],
3670
    'tns:result_editCourseDescription'
3671
);
3672
3673
3674
// Register the method to expose
3675
$server->register(
3676
    'WSEditCourseDescription', // method name
3677
    ['editCourseDescription' => 'tns:editCourseDescription'], // input parameters
3678
    ['return' => 'tns:results_editCourseDescription'], // output parameters
3679
    'urn:WSRegistration', // namespace
3680
    'urn:WSRegistration#WSEditCourseDescription', // soapaction
3681
    'rpc', // style
3682
    'encoded', // use
3683
    'This service edits a course description'                      // documentation
3684
);
3685
3686
// Define the method WSEditCourseDescription
3687
function WSEditCourseDescription($params)
3688
{
3689
    if (!WSHelperVerifyKey($params)) {
3690
        return -1;
3691
    }
3692
3693
    $courses_params = $params['course_desc'];
3694
    $results = [];
3695
    $orig_course_id_value = [];
3696
    $course_description_id = [];
3697
3698
    $courseDescription = new CourseDescription();
3699
    $defaultDescTitle = $courseDescription->get_default_description_title();
3700
3701
    foreach ($courses_params as $course_param) {
3702
        $original_course_id_name = $course_param['original_course_id_name'];
3703
        $original_course_id_value = $course_param['original_course_id_value'];
3704
        $course_desc_id = $course_param['course_desc_id'];
3705
        $course_desc_title = $course_param['course_desc_title'];
3706
        $course_desc_content = $course_param['course_desc_content'];
3707
        $orig_course_id_value[] = $original_course_id_value;
3708
        $course_description_id[] = $course_desc_id;
3709
3710
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
3711
            $original_course_id_value,
3712
            $original_course_id_name
3713
        );
3714
3715
        if (empty($courseInfo) || (isset($courseInfo) && $courseInfo['visibility'] == 0)) {
3716
            $results[] = 0;
3717
            continue; // Original_course_id_value doesn't exist.
3718
        }
3719
3720
        $course_desc_id = Database::escape_string($course_desc_id);
3721
        $course_desc_title = Database::escape_string($course_desc_title);
3722
        $course_desc_content = Database::escape_string($course_desc_content);
3723
3724
        $course_desc_id = (int) $course_desc_id;
3725
        if ($course_desc_id > 8 && $course_desc_id < 1) {
3726
            $results[] = 0; // course_desc_id invalid.
3727
            continue;
3728
        }
3729
3730
        // if title is empty set default title instead
3731
        if (empty($course_desc_title)) {
3732
            $course_desc_title = $defaultDescTitle[$course_desc_id];
3733
        }
3734
3735
        $courseId = $courseInfo['real_id'];
3736
        $courseDescription->set_id(null);
3737
        $courseDescription->set_course_id($courseId);
3738
        $courseDescription->set_session_id(0);
3739
        $courseDescription->set_title($course_desc_title);
3740
        $courseDescription->set_content($course_desc_content);
3741
        $courseDescription->set_description_type($course_desc_id);
3742
3743
        $data = $courseDescription->get_data_by_description_type($course_desc_id, $courseId);
3744
        if ($data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
3745
            // Update existing description
3746
            $courseDescription->set_id($data['id']);
3747
            $result = $courseDescription->update();
3748
        } else {
3749
            // Insert new description
3750
            $result = $courseDescription->insert();
3751
        }
3752
3753
        $results[] = $result ? 1 : 0;
3754
    } // end principal foreach
3755
3756
    $count_results = count($results);
3757
    $output = [];
3758
    for ($i = 0; $i < $count_results; $i++) {
3759
        $output[] = [
3760
            'original_course_id_value' => $orig_course_id_value[$i],
3761
            'course_desc_id' => $course_description_id[$i],
3762
            'result' => $results[$i],
3763
        ];
3764
    }
3765
3766
    return $output;
3767
}
3768
3769
/* Register WSDeleteCourse function */
3770
// Register the data structures used by the service
3771
$server->wsdl->addComplexType(
3772
    'deleteCourseParams',
3773
    'complexType',
3774
    'struct',
3775
    'all',
3776
    '',
3777
    [
3778
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3779
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string']
3780
    ]
3781
);
3782
3783
$server->wsdl->addComplexType(
3784
    'deleteCourseParamsList',
3785
    'complexType',
3786
    'array',
3787
    '',
3788
    'SOAP-ENC:Array',
3789
    [],
3790
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:deleteCourseParams[]']],
3791
    'tns:deleteCourseParams'
3792
);
3793
3794
// Register the data structures used by the service.
3795
$server->wsdl->addComplexType(
3796
    'deleteCourse',
3797
    'complexType',
3798
    'struct',
3799
    'all',
3800
    '',
3801
    [
3802
        'courses' => ['name' => 'courses', 'type' => 'tns:deleteCourseParamsList'],
3803
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3804
    ]
3805
);
3806
3807
// Prepare output params, in this case will return an array.
3808
$server->wsdl->addComplexType(
3809
    'result_deleteCourse',
3810
    'complexType',
3811
    'struct',
3812
    'all',
3813
    '',
3814
    [
3815
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3816
        'result' => ['name' => 'result', 'type' => 'xsd:string']
3817
    ]
3818
);
3819
3820
$server->wsdl->addComplexType(
3821
    'results_deleteCourse',
3822
    'complexType',
3823
    'array',
3824
    '',
3825
    'SOAP-ENC:Array',
3826
    [],
3827
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_deleteCourse[]']],
3828
    'tns:result_deleteCourse'
3829
);
3830
3831
$server->register(
3832
    'WSDeleteCourse', // method name
3833
    ['deleteCourse' => 'tns:deleteCourse'], // input parameters
3834
    ['return' => 'tns:results_deleteCourse'], // output parameters
3835
    'urn:WSRegistration', // namespace
3836
    'urn:WSRegistration#WSDeleteCourse', // soapaction
3837
    'rpc', // style
3838
    'encoded', // use
3839
    'This service deletes a course '               // documentation
3840
);
3841
3842
3843
// Define the method WSDeleteCourse
3844
function WSDeleteCourse($params)
3845
{
3846
    if (!WSHelperVerifyKey($params)) {
3847
        return returnError(WS_ERROR_SECRET_KEY);
3848
    }
3849
3850
    $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
3851
    $courses_params = $params['courses'];
3852
    $results = [];
3853
    $orig_course_id_value = [];
3854
    foreach ($courses_params as $course_param) {
3855
        $original_course_id_value = $course_param['original_course_id_value'];
3856
        $original_course_id_name = $course_param['original_course_id_name'];
3857
        $orig_course_id_value[] = $original_course_id_value;
3858
3859
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
3860
            $original_course_id_value,
3861
            $original_course_id_name
3862
        );
3863
3864
        if (empty($courseInfo) || (isset($courseInfo) && $courseInfo['visibility'] == 0)) {
3865
            $results[] = 0;
3866
            continue; // Original_course_id_value doesn't exist.
3867
        }
3868
3869
        $courseId = $courseInfo['real_id'];
3870
        $sql = "UPDATE $table_course SET visibility = '0' WHERE id = '$courseId'";
3871
        $return = Database::query($sql);
3872
        $results[] = $return;
3873
    }
3874
3875
    $count_results = count($results);
3876
    $output = [];
3877
    for ($i = 0; $i < $count_results; $i++) {
3878
        $output[] = [
3879
            'original_course_id_value' => $orig_course_id_value[$i],
3880
            'result' => $results[$i],
3881
        ];
3882
    }
3883
3884
    return $output;
3885
}
3886
3887
/* Register WSCreateSession function */
3888
// Register data structures used by the service.
3889
$server->wsdl->addComplexType(
3890
    'createSessionParam',
3891
    'complexType',
3892
    'struct',
3893
    'all',
3894
    '',
3895
    [
3896
        'name' => ['name' => 'name', 'type' => 'xsd:string'],
3897
        'year_start' => ['name' => 'year_start', 'type' => 'xsd:string'],
3898
        'month_start' => ['name' => 'month_start', 'type' => 'xsd:string'],
3899
        'day_start' => ['name' => 'day_start', 'type' => 'xsd:string'],
3900
        'year_end' => ['name' => 'year_end', 'type' => 'xsd:string'],
3901
        'month_end' => ['name' => 'month_end', 'type' => 'xsd:string'],
3902
        'day_end' => ['name' => 'day_end', 'type' => 'xsd:string'],
3903
        'nb_days_access_before' => ['name' => 'nb_days_access_before', 'type' => 'xsd:string'],
3904
        'nb_days_access_after' => ['name' => 'nb_days_access_after', 'type' => 'xsd:string'],
3905
        'nolimit' => ['name' => 'nolimit', 'type' => 'xsd:string'],
3906
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
3907
        'duration' => ['name' => 'duration', 'type' => 'xsd:string'],
3908
        'original_session_id_name' => ['name' => 'original_session_id_name', 'type' => 'xsd:string'],
3909
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
3910
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
3911
    ]
3912
);
3913
3914
$server->wsdl->addComplexType(
3915
    'createSessionParamList',
3916
    'complexType',
3917
    'array',
3918
    '',
3919
    'SOAP-ENC:Array',
3920
    [],
3921
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:createSessionParam[]']],
3922
    'tns:createSessionParamList'
3923
);
3924
3925
// Register the data structures used by the service
3926
$server->wsdl->addComplexType(
3927
    'createSession',
3928
    'complexType',
3929
    'struct',
3930
    'all',
3931
    '',
3932
    [
3933
        'sessions' => ['name' => 'sessions', 'type' => 'tns:createSessionParamList'],
3934
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3935
    ]
3936
);
3937
3938
// Prepare output params, in this case will return an array
3939
$server->wsdl->addComplexType(
3940
    'result_createSession',
3941
    'complexType',
3942
    'struct',
3943
    'all',
3944
    '',
3945
    [
3946
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
3947
        'result' => ['name' => 'result', 'type' => 'xsd:string']
3948
    ]
3949
);
3950
3951
$server->wsdl->addComplexType(
3952
    'results_createSession',
3953
    'complexType',
3954
    'array',
3955
    '',
3956
    'SOAP-ENC:Array',
3957
    [],
3958
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_createSession[]']],
3959
    'tns:result_createSession'
3960
);
3961
3962
// Register the method to expose
3963
$server->register(
3964
    'WSCreateSession', // method name
3965
    ['createSession' => 'tns:createSession'], // input parameters
3966
    ['return' => 'tns:results_createSession'], // output parameters
3967
    'urn:WSRegistration', // namespace
3968
    'urn:WSRegistration#WSCreateSession', // soapaction
3969
    'rpc', // style
3970
    'encoded', // use
3971
    'This service edits a session'                  // documentation
3972
);
3973
3974
3975
// define the method WSCreateSession
3976
function WSCreateSession($params)
3977
{
3978
    global $debug;
3979
    $sessionAdminId = DEFAULT_ADMIN_USER_ID;
3980
3981
    if (!WSHelperVerifyKey($params)) {
3982
        return returnError(WS_ERROR_SECRET_KEY);
3983
    }
3984
3985
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3986
    error_log(print_r($params, 1));
3987
3988
    $sessions_params = $params['sessions'];
3989
    $results = [];
3990
    $orig_session_id_value = [];
3991
3992
    foreach ($sessions_params as $session_param) {
3993
        $name = trim($session_param['name']);
3994
        $year_start = intval($session_param['year_start']);
3995
        $month_start = intval($session_param['month_start']);
3996
        $day_start = intval($session_param['day_start']);
3997
        $year_end = intval($session_param['year_end']);
3998
        $month_end = intval($session_param['month_end']);
3999
        $day_end = intval($session_param['day_end']);
4000
        $nb_days_access_before = intval($session_param['nb_days_access_before']);
4001
        $nb_days_access_after = intval($session_param['nb_days_access_after']);
4002
        $id_coach = $session_param['user_id'];
4003
        $nolimit = $session_param['nolimit'];
4004
        $duration = $session_param['duration'];
4005
        $original_session_id_name = $session_param['original_session_id_name'];
4006
        $original_session_id_value = $session_param['original_session_id_value'];
4007
        $orig_session_id_value[] = $session_param['original_session_id_value'];
4008
        $extra_list = isset($session_param['extra']) ? $session_param['extra'] : '';
4009
4010
        $sessionId = SessionManager::getSessionIdFromOriginalId(
4011
            $original_session_id_value,
4012
            $original_session_id_name
4013
        );
4014
4015
        if (!empty($sessionId)) {
4016
            if ($debug) {
4017
                error_log("session with external session id '$original_session_id_value' with '$name' exists");
4018
            }
4019
            $results[] = 0;
4020
            continue;
4021
        }
4022
4023
        if (empty($nolimit)) {
4024
            $date_start = "$year_start-".(($month_start < 10) ? "0$month_start" : $month_start)."-".(($day_start < 10) ? "0$day_start" : $day_start).' 00:00:00';
4025
            $date_end = "$year_end-".(($month_end < 10) ? "0$month_end" : $month_end)."-".(($day_end < 10) ? "0$day_end" : $day_end).' 23:59:59';
4026
        } else {
4027
            $date_start = "";
4028
            $date_end = "";
4029
        }
4030
4031
        if (empty($name)) {
4032
            if ($debug) {
4033
                error_log("session has no name");
4034
            }
4035
            $results[] = 0;
4036
            continue;
4037
        } elseif (empty($id_coach)) {
4038
            $results[] = 0;
4039
            if ($debug) {
4040
                error_log("Coach id must not be empty");
4041
            }
4042
            continue;
4043
        } elseif (empty($nolimit) && (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start))) {
4044
            if ($debug) {
4045
                error_log("There's an error with the start date: $month_start - $day_start - $year_start");
4046
            }
4047
            $results[] = 0;
4048
            continue;
4049
        } elseif (empty($nolimit) && (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end))) {
4050
            $results[] = 0;
4051
            if ($debug) {
4052
                error_log("There's an error with the end date: $month_end - $day_end - $year_end");
4053
            }
4054
            continue;
4055
        } elseif (empty($nolimit) && $date_start >= $date_end) {
4056
            $results[] = 0;
4057
            if ($debug) {
4058
                error_log("There's an error with the start and end date");
4059
            }
4060
            continue;
4061
        } else {
4062
            $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='".addslashes($name)."'");
4063
            if (Database::num_rows($rs)) {
4064
                if ($debug) {
4065
                    error_log("Session with name '$name' already exists");
4066
                }
4067
                $results[] = 0;
4068
                continue;
4069
            } else {
4070
                $coachStartDate = '';
4071
                if ($date_start) {
4072
                    $startDate = new DateTime($date_start);
4073
                    $diffStart = new DateInterval("P".$nb_days_access_before."D");
4074
                    $coachStartDate = $startDate->sub($diffStart);
4075
                    $coachStartDate = $coachStartDate->format('Y-m-d H:i:s');
4076
                }
4077
                $coachEndDate = '';
4078
                if ($date_end) {
4079
                    $endDate = new DateTime($date_end);
4080
                    $diffEnd = new DateInterval("P".$nb_days_access_after."D");
4081
                    $coachEndDate = $endDate->add($diffEnd);
4082
                    $coachEndDate = $coachEndDate->format('Y-m-d H:i:s');
4083
                }
4084
                $id_session = SessionManager::create_session(
4085
                    $name,
4086
                    $date_start,
4087
                    $date_end,
4088
                    $date_start,
4089
                    $date_end,
4090
                    $coachStartDate,
4091
                    $coachEndDate,
4092
                    $id_coach,
4093
                    0,
4094
                    1,
4095
                    false,
4096
                    $duration,
4097
                    null,
4098
                    0,
4099
                    [],
4100
                    $sessionAdminId
4101
                );
4102
4103
                if ($id_session) {
4104
                    if ($debug) {
4105
                        error_log("Session created '$id_session' ");
4106
                    }
4107
                    // Save new field label into course_field table.
4108
                    SessionManager::create_session_extra_field(
4109
                        $original_session_id_name,
4110
                        1,
4111
                        $original_session_id_name
4112
                    );
4113
4114
                    // Save the external system's id into user_field_value table.
4115
                    SessionManager::update_session_extra_field_value(
4116
                        $id_session,
4117
                        $original_session_id_name,
4118
                        $original_session_id_value
4119
                    );
4120
4121
                    if (is_array($extra_list) && count($extra_list) > 0) {
4122
                        foreach ($extra_list as $extra) {
4123
                            $extra_field_name = $extra['field_name'];
4124
                            $extra_field_value = $extra['field_value'];
4125
                            // Save new fieldlabel into course_field table.
4126
                            SessionManager::create_session_extra_field(
4127
                                $extra_field_name,
4128
                                1,
4129
                                $extra_field_name
4130
                            );
4131
                            // Save the external system's id into course_field_value table.
4132
                            SessionManager::update_session_extra_field_value(
4133
                                $id_session,
4134
                                $extra_field_name,
4135
                                $extra_field_value
4136
                            );
4137
                        }
4138
                    }
4139
                    $results[] = $id_session;
4140
                } else {
4141
                    if ($debug) {
4142
                        error_log("There was an error when trying to save session with name $name");
4143
                    }
4144
                }
4145
            }
4146
        }
4147
    } // end principal foreach
4148
4149
    $count_results = count($results);
4150
    $output = [];
4151
    for ($i = 0; $i < $count_results; $i++) {
4152
        $output[] = [
4153
            'original_session_id_value' => $orig_session_id_value[$i],
4154
            'result' => $results[$i],
4155
        ];
4156
    }
4157
4158
    return $output;
4159
}
4160
4161
/* Register WSEditSession function */
4162
// Register the data structures used by the service
4163
$server->wsdl->addComplexType(
4164
    'editSessionParams',
4165
    'complexType',
4166
    'struct',
4167
    'all',
4168
    '',
4169
    [
4170
        'name' => ['name' => 'name', 'type' => 'xsd:string'],
4171
        'year_start' => ['name' => 'year_start', 'type' => 'xsd:string'],
4172
        'month_start' => ['name' => 'month_start', 'type' => 'xsd:string'],
4173
        'day_start' => ['name' => 'day_start', 'type' => 'xsd:string'],
4174
        'year_end' => ['name' => 'year_end', 'type' => 'xsd:string'],
4175
        'month_end' => ['name' => 'month_end', 'type' => 'xsd:string'],
4176
        'day_end' => ['name' => 'day_end', 'type' => 'xsd:string'],
4177
        'nb_days_access_before' => ['name' => 'nb_days_access_before', 'type' => 'xsd:string'],
4178
        'nb_days_access_after' => ['name' => 'nb_days_access_after', 'type' => 'xsd:string'],
4179
        'nolimit' => ['name' => 'nolimit', 'type' => 'xsd:string'],
4180
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
4181
        'duration' => ['name' => 'duration', 'type' => 'xsd:string'],
4182
        'original_session_id_name' => ['name' => 'original_session_id_name', 'type' => 'xsd:string'],
4183
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
4184
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
4185
    ]
4186
);
4187
4188
$server->wsdl->addComplexType(
4189
    'editSessionParamsList',
4190
    'complexType',
4191
    'array',
4192
    '',
4193
    'SOAP-ENC:Array',
4194
    [],
4195
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:editSessionParams[]']],
4196
    'tns:editSessionParams'
4197
);
4198
4199
$server->wsdl->addComplexType(
4200
    'editSession',
4201
    'complexType',
4202
    'struct',
4203
    'all',
4204
    '',
4205
    [
4206
        'sessions' => ['name' => 'sessions', 'type' => 'tns:editSessionParamsList'],
4207
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
4208
    ]
4209
);
4210
4211
// Prepare output params, in this case will return an array
4212
$server->wsdl->addComplexType(
4213
    'result_editSession',
4214
    'complexType',
4215
    'struct',
4216
    'all',
4217
    '',
4218
    [
4219
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
4220
        'result' => ['name' => 'result', 'type' => 'xsd:string']
4221
    ]
4222
);
4223
4224
$server->wsdl->addComplexType(
4225
    'results_editSession',
4226
    'complexType',
4227
    'array',
4228
    '',
4229
    'SOAP-ENC:Array',
4230
    [],
4231
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_editSession[]']],
4232
    'tns:result_editSession'
4233
);
4234
4235
4236
// Register the method to expose
4237
$server->register(
4238
    'WSEditSession', // method name
4239
    ['editSession' => 'tns:editSession'], // input parameters
4240
    ['return' => 'tns:results_editSession'], // output parameters
4241
    'urn:WSRegistration', // namespace
4242
    'urn:WSRegistration#WSEditSession', // soapaction
4243
    'rpc', // style
4244
    'encoded', // use
4245
    'This service edits a session'                // documentation
4246
);
4247
4248
// define the method WSEditSession
4249
function WSEditSession($params)
4250
{
4251
    if (!WSHelperVerifyKey($params)) {
4252
        return returnError(WS_ERROR_SECRET_KEY);
4253
    }
4254
4255
    $sessions_params = $params['sessions'];
4256
    $results = [];
4257
    $orig_session_id_value = [];
4258
    foreach ($sessions_params as $session_param) {
4259
        $name = trim($session_param['name']);
4260
        $year_start = intval($session_param['year_start']);
4261
        $month_start = intval($session_param['month_start']);
4262
        $day_start = intval($session_param['day_start']);
4263
        $year_end = intval($session_param['year_end']);
4264
        $month_end = intval($session_param['month_end']);
4265
        $day_end = intval($session_param['day_end']);
4266
        $nb_days_access_before = intval($session_param['nb_days_access_before']);
4267
        $nb_days_access_after = intval($session_param['nb_days_access_after']);
4268
        $original_session_id_value = $session_param['original_session_id_value'];
4269
        $original_session_id_name = $session_param['original_session_id_name'];
4270
        $orig_session_id_value[] = $original_session_id_value;
4271
        $coach_username = $session_param['coach_username'];
4272
        $nolimit = $session_param['nolimit'];
4273
        $id_coach = $session_param['user_id'];
4274
        $duration = intval($session_param['duration']);
4275
        $extra_list = $session_param['extra'];
4276
4277
        $id = SessionManager::getSessionIdFromOriginalId(
4278
            $original_session_id_value,
4279
            $original_session_id_name
4280
        );
4281
4282
        if (empty($id)) {
4283
            $results[] = 0;
4284
            continue;
4285
        }
4286
4287
        if (empty($nolimit)) {
4288
            $date_start = "$year_start-".(($month_start < 10) ? "0$month_start" : $month_start)."-".(($day_start < 10) ? "0$day_start" : $day_start).' 00:00:00';
4289
            $date_end = "$year_end-".(($month_end < 10) ? "0$month_end" : $month_end)."-".(($day_end < 10) ? "0$day_end" : $day_end).' 23:59:59';
4290
        } else {
4291
            $date_start = '';
4292
            $date_end = '';
4293
        }
4294
        if (empty($name)) {
4295
            $results[] = 0; //SessionNameIsRequired
4296
            continue;
4297
        } elseif (empty($id_coach)) { // Session must have coach
4298
            $results[] = 0;
4299
            continue;
4300
        } elseif (empty($nolimit) && (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start))) {
4301
            $results[] = 0; //InvalidStartDate
4302
            continue;
4303
        } elseif (empty($nolimit) && (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end))) {
4304
            $results[] = 0; //InvalidEndDate
4305
            continue;
4306
        } elseif (empty($nolimit) && $date_start >= $date_end) {
4307
            $results[] = 0; //StartDateShouldBeBeforeEndDate
4308
            continue;
4309
        } else {
4310
            $coachStartDate = '';
4311
            if ($date_start) {
4312
                $startDate = new DateTime($date_start);
4313
                $diffStart = new DateInterval("P".$nb_days_access_before."D");
4314
                $coachStartDate = $startDate->sub($diffStart);
4315
                $coachStartDate = $coachStartDate->format('Y-m-d H:i:s');
4316
            }
4317
            $coachEndDate = '';
4318
            if ($date_end) {
4319
                $endDate = new DateTime($date_end);
4320
                $diffEnd = new DateInterval("P".$nb_days_access_after."D");
4321
                $coachEndDate = $endDate->add($diffEnd);
4322
                $coachEndDate = $coachEndDate->format('Y-m-d H:i:s');
4323
            }
4324
            $sessionInfo = api_get_session_info($id);
4325
4326
            $editResult = SessionManager::edit_session(
4327
                $id,
4328
                $name,
4329
                $date_start,
4330
                $date_end,
4331
                $date_start,
4332
                $date_end,
4333
                $coachStartDate,
4334
                $coachEndDate,
4335
                $id_coach,
4336
                $sessionInfo['session_category_id'],
4337
                $sessionInfo['visibility'],
4338
                $sessionInfo['description'],
4339
                $sessionInfo['show_description'],
4340
                $duration,
4341
                null,
4342
                DEFAULT_ADMIN_USER_ID
4343
            );
4344
4345
            if (is_array($extra_list) && count($extra_list) > 0) {
4346
                foreach ($extra_list as $extra) {
4347
                    $extra_field_name = $extra['field_name'];
4348
                    $extra_field_value = $extra['field_value'];
4349
                    // Save the external system's id into session_field_value table.
4350
                    SessionManager::update_session_extra_field_value(
4351
                        $id,
4352
                        $extra_field_name,
4353
                        $extra_field_value
4354
                    );
4355
                }
4356
            }
4357
4358
            $results[] = $editResult ? 1 : 0;
4359
            continue;
4360
        }
4361
    } // end principal foreach
4362
4363
    $count_results = count($results);
4364
    $output = [];
4365
    for ($i = 0; $i < $count_results; $i++) {
4366
        $output[] = [
4367
            'original_session_id_value' => $orig_session_id_value[$i],
4368
            'result' => $results[$i],
4369
        ];
4370
    }
4371
4372
    return $output;
4373
}
4374
4375
/* Register WSDeleteSession function */
4376
$server->wsdl->addComplexType(
4377
    'deleteSessionParams',
4378
    'complexType',
4379
    'struct',
4380
    'all',
4381
    '',
4382
    [
4383
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
4384
        'original_session_id_name' => ['name' => 'original_session_id_name', 'type' => 'xsd:string']
4385
    ]
4386
);
4387
4388
$server->wsdl->addComplexType(
4389
    'deleteSessionParamsList',
4390
    'complexType',
4391
    'array',
4392
    '',
4393
    'SOAP-ENC:Array',
4394
    [],
4395
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:deleteSessionParams[]']],
4396
    'tns:deleteSessionParams'
4397
);
4398
4399
// Register the data structures used by the service
4400
$server->wsdl->addComplexType(
4401
    'deleteSession',
4402
    'complexType',
4403
    'struct',
4404
    'all',
4405
    '',
4406
    [
4407
        'sessions' => ['name' => 'sessions', 'type' => 'tns:deleteSessionParamsList'],
4408
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
4409
    ]
4410
);
4411
4412
// Prepare output params, in this case will return an array
4413
$server->wsdl->addComplexType(
4414
    'result_deleteSession',
4415
    'complexType',
4416
    'struct',
4417
    'all',
4418
    '',
4419
    [
4420
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
4421
        'result' => ['name' => 'result', 'type' => 'xsd:string']
4422
    ]
4423
);
4424
4425
$server->wsdl->addComplexType(
4426
    'results_deleteSession',
4427
    'complexType',
4428
    'array',
4429
    '',
4430
    'SOAP-ENC:Array',
4431
    [],
4432
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_deleteSession[]']],
4433
    'tns:result_deleteSession'
4434
);
4435
4436
$server->register(
4437
    'WSDeleteSession', // method name
4438
    ['deleteSession' => 'tns:deleteSession'], // input parameters
4439
    ['return' => 'tns:results_deleteSession'], // output parameters
4440
    'urn:WSRegistration', // namespace
4441
    'urn:WSRegistration#WSDeleteSession', // soapaction
4442
    'rpc', // style
4443
    'encoded', // use
4444
    'This service deletes a session '               // documentation
4445
);
4446
4447
// define the method WSDeleteSession
4448
function WSDeleteSession($params)
4449
{
4450
    if (!WSHelperVerifyKey($params)) {
4451
        return returnError(WS_ERROR_SECRET_KEY);
4452
    }
4453
4454
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
4455
    $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4456
    $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4457
    $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
4458
4459
    $session_params = $params['sessions'];
4460
    $results = [];
4461
    $orig_session_id_value = [];
4462
4463
    foreach ($session_params as $session_param) {
4464
        $original_session_id_value = $session_param['original_session_id_value'];
4465
        $original_session_id_name = $session_param['original_session_id_name'];
4466
        $orig_session_id_value[] = $original_session_id_name;
4467
4468
        $idChecked = SessionManager::getSessionIdFromOriginalId(
4469
            $original_session_id_value,
4470
            $original_session_id_name
4471
        );
4472
4473
        if (empty($idChecked)) {
4474
            $results[] = 0;
4475
            continue;
4476
        }
4477
4478
        $session_ids[] = $idChecked;
4479
4480
        $sql = "DELETE FROM $tbl_session WHERE id = '$idChecked'";
4481
        Database::query($sql);
4482
        $sql = "DELETE FROM $tbl_session_rel_course WHERE session_id = '$idChecked'";
4483
        Database::query($sql);
4484
        $sql = "DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id = '$idChecked'";
4485
        Database::query($sql);
4486
        $sql = "DELETE FROM $tbl_session_rel_user WHERE session_id = '$idChecked'";
4487
        Database::query($sql);
4488
        $results[] = 1;
4489
        continue;
4490
    }
4491
4492
    $extraFieldValue = new ExtraFieldValue('session');
4493
4494
    //delete from table_session_field_value from a given session_id
4495
    foreach ($session_ids as $session_id) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $session_ids does not seem to be defined for all execution paths leading up to this point.
Loading history...
4496
        $extraFieldValue->deleteValuesByItem($session_id);
4497
    }
4498
4499
    // Preparing output.
4500
    $count_results = count($results);
4501
    $output = [];
4502
    for ($i = 0; $i < $count_results; $i++) {
4503
        $output[] = [
4504
            'original_session_id_value' => $orig_session_id_value[$i],
4505
            'result' => $results[$i],
4506
        ];
4507
    }
4508
4509
    return $output;
4510
}
4511
4512
/** WSSubscribeUserToCourse **/
4513
// Register the data structures used by the service
4514
$server->wsdl->addComplexType(
4515
    'user_course_status',
4516
    'complexType',
4517
    'struct',
4518
    'all',
4519
    '',
4520
    [
4521
        'course_id' => ['name' => 'course_id', 'type' => 'tns:course_id'],
4522
        'user_id'   => ['name' => 'user_id', 'type' => 'tns:user_id'],
4523
        'status'    => ['name' => 'status', 'type' => 'xsd:int']
4524
    ]
4525
);
4526
4527
$server->wsdl->addComplexType(
4528
    'subscribeUserToCourse_arg',
4529
    'complexType',
4530
    'struct',
4531
    'all',
4532
    '',
4533
    [
4534
        'userscourses'  => ['name' => 'userscourses', 'type' => 'tns:user_course_status_array'], //removed []
4535
        'secret_key'    => ['name' => 'secret_key', 'type' => 'xsd:string']
4536
    ]
4537
);
4538
4539
$server->wsdl->addComplexType(
4540
    'user_course_status_array',
4541
    'complexType',
4542
    'array',
4543
    '',
4544
    'SOAP-ENC:Array',
4545
    [],
4546
    [
4547
        ['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:user_course_status[]']
4548
    ],
4549
    'tns:user_course_status'
4550
);
4551
4552
$server->wsdl->addComplexType(
4553
    'subscribeUserToCourse_return',
4554
    'complexType',
4555
    'struct',
4556
    'all',
4557
    '',
4558
    [
4559
        'original_user_id_value'    => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
4560
        'original_course_id_value'  => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
4561
        'result'                    => ['name' => 'result', 'type' => 'xsd:int']
4562
    ]
4563
);
4564
4565
$server->wsdl->addComplexType(
4566
    'subscribeUserToCourse_return_global',
4567
    'complexType',
4568
    'array',
4569
    '',
4570
    'SOAP-ENC:Array',
4571
    [],
4572
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:subscribeUserToCourse_return[]']],
4573
    'tns:subscribeUserToCourse_return'
4574
);
4575
4576
// Register the method to expose
4577
$server->register(
4578
    'WSSubscribeUserToCourse', // method name
4579
    ['subscribeUserToCourse' => 'tns:subscribeUserToCourse_arg'], // input parameters
4580
    ['return' => 'tns:subscribeUserToCourse_return_global'],
4581
    'urn:WSRegistration', // namespace
4582
    'urn:WSRegistration#WSSubscribeUserToCourse', // soapaction
4583
    'rpc', // style
4584
    'encoded', // use
4585
    'This service subscribes a user to a course'                        // documentation
4586
);
4587
4588
// define the method WSSubscribeUserToCourse
4589
function WSSubscribeUserToCourse($params)
4590
{
4591
    global $debug;
4592
    if (!WSHelperVerifyKey($params)) {
4593
        return returnError(WS_ERROR_SECRET_KEY);
4594
    }
4595
    if ($debug) {
4596
        error_log('WSSubscribeUserToCourse params: '.print_r($params, 1));
4597
    }
4598
4599
    $results = [];
4600
    $userscourses = $params['userscourses'];
4601
    foreach ($userscourses as $usercourse) {
4602
        $original_course_id = $usercourse['course_id'];
4603
        $original_user_id   = $usercourse['user_id'];
4604
        $status = STUDENT;
4605
        if ($usercourse['status']) {
4606
            $status = $usercourse['status'];
4607
        }
4608
4609
        $resultValue = 0;
4610
4611
        // Get user id
4612
        $user_id = UserManager::get_user_id_from_original_id(
4613
            $original_user_id['original_user_id_value'],
4614
            $original_user_id['original_user_id_name']
4615
        );
4616
        if ($debug) {
4617
            error_log('WSSubscribeUserToCourse user_id: '.$user_id);
4618
        }
4619
4620
        if ($user_id == 0) {
4621
            // If user was not found, there was a problem
4622
            $resultValue = 0;
4623
        } else {
4624
            // User was found
4625
            $courseInfo = CourseManager::getCourseInfoFromOriginalId(
4626
                $original_course_id['original_course_id_value'],
4627
                $original_course_id['original_course_id_name']
4628
            );
4629
4630
            $courseCode = isset($courseInfo['code']) ? $courseInfo['code'] : '';
4631
4632
            if (empty($courseCode)) {
4633
                // Course was not found
4634
                $resultValue = 0;
4635
            } else {
4636
                if ($debug) {
4637
                    error_log('WSSubscribeUserToCourse courseCode: '.$courseCode);
4638
                }
4639
                $result = CourseManager::add_user_to_course($user_id, $courseCode, $status, false);
4640
                if ($result) {
4641
                    $resultValue = 1;
4642
                    if ($debug) {
4643
                        error_log('WSSubscribeUserToCourse subscribed');
4644
                    }
4645
                } else {
4646
                    if ($debug) {
4647
                        error_log('WSSubscribeUserToCourse NOT subscribed: ');
4648
                    }
4649
                }
4650
            }
4651
        }
4652
4653
        $results[] = [
4654
            'original_user_id_value' => $original_user_id['original_user_id_value'],
4655
            'original_course_id_value' => $original_course_id['original_course_id_value'],
4656
            'result' => $resultValue
4657
        ];
4658
    }
4659
4660
    return $results;
4661
}
4662
4663
4664
/** WSSubscribeUserToCourse **/
4665
// Register the data structures used by the service
4666
$server->wsdl->addComplexType(
4667
    'subscribeUserToCourseSimple_arg',
4668
    'complexType',
4669
    'struct',
4670
    'all',
4671
    '',
4672
    [
4673
        'course'       => ['name' => 'course', 'type' => 'xsd:string'], //Course string code
4674
        'user_id'      => ['name' => 'user_id', 'type' => 'xsd:string'], //Chamilo user_id
4675
        'status'       => ['name' => 'status', 'type' => 'xsd:int'],
4676
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string']
4677
    ]
4678
);
4679
4680
4681
// Prepare output params, in this case will return an array
4682
$server->wsdl->addComplexType(
4683
    'Result',
4684
    'complexType',
4685
    'struct',
4686
    'all',
4687
    '',
4688
    ['message' => ['name' => 'message', 'type' => 'xsd:string']]
4689
);
4690
4691
4692
// Register the method to expose
4693
$server->register(
4694
    'WSSubscribeUserToCourseSimple', // method name
4695
    ['subscribeUserToCourseSimple' => 'tns:subscribeUserToCourseSimple_arg'], // input parameters
4696
    ['return' => 'xsd:string'], // output parameters
4697
    'urn:WSRegistration', // namespace
4698
    'urn:WSRegistration#WSSubscribeUserToCourseSimple', // soapaction
4699
    'rpc', // style
4700
    'encoded', // use
4701
    'This service subscribes a user to a course in a simple way'                   // documentation
4702
);
4703
4704
/**
4705
 * define the method WSSubscribeUserToCourse
4706
 * @param array $params
4707
 * @return array|int|null|soap_fault|string
4708
 */
4709
function WSSubscribeUserToCourseSimple($params)
4710
{
4711
    global $debug;
4712
4713
    if ($debug) {
4714
        error_log('WSSubscribeUserToCourseSimple');
4715
    }
4716
    if ($debug) {
4717
        error_log('Params '.print_r($params, 1));
4718
    }
4719
    if (!WSHelperVerifyKey($params)) {
4720
        return returnError(WS_ERROR_SECRET_KEY);
4721
    }
4722
    $result = [];
4723
    $course_code = $params['course']; //Course code
4724
    $user_id = $params['user_id']; //chamilo user id
4725
    $status = STUDENT;
4726
4727
    if (!empty($params['status'])) {
4728
        $status = $params['status'];
4729
    }
4730
    // Get user id
4731
    $user_data = api_get_user_info($user_id);
4732
4733
    if (empty($user_data)) {
4734
        // If user was not found, there was a problem
4735
        $result = "User $user_id does not exist";
4736
        if ($debug) {
4737
            error_log($result);
4738
        }
4739
        return $result;
4740
    }
4741
    if (!empty($course_code)) {
4742
        $course_data = api_get_course_info($course_code);
4743
        if (empty($course_data)) {
4744
            // Course was not found
4745
            $result = "Course $course_code does not exist in the platform ";
4746
            if ($debug) {
4747
                error_log($result);
4748
            }
4749
        } else {
4750
            if ($debug) {
4751
                error_log('Try to register: user_id= '.$user_id.' to course: '.$course_data['code']);
4752
            }
4753
            if (!CourseManager::add_user_to_course($user_id, $course_data['code'], $status)) {
4754
                $result = 'User was not registered possible reasons: User already registered to the course, Course visibility doesnt allow user subscriptions ';
4755
                if ($debug) {
4756
                    error_log($result);
4757
                }
4758
            } else {
4759
                if ($debug) {
4760
                    error_log('User registered to the course: '.$course_data['code']);
4761
                }
4762
                $result = 1;
4763
            }
4764
        }
4765
    }
4766
    return $result;
4767
}
4768
4769
/*   GetUser    */
4770
$server->wsdl->addComplexType(
4771
    'GetUserArg',
4772
    'complexType',
4773
    'struct',
4774
    'all',
4775
    '',
4776
    [
4777
        'original_user_id_value'      => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
4778
        'original_user_id_name'       => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
4779
        'secret_key'                  => ['name' => 'secret_key', 'type' => 'xsd:string']
4780
    ]
4781
);
4782
4783
// Prepare output params, in this case will return an array
4784
$server->wsdl->addComplexType(
4785
    'User',
4786
    'complexType',
4787
    'struct',
4788
    'all',
4789
    '',
4790
    [
4791
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
4792
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
4793
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
4794
    ]
4795
);
4796
4797
// Register the method to expose
4798
$server->register(
4799
    'WSGetUser', // method name
4800
    ['GetUser' => 'tns:GetUserArg'], // input parameters
4801
    ['return' => 'tns:User'], // output parameters
4802
    'urn:WSRegistration', // namespace
4803
    'urn:WSRegistration#WSGetUser', // soapaction
4804
    'rpc', // style
4805
    'encoded', // use
4806
    'This service get user information by id'    // documentation
4807
);
4808
4809
// define the method WSGetUser
4810
function WSGetUser($params)
4811
{
4812
    global $debug;
4813
    if ($debug) {
4814
        error_log('WSGetUser');
4815
    }
4816
    if ($debug) {
4817
        error_log('$params: '.print_r($params, 1));
4818
    }
4819
4820
    if (!WSHelperVerifyKey($params)) {
4821
        return returnError(WS_ERROR_SECRET_KEY);
4822
    }
4823
4824
    $result = [];
4825
4826
    // Get user id
4827
    $user_id = UserManager::get_user_id_from_original_id(
4828
        $params['original_user_id_value'],
4829
        $params['original_user_id_name']
4830
    );
4831
    $user_data = api_get_user_info($user_id);
4832
4833
    if (empty($user_data)) {
4834
        // If user was not found, there was a problem
4835
        $result['user_id'] = '';
4836
        $result['firstname'] = '';
4837
        $result['lastname'] = '';
4838
    } else {
4839
        $result['user_id'] = $user_data['user_id'];
4840
        $result['firstname'] = $user_data['firstname'];
4841
        $result['lastname'] = $user_data['lastname'];
4842
    }
4843
    return $result;
4844
}
4845
4846
$server->wsdl->addComplexType(
4847
    'GetUserArgUsername',
4848
    'complexType',
4849
    'struct',
4850
    'all',
4851
    '',
4852
    [
4853
        'username'      => ['name' => 'username', 'type' => 'xsd:string'],
4854
        'secret_key'    => ['name' => 'secret_key', 'type' => 'xsd:string']
4855
    ]
4856
);
4857
// Register the method to expose
4858
$server->register(
4859
    'WSGetUserFromUsername', // method name
4860
    ['GetUserFromUsername' => 'tns:GetUserArgUsername'], // input params
4861
    ['return' => 'tns:User'], // output parameters
4862
    'urn:WSRegistration', // namespace
4863
    'urn:WSRegistration#WSGetUserFromUsername', // soapaction
4864
    'rpc', // style
4865
    'encoded', // use
4866
    'This service get user information by username'            // documentation
4867
);
4868
4869
// define the method WSGetUserFromUsername
4870
function WSGetUserFromUsername($params)
4871
{
4872
    global $debug;
4873
    if ($debug) {
4874
        error_log('WSGetUserFromUsername');
4875
    }
4876
    if ($debug) {
4877
        error_log('$params: '.print_r($params, 1));
4878
    }
4879
4880
    if (!WSHelperVerifyKey($params)) {
4881
        return returnError(WS_ERROR_SECRET_KEY);
4882
    }
4883
4884
    $result = [];
4885
4886
    // Get user id
4887
    $user_data = api_get_user_info($params['username']);
4888
4889
    if (empty($user_data)) {
4890
        // If user was not found, there was a problem
4891
        $result['user_id']    = '';
4892
        $result['firstname']  = '';
4893
        $result['lastname']   = '';
4894
    } else {
4895
        $result['user_id']    = $user_data['user_id'];
4896
        $result['firstname']  = $user_data['firstname'];
4897
        $result['lastname']   = $user_data['lastname'];
4898
    }
4899
    return $result;
4900
}
4901
4902
/* Register WSUnsubscribeUserFromCourse function */
4903
// Register the data structures used by the service
4904
$server->wsdl->addComplexType(
4905
    'unsuscribeUserFromCourseParams',
4906
    'complexType',
4907
    'struct',
4908
    'all',
4909
    '',
4910
    [
4911
        'original_user_id_values'   => ['name' => 'original_user_id_values', 'type' => 'tns:originalUsersList'],
4912
        'original_user_id_name'     => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
4913
        'original_course_id_value'  => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
4914
        'original_course_id_name'   => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
4915
    ]
4916
);
4917
4918
$server->wsdl->addComplexType(
4919
    'unsuscribeUserFromCourseParamsList',
4920
    'complexType',
4921
    'array',
4922
    '',
4923
    'SOAP-ENC:Array',
4924
    [],
4925
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:unsuscribeUserFromCourseParams[]']],
4926
    'tns:unsuscribeUserFromCourseParams'
4927
);
4928
4929
$server->wsdl->addComplexType(
4930
    'unsuscribeUserFromCourse',
4931
    'complexType',
4932
    'struct',
4933
    'all',
4934
    '',
4935
    [
4936
        'userscourses' => ['name' => 'userscourses', 'type' => 'tns:unsuscribeUserFromCourseParamsList'],
4937
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
4938
    ]
4939
);
4940
4941
// Prepare output params, in this case will return an array
4942
$server->wsdl->addComplexType(
4943
    'result_unsuscribeUserFromCourse',
4944
    'complexType',
4945
    'struct',
4946
    'all',
4947
    '',
4948
    [
4949
        'original_user_id_values' => ['name' => 'original_user_id_values', 'type' => 'xsd:string'],
4950
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
4951
        'result' => ['name' => 'result', 'type' => 'xsd:string']
4952
    ]
4953
);
4954
4955
$server->wsdl->addComplexType(
4956
    'results_unsuscribeUserFromCourse',
4957
    'complexType',
4958
    'array',
4959
    '',
4960
    'SOAP-ENC:Array',
4961
    [],
4962
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_unsuscribeUserFromCourse[]']],
4963
    'tns:result_unsuscribeUserFromCourse'
4964
);
4965
4966
// Register the method to expose
4967
$server->register(
4968
    'WSUnsubscribeUserFromCourse', // method name
4969
    ['unsuscribeUserFromCourse' => 'tns:unsuscribeUserFromCourse'], // input parameters
4970
    ['return' => 'tns:results_unsuscribeUserFromCourse'], // output parameters
4971
    'urn:WSRegistration', // namespace
4972
    'urn:WSRegistration#WSUnsubscribeUserFromCourse', // soapaction
4973
    'rpc', // style
4974
    'encoded', // use
4975
    'This service unsubscribes a user from a course'                     // documentation
4976
);
4977
4978
// define the method WSUnsubscribeUserFromCourse
4979
function WSUnsubscribeUserFromCourse($params)
4980
{
4981
    if (!WSHelperVerifyKey($params)) {
4982
        return returnError(WS_ERROR_SECRET_KEY);
4983
    }
4984
4985
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
4986
    $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
4987
4988
    $userscourses_params = $params['userscourses'];
4989
    $results = [];
4990
    $orig_user_id_value = [];
4991
    $orig_course_id_value = [];
4992
    foreach ($userscourses_params as $usercourse_param) {
4993
        $original_user_id_values = $usercourse_param['original_user_id_values'];
4994
        $original_user_id_name = $usercourse_param['original_user_id_name'];
4995
        $original_course_id_value = $usercourse_param['original_course_id_value'];
4996
        $original_course_id_name = $usercourse_param['original_course_id_name'];
4997
        $orig_course_id_value[] = $original_course_id_value;
4998
4999
        // Get user id from original user id
5000
        $usersList = [];
5001
        foreach ($original_user_id_values as $key => $row_original_user_id) {
5002
            $user_id = UserManager::get_user_id_from_original_id(
5003
                $original_user_id_values[$key],
5004
                $original_user_id_name[$key]
5005
            );
5006
            if ($user_id == 0) {
5007
                continue; // user_id doesn't exist.
5008
            } else {
5009
                $sql = "SELECT user_id FROM $user_table WHERE user_id ='".$user_id."' AND active= '0'";
5010
                $resu = Database::query($sql);
5011
                $r_check_user = Database::fetch_row($resu);
5012
                if (!empty($r_check_user[0])) {
5013
                    continue; // user_id is not active.
5014
                }
5015
            }
5016
            $usersList[] = $user_id;
5017
        }
5018
5019
        $orig_user_id_value[] = implode(',', $usersList);
5020
5021
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
5022
            $original_course_id_value,
5023
            $original_course_id_name
5024
        );
5025
5026
        if (empty($courseInfo) ||
5027
            (isset($courseInfo) && $courseInfo['visibility'] == 0)
5028
        ) {
5029
            $results[] = 0;
5030
            continue; // Original_course_id_value doesn't exist.
5031
        }
5032
5033
        $courseId = $courseInfo['real_id'];
5034
5035
        if (count($usersList) == 0) {
5036
            $results[] = 0;
5037
            continue;
5038
        }
5039
5040
        foreach ($usersList as $user_id) {
5041
            $sql = "DELETE FROM $table_course_user
5042
                    WHERE user_id = '$user_id' AND c_id = '".$courseId."'";
5043
            $result = Database::query($sql);
5044
            Database::affected_rows($result);
5045
        }
5046
        $results[] = 1;
5047
        continue;
5048
    } // end principal foreach
5049
5050
    $count_results = count($results);
5051
    $output = [];
5052
    for ($i = 0; $i < $count_results; $i++) {
5053
        $output[] = [
5054
            'original_user_id_values' => $orig_user_id_value[$i],
5055
            'original_course_id_value' => $orig_course_id_value[$i],
5056
            'result' => $results[$i]
5057
        ];
5058
    }
5059
5060
    return $output;
5061
}
5062
5063
/* Register WSSuscribeUsersToSession function */
5064
$server->wsdl->addComplexType(
5065
    'unSubscribeUserFromCourseSimple',
5066
    'complexType',
5067
    'struct',
5068
    'all',
5069
    '',
5070
    [
5071
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
5072
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
5073
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
5074
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
5075
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5076
    ]
5077
);
5078
5079
$server->wsdl->addComplexType(
5080
    'unSubscribeUserToCourseSimple_return',
5081
    'complexType',
5082
    'struct',
5083
    'all',
5084
    '',
5085
    [
5086
        'original_user_id_value'    => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
5087
        'original_course_id_value'  => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
5088
        'result'                    => ['name' => 'result', 'type' => 'xsd:int']
5089
    ]
5090
);
5091
5092
// Register the method to expose
5093
$server->register(
5094
    'WSUnSubscribeUserFromCourseSimple', // method name
5095
    ['unSubscribeUserFromCourseSimple' => 'tns:unSubscribeUserFromCourseSimple'], // input parameters
5096
    ['return' => 'tns:unSubscribeUserToCourseSimple_return'], // output parameters
5097
    'urn:WSRegistration', // namespace
5098
    'urn:WSRegistration#WSUnSubscribeUserFromCourseSimple', // soapaction
5099
    'rpc', // style
5100
    'encoded', // use
5101
    'This service unsubscribe a user from a course'                     // documentation
5102
);
5103
5104
/**
5105
 * @param array $params
5106
 * @return array|null|soap_fault
5107
 */
5108
function WSUnSubscribeUserFromCourseSimple($params)
5109
{
5110
    global $debug;
5111
    error_log('WSUnSubscribeUserFromCourseSimple');
5112
    if (!WSHelperVerifyKey($params)) {
5113
        return returnError(WS_ERROR_SECRET_KEY);
5114
    }
5115
5116
    $original_user_id_value = $params['original_user_id_value'];
5117
    $original_user_id_name = $params['original_user_id_name'];
5118
    $original_course_id_value = $params['original_course_id_value'];
5119
    $original_course_id_name = $params['original_course_id_name'];
5120
5121
    $result = [];
5122
    $result['original_user_id_value'] = $original_user_id_value;
5123
    $result['original_course_id_value'] = $original_course_id_value;
5124
    $result['result'] = 0;
5125
5126
    $user_id = UserManager::get_user_id_from_original_id(
5127
        $original_user_id_value,
5128
        $original_user_id_name
5129
    );
5130
5131
    if ($user_id) {
5132
        if ($debug) {
5133
            error_log("User $original_user_id_value, $original_user_id_name found");
5134
            error_log("Course $original_course_id_value, $original_course_id_name found");
5135
        }
5136
5137
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
5138
            $original_course_id_value,
5139
            $original_course_id_name
5140
        );
5141
5142
        $courseCode = $courseInfo['code'];
5143
5144
        if (empty($courseCode)) {
5145
            // Course was not found
5146
            if ($debug) {
5147
                error_log("course not found");
5148
            }
5149
        } else {
5150
            if ($debug) {
5151
                error_log("Course $courseCode found");
5152
            }
5153
            CourseManager::unsubscribe_user($user_id, $courseCode, 0);
5154
            $result['result'] = 1;
5155
        }
5156
    } else {
5157
        if ($debug) {
5158
            error_log("User not found");
5159
        }
5160
    }
5161
5162
    return $result;
5163
}
5164
5165
$server->wsdl->addComplexType(
5166
    'subscribeUserToCourseParams',
5167
    'complexType',
5168
    'struct',
5169
    'all',
5170
    '',
5171
    [
5172
        'original_user_id_values'   => ['name' => 'original_user_id_values', 'type' => 'tns:originalUsersList'],
5173
        'original_user_id_name'     => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
5174
        'original_course_id_value'  => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
5175
        'original_course_id_name'   => ['name' => 'original_course_id_value', 'type' => 'xsd:string']
5176
    ]
5177
);
5178
5179
5180
// Prepare output params, in this case will return an array.
5181
$server->wsdl->addComplexType(
5182
    'result_subscribeUsersToSession',
5183
    'complexType',
5184
    'struct',
5185
    'all',
5186
    '',
5187
    [
5188
        'original_user_id_values' => ['name' => 'original_user_id_values', 'type' => 'xsd:string'],
5189
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5190
        'result' => ['name' => 'result', 'type' => 'xsd:string']
5191
    ]
5192
);
5193
5194
$server->wsdl->addComplexType(
5195
    'results_subscribeUsersToSession',
5196
    'complexType',
5197
    'array',
5198
    '',
5199
    'SOAP-ENC:Array',
5200
    [],
5201
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_subscribeUsersToSession[]']],
5202
    'tns:result_subscribeUsersToSession'
5203
);
5204
5205
$server->wsdl->addComplexType(
5206
    'originalUserItem',
5207
    'complexType',
5208
    'struct',
5209
    'all',
5210
    '',
5211
    [
5212
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string']
5213
    ]
5214
);
5215
5216
// Register the data structures used by the service
5217
$server->wsdl->addComplexType(
5218
    'originalUsersList',
5219
    'complexType',
5220
    'array',
5221
    '',
5222
    'SOAP-ENC:Array',
5223
    [],
5224
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:originalUserItem[]']],
5225
    'tns:originalUserItem'
5226
);
5227
5228
/* Register WSSuscribeUsersToSession function */
5229
// Register the data structures used by the service
5230
$server->wsdl->addComplexType(
5231
    'subscribeUsersToSessionParams',
5232
    'complexType',
5233
    'struct',
5234
    'all',
5235
    '',
5236
    [
5237
        'original_user_id_values' => ['name' => 'original_user_id_values', 'type' => 'tns:originalUsersList'],
5238
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
5239
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5240
        'original_session_id_name' => ['name' => 'original_session_id_name', 'type' => 'xsd:string']
5241
    ]
5242
);
5243
5244
$server->wsdl->addComplexType(
5245
    'subscribeUsersToSessionParamsList',
5246
    'complexType',
5247
    'array',
5248
    '',
5249
    'SOAP-ENC:Array',
5250
    [],
5251
    [
5252
        [
5253
            'ref' => 'SOAP-ENC:arrayType',
5254
            'wsdl:arrayType' => 'tns:subscribeUsersToSessionParams[]',
5255
        ],
5256
    ],
5257
    'tns:subscribeUsersToSessionParams'
5258
);
5259
5260
$server->wsdl->addComplexType(
5261
    'subscribeUsersToSession',
5262
    'complexType',
5263
    'struct',
5264
    'all',
5265
    '',
5266
    [
5267
        'userssessions' => ['name' => 'userssessions', 'type' => 'tns:subscribeUsersToSessionParamsList'],
5268
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5269
    ]
5270
);
5271
5272
// Register the method to expose
5273
$server->register(
5274
    'WSSuscribeUsersToSession', // method name
5275
    ['subscribeUsersToSession' => 'tns:subscribeUsersToSession'], // input parameters
5276
    ['return' => 'tns:results_subscribeUsersToSession'], // output parameters
5277
    'urn:WSRegistration', // namespace
5278
    'urn:WSRegistration#WSSuscribeUsersToSession', // soapaction
5279
    'rpc', // style
5280
    'encoded', // use
5281
    'This service subscribes a user to a session'                      // documentation
5282
);
5283
5284
// define the method WSSuscribeUsersToSession
5285
function WSSuscribeUsersToSession($params)
5286
{
5287
    global $debug;
5288
5289
    if (!WSHelperVerifyKey($params)) {
5290
        return returnError(WS_ERROR_SECRET_KEY);
5291
    }
5292
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
5293
    $userssessions_params = $params['userssessions'];
5294
5295
    if ($debug) {
5296
        error_log('WSSuscribeUsersToSession');
5297
        error_log(print_r($params, 1));
5298
5299
        if (empty($userssessions_params)) {
5300
            error_log('userssessions is empty');
5301
        }
5302
    }
5303
5304
    $results = [];
5305
    $orig_user_id_value = [];
5306
    $orig_session_id_value = [];
5307
    foreach ($userssessions_params as $usersession_params) {
5308
        $original_session_id_value = $usersession_params['original_session_id_value'];
5309
        $original_session_id_name = $usersession_params['original_session_id_name'];
5310
        $original_user_id_name = $usersession_params['original_user_id_name'];
5311
        $original_user_id_values = $usersession_params['original_user_id_values'];
5312
5313
        $sessionId = SessionManager::getSessionIdFromOriginalId(
5314
            $original_session_id_value,
5315
            $original_session_id_name
5316
        );
5317
5318
        if (empty($sessionId)) {
5319
            $orig_session_id_value[] = $original_session_id_value;
5320
            $results[] = 0;
5321
            continue;
5322
        }
5323
5324
        foreach ($original_user_id_values as $key => $row_original_user_list) {
5325
            $orig_session_id_value[] = $original_session_id_value;
5326
            $orig_user_id_value[] = $row_original_user_list['original_user_id_value'];
5327
5328
            $user_id = UserManager::get_user_id_from_original_id(
5329
                $row_original_user_list['original_user_id_value'],
5330
                $original_user_id_name
5331
            );
5332
5333
            if ($debug) {
5334
                error_log("User to subscribe: $user_id");
5335
            }
5336
5337
            if ($user_id == 0) {
5338
                $results[] = 0;
5339
                continue; // user_id doesn't exist.
5340
            } else {
5341
                $sql = "SELECT user_id FROM $user_table
5342
                        WHERE user_id ='".$user_id."' AND active= '0'";
5343
                $resu = Database::query($sql);
5344
                $r_check_user = Database::fetch_row($resu);
5345
                if (!empty($r_check_user[0])) {
5346
                    $results[] = 0;
5347
                    continue; // user_id is not active.
5348
                }
5349
5350
                SessionManager::subscribe_users_to_session(
5351
                    $sessionId,
5352
                    [$user_id],
5353
                    SESSION_VISIBLE_READ_ONLY,
5354
                    false
5355
                );
5356
                $results[] = 1;
5357
5358
                if ($debug) {
5359
                    error_log("subscribe user:$user_id to session $sessionId");
5360
                }
5361
            }
5362
        }
5363
    } // end principal foreach
5364
5365
    $count_results = count($results);
5366
    $output = [];
5367
    for ($i = 0; $i < $count_results; $i++) {
5368
        $output[] = [
5369
            'original_user_id_values' => $orig_user_id_value[$i],
5370
            'original_session_id_value' => $orig_session_id_value[$i],
5371
            'result' => $results[$i]
5372
        ];
5373
    }
5374
5375
    return $output;
5376
}
5377
5378
// WSSubscribeUserToSessionSimple
5379
$server->wsdl->addComplexType(
5380
    'subscribeUserToSessionSimple_arg',
5381
    'complexType',
5382
    'struct',
5383
    'all',
5384
    '',
5385
    [
5386
        'session'    => ['name' => 'session', 'type' => 'xsd:string'], // Session ID
5387
        'user_id'    => ['name' => 'user_id', 'type' => 'xsd:string'], // Chamilo user_id
5388
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5389
    ]
5390
);
5391
5392
$server->register(
5393
    'WSSubscribeUserToSessionSimple', // method name
5394
    ['subscribeUserToSessionSimple' => 'tns:subscribeUserToSessionSimple_arg'], // input parameters
5395
    ['return' => 'xsd:string'], // output parameters
5396
    'urn:WSRegistration', // namespace
5397
    'urn:WSRegistration#WSSubscribeUserToSessionSimple', // soapaction
5398
    'rpc', // style
5399
    'encoded', // use
5400
    'This service subscribes a user to a session in a simple way'                     // documentation
5401
);
5402
5403
/**
5404
 * @param array $params
5405
 * @return int|null|soap_fault|string
5406
 */
5407
function WSSubscribeUserToSessionSimple($params)
5408
{
5409
    global $debug;
5410
5411
    if ($debug) {
5412
        error_log('WSSubscribeUserToSessionSimple with params=['.serialize($params).']');
5413
    }
5414
5415
    // Check security key
5416
    if (!WSHelperVerifyKey($params)) {
5417
        return returnError(WS_ERROR_SECRET_KEY);
5418
    }
5419
5420
    // Get input parameters
5421
    $session_id = intval($params['session']); // Session ID
5422
    $user_id    = intval($params['user_id']); // Chamilo user id
5423
5424
    // Get user id
5425
    $user_data = api_get_user_info($user_id);
5426
5427
    // Prepare answer
5428
    $result = 0;
5429
5430
    if (empty($user_data)) {
5431
        $result = "User {$user_id} does not exist";
5432
        if ($debug) {
5433
            error_log($result);
5434
        }
5435
        return $result;
5436
    }
5437
    if (!empty($session_id) && is_numeric($session_id)) {
5438
        $session_data = api_get_session_info($session_id);
5439
        if (empty($session_data)) {
5440
            $result = "Session {$session_id} does not exist.";
5441
            if ($debug) {
5442
                error_log($result);
5443
            }
5444
        } else {
5445
            SessionManager::subscribe_users_to_session(
5446
                $session_id,
5447
                [$user_id],
5448
                SESSION_VISIBLE_READ_ONLY,
5449
                false
5450
            );
5451
            if ($debug) {
5452
                error_log('User registered to the course: '.$session_id);
5453
            }
5454
            $result = 1;
5455
        }
5456
    }
5457
    return $result;
5458
}
5459
5460
/* Register WSUnsuscribeUsersFromSession function */
5461
// Register the data structures used by the service
5462
$server->wsdl->addComplexType(
5463
    'unsubscribeUsersFromSessionParams',
5464
    'complexType',
5465
    'struct',
5466
    'all',
5467
    '',
5468
    [
5469
        'original_user_id_values'   => ['name' => 'original_user_id_values', 'type' => 'tns:originalUsersList'],
5470
        'original_user_id_name'     => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
5471
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5472
        'original_session_id_name'  => ['name' => 'original_session_id_name', 'type' => 'xsd:string']
5473
    ]
5474
);
5475
5476
$server->wsdl->addComplexType(
5477
    'unsubscribeUsersFromSessionParamsList',
5478
    'complexType',
5479
    'array',
5480
    '',
5481
    'SOAP-ENC:Array',
5482
    [],
5483
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:unsubscribeUsersFromSessionParams[]']],
5484
    'tns:unsubscribeUsersFromSessionParams'
5485
);
5486
5487
$server->wsdl->addComplexType(
5488
    'unsubscribeUsersFromSession',
5489
    'complexType',
5490
    'struct',
5491
    'all',
5492
    '',
5493
    [
5494
        'userssessions' => ['name' => 'userssessions', 'type' => 'tns:subscribeUsersToSessionParamsList'],
5495
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5496
    ]
5497
);
5498
5499
// Prepare output params, in this case will return an array
5500
$server->wsdl->addComplexType(
5501
    'result_unsubscribeUsersFromSession',
5502
    'complexType',
5503
    'struct',
5504
    'all',
5505
    '',
5506
    [
5507
        'original_user_id_values' => ['name' => 'original_user_id_values', 'type' => 'xsd:string'],
5508
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5509
        'result' => ['name' => 'result', 'type' => 'xsd:string']
5510
    ]
5511
);
5512
5513
$server->wsdl->addComplexType(
5514
    'results_unsubscribeUsersFromSession',
5515
    'complexType',
5516
    'array',
5517
    '',
5518
    'SOAP-ENC:Array',
5519
    [],
5520
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_unsubscribeUsersFromSession[]']],
5521
    'tns:result_unsubscribeUsersFromSession'
5522
);
5523
5524
// Register the method to expose
5525
$server->register(
5526
    'WSUnsuscribeUsersFromSession', // method name
5527
    ['unsubscribeUsersFromSession' => 'tns:unsubscribeUsersFromSession'], // input parameters
5528
    ['return' => 'tns:results_unsubscribeUsersFromSession'], // output parameters
5529
    'urn:WSRegistration', // namespace
5530
    'urn:WSRegistration#WSUnsuscribeUsersFromSession', // soapaction
5531
    'rpc', // style
5532
    'encoded', // use
5533
    'This service unsubscribes a user to a session'                            // documentation
5534
);
5535
5536
// define the method WSUnsuscribeUsersFromSession
5537
function WSUnsuscribeUsersFromSession($params)
5538
{
5539
    if (!WSHelperVerifyKey($params)) {
5540
        return returnError(WS_ERROR_SECRET_KEY);
5541
    }
5542
5543
    global $debug;
5544
5545
    if ($debug) {
5546
        error_log('WSUnsuscribeUsersFromSession with params=['.serialize($params).']');
5547
    }
5548
5549
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
5550
5551
    $userssessions_params = $params['userssessions'];
5552
    $results = [];
5553
    $orig_user_id_value = [];
5554
    $orig_session_id_value = [];
5555
5556
    foreach ($userssessions_params as $usersession_params) {
5557
        $original_session_id_value = $usersession_params['original_session_id_value'];
5558
        $original_session_id_name = $usersession_params['original_session_id_name'];
5559
        $original_user_id_name = $usersession_params['original_user_id_name'];
5560
        $original_user_id_values = $usersession_params['original_user_id_values'];
5561
5562
        $id_session = SessionManager::getSessionIdFromOriginalId(
5563
            $original_session_id_value,
5564
            $original_session_id_name
5565
        );
5566
5567
        if (empty($id_session)) {
5568
            $orig_session_id_value[] = $original_session_id_value;
5569
            $results[] = 0;
5570
            continue;
5571
        }
5572
5573
        foreach ($original_user_id_values as $key => $row_original_user_list) {
5574
            $orig_session_id_value[] = $original_session_id_value;
5575
            $orig_user_id_value[] = $row_original_user_list['original_user_id_value'];
5576
            $user_id = UserManager::get_user_id_from_original_id(
5577
                $row_original_user_list['original_user_id_value'],
5578
                $original_user_id_name
5579
            );
5580
5581
            if ($user_id == 0) {
5582
                $results[] = 0;
5583
                continue; // user_id doesn't exist.
5584
            } else {
5585
                $sql = "SELECT user_id FROM $user_table
5586
                        WHERE user_id ='".$user_id."' AND active= '0'";
5587
                $resu = Database::query($sql);
5588
                $r_check_user = Database::fetch_row($resu);
5589
                if (!empty($r_check_user[0])) {
5590
                    $results[] = 0;
5591
                    continue; // user_id is not active.
5592
                }
5593
5594
                SessionManager::unsubscribe_user_from_session(
5595
                    $id_session,
5596
                    $user_id
5597
                );
5598
5599
                $results[] = 1;
5600
5601
                if ($debug) {
5602
                    error_log("Unsubscribe user:$user_id to session:$id_session");
5603
                }
5604
            }
5605
        }
5606
    } // end principal foreach
5607
5608
    $count_results = count($results);
5609
    $output = [];
5610
    for ($i = 0; $i < $count_results; $i++) {
5611
        $output[] = [
5612
            'original_user_id_values' => $orig_user_id_value[$i],
5613
            'original_session_id_value' => $orig_session_id_value[$i],
5614
            'result' => $results[$i]
5615
        ];
5616
    }
5617
5618
    return $output;
5619
}
5620
5621
/* Register WSSuscribeCoursesToSession function */
5622
// Register the data structures used by the service
5623
5624
/*$server->wsdl->addComplexType(
5625
'originalCoursesList',
5626
'complexType',
5627
'array',
5628
'',
5629
'SOAP-ENC:Array',
5630
array(),
5631
array(array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'string[]')),
5632
'xsd:string'
5633
);*/
5634
$server->wsdl->addComplexType(
5635
    'course_code_type',
5636
    'complexType',
5637
    'struct',
5638
    'all',
5639
    '',
5640
    [
5641
        'course_code'   => ['name' => 'course_code', 'type' => 'xsd:string'],
5642
    ]
5643
);
5644
5645
$server->wsdl->addComplexType(
5646
    'originalCoursesList',
5647
    'complexType',
5648
    'array',
5649
    '',
5650
    'SOAP-ENC:Array',
5651
    [],
5652
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:course_code_type[]']],
5653
    'tns:course_code_type'
5654
);
5655
5656
5657
$server->wsdl->addComplexType(
5658
    'subscribeCoursesToSessionParamsList',
5659
    'complexType',
5660
    'array',
5661
    '',
5662
    'SOAP-ENC:Array',
5663
    [],
5664
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:subscribeCoursesToSessionParams[]']],
5665
    'tns:subscribeCoursesToSessionParams'
5666
);
5667
5668
$server->wsdl->addComplexType(
5669
    'subscribeCoursesToSessionParams',
5670
    'complexType',
5671
    'struct',
5672
    'all',
5673
    '',
5674
    [
5675
        'original_course_id_values' => ['name' => 'original_course_id_values', 'type' => 'tns:originalCoursesList'],
5676
        'original_course_id_name'   => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
5677
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5678
        'original_session_id_name'  => ['name' => 'original_session_id_name', 'type' => 'xsd:string']
5679
    ]
5680
);
5681
5682
$server->wsdl->addComplexType(
5683
    'subscribeCoursesToSessionParamsList',
5684
    'complexType',
5685
    'array',
5686
    '',
5687
    'SOAP-ENC:Array',
5688
    [],
5689
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:subscribeCoursesToSessionParams[]']],
5690
    'tns:subscribeCoursesToSessionParams'
5691
);
5692
5693
$server->wsdl->addComplexType(
5694
    'subscribeCoursesToSession',
5695
    'complexType',
5696
    'struct',
5697
    'all',
5698
    '',
5699
    [
5700
        'coursessessions' => ['name' => 'coursessessions', 'type' => 'tns:subscribeCoursesToSessionParamsList'],
5701
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5702
    ]
5703
);
5704
5705
// Prepare output params, in this case will return an array
5706
$server->wsdl->addComplexType(
5707
    'result_subscribeCoursesToSession',
5708
    'complexType',
5709
    'struct',
5710
    'all',
5711
    '',
5712
    [
5713
        'original_course_id_values' => ['name' => 'original_course_id_values', 'type' => 'xsd:string'],
5714
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5715
        'result' => ['name' => 'result', 'type' => 'xsd:string']
5716
    ]
5717
);
5718
5719
$server->wsdl->addComplexType(
5720
    'results_subscribeCoursesToSession',
5721
    'complexType',
5722
    'array',
5723
    '',
5724
    'SOAP-ENC:Array',
5725
    [],
5726
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_subscribeCoursesToSession[]']],
5727
    'tns:result_subscribeCoursesToSession'
5728
);
5729
5730
// Register the method to expose
5731
$server->register(
5732
    'WSSuscribeCoursesToSession', // method name
5733
    ['subscribeCoursesToSession' => 'tns:subscribeCoursesToSession'], // input parameters
5734
    ['return' => 'tns:results_subscribeCoursesToSession'], // output parameters
5735
    'urn:WSRegistration', // namespace
5736
    'urn:WSRegistration#WSSuscribeCoursesToSession', // soapaction
5737
    'rpc', // style
5738
    'encoded', // use
5739
    'This service subscribes a course to a session'                        // documentation
5740
);
5741
5742
// Define the method WSSuscribeCoursesToSession
5743
function WSSuscribeCoursesToSession($params)
5744
{
5745
    global $debug;
5746
5747
    if (!WSHelperVerifyKey($params)) {
5748
        return returnError(WS_ERROR_SECRET_KEY);
5749
    }
5750
5751
    if ($debug) {
5752
        error_log('WSSuscribeCoursesToSession: '.print_r($params, 1));
5753
    }
5754
5755
    $coursessessions_params = $params['coursessessions'];
5756
    $results = [];
5757
    $orig_course_id_value = [];
5758
    $orig_session_id_value = [];
5759
    foreach ($coursessessions_params as $coursesession_param) {
5760
        $original_session_id_value = $coursesession_param['original_session_id_value'];
5761
        $original_session_id_name = $coursesession_param['original_session_id_name'];
5762
        $original_course_id_name = $coursesession_param['original_course_id_name'];
5763
        $original_course_id_values = $coursesession_param['original_course_id_values'];
5764
5765
        $sessionId = SessionManager::getSessionIdFromOriginalId(
5766
            $original_session_id_value,
5767
            $original_session_id_name
5768
        );
5769
5770
        if (empty($sessionId)) {
5771
            $orig_session_id_value[] = $original_session_id_value;
5772
            $results[] = 0;
5773
            continue;
5774
        }
5775
5776
        // Get course list from row_original_course_id_values
5777
        foreach ($original_course_id_values as $row_original_course_list) {
5778
            $orig_session_id_value[] = $original_session_id_value;
5779
            $orig_course_id_value[] = $row_original_course_list['course_code'];
5780
5781
            $courseInfo = CourseManager::getCourseInfoFromOriginalId(
5782
                $row_original_course_list['course_code'],
5783
                $original_course_id_name
5784
            );
5785
5786
            if (empty($courseInfo) ||
5787
                (isset($courseInfo) && $courseInfo['visibility'] == 0)
5788
            ) {
5789
                $results[] = 0;
5790
                continue; // Original_course_id_value doesn't exist.
5791
            } else {
5792
                $courseCode = $courseInfo['code'];
5793
                SessionManager::add_courses_to_session(
5794
                    $sessionId,
5795
                    [$courseInfo['real_id']],
5796
                    false
5797
                );
5798
                if ($debug) {
5799
                    error_log("add_courses_to_session: course:$courseCode to session:$sessionId");
5800
                }
5801
5802
                $results[] = 1;
5803
            }
5804
        }
5805
    }
5806
5807
    $count_results = count($results);
5808
    $output = [];
5809
    for ($i = 0; $i < $count_results; $i++) {
5810
        $output[] = [
5811
            'original_course_id_values' => $orig_course_id_value[$i],
5812
            'original_session_id_value' => $orig_session_id_value[$i],
5813
            'result' => $results[$i]
5814
        ];
5815
    }
5816
5817
    return $output;
5818
}
5819
5820
/* Register WSUnsuscribeCoursesFromSession function */
5821
// Register the data structures used by the service
5822
$server->wsdl->addComplexType(
5823
    'unsubscribeCoursesFromSessionParams',
5824
    'complexType',
5825
    'struct',
5826
    'all',
5827
    '',
5828
    [
5829
        'original_course_id_values' => ['name' => 'original_course_id_values', 'type' => 'tns:originalCoursesList'],
5830
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
5831
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5832
        'original_session_id_name' => ['name' => 'original_session_id_name', 'type' => 'xsd:string']
5833
    ]
5834
);
5835
5836
$server->wsdl->addComplexType(
5837
    'unsubscribeCoursesFromSessionParamsList',
5838
    'complexType',
5839
    'array',
5840
    '',
5841
    'SOAP-ENC:Array',
5842
    [],
5843
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:unsubscribeCoursesFromSessionParams[]']],
5844
    'tns:unsubscribeCoursesFromSessionParams'
5845
);
5846
5847
$server->wsdl->addComplexType(
5848
    'unsubscribeCoursesFromSession',
5849
    'complexType',
5850
    'struct',
5851
    'all',
5852
    '',
5853
    [
5854
        'coursessessions' => ['name' => 'coursessessions', 'type' => 'tns:unsubscribeCoursesFromSessionParamsList'],
5855
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5856
    ]
5857
);
5858
5859
// Prepare output params, in this case will return an array
5860
$server->wsdl->addComplexType(
5861
    'result_unsubscribeCoursesFromSession',
5862
    'complexType',
5863
    'struct',
5864
    'all',
5865
    '',
5866
    [
5867
        'original_course_id_values' => ['name' => 'original_course_id_values', 'type' => 'xsd:string'],
5868
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5869
        'result' => ['name' => 'result', 'type' => 'xsd:string']
5870
    ]
5871
);
5872
5873
$server->wsdl->addComplexType(
5874
    'results_unsubscribeCoursesFromSession',
5875
    'complexType',
5876
    'array',
5877
    '',
5878
    'SOAP-ENC:Array',
5879
    [],
5880
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_unsubscribeCoursesFromSession[]']],
5881
    'tns:result_unsubscribeCoursesFromSession'
5882
);
5883
5884
5885
// Register the method to expose
5886
$server->register(
5887
    'WSUnsuscribeCoursesFromSession', // method name
5888
    ['unsubscribeCoursesFromSession' => 'tns:unsubscribeCoursesFromSession'], // input parameters
5889
    ['return' => 'tns:results_unsubscribeCoursesFromSession'], // output parameters
5890
    'urn:WSRegistration', // namespace
5891
    'urn:WSRegistration#WSUnsuscribeCoursesFromSession', // soapaction
5892
    'rpc', // style
5893
    'encoded', // use
5894
    'This service subscribes a course to a session'                                // documentation
5895
);
5896
5897
// define the method WSUnsuscribeCoursesFromSession
5898
function WSUnsuscribeCoursesFromSession($params)
5899
{
5900
    if (!WSHelperVerifyKey($params)) {
5901
        return returnError(WS_ERROR_SECRET_KEY);
5902
    }
5903
5904
    $sessionAdminId = DEFAULT_ADMIN_USER_ID;
5905
5906
    // Initialisation
5907
    $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5908
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
5909
    $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
5910
    $coursessessions_params = $params['coursessessions'];
5911
    $results = [];
5912
    $orig_course_id_value = [];
5913
    $orig_session_id_value = [];
5914
5915
    foreach ($coursessessions_params as $coursesession_param) {
5916
        $original_session_id_value = $coursesession_param['original_session_id_value'];
5917
        $original_session_id_name = $coursesession_param['original_session_id_name'];
5918
        $original_course_id_name = $coursesession_param['original_course_id_name'];
5919
        $original_course_id_values = $coursesession_param['original_course_id_values'];
5920
        $orig_session_id_value[] = $original_session_id_value;
5921
5922
        $id_session = SessionManager::getSessionIdFromOriginalId(
5923
            $original_session_id_value,
5924
            $original_session_id_name
5925
        );
5926
5927
        if (empty($id_session)) {
5928
            $results[] = 0;
5929
            continue;
5930
        }
5931
5932
        // Get courses list from row_original_course_id_values
5933
        $course_list = [];
5934
        $courseIdList = [];
5935
        foreach ($original_course_id_values as $row_original_course_list) {
5936
            $course_code = Database::escape_string($row_original_course_list['course_code']);
5937
5938
            // Check whether exits $x_course_code into user_field_values table.
5939
            $courseInfo = CourseManager::getCourseInfoFromOriginalId(
5940
                $row_original_course_list['course_code'],
5941
                $original_course_id_name
5942
            );
5943
5944
            if (empty($courseInfo) || isset($courseInfo) &&
5945
                $courseInfo['visibility'] == 0
5946
            ) {
5947
                continue; // Course_code doesn't exist'
5948
            }
5949
5950
            $course_list[] = $courseInfo['code'];
5951
            $courseIdList[] = $courseInfo['real_id'];
5952
        }
5953
5954
        if (empty($course_list)) {
5955
            $results[] = 0;
5956
            continue;
5957
        }
5958
5959
        $orig_course_id_value[] = implode(',', $course_list);
5960
5961
        foreach ($courseIdList as $courseId) {
5962
            $courseId = intval($courseId);
5963
            Database::query("DELETE FROM $tbl_session_rel_course
5964
                            WHERE c_id ='$courseId' AND session_id='$id_session'");
5965
            $result = Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE c_id='$courseId' AND session_id = '$id_session'");
5966
5967
            Event::addEvent(
5968
                LOG_SESSION_DELETE_COURSE,
5969
                LOG_COURSE_ID,
5970
                $courseId,
5971
                api_get_utc_datetime(),
5972
                $sessionAdminId,
5973
                $courseId,
5974
                $id_session
5975
            );
5976
5977
            $return = Database::affected_rows($result);
5978
        }
5979
5980
        $nbr_courses = 0;
5981
        $sql = "SELECT nbr_courses FROM $tbl_session WHERE id = '$id_session'";
5982
        $res_nbr_courses = Database::query($sql);
5983
        $row_nbr_courses = Database::fetch_row($res_nbr_courses);
5984
5985
        if (Database::num_rows($res_nbr_courses) > 0) {
5986
            $nbr_users = ($row_nbr_courses[0] - $return);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $return does not seem to be defined for all execution paths leading up to this point.
Loading history...
5987
        }
5988
5989
        // Update number of users in the session.
5990
        $update_sql = "UPDATE $tbl_session SET nbr_courses= $nbr_courses WHERE id='$id_session' ";
5991
        Database::query($update_sql);
5992
5993
        $results[] = 1;
5994
        continue;
5995
    }
5996
5997
    $count_results = count($results);
5998
    $output = [];
5999
    for ($i = 0; $i < $count_results; $i++) {
6000
        $output[] = [
6001
            'original_course_id_values' => $orig_course_id_value[$i],
6002
            'original_session_id_value' => $orig_session_id_value[$i],
6003
            'result' => $results[$i],
6004
        ];
6005
    }
6006
6007
    return $output;
6008
}
6009
6010
/** WSListCourses **/
6011
6012
$server->wsdl->addComplexType(
6013
    'listCourseInput',
6014
    'complexType',
6015
    'struct',
6016
    'all',
6017
    '',
6018
    [
6019
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
6020
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
6021
        'from' => ['name' => 'from', 'type' => 'xsd:int'],
6022
        'to' => ['name' => 'to', 'type' => 'xsd:int']
6023
    ]
6024
);
6025
6026
$server->wsdl->addComplexType(
6027
    'course',
6028
    'complexType',
6029
    'struct',
6030
    'all',
6031
    '',
6032
    [
6033
        'id' => ['name' => 'id', 'type' => 'xsd:int'],
6034
        'code' => ['name' => 'code', 'type' => 'xsd:string'],
6035
        'external_course_id' => ['name' => 'external_course_id', 'type' => 'xsd:string'],
6036
        'title' => ['name' => 'title', 'type' => 'xsd:string'],
6037
        'language' => ['name' => 'language', 'type' => 'xsd:string'],
6038
        'category_name' => ['name' => 'category_name', 'type' => 'xsd:string'],
6039
        'visibility' => ['name' => 'visibility', 'type' => 'xsd:int'],
6040
        'number_students' => ['name' => 'number_students', 'type' => 'xsd:int']
6041
    ]
6042
);
6043
6044
$server->wsdl->addComplexType(
6045
    'courses',
6046
    'complexType',
6047
    'array',
6048
    '',
6049
    'SOAP-ENC:Array',
6050
    [],
6051
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:course[]']],
6052
    'tns:course'
6053
);
6054
6055
6056
// Register the method to expose
6057
$server->register(
6058
    'WSListCourses', // method name
6059
    ['listCourseInput' => 'tns:listCourseInput'], // input parameters
6060
    ['return' => 'tns:courses'], // output parameters
6061
    'urn:WSRegistration', // namespace
6062
    'urn:WSRegistration#WSListCourses', // soapaction
6063
    'rpc', // style
6064
    'encoded', // use
6065
    'This service list courses available on the system'                             // documentation
6066
);
6067
6068
// define the method WSListCourses
6069
function WSListCourses($params)
6070
{
6071
    global $debug;
6072
    if (!WSHelperVerifyKey($params)) {
6073
        return returnError(WS_ERROR_SECRET_KEY);
6074
    }
6075
6076
    $course_field_name = isset($params['original_course_id_name']) ? $params['original_course_id_name'] : '';
6077
6078
    $courses_result = [];
6079
    $category_names = [];
6080
6081
    $from = isset($params['from']) ? $params['from'] : null;
6082
    $to = isset($params['to']) ? $params['to'] : null;
6083
6084
    if ($debug) {
6085
        error_log(print_r($params, 1));
6086
        error_log($from);
6087
        error_log($to);
6088
    }
6089
6090
    $courses = CourseManager::get_courses_list($from, $to);
6091
6092
    foreach ($courses as $course) {
6093
        $course_tmp = [];
6094
        $course_tmp['id'] = $course['id'];
6095
        $course_tmp['code'] = $course['code'];
6096
        $course_tmp['title'] = $course['title'];
6097
        $course_tmp['language'] = $course['course_language'];
6098
        $course_tmp['visibility'] = $course['visibility'];
6099
        $course_tmp['category_name'] = '';
6100
6101
        // Determining category name
6102
        if (!empty($course['category_code']) &&
6103
            isset($category_names[$course['category_code']])
6104
        ) {
6105
            $course_tmp['category_name'] = $category_names[$course['category_code']];
6106
        } else {
6107
            $category = CourseManager::get_course_category($course['category_code']);
6108
            if ($category) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $category of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
6109
                $category_names[$course['category_code']] = $category['name'];
6110
                $course_tmp['category_name'] = $category['name'];
6111
            }
6112
        }
6113
6114
        // Determining number of students registered in course
6115
        $course_tmp['number_students'] = CourseManager::get_users_count_in_course(
6116
            $course['code']
6117
        );
6118
6119
        // Determining external course id
6120
        $externalCourseId = '';
6121
        if ($course_field_name) {
6122
            $externalCourseId = CourseManager::get_course_extra_field_value(
6123
                $course_field_name,
6124
                $course['code']
6125
            );
6126
        }
6127
6128
        $course_tmp['external_course_id'] = $externalCourseId;
6129
        $courses_result[] = $course_tmp;
6130
    }
6131
6132
    return $courses_result;
6133
}
6134
6135
6136
/* Get user api key */
6137
$server->wsdl->addComplexType(
6138
    'userApiKey',
6139
    'complexType',
6140
    'struct',
6141
    'all',
6142
    '',
6143
    [
6144
        'original_user_id_name'     => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
6145
        'original_user_id_value'    => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
6146
        'chamilo_username'          => ['name' => 'chamilo_username', 'type' => 'xsd:string'],
6147
        'secret_key'                => ['name' => 'secret_key', 'type' => 'xsd:string']
6148
    ]
6149
);
6150
6151
// Register the method to expose
6152
$server->register(
6153
    'WSUpdateUserApiKey', // method name
6154
    ['userApiKey' => 'tns:userApiKey'], // input parameters
6155
    ['return' => 'xsd:string'], // output parameters
6156
    'urn:WSRegistration', // namespace
6157
    'urn:WSRegistration#WSListCourses', // soapaction
6158
    'rpc', // style
6159
    'encoded', // use
6160
    'This service return user api key'       // documentation
6161
);
6162
6163
/**
6164
 * @param array $params
6165
 * @return int|null|soap_fault
6166
 */
6167
function WSUpdateUserApiKey($params)
6168
{
6169
    if (!WSHelperVerifyKey($params)) {
6170
        return returnError(WS_ERROR_SECRET_KEY);
6171
    }
6172
6173
    $user_id = UserManager::get_user_id_from_original_id(
6174
        $params['original_user_id_value'],
6175
        $params['original_user_id_name']
6176
    );
6177
    if (!$user_id) {
6178
        if (!empty($params['chamilo_username'])) {
6179
            $info = api_get_user_info_from_username($params['chamilo_username']);
6180
            $user_id = $info['user_id'];
6181
            // Save new fieldlabel into user_field table.
6182
            UserManager::create_extra_field($params['original_user_id_name'], 1, $params['original_user_id_name'], '');
6183
            // Save the external system's id into user_field_value table.
6184
            UserManager::update_extra_field_value(
6185
                $user_id,
6186
                $params['original_user_id_name'],
6187
                $params['original_user_id_value']
6188
            );
6189
        } else {
6190
            return 0;
6191
        }
6192
    }
6193
6194
    $list = UserManager::get_api_keys($user_id);
6195
    $key_id = UserManager::get_api_key_id($user_id, 'dokeos');
6196
6197
    if (isset($list[$key_id])) {
6198
        $apikey = $list[$key_id];
6199
    } else {
6200
        $lastid = UserManager::update_api_key($user_id, 'dokeos');
6201
        if ($lastid) {
6202
            $apikeys = UserManager::get_api_keys($user_id);
6203
            $apikey = $apikeys[$lastid];
6204
        }
6205
    }
6206
6207
    return $apikey;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $apikey does not seem to be defined for all execution paths leading up to this point.
Loading history...
6208
}
6209
6210
/** WSListSessions **/
6211
$server->wsdl->addComplexType(
6212
    'session_arg',
6213
    'complexType',
6214
    'struct',
6215
    'all',
6216
    '',
6217
    [
6218
        'from'  => ['name' => 'from', 'type' => 'xsd:int'],
6219
        'to'    => ['name' => 'to', 'type' => 'xsd:int'],
6220
        'date_start'  => ['name' => 'date_start', 'type' => 'xsd:string'],
6221
        'date_end'    => ['name' => 'date_end', 'type' => 'xsd:string'],
6222
        'secret_key'  => ['name' => 'secret_key', 'type' => 'xsd:string']
6223
    ]
6224
);
6225
6226
$server->wsdl->addComplexType(
6227
    'session',
6228
    'complexType',
6229
    'struct',
6230
    'all',
6231
    '',
6232
    [
6233
        'id' => ['name' => 'id', 'type' => 'xsd:int'],
6234
        'title' => ['name' => 'title', 'type' => 'xsd:string'],
6235
        'url' => ['name' => 'url', 'type' => 'xsd:string'],
6236
        'date_start' => ['name' => 'date_start', 'type' => 'xsd:string'],
6237
        'date_end' => ['name' => 'date_end', 'type' => 'xsd:string'],
6238
    ]
6239
);
6240
6241
$server->wsdl->addComplexType(
6242
    'sessions',
6243
    'complexType',
6244
    'array',
6245
    '',
6246
    'SOAP-ENC:Array',
6247
    [],
6248
    [
6249
        ['ref'=>'SOAP-ENC:arrayType',
6250
            'wsdl:arrayType'=>'tns:session[]']
6251
    ],
6252
    'tns:session'
6253
);
6254
6255
// Register the method to expose
6256
$server->register(
6257
    'WSListSessions', // method name
6258
    ['input'  => 'tns:session_arg'], // input parameters
6259
    ['return' => 'tns:sessions'], // output parameters
6260
    'urn:WSRegistration', // namespace
6261
    'urn:WSRegistration#WSListSessions', // soapaction
6262
    'rpc', // style
6263
    'encoded', // use
6264
    'This service returns a list of sessions' // documentation
6265
);
6266
6267
6268
/**
6269
 * Get a list of sessions (id, title, url, date_start, date_end) and
6270
 * return to caller. Date start can be set to ask only for the sessions
6271
 * starting at or after this date. Date end can be set to ask only for the
6272
 * sessions ending before or at this date.
6273
 * Function registered as service. Returns strings in UTF-8.
6274
 * @param array List of parameters (security key, date_start and date_end)
6275
 * @return array Sessions list (id=>[title=>'title',url='http://...',date_start=>'...',date_end=>''])
6276
 */
6277
function WSListSessions($params)
6278
{
6279
    if (!WSHelperVerifyKey($params)) {
6280
        return returnError(WS_ERROR_SECRET_KEY);
0 ignored issues
show
Bug Best Practice introduced by
The expression return returnError(WS_ERROR_SECRET_KEY) also could return the type soap_fault which is incompatible with the documented return type array.
Loading history...
6281
    }
6282
    $sql_params = [];
6283
    // Dates should be provided in YYYY-MM-DD format, UTC
6284
    if (!empty($params['date_start'])) {
6285
        $sql_params['s.access_start_date'] = ['operator' => '>=', 'value' => $params['date_start']];
6286
    }
6287
    if (!empty($params['date_end'])) {
6288
        $sql_params['s.access_end_date'] = ['operator' => '<=', 'value' => $params['date_end']];
6289
    }
6290
    $from = isset($params['from']) ? $params['from'] : null;
6291
    $to = isset($params['to']) ? $params['to'] : null;
6292
6293
    $sessions_list = SessionManager::get_sessions_list($sql_params, null, $from, $to);
6294
    $return_list = [];
6295
    foreach ($sessions_list as $session) {
6296
        $return_list[] = [
6297
            'id' => $session['id'],
6298
            'title' => $session['name'],
6299
            // something like http://my.chamilo.net/main/session/index.php?session_id=5
6300
            'url' => api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$session['id'],
6301
            'date_start' => $session['access_start_date'],
6302
            'date_end' => $session['access_end_date'],
6303
        ];
6304
    }
6305
6306
    return $return_list;
6307
}
6308
6309
/* Register WSUserSubscribedInCourse function */
6310
// Register the data structures used by the service
6311
6312
//prepare input params
6313
6314
// Input params for editing users
6315
$server->wsdl->addComplexType(
6316
    'UserSubscribedInCourse',
6317
    'complexType',
6318
    'struct',
6319
    'all',
6320
    '',
6321
    [
6322
        'course' => ['name' => 'course', 'type' => 'xsd:string'],
6323
        //Course string code
6324
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
6325
        //Chamilo user_id
6326
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
6327
    ]
6328
);
6329
6330
// Register the method to expose
6331
$server->register(
6332
    'WSUserSubscribedInCourse', // method name
6333
    ['UserSubscribedInCourse' => 'tns:UserSubscribedInCourse'], // input parameters
6334
    ['return' => 'xsd:string'], // output parameters
6335
    'urn:WSRegistration', // namespace
6336
    'urn:WSRegistration#WSUserSubscribedInCourse', // soapaction
6337
    'rpc', // style
6338
    'encoded', // use
6339
    'This service checks if user assigned to course'    // documentation
6340
);
6341
6342
/**
6343
 * Web service to tell if a given user is subscribed to the course
6344
 * @param array $params Array of parameters (course and user_id)
6345
 * @return bool|null|soap_fault A simple boolean (true if user is subscribed, false otherwise)
6346
 */
6347
function WSUserSubscribedInCourse($params)
6348
{
6349
    global $debug;
6350
6351
    if ($debug) {
6352
        error_log('WSUserSubscribedInCourse');
6353
    }
6354
    if ($debug) {
6355
        error_log('Params '.print_r($params, 1));
6356
    }
6357
    if (!WSHelperVerifyKey($params)) {
6358
        return returnError(WS_ERROR_SECRET_KEY);
6359
    }
6360
    $courseCode = $params['course']; //Course code
6361
    $userId = $params['user_id']; //chamilo user id
6362
6363
    return CourseManager::is_user_subscribed_in_course($userId, $courseCode);
6364
}
6365
6366
/* Search session Web Service start */
6367
6368
// Input params for WSSearchSession
6369
$server->wsdl->addComplexType(
6370
    'SearchSession',
6371
    'complexType',
6372
    'struct',
6373
    'all',
6374
    '',
6375
    [
6376
        'term' => ['name' => 'term', 'type' => 'xsd:string'],
6377
        'extrafields' => ['name' => 'extrafields', 'type' => 'xsd:string'],
6378
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string']
6379
    ]
6380
);
6381
6382
//Output params for WSSearchSession
6383
$server->wsdl->addComplexType(
6384
    'searchedSessionExtra',
6385
    'complexType',
6386
    'struct',
6387
    'all',
6388
    '',
6389
    [
6390
        'variable' => ['name'=>'variable', 'type'=>'xsd:string'],
6391
        'value' => ['name'=>'value', 'type'=>'xsd:string']
6392
    ]
6393
);
6394
6395
$server->wsdl->addComplexType(
6396
    'searchedSessionExtras',
6397
    'complexType',
6398
    'array',
6399
    '',
6400
    'SOAP-ENC:Array',
6401
    [],
6402
    [
6403
        ['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:searchedSessionExtra[]']
6404
    ],
6405
    'tns:searchedSessionExtra'
6406
);
6407
6408
$server->wsdl->addComplexType(
6409
    'searchedSession',
6410
    'complexType',
6411
    'struct',
6412
    'all',
6413
    '',
6414
    [
6415
        'id' => ['name' => 'id', 'type' => 'xsd:int'],
6416
        'id_coach' => ['name' => 'id_coach', 'type' => 'xsd:int'],
6417
        'name' => ['name' => 'name', 'type' => 'xsd:string'],
6418
        'nbr_courses' => ['name' => 'nbr_courses', 'type' => 'xsd:int'],
6419
        'nbr_users' => ['name' => 'nbr_users', 'type' => 'xsd:int'],
6420
        'nbr_classes' => ['name' => 'nbr_classes', 'type' => 'xsd:int'],
6421
        'date_start' => ['name' => 'date_start', 'type' => 'xsd:string'],
6422
        'date_end' => ['name' => 'date_end', 'type' => 'xsd:string'],
6423
        'nb_days_access_before_beginning' => ['name' => 'nb_days_access_before_beginning', 'type' => 'xsd:int'],
6424
        'nb_days_access_after_end' => ['nb_days_access_after_end' => 'duration', 'type' => 'xsd:int'],
6425
        'session_admin_id' => ['session_admin_id' => 'duration', 'type' => 'xsd:int'],
6426
        'visibility' => ['visibility' => 'duration', 'type' => 'xsd:int'],
6427
        'session_category_id' => ['session_category_id' => 'duration', 'type' => 'xsd:int'],
6428
        'promotion_id' => ['promotion_id' => 'duration', 'type' => 'xsd:int'],
6429
        'description' => ['name' => 'description', 'type' => 'xsd:string'],
6430
        'show_description' => ['name' => 'description', 'type' => 'xsd:int'],
6431
        'duration' => ['name' => 'duration', 'type' => 'xsd:string'],
6432
        'extra' => ['name' => 'extra', 'type' => 'tns:searchedSessionExtras'],
6433
    ]
6434
);
6435
6436
$server->wsdl->addComplexType(
6437
    'searchedSessionList',
6438
    'complexType',
6439
    'array',
6440
    '',
6441
    'SOAP-ENC:Array',
6442
    [],
6443
    [
6444
        ['ref' => 'SOAP-ENC:arrayType',
6445
            'wsdl:arrayType' => 'tns:searchedSession[]']
6446
    ],
6447
    'tns:searchedSession'
6448
);
6449
6450
//Reister WSSearchSession
6451
$server->register(
6452
    'WSSearchSession',
6453
    ['SearchSession' => 'tns:SearchSession'], // input parameters
6454
    ['return' => 'tns:searchedSessionList'], // output parameters
6455
    'urn:WSRegistration', // namespace
6456
    'urn:WSRegistration#WSSearchSession', // soapaction
6457
    'rpc', // style
6458
    'encoded', // use
6459
    'This service to get a session list filtered by name, description or short description extra field'    // documentation
6460
);
6461
6462
/**
6463
 * Web service to get a session list filtered by name, description or short description extra field
6464
 * @param array $params Contains the following parameters
6465
 *   string $params['term'] Search term
6466
 *   string $params['extrafields'] Extrafields to include in request result
6467
 *   string $params['secret_key'] Secret key to check
6468
 * @return array The list
6469
 */
6470
function WSSearchSession($params)
6471
{
6472
    if (!WSHelperVerifyKey($params['secret_key'])) {
6473
        return returnError(WS_ERROR_SECRET_KEY);
0 ignored issues
show
Bug Best Practice introduced by
The expression return returnError(WS_ERROR_SECRET_KEY) also could return the type soap_fault which is incompatible with the documented return type array.
Loading history...
6474
    }
6475
6476
    $fieldsToInclude = [];
6477
6478
    if (!empty($params['extrafields'])) {
6479
        $fieldsToInclude = explode(',', $params['extrafields']);
6480
        foreach ($fieldsToInclude as &$field) {
6481
            if (empty($field)) {
6482
                continue;
6483
            }
6484
6485
            $field = trim($field);
6486
        }
6487
    }
6488
6489
    return SessionManager::searchSession($params['term'], $fieldsToInclude);
6490
}
6491
6492
/* Search session Web Service end */
6493
/* Fetch session Web Service start */
6494
// Input params for WSFetchSession
6495
$server->wsdl->addComplexType(
6496
    'FetchSession',
6497
    'complexType',
6498
    'struct',
6499
    'all',
6500
    '',
6501
    [
6502
        'id' => ['name' => 'id', 'type' => 'xsd:int'],
6503
        'extrafields' => ['name' => 'extrafields', 'type' => 'xsd:string'],
6504
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
6505
    ]
6506
);
6507
6508
//Reister WSFetchSession
6509
$server->register(
6510
    'WSFetchSession',
6511
    ['SearchSession' => 'tns:FetchSession'], // input parameters
6512
    ['return' => 'tns:searchedSessionList'], // output parameters
6513
    'urn:WSRegistration', // namespace
6514
    'urn:WSRegistration#WSFetchSession', // soapaction
6515
    'rpc', // style
6516
    'encoded', // use
6517
    'This service get a session by its id. Optionally can get its extra fields values'    // documentation
6518
);
6519
6520
/**
6521
 * Web service to get a session by its id. Optionally can get its extra fields values
6522
 * @param array $params Contains the following parameters:
6523
 *   int $params['id'] The session id
6524
 *   string $params['extrafields'] Extrafields to include in request result
6525
 *   string $params['secret_key'] Secret key to check
6526
 * @return array The session data
6527
 */
6528
function WSFetchSession($params)
6529
{
6530
    if (!WSHelperVerifyKey($params['secret_key'])) {
6531
        return returnError(WS_ERROR_SECRET_KEY);
0 ignored issues
show
Bug Best Practice introduced by
The expression return returnError(WS_ERROR_SECRET_KEY) also could return the type soap_fault which is incompatible with the documented return type array.
Loading history...
6532
    }
6533
6534
    $fieldsToInclude = explode(',', $params['extrafields']);
6535
6536
    foreach ($fieldsToInclude as &$field) {
6537
        if (empty($field)) {
6538
            continue;
6539
        }
6540
6541
        $field = trim($field);
6542
    }
6543
6544
    $sessionData = SessionManager::fetch($params['id']);
6545
6546
    if ($sessionData === false) {
6547
        return returnError(WS_ERROR_INVALID_INPUT);
6548
    }
6549
6550
    if (!empty($extraFields)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $extraFields seems to never exist and therefore empty should always be true.
Loading history...
6551
        $sessionData['extra'] = SessionManager::getFilteredExtraFields($params['id'], $fieldsToInclude);
6552
    }
6553
6554
    return [$sessionData];
6555
}
6556
6557
/* Fetch session Web Service end */
6558
6559
/* Register WSCertificatesList function */
6560
// Register the data structures used by the service
6561
$server->wsdl->addComplexType(
6562
    'certificateDetails',
6563
    'complexType',
6564
    'struct',
6565
    'all',
6566
    '',
6567
    [
6568
        'id' => ['name' => 'id', 'type' => 'xsd:int'],
6569
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
6570
        'course_code' => ['name' => 'course_code', 'type' => 'xsd:string'],
6571
        'session_id' => ['name' => 'session_id', 'type' => 'xsd:int'],
6572
        'cat_id' => ['name' => 'cat_id', 'type' => 'xsd:int'],
6573
        'created_at' => ['name' => 'created_at', 'type' => 'xsd:string'],
6574
        'path_certificate' => ['name' => 'path_certificate', 'type' => 'xsd:string']
6575
    ]
6576
);
6577
6578
$server->wsdl->addComplexType(
6579
    'certificatesList',
6580
    'complexType',
6581
    'array',
6582
    '',
6583
    'SOAP-ENC:Array',
6584
    [],
6585
    [
6586
        ['ref'=>'SOAP-ENC:arrayType',
6587
            'wsdl:arrayType'=>'tns:certificateDetails[]']
6588
    ],
6589
    'tns:certificateDetails'
6590
);
6591
// Register the method to expose
6592
$server->register(
6593
    'WSCertificatesList', // method name
6594
    [
6595
        'startingDate' => 'xsd:string', // input parameters
6596
        'endingDate' => 'xsd:string'
6597
    ],
6598
    ['return' => 'tns:certificatesList'], // output parameters
6599
    'urn:WSRegistration', // namespace
6600
    'urn:WSRegistration#WSCertificatesList', // soapaction
6601
    'rpc', // style
6602
    'encoded', // use
6603
    'This service returns a list of certificates'   // documentation
6604
);
6605
6606
function WSCertificatesList($startingDate = '', $endingDate = '')
6607
{
6608
    $certificatesCron = api_get_setting('add_gradebook_certificates_cron_task_enabled');
6609
    if ($certificatesCron === 'true') {
6610
        require_once api_get_path(SYS_CODE_PATH).'cron/add_gradebook_certificates.php';
6611
    }
6612
    $result = [];
6613
    $certificateTable = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
6614
    $userTable = Database::get_main_table(TABLE_MAIN_USER);
6615
    $categoryTable = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
6616
6617
    $query = "SELECT
6618
                    certificate.id,
6619
                    user.username,
6620
                    category.course_code,
6621
                    category.session_id,
6622
                    certificate.user_id,
6623
                    certificate.cat_id,
6624
                    certificate.created_at,
6625
                    certificate.path_certificate
6626
                FROM $certificateTable AS certificate
6627
                JOIN $userTable AS user
6628
                ON certificate.user_id = user.user_id
6629
                JOIN $categoryTable AS category
6630
                ON certificate.cat_id = category.id";
6631
6632
    if (!empty($startingDate) && !empty($endingDate)) {
6633
        $query .= " WHERE certificate.created_at BETWEEN '$startingDate' AND '$endingDate'";
6634
    } elseif (!empty($startingDate)) {
6635
        $query .= " WHERE certificate.created_at >= '$startingDate'";
6636
    } elseif (!empty($endingDate)) {
6637
        $query .= " WHERE certificate.created_at <= '$endingDate'";
6638
    }
6639
6640
    $queryResult = Database::query($query);
6641
    while ($row = Database::fetch_array($queryResult)) {
6642
        $userPath = USermanager::getUserPathById($row['user_id'], 'web');
6643
        $row['path_certificate'] = $userPath.'/certificate'.$row['path_certificate'];
6644
        $result[] = $row;
6645
    }
6646
6647
    return $result;
6648
}
6649
6650
/* Create group Web Service start */
6651
// Register the data structures used by the service
6652
6653
// Input params for WSCreateGroup
6654
$server->wsdl->addComplexType(
6655
    'createGroup',
6656
    'complexType',
6657
    'struct',
6658
    'all',
6659
    '',
6660
    [
6661
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
6662
        'name' => ['name' => 'name', 'type' => 'xsd:string']
6663
    ]
6664
);
6665
6666
// Register the method to expose
6667
$server->register(
6668
    'WSCreateGroup', // method name
6669
    ['createGroup' => 'tns:createGroup'], // input parameters
6670
    ['return' => 'xsd:string'], // output parameters
6671
    'urn:WSRegistration', // namespace
6672
    'urn:WSRegistration#WSCreateGroup', // soapaction
6673
    'rpc', // style
6674
    'encoded', // use
6675
    'This service adds a group'                 // documentation
6676
);
6677
6678
// Define the method WSCreateGroup
6679
function WSCreateGroup($params)
6680
{
6681
    if (!WSHelperVerifyKey($params['secret_key'])) {
6682
        return returnError(WS_ERROR_SECRET_KEY);
6683
    }
6684
    $userGroup = new UserGroup();
6685
    $params = [
6686
        'name' => $params['name']
6687
    ];
6688
    return $userGroup->save($params);
6689
}
6690
6691
/* Create group Web Service end */
6692
6693
/* Update group Web Service start */
6694
// Register the data structures used by the service
6695
6696
// Input params for WSUpdateGroup
6697
$server->wsdl->addComplexType(
6698
    'updateGroup',
6699
    'complexType',
6700
    'struct',
6701
    'all',
6702
    '',
6703
    [
6704
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6705
        'id' => ['name' => 'id', 'type' => 'xsd:string'],
6706
        'name' => ['name' => 'name', 'type' => 'xsd:string'],
6707
        'description'   => ['name' => 'description', 'type' => 'xsd:string'],
6708
        'url' => ['name' => 'url', 'type' => 'xsd:string'],
6709
        'visibility' => ['name' => 'visibility', 'type' => 'xsd:string'],
6710
        'picture_uri' => ['name' => 'picture_uri', 'type' => 'xsd:string'],
6711
        'allow_member_group_to_leave' => ['name' => 'allow_member_group_to_leave', 'type' => 'xsd:string']
6712
    ]
6713
);
6714
6715
// Register the method to expose
6716
$server->register(
6717
    'WSUpdateGroup', // method name
6718
    ['updateGroup' => 'tns:updateGroup'], // input parameters
6719
    ['return' => 'xsd:string'], // output parameters
6720
    'urn:WSRegistration', // namespace
6721
    'urn:WSRegistration#WSUpdateGroup', // soapaction
6722
    'rpc', // style
6723
    'encoded', // use
6724
    'This service updates a group'              // documentation
6725
);
6726
6727
// Define the method WSUpdateGroup
6728
function WSUpdateGroup($params)
6729
{
6730
    if (!WSHelperVerifyKey($params['secret_key'])) {
6731
        return returnError(WS_ERROR_SECRET_KEY);
6732
    }
6733
    $params['allow_member_group_to_leave'] = null;
6734
    $userGroup = new UserGroup();
6735
6736
    return $userGroup->update($params);
6737
}
6738
6739
/* Update group Web Service end */
6740
6741
/* Delete group Web Service start */
6742
// Register the data structures used by the service
6743
6744
// Input params for WSDeleteGroup
6745
$server->wsdl->addComplexType(
6746
    'deleteGroup',
6747
    'complexType',
6748
    'struct',
6749
    'all',
6750
    '',
6751
    [
6752
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6753
        'id' => ['name' => 'id', 'type' => 'xsd:string']
6754
    ]
6755
);
6756
6757
// Register the method to expose
6758
$server->register(
6759
    'WSDeleteGroup', // method name
6760
    ['deleteGroup' => 'tns:deleteGroup'], // input parameters
6761
    ['return' => 'xsd:string'], // output parameters
6762
    'urn:WSRegistration', // namespace
6763
    'urn:WSRegistration#WSDeleteGroup', // soapaction
6764
    'rpc', // style
6765
    'encoded', // use
6766
    'This service deletes a group'              // documentation
6767
);
6768
6769
// Define the method WSDeleteGroup
6770
function WSDeleteGroup($params)
6771
{
6772
    if (!WSHelperVerifyKey($params['secret_key'])) {
6773
        return returnError(WS_ERROR_SECRET_KEY);
6774
    }
6775
    $userGroup = new UserGroup();
6776
6777
    return $userGroup->delete($params['id']);
6778
}
6779
6780
/* Delete group Web Service end */
6781
6782
/* Bind group to parent Web Service start */
6783
// Register the data structures used by the service
6784
6785
// Input params for GroupBindToParent
6786
$server->wsdl->addComplexType(
6787
    'groupBindToParent',
6788
    'complexType',
6789
    'struct',
6790
    'all',
6791
    '',
6792
    [
6793
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6794
        'id' => ['name' => 'id', 'type' => 'xsd:string'],
6795
        'parent_id' => ['name' => 'parent_id', 'type' => 'xsd:string']
6796
    ]
6797
);
6798
6799
// Register the method to expose
6800
$server->register(
6801
    'GroupBindToParent', // method name
6802
    ['groupBindToParent' => 'tns:groupBindToParent'], // input parameters
6803
    ['return' => 'xsd:string'], // output parameters
6804
    'urn:WSRegistration', // namespace
6805
    'urn:WSRegistration#GroupBindToParent', // soapaction
6806
    'rpc', // style
6807
    'encoded', // use
6808
    'This service binds a group to a parent'                // documentation
6809
);
6810
6811
// Define the method GroupBindToParent
6812
function GroupBindToParent($params)
6813
{
6814
    if (!WSHelperVerifyKey($params['secret_key'])) {
6815
        return returnError(WS_ERROR_SECRET_KEY);
6816
    }
6817
    $userGroup = new UserGroup();
6818
6819
    return $userGroup->setParentGroup($params['id'], $params['parent_id']);
6820
}
6821
6822
/* Bind group Web Service end */
6823
6824
/* Unbind group from parent Web Service start */
6825
// Register the data structures used by the service
6826
6827
// Input params for GroupUnbindFromParent
6828
$server->wsdl->addComplexType(
6829
    'groupUnbindFromParent',
6830
    'complexType',
6831
    'struct',
6832
    'all',
6833
    '',
6834
    [
6835
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6836
        'id' => ['name' => 'id', 'type' => 'xsd:string']
6837
    ]
6838
);
6839
6840
// Register the method to expose
6841
$server->register(
6842
    'GroupUnbindFromParent', // method name
6843
    ['groupUnbindFromParent' => 'tns:groupUnbindFromParent'], // input parameters
6844
    ['return' => 'xsd:string'], // output parameters
6845
    'urn:WSRegistration', // namespace
6846
    'urn:WSRegistration#GroupUnbindFromParent', // soapaction
6847
    'rpc', // style
6848
    'encoded', // use
6849
    'This service unbinds a group from its parent'                  // documentation
6850
);
6851
6852
// Define the method GroupUnbindFromParent
6853
function GroupUnbindFromParent($params)
6854
{
6855
    if (!WSHelperVerifyKey($params['secret_key'])) {
6856
        return returnError(WS_ERROR_SECRET_KEY);
6857
    }
6858
    $userGroup = new UserGroup();
6859
    return $userGroup->setParentGroup($params['id'], 0);
6860
}
6861
6862
/* Unbind group Web Service end */
6863
6864
/* Add user to group Web Service start */
6865
// Register the data structures used by the service
6866
6867
// Input params for WSAddUserToGroup
6868
$server->wsdl->addComplexType(
6869
    'addUserToGroup',
6870
    'complexType',
6871
    'struct',
6872
    'all',
6873
    '',
6874
    [
6875
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6876
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
6877
        'group_id' => ['name' => 'group_id', 'type' => 'xsd:string'],
6878
        'relation_type' => ['name' => 'relation_type', 'type' => 'xsd:string']
6879
    ]
6880
);
6881
6882
// Register the method to expose
6883
$server->register(
6884
    'WSAddUserToGroup', // method name
6885
    ['addUserToGroup' => 'tns:addUserToGroup'], // input parameters
6886
    ['return' => 'xsd:string'], // output parameters
6887
    'urn:WSRegistration', // namespace
6888
    'urn:WSRegistration#WSAddUserToGroup', // soapaction
6889
    'rpc', // style
6890
    'encoded', // use
6891
    'This service adds a user to a group'               // documentation
6892
);
6893
6894
// Define the method WSAddUserToGroup
6895
function WSAddUserToGroup($params)
6896
{
6897
    if (!WSHelperVerifyKey($params['secret_key'])) {
6898
        return returnError(WS_ERROR_SECRET_KEY);
6899
    }
6900
6901
    $userGroup = new UserGroup();
6902
6903
    return $userGroup->subscribe_users_to_usergroup(
0 ignored issues
show
Bug introduced by
Are you sure the usage of $userGroup->subscribe_us...arams['relation_type']) targeting UserGroup::subscribe_users_to_usergroup() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
6904
        $params['group_id'],
6905
        [0 => $params['user_id']],
6906
        false,
6907
        $params['relation_type']
6908
    );
6909
}
6910
6911
/* Add user to group Web Service end */
6912
6913
/* Update user role in group Web Service start */
6914
// Register the data structures used by the service
6915
6916
// Input params for WSUpdateUserRoleInGroup
6917
$server->wsdl->addComplexType(
6918
    'updateUserRoleInGroup',
6919
    'complexType',
6920
    'struct',
6921
    'all',
6922
    '',
6923
    [
6924
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6925
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
6926
        'group_id' => ['name' => 'group_id', 'type' => 'xsd:string'],
6927
        'relation_type' => ['name' => 'relation_type', 'type' => 'xsd:string']
6928
    ]
6929
);
6930
6931
// Register the method to expose
6932
$server->register(
6933
    'WSUpdateUserRoleInGroup', // method name
6934
    ['updateUserRoleInGroup' => 'tns:updateUserRoleInGroup'], // input parameters
6935
    ['return' => 'xsd:string'], // output parameters
6936
    'urn:WSRegistration', // namespace
6937
    'urn:WSRegistration#WSUpdateUserRoleInGroup', // soapaction
6938
    'rpc', // style
6939
    'encoded', // use
6940
    'This service updates a user role in group'                     // documentation
6941
);
6942
6943
// Define the method WSUpdateUserRoleInGroup
6944
function WSUpdateUserRoleInGroup($params)
6945
{
6946
    if (!WSHelperVerifyKey($params['secret_key'])) {
6947
        return returnError(WS_ERROR_SECRET_KEY);
6948
    }
6949
    $userGroup = new UserGroup();
6950
6951
    return $userGroup->update_user_role(
0 ignored issues
show
Bug introduced by
Are you sure the usage of $userGroup->update_user_...arams['relation_type']) targeting UserGroup::update_user_role() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
6952
        $params['user_id'],
6953
        $params['group_id'],
6954
        $params['relation_type']
6955
    );
6956
}
6957
6958
/* Update user role Web Service end */
6959
6960
/* Delete user from group Web Service start */
6961
// Register the data structures used by the service
6962
6963
// Input params for WSDeleteUserFromGroup
6964
$server->wsdl->addComplexType(
6965
    'deleteUserFromGroup',
6966
    'complexType',
6967
    'struct',
6968
    'all',
6969
    '',
6970
    [
6971
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6972
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
6973
        'group_id' => ['name' => 'group_id', 'type' => 'xsd:string']
6974
    ]
6975
);
6976
6977
// Register the method to expose
6978
$server->register(
6979
    'WSDeleteUserFromGroup', // method name
6980
    ['deleteUserFromGroup' => 'tns:deleteUserFromGroup'], // input parameters
6981
    ['return' => 'xsd:string'], // output parameters
6982
    'urn:WSRegistration', // namespace
6983
    'urn:WSRegistration#WSDeleteUserFromGroup', // soapaction
6984
    'rpc', // style
6985
    'encoded', // use
6986
    'This service deletes a user from a group'                  // documentation
6987
);
6988
6989
// Define the method WSDeleteUserFromGroup
6990
function WSDeleteUserFromGroup($params)
6991
{
6992
    if (!WSHelperVerifyKey($params['secret_key'])) {
6993
        return returnError(WS_ERROR_SECRET_KEY);
6994
    }
6995
    $userGroup = new UserGroup();
6996
6997
    return $userGroup->delete_user_rel_group(
6998
        $params['user_id'],
6999
        $params['group_id']
7000
    );
7001
}
7002
7003
/* Delete user from group Web Service end */
7004
7005
/** WSRegisterUserVisibilityToCourseCatalogue **/
7006
// Register the data structures used by the service
7007
7008
$server->wsdl->addComplexType(
7009
    'user_course_visibility',
7010
    'complexType',
7011
    'struct',
7012
    'all',
7013
    '',
7014
    [
7015
        'course_id' => ['name' => 'course_id', 'type' => 'tns:course_id'],
7016
        'user_id' => ['name' => 'user_id', 'type' => 'tns:user_id'],
7017
        'visible' => ['name' => 'status', 'type' => 'xsd:int'],
7018
    ]
7019
);
7020
7021
$server->wsdl->addComplexType(
7022
    'user_course_visibility_array',
7023
    'complexType',
7024
    'array',
7025
    '',
7026
    'SOAP-ENC:Array',
7027
    [],
7028
    [
7029
        ['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:user_course_visibility[]']
7030
    ],
7031
    'tns:user_course_visibility'
7032
);
7033
7034
$server->wsdl->addComplexType(
7035
    'registerUserToCourseCatalogue_arg',
7036
    'complexType',
7037
    'struct',
7038
    'all',
7039
    '',
7040
    [
7041
        'userscourses' => ['name' => 'userscourses', 'type' => 'tns:user_course_visibility_array'],
7042
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
7043
    ]
7044
);
7045
7046
$server->wsdl->addComplexType(
7047
    'registerUserToCourseCatalogue_return',
7048
    'complexType',
7049
    'struct',
7050
    'all',
7051
    '',
7052
    [
7053
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
7054
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
7055
        'visible' => ['name' => 'visible', 'type' => 'xsd:int'],
7056
        'result' => ['name' => 'result', 'type' => 'xsd:int'],
7057
    ]
7058
);
7059
7060
$server->wsdl->addComplexType(
7061
    'registerUserToCourseCatalogue_return_global',
7062
    'complexType',
7063
    'array',
7064
    '',
7065
    'SOAP-ENC:Array',
7066
    [],
7067
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:registerUserToCourseCatalogue_return[]']],
7068
    'tns:registerUserToCourseCatalogue_return'
7069
);
7070
7071
// Register the method to expose
7072
$server->register(
7073
    'WSAddUserVisibilityToCourseInCatalogue', // method name
7074
    ['registerUserToCourseCatalogue' => 'tns:registerUserToCourseCatalogue_arg'], // input parameters
7075
    ['return' => 'tns:registerUserToCourseCatalogue_return_global'],
7076
    'urn:WSRegistration', // namespace
7077
    'urn:WSRegistration#WSRegisterUserVisibilityToCourseCatalogue', // soapaction
7078
    'rpc', // style
7079
    'encoded', // use
7080
    'This service registers the visibility of users to course in catalogue' // documentation
7081
);
7082
7083
// define the method WSRegisterUserVisibilityToCourseInCatalogue
7084
function WSAddUserVisibilityToCourseInCatalogue($params)
7085
{
7086
    global $debug;
7087
    if (!WSHelperVerifyKey($params)) {
7088
        return returnError(WS_ERROR_SECRET_KEY);
7089
    }
7090
    if ($debug) {
7091
        error_log('WSAddUserVisibilityToCourseCatalogue params: '.print_r($params, 1));
7092
    }
7093
7094
    $results = [];
7095
    $userscourses = $params['userscourses'];
7096
    foreach ($userscourses as $usercourse) {
7097
        $original_course_id = $usercourse['course_id'];
7098
        $original_user_id   = $usercourse['user_id'];
7099
        $visible = $usercourse['visible'];
7100
7101
        $resultValue = 0;
7102
7103
        // Get user id
7104
        $userId = UserManager::get_user_id_from_original_id(
7105
            $original_user_id['original_user_id_value'],
7106
            $original_user_id['original_user_id_name']
7107
        );
7108
        if ($debug) {
7109
            error_log('WSAddUserVisibilityToCourseCatalogue userId: '.$userId);
7110
        }
7111
7112
        if ($userId == 0) {
7113
            // If user was not found, there was a problem
7114
            $resultValue = 0;
7115
        } else {
7116
            // User was found
7117
            $courseInfo = CourseManager::getCourseInfoFromOriginalId(
7118
                $original_course_id['original_course_id_value'],
7119
                $original_course_id['original_course_id_name']
7120
            );
7121
7122
            $courseCode = $courseInfo['code'];
7123
            if (empty($courseCode)) {
7124
                // Course was not found
7125
                $resultValue = 0;
7126
            } else {
7127
                if ($debug) {
7128
                    error_log('WSAddUserVisibilityToCourseCatalogue courseCode: '.$courseCode);
7129
                }
7130
                $result = CourseManager::addUserVisibilityToCourseInCatalogue($userId, $courseCode, $visible);
7131
                if ($result) {
7132
                    $resultValue = 1;
7133
                    if ($debug) {
7134
                        error_log('WSAddUserVisibilityToCourseCatalogue registered');
7135
                    }
7136
                } else {
7137
                    if ($debug) {
7138
                        error_log('WSAddUserVisibilityToCourseCatalogue NOT registered: ');
7139
                    }
7140
                }
7141
            }
7142
        }
7143
7144
        $results[] = [
7145
            'original_user_id_value' => $original_user_id['original_user_id_value'],
7146
            'original_course_id_value' => $original_course_id['original_course_id_value'],
7147
            'visible' => $visible,
7148
            'result' => $resultValue
7149
        ];
7150
    }
7151
7152
    return $results;
7153
}
7154
7155
// Register the method to expose
7156
$server->register(
7157
    'WSRemoveUserVisibilityToCourseInCatalogue', // method name
7158
    ['registerUserToCourseCatalogue' => 'tns:registerUserToCourseCatalogue_arg'], // input parameters
7159
    ['return' => 'tns:registerUserToCourseCatalogue_return_global'],
7160
    'urn:WSRegistration', // namespace
7161
    'urn:WSRegistration#WSRegisterUserVisibilityToCourseCatalogue', // soapaction
7162
    'rpc', // style
7163
    'encoded', // use
7164
    'This service removes the visibility of users to course in catalogue' // documentation
7165
);
7166
7167
// define the method WSRemoveUserVisibilityToCourseInCatalogue
7168
function WSRemoveUserVisibilityToCourseInCatalogue($params)
7169
{
7170
    global $debug;
7171
    if (!WSHelperVerifyKey($params)) {
7172
        return returnError(WS_ERROR_SECRET_KEY);
7173
    }
7174
    if ($debug) {
7175
        error_log('WSRemoveUserVisibilityToCourseInCatalogue params: '.print_r($params, 1));
7176
    }
7177
7178
    $results = [];
7179
    $userscourses = $params['userscourses'];
7180
    foreach ($userscourses as $usercourse) {
7181
        $original_course_id = $usercourse['course_id'];
7182
        $original_user_id   = $usercourse['user_id'];
7183
        $visible = $usercourse['visible'];
7184
7185
        $resultValue = 0;
7186
7187
        // Get user id
7188
        $userId = UserManager::get_user_id_from_original_id(
7189
            $original_user_id['original_user_id_value'],
7190
            $original_user_id['original_user_id_name']
7191
        );
7192
        if ($debug) {
7193
            error_log('WSRemoveUserVisibilityToCourseInCatalogue user_id: '.$userId);
7194
        }
7195
7196
        if ($userId == 0) {
7197
            // If user was not found, there was a problem
7198
            $resultValue = 0;
7199
        } else {
7200
            // User was found
7201
            $courseInfo = CourseManager::getCourseInfoFromOriginalId(
7202
                $original_course_id['original_course_id_value'],
7203
                $original_course_id['original_course_id_name']
7204
            );
7205
7206
            $courseCode = $courseInfo['code'];
7207
            if (empty($courseCode)) {
7208
                // Course was not found
7209
                $resultValue = 0;
7210
            } else {
7211
                if ($debug) {
7212
                    error_log('WSRemoveUserVisibilityToCourseInCatalogue courseCode: '.$courseCode);
7213
                }
7214
                $result = CourseManager::removeUserVisibilityToCourseInCatalogue($userId, $courseCode, $visible);
7215
                if ($result) {
7216
                    $resultValue = 1;
7217
                    if ($debug) {
7218
                        error_log('WSRemoveUserVisibilityToCourseInCatalogue removed');
7219
                    }
7220
                } else {
7221
                    if ($debug) {
7222
                        error_log('WSRemoveUserVisibilityToCourseInCatalogue NOT removed: ');
7223
                    }
7224
                }
7225
            }
7226
        }
7227
7228
        $results[] = [
7229
            'original_user_id_value' => $original_user_id['original_user_id_value'],
7230
            'original_course_id_value' => $original_course_id['original_course_id_value'],
7231
            'visible' => $visible,
7232
            'result' => $resultValue
7233
        ];
7234
    }
7235
7236
    return $results;
7237
}
7238
7239
// Add more webservices through hooks from plugins
7240
if (!empty($hook)) {
7241
    $hook->setEventData(['server' => $server]);
7242
    $res = $hook->notifyWSRegistration(HOOK_EVENT_TYPE_POST);
7243
    if (!empty($res['server'])) {
7244
        $server = $res['server'];
7245
    }
7246
}
7247
7248
// Use the request to (try to) invoke the service
7249
$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents('php://input');
7250
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
7251
7252
// If you send your data in utf8 then this value must be false.
7253
$decodeUTF8 = api_get_setting('registration.soap.php.decode_utf8');
7254
if ($decodeUTF8 === 'true') {
7255
    $server->decode_utf8 = true;
7256
} else {
7257
    $server->decode_utf8 = false;
7258
}
7259
$server->service($HTTP_RAW_POST_DATA);
7260