Completed
Push — master ( 27e209...a08afa )
by Julito
186:04 queued 150:53
created

WSEditUsersPasswordCrypted()   F

Complexity

Conditions 28
Paths 1049

Size

Total Lines 165
Code Lines 120

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 28
eloc 120
nc 1049
nop 1
dl 0
loc 165
rs 2
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
    }
1272
    if ($debug) {
1273
        error_log(print_r($params, 1));
1274
    }
1275
1276
    if (!WSHelperVerifyKey($params)) {
1277
        return returnError(WS_ERROR_SECRET_KEY);
1278
    }
1279
1280
    // Database table definition.
1281
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1282
    $password = $params['password'];
1283
    $encrypt_method = $params['encrypt_method'];
1284
    $firstName = $params['firstname'];
1285
    $lastName = $params['lastname'];
1286
    $status = $params['status'];
1287
    $email = $params['email'];
1288
    $loginName = $params['loginname'];
1289
    $official_code = isset($params['official_code']) ? $params['official_code'] : '';
1290
    $language = '';
1291
    $phone = isset($params['phone']) ? $params['phone'] : '';
1292
    $picture_uri = '';
1293
    $auth_source = PLATFORM_AUTH_SOURCE;
1294
    $expiration_date = '';
1295
    $active = 1;
1296
    $hr_dept_id = 0;
1297
    $extra = null;
1298
    $original_user_id_name = $params['original_user_id_name'];
1299
    $original_user_id_value = $params['original_user_id_value'];
1300
    $extra_list = isset($params['extra']) ? $params['extra'] : '';
1301
1302
    if (!empty($_configuration['password_encryption'])) {
1303
        if ($_configuration['password_encryption'] === $encrypt_method) {
1304
            if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
1305
                $msg = "Encryption $encrypt_method is invalid";
1306
                if ($debug) {
1307
                    error_log($msg);
1308
                }
1309
                return $msg;
1310
            } elseif ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
1311
                $msg = "Encryption $encrypt_method is invalid";
1312
                if ($debug) {
1313
                    error_log($msg);
1314
                }
1315
                return $msg;
1316
            }
1317
        } else {
1318
            $msg = "This encryption $encrypt_method is not configured";
1319
            if ($debug) {
1320
                error_log($msg);
1321
            }
1322
            return $msg;
1323
        }
1324
    } else {
1325
        $msg = 'The chamilo setting $_configuration["password_encryption"] is not configured';
1326
        if ($debug) {
1327
            error_log($msg);
1328
        }
1329
        return $msg;
1330
    }
1331
1332
    if (!empty($params['language'])) {
1333
        $language = $params['language'];
1334
    }
1335
    if (!empty($params['phone'])) {
1336
        $phone = $params['phone'];
1337
    }
1338
    if (!empty($params['expiration_date'])) {
1339
        $expiration_date = $params['expiration_date'];
1340
    }
1341
1342
    // Check whether x_user_id exists into user_field_values table.
1343
    $user_id = UserManager::get_user_id_from_original_id(
1344
        $original_user_id_value,
1345
        $original_user_id_name
1346
    );
1347
1348
    if ($debug) {
1349
        error_log('Ready to create user');
1350
    }
1351
1352
    if ($user_id > 0) {
1353
        if ($debug) {
1354
            error_log('User found with id: '.$user_id);
1355
        }
1356
1357
        // Check whether user is not active
1358
        //@todo why this condition exists??
1359
        $sql = "SELECT user_id FROM $table_user
1360
                WHERE user_id ='".$user_id."' AND active= '0' ";
1361
        $resu = Database::query($sql);
1362
        $r_check_user = Database::fetch_row($resu);
1363
        $count_check_user = Database::num_rows($resu);
1364
        if ($count_check_user > 0) {
1365
            if ($debug) {
1366
                error_log('User id: '.$user_id.' exists and is NOT active. Updating user and setting setting active = 1');
1367
            }
1368
            $sql = "UPDATE $table_user SET
1369
                    lastname='".Database::escape_string($lastName)."',
1370
                    firstname='".Database::escape_string($firstName)."',
1371
                    username='".Database::escape_string($loginName)."',";
1372
1373
            if (!is_null($auth_source)) {
1374
                $sql .= " auth_source='".Database::escape_string($auth_source)."',";
1375
            }
1376
            $sql .= "
1377
                    password='".Database::escape_string($password)."',
1378
                    email='".Database::escape_string($email)."',
1379
                    status='".Database::escape_string($status)."',
1380
                    official_code='".Database::escape_string($official_code)."',
1381
                    phone='".Database::escape_string($phone)."',
1382
                    expiration_date='".Database::escape_string($expiration_date)."',
1383
                    active='1',
1384
                    hr_dept_id=".intval($hr_dept_id)." 
1385
                WHERE user_id='".$r_check_user[0]."'";
1386
1387
            Database::query($sql);
1388
1389
            if (is_array($extra_list) && count($extra_list) > 0) {
1390
                foreach ($extra_list as $extra) {
1391
                    $extra_field_name = $extra['field_name'];
1392
                    $extra_field_value = $extra['field_value'];
1393
                    // Save the external system's id into user_field_value table.
1394
                    UserManager::update_extra_field_value(
1395
                        $r_check_user[0],
1396
                        $extra_field_name,
1397
                        $extra_field_value
1398
                    );
1399
                }
1400
            }
1401
            return $r_check_user[0];
1402
        } else {
1403
            if ($debug) {
1404
                error_log('User exists but is active. Cant be updated');
1405
            }
1406
            return 0;
1407
        }
1408
    } else {
1409
        if ($debug) {
1410
            error_log("User not found with original_id = $original_user_id_value and original_name = $original_user_id_name");
1411
        }
1412
    }
1413
1414
    // Default language.
1415
    if (empty($language)) {
1416
        $language = api_get_setting('platformLanguage');
1417
    }
1418
1419
    $creator_id = DEFAULT_ADMIN_USER_ID;
1420
1421
    // First check wether the login already exists
1422
    if (!UserManager::is_username_available($loginName)) {
1423
        if ($debug) {
1424
            error_log("Username $loginName is not available");
1425
        }
1426
        return 0;
1427
    }
1428
1429
    $queryExpirationDate = '';
1430
    if (!empty($params['expiration_date'])) {
1431
        $queryExpirationDate = "expiration_date     = '".Database::escape_string($expiration_date)."', ";
1432
    }
1433
1434
    $sql = "INSERT INTO $table_user SET
1435
            lastname            = '".Database::escape_string(trim($lastName))."',
1436
            firstname           = '".Database::escape_string(trim($firstName))."',
1437
            username            = '".Database::escape_string(trim($loginName))."',
1438
            username_canonical  = '".Database::escape_string(api_strtolower(trim($loginName)))."',
1439
            status              = '".Database::escape_string($status)."',
1440
            password            = '".Database::escape_string($password)."',
1441
            email               = '".Database::escape_string($email)."',
1442
            official_code       = '".Database::escape_string($official_code)."',
1443
            picture_uri         = '".Database::escape_string($picture_uri)."',
1444
            creator_id          = '".Database::escape_string($creator_id)."',
1445
            auth_source         = '".Database::escape_string($auth_source)."',
1446
            phone               = '".Database::escape_string($phone)."',
1447
            language            = '".Database::escape_string($language)."',
1448
            registration_date   = '".api_get_utc_datetime()."',
1449
            roles = 'a:0:{}', 
1450
            ".$queryExpirationDate."
1451
            hr_dept_id          = '".Database::escape_string($hr_dept_id)."',
1452
            active              = '".Database::escape_string($active)."'";
1453
1454
    Database::query($sql);
1455
    $return = Database::insert_id();
1456
    if ($return) {
1457
        $sql = "UPDATE $table_user SET user_id = id WHERE id = $return";
1458
        Database::query($sql);
1459
1460
        $url_id = api_get_current_access_url_id();
1461
        UrlManager::add_user_to_url($return, $url_id);
1462
        if ($debug) {
1463
            error_log("Adding user_id = $return to URL id $url_id ");
1464
        }
1465
1466
        // Create extra field for the original_user_id_name
1467
        UserManager::create_extra_field(
1468
            $original_user_id_name,
1469
            1,
1470
            $original_user_id_name,
1471
            ''
1472
        );
1473
        // Save the remote system's id into user_field_value table.
1474
        UserManager::update_extra_field_value(
1475
            $return,
1476
            $original_user_id_name,
1477
            $original_user_id_value
1478
        );
1479
1480
        // Create extra fields
1481
        if (is_array($extra_list) && count($extra_list) > 0) {
1482
            foreach ($extra_list as $extra) {
1483
                $extra_field_name   = $extra['field_name'];
1484
                $extra_field_value  = $extra['field_value'];
1485
                // save new fieldlabel into user_field table
1486
                UserManager::create_extra_field(
1487
                    $extra_field_name,
1488
                    1,
1489
                    $extra_field_name,
1490
                    ''
1491
                );
1492
                // save the external system's id into user_field_value table'
1493
                UserManager::update_extra_field_value(
1494
                    $return,
1495
                    $extra_field_name,
1496
                    $extra_field_value
1497
                );
1498
            }
1499
        }
1500
    } else {
1501
        if ($debug) {
1502
            error_log('Error while inserting a user');
1503
        }
1504
1505
        return 0;
1506
    }
1507
1508
    return $return;
1509
}
1510
1511
/* Register WSEditUsers function */
1512
// Register the data structures used by the service
1513
$server->wsdl->addComplexType(
1514
    'editUsersParams',
1515
    'complexType',
1516
    'struct',
1517
    'all',
1518
    '',
1519
    [
1520
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
1521
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
1522
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
1523
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
1524
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
1525
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
1526
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
1527
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
1528
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
1529
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
1530
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
1531
    ]
1532
);
1533
1534
$server->wsdl->addComplexType(
1535
    'editUsersParamsList',
1536
    'complexType',
1537
    'array',
1538
    '',
1539
    'SOAP-ENC:Array',
1540
    [],
1541
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:editUsersParams[]']],
1542
    'tns:editUsersParams'
1543
);
1544
1545
$server->wsdl->addComplexType(
1546
    'editUsers',
1547
    'complexType',
1548
    'struct',
1549
    'all',
1550
    '',
1551
    [
1552
        'users' => ['name' => 'users', 'type' => 'tns:editUsersParamsList'],
1553
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
1554
    ]
1555
);
1556
1557
/* Register WSEditUserCredentials function */
1558
// Register the data structures used by the service
1559
$server->wsdl->addComplexType(
1560
    'editUserCredentials',
1561
    'complexType',
1562
    'struct',
1563
    'all',
1564
    '',
1565
    [
1566
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
1567
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
1568
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
1569
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
1570
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string']
1571
    ]
1572
);
1573
1574
// Register the method to expose
1575
$server->register(
1576
    'WSEditUserCredentials', // method name
1577
    ['editUserCredentials' => 'tns:editUserCredentials'], // input parameters
1578
    ['return' => 'xsd:string'], // output parameters
1579
    'urn:WSRegistration', // namespace
1580
    'urn:WSRegistration#WSEditUserCredentials', // soapaction
1581
    'rpc', // style
1582
    'encoded', // use
1583
    'This service edits the username and password of a user'    // documentation
1584
);
1585
1586
/**
1587
 * Define the method WSEditUser
1588
 * @param array $params
1589
 * @return bool|int|null|soap_fault
1590
 * @throws \Doctrine\DBAL\DBALException
1591
 */
1592
function WSEditUserCredentials($params)
1593
{
1594
    if (!WSHelperVerifyKey($params)) {
1595
        return returnError(WS_ERROR_SECRET_KEY);
1596
    }
1597
1598
    $userManager = UserManager::getManager();
1599
    $userRepository = UserManager::getRepository();
1600
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1601
    $original_user_id_value = $params['original_user_id_value'];
1602
    $original_user_id_name = $params['original_user_id_name'];
1603
    $username = $params['username'];
1604
    $password = null;
1605
1606
    if (!empty($params['password'])) {
1607
        $password = $params['password'];
1608
    }
1609
1610
    // Get user id from the other system ID
1611
    $user_id = UserManager::get_user_id_from_original_id(
1612
        $original_user_id_value,
1613
        $original_user_id_name
1614
    );
1615
1616
    if ($user_id == 0) {
1617
        return 0;
1618
    } else {
1619
        $sql = "SELECT user_id FROM $table_user
1620
                WHERE user_id ='$user_id' AND active= '0'";
1621
        $resu = Database::query($sql);
1622
        $r_check_user = Database::fetch_row($resu);
1623
        if (!empty($r_check_user[0])) {
1624
            return 0;
1625
        }
1626
    }
1627
1628
    // Check whether username already exits.
1629
    $sql = "SELECT username FROM $table_user
1630
            WHERE username = '$username' AND user_id <> '$user_id'";
1631
    $res_un = Database::query($sql);
1632
    $r_username = Database::fetch_row($res_un);
1633
1634
    if (!empty($r_username[0])) {
1635
        return 0;
1636
    }
1637
1638
    /** @var User $user */
1639
    $user = $userRepository->find($user_id);
1640
    if ($user) {
1641
        $user->setUsername($username);
1642
        if (!is_null($password)) {
1643
            $user->setPlainPassword($password);
1644
        }
1645
1646
        $userManager->updateUser($user, true);
1647
1648
        return true;
1649
    }
1650
1651
    return false;
1652
}
1653
1654
// Prepare output params, in this case will return an array
1655
$server->wsdl->addComplexType(
1656
    'result_editUsers',
1657
    'complexType',
1658
    'struct',
1659
    'all',
1660
    '',
1661
    [
1662
        'original_user_id_value' => [
1663
            'name' => 'original_user_id_value',
1664
            'type' => 'xsd:string'
1665
        ],
1666
        'result' => ['name' => 'result', 'type' => 'xsd:string']
1667
    ]
1668
);
1669
1670
$server->wsdl->addComplexType(
1671
    'results_editUsers',
1672
    'complexType',
1673
    'array',
1674
    '',
1675
    'SOAP-ENC:Array',
1676
    [],
1677
    [
1678
        [
1679
            'ref' => 'SOAP-ENC:arrayType',
1680
            'wsdl:arrayType' => 'tns:result_editUsers[]'
1681
        ]
1682
    ],
1683
    'tns:result_editUsers'
1684
);
1685
1686
// Register the method to expose
1687
$server->register(
1688
    'WSEditUsers', // method name
1689
    ['editUsers' => 'tns:editUsers'], // input parameters
1690
    ['return' => 'tns:results_editUsers'], // output parameters
1691
    'urn:WSRegistration', // namespace
1692
    'urn:WSRegistration#WSEditUsers', // soapaction
1693
    'rpc', // style
1694
    'encoded', // use
1695
    'This service edits a user from wiener'     // documentation
1696
);
1697
1698
// Define the method WSEditUsers
1699
function WSEditUsers($params)
1700
{
1701
    if (!WSHelperVerifyKey($params)) {
1702
        return returnError(WS_ERROR_SECRET_KEY);
1703
    }
1704
1705
    $userManager = UserManager::getManager();
1706
    $userRepository = UserManager::getRepository();
1707
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1708
1709
    $users_params = $params['users'];
1710
    $results = [];
1711
    $orig_user_id_value = [];
1712
1713
    foreach ($users_params as $user_param) {
1714
        $original_user_id_value = $user_param['original_user_id_value'];
1715
        $original_user_id_name = $user_param['original_user_id_name'];
1716
        $orig_user_id_value[] = $original_user_id_value;
1717
        $firstname = $user_param['firstname'];
1718
        $lastname = $user_param['lastname'];
1719
        $username = $user_param['username'];
1720
        $password = null;
1721
        $auth_source = null;
1722
        $email = $user_param['email'];
1723
        $status = $user_param['status'];
1724
        $official_code = '';
1725
        $phone = $user_param['phone'];
1726
        $expiration_date = $user_param['expiration_date'];
1727
        $creator_id = null;
1728
        $hr_dept_id = 0;
1729
        $extra = null;
1730
        $extra_list = $user_param['extra'];
1731
1732
        if (!empty($user_param['password'])) {
1733
            $password = $user_param['password'];
1734
        }
1735
1736
        // Get user id
1737
        $user_id = UserManager::get_user_id_from_original_id(
1738
            $original_user_id_value,
1739
            $original_user_id_name
1740
        );
1741
1742
        if ($user_id == 0) {
1743
            $results[] = 0; // Original_user_id_value doesn't exist.
1744
            continue;
1745
        } else {
1746
            $sql = "SELECT user_id FROM $table_user
1747
                    WHERE user_id ='$user_id' AND active= '0'";
1748
            $resu = Database::query($sql);
1749
            $r_check_user = Database::fetch_row($resu);
1750
            if (!empty($r_check_user[0])) {
1751
                $results[] = 0; // user_id is not active.
1752
                continue;
1753
            }
1754
        }
1755
1756
        // Check whether username already exits.
1757
        $sql = "SELECT username FROM $table_user
1758
                WHERE username = '$username' AND user_id <> '$user_id'";
1759
        $res_un = Database::query($sql);
1760
        $r_username = Database::fetch_row($res_un);
1761
1762
        if (!empty($r_username[0])) {
1763
            $results[] = 0; // username already exits.
1764
            continue;
1765
        }
1766
        // Edit lastname and firstname only if not empty
1767
1768
        /** @var User $user */
1769
        $user = $userRepository->find($user_id);
1770
1771
        if (!empty($lastname)) {
1772
            $user->setLastname($lastname);
1773
        }
1774
        if (!empty($firstname)) {
1775
            $user->setFirstname($firstname);
1776
        }
1777
        $user->setUsername($username);
1778
        if (!is_null($password)) {
1779
            $user->setPlainPassword($password);
1780
        }
1781
        if (!is_null($auth_source)) {
1782
            $user->setAuthSource($auth_source);
1783
        }
1784
1785
        // Exception for admins in case no status is provided in WS call...
1786
        $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
1787
        $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
1788
        $resadmin = Database::query($sqladmin);
1789
        $is_admin = Database::num_rows($resadmin);
1790
1791
        if (empty($status)) {
1792
            $status = 5;
1793
        }
1794
1795
        if ($is_admin) {
1796
            $status = 1;
1797
        }
1798
1799
        if (!empty($expiration_date)) {
1800
            $expiration_date = new DateTime($expiration_date);
1801
        }
1802
1803
        $user
1804
            ->setEmail($email)
1805
            ->setStatus($status)
1806
            ->setOfficialCode($official_code)
1807
            ->setPhone($phone)
1808
            ->setExpirationDate($expiration_date)
1809
            ->setHrDeptId($hr_dept_id)
1810
            ->setActive(true);
1811
1812
        if (!is_null($creator_id)) {
1813
            $user->setCreatorId($creator_id);
1814
        }
1815
1816
        $userManager->updateUser($user, true);
1817
1818
        if (is_array($extra_list) && count($extra_list) > 0) {
1819
            foreach ($extra_list as $extra) {
1820
                $extra_field_name = $extra['field_name'];
1821
                $extra_field_value = $extra['field_value'];
1822
                // Save the external system's id into user_field_value table.
1823
                UserManager::update_extra_field_value(
1824
                    $user_id,
1825
                    $extra_field_name,
1826
                    $extra_field_value
1827
                );
1828
            }
1829
        }
1830
1831
        $results[] = $user->getId();
1832
        continue;
1833
    }
1834
1835
    $count_results = count($results);
1836
    $output = [];
1837
    for ($i = 0; $i < $count_results; $i++) {
1838
        $output[] = [
1839
            'original_user_id_value' => $orig_user_id_value[$i],
1840
            'result' => $results[$i],
1841
        ];
1842
    }
1843
1844
    return $output;
1845
}
1846
1847
/* Register WSEditUser function */
1848
// Register the data structures used by the service
1849
$server->wsdl->addComplexType(
1850
    'editUser',
1851
    'complexType',
1852
    'struct',
1853
    'all',
1854
    '',
1855
    [
1856
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
1857
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
1858
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
1859
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
1860
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
1861
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
1862
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
1863
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
1864
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
1865
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
1866
        'enable' => ['name' => 'enable', 'type' => 'xsd:boolean'],
1867
        'language' => ['name' => 'language', 'type' => 'xsd:string'],
1868
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList'],
1869
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
1870
    ]
1871
);
1872
1873
// Register the method to expose
1874
$server->register(
1875
    'WSEditUser', // method name
1876
    ['editUser' => 'tns:editUser'], // input parameters
1877
    ['return' => 'xsd:string'], // output parameters
1878
    'urn:WSRegistration', // namespace
1879
    'urn:WSRegistration#WSEditUser', // soapaction
1880
    'rpc', // style
1881
    'encoded', // use
1882
    'This service edits a user from wiener'  // documentation
1883
);
1884
1885
// Define the method WSEditUser
1886
function WSEditUser($params)
1887
{
1888
    if (!WSHelperVerifyKey($params)) {
1889
        return returnError(WS_ERROR_SECRET_KEY);
1890
    }
1891
1892
    $userManager = UserManager::getManager();
1893
    $userRepository = UserManager::getRepository();
1894
1895
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1896
1897
    $original_user_id_value = $params['original_user_id_value'];
1898
    $original_user_id_name = $params['original_user_id_name'];
1899
    $firstname = $params['firstname'];
1900
    $lastname = $params['lastname'];
1901
    $username = $params['username'];
1902
    $password = null;
1903
    $auth_source = null;
1904
    $email = $params['email'];
1905
    $status = $params['status'];
1906
    $official_code = '';
1907
    $phone = $params['phone'];
1908
    $picture_uri = '';
1909
    $expiration_date = $params['expiration_date'];
1910
    $enable = $params['enable'];
1911
    $language = $params['language'];
1912
    $creator_id = null;
1913
    $hr_dept_id = 0;
1914
    $extra = null;
1915
    $extra_list = $params['extra'];
1916
1917
    if (!empty($params['password'])) {
1918
        $password = $params['password'];
1919
    }
1920
1921
    // Get user id from id wiener
1922
    $user_id = UserManager::get_user_id_from_original_id(
1923
        $original_user_id_value,
1924
        $original_user_id_name
1925
    );
1926
1927
    if ($user_id == 0) {
1928
        return 0;
1929
    } elseif (empty($enable)) {
1930
        $sql = "SELECT user_id FROM $table_user
1931
                WHERE user_id ='$user_id' AND active= '0'";
1932
        $resu = Database::query($sql);
1933
        $r_check_user = Database::fetch_row($resu);
1934
        if (!empty($r_check_user[0])) {
1935
            return 0;
1936
        }
1937
    }
1938
1939
    // Check whether username already exits.
1940
    $sql = "SELECT username FROM $table_user
1941
            WHERE username = '$username' AND user_id <> '$user_id'";
1942
    $res_un = Database::query($sql);
1943
    $r_username = Database::fetch_row($res_un);
1944
1945
    if (!empty($r_username[0])) {
1946
        return 0;
1947
    }
1948
1949
    /** @var User $user */
1950
    $user = $userRepository->find($user_id);
1951
1952
    if (!empty($lastname)) {
1953
        $user->setLastname($lastname);
1954
    }
1955
    if (!empty($firstname)) {
1956
        $user->setFirstname($firstname);
1957
    }
1958
    $user->setUsername($username);
1959
    if (!is_null($password)) {
1960
        $user->setPlainPassword($password);
1961
    }
1962
    if (!is_null($auth_source)) {
1963
        $user->setAuthSource($auth_source);
1964
    }
1965
1966
    // Exception for admins in case no status is provided in WS call...
1967
    $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
1968
    $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
1969
    $resadmin = Database::query($sqladmin);
1970
    $is_admin = Database::num_rows($resadmin);
1971
1972
    if (empty($status)) {
1973
        $status = 5;
1974
    }
1975
1976
    if ($is_admin) {
1977
        $status = 1;
1978
    }
1979
1980
    if (!empty($expiration_date)) {
1981
        $expiration_date = new DateTime($expiration_date);
1982
        $user->setExpirationDate($expiration_date);
1983
    }
1984
    if (!empty($language)) {
1985
        $user->setLanguage($language);
1986
    }
1987
1988
    $user
1989
        ->setEmail($email)
1990
        ->setStatus($status)
1991
        ->setOfficialCode($official_code)
1992
        ->setPhone($phone)
1993
        ->setPictureUri($picture_uri)
1994
        ->setHrDeptId($hr_dept_id)
1995
        ->setActive(true);
1996
1997
    if (!is_null($creator_id)) {
1998
        $user->setCreatorId($creator_id);
1999
    }
2000
2001
    $userManager->updateUser($user, true);
2002
2003
    if (is_array($extra_list) && count($extra_list) > 0) {
2004
        foreach ($extra_list as $extra) {
2005
            $extra_field_name = $extra['field_name'];
2006
            $extra_field_value = $extra['field_value'];
2007
            // Save the external system's id into user_field_value table.
2008
            UserManager::update_extra_field_value(
2009
                $user_id,
2010
                $extra_field_name,
2011
                $extra_field_value
2012
            );
2013
        }
2014
    }
2015
2016
    return  $user_id;
2017
}
2018
2019
/* Register WSEditUserWithPicture function */
2020
// Register the data structures used by the service
2021
$server->wsdl->addComplexType(
2022
    'editUserWithPicture',
2023
    'complexType',
2024
    'struct',
2025
    'all',
2026
    '',
2027
    [
2028
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2029
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
2030
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
2031
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
2032
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
2033
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
2034
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
2035
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
2036
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
2037
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
2038
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList'],
2039
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
2040
        'picture_url' => ['name' => 'picture_url', 'type' => 'xsd:string']
2041
    ]
2042
);
2043
2044
// Register the method to expose
2045
$server->register(
2046
    'WSEditUserWithPicture', // method name
2047
    ['editUserWithPicture' => 'tns:editUserWithPicture'], // input parameters
2048
    ['return' => 'xsd:string'], // output parameters
2049
    'urn:WSRegistration', // namespace
2050
    'urn:WSRegistration#WSEditUserWithPicture', // soapaction
2051
    'rpc', // style
2052
    'encoded', // use
2053
    'This service edits a user from wiener'             // documentation
2054
);
2055
2056
// Define the method WSEditUserWithPicture
2057
function WSEditUserWithPicture($params)
2058
{
2059
    if (!WSHelperVerifyKey($params)) {
2060
        return returnError(WS_ERROR_SECRET_KEY);
2061
    }
2062
2063
    $userManager = UserManager::getManager();
2064
    $userRepository = UserManager::getRepository();
2065
2066
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
2067
2068
    $original_user_id_value = $params['original_user_id_value'];
2069
    $original_user_id_name = $params['original_user_id_name'];
2070
    $firstname = $params['firstname'];
2071
    $lastname = $params['lastname'];
2072
    $username = $params['username'];
2073
    $password = null;
2074
    $auth_source = null;
2075
    $email = $params['email'];
2076
    $expiration_date = null;
2077
    $status = $params['status'];
2078
    $phone = $params['phone'];
2079
    $picture_url = $params['picture_url'];
2080
    $pictureUri = '';
2081
    $creator_id = null;
2082
    $hr_dept_id = 0;
2083
    $extra = null;
2084
    $extra_list = $params['extra'];
2085
    if (!empty($params['expiration_date'])) {
2086
        $expiration_date = $params['expiration_date'];
2087
    }
2088
2089
    if (!empty($params['password'])) {
2090
        $password = $params['password'];
2091
    }
2092
2093
    // Get user id from external id
2094
    $user_id = UserManager::get_user_id_from_original_id(
2095
        $original_user_id_value,
2096
        $original_user_id_name
2097
    );
2098
2099
    // Get picture and generate uri.
2100
    $filename = basename($picture_url);
2101
    $tempDir = api_get_path(SYS_ARCHIVE_PATH);
2102
    // Make sure the file download was OK by checking the HTTP headers for OK
2103
    if (strpos(get_headers($picture_url)[0], "OK")) {
0 ignored issues
show
Bug introduced by
The call to get_headers() has too few arguments starting with context. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2103
    if (strpos(/** @scrutinizer ignore-call */ get_headers($picture_url)[0], "OK")) {

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
2104
        file_put_contents($tempDir.$filename, file_get_contents($picture_url));
2105
        $pictureUri = UserManager::update_user_picture($user_id, $filename, $tempDir.$filename);
2106
    }
2107
2108
    if ($user_id == 0) {
2109
        return 0;
2110
    } else {
2111
        $sql = "SELECT id FROM $table_user WHERE id =$user_id AND active= 0";
2112
        $resu = Database::query($sql);
2113
        $r_check_user = Database::fetch_row($resu);
2114
        if (!empty($r_check_user[0])) {
2115
            return 0;
2116
        }
2117
    }
2118
2119
    // Check whether username already exits.
2120
    $sql = "SELECT username FROM $table_user 
2121
            WHERE username = '$username' AND id <> $user_id";
2122
    $res_un = Database::query($sql);
2123
    $r_username = Database::fetch_row($res_un);
2124
2125
    if (!empty($r_username[0])) {
2126
        return 0;
2127
    }
2128
2129
    /** @var User $user */
2130
    $user = $userRepository->find($user_id);
2131
2132
    if (!empty($lastname)) {
2133
        $user->setLastname($lastname);
2134
    }
2135
    if (!empty($firstname)) {
2136
        $user->setFirstname($firstname);
2137
    }
2138
    $user->setUsername($username);
2139
    if (!is_null($password)) {
2140
        $user->setPlainPassword($password);
2141
    }
2142
    if (!is_null($auth_source)) {
2143
        $user->setAuthSource($auth_source);
2144
    }
2145
2146
    // Exception for admins in case no status is provided in WS call...
2147
    $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
2148
    $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
2149
    $resadmin = Database::query($sqladmin);
2150
    $is_admin = Database::num_rows($resadmin);
2151
2152
    if (empty($status)) {
2153
        $status = $user->getStatus();
2154
    }
2155
2156
    if ($is_admin) {
2157
        $status = 1;
2158
    }
2159
2160
    if (!empty($expiration_date)) {
2161
        $expiration_date = new DateTime($expiration_date);
2162
    }
2163
2164
    $user
2165
        ->setEmail($email)
2166
        ->setStatus($status)
2167
        ->setPhone($phone)
2168
        ->setExpirationDate($expiration_date)
2169
        ->setHrDeptId($hr_dept_id)
2170
        ->setActive(true)
2171
        ->setPictureUri($pictureUri);
2172
2173
    if (!is_null($creator_id)) {
2174
        $user->setCreatorId($creator_id);
2175
    }
2176
2177
    $userManager->updateUser($user, true);
2178
2179
    if (is_array($extra_list) && count($extra_list) > 0) {
2180
        foreach ($extra_list as $extra) {
2181
            $extra_field_name = $extra['field_name'];
2182
            $extra_field_value = $extra['field_value'];
2183
            // Save the external system's id into user_field_value table.
2184
            UserManager::update_extra_field_value(
2185
                $user_id,
2186
                $extra_field_name,
2187
                $extra_field_value
2188
            );
2189
        }
2190
    }
2191
2192
    return $user_id;
2193
}
2194
2195
/* Register WSEditUsersPasswordCrypted function */
2196
// Register the data structures used by the service
2197
$server->wsdl->addComplexType(
2198
    'editUsersPasswordCryptedParams',
2199
    'complexType',
2200
    'struct',
2201
    'all',
2202
    '',
2203
    [
2204
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2205
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
2206
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
2207
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
2208
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
2209
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
2210
        'encrypt_method' => ['name' => 'encrypt_method', 'type' => 'xsd:string'],
2211
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
2212
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
2213
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
2214
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
2215
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
2216
    ]
2217
);
2218
2219
$server->wsdl->addComplexType(
2220
    'editUsersPasswordCryptedParamsList',
2221
    'complexType',
2222
    'array',
2223
    '',
2224
    'SOAP-ENC:Array',
2225
    [],
2226
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:editUsersPasswordCryptedParams[]']],
2227
    'tns:editUsersPasswordCryptedParams'
2228
);
2229
2230
$server->wsdl->addComplexType(
2231
    'editUsersPasswordCrypted',
2232
    'complexType',
2233
    'struct',
2234
    'all',
2235
    '',
2236
    [
2237
        'users' => ['name' => 'users', 'type' => 'tns:editUsersPasswordCryptedParamsList'],
2238
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
2239
    ]
2240
);
2241
2242
// Prepare output params, in this case will return an array
2243
$server->wsdl->addComplexType(
2244
    'result_editUsersPasswordCrypted',
2245
    'complexType',
2246
    'struct',
2247
    'all',
2248
    '',
2249
    [
2250
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2251
        'result' => ['name' => 'result', 'type' => 'xsd:string']
2252
    ]
2253
);
2254
2255
$server->wsdl->addComplexType(
2256
    'results_editUsersPasswordCrypted',
2257
    'complexType',
2258
    'array',
2259
    '',
2260
    'SOAP-ENC:Array',
2261
    [],
2262
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_editUsersPasswordCrypted[]']],
2263
    'tns:result_editUsersPasswordCrypted'
2264
);
2265
2266
// Register the method to expose
2267
$server->register(
2268
    'WSEditUsersPasswordCrypted', // method name
2269
    ['editUsersPasswordCrypted' => 'tns:editUsersPasswordCrypted'], // input parameters
2270
    ['return' => 'tns:results_editUsersPasswordCrypted'], // output parameters
2271
    'urn:WSRegistration', // namespace
2272
    'urn:WSRegistration#WSEditUsersPasswordCrypted', // soapaction
2273
    'rpc', // style
2274
    'encoded', // use
2275
    'This service edits a user'                                           // documentation
2276
);
2277
2278
// Define the method WSEditUsersPasswordCrypted
2279
function WSEditUsersPasswordCrypted($params)
2280
{
2281
    global $_configuration;
2282
2283
    if (!WSHelperVerifyKey($params)) {
2284
        return returnError(WS_ERROR_SECRET_KEY);
2285
    }
2286
2287
    // get user id from id of remote system
2288
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
2289
    $users_params = $params['users'];
2290
    $results = [];
2291
    $orig_user_id_value = [];
2292
2293
    foreach ($users_params as $user_param) {
2294
        $original_user_id_value = $user_param['original_user_id_value'];
2295
        $original_user_id_name = $user_param['original_user_id_name'];
2296
        $orig_user_id_value[] = $original_user_id_value;
2297
        $firstname = $user_param['firstname'];
2298
        $lastname = $user_param['lastname'];
2299
        $username = $user_param['username'];
2300
        $password = null;
2301
        $auth_source = null;
2302
        $email = $user_param['email'];
2303
        $status = $user_param['status'];
2304
        $official_code = '';
2305
        $phone = $user_param['phone'];
2306
        $picture_uri = '';
2307
        $expiration_date = $user_param['expiration_date'];
2308
        $active = 1;
2309
        $creator_id = null;
2310
        $hr_dept_id = 0;
2311
        $extra = null;
2312
        $extra_list = $user_param['extra'];
2313
2314
        if (!empty($user_param['password']) && !empty($user_param['encrypt_method'])) {
2315
            $password = $user_param['password'];
2316
            $encrypt_method = $user_param['encrypt_method'];
2317
            if ($_configuration['password_encryption'] === $encrypt_method) {
2318
                if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
2319
                    $msg = "Encryption $encrypt_method is invalid";
2320
                    $results[] = $msg;
2321
                    continue;
2322
                } elseif ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
2323
                    $msg = "Encryption $encrypt_method is invalid";
2324
                    $results[] = $msg;
2325
                    continue;
2326
                }
2327
            } else {
2328
                $msg = "This encryption $encrypt_method is not configured";
2329
                $results[] = $msg;
2330
                continue;
2331
            }
2332
        } elseif (!empty($user_param['password']) && empty($user_param['encrypt_method'])) {
2333
            $msg = "If password is not empty the encrypt_method param is required ";
2334
            $results[] = $msg;
2335
            continue;
2336
        } elseif (empty($user_param['password']) && !empty($user_param['encrypt_method'])) {
2337
            $msg = "If encrypt_method is not empty the password param is required ";
2338
            $results[] = $msg;
2339
            continue;
2340
        }
2341
2342
        $user_id = UserManager::get_user_id_from_original_id(
2343
            $original_user_id_value,
2344
            $original_user_id_name
2345
        );
2346
2347
        if ($user_id == 0) {
2348
            $results[] = 0; // Original_user_id_value doesn't exist.
2349
            continue;
2350
        } else {
2351
            $sql = "SELECT user_id FROM $table_user
2352
                    WHERE user_id ='$user_id' AND active= '0'";
2353
            $resu = Database::query($sql);
2354
            $r_check_user = Database::fetch_row($resu);
2355
            if (!empty($r_check_user[0])) {
2356
                $results[] = 0; // user_id is not active
2357
                continue;
2358
            }
2359
        }
2360
2361
        // Check if username already exits.
2362
        $sql = "SELECT username FROM $table_user
2363
                WHERE username ='$username' AND user_id <> '$user_id'";
2364
        $res_un = Database::query($sql);
2365
        $r_username = Database::fetch_row($res_un);
2366
2367
        if (!empty($r_username[0])) {
2368
            $results[] = 0;
2369
            continue; // username already exits
2370
        }
2371
2372
        $sql = "UPDATE $table_user SET ";
2373
        if (!empty($lastname)) {
2374
            $sql .= " lastname='".Database::escape_string($lastname)."', ";
2375
        }
2376
        if (!empty($firstname)) {
2377
            $sql .= " firstname='".Database::escape_string($firstname)."', ";
2378
        }
2379
        $sql .= " username='".Database::escape_string($username)."',";
2380
        if (!is_null($password)) {
2381
            $sql .= " password='".Database::escape_string($password)."',";
2382
        }
2383
        if (!is_null($auth_source)) {
2384
            $sql .= " auth_source='".Database::escape_string($auth_source)."',";
2385
        }
2386
2387
        // Exception for admins in case no status is provided in WS call...
2388
        $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
2389
        $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
2390
        $resadmin = Database::query($sqladmin);
2391
        $is_admin = Database::num_rows($resadmin);
2392
2393
        if (empty($status)) {
2394
            $status = 5;
2395
        }
2396
2397
        if ($is_admin) {
2398
            $status = 1;
2399
        }
2400
2401
        $sql .= "
2402
                email='".Database::escape_string($email)."',
2403
                status='".Database::escape_string($status)."',
2404
                official_code='".Database::escape_string($official_code)."',
2405
                phone='".Database::escape_string($phone)."',
2406
                picture_uri='".Database::escape_string($picture_uri)."',
2407
                expiration_date='".Database::escape_string($expiration_date)."',
2408
                active='".Database::escape_string($active)."',
2409
                hr_dept_id=".intval($hr_dept_id);
2410
2411
        if (!is_null($creator_id)) {
2412
            $sql .= ", creator_id='".Database::escape_string($creator_id)."'";
2413
        }
2414
        $sql .= " WHERE user_id='$user_id'";
2415
        $return = @Database::query($sql);
2416
2417
        if (is_array($extra_list) && count($extra_list) > 0) {
2418
            foreach ($extra_list as $extra) {
2419
                $extra_field_name = $extra['field_name'];
2420
                $extra_field_value = $extra['field_value'];
2421
                // Save the external system's id into user_field_value table.
2422
                UserManager::update_extra_field_value(
2423
                    $user_id,
2424
                    $extra_field_name,
2425
                    $extra_field_value
2426
                );
2427
            }
2428
        }
2429
2430
        $results[] = $return;
2431
        continue;
2432
    } //end principal foreach
2433
2434
    $count_results = count($results);
2435
    $output = [];
2436
    for ($i = 0; $i < $count_results; $i++) {
2437
        $output[] = [
2438
            'original_user_id_value' => $orig_user_id_value[$i],
2439
            'result' => $results[$i]
2440
        ];
2441
    }
2442
2443
    return $output;
2444
}
2445
2446
/* Register WSEditUserPasswordCrypted function */
2447
// Register the data structures used by the service
2448
$server->wsdl->addComplexType(
2449
    'editUserPasswordCrypted',
2450
    'complexType',
2451
    'struct',
2452
    'all',
2453
    '',
2454
    [
2455
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2456
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
2457
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
2458
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
2459
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
2460
        'password' => ['name' => 'password', 'type' => 'xsd:string'],
2461
        'encrypt_method' => ['name' => 'encrypt_method', 'type' => 'xsd:string'],
2462
        'email' => ['name' => 'email', 'type' => 'xsd:string'],
2463
        'status' => ['name' => 'status', 'type' => 'xsd:string'],
2464
        'phone' => ['name' => 'phone', 'type' => 'xsd:string'],
2465
        'expiration_date' => ['name' => 'expiration_date', 'type' => 'xsd:string'],
2466
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList'],
2467
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
2468
    ]
2469
);
2470
2471
// Register the method to expose
2472
$server->register(
2473
    'WSEditUserPasswordCrypted', // method name
2474
    ['editUserPasswordCrypted' => 'tns:editUserPasswordCrypted'], // input parameters
2475
    ['return' => 'xsd:string'], // output parameters
2476
    'urn:WSRegistration', // namespace
2477
    'urn:WSRegistration#WSEditUserPasswordCrypted', // soapaction
2478
    'rpc', // style
2479
    'encoded', // use
2480
    'This service edits a user'                                        // documentation
2481
);
2482
2483
// Define the method WSEditUserPasswordCrypted
2484
function WSEditUserPasswordCrypted($params)
2485
{
2486
    global $_configuration, $debug;
2487
    if (!WSHelperVerifyKey($params)) {
2488
        return returnError(WS_ERROR_SECRET_KEY);
2489
    }
2490
2491
    if ($debug) {
2492
        error_log('WSEditUserPasswordCrypted');
2493
    }
2494
2495
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
2496
2497
    $original_user_id_value = $params['original_user_id_value'];
2498
    $original_user_id_name = $params['original_user_id_name'];
2499
2500
    $firstname = isset($params['firstname']) ? $params['firstname'] : '';
2501
    $lastname = isset($params['lastname']) ? $params['lastname'] : '';
2502
    $username = isset($params['username']) ? $params['username'] : '';
2503
    $password = null;
2504
    $auth_source = null;
2505
    $email = isset($params['email']) ? $params['email'] : '';
2506
    $status = isset($params['status']) ? $params['status'] : '';
2507
    $official_code = '';
2508
    $phone = isset($params['phone']) ? $params['phone'] : '';
2509
    $picture_uri = '';
2510
    $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : '';
2511
    $active = 1;
2512
    $creator_id = null;
2513
    $hr_dept_id = 0;
2514
    $extra = null;
2515
    $extra_list = isset($params['extra']) ? $params['extra'] : '';
2516
    $params['password'] = isset($params['password']) ? $params['password'] : '';
2517
    $params['encrypt_method'] = isset($params['encrypt_method']) ? $params['encrypt_method'] : '';
2518
2519
    if (!empty($params['password']) && !empty($params['encrypt_method'])) {
2520
        $password = $params['password'];
2521
        $encrypt_method = $params['encrypt_method'];
2522
        if ($_configuration['password_encryption'] === $encrypt_method) {
2523
            if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
2524
                $msg = "Encryption $encrypt_method is invalid";
2525
                return $msg;
2526
            } elseif ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
2527
                $msg = "Encryption $encrypt_method is invalid";
2528
                return $msg;
2529
            }
2530
        } else {
2531
            $msg = "This encryption $encrypt_method is not configured";
2532
            return $msg;
2533
        }
2534
    } elseif (!empty($params['password']) && empty($params['encrypt_method'])) {
2535
        $msg = "If password is not empty the encrypt_method param is required ";
2536
2537
        return $msg;
2538
    } elseif (empty($params['password']) && !empty($params['encrypt_method'])) {
2539
        $msg = "If encrypt_method is not empty the password param is required ";
2540
2541
        return $msg;
2542
    }
2543
2544
    $user_id = UserManager::get_user_id_from_original_id(
2545
        $original_user_id_value,
2546
        $original_user_id_name
2547
    );
2548
2549
    if ($debug) {
2550
        error_log("user: $user_id");
2551
    }
2552
2553
    if ($user_id == 0) {
2554
        return 0;
2555
    } else {
2556
        $sql = "SELECT user_id FROM $table_user
2557
                WHERE user_id ='$user_id' AND active= '0'";
2558
        $resu = Database::query($sql);
2559
        $r_check_user = Database::fetch_row($resu);
2560
        if (!empty($r_check_user[0])) {
2561
            return 0;
2562
        }
2563
    }
2564
2565
    // Check whether username already exits.
2566
    $sql = "SELECT username FROM $table_user
2567
            WHERE username ='$username' AND user_id <> '$user_id'";
2568
    $res_un = Database::query($sql);
2569
    $r_username = Database::fetch_row($res_un);
2570
2571
    if (!empty($r_username[0])) {
2572
        return 0;
2573
    }
2574
    // Edit lastname and firstname only if not empty
2575
    $sql = "UPDATE $table_user SET ";
2576
    if (!empty($lastname)) {
2577
        $sql .= " lastname='".Database::escape_string($lastname)."', ";
2578
    }
2579
    if (!empty($firstname)) {
2580
        $sql .= " firstname='".Database::escape_string($firstname)."', ";
2581
    }
2582
    $sql .= " username='".Database::escape_string($username)."',";
2583
2584
    if (!empty($password)) {
2585
        $sql .= " password='".Database::escape_string($password)."',";
2586
    }
2587
2588
    if (!empty($auth_source)) {
2589
        $sql .= " auth_source='".Database::escape_string($auth_source)."',";
2590
    }
2591
2592
    // Exception for admins in case no status is provided in WS call...
2593
    $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
2594
    $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
2595
    $resadmin = Database::query($sqladmin);
2596
    $is_admin = Database::num_rows($resadmin);
2597
2598
    if (empty($status)) {
2599
        $status = 5;
2600
    }
2601
2602
    if ($is_admin) {
2603
        $status = 1;
2604
    }
2605
2606
    $sql .= "
2607
            email='".Database::escape_string($email)."',
2608
            status='".Database::escape_string($status)."',
2609
            official_code='".Database::escape_string($official_code)."',
2610
            phone='".Database::escape_string($phone)."',
2611
            picture_uri='".Database::escape_string($picture_uri)."',
2612
            expiration_date='".Database::escape_string($expiration_date)."',
2613
            active='".Database::escape_string($active)."',
2614
            hr_dept_id=".intval($hr_dept_id);
2615
2616
    if (!is_null($creator_id)) {
2617
        $sql .= ", creator_id='".Database::escape_string($creator_id)."'";
2618
    }
2619
2620
    $sql .= " WHERE user_id='$user_id'";
2621
    $return = @Database::query($sql);
2622
2623
    if ($debug) {
2624
        error_log("SQL: $sql");
2625
    }
2626
2627
    if (is_array($extra_list) && count($extra_list) > 0) {
2628
        foreach ($extra_list as $extra) {
2629
            $extra_field_name = $extra['field_name'];
2630
            $extra_field_value = $extra['field_value'];
2631
            // save the external system's id into user_field_value table'
2632
            UserManager::update_extra_field_value(
2633
                $user_id,
2634
                $extra_field_name,
2635
                $extra_field_value
2636
            );
2637
        }
2638
    }
2639
2640
    if ($return) {
2641
        return 1;
2642
    }
2643
2644
    return 0;
2645
}
2646
2647
// Prepare output params for actions on users (delete, disable, enable), will return an array
2648
$server->wsdl->addComplexType(
2649
    'result_actionUsers',
2650
    'complexType',
2651
    'struct',
2652
    'all',
2653
    '',
2654
    [
2655
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2656
        'result' => ['name' => 'result', 'type' => 'xsd:string']
2657
    ]
2658
);
2659
2660
$server->wsdl->addComplexType(
2661
    'results_actionUsers',
2662
    'complexType',
2663
    'array',
2664
    '',
2665
    'SOAP-ENC:Array',
2666
    [],
2667
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_actionUsers[]']],
2668
    'tns:result_actionUsers'
2669
);
2670
2671
/** WSDeleteUsers **/
2672
$server->wsdl->addComplexType(
2673
    'user_id',
2674
    'complexType',
2675
    'struct',
2676
    'all',
2677
    '',
2678
    [
2679
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
2680
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string']
2681
    ]
2682
);
2683
2684
$server->wsdl->addComplexType(
2685
    'user_ids_array',
2686
    'complexType',
2687
    'array',
2688
    '',
2689
    'SOAP-ENC:Array',
2690
    [],
2691
    [
2692
        [
2693
            'ref' => 'SOAP-ENC:arrayType',
2694
            'wsdl:arrayType' => 'tns:user_id[]',
2695
        ],
2696
    ],
2697
    'tns:user_id'
2698
);
2699
2700
$server->wsdl->addComplexType(
2701
    'user_ids',
2702
    'complexType',
2703
    'struct',
2704
    'all',
2705
    '',
2706
    [
2707
        'ids' => ['name' => 'user_ids', 'type' => 'tns:user_ids_array'],
2708
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
2709
    ]
2710
);
2711
2712
function WSHelperActionOnUsers($params, $type)
2713
{
2714
    if (!WSHelperVerifyKey($params)) {
2715
        return returnError(WS_ERROR_SECRET_KEY);
2716
    }
2717
2718
    $results = [];
2719
    $orig_user_id_value = [];
2720
    $original_user_ids = $params['ids'];
2721
    foreach ($original_user_ids as $original_user_id) {
2722
        $result = false;
2723
        $orig_user_id_value[] = $original_user_id['original_user_id_value'];
2724
        $user_id = UserManager::get_user_id_from_original_id(
2725
            $original_user_id['original_user_id_value'],
2726
            $original_user_id['original_user_id_name']
2727
        );
2728
        if ($user_id > 0) {
2729
            if ($type == "delete") {
2730
                $result = UserManager::delete_user($user_id);
2731
            } elseif ($type == "disable") {
2732
                $result = UserManager::disable($user_id);
2733
            } elseif ($type == "enable") {
2734
                $result = UserManager::enable($user_id);
2735
            }
2736
        }
2737
        $results[] = $result ? 1 : 0;
2738
    }
2739
2740
2741
    $count_results = count($results);
2742
    $output = [];
2743
    for ($i = 0; $i < $count_results; $i++) {
2744
        $output[] = [
2745
            'original_user_id_value' => $orig_user_id_value[$i],
2746
            'result' => $results[$i]
2747
        ];
2748
    }
2749
2750
    return $output;
2751
}
2752
2753
$server->register(
2754
    'WSDeleteUsers', // method name
2755
    ['user_ids' => 'tns:user_ids'], // input parameters
2756
    ['return' => 'tns:results_actionUsers'], // output parameters
2757
    'urn:WSRegistration', // namespace
2758
    'urn:WSRegistration#WSDeleteUsers', // soapaction
2759
    'rpc', // style
2760
    'encoded', // use
2761
    'Deletes users provided as parameters from the system' // documentation
2762
);
2763
2764
function WSDeleteUsers($params)
2765
{
2766
    return WSHelperActionOnUsers($params, "delete");
2767
}
2768
2769
/** WSDisableUsers **/
2770
$server->register(
2771
    'WSDisableUsers', // method name
2772
    ['user_ids' => 'tns:user_ids'], // input parameters
2773
    ['return' => 'tns:results_actionUsers'], // output parameters
2774
    'urn:WSRegistration', // namespace
2775
    'urn:WSRegistration#WSDisableUsers', // soapaction
2776
    'rpc', // style
2777
    'encoded', // use
2778
    'Disables users provided as parameters from the system' // documentation
2779
);
2780
2781
function WSDisableUsers($params)
2782
{
2783
    return WSHelperActionOnUsers($params, "disable");
2784
}
2785
2786
/** WSEnableUsers **/
2787
$server->register(
2788
    'WSEnableUsers', // method name
2789
    ['user_ids' => 'tns:user_ids'], // input parameters
2790
    ['return' => 'tns:results_actionUsers'], // output parameters
2791
    'urn:WSRegistration', // namespace
2792
    'urn:WSRegistration#WSEnableUsers', // soapaction
2793
    'rpc', // style
2794
    'encoded', // use
2795
    'Enables users provided as parameters'    // documentation
2796
);
2797
2798
function WSEnableUsers($params)
2799
{
2800
    return WSHelperActionOnUsers($params, "enable");
2801
}
2802
2803
/* Register WSCreateCourse function */
2804
// Register the data structures used by the service
2805
2806
$server->wsdl->addComplexType(
2807
    'course_id',
2808
    'complexType',
2809
    'struct',
2810
    'all',
2811
    '',
2812
    [
2813
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
2814
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string']
2815
    ]
2816
);
2817
2818
$server->wsdl->addComplexType(
2819
    'createCourseParams',
2820
    'complexType',
2821
    'struct',
2822
    'all',
2823
    '',
2824
    [
2825
        'title' => ['name' => 'title', 'type' => 'xsd:string'],
2826
        'category_code' => ['name' => 'category_code', 'type' => 'xsd:string'],
2827
        'wanted_code' => ['name' => 'wanted_code', 'type' => 'xsd:string'],
2828
        'tutor_name' => ['name' => 'tutor_name', 'type' => 'xsd:string'],
2829
        'course_language' => ['name' => 'course_language', 'type' => 'xsd:string'],
2830
        'disk_quota' => ['name' => 'disk_quota', 'type' => 'xsd:string'], // disk_quota in MB
2831
        'subscribe' => ['name' => 'subscribe', 'type' => 'xsd:string'],
2832
        'unsubscribe' => ['name' => 'unsubscribe', 'type' => 'xsd:string'],
2833
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
2834
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
2835
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
2836
    ]
2837
);
2838
2839
$server->wsdl->addComplexType(
2840
    'createCourseParamsList',
2841
    'complexType',
2842
    'array',
2843
    '',
2844
    'SOAP-ENC:Array',
2845
    [],
2846
    [
2847
        [
2848
            'ref' => 'SOAP-ENC:arrayType',
2849
            'wsdl:arrayType' => 'tns:createCourseParams[]',
2850
        ],
2851
    ],
2852
    'tns:createCourseParams'
2853
);
2854
2855
// Register the data structures used by the service
2856
$server->wsdl->addComplexType(
2857
    'createCourse',
2858
    'complexType',
2859
    'struct',
2860
    'all',
2861
    '',
2862
    [
2863
        'courses' => ['name' => 'courses', 'type' => 'tns:createCourseParamsList'],
2864
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
2865
    ]
2866
);
2867
2868
// Prepare output params, in this case will return an array
2869
$server->wsdl->addComplexType(
2870
    'result_createCourse',
2871
    'complexType',
2872
    'struct',
2873
    'all',
2874
    '',
2875
    [
2876
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
2877
        'result' => ['name' => 'result', 'type' => 'xsd:string']
2878
    ]
2879
);
2880
2881
$server->wsdl->addComplexType(
2882
    'results_createCourse',
2883
    'complexType',
2884
    'array',
2885
    '',
2886
    'SOAP-ENC:Array',
2887
    [],
2888
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_createCourse[]']],
2889
    'tns:result_createCourse'
2890
);
2891
2892
// Register the method to expose
2893
$server->register(
2894
    'WSCreateCourse', // method name
2895
    ['createCourse' => 'tns:createCourse'], // input parameters
2896
    ['return' => 'tns:results_createCourse'], // output parameters
2897
    'urn:WSRegistration', // namespace
2898
    'urn:WSRegistration#WSCreateCourse', // soapaction
2899
    'rpc', // style
2900
    'encoded', // use
2901
    'This service adds a course'                   // documentation
2902
);
2903
2904
// Define the method WSCreateCourse
2905
function WSCreateCourse($params)
2906
{
2907
    if (!WSHelperVerifyKey($params)) {
2908
        return returnError(WS_ERROR_SECRET_KEY);
2909
    }
2910
    $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
2911
    $courses_params = $params['courses'];
2912
    $results = [];
2913
    $sessionAdminId = DEFAULT_ADMIN_USER_ID;
2914
    $orig_course_id_value = [];
2915
    foreach ($courses_params as $course_param) {
2916
        $title = $course_param['title'];
2917
        $category_code = isset($course_param['category_code']) ? $course_param['category_code'] : '';
2918
        $wanted_code = $course_param['wanted_code'];
2919
        $tutor_name = isset($course_param['tutor_name']) ? $course_param['tutor_name'] : '';
2920
        $diskQuota = isset($course_param['disk_quota']) ? $course_param['disk_quota'] : '100';
2921
        // Convert to MB
2922
        $diskQuota = $diskQuota * 1024 * 1024;
2923
2924
        $course_language = 'english'; // TODO: A hard-coded value.
2925
        $original_course_id_name = $course_param['original_course_id_name'];
2926
        $original_course_id_value = $course_param['original_course_id_value'];
2927
        $orig_course_id_value[] = $course_param['original_course_id_value'];
2928
        $visibility = null;
2929
        $subscribe = $course_param['subscribe'];
2930
        $unsubscribe = $course_param['unsubscribe'];
2931
2932
        if (isset($course_param['visibility'])) {
2933
            if ($course_param['visibility'] &&
2934
                $course_param['visibility'] >= 0 &&
2935
                $course_param['visibility'] <= 3
2936
            ) {
2937
                $visibility = $course_param['visibility'];
2938
            }
2939
        }
2940
        $extra_list = isset($course_param['extra']) ? $course_param['extra'] : '';
2941
2942
2943
        // Check whether exits $x_course_code into user_field_values table.
2944
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
2945
            $course_param['original_course_id_value'],
2946
            $course_param['original_course_id_name']
2947
        );
2948
2949
        if (!empty($courseInfo)) {
2950
            if ($courseInfo['visibility'] != 0) {
2951
                $sql = "UPDATE $table_course SET
2952
                            course_language='".Database::escape_string($course_language)."',
2953
                            title='".Database::escape_string($title)."',
2954
                            category_code='".Database::escape_string($category_code)."',
2955
                            tutor_name='".Database::escape_string($tutor_name)."',
2956
                            visual_code='".Database::escape_string($wanted_code)."'";
2957
                if ($visibility !== null) {
2958
                    $sql .= ", visibility = '$visibility' ";
2959
                }
2960
                $sql .= " WHERE id='".$courseInfo['real_id']."'";
2961
                Database::query($sql);
2962
                if (is_array($extra_list) && count($extra_list) > 0) {
2963
                    foreach ($extra_list as $extra) {
2964
                        $extra_field_name = $extra['field_name'];
2965
                        $extra_field_value = $extra['field_value'];
2966
                        // Save the external system's id into course_field_value table.
2967
                        CourseManager::update_course_extra_field_value(
2968
                            $courseInfo['code'],
2969
                            $extra_field_name,
2970
                            $extra_field_value
2971
                        );
2972
                    }
2973
                }
2974
                $results[] = $courseInfo['code'];
2975
                continue;
2976
            } else {
2977
                $results[] = 0;
2978
                continue; // Original course id already exits.
2979
            }
2980
        }
2981
2982
        if (!empty($course_param['course_language'])) {
2983
            $course_language = $course_param['course_language'];
2984
        }
2985
2986
        $params = [];
2987
        $params['title'] = $title;
2988
        $params['wanted_code'] = $wanted_code;
2989
        $params['category_code'] = $category_code;
2990
        $params['course_category'] = $category_code;
2991
        $params['tutor_name'] = $tutor_name;
2992
        $params['course_language'] = $course_language;
2993
        $params['user_id'] = $sessionAdminId;
2994
        $params['visibility'] = $visibility;
2995
        $params['disk_quota'] = $diskQuota;
2996
2997
        if (isset($subscribe) && $subscribe != '') { // Valid values: 0, 1
2998
            $params['subscribe'] = $subscribe;
2999
        }
3000
        if (isset($unsubscribe) && $subscribe != '') { // Valid values: 0, 1
3001
            $params['unsubscribe'] = $unsubscribe;
3002
        }
3003
3004
        $course_info = CourseManager::create_course($params, $sessionAdminId);
3005
3006
        if (!empty($course_info)) {
3007
            $course_code = $course_info['code'];
3008
3009
            // Save new field label into course_field table
3010
            CourseManager::create_course_extra_field(
3011
                $original_course_id_name,
3012
                1,
3013
                $original_course_id_name,
3014
                ''
3015
            );
3016
3017
            // Save the external system's id into user_field_value table.
3018
            CourseManager::update_course_extra_field_value(
3019
                $course_code,
3020
                $original_course_id_name,
3021
                $original_course_id_value
3022
            );
3023
3024
            if (is_array($extra_list) && count($extra_list) > 0) {
3025
                foreach ($extra_list as $extra) {
3026
                    $extra_field_name  = $extra['field_name'];
3027
                    $extra_field_value = $extra['field_value'];
3028
                    // Save new fieldlabel into course_field table.
3029
                    CourseManager::create_course_extra_field(
3030
                        $extra_field_name,
3031
                        1,
3032
                        $extra_field_name,
3033
                        ''
3034
                    );
3035
                    // Save the external system's id into course_field_value table.
3036
                    CourseManager::update_course_extra_field_value(
3037
                        $course_code,
3038
                        $extra_field_name,
3039
                        $extra_field_value
3040
                    );
3041
                }
3042
            }
3043
            $results[] = $course_code;
3044
        } else {
3045
            $results[] = 0;
3046
        }
3047
    } // end principal foreach
3048
3049
    $count_results = count($results);
3050
    $output = [];
3051
    for ($i = 0; $i < $count_results; $i++) {
3052
        $output[] = [
3053
            'original_course_id_value' => $orig_course_id_value[$i],
3054
            'result' => $results[$i],
3055
        ];
3056
    }
3057
3058
    return $output;
3059
}
3060
3061
/* Register WSCreateCourseByTitle function */
3062
// Register the data structures used by the service
3063
$server->wsdl->addComplexType(
3064
    'createCourseByTitleParams',
3065
    'complexType',
3066
    'struct',
3067
    'all',
3068
    '',
3069
    [
3070
        'title' => ['name' => 'title', 'type' => 'xsd:string'],
3071
        'tutor_name' => ['name' => 'tutor_name', 'type' => 'xsd:string'],
3072
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
3073
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3074
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
3075
    ]
3076
);
3077
3078
$server->wsdl->addComplexType(
3079
    'createCourseByTitleParamsList',
3080
    'complexType',
3081
    'array',
3082
    '',
3083
    'SOAP-ENC:Array',
3084
    [],
3085
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:createCourseByTitleParams[]']],
3086
    'tns:createCourseByTitleParams'
3087
);
3088
3089
// Register the data structures used by the service
3090
$server->wsdl->addComplexType(
3091
    'createCourseByTitle',
3092
    'complexType',
3093
    'struct',
3094
    'all',
3095
    '',
3096
    [
3097
        'courses' => ['name' => 'courses', 'type' => 'tns:createCourseByTitleParamsList'],
3098
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3099
    ]
3100
);
3101
3102
// Prepare output params, in this case will return an array
3103
$server->wsdl->addComplexType(
3104
    'result_createCourseByTitle',
3105
    'complexType',
3106
    'struct',
3107
    'all',
3108
    '',
3109
    [
3110
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3111
        'result' => ['name' => 'result', 'type' => 'xsd:string']
3112
    ]
3113
);
3114
3115
$server->wsdl->addComplexType(
3116
    'results_createCourseByTitle',
3117
    'complexType',
3118
    'array',
3119
    '',
3120
    'SOAP-ENC:Array',
3121
    [],
3122
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_createCourseByTitle[]']],
3123
    'tns:result_createCourseByTitle'
3124
);
3125
3126
3127
// Register the method to expose
3128
$server->register(
3129
    'WSCreateCourseByTitle', // method name
3130
    ['createCourseByTitle' => 'tns:createCourseByTitle'], // input parameters
3131
    ['return' => 'tns:results_createCourseByTitle'], // output parameters
3132
    'urn:WSRegistration', // namespace
3133
    'urn:WSRegistration#WSCreateCourseByTitle', // soapaction
3134
    'rpc', // style
3135
    'encoded', // use
3136
    'This service adds a course by title'                      // documentation
3137
);
3138
3139
// Define the method WSCreateCourseByTitle
3140
function WSCreateCourseByTitle($params)
3141
{
3142
    global $_configuration;
3143
    if (!WSHelperVerifyKey($params)) {
3144
        return returnError(WS_ERROR_SECRET_KEY);
3145
    }
3146
3147
    $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
3148
    $sessionAdminId = DEFAULT_ADMIN_USER_ID;
3149
    $courses_params = $params['courses'];
3150
    $results = [];
3151
    $orig_course_id_value = [];
3152
3153
    foreach ($courses_params as $course_param) {
3154
        $title = $course_param['title'];
3155
        $category_code = 'LANG'; // TODO: A hard-coded value.
3156
        $wanted_code = '';
3157
        $tutor_firstname = api_get_setting('administratorName');
3158
        $tutor_lastname = api_get_setting('administratorSurname');
3159
        $course_language = 'spanish'; // TODO: Incorrect default value, it should 'english'.
3160
        if (!empty($course_param['course_language'])) {
3161
            $course_language = $course_param['course_language'];
3162
        }
3163
        $tutor_name = api_get_person_name($tutor_firstname, $tutor_lastname, null, null, $course_language);
3164
        if (!empty($course_param['tutor_name'])) {
3165
            $tutor_name = $course_param['tutor_name'];
3166
        }
3167
        $original_course_id_name = $course_param['original_course_id_name'];
3168
        $original_course_id_value = $course_param['original_course_id_value'];
3169
        $orig_course_id_value[] = $course_param['original_course_id_value'];
3170
        $extra_list = $course_param['extra'];
3171
3172
        // Ensure the database prefix + database name do not get over 40 characters
3173
        $maxlength = 40;
3174
        if (empty($wanted_code)) {
3175
            $wanted_code = CourseManager::generate_course_code(substr($title, 0, $maxlength));
3176
        }
3177
3178
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
3179
            $original_course_id_value,
3180
            $original_course_id_name
3181
        );
3182
3183
        if (!empty($courseInfo)) {
3184
            if ($courseInfo['visibility'] != 0) {
3185
                $sql = "UPDATE $table_course SET
3186
                            course_language='".Database::escape_string($course_language)."',
3187
                            title='".Database::escape_string($title)."',
3188
                            category_code='".Database::escape_string($category_code)."',
3189
                            tutor_name='".Database::escape_string($tutor_name)."',
3190
                            visual_code='".Database::escape_string($wanted_code)."',
3191
                            visibility = '3'
3192
                        WHERE id ='".$courseInfo['real_id']."'";
3193
                Database::query($sql);
3194
                $results[] = $courseInfo['real_id'];
3195
                continue;
3196
            } else {
3197
                $results[] = 0;
3198
                continue;
3199
            }
3200
        }
3201
3202
        $values['course_language'] = api_get_setting('platformLanguage');
3203
3204
        $keys = AddCourse::define_course_keys($wanted_code, '', $_configuration['db_prefix']);
3205
3206
        $sql_check = sprintf('SELECT * FROM '.$table_course.' WHERE visual_code = "%s"', Database :: escape_string($wanted_code));
3207
        $result_check = Database::query($sql_check); // I don't know why this api function doesn't work...
3208
        if (Database::num_rows($result_check) < 1) {
3209
            $params = [];
3210
            $params['title'] = $title;
3211
            $params['wanted_code'] = $wanted_code;
3212
            $params['category_code'] = $category_code;
3213
            $params['tutor_name'] = $tutor_name;
3214
            $params['course_language'] = $course_language;
3215
            $params['user_id'] = $sessionAdminId;
3216
            $course_info = CourseManager::create_course($params, $sessionAdminId);
3217
            if (!empty($course_info)) {
3218
                $course_code = $course_info['code'];
3219
3220
                // Save new fieldlabel into course_field table.
3221
                CourseManager::create_course_extra_field(
3222
                    $original_course_id_name,
3223
                    1,
3224
                    $original_course_id_name,
3225
                    ''
3226
                );
3227
3228
                // Save the external system's id into user_field_value table.
3229
                CourseManager::update_course_extra_field_value(
3230
                    $course_code,
3231
                    $original_course_id_name,
3232
                    $original_course_id_value
3233
                );
3234
3235
                if (is_array($extra_list) && count($extra_list) > 0) {
3236
                    foreach ($extra_list as $extra) {
3237
                        $extra_field_name = $extra['field_name'];
3238
                        $extra_field_value = $extra['field_value'];
3239
                        // Save new fieldlabel into course_field table.
3240
                        CourseManager::create_course_extra_field(
3241
                            $extra_field_name,
3242
                            1,
3243
                            $extra_field_name,
3244
                            ''
3245
                        );
3246
                        // Save the external system's id into course_field_value table.
3247
                        CourseManager::update_course_extra_field_value(
3248
                            $course_code,
3249
                            $extra_field_name,
3250
                            $extra_field_value
3251
                        );
3252
                    }
3253
                }
3254
            }
3255
            $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...
3256
            continue;
3257
        } else {
3258
            $results[] = 0;
3259
            continue;
3260
        }
3261
    } // end principal foreach
3262
3263
    $count_results = count($results);
3264
    $output = [];
3265
    for ($i = 0; $i < $count_results; $i++) {
3266
        $output[] = [
3267
            'original_course_id_value' => $orig_course_id_value[$i],
3268
            'result' => $results[$i],
3269
        ];
3270
    }
3271
3272
    return $output;
3273
}
3274
3275
/* Register WSEditCourse function */
3276
// Register the data structures used by the service
3277
3278
$server->wsdl->addComplexType(
3279
    'editCourseParams',
3280
    'complexType',
3281
    'struct',
3282
    'all',
3283
    '',
3284
    [
3285
        'tutor_id' => ['name' => 'tutor_id', 'type' => 'xsd:string'],
3286
        'title' => ['name' => 'title', 'type' => 'xsd:string'],
3287
        'category_code' => ['name' => 'category_code', 'type' => 'xsd:string'],
3288
        'department_name' => ['name' => 'department_name', 'type' => 'xsd:string'],
3289
        'department_url' => ['name' => 'department_url', 'type' => 'xsd:string'],
3290
        'course_language' => ['name' => 'course_language', 'type' => 'xsd:string'],
3291
        'visibility' => ['name' => 'visibility', 'type' => 'xsd:string'],
3292
        'subscribe' => ['name' => 'subscribe', 'type' => 'xsd:string'],
3293
        'unsubscribe' => ['name' => 'unsubscribe', 'type' => 'xsd:string'],
3294
        'visual_code' => ['name' => 'visual_code', 'type' => 'xsd:string'],
3295
        'disk_quota' => ['name' => 'disk_quota', 'type' => 'xsd:string'], // disk_quota in MB
3296
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
3297
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3298
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
3299
    ]
3300
);
3301
3302
$server->wsdl->addComplexType(
3303
    'editCourseParamsList',
3304
    'complexType',
3305
    'array',
3306
    '',
3307
    'SOAP-ENC:Array',
3308
    [],
3309
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:editCourseParams[]']],
3310
    'tns:editCourseParams'
3311
);
3312
3313
$server->wsdl->addComplexType(
3314
    'editCourse',
3315
    'complexType',
3316
    'struct',
3317
    'all',
3318
    '',
3319
    [
3320
        'courses' => ['name' => 'courses', 'type' => 'tns:editCourseParamsList'],
3321
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3322
    ]
3323
);
3324
3325
// Prepare output params, in this case will return an array
3326
$server->wsdl->addComplexType(
3327
    'result_editCourse',
3328
    'complexType',
3329
    'struct',
3330
    'all',
3331
    '',
3332
    [
3333
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3334
        'result' => ['name' => 'result', 'type' => 'xsd:string']
3335
    ]
3336
);
3337
3338
$server->wsdl->addComplexType(
3339
    'results_editCourse',
3340
    'complexType',
3341
    'array',
3342
    '',
3343
    'SOAP-ENC:Array',
3344
    [],
3345
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_editCourse[]']],
3346
    'tns:result_editCourse'
3347
);
3348
3349
// Register the method to expose
3350
$server->register(
3351
    'WSEditCourse', // method name
3352
    ['editCourse' => 'tns:editCourse'], // input parameters
3353
    ['return' => 'tns:results_editCourse'], // output parameters
3354
    'urn:WSRegistration', // namespace
3355
    'urn:WSRegistration#WSEditCourse', // soapaction
3356
    'rpc', // style
3357
    'encoded', // use
3358
    'This service edits a course'                // documentation
3359
);
3360
3361
// Define the method WSEditCourse
3362
function WSEditCourse($params)
3363
{
3364
    global $_configuration;
3365
    if (!WSHelperVerifyKey($params)) {
3366
        return returnError(WS_ERROR_SECRET_KEY);
3367
    }
3368
3369
    $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
3370
3371
    $courses_params = $params['courses'];
3372
    $results = [];
3373
    $orig_course_id_value = [];
3374
3375
    foreach ($courses_params as $course_param) {
3376
        $tutor_id = isset($course_param['tutor_id']) ? $course_param['tutor_id'] : '';
3377
        $title = $course_param['title'];
3378
        $category_code = isset($course_param['category_code']) ? $course_param['category_code'] : '';
3379
        $department_name = isset($course_param['department_name']) ? $course_param['department_name'] : '';
3380
        $department_url = isset($course_param['department_url']) ? $course_param['department_url'] : '';
3381
        $course_language = $course_param['course_language'];
3382
        $visibility = $course_param['visibility'];
3383
        $subscribe = $course_param['subscribe'];
3384
        $unsubscribe = $course_param['unsubscribe'];
3385
        $visual_code = $course_param['visual_code'];
3386
        $diskQuota = isset($course_param['disk_quota']) ? $course_param['disk_quota'] : '100';
3387
        // Convert to MB
3388
        $diskQuota = $diskQuota * 1024 * 1024;
3389
3390
        $original_course_id_name = $course_param['original_course_id_name'];
3391
        $original_course_id_value = $course_param['original_course_id_value'];
3392
        $orig_course_id_value[] = $original_course_id_value;
3393
        $extra_list = isset($course_param['extra']) ? $course_param['extra'] : null;
3394
3395
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
3396
            $original_course_id_value,
3397
            $original_course_id_name
3398
        );
3399
3400
        if (empty($courseInfo)) {
3401
            $results[] = 0; // Original_course_id_value doesn't exist.
3402
            continue;
3403
        }
3404
3405
        $course_code = $courseInfo['code'];
3406
        $courseId = $courseInfo['real_id'];
3407
3408
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
3409
        $sql = "SELECT concat(lastname,'',firstname) as tutor_name
3410
                FROM $table_user WHERE status='1' AND user_id = '$tutor_id'
3411
                ORDER BY lastname,firstname";
3412
        $res = Database::query($sql);
3413
        $tutor_name = Database::fetch_row($res);
3414
3415
        $dbnamelength = strlen($_configuration['db_prefix']);
3416
        $maxlength = 40 - $dbnamelength;
3417
3418
        if (empty($visual_code)) {
3419
            $visual_code = CourseManager::generate_course_code(substr($title, 0, $maxlength));
3420
        }
3421
        $tutor_name = $tutor_name[0];
3422
        $sql = "UPDATE $course_table SET
3423
                    course_language='".Database::escape_string($course_language)."',
3424
                    title='".Database::escape_string($title)."',
3425
                    category_code='".Database::escape_string($category_code)."',
3426
                    tutor_name='".Database::escape_string($tutor_name)."',
3427
                    visual_code='".Database::escape_string($visual_code)."',
3428
                    department_name='".Database::escape_string($department_name)."',
3429
                    department_url='".Database::escape_string($department_url)."',
3430
                    visibility = '".Database::escape_string($visibility)."',
3431
                    subscribe = '".Database::escape_string($subscribe)."',
3432
                    disk_quota='".Database::escape_string($diskQuota)."',
3433
                    unsubscribe='".Database::escape_string($unsubscribe)."'
3434
                WHERE id ='".Database::escape_string($courseId)."'";
3435
        $res = Database::query($sql);
3436
3437
        if (is_array($extra_list) && count($extra_list) > 0) {
3438
            foreach ($extra_list as $extra) {
3439
                $extra_field_name = $extra['field_name'];
3440
                $extra_field_value = $extra['field_value'];
3441
                // Save the external system's id into course_field_value table.
3442
                $res = CourseManager::update_course_extra_field_value(
3443
                    $course_code,
3444
                    $extra_field_name,
3445
                    $extra_field_value
3446
                );
3447
            }
3448
        }
3449
3450
        if ($res) {
3451
            $results[] = 1;
3452
            continue;
3453
        } else {
3454
            $results[] = 0;
3455
            continue;
3456
        }
3457
    } // end principal foreach
3458
3459
    $count_results = count($results);
3460
    $output = [];
3461
    for ($i = 0; $i < $count_results; $i++) {
3462
        $output[] = [
3463
            'original_course_id_value' => $orig_course_id_value[$i],
3464
            'result' => $results[$i],
3465
        ];
3466
    }
3467
3468
    return $output;
3469
}
3470
3471
/* Register WSCourseDescription function */
3472
// Register the data structures used by the service
3473
3474
$server->wsdl->addComplexType(
3475
    'courseDescription',
3476
    'complexType',
3477
    'struct',
3478
    'all',
3479
    '',
3480
    [
3481
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
3482
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3483
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3484
    ]
3485
);
3486
3487
// Prepare output params, in this case will return an array
3488
$server->wsdl->addComplexType(
3489
    'fields_course_desc',
3490
    'complexType',
3491
    'struct',
3492
    'all',
3493
    '',
3494
    [
3495
        'course_desc_id' => ['name' => 'course_desc_id', 'type' => 'xsd:string'],
3496
        'course_desc_default_title' => ['name' => 'course_desc_default_title', 'type' => 'xsd:string'],
3497
        'course_desc_title' => ['name' => 'course_desc_title', 'type' => 'xsd:string'],
3498
        'course_desc_content' => ['name' => 'course_desc_content', 'type' => 'xsd:string']
3499
    ]
3500
);
3501
3502
$server->wsdl->addComplexType(
3503
    'fields_course_desc_list',
3504
    'complexType',
3505
    'array',
3506
    '',
3507
    'SOAP-ENC:Array',
3508
    [],
3509
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:fields_course_desc[]']],
3510
    'tns:fields_course_desc'
3511
);
3512
3513
3514
// Register the method to expose
3515
$server->register(
3516
    'WSCourseDescription', // method name
3517
    ['courseDescription' => 'tns:courseDescription'], // input parameters
3518
    ['return' => 'tns:fields_course_desc_list'], // output parameters
3519
    'urn:WSRegistration', // namespace
3520
    'urn:WSRegistration#WSCourseDescription', // soapaction
3521
    'rpc', // style
3522
    'encoded', // use
3523
    'This service edits a course description'               // documentation
3524
);
3525
3526
// Define the method WSCourseDescription
3527
function WSCourseDescription($params)
3528
{
3529
    if (!WSHelperVerifyKey($params)) {
3530
        return returnError(WS_ERROR_SECRET_KEY);
3531
    }
3532
3533
    $array_course_desc_id = [];
3534
    $array_course_desc_title = [];
3535
    $array_course_desc_content = [];
3536
3537
    $original_course_id_name = $params['original_course_id_name'];
3538
    $original_course_id_value = $params['original_course_id_value'];
3539
3540
    $courseInfo = CourseManager::getCourseInfoFromOriginalId(
3541
        $original_course_id_value,
3542
        $original_course_id_name
3543
    );
3544
3545
    if (empty($courseInfo) || (isset($courseInfo) && $courseInfo['visibility'] == 0)) {
3546
        return 0; // Original_course_id_value doesn't exist.
3547
    }
3548
3549
    $t_course_desc = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
3550
    $sql = "SELECT * FROM $t_course_desc WHERE c_id = {$courseInfo['real_id']} ";
3551
    $result = Database::query($sql);
3552
3553
    $default_titles = [
3554
        get_lang('GeneralDescription'),
3555
        get_lang('Objectives'),
3556
        get_lang('Topics'),
3557
        get_lang('Methodology'),
3558
        get_lang('CourseMaterial'),
3559
        get_lang('HumanAndTechnicalResources'),
3560
        get_lang('Assessment'),
3561
        get_lang('AddCategory')
3562
    ];
3563
3564
    for ($x = 1; $x < 9; $x++) {
3565
        $array_course_desc_id[$x] = $x;
3566
        $array_course_desc_default_title[$x] = $default_titles[$x - 1];
3567
        $array_course_desc_title[$x] = '';
3568
        $array_course_desc_content[$x] = '';
3569
    }
3570
3571
    while ($row = Database::fetch_array($result)) {
3572
        $ind = (int) $row['id'];
3573
        $array_course_desc_title[$ind] = $row['title'];
3574
        $array_course_desc_content[$ind] = $row['content'];
3575
    }
3576
3577
    $count_results = count($default_titles);
3578
    $output = [];
3579
    for ($i = 1; $i <= $count_results; $i++) {
3580
        $output[] = [
3581
            'course_desc_id' => $array_course_desc_id[$i],
3582
            '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...
3583
            'course_desc_title' => $array_course_desc_title[$i],
3584
            'course_desc_content' => $array_course_desc_content[$i]
3585
        ];
3586
    }
3587
3588
    return $output;
3589
}
3590
3591
/* Register WSEditCourseDescription function */
3592
// Register the data structures used by the service
3593
3594
$server->wsdl->addComplexType(
3595
    'editCourseDescriptionParams',
3596
    'complexType',
3597
    'struct',
3598
    'all',
3599
    '',
3600
    [
3601
        'course_desc_id' => ['name' => 'course_desc_id', 'type' => 'xsd:string'],
3602
        'course_desc_title' => ['name' => 'course_desc_title', 'type' => 'xsd:string'],
3603
        'course_desc_content' => ['name' => 'course_desc_content', 'type' => 'xsd:string'],
3604
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
3605
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string']
3606
    ]
3607
);
3608
3609
$server->wsdl->addComplexType(
3610
    'editCourseDescriptionParamsList',
3611
    'complexType',
3612
    'array',
3613
    '',
3614
    'SOAP-ENC:Array',
3615
    [],
3616
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:editCourseDescriptionParams[]']],
3617
    'tns:editCourseDescriptionParams'
3618
);
3619
3620
$server->wsdl->addComplexType(
3621
    'editCourseDescription',
3622
    'complexType',
3623
    'struct',
3624
    'all',
3625
    '',
3626
    [
3627
        'course_desc' => ['name' => 'course_desc', 'type' => 'tns:editCourseDescriptionParamsList'],
3628
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3629
    ]
3630
);
3631
3632
// Prepare output params, in this case will return an array
3633
$server->wsdl->addComplexType(
3634
    'result_editCourseDescription',
3635
    'complexType',
3636
    'struct',
3637
    'all',
3638
    '',
3639
    [
3640
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3641
        'course_desc_id' => ['name' => 'course_desc_id', 'type' => 'xsd:string'],
3642
        'result' => ['name' => 'result', 'type' => 'xsd:string']
3643
    ]
3644
);
3645
3646
$server->wsdl->addComplexType(
3647
    'results_editCourseDescription',
3648
    'complexType',
3649
    'array',
3650
    '',
3651
    'SOAP-ENC:Array',
3652
    [],
3653
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_editCourseDescription[]']],
3654
    'tns:result_editCourseDescription'
3655
);
3656
3657
3658
// Register the method to expose
3659
$server->register(
3660
    'WSEditCourseDescription', // method name
3661
    ['editCourseDescription' => 'tns:editCourseDescription'], // input parameters
3662
    ['return' => 'tns:results_editCourseDescription'], // output parameters
3663
    'urn:WSRegistration', // namespace
3664
    'urn:WSRegistration#WSEditCourseDescription', // soapaction
3665
    'rpc', // style
3666
    'encoded', // use
3667
    'This service edits a course description'                      // documentation
3668
);
3669
3670
// Define the method WSEditCourseDescription
3671
function WSEditCourseDescription($params)
3672
{
3673
    if (!WSHelperVerifyKey($params)) {
3674
        return -1;
3675
    }
3676
3677
    $courses_params = $params['course_desc'];
3678
    $results = [];
3679
    $orig_course_id_value = [];
3680
    $course_description_id = [];
3681
3682
    $courseDescription = new CourseDescription();
3683
    $defaultDescTitle = $courseDescription->get_default_description_title();
3684
3685
    foreach ($courses_params as $course_param) {
3686
        $original_course_id_name = $course_param['original_course_id_name'];
3687
        $original_course_id_value = $course_param['original_course_id_value'];
3688
        $course_desc_id = $course_param['course_desc_id'];
3689
        $course_desc_title = $course_param['course_desc_title'];
3690
        $course_desc_content = $course_param['course_desc_content'];
3691
        $orig_course_id_value[] = $original_course_id_value;
3692
        $course_description_id[] = $course_desc_id;
3693
3694
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
3695
            $original_course_id_value,
3696
            $original_course_id_name
3697
        );
3698
3699
        if (empty($courseInfo) || (isset($courseInfo) && $courseInfo['visibility'] == 0)) {
3700
            $results[] = 0;
3701
            continue; // Original_course_id_value doesn't exist.
3702
        }
3703
3704
        $course_desc_id = Database::escape_string($course_desc_id);
3705
        $course_desc_title = Database::escape_string($course_desc_title);
3706
        $course_desc_content = Database::escape_string($course_desc_content);
3707
3708
        $course_desc_id = (int) $course_desc_id;
3709
        if ($course_desc_id > 8 && $course_desc_id < 1) {
3710
            $results[] = 0; // course_desc_id invalid.
3711
            continue;
3712
        }
3713
3714
        // if title is empty set default title instead
3715
        if (empty($course_desc_title)) {
3716
            $course_desc_title = $defaultDescTitle[$course_desc_id];
3717
        }
3718
3719
        $courseId = $courseInfo['real_id'];
3720
        $courseDescription->set_id(null);
3721
        $courseDescription->set_course_id($courseId);
3722
        $courseDescription->set_session_id(0);
3723
        $courseDescription->set_title($course_desc_title);
3724
        $courseDescription->set_content($course_desc_content);
3725
        $courseDescription->set_description_type($course_desc_id);
3726
3727
        $data = $courseDescription->get_data_by_description_type($course_desc_id, $courseId);
3728
        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...
3729
            // Update existing description
3730
            $courseDescription->set_id($data['id']);
3731
            $result = $courseDescription->update();
3732
        } else {
3733
            // Insert new description
3734
            $result = $courseDescription->insert();
3735
        }
3736
3737
        $results[] = $result ? 1 : 0;
3738
    } // end principal foreach
3739
3740
    $count_results = count($results);
3741
    $output = [];
3742
    for ($i = 0; $i < $count_results; $i++) {
3743
        $output[] = [
3744
            'original_course_id_value' => $orig_course_id_value[$i],
3745
            'course_desc_id' => $course_description_id[$i],
3746
            'result' => $results[$i],
3747
        ];
3748
    }
3749
3750
    return $output;
3751
}
3752
3753
/* Register WSDeleteCourse function */
3754
// Register the data structures used by the service
3755
$server->wsdl->addComplexType(
3756
    'deleteCourseParams',
3757
    'complexType',
3758
    'struct',
3759
    'all',
3760
    '',
3761
    [
3762
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3763
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string']
3764
    ]
3765
);
3766
3767
$server->wsdl->addComplexType(
3768
    'deleteCourseParamsList',
3769
    'complexType',
3770
    'array',
3771
    '',
3772
    'SOAP-ENC:Array',
3773
    [],
3774
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:deleteCourseParams[]']],
3775
    'tns:deleteCourseParams'
3776
);
3777
3778
// Register the data structures used by the service.
3779
$server->wsdl->addComplexType(
3780
    'deleteCourse',
3781
    'complexType',
3782
    'struct',
3783
    'all',
3784
    '',
3785
    [
3786
        'courses' => ['name' => 'courses', 'type' => 'tns:deleteCourseParamsList'],
3787
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3788
    ]
3789
);
3790
3791
// Prepare output params, in this case will return an array.
3792
$server->wsdl->addComplexType(
3793
    'result_deleteCourse',
3794
    'complexType',
3795
    'struct',
3796
    'all',
3797
    '',
3798
    [
3799
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
3800
        'result' => ['name' => 'result', 'type' => 'xsd:string']
3801
    ]
3802
);
3803
3804
$server->wsdl->addComplexType(
3805
    'results_deleteCourse',
3806
    'complexType',
3807
    'array',
3808
    '',
3809
    'SOAP-ENC:Array',
3810
    [],
3811
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_deleteCourse[]']],
3812
    'tns:result_deleteCourse'
3813
);
3814
3815
$server->register(
3816
    'WSDeleteCourse', // method name
3817
    ['deleteCourse' => 'tns:deleteCourse'], // input parameters
3818
    ['return' => 'tns:results_deleteCourse'], // output parameters
3819
    'urn:WSRegistration', // namespace
3820
    'urn:WSRegistration#WSDeleteCourse', // soapaction
3821
    'rpc', // style
3822
    'encoded', // use
3823
    'This service deletes a course '               // documentation
3824
);
3825
3826
3827
// Define the method WSDeleteCourse
3828
function WSDeleteCourse($params)
3829
{
3830
    if (!WSHelperVerifyKey($params)) {
3831
        return returnError(WS_ERROR_SECRET_KEY);
3832
    }
3833
3834
    $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
3835
    $courses_params = $params['courses'];
3836
    $results = [];
3837
    $orig_course_id_value = [];
3838
    foreach ($courses_params as $course_param) {
3839
        $original_course_id_value = $course_param['original_course_id_value'];
3840
        $original_course_id_name = $course_param['original_course_id_name'];
3841
        $orig_course_id_value[] = $original_course_id_value;
3842
3843
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
3844
            $original_course_id_value,
3845
            $original_course_id_name
3846
        );
3847
3848
        if (empty($courseInfo) || (isset($courseInfo) && $courseInfo['visibility'] == 0)) {
3849
            $results[] = 0;
3850
            continue; // Original_course_id_value doesn't exist.
3851
        }
3852
3853
        $courseId = $courseInfo['real_id'];
3854
        $sql = "UPDATE $table_course SET visibility = '0' WHERE id = '$courseId'";
3855
        $return = Database::query($sql);
3856
        $results[] = $return;
3857
    }
3858
3859
    $count_results = count($results);
3860
    $output = [];
3861
    for ($i = 0; $i < $count_results; $i++) {
3862
        $output[] = [
3863
            'original_course_id_value' => $orig_course_id_value[$i],
3864
            'result' => $results[$i],
3865
        ];
3866
    }
3867
3868
    return $output;
3869
}
3870
3871
/* Register WSCreateSession function */
3872
// Register data structures used by the service.
3873
$server->wsdl->addComplexType(
3874
    'createSessionParam',
3875
    'complexType',
3876
    'struct',
3877
    'all',
3878
    '',
3879
    [
3880
        'name' => ['name' => 'name', 'type' => 'xsd:string'],
3881
        'year_start' => ['name' => 'year_start', 'type' => 'xsd:string'],
3882
        'month_start' => ['name' => 'month_start', 'type' => 'xsd:string'],
3883
        'day_start' => ['name' => 'day_start', 'type' => 'xsd:string'],
3884
        'year_end' => ['name' => 'year_end', 'type' => 'xsd:string'],
3885
        'month_end' => ['name' => 'month_end', 'type' => 'xsd:string'],
3886
        'day_end' => ['name' => 'day_end', 'type' => 'xsd:string'],
3887
        'nb_days_access_before' => ['name' => 'nb_days_access_before', 'type' => 'xsd:string'],
3888
        'nb_days_access_after' => ['name' => 'nb_days_access_after', 'type' => 'xsd:string'],
3889
        'nolimit' => ['name' => 'nolimit', 'type' => 'xsd:string'],
3890
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
3891
        'duration' => ['name' => 'duration', 'type' => 'xsd:string'],
3892
        'original_session_id_name' => ['name' => 'original_session_id_name', 'type' => 'xsd:string'],
3893
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
3894
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
3895
    ]
3896
);
3897
3898
$server->wsdl->addComplexType(
3899
    'createSessionParamList',
3900
    'complexType',
3901
    'array',
3902
    '',
3903
    'SOAP-ENC:Array',
3904
    [],
3905
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:createSessionParam[]']],
3906
    'tns:createSessionParamList'
3907
);
3908
3909
// Register the data structures used by the service
3910
$server->wsdl->addComplexType(
3911
    'createSession',
3912
    'complexType',
3913
    'struct',
3914
    'all',
3915
    '',
3916
    [
3917
        'sessions' => ['name' => 'sessions', 'type' => 'tns:createSessionParamList'],
3918
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
3919
    ]
3920
);
3921
3922
// Prepare output params, in this case will return an array
3923
$server->wsdl->addComplexType(
3924
    'result_createSession',
3925
    'complexType',
3926
    'struct',
3927
    'all',
3928
    '',
3929
    [
3930
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
3931
        'result' => ['name' => 'result', 'type' => 'xsd:string']
3932
    ]
3933
);
3934
3935
$server->wsdl->addComplexType(
3936
    'results_createSession',
3937
    'complexType',
3938
    'array',
3939
    '',
3940
    'SOAP-ENC:Array',
3941
    [],
3942
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_createSession[]']],
3943
    'tns:result_createSession'
3944
);
3945
3946
// Register the method to expose
3947
$server->register(
3948
    'WSCreateSession', // method name
3949
    ['createSession' => 'tns:createSession'], // input parameters
3950
    ['return' => 'tns:results_createSession'], // output parameters
3951
    'urn:WSRegistration', // namespace
3952
    'urn:WSRegistration#WSCreateSession', // soapaction
3953
    'rpc', // style
3954
    'encoded', // use
3955
    'This service edits a session'                  // documentation
3956
);
3957
3958
3959
// define the method WSCreateSession
3960
function WSCreateSession($params)
3961
{
3962
    global $debug;
3963
    $sessionAdminId = DEFAULT_ADMIN_USER_ID;
3964
3965
    if (!WSHelperVerifyKey($params)) {
3966
        return returnError(WS_ERROR_SECRET_KEY);
3967
    }
3968
3969
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3970
    error_log(print_r($params, 1));
3971
3972
    $sessions_params = $params['sessions'];
3973
    $results = [];
3974
    $orig_session_id_value = [];
3975
3976
    foreach ($sessions_params as $session_param) {
3977
        $name = trim($session_param['name']);
3978
        $year_start = intval($session_param['year_start']);
3979
        $month_start = intval($session_param['month_start']);
3980
        $day_start = intval($session_param['day_start']);
3981
        $year_end = intval($session_param['year_end']);
3982
        $month_end = intval($session_param['month_end']);
3983
        $day_end = intval($session_param['day_end']);
3984
        $nb_days_access_before = intval($session_param['nb_days_access_before']);
3985
        $nb_days_access_after = intval($session_param['nb_days_access_after']);
3986
        $id_coach = $session_param['user_id'];
3987
        $nolimit = $session_param['nolimit'];
3988
        $duration = $session_param['duration'];
3989
        $original_session_id_name = $session_param['original_session_id_name'];
3990
        $original_session_id_value = $session_param['original_session_id_value'];
3991
        $orig_session_id_value[] = $session_param['original_session_id_value'];
3992
        $extra_list = isset($session_param['extra']) ? $session_param['extra'] : '';
3993
3994
        $sessionId = SessionManager::getSessionIdFromOriginalId(
3995
            $original_session_id_value,
3996
            $original_session_id_name
3997
        );
3998
3999
        if (!empty($sessionId)) {
4000
            if ($debug) {
4001
                error_log("session with external session id '$original_session_id_value' with '$name' exists");
4002
            }
4003
            $results[] = 0;
4004
            continue;
4005
        }
4006
4007
        if (empty($nolimit)) {
4008
            $date_start = "$year_start-".(($month_start < 10) ? "0$month_start" : $month_start)."-".(($day_start < 10) ? "0$day_start" : $day_start).' 00:00:00';
4009
            $date_end = "$year_end-".(($month_end < 10) ? "0$month_end" : $month_end)."-".(($day_end < 10) ? "0$day_end" : $day_end).' 23:59:59';
4010
        } else {
4011
            $date_start = "";
4012
            $date_end = "";
4013
        }
4014
4015
        if (empty($name)) {
4016
            if ($debug) {
4017
                error_log("session has no name");
4018
            }
4019
            $results[] = 0;
4020
            continue;
4021
        } elseif (empty($id_coach)) {
4022
            $results[] = 0;
4023
            if ($debug) {
4024
                error_log("Coach id must not be empty");
4025
            }
4026
            continue;
4027
        } elseif (empty($nolimit) && (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start))) {
4028
            if ($debug) {
4029
                error_log("There's an error with the start date: $month_start - $day_start - $year_start");
4030
            }
4031
            $results[] = 0;
4032
            continue;
4033
        } elseif (empty($nolimit) && (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end))) {
4034
            $results[] = 0;
4035
            if ($debug) {
4036
                error_log("There's an error with the end date: $month_end - $day_end - $year_end");
4037
            }
4038
            continue;
4039
        } elseif (empty($nolimit) && $date_start >= $date_end) {
4040
            $results[] = 0;
4041
            if ($debug) {
4042
                error_log("There's an error with the start and end date");
4043
            }
4044
            continue;
4045
        } else {
4046
            $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='".addslashes($name)."'");
4047
            if (Database::num_rows($rs)) {
4048
                if ($debug) {
4049
                    error_log("Session with name '$name' already exists");
4050
                }
4051
                $results[] = 0;
4052
                continue;
4053
            } else {
4054
                $coachStartDate = '';
4055
                if ($date_start) {
4056
                    $startDate = new DateTime($date_start);
4057
                    $diffStart = new DateInterval("P".$nb_days_access_before."D");
4058
                    $coachStartDate = $startDate->sub($diffStart);
4059
                    $coachStartDate = $coachStartDate->format('Y-m-d H:i:s');
4060
                }
4061
                $coachEndDate = '';
4062
                if ($date_end) {
4063
                    $endDate = new DateTime($date_end);
4064
                    $diffEnd = new DateInterval("P".$nb_days_access_after."D");
4065
                    $coachEndDate = $endDate->add($diffEnd);
4066
                    $coachEndDate = $coachEndDate->format('Y-m-d H:i:s');
4067
                }
4068
                $id_session = SessionManager::create_session(
4069
                    $name,
4070
                    $date_start,
4071
                    $date_end,
4072
                    $date_start,
4073
                    $date_end,
4074
                    $coachStartDate,
4075
                    $coachEndDate,
4076
                    $id_coach,
4077
                    0,
4078
                    1,
4079
                    false,
4080
                    $duration,
4081
                    null,
4082
                    0,
4083
                    [],
4084
                    $sessionAdminId
4085
                );
4086
4087
                if ($id_session) {
4088
                    if ($debug) {
4089
                        error_log("Session created '$id_session' ");
4090
                    }
4091
                    // Save new field label into course_field table.
4092
                    SessionManager::create_session_extra_field(
4093
                        $original_session_id_name,
4094
                        1,
4095
                        $original_session_id_name
4096
                    );
4097
4098
                    // Save the external system's id into user_field_value table.
4099
                    SessionManager::update_session_extra_field_value(
4100
                        $id_session,
4101
                        $original_session_id_name,
4102
                        $original_session_id_value
4103
                    );
4104
4105
                    if (is_array($extra_list) && count($extra_list) > 0) {
4106
                        foreach ($extra_list as $extra) {
4107
                            $extra_field_name = $extra['field_name'];
4108
                            $extra_field_value = $extra['field_value'];
4109
                            // Save new fieldlabel into course_field table.
4110
                            SessionManager::create_session_extra_field(
4111
                                $extra_field_name,
4112
                                1,
4113
                                $extra_field_name
4114
                            );
4115
                            // Save the external system's id into course_field_value table.
4116
                            SessionManager::update_session_extra_field_value(
4117
                                $id_session,
4118
                                $extra_field_name,
4119
                                $extra_field_value
4120
                            );
4121
                        }
4122
                    }
4123
                    $results[] = $id_session;
4124
                } else {
4125
                    if ($debug) {
4126
                        error_log("There was an error when trying to save session with name $name");
4127
                    }
4128
                }
4129
            }
4130
        }
4131
    } // end principal foreach
4132
4133
    $count_results = count($results);
4134
    $output = [];
4135
    for ($i = 0; $i < $count_results; $i++) {
4136
        $output[] = [
4137
            'original_session_id_value' => $orig_session_id_value[$i],
4138
            'result' => $results[$i],
4139
        ];
4140
    }
4141
4142
    return $output;
4143
}
4144
4145
/* Register WSEditSession function */
4146
// Register the data structures used by the service
4147
$server->wsdl->addComplexType(
4148
    'editSessionParams',
4149
    'complexType',
4150
    'struct',
4151
    'all',
4152
    '',
4153
    [
4154
        'name' => ['name' => 'name', 'type' => 'xsd:string'],
4155
        'year_start' => ['name' => 'year_start', 'type' => 'xsd:string'],
4156
        'month_start' => ['name' => 'month_start', 'type' => 'xsd:string'],
4157
        'day_start' => ['name' => 'day_start', 'type' => 'xsd:string'],
4158
        'year_end' => ['name' => 'year_end', 'type' => 'xsd:string'],
4159
        'month_end' => ['name' => 'month_end', 'type' => 'xsd:string'],
4160
        'day_end' => ['name' => 'day_end', 'type' => 'xsd:string'],
4161
        'nb_days_access_before' => ['name' => 'nb_days_access_before', 'type' => 'xsd:string'],
4162
        'nb_days_access_after' => ['name' => 'nb_days_access_after', 'type' => 'xsd:string'],
4163
        'nolimit' => ['name' => 'nolimit', 'type' => 'xsd:string'],
4164
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
4165
        'duration' => ['name' => 'duration', 'type' => 'xsd:string'],
4166
        'original_session_id_name' => ['name' => 'original_session_id_name', 'type' => 'xsd:string'],
4167
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
4168
        'extra' => ['name' => 'extra', 'type' => 'tns:extrasList']
4169
    ]
4170
);
4171
4172
$server->wsdl->addComplexType(
4173
    'editSessionParamsList',
4174
    'complexType',
4175
    'array',
4176
    '',
4177
    'SOAP-ENC:Array',
4178
    [],
4179
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:editSessionParams[]']],
4180
    'tns:editSessionParams'
4181
);
4182
4183
$server->wsdl->addComplexType(
4184
    'editSession',
4185
    'complexType',
4186
    'struct',
4187
    'all',
4188
    '',
4189
    [
4190
        'sessions' => ['name' => 'sessions', 'type' => 'tns:editSessionParamsList'],
4191
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
4192
    ]
4193
);
4194
4195
// Prepare output params, in this case will return an array
4196
$server->wsdl->addComplexType(
4197
    'result_editSession',
4198
    'complexType',
4199
    'struct',
4200
    'all',
4201
    '',
4202
    [
4203
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
4204
        'result' => ['name' => 'result', 'type' => 'xsd:string']
4205
    ]
4206
);
4207
4208
$server->wsdl->addComplexType(
4209
    'results_editSession',
4210
    'complexType',
4211
    'array',
4212
    '',
4213
    'SOAP-ENC:Array',
4214
    [],
4215
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_editSession[]']],
4216
    'tns:result_editSession'
4217
);
4218
4219
4220
// Register the method to expose
4221
$server->register(
4222
    'WSEditSession', // method name
4223
    ['editSession' => 'tns:editSession'], // input parameters
4224
    ['return' => 'tns:results_editSession'], // output parameters
4225
    'urn:WSRegistration', // namespace
4226
    'urn:WSRegistration#WSEditSession', // soapaction
4227
    'rpc', // style
4228
    'encoded', // use
4229
    'This service edits a session'                // documentation
4230
);
4231
4232
// define the method WSEditSession
4233
function WSEditSession($params)
4234
{
4235
    if (!WSHelperVerifyKey($params)) {
4236
        return returnError(WS_ERROR_SECRET_KEY);
4237
    }
4238
4239
    $sessions_params = $params['sessions'];
4240
    $results = [];
4241
    $orig_session_id_value = [];
4242
    foreach ($sessions_params as $session_param) {
4243
        $name = trim($session_param['name']);
4244
        $year_start = intval($session_param['year_start']);
4245
        $month_start = intval($session_param['month_start']);
4246
        $day_start = intval($session_param['day_start']);
4247
        $year_end = intval($session_param['year_end']);
4248
        $month_end = intval($session_param['month_end']);
4249
        $day_end = intval($session_param['day_end']);
4250
        $nb_days_access_before = intval($session_param['nb_days_access_before']);
4251
        $nb_days_access_after = intval($session_param['nb_days_access_after']);
4252
        $original_session_id_value = $session_param['original_session_id_value'];
4253
        $original_session_id_name = $session_param['original_session_id_name'];
4254
        $orig_session_id_value[] = $original_session_id_value;
4255
        $coach_username = $session_param['coach_username'];
4256
        $nolimit = $session_param['nolimit'];
4257
        $id_coach = $session_param['user_id'];
4258
        $duration = intval($session_param['duration']);
4259
        $extra_list = $session_param['extra'];
4260
4261
        $id = SessionManager::getSessionIdFromOriginalId(
4262
            $original_session_id_value,
4263
            $original_session_id_name
4264
        );
4265
4266
        if (empty($id)) {
4267
            $results[] = 0;
4268
            continue;
4269
        }
4270
4271
        if (empty($nolimit)) {
4272
            $date_start = "$year_start-".(($month_start < 10) ? "0$month_start" : $month_start)."-".(($day_start < 10) ? "0$day_start" : $day_start).' 00:00:00';
4273
            $date_end = "$year_end-".(($month_end < 10) ? "0$month_end" : $month_end)."-".(($day_end < 10) ? "0$day_end" : $day_end).' 23:59:59';
4274
        } else {
4275
            $date_start = '';
4276
            $date_end = '';
4277
        }
4278
        if (empty($name)) {
4279
            $results[] = 0; //SessionNameIsRequired
4280
            continue;
4281
        } elseif (empty($id_coach)) { // Session must have coach
4282
            $results[] = 0;
4283
            continue;
4284
        } elseif (empty($nolimit) && (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start))) {
4285
            $results[] = 0; //InvalidStartDate
4286
            continue;
4287
        } elseif (empty($nolimit) && (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end))) {
4288
            $results[] = 0; //InvalidEndDate
4289
            continue;
4290
        } elseif (empty($nolimit) && $date_start >= $date_end) {
4291
            $results[] = 0; //StartDateShouldBeBeforeEndDate
4292
            continue;
4293
        } else {
4294
            $coachStartDate = '';
4295
            if ($date_start) {
4296
                $startDate = new DateTime($date_start);
4297
                $diffStart = new DateInterval("P".$nb_days_access_before."D");
4298
                $coachStartDate = $startDate->sub($diffStart);
4299
                $coachStartDate = $coachStartDate->format('Y-m-d H:i:s');
4300
            }
4301
            $coachEndDate = '';
4302
            if ($date_end) {
4303
                $endDate = new DateTime($date_end);
4304
                $diffEnd = new DateInterval("P".$nb_days_access_after."D");
4305
                $coachEndDate = $endDate->add($diffEnd);
4306
                $coachEndDate = $coachEndDate->format('Y-m-d H:i:s');
4307
            }
4308
            $sessionInfo = api_get_session_info($id);
4309
4310
            $editResult = SessionManager::edit_session(
4311
                $id,
4312
                $name,
4313
                $date_start,
4314
                $date_end,
4315
                $date_start,
4316
                $date_end,
4317
                $coachStartDate,
4318
                $coachEndDate,
4319
                $id_coach,
4320
                $sessionInfo['session_category_id'],
4321
                $sessionInfo['visibility'],
4322
                $sessionInfo['description'],
4323
                $sessionInfo['show_description'],
4324
                $duration,
4325
                null,
4326
                DEFAULT_ADMIN_USER_ID
4327
            );
4328
4329
            if (is_array($extra_list) && count($extra_list) > 0) {
4330
                foreach ($extra_list as $extra) {
4331
                    $extra_field_name = $extra['field_name'];
4332
                    $extra_field_value = $extra['field_value'];
4333
                    // Save the external system's id into session_field_value table.
4334
                    SessionManager::update_session_extra_field_value(
4335
                        $id,
4336
                        $extra_field_name,
4337
                        $extra_field_value
4338
                    );
4339
                }
4340
            }
4341
4342
            $results[] = $editResult ? 1 : 0;
4343
            continue;
4344
        }
4345
    } // end principal foreach
4346
4347
    $count_results = count($results);
4348
    $output = [];
4349
    for ($i = 0; $i < $count_results; $i++) {
4350
        $output[] = [
4351
            'original_session_id_value' => $orig_session_id_value[$i],
4352
            'result' => $results[$i],
4353
        ];
4354
    }
4355
4356
    return $output;
4357
}
4358
4359
/* Register WSDeleteSession function */
4360
$server->wsdl->addComplexType(
4361
    'deleteSessionParams',
4362
    'complexType',
4363
    'struct',
4364
    'all',
4365
    '',
4366
    [
4367
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
4368
        'original_session_id_name' => ['name' => 'original_session_id_name', 'type' => 'xsd:string']
4369
    ]
4370
);
4371
4372
$server->wsdl->addComplexType(
4373
    'deleteSessionParamsList',
4374
    'complexType',
4375
    'array',
4376
    '',
4377
    'SOAP-ENC:Array',
4378
    [],
4379
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:deleteSessionParams[]']],
4380
    'tns:deleteSessionParams'
4381
);
4382
4383
// Register the data structures used by the service
4384
$server->wsdl->addComplexType(
4385
    'deleteSession',
4386
    'complexType',
4387
    'struct',
4388
    'all',
4389
    '',
4390
    [
4391
        'sessions' => ['name' => 'sessions', 'type' => 'tns:deleteSessionParamsList'],
4392
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
4393
    ]
4394
);
4395
4396
// Prepare output params, in this case will return an array
4397
$server->wsdl->addComplexType(
4398
    'result_deleteSession',
4399
    'complexType',
4400
    'struct',
4401
    'all',
4402
    '',
4403
    [
4404
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
4405
        'result' => ['name' => 'result', 'type' => 'xsd:string']
4406
    ]
4407
);
4408
4409
$server->wsdl->addComplexType(
4410
    'results_deleteSession',
4411
    'complexType',
4412
    'array',
4413
    '',
4414
    'SOAP-ENC:Array',
4415
    [],
4416
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_deleteSession[]']],
4417
    'tns:result_deleteSession'
4418
);
4419
4420
$server->register(
4421
    'WSDeleteSession', // method name
4422
    ['deleteSession' => 'tns:deleteSession'], // input parameters
4423
    ['return' => 'tns:results_deleteSession'], // output parameters
4424
    'urn:WSRegistration', // namespace
4425
    'urn:WSRegistration#WSDeleteSession', // soapaction
4426
    'rpc', // style
4427
    'encoded', // use
4428
    'This service deletes a session '               // documentation
4429
);
4430
4431
// define the method WSDeleteSession
4432
function WSDeleteSession($params)
4433
{
4434
    if (!WSHelperVerifyKey($params)) {
4435
        return returnError(WS_ERROR_SECRET_KEY);
4436
    }
4437
4438
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
4439
    $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4440
    $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4441
    $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
4442
4443
    $session_params = $params['sessions'];
4444
    $results = [];
4445
    $orig_session_id_value = [];
4446
4447
    foreach ($session_params as $session_param) {
4448
        $original_session_id_value = $session_param['original_session_id_value'];
4449
        $original_session_id_name = $session_param['original_session_id_name'];
4450
        $orig_session_id_value[] = $original_session_id_name;
4451
4452
        $idChecked = SessionManager::getSessionIdFromOriginalId(
4453
            $original_session_id_value,
4454
            $original_session_id_name
4455
        );
4456
4457
        if (empty($idChecked)) {
4458
            $results[] = 0;
4459
            continue;
4460
        }
4461
4462
        $session_ids[] = $idChecked;
4463
4464
        $sql = "DELETE FROM $tbl_session WHERE id = '$idChecked'";
4465
        Database::query($sql);
4466
        $sql = "DELETE FROM $tbl_session_rel_course WHERE session_id = '$idChecked'";
4467
        Database::query($sql);
4468
        $sql = "DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id = '$idChecked'";
4469
        Database::query($sql);
4470
        $sql = "DELETE FROM $tbl_session_rel_user WHERE session_id = '$idChecked'";
4471
        Database::query($sql);
4472
        $results[] = 1;
4473
        continue;
4474
    }
4475
4476
    $extraFieldValue = new ExtraFieldValue('session');
4477
4478
    //delete from table_session_field_value from a given session_id
4479
    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...
4480
        $extraFieldValue->deleteValuesByItem($session_id);
4481
    }
4482
4483
    // Preparing output.
4484
    $count_results = count($results);
4485
    $output = [];
4486
    for ($i = 0; $i < $count_results; $i++) {
4487
        $output[] = [
4488
            'original_session_id_value' => $orig_session_id_value[$i],
4489
            'result' => $results[$i],
4490
        ];
4491
    }
4492
4493
    return $output;
4494
}
4495
4496
/** WSSubscribeUserToCourse **/
4497
// Register the data structures used by the service
4498
$server->wsdl->addComplexType(
4499
    'user_course_status',
4500
    'complexType',
4501
    'struct',
4502
    'all',
4503
    '',
4504
    [
4505
        'course_id' => ['name' => 'course_id', 'type' => 'tns:course_id'],
4506
        'user_id'   => ['name' => 'user_id', 'type' => 'tns:user_id'],
4507
        'status'    => ['name' => 'status', 'type' => 'xsd:int']
4508
    ]
4509
);
4510
4511
$server->wsdl->addComplexType(
4512
    'subscribeUserToCourse_arg',
4513
    'complexType',
4514
    'struct',
4515
    'all',
4516
    '',
4517
    [
4518
        'userscourses'  => ['name' => 'userscourses', 'type' => 'tns:user_course_status_array'], //removed []
4519
        'secret_key'    => ['name' => 'secret_key', 'type' => 'xsd:string']
4520
    ]
4521
);
4522
4523
$server->wsdl->addComplexType(
4524
    'user_course_status_array',
4525
    'complexType',
4526
    'array',
4527
    '',
4528
    'SOAP-ENC:Array',
4529
    [],
4530
    [
4531
        ['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:user_course_status[]']
4532
    ],
4533
    'tns:user_course_status'
4534
);
4535
4536
$server->wsdl->addComplexType(
4537
    'subscribeUserToCourse_return',
4538
    'complexType',
4539
    'struct',
4540
    'all',
4541
    '',
4542
    [
4543
        'original_user_id_value'    => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
4544
        'original_course_id_value'  => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
4545
        'result'                    => ['name' => 'result', 'type' => 'xsd:int']
4546
    ]
4547
);
4548
4549
$server->wsdl->addComplexType(
4550
    'subscribeUserToCourse_return_global',
4551
    'complexType',
4552
    'array',
4553
    '',
4554
    'SOAP-ENC:Array',
4555
    [],
4556
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:subscribeUserToCourse_return[]']],
4557
    'tns:subscribeUserToCourse_return'
4558
);
4559
4560
// Register the method to expose
4561
$server->register(
4562
    'WSSubscribeUserToCourse', // method name
4563
    ['subscribeUserToCourse' => 'tns:subscribeUserToCourse_arg'], // input parameters
4564
    ['return' => 'tns:subscribeUserToCourse_return_global'],
4565
    'urn:WSRegistration', // namespace
4566
    'urn:WSRegistration#WSSubscribeUserToCourse', // soapaction
4567
    'rpc', // style
4568
    'encoded', // use
4569
    'This service subscribes a user to a course'                        // documentation
4570
);
4571
4572
// define the method WSSubscribeUserToCourse
4573
function WSSubscribeUserToCourse($params)
4574
{
4575
    global $debug;
4576
    if (!WSHelperVerifyKey($params)) {
4577
        return returnError(WS_ERROR_SECRET_KEY);
4578
    }
4579
    if ($debug) {
4580
        error_log('WSSubscribeUserToCourse params: '.print_r($params, 1));
4581
    }
4582
4583
    $results = [];
4584
    $userscourses = $params['userscourses'];
4585
    foreach ($userscourses as $usercourse) {
4586
        $original_course_id = $usercourse['course_id'];
4587
        $original_user_id   = $usercourse['user_id'];
4588
        $status = STUDENT;
4589
        if ($usercourse['status']) {
4590
            $status = $usercourse['status'];
4591
        }
4592
4593
        $resultValue = 0;
4594
4595
        // Get user id
4596
        $user_id = UserManager::get_user_id_from_original_id(
4597
            $original_user_id['original_user_id_value'],
4598
            $original_user_id['original_user_id_name']
4599
        );
4600
        if ($debug) {
4601
            error_log('WSSubscribeUserToCourse user_id: '.$user_id);
4602
        }
4603
4604
        if ($user_id == 0) {
4605
            // If user was not found, there was a problem
4606
            $resultValue = 0;
4607
        } else {
4608
            // User was found
4609
            $courseInfo = CourseManager::getCourseInfoFromOriginalId(
4610
                $original_course_id['original_course_id_value'],
4611
                $original_course_id['original_course_id_name']
4612
            );
4613
4614
            $courseCode = $courseInfo['code'];
4615
4616
            if (empty($courseCode)) {
4617
                // Course was not found
4618
                $resultValue = 0;
4619
            } else {
4620
                if ($debug) {
4621
                    error_log('WSSubscribeUserToCourse courseCode: '.$courseCode);
4622
                }
4623
                $result = CourseManager::add_user_to_course($user_id, $courseCode, $status, false);
4624
                if ($result) {
4625
                    $resultValue = 1;
4626
                    if ($debug) {
4627
                        error_log('WSSubscribeUserToCourse subscribed');
4628
                    }
4629
                } else {
4630
                    if ($debug) {
4631
                        error_log('WSSubscribeUserToCourse NOT subscribed: ');
4632
                    }
4633
                }
4634
            }
4635
        }
4636
4637
        $results[] = [
4638
            'original_user_id_value' => $original_user_id['original_user_id_value'],
4639
            'original_course_id_value' => $original_course_id['original_course_id_value'],
4640
            'result' => $resultValue
4641
        ];
4642
    }
4643
4644
    return $results;
4645
}
4646
4647
4648
/** WSSubscribeUserToCourse **/
4649
// Register the data structures used by the service
4650
$server->wsdl->addComplexType(
4651
    'subscribeUserToCourseSimple_arg',
4652
    'complexType',
4653
    'struct',
4654
    'all',
4655
    '',
4656
    [
4657
        'course'       => ['name' => 'course', 'type' => 'xsd:string'], //Course string code
4658
        'user_id'      => ['name' => 'user_id', 'type' => 'xsd:string'], //Chamilo user_id
4659
        'status'       => ['name' => 'status', 'type' => 'xsd:int'],
4660
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string']
4661
    ]
4662
);
4663
4664
4665
// Prepare output params, in this case will return an array
4666
$server->wsdl->addComplexType(
4667
    'Result',
4668
    'complexType',
4669
    'struct',
4670
    'all',
4671
    '',
4672
    ['message' => ['name' => 'message', 'type' => 'xsd:string']]
4673
);
4674
4675
4676
// Register the method to expose
4677
$server->register(
4678
    'WSSubscribeUserToCourseSimple', // method name
4679
    ['subscribeUserToCourseSimple' => 'tns:subscribeUserToCourseSimple_arg'], // input parameters
4680
    ['return' => 'xsd:string'], // output parameters
4681
    'urn:WSRegistration', // namespace
4682
    'urn:WSRegistration#WSSubscribeUserToCourseSimple', // soapaction
4683
    'rpc', // style
4684
    'encoded', // use
4685
    'This service subscribes a user to a course in a simple way'                   // documentation
4686
);
4687
4688
/**
4689
 * define the method WSSubscribeUserToCourse
4690
 * @param array $params
4691
 * @return array|int|null|soap_fault|string
4692
 */
4693
function WSSubscribeUserToCourseSimple($params)
4694
{
4695
    global $debug;
4696
4697
    if ($debug) {
4698
        error_log('WSSubscribeUserToCourseSimple');
4699
    }
4700
    if ($debug) {
4701
        error_log('Params '.print_r($params, 1));
4702
    }
4703
    if (!WSHelperVerifyKey($params)) {
4704
        return returnError(WS_ERROR_SECRET_KEY);
4705
    }
4706
    $result = [];
4707
    $course_code = $params['course']; //Course code
4708
    $user_id = $params['user_id']; //chamilo user id
4709
    $status = STUDENT;
4710
4711
    if (!empty($params['status'])) {
4712
        $status = $params['status'];
4713
    }
4714
    // Get user id
4715
    $user_data = api_get_user_info($user_id);
4716
4717
    if (empty($user_data)) {
4718
        // If user was not found, there was a problem
4719
        $result = "User $user_id does not exist";
4720
        if ($debug) {
4721
            error_log($result);
4722
        }
4723
        return $result;
4724
    }
4725
    if (!empty($course_code)) {
4726
        $course_data = api_get_course_info($course_code);
4727
        if (empty($course_data)) {
4728
            // Course was not found
4729
            $result = "Course $course_code does not exist in the platform ";
4730
            if ($debug) {
4731
                error_log($result);
4732
            }
4733
        } else {
4734
            if ($debug) {
4735
                error_log('Try to register: user_id= '.$user_id.' to course: '.$course_data['code']);
4736
            }
4737
            if (!CourseManager::add_user_to_course($user_id, $course_data['code'], $status)) {
4738
                $result = 'User was not registered possible reasons: User already registered to the course, Course visibility doesnt allow user subscriptions ';
4739
                if ($debug) {
4740
                    error_log($result);
4741
                }
4742
            } else {
4743
                if ($debug) {
4744
                    error_log('User registered to the course: '.$course_data['code']);
4745
                }
4746
                $result = 1;
4747
            }
4748
        }
4749
    }
4750
    return $result;
4751
}
4752
4753
/*   GetUser    */
4754
$server->wsdl->addComplexType(
4755
    'GetUserArg',
4756
    'complexType',
4757
    'struct',
4758
    'all',
4759
    '',
4760
    [
4761
        'original_user_id_value'      => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
4762
        'original_user_id_name'       => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
4763
        'secret_key'                  => ['name' => 'secret_key', 'type' => 'xsd:string']
4764
    ]
4765
);
4766
4767
// Prepare output params, in this case will return an array
4768
$server->wsdl->addComplexType(
4769
    'User',
4770
    'complexType',
4771
    'struct',
4772
    'all',
4773
    '',
4774
    [
4775
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
4776
        'firstname' => ['name' => 'firstname', 'type' => 'xsd:string'],
4777
        'lastname' => ['name' => 'lastname', 'type' => 'xsd:string'],
4778
    ]
4779
);
4780
4781
// Register the method to expose
4782
$server->register(
4783
    'WSGetUser', // method name
4784
    ['GetUser' => 'tns:GetUserArg'], // input parameters
4785
    ['return' => 'tns:User'], // output parameters
4786
    'urn:WSRegistration', // namespace
4787
    'urn:WSRegistration#WSGetUser', // soapaction
4788
    'rpc', // style
4789
    'encoded', // use
4790
    'This service get user information by id'    // documentation
4791
);
4792
4793
// define the method WSGetUser
4794
function WSGetUser($params)
4795
{
4796
    global $debug;
4797
    if ($debug) {
4798
        error_log('WSGetUser');
4799
    }
4800
    if ($debug) {
4801
        error_log('$params: '.print_r($params, 1));
4802
    }
4803
4804
    if (!WSHelperVerifyKey($params)) {
4805
        return returnError(WS_ERROR_SECRET_KEY);
4806
    }
4807
4808
    $result = [];
4809
4810
    // Get user id
4811
    $user_id = UserManager::get_user_id_from_original_id(
4812
        $params['original_user_id_value'],
4813
        $params['original_user_id_name']
4814
    );
4815
    $user_data = api_get_user_info($user_id);
4816
4817
    if (empty($user_data)) {
4818
        // If user was not found, there was a problem
4819
        $result['user_id'] = '';
4820
        $result['firstname'] = '';
4821
        $result['lastname'] = '';
4822
    } else {
4823
        $result['user_id'] = $user_data['user_id'];
4824
        $result['firstname'] = $user_data['firstname'];
4825
        $result['lastname'] = $user_data['lastname'];
4826
    }
4827
    return $result;
4828
}
4829
4830
$server->wsdl->addComplexType(
4831
    'GetUserArgUsername',
4832
    'complexType',
4833
    'struct',
4834
    'all',
4835
    '',
4836
    [
4837
        'username'      => ['name' => 'username', 'type' => 'xsd:string'],
4838
        'secret_key'    => ['name' => 'secret_key', 'type' => 'xsd:string']
4839
    ]
4840
);
4841
// Register the method to expose
4842
$server->register(
4843
    'WSGetUserFromUsername', // method name
4844
    ['GetUserFromUsername' => 'tns:GetUserArgUsername'], // input params
4845
    ['return' => 'tns:User'], // output parameters
4846
    'urn:WSRegistration', // namespace
4847
    'urn:WSRegistration#WSGetUserFromUsername', // soapaction
4848
    'rpc', // style
4849
    'encoded', // use
4850
    'This service get user information by username'            // documentation
4851
);
4852
4853
// define the method WSGetUserFromUsername
4854
function WSGetUserFromUsername($params)
4855
{
4856
    global $debug;
4857
    if ($debug) {
4858
        error_log('WSGetUserFromUsername');
4859
    }
4860
    if ($debug) {
4861
        error_log('$params: '.print_r($params, 1));
4862
    }
4863
4864
    if (!WSHelperVerifyKey($params)) {
4865
        return returnError(WS_ERROR_SECRET_KEY);
4866
    }
4867
4868
    $result = [];
4869
4870
    // Get user id
4871
    $user_data = api_get_user_info($params['username']);
4872
4873
    if (empty($user_data)) {
4874
        // If user was not found, there was a problem
4875
        $result['user_id']    = '';
4876
        $result['firstname']  = '';
4877
        $result['lastname']   = '';
4878
    } else {
4879
        $result['user_id']    = $user_data['user_id'];
4880
        $result['firstname']  = $user_data['firstname'];
4881
        $result['lastname']   = $user_data['lastname'];
4882
    }
4883
    return $result;
4884
}
4885
4886
/* Register WSUnsubscribeUserFromCourse function */
4887
// Register the data structures used by the service
4888
$server->wsdl->addComplexType(
4889
    'unsuscribeUserFromCourseParams',
4890
    'complexType',
4891
    'struct',
4892
    'all',
4893
    '',
4894
    [
4895
        'original_user_id_values'   => ['name' => 'original_user_id_values', 'type' => 'tns:originalUsersList'],
4896
        'original_user_id_name'     => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
4897
        'original_course_id_value'  => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
4898
        'original_course_id_name'   => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
4899
    ]
4900
);
4901
4902
$server->wsdl->addComplexType(
4903
    'unsuscribeUserFromCourseParamsList',
4904
    'complexType',
4905
    'array',
4906
    '',
4907
    'SOAP-ENC:Array',
4908
    [],
4909
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:unsuscribeUserFromCourseParams[]']],
4910
    'tns:unsuscribeUserFromCourseParams'
4911
);
4912
4913
$server->wsdl->addComplexType(
4914
    'unsuscribeUserFromCourse',
4915
    'complexType',
4916
    'struct',
4917
    'all',
4918
    '',
4919
    [
4920
        'userscourses' => ['name' => 'userscourses', 'type' => 'tns:unsuscribeUserFromCourseParamsList'],
4921
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
4922
    ]
4923
);
4924
4925
// Prepare output params, in this case will return an array
4926
$server->wsdl->addComplexType(
4927
    'result_unsuscribeUserFromCourse',
4928
    'complexType',
4929
    'struct',
4930
    'all',
4931
    '',
4932
    [
4933
        'original_user_id_values' => ['name' => 'original_user_id_values', 'type' => 'xsd:string'],
4934
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
4935
        'result' => ['name' => 'result', 'type' => 'xsd:string']
4936
    ]
4937
);
4938
4939
$server->wsdl->addComplexType(
4940
    'results_unsuscribeUserFromCourse',
4941
    'complexType',
4942
    'array',
4943
    '',
4944
    'SOAP-ENC:Array',
4945
    [],
4946
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_unsuscribeUserFromCourse[]']],
4947
    'tns:result_unsuscribeUserFromCourse'
4948
);
4949
4950
// Register the method to expose
4951
$server->register(
4952
    'WSUnsubscribeUserFromCourse', // method name
4953
    ['unsuscribeUserFromCourse' => 'tns:unsuscribeUserFromCourse'], // input parameters
4954
    ['return' => 'tns:results_unsuscribeUserFromCourse'], // output parameters
4955
    'urn:WSRegistration', // namespace
4956
    'urn:WSRegistration#WSUnsubscribeUserFromCourse', // soapaction
4957
    'rpc', // style
4958
    'encoded', // use
4959
    'This service unsubscribes a user from a course'                     // documentation
4960
);
4961
4962
// define the method WSUnsubscribeUserFromCourse
4963
function WSUnsubscribeUserFromCourse($params)
4964
{
4965
    if (!WSHelperVerifyKey($params)) {
4966
        return returnError(WS_ERROR_SECRET_KEY);
4967
    }
4968
4969
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
4970
    $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
4971
4972
    $userscourses_params = $params['userscourses'];
4973
    $results = [];
4974
    $orig_user_id_value = [];
4975
    $orig_course_id_value = [];
4976
    foreach ($userscourses_params as $usercourse_param) {
4977
        $original_user_id_values = $usercourse_param['original_user_id_values'];
4978
        $original_user_id_name = $usercourse_param['original_user_id_name'];
4979
        $original_course_id_value = $usercourse_param['original_course_id_value'];
4980
        $original_course_id_name = $usercourse_param['original_course_id_name'];
4981
        $orig_course_id_value[] = $original_course_id_value;
4982
4983
        // Get user id from original user id
4984
        $usersList = [];
4985
        foreach ($original_user_id_values as $key => $row_original_user_id) {
4986
            $user_id = UserManager::get_user_id_from_original_id(
4987
                $original_user_id_values[$key],
4988
                $original_user_id_name[$key]
4989
            );
4990
            if ($user_id == 0) {
4991
                continue; // user_id doesn't exist.
4992
            } else {
4993
                $sql = "SELECT user_id FROM $user_table WHERE user_id ='".$user_id."' AND active= '0'";
4994
                $resu = Database::query($sql);
4995
                $r_check_user = Database::fetch_row($resu);
4996
                if (!empty($r_check_user[0])) {
4997
                    continue; // user_id is not active.
4998
                }
4999
            }
5000
            $usersList[] = $user_id;
5001
        }
5002
5003
        $orig_user_id_value[] = implode(',', $usersList);
5004
5005
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
5006
            $original_course_id_value,
5007
            $original_course_id_name
5008
        );
5009
5010
        if (empty($courseInfo) ||
5011
            (isset($courseInfo) && $courseInfo['visibility'] == 0)
5012
        ) {
5013
            $results[] = 0;
5014
            continue; // Original_course_id_value doesn't exist.
5015
        }
5016
5017
        $courseId = $courseInfo['real_id'];
5018
5019
        if (count($usersList) == 0) {
5020
            $results[] = 0;
5021
            continue;
5022
        }
5023
5024
        foreach ($usersList as $user_id) {
5025
            $sql = "DELETE FROM $table_course_user
5026
                    WHERE user_id = '$user_id' AND c_id = '".$courseId."'";
5027
            $result = Database::query($sql);
5028
            Database::affected_rows($result);
5029
        }
5030
        $results[] = 1;
5031
        continue;
5032
    } // end principal foreach
5033
5034
    $count_results = count($results);
5035
    $output = [];
5036
    for ($i = 0; $i < $count_results; $i++) {
5037
        $output[] = [
5038
            'original_user_id_values' => $orig_user_id_value[$i],
5039
            'original_course_id_value' => $orig_course_id_value[$i],
5040
            'result' => $results[$i]
5041
        ];
5042
    }
5043
5044
    return $output;
5045
}
5046
5047
/* Register WSSuscribeUsersToSession function */
5048
$server->wsdl->addComplexType(
5049
    'unSubscribeUserFromCourseSimple',
5050
    'complexType',
5051
    'struct',
5052
    'all',
5053
    '',
5054
    [
5055
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
5056
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
5057
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
5058
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
5059
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5060
    ]
5061
);
5062
5063
$server->wsdl->addComplexType(
5064
    'unSubscribeUserToCourseSimple_return',
5065
    'complexType',
5066
    'struct',
5067
    'all',
5068
    '',
5069
    [
5070
        'original_user_id_value'    => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
5071
        'original_course_id_value'  => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
5072
        'result'                    => ['name' => 'result', 'type' => 'xsd:int']
5073
    ]
5074
);
5075
5076
// Register the method to expose
5077
$server->register(
5078
    'WSUnSubscribeUserFromCourseSimple', // method name
5079
    ['unSubscribeUserFromCourseSimple' => 'tns:unSubscribeUserFromCourseSimple'], // input parameters
5080
    ['return' => 'tns:unSubscribeUserToCourseSimple_return'], // output parameters
5081
    'urn:WSRegistration', // namespace
5082
    'urn:WSRegistration#WSUnSubscribeUserFromCourseSimple', // soapaction
5083
    'rpc', // style
5084
    'encoded', // use
5085
    'This service unsubscribe a user from a course'                     // documentation
5086
);
5087
5088
/**
5089
 * @param array $params
5090
 * @return array|null|soap_fault
5091
 */
5092
function WSUnSubscribeUserFromCourseSimple($params)
5093
{
5094
    global $debug;
5095
    error_log('WSUnSubscribeUserFromCourseSimple');
5096
    if (!WSHelperVerifyKey($params)) {
5097
        return returnError(WS_ERROR_SECRET_KEY);
5098
    }
5099
5100
    $original_user_id_value = $params['original_user_id_value'];
5101
    $original_user_id_name = $params['original_user_id_name'];
5102
    $original_course_id_value = $params['original_course_id_value'];
5103
    $original_course_id_name = $params['original_course_id_name'];
5104
5105
    $result = [];
5106
    $result['original_user_id_value'] = $original_user_id_value;
5107
    $result['original_course_id_value'] = $original_course_id_value;
5108
    $result['result'] = 0;
5109
5110
    $user_id = UserManager::get_user_id_from_original_id(
5111
        $original_user_id_value,
5112
        $original_user_id_name
5113
    );
5114
5115
    if ($user_id) {
5116
        if ($debug) {
5117
            error_log("User $original_user_id_value, $original_user_id_name found");
5118
            error_log("Course $original_course_id_value, $original_course_id_name found");
5119
        }
5120
5121
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
5122
            $original_course_id_value,
5123
            $original_course_id_name
5124
        );
5125
5126
        $courseCode = $courseInfo['code'];
5127
5128
        if (empty($courseCode)) {
5129
            // Course was not found
5130
            if ($debug) {
5131
                error_log("course not found");
5132
            }
5133
        } else {
5134
            if ($debug) {
5135
                error_log("Course $courseCode found");
5136
            }
5137
            CourseManager::unsubscribe_user($user_id, $courseCode, 0);
5138
            $result['result'] = 1;
5139
        }
5140
    } else {
5141
        if ($debug) {
5142
            error_log("User not found");
5143
        }
5144
    }
5145
5146
    return $result;
5147
}
5148
5149
$server->wsdl->addComplexType(
5150
    'subscribeUserToCourseParams',
5151
    'complexType',
5152
    'struct',
5153
    'all',
5154
    '',
5155
    [
5156
        'original_user_id_values'   => ['name' => 'original_user_id_values', 'type' => 'tns:originalUsersList'],
5157
        'original_user_id_name'     => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
5158
        'original_course_id_value'  => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
5159
        'original_course_id_name'   => ['name' => 'original_course_id_value', 'type' => 'xsd:string']
5160
    ]
5161
);
5162
5163
5164
// Prepare output params, in this case will return an array.
5165
$server->wsdl->addComplexType(
5166
    'result_subscribeUsersToSession',
5167
    'complexType',
5168
    'struct',
5169
    'all',
5170
    '',
5171
    [
5172
        'original_user_id_values' => ['name' => 'original_user_id_values', 'type' => 'xsd:string'],
5173
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5174
        'result' => ['name' => 'result', 'type' => 'xsd:string']
5175
    ]
5176
);
5177
5178
$server->wsdl->addComplexType(
5179
    'results_subscribeUsersToSession',
5180
    'complexType',
5181
    'array',
5182
    '',
5183
    'SOAP-ENC:Array',
5184
    [],
5185
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_subscribeUsersToSession[]']],
5186
    'tns:result_subscribeUsersToSession'
5187
);
5188
5189
$server->wsdl->addComplexType(
5190
    'originalUserItem',
5191
    'complexType',
5192
    'struct',
5193
    'all',
5194
    '',
5195
    [
5196
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string']
5197
    ]
5198
);
5199
5200
// Register the data structures used by the service
5201
$server->wsdl->addComplexType(
5202
    'originalUsersList',
5203
    'complexType',
5204
    'array',
5205
    '',
5206
    'SOAP-ENC:Array',
5207
    [],
5208
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:originalUserItem[]']],
5209
    'tns:originalUserItem'
5210
);
5211
5212
/* Register WSSuscribeUsersToSession function */
5213
// Register the data structures used by the service
5214
$server->wsdl->addComplexType(
5215
    'subscribeUsersToSessionParams',
5216
    'complexType',
5217
    'struct',
5218
    'all',
5219
    '',
5220
    [
5221
        'original_user_id_values' => ['name' => 'original_user_id_values', 'type' => 'tns:originalUsersList'],
5222
        'original_user_id_name' => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
5223
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5224
        'original_session_id_name' => ['name' => 'original_session_id_name', 'type' => 'xsd:string']
5225
    ]
5226
);
5227
5228
$server->wsdl->addComplexType(
5229
    'subscribeUsersToSessionParamsList',
5230
    'complexType',
5231
    'array',
5232
    '',
5233
    'SOAP-ENC:Array',
5234
    [],
5235
    [
5236
        [
5237
            'ref' => 'SOAP-ENC:arrayType',
5238
            'wsdl:arrayType' => 'tns:subscribeUsersToSessionParams[]',
5239
        ],
5240
    ],
5241
    'tns:subscribeUsersToSessionParams'
5242
);
5243
5244
$server->wsdl->addComplexType(
5245
    'subscribeUsersToSession',
5246
    'complexType',
5247
    'struct',
5248
    'all',
5249
    '',
5250
    [
5251
        'userssessions' => ['name' => 'userssessions', 'type' => 'tns:subscribeUsersToSessionParamsList'],
5252
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5253
    ]
5254
);
5255
5256
// Register the method to expose
5257
$server->register(
5258
    'WSSuscribeUsersToSession', // method name
5259
    ['subscribeUsersToSession' => 'tns:subscribeUsersToSession'], // input parameters
5260
    ['return' => 'tns:results_subscribeUsersToSession'], // output parameters
5261
    'urn:WSRegistration', // namespace
5262
    'urn:WSRegistration#WSSuscribeUsersToSession', // soapaction
5263
    'rpc', // style
5264
    'encoded', // use
5265
    'This service subscribes a user to a session'                      // documentation
5266
);
5267
5268
// define the method WSSuscribeUsersToSession
5269
function WSSuscribeUsersToSession($params)
5270
{
5271
    global $debug;
5272
5273
    if (!WSHelperVerifyKey($params)) {
5274
        return returnError(WS_ERROR_SECRET_KEY);
5275
    }
5276
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
5277
    $userssessions_params = $params['userssessions'];
5278
5279
    if ($debug) {
5280
        error_log('WSSuscribeUsersToSession');
5281
        error_log(print_r($params, 1));
5282
5283
        if (empty($userssessions_params)) {
5284
            error_log('userssessions is empty');
5285
        }
5286
    }
5287
5288
    $results = [];
5289
    $orig_user_id_value = [];
5290
    $orig_session_id_value = [];
5291
    foreach ($userssessions_params as $usersession_params) {
5292
        $original_session_id_value = $usersession_params['original_session_id_value'];
5293
        $original_session_id_name = $usersession_params['original_session_id_name'];
5294
        $original_user_id_name = $usersession_params['original_user_id_name'];
5295
        $original_user_id_values = $usersession_params['original_user_id_values'];
5296
5297
        $sessionId = SessionManager::getSessionIdFromOriginalId(
5298
            $original_session_id_value,
5299
            $original_session_id_name
5300
        );
5301
5302
        if (empty($sessionId)) {
5303
            $orig_session_id_value[] = $original_session_id_value;
5304
            $results[] = 0;
5305
            continue;
5306
        }
5307
5308
        foreach ($original_user_id_values as $key => $row_original_user_list) {
5309
            $orig_session_id_value[] = $original_session_id_value;
5310
            $orig_user_id_value[] = $row_original_user_list['original_user_id_value'];
5311
5312
            $user_id = UserManager::get_user_id_from_original_id(
5313
                $row_original_user_list['original_user_id_value'],
5314
                $original_user_id_name
5315
            );
5316
5317
            if ($debug) {
5318
                error_log("User to subscribe: $user_id");
5319
            }
5320
5321
            if ($user_id == 0) {
5322
                $results[] = 0;
5323
                continue; // user_id doesn't exist.
5324
            } else {
5325
                $sql = "SELECT user_id FROM $user_table
5326
                        WHERE user_id ='".$user_id."' AND active= '0'";
5327
                $resu = Database::query($sql);
5328
                $r_check_user = Database::fetch_row($resu);
5329
                if (!empty($r_check_user[0])) {
5330
                    $results[] = 0;
5331
                    continue; // user_id is not active.
5332
                }
5333
5334
                SessionManager::subscribe_users_to_session(
5335
                    $sessionId,
5336
                    [$user_id],
5337
                    SESSION_VISIBLE_READ_ONLY,
5338
                    false
5339
                );
5340
                $results[] = 1;
5341
5342
                if ($debug) {
5343
                    error_log("subscribe user:$user_id to session $sessionId");
5344
                }
5345
            }
5346
        }
5347
    } // end principal foreach
5348
5349
    $count_results = count($results);
5350
    $output = [];
5351
    for ($i = 0; $i < $count_results; $i++) {
5352
        $output[] = [
5353
            'original_user_id_values' => $orig_user_id_value[$i],
5354
            'original_session_id_value' => $orig_session_id_value[$i],
5355
            'result' => $results[$i]
5356
        ];
5357
    }
5358
5359
    return $output;
5360
}
5361
5362
// WSSubscribeUserToSessionSimple
5363
$server->wsdl->addComplexType(
5364
    'subscribeUserToSessionSimple_arg',
5365
    'complexType',
5366
    'struct',
5367
    'all',
5368
    '',
5369
    [
5370
        'session'    => ['name' => 'session', 'type' => 'xsd:string'], // Session ID
5371
        'user_id'    => ['name' => 'user_id', 'type' => 'xsd:string'], // Chamilo user_id
5372
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5373
    ]
5374
);
5375
5376
$server->register(
5377
    'WSSubscribeUserToSessionSimple', // method name
5378
    ['subscribeUserToSessionSimple' => 'tns:subscribeUserToSessionSimple_arg'], // input parameters
5379
    ['return' => 'xsd:string'], // output parameters
5380
    'urn:WSRegistration', // namespace
5381
    'urn:WSRegistration#WSSubscribeUserToSessionSimple', // soapaction
5382
    'rpc', // style
5383
    'encoded', // use
5384
    'This service subscribes a user to a session in a simple way'                     // documentation
5385
);
5386
5387
/**
5388
 * @param array $params
5389
 * @return int|null|soap_fault|string
5390
 */
5391
function WSSubscribeUserToSessionSimple($params)
5392
{
5393
    global $debug;
5394
5395
    if ($debug) {
5396
        error_log('WSSubscribeUserToSessionSimple with params=['.serialize($params).']');
5397
    }
5398
5399
    // Check security key
5400
    if (!WSHelperVerifyKey($params)) {
5401
        return returnError(WS_ERROR_SECRET_KEY);
5402
    }
5403
5404
    // Get input parameters
5405
    $session_id = intval($params['session']); // Session ID
5406
    $user_id    = intval($params['user_id']); // Chamilo user id
5407
5408
    // Get user id
5409
    $user_data = api_get_user_info($user_id);
5410
5411
    // Prepare answer
5412
    $result = 0;
5413
5414
    if (empty($user_data)) {
5415
        $result = "User {$user_id} does not exist";
5416
        if ($debug) {
5417
            error_log($result);
5418
        }
5419
        return $result;
5420
    }
5421
    if (!empty($session_id) && is_numeric($session_id)) {
5422
        $session_data = api_get_session_info($session_id);
5423
        if (empty($session_data)) {
5424
            $result = "Session {$session_id} does not exist.";
5425
            if ($debug) {
5426
                error_log($result);
5427
            }
5428
        } else {
5429
            SessionManager::subscribe_users_to_session(
5430
                $session_id,
5431
                [$user_id],
5432
                SESSION_VISIBLE_READ_ONLY,
5433
                false
5434
            );
5435
            if ($debug) {
5436
                error_log('User registered to the course: '.$session_id);
5437
            }
5438
            $result = 1;
5439
        }
5440
    }
5441
    return $result;
5442
}
5443
5444
/* Register WSUnsuscribeUsersFromSession function */
5445
// Register the data structures used by the service
5446
$server->wsdl->addComplexType(
5447
    'unsubscribeUsersFromSessionParams',
5448
    'complexType',
5449
    'struct',
5450
    'all',
5451
    '',
5452
    [
5453
        'original_user_id_values'   => ['name' => 'original_user_id_values', 'type' => 'tns:originalUsersList'],
5454
        'original_user_id_name'     => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
5455
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5456
        'original_session_id_name'  => ['name' => 'original_session_id_name', 'type' => 'xsd:string']
5457
    ]
5458
);
5459
5460
$server->wsdl->addComplexType(
5461
    'unsubscribeUsersFromSessionParamsList',
5462
    'complexType',
5463
    'array',
5464
    '',
5465
    'SOAP-ENC:Array',
5466
    [],
5467
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:unsubscribeUsersFromSessionParams[]']],
5468
    'tns:unsubscribeUsersFromSessionParams'
5469
);
5470
5471
$server->wsdl->addComplexType(
5472
    'unsubscribeUsersFromSession',
5473
    'complexType',
5474
    'struct',
5475
    'all',
5476
    '',
5477
    [
5478
        'userssessions' => ['name' => 'userssessions', 'type' => 'tns:subscribeUsersToSessionParamsList'],
5479
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5480
    ]
5481
);
5482
5483
// Prepare output params, in this case will return an array
5484
$server->wsdl->addComplexType(
5485
    'result_unsubscribeUsersFromSession',
5486
    'complexType',
5487
    'struct',
5488
    'all',
5489
    '',
5490
    [
5491
        'original_user_id_values' => ['name' => 'original_user_id_values', 'type' => 'xsd:string'],
5492
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5493
        'result' => ['name' => 'result', 'type' => 'xsd:string']
5494
    ]
5495
);
5496
5497
$server->wsdl->addComplexType(
5498
    'results_unsubscribeUsersFromSession',
5499
    'complexType',
5500
    'array',
5501
    '',
5502
    'SOAP-ENC:Array',
5503
    [],
5504
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_unsubscribeUsersFromSession[]']],
5505
    'tns:result_unsubscribeUsersFromSession'
5506
);
5507
5508
// Register the method to expose
5509
$server->register(
5510
    'WSUnsuscribeUsersFromSession', // method name
5511
    ['unsubscribeUsersFromSession' => 'tns:unsubscribeUsersFromSession'], // input parameters
5512
    ['return' => 'tns:results_unsubscribeUsersFromSession'], // output parameters
5513
    'urn:WSRegistration', // namespace
5514
    'urn:WSRegistration#WSUnsuscribeUsersFromSession', // soapaction
5515
    'rpc', // style
5516
    'encoded', // use
5517
    'This service unsubscribes a user to a session'                            // documentation
5518
);
5519
5520
// define the method WSUnsuscribeUsersFromSession
5521
function WSUnsuscribeUsersFromSession($params)
5522
{
5523
    if (!WSHelperVerifyKey($params)) {
5524
        return returnError(WS_ERROR_SECRET_KEY);
5525
    }
5526
5527
    global $debug;
5528
5529
    if ($debug) {
5530
        error_log('WSUnsuscribeUsersFromSession with params=['.serialize($params).']');
5531
    }
5532
5533
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
5534
5535
    $userssessions_params = $params['userssessions'];
5536
    $results = [];
5537
    $orig_user_id_value = [];
5538
    $orig_session_id_value = [];
5539
5540
    foreach ($userssessions_params as $usersession_params) {
5541
        $original_session_id_value = $usersession_params['original_session_id_value'];
5542
        $original_session_id_name = $usersession_params['original_session_id_name'];
5543
        $original_user_id_name = $usersession_params['original_user_id_name'];
5544
        $original_user_id_values = $usersession_params['original_user_id_values'];
5545
5546
        $id_session = SessionManager::getSessionIdFromOriginalId(
5547
            $original_session_id_value,
5548
            $original_session_id_name
5549
        );
5550
5551
        if (empty($id_session)) {
5552
            $orig_session_id_value[] = $original_session_id_value;
5553
            $results[] = 0;
5554
            continue;
5555
        }
5556
5557
        foreach ($original_user_id_values as $key => $row_original_user_list) {
5558
            $orig_session_id_value[] = $original_session_id_value;
5559
            $orig_user_id_value[] = $row_original_user_list['original_user_id_value'];
5560
            $user_id = UserManager::get_user_id_from_original_id(
5561
                $row_original_user_list['original_user_id_value'],
5562
                $original_user_id_name
5563
            );
5564
5565
            if ($user_id == 0) {
5566
                $results[] = 0;
5567
                continue; // user_id doesn't exist.
5568
            } else {
5569
                $sql = "SELECT user_id FROM $user_table
5570
                        WHERE user_id ='".$user_id."' AND active= '0'";
5571
                $resu = Database::query($sql);
5572
                $r_check_user = Database::fetch_row($resu);
5573
                if (!empty($r_check_user[0])) {
5574
                    $results[] = 0;
5575
                    continue; // user_id is not active.
5576
                }
5577
5578
                SessionManager::unsubscribe_user_from_session(
5579
                    $id_session,
5580
                    $user_id
5581
                );
5582
5583
                $results[] = 1;
5584
5585
                if ($debug) {
5586
                    error_log("Unsubscribe user:$user_id to session:$id_session");
5587
                }
5588
            }
5589
        }
5590
    } // end principal foreach
5591
5592
    $count_results = count($results);
5593
    $output = [];
5594
    for ($i = 0; $i < $count_results; $i++) {
5595
        $output[] = [
5596
            'original_user_id_values' => $orig_user_id_value[$i],
5597
            'original_session_id_value' => $orig_session_id_value[$i],
5598
            'result' => $results[$i]
5599
        ];
5600
    }
5601
5602
    return $output;
5603
}
5604
5605
/* Register WSSuscribeCoursesToSession function */
5606
// Register the data structures used by the service
5607
5608
/*$server->wsdl->addComplexType(
5609
'originalCoursesList',
5610
'complexType',
5611
'array',
5612
'',
5613
'SOAP-ENC:Array',
5614
array(),
5615
array(array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'string[]')),
5616
'xsd:string'
5617
);*/
5618
$server->wsdl->addComplexType(
5619
    'course_code_type',
5620
    'complexType',
5621
    'struct',
5622
    'all',
5623
    '',
5624
    [
5625
        'course_code'   => ['name' => 'course_code', 'type' => 'xsd:string'],
5626
    ]
5627
);
5628
5629
$server->wsdl->addComplexType(
5630
    'originalCoursesList',
5631
    'complexType',
5632
    'array',
5633
    '',
5634
    'SOAP-ENC:Array',
5635
    [],
5636
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:course_code_type[]']],
5637
    'tns:course_code_type'
5638
);
5639
5640
5641
$server->wsdl->addComplexType(
5642
    'subscribeCoursesToSessionParamsList',
5643
    'complexType',
5644
    'array',
5645
    '',
5646
    'SOAP-ENC:Array',
5647
    [],
5648
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:subscribeCoursesToSessionParams[]']],
5649
    'tns:subscribeCoursesToSessionParams'
5650
);
5651
5652
$server->wsdl->addComplexType(
5653
    'subscribeCoursesToSessionParams',
5654
    'complexType',
5655
    'struct',
5656
    'all',
5657
    '',
5658
    [
5659
        'original_course_id_values' => ['name' => 'original_course_id_values', 'type' => 'tns:originalCoursesList'],
5660
        'original_course_id_name'   => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
5661
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5662
        'original_session_id_name'  => ['name' => 'original_session_id_name', 'type' => 'xsd:string']
5663
    ]
5664
);
5665
5666
$server->wsdl->addComplexType(
5667
    'subscribeCoursesToSessionParamsList',
5668
    'complexType',
5669
    'array',
5670
    '',
5671
    'SOAP-ENC:Array',
5672
    [],
5673
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:subscribeCoursesToSessionParams[]']],
5674
    'tns:subscribeCoursesToSessionParams'
5675
);
5676
5677
$server->wsdl->addComplexType(
5678
    'subscribeCoursesToSession',
5679
    'complexType',
5680
    'struct',
5681
    'all',
5682
    '',
5683
    [
5684
        'coursessessions' => ['name' => 'coursessessions', 'type' => 'tns:subscribeCoursesToSessionParamsList'],
5685
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5686
    ]
5687
);
5688
5689
// Prepare output params, in this case will return an array
5690
$server->wsdl->addComplexType(
5691
    'result_subscribeCoursesToSession',
5692
    'complexType',
5693
    'struct',
5694
    'all',
5695
    '',
5696
    [
5697
        'original_course_id_values' => ['name' => 'original_course_id_values', 'type' => 'xsd:string'],
5698
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5699
        'result' => ['name' => 'result', 'type' => 'xsd:string']
5700
    ]
5701
);
5702
5703
$server->wsdl->addComplexType(
5704
    'results_subscribeCoursesToSession',
5705
    'complexType',
5706
    'array',
5707
    '',
5708
    'SOAP-ENC:Array',
5709
    [],
5710
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_subscribeCoursesToSession[]']],
5711
    'tns:result_subscribeCoursesToSession'
5712
);
5713
5714
// Register the method to expose
5715
$server->register(
5716
    'WSSuscribeCoursesToSession', // method name
5717
    ['subscribeCoursesToSession' => 'tns:subscribeCoursesToSession'], // input parameters
5718
    ['return' => 'tns:results_subscribeCoursesToSession'], // output parameters
5719
    'urn:WSRegistration', // namespace
5720
    'urn:WSRegistration#WSSuscribeCoursesToSession', // soapaction
5721
    'rpc', // style
5722
    'encoded', // use
5723
    'This service subscribes a course to a session'                        // documentation
5724
);
5725
5726
// Define the method WSSuscribeCoursesToSession
5727
function WSSuscribeCoursesToSession($params)
5728
{
5729
    global $debug;
5730
5731
    if (!WSHelperVerifyKey($params)) {
5732
        return returnError(WS_ERROR_SECRET_KEY);
5733
    }
5734
5735
    if ($debug) {
5736
        error_log('WSSuscribeCoursesToSession: '.print_r($params, 1));
5737
    }
5738
5739
    $coursessessions_params = $params['coursessessions'];
5740
    $results = [];
5741
    $orig_course_id_value = [];
5742
    $orig_session_id_value = [];
5743
    foreach ($coursessessions_params as $coursesession_param) {
5744
        $original_session_id_value = $coursesession_param['original_session_id_value'];
5745
        $original_session_id_name = $coursesession_param['original_session_id_name'];
5746
        $original_course_id_name = $coursesession_param['original_course_id_name'];
5747
        $original_course_id_values = $coursesession_param['original_course_id_values'];
5748
5749
        $sessionId = SessionManager::getSessionIdFromOriginalId(
5750
            $original_session_id_value,
5751
            $original_session_id_name
5752
        );
5753
5754
        if (empty($sessionId)) {
5755
            $orig_session_id_value[] = $original_session_id_value;
5756
            $results[] = 0;
5757
            continue;
5758
        }
5759
5760
        // Get course list from row_original_course_id_values
5761
        foreach ($original_course_id_values as $row_original_course_list) {
5762
            $orig_session_id_value[] = $original_session_id_value;
5763
            $orig_course_id_value[] = $row_original_course_list['course_code'];
5764
5765
            $courseInfo = CourseManager::getCourseInfoFromOriginalId(
5766
                $row_original_course_list['course_code'],
5767
                $original_course_id_name
5768
            );
5769
5770
            if (empty($courseInfo) ||
5771
                (isset($courseInfo) && $courseInfo['visibility'] == 0)
5772
            ) {
5773
                $results[] = 0;
5774
                continue; // Original_course_id_value doesn't exist.
5775
            } else {
5776
                $courseCode = $courseInfo['code'];
5777
                SessionManager::add_courses_to_session(
5778
                    $sessionId,
5779
                    [$courseInfo['real_id']],
5780
                    false
5781
                );
5782
                if ($debug) {
5783
                    error_log("add_courses_to_session: course:$courseCode to session:$sessionId");
5784
                }
5785
5786
                $results[] = 1;
5787
            }
5788
        }
5789
    }
5790
5791
    $count_results = count($results);
5792
    $output = [];
5793
    for ($i = 0; $i < $count_results; $i++) {
5794
        $output[] = [
5795
            'original_course_id_values' => $orig_course_id_value[$i],
5796
            'original_session_id_value' => $orig_session_id_value[$i],
5797
            'result' => $results[$i]
5798
        ];
5799
    }
5800
5801
    return $output;
5802
}
5803
5804
/* Register WSUnsuscribeCoursesFromSession function */
5805
// Register the data structures used by the service
5806
$server->wsdl->addComplexType(
5807
    'unsubscribeCoursesFromSessionParams',
5808
    'complexType',
5809
    'struct',
5810
    'all',
5811
    '',
5812
    [
5813
        'original_course_id_values' => ['name' => 'original_course_id_values', 'type' => 'tns:originalCoursesList'],
5814
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
5815
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5816
        'original_session_id_name' => ['name' => 'original_session_id_name', 'type' => 'xsd:string']
5817
    ]
5818
);
5819
5820
$server->wsdl->addComplexType(
5821
    'unsubscribeCoursesFromSessionParamsList',
5822
    'complexType',
5823
    'array',
5824
    '',
5825
    'SOAP-ENC:Array',
5826
    [],
5827
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:unsubscribeCoursesFromSessionParams[]']],
5828
    'tns:unsubscribeCoursesFromSessionParams'
5829
);
5830
5831
$server->wsdl->addComplexType(
5832
    'unsubscribeCoursesFromSession',
5833
    'complexType',
5834
    'struct',
5835
    'all',
5836
    '',
5837
    [
5838
        'coursessessions' => ['name' => 'coursessessions', 'type' => 'tns:unsubscribeCoursesFromSessionParamsList'],
5839
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
5840
    ]
5841
);
5842
5843
// Prepare output params, in this case will return an array
5844
$server->wsdl->addComplexType(
5845
    'result_unsubscribeCoursesFromSession',
5846
    'complexType',
5847
    'struct',
5848
    'all',
5849
    '',
5850
    [
5851
        'original_course_id_values' => ['name' => 'original_course_id_values', 'type' => 'xsd:string'],
5852
        'original_session_id_value' => ['name' => 'original_session_id_value', 'type' => 'xsd:string'],
5853
        'result' => ['name' => 'result', 'type' => 'xsd:string']
5854
    ]
5855
);
5856
5857
$server->wsdl->addComplexType(
5858
    'results_unsubscribeCoursesFromSession',
5859
    'complexType',
5860
    'array',
5861
    '',
5862
    'SOAP-ENC:Array',
5863
    [],
5864
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:result_unsubscribeCoursesFromSession[]']],
5865
    'tns:result_unsubscribeCoursesFromSession'
5866
);
5867
5868
5869
// Register the method to expose
5870
$server->register(
5871
    'WSUnsuscribeCoursesFromSession', // method name
5872
    ['unsubscribeCoursesFromSession' => 'tns:unsubscribeCoursesFromSession'], // input parameters
5873
    ['return' => 'tns:results_unsubscribeCoursesFromSession'], // output parameters
5874
    'urn:WSRegistration', // namespace
5875
    'urn:WSRegistration#WSUnsuscribeCoursesFromSession', // soapaction
5876
    'rpc', // style
5877
    'encoded', // use
5878
    'This service subscribes a course to a session'                                // documentation
5879
);
5880
5881
// define the method WSUnsuscribeCoursesFromSession
5882
function WSUnsuscribeCoursesFromSession($params)
5883
{
5884
    if (!WSHelperVerifyKey($params)) {
5885
        return returnError(WS_ERROR_SECRET_KEY);
5886
    }
5887
5888
    $sessionAdminId = DEFAULT_ADMIN_USER_ID;
5889
5890
    // Initialisation
5891
    $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5892
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
5893
    $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
5894
    $coursessessions_params = $params['coursessessions'];
5895
    $results = [];
5896
    $orig_course_id_value = [];
5897
    $orig_session_id_value = [];
5898
5899
    foreach ($coursessessions_params as $coursesession_param) {
5900
        $original_session_id_value = $coursesession_param['original_session_id_value'];
5901
        $original_session_id_name = $coursesession_param['original_session_id_name'];
5902
        $original_course_id_name = $coursesession_param['original_course_id_name'];
5903
        $original_course_id_values = $coursesession_param['original_course_id_values'];
5904
        $orig_session_id_value[] = $original_session_id_value;
5905
5906
        $id_session = SessionManager::getSessionIdFromOriginalId(
5907
            $original_session_id_value,
5908
            $original_session_id_name
5909
        );
5910
5911
        if (empty($id_session)) {
5912
            $results[] = 0;
5913
            continue;
5914
        }
5915
5916
        // Get courses list from row_original_course_id_values
5917
        $course_list = [];
5918
        $courseIdList = [];
5919
        foreach ($original_course_id_values as $row_original_course_list) {
5920
            $course_code = Database::escape_string($row_original_course_list['course_code']);
5921
5922
            // Check whether exits $x_course_code into user_field_values table.
5923
            $courseInfo = CourseManager::getCourseInfoFromOriginalId(
5924
                $row_original_course_list['course_code'],
5925
                $original_course_id_name
5926
            );
5927
5928
            if (empty($courseInfo) || isset($courseInfo) &&
5929
                $courseInfo['visibility'] == 0
5930
            ) {
5931
                continue; // Course_code doesn't exist'
5932
            }
5933
5934
            $course_list[] = $courseInfo['code'];
5935
            $courseIdList[] = $courseInfo['real_id'];
5936
        }
5937
5938
        if (empty($course_list)) {
5939
            $results[] = 0;
5940
            continue;
5941
        }
5942
5943
        $orig_course_id_value[] = implode(',', $course_list);
5944
5945
        foreach ($courseIdList as $courseId) {
5946
            $courseId = intval($courseId);
5947
            Database::query("DELETE FROM $tbl_session_rel_course
5948
                            WHERE c_id ='$courseId' AND session_id='$id_session'");
5949
            $result = Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE c_id='$courseId' AND session_id = '$id_session'");
5950
5951
            Event::addEvent(
5952
                LOG_SESSION_DELETE_COURSE,
5953
                LOG_COURSE_ID,
5954
                $courseId,
5955
                api_get_utc_datetime(),
5956
                $sessionAdminId,
5957
                $courseId,
5958
                $id_session
5959
            );
5960
5961
            $return = Database::affected_rows($result);
5962
        }
5963
5964
        $nbr_courses = 0;
5965
        $sql = "SELECT nbr_courses FROM $tbl_session WHERE id = '$id_session'";
5966
        $res_nbr_courses = Database::query($sql);
5967
        $row_nbr_courses = Database::fetch_row($res_nbr_courses);
5968
5969
        if (Database::num_rows($res_nbr_courses) > 0) {
5970
            $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...
5971
        }
5972
5973
        // Update number of users in the session.
5974
        $update_sql = "UPDATE $tbl_session SET nbr_courses= $nbr_courses WHERE id='$id_session' ";
5975
        Database::query($update_sql);
5976
5977
        $results[] = 1;
5978
        continue;
5979
    }
5980
5981
    $count_results = count($results);
5982
    $output = [];
5983
    for ($i = 0; $i < $count_results; $i++) {
5984
        $output[] = [
5985
            'original_course_id_values' => $orig_course_id_value[$i],
5986
            'original_session_id_value' => $orig_session_id_value[$i],
5987
            'result' => $results[$i],
5988
        ];
5989
    }
5990
5991
    return $output;
5992
}
5993
5994
/** WSListCourses **/
5995
5996
$server->wsdl->addComplexType(
5997
    'listCourseInput',
5998
    'complexType',
5999
    'struct',
6000
    'all',
6001
    '',
6002
    [
6003
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
6004
        'original_course_id_name' => ['name' => 'original_course_id_name', 'type' => 'xsd:string'],
6005
        'from' => ['name' => 'from', 'type' => 'xsd:int'],
6006
        'to' => ['name' => 'to', 'type' => 'xsd:int']
6007
    ]
6008
);
6009
6010
$server->wsdl->addComplexType(
6011
    'course',
6012
    'complexType',
6013
    'struct',
6014
    'all',
6015
    '',
6016
    [
6017
        'id' => ['name' => 'id', 'type' => 'xsd:int'],
6018
        'code' => ['name' => 'code', 'type' => 'xsd:string'],
6019
        'external_course_id' => ['name' => 'external_course_id', 'type' => 'xsd:string'],
6020
        'title' => ['name' => 'title', 'type' => 'xsd:string'],
6021
        'language' => ['name' => 'language', 'type' => 'xsd:string'],
6022
        'category_name' => ['name' => 'category_name', 'type' => 'xsd:string'],
6023
        'visibility' => ['name' => 'visibility', 'type' => 'xsd:int'],
6024
        'number_students' => ['name' => 'number_students', 'type' => 'xsd:int']
6025
    ]
6026
);
6027
6028
$server->wsdl->addComplexType(
6029
    'courses',
6030
    'complexType',
6031
    'array',
6032
    '',
6033
    'SOAP-ENC:Array',
6034
    [],
6035
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:course[]']],
6036
    'tns:course'
6037
);
6038
6039
6040
// Register the method to expose
6041
$server->register(
6042
    'WSListCourses', // method name
6043
    ['listCourseInput' => 'tns:listCourseInput'], // input parameters
6044
    ['return' => 'tns:courses'], // output parameters
6045
    'urn:WSRegistration', // namespace
6046
    'urn:WSRegistration#WSListCourses', // soapaction
6047
    'rpc', // style
6048
    'encoded', // use
6049
    'This service list courses available on the system'                             // documentation
6050
);
6051
6052
// define the method WSListCourses
6053
function WSListCourses($params)
6054
{
6055
    global $debug;
6056
    if (!WSHelperVerifyKey($params)) {
6057
        return returnError(WS_ERROR_SECRET_KEY);
6058
    }
6059
6060
    $course_field_name = isset($params['original_course_id_name']) ? $params['original_course_id_name'] : '';
6061
6062
    $courses_result = [];
6063
    $category_names = [];
6064
6065
    $from = isset($params['from']) ? $params['from'] : null;
6066
    $to = isset($params['to']) ? $params['to'] : null;
6067
6068
    if ($debug) {
6069
        error_log(print_r($params, 1));
6070
        error_log($from);
6071
        error_log($to);
6072
    }
6073
6074
    $courses = CourseManager::get_courses_list($from, $to);
6075
6076
    foreach ($courses as $course) {
6077
        $course_tmp = [];
6078
        $course_tmp['id'] = $course['id'];
6079
        $course_tmp['code'] = $course['code'];
6080
        $course_tmp['title'] = $course['title'];
6081
        $course_tmp['language'] = $course['course_language'];
6082
        $course_tmp['visibility'] = $course['visibility'];
6083
        $course_tmp['category_name'] = '';
6084
6085
        // Determining category name
6086
        if (!empty($course['category_code']) &&
6087
            isset($category_names[$course['category_code']])
6088
        ) {
6089
            $course_tmp['category_name'] = $category_names[$course['category_code']];
6090
        } else {
6091
            $category = CourseManager::get_course_category($course['category_code']);
6092
            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...
6093
                $category_names[$course['category_code']] = $category['name'];
6094
                $course_tmp['category_name'] = $category['name'];
6095
            }
6096
        }
6097
6098
        // Determining number of students registered in course
6099
        $course_tmp['number_students'] = CourseManager::get_users_count_in_course(
6100
            $course['code']
6101
        );
6102
6103
        // Determining external course id
6104
        $externalCourseId = '';
6105
        if ($course_field_name) {
6106
            $externalCourseId = CourseManager::get_course_extra_field_value(
6107
                $course_field_name,
6108
                $course['code']
6109
            );
6110
        }
6111
6112
        $course_tmp['external_course_id'] = $externalCourseId;
6113
        $courses_result[] = $course_tmp;
6114
    }
6115
6116
    return $courses_result;
6117
}
6118
6119
6120
/* Get user api key */
6121
$server->wsdl->addComplexType(
6122
    'userApiKey',
6123
    'complexType',
6124
    'struct',
6125
    'all',
6126
    '',
6127
    [
6128
        'original_user_id_name'     => ['name' => 'original_user_id_name', 'type' => 'xsd:string'],
6129
        'original_user_id_value'    => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
6130
        'chamilo_username'          => ['name' => 'chamilo_username', 'type' => 'xsd:string'],
6131
        'secret_key'                => ['name' => 'secret_key', 'type' => 'xsd:string']
6132
    ]
6133
);
6134
6135
// Register the method to expose
6136
$server->register(
6137
    'WSUpdateUserApiKey', // method name
6138
    ['userApiKey' => 'tns:userApiKey'], // input parameters
6139
    ['return' => 'xsd:string'], // output parameters
6140
    'urn:WSRegistration', // namespace
6141
    'urn:WSRegistration#WSListCourses', // soapaction
6142
    'rpc', // style
6143
    'encoded', // use
6144
    'This service return user api key'       // documentation
6145
);
6146
6147
/**
6148
 * @param array $params
6149
 * @return int|null|soap_fault
6150
 */
6151
function WSUpdateUserApiKey($params)
6152
{
6153
    if (!WSHelperVerifyKey($params)) {
6154
        return returnError(WS_ERROR_SECRET_KEY);
6155
    }
6156
6157
    $user_id = UserManager::get_user_id_from_original_id(
6158
        $params['original_user_id_value'],
6159
        $params['original_user_id_name']
6160
    );
6161
    if (!$user_id) {
6162
        if (!empty($params['chamilo_username'])) {
6163
            $info = api_get_user_info_from_username($params['chamilo_username']);
6164
            $user_id = $info['user_id'];
6165
            // Save new fieldlabel into user_field table.
6166
            UserManager::create_extra_field($params['original_user_id_name'], 1, $params['original_user_id_name'], '');
6167
            // Save the external system's id into user_field_value table.
6168
            UserManager::update_extra_field_value(
6169
                $user_id,
6170
                $params['original_user_id_name'],
6171
                $params['original_user_id_value']
6172
            );
6173
        } else {
6174
            return 0;
6175
        }
6176
    }
6177
6178
    $list = UserManager::get_api_keys($user_id);
6179
    $key_id = UserManager::get_api_key_id($user_id, 'dokeos');
6180
6181
    if (isset($list[$key_id])) {
6182
        $apikey = $list[$key_id];
6183
    } else {
6184
        $lastid = UserManager::update_api_key($user_id, 'dokeos');
6185
        if ($lastid) {
6186
            $apikeys = UserManager::get_api_keys($user_id);
6187
            $apikey = $apikeys[$lastid];
6188
        }
6189
    }
6190
6191
    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...
6192
}
6193
6194
/** WSListSessions **/
6195
$server->wsdl->addComplexType(
6196
    'session_arg',
6197
    'complexType',
6198
    'struct',
6199
    'all',
6200
    '',
6201
    [
6202
        'from'  => ['name' => 'from', 'type' => 'xsd:int'],
6203
        'to'    => ['name' => 'to', 'type' => 'xsd:int'],
6204
        'date_start'  => ['name' => 'date_start', 'type' => 'xsd:string'],
6205
        'date_end'    => ['name' => 'date_end', 'type' => 'xsd:string'],
6206
        'secret_key'  => ['name' => 'secret_key', 'type' => 'xsd:string']
6207
    ]
6208
);
6209
6210
$server->wsdl->addComplexType(
6211
    'session',
6212
    'complexType',
6213
    'struct',
6214
    'all',
6215
    '',
6216
    [
6217
        'id' => ['name' => 'id', 'type' => 'xsd:int'],
6218
        'title' => ['name' => 'title', 'type' => 'xsd:string'],
6219
        'url' => ['name' => 'url', 'type' => 'xsd:string'],
6220
        'date_start' => ['name' => 'date_start', 'type' => 'xsd:string'],
6221
        'date_end' => ['name' => 'date_end', 'type' => 'xsd:string'],
6222
    ]
6223
);
6224
6225
$server->wsdl->addComplexType(
6226
    'sessions',
6227
    'complexType',
6228
    'array',
6229
    '',
6230
    'SOAP-ENC:Array',
6231
    [],
6232
    [
6233
        ['ref'=>'SOAP-ENC:arrayType',
6234
            'wsdl:arrayType'=>'tns:session[]']
6235
    ],
6236
    'tns:session'
6237
);
6238
6239
// Register the method to expose
6240
$server->register(
6241
    'WSListSessions', // method name
6242
    ['input'  => 'tns:session_arg'], // input parameters
6243
    ['return' => 'tns:sessions'], // output parameters
6244
    'urn:WSRegistration', // namespace
6245
    'urn:WSRegistration#WSListSessions', // soapaction
6246
    'rpc', // style
6247
    'encoded', // use
6248
    'This service returns a list of sessions' // documentation
6249
);
6250
6251
6252
/**
6253
 * Get a list of sessions (id, title, url, date_start, date_end) and
6254
 * return to caller. Date start can be set to ask only for the sessions
6255
 * starting at or after this date. Date end can be set to ask only for the
6256
 * sessions ending before or at this date.
6257
 * Function registered as service. Returns strings in UTF-8.
6258
 * @param array List of parameters (security key, date_start and date_end)
6259
 * @return array Sessions list (id=>[title=>'title',url='http://...',date_start=>'...',date_end=>''])
6260
 */
6261
function WSListSessions($params)
6262
{
6263
    if (!WSHelperVerifyKey($params)) {
6264
        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...
6265
    }
6266
    $sql_params = [];
6267
    // Dates should be provided in YYYY-MM-DD format, UTC
6268
    if (!empty($params['date_start'])) {
6269
        $sql_params['s.access_start_date'] = ['operator' => '>=', 'value' => $params['date_start']];
6270
    }
6271
    if (!empty($params['date_end'])) {
6272
        $sql_params['s.access_end_date'] = ['operator' => '<=', 'value' => $params['date_end']];
6273
    }
6274
    $from = isset($params['from']) ? $params['from'] : null;
6275
    $to = isset($params['to']) ? $params['to'] : null;
6276
6277
    $sessions_list = SessionManager::get_sessions_list($sql_params, null, $from, $to);
6278
    $return_list = [];
6279
    foreach ($sessions_list as $session) {
6280
        $return_list[] = [
6281
            'id' => $session['id'],
6282
            'title' => $session['name'],
6283
            // something like http://my.chamilo.net/main/session/index.php?session_id=5
6284
            'url' => api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$session['id'],
6285
            'date_start' => $session['access_start_date'],
6286
            'date_end' => $session['access_end_date'],
6287
        ];
6288
    }
6289
6290
    return $return_list;
6291
}
6292
6293
/* Register WSUserSubscribedInCourse function */
6294
// Register the data structures used by the service
6295
6296
//prepare input params
6297
6298
// Input params for editing users
6299
$server->wsdl->addComplexType(
6300
    'UserSubscribedInCourse',
6301
    'complexType',
6302
    'struct',
6303
    'all',
6304
    '',
6305
    [
6306
        'course' => ['name' => 'course', 'type' => 'xsd:string'],
6307
        //Course string code
6308
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
6309
        //Chamilo user_id
6310
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
6311
    ]
6312
);
6313
6314
// Register the method to expose
6315
$server->register(
6316
    'WSUserSubscribedInCourse', // method name
6317
    ['UserSubscribedInCourse' => 'tns:UserSubscribedInCourse'], // input parameters
6318
    ['return' => 'xsd:string'], // output parameters
6319
    'urn:WSRegistration', // namespace
6320
    'urn:WSRegistration#WSUserSubscribedInCourse', // soapaction
6321
    'rpc', // style
6322
    'encoded', // use
6323
    'This service checks if user assigned to course'    // documentation
6324
);
6325
6326
/**
6327
 * Web service to tell if a given user is subscribed to the course
6328
 * @param array $params Array of parameters (course and user_id)
6329
 * @return bool|null|soap_fault A simple boolean (true if user is subscribed, false otherwise)
6330
 */
6331
function WSUserSubscribedInCourse($params)
6332
{
6333
    global $debug;
6334
6335
    if ($debug) {
6336
        error_log('WSUserSubscribedInCourse');
6337
    }
6338
    if ($debug) {
6339
        error_log('Params '.print_r($params, 1));
6340
    }
6341
    if (!WSHelperVerifyKey($params)) {
6342
        return returnError(WS_ERROR_SECRET_KEY);
6343
    }
6344
    $courseCode = $params['course']; //Course code
6345
    $userId = $params['user_id']; //chamilo user id
6346
6347
    return CourseManager::is_user_subscribed_in_course($userId, $courseCode);
6348
}
6349
6350
/* Search session Web Service start */
6351
6352
// Input params for WSSearchSession
6353
$server->wsdl->addComplexType(
6354
    'SearchSession',
6355
    'complexType',
6356
    'struct',
6357
    'all',
6358
    '',
6359
    [
6360
        'term' => ['name' => 'term', 'type' => 'xsd:string'],
6361
        'extrafields' => ['name' => 'extrafields', 'type' => 'xsd:string'],
6362
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string']
6363
    ]
6364
);
6365
6366
//Output params for WSSearchSession
6367
$server->wsdl->addComplexType(
6368
    'searchedSessionExtra',
6369
    'complexType',
6370
    'struct',
6371
    'all',
6372
    '',
6373
    [
6374
        'variable' => ['name'=>'variable', 'type'=>'xsd:string'],
6375
        'value' => ['name'=>'value', 'type'=>'xsd:string']
6376
    ]
6377
);
6378
6379
$server->wsdl->addComplexType(
6380
    'searchedSessionExtras',
6381
    'complexType',
6382
    'array',
6383
    '',
6384
    'SOAP-ENC:Array',
6385
    [],
6386
    [
6387
        ['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:searchedSessionExtra[]']
6388
    ],
6389
    'tns:searchedSessionExtra'
6390
);
6391
6392
$server->wsdl->addComplexType(
6393
    'searchedSession',
6394
    'complexType',
6395
    'struct',
6396
    'all',
6397
    '',
6398
    [
6399
        'id' => ['name' => 'id', 'type' => 'xsd:int'],
6400
        'id_coach' => ['name' => 'id_coach', 'type' => 'xsd:int'],
6401
        'name' => ['name' => 'name', 'type' => 'xsd:string'],
6402
        'nbr_courses' => ['name' => 'nbr_courses', 'type' => 'xsd:int'],
6403
        'nbr_users' => ['name' => 'nbr_users', 'type' => 'xsd:int'],
6404
        'nbr_classes' => ['name' => 'nbr_classes', 'type' => 'xsd:int'],
6405
        'date_start' => ['name' => 'date_start', 'type' => 'xsd:string'],
6406
        'date_end' => ['name' => 'date_end', 'type' => 'xsd:string'],
6407
        'nb_days_access_before_beginning' => ['name' => 'nb_days_access_before_beginning', 'type' => 'xsd:int'],
6408
        'nb_days_access_after_end' => ['nb_days_access_after_end' => 'duration', 'type' => 'xsd:int'],
6409
        'session_admin_id' => ['session_admin_id' => 'duration', 'type' => 'xsd:int'],
6410
        'visibility' => ['visibility' => 'duration', 'type' => 'xsd:int'],
6411
        'session_category_id' => ['session_category_id' => 'duration', 'type' => 'xsd:int'],
6412
        'promotion_id' => ['promotion_id' => 'duration', 'type' => 'xsd:int'],
6413
        'description' => ['name' => 'description', 'type' => 'xsd:string'],
6414
        'show_description' => ['name' => 'description', 'type' => 'xsd:int'],
6415
        'duration' => ['name' => 'duration', 'type' => 'xsd:string'],
6416
        'extra' => ['name' => 'extra', 'type' => 'tns:searchedSessionExtras'],
6417
    ]
6418
);
6419
6420
$server->wsdl->addComplexType(
6421
    'searchedSessionList',
6422
    'complexType',
6423
    'array',
6424
    '',
6425
    'SOAP-ENC:Array',
6426
    [],
6427
    [
6428
        ['ref' => 'SOAP-ENC:arrayType',
6429
            'wsdl:arrayType' => 'tns:searchedSession[]']
6430
    ],
6431
    'tns:searchedSession'
6432
);
6433
6434
//Reister WSSearchSession
6435
$server->register(
6436
    'WSSearchSession',
6437
    ['SearchSession' => 'tns:SearchSession'], // input parameters
6438
    ['return' => 'tns:searchedSessionList'], // output parameters
6439
    'urn:WSRegistration', // namespace
6440
    'urn:WSRegistration#WSSearchSession', // soapaction
6441
    'rpc', // style
6442
    'encoded', // use
6443
    'This service to get a session list filtered by name, description or short description extra field'    // documentation
6444
);
6445
6446
/**
6447
 * Web service to get a session list filtered by name, description or short description extra field
6448
 * @param array $params Contains the following parameters
6449
 *   string $params['term'] Search term
6450
 *   string $params['extrafields'] Extrafields to include in request result
6451
 *   string $params['secret_key'] Secret key to check
6452
 * @return array The list
6453
 */
6454
function WSSearchSession($params)
6455
{
6456
    if (!WSHelperVerifyKey($params['secret_key'])) {
6457
        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...
6458
    }
6459
6460
    $fieldsToInclude = [];
6461
6462
    if (!empty($params['extrafields'])) {
6463
        $fieldsToInclude = explode(',', $params['extrafields']);
6464
        foreach ($fieldsToInclude as &$field) {
6465
            if (empty($field)) {
6466
                continue;
6467
            }
6468
6469
            $field = trim($field);
6470
        }
6471
    }
6472
6473
    return SessionManager::searchSession($params['term'], $fieldsToInclude);
6474
}
6475
6476
/* Search session Web Service end */
6477
/* Fetch session Web Service start */
6478
// Input params for WSFetchSession
6479
$server->wsdl->addComplexType(
6480
    'FetchSession',
6481
    'complexType',
6482
    'struct',
6483
    'all',
6484
    '',
6485
    [
6486
        'id' => ['name' => 'id', 'type' => 'xsd:int'],
6487
        'extrafields' => ['name' => 'extrafields', 'type' => 'xsd:string'],
6488
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string']
6489
    ]
6490
);
6491
6492
//Reister WSFetchSession
6493
$server->register(
6494
    'WSFetchSession',
6495
    ['SearchSession' => 'tns:FetchSession'], // input parameters
6496
    ['return' => 'tns:searchedSessionList'], // output parameters
6497
    'urn:WSRegistration', // namespace
6498
    'urn:WSRegistration#WSFetchSession', // soapaction
6499
    'rpc', // style
6500
    'encoded', // use
6501
    'This service get a session by its id. Optionally can get its extra fields values'    // documentation
6502
);
6503
6504
/**
6505
 * Web service to get a session by its id. Optionally can get its extra fields values
6506
 * @param array $params Contains the following parameters:
6507
 *   int $params['id'] The session id
6508
 *   string $params['extrafields'] Extrafields to include in request result
6509
 *   string $params['secret_key'] Secret key to check
6510
 * @return array The session data
6511
 */
6512
function WSFetchSession($params)
6513
{
6514
    if (!WSHelperVerifyKey($params['secret_key'])) {
6515
        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...
6516
    }
6517
6518
    $fieldsToInclude = explode(',', $params['extrafields']);
6519
6520
    foreach ($fieldsToInclude as &$field) {
6521
        if (empty($field)) {
6522
            continue;
6523
        }
6524
6525
        $field = trim($field);
6526
    }
6527
6528
    $sessionData = SessionManager::fetch($params['id']);
6529
6530
    if ($sessionData === false) {
6531
        return returnError(WS_ERROR_INVALID_INPUT);
6532
    }
6533
6534
    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...
6535
        $sessionData['extra'] = SessionManager::getFilteredExtraFields($params['id'], $fieldsToInclude);
6536
    }
6537
6538
    return [$sessionData];
6539
}
6540
6541
/* Fetch session Web Service end */
6542
6543
/* Register WSCertificatesList function */
6544
// Register the data structures used by the service
6545
$server->wsdl->addComplexType(
6546
    'certificateDetails',
6547
    'complexType',
6548
    'struct',
6549
    'all',
6550
    '',
6551
    [
6552
        'id' => ['name' => 'id', 'type' => 'xsd:int'],
6553
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
6554
        'course_code' => ['name' => 'course_code', 'type' => 'xsd:string'],
6555
        'session_id' => ['name' => 'session_id', 'type' => 'xsd:int'],
6556
        'cat_id' => ['name' => 'cat_id', 'type' => 'xsd:int'],
6557
        'created_at' => ['name' => 'created_at', 'type' => 'xsd:string'],
6558
        'path_certificate' => ['name' => 'path_certificate', 'type' => 'xsd:string']
6559
    ]
6560
);
6561
6562
$server->wsdl->addComplexType(
6563
    'certificatesList',
6564
    'complexType',
6565
    'array',
6566
    '',
6567
    'SOAP-ENC:Array',
6568
    [],
6569
    [
6570
        ['ref'=>'SOAP-ENC:arrayType',
6571
            'wsdl:arrayType'=>'tns:certificateDetails[]']
6572
    ],
6573
    'tns:certificateDetails'
6574
);
6575
// Register the method to expose
6576
$server->register(
6577
    'WSCertificatesList', // method name
6578
    [
6579
        'startingDate' => 'xsd:string', // input parameters
6580
        'endingDate' => 'xsd:string'
6581
    ],
6582
    ['return' => 'tns:certificatesList'], // output parameters
6583
    'urn:WSRegistration', // namespace
6584
    'urn:WSRegistration#WSCertificatesList', // soapaction
6585
    'rpc', // style
6586
    'encoded', // use
6587
    'This service returns a list of certificates'   // documentation
6588
);
6589
6590
function WSCertificatesList($startingDate = '', $endingDate = '')
6591
{
6592
    $certificatesCron = api_get_setting('add_gradebook_certificates_cron_task_enabled');
6593
    if ($certificatesCron === 'true') {
6594
        require_once api_get_path(SYS_CODE_PATH).'cron/add_gradebook_certificates.php';
6595
    }
6596
    $result = [];
6597
    $certificateTable = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
6598
    $userTable = Database::get_main_table(TABLE_MAIN_USER);
6599
    $categoryTable = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
6600
6601
    $query = "SELECT
6602
                    certificate.id,
6603
                    user.username,
6604
                    category.course_code,
6605
                    category.session_id,
6606
                    certificate.user_id,
6607
                    certificate.cat_id,
6608
                    certificate.created_at,
6609
                    certificate.path_certificate
6610
                FROM $certificateTable AS certificate
6611
                JOIN $userTable AS user
6612
                ON certificate.user_id = user.user_id
6613
                JOIN $categoryTable AS category
6614
                ON certificate.cat_id = category.id";
6615
6616
    if (!empty($startingDate) && !empty($endingDate)) {
6617
        $query .= " WHERE certificate.created_at BETWEEN '$startingDate' AND '$endingDate'";
6618
    } elseif (!empty($startingDate)) {
6619
        $query .= " WHERE certificate.created_at >= '$startingDate'";
6620
    } elseif (!empty($endingDate)) {
6621
        $query .= " WHERE certificate.created_at <= '$endingDate'";
6622
    }
6623
6624
    $queryResult = Database::query($query);
6625
    while ($row = Database::fetch_array($queryResult)) {
6626
        $userPath = USermanager::getUserPathById($row['user_id'], 'web');
6627
        $row['path_certificate'] = $userPath.'/certificate'.$row['path_certificate'];
6628
        $result[] = $row;
6629
    }
6630
6631
    return $result;
6632
}
6633
6634
/* Create group Web Service start */
6635
// Register the data structures used by the service
6636
6637
// Input params for WSCreateGroup
6638
$server->wsdl->addComplexType(
6639
    'createGroup',
6640
    'complexType',
6641
    'struct',
6642
    'all',
6643
    '',
6644
    [
6645
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
6646
        'name' => ['name' => 'name', 'type' => 'xsd:string']
6647
    ]
6648
);
6649
6650
// Register the method to expose
6651
$server->register(
6652
    'WSCreateGroup', // method name
6653
    ['createGroup' => 'tns:createGroup'], // input parameters
6654
    ['return' => 'xsd:string'], // output parameters
6655
    'urn:WSRegistration', // namespace
6656
    'urn:WSRegistration#WSCreateGroup', // soapaction
6657
    'rpc', // style
6658
    'encoded', // use
6659
    'This service adds a group'                 // documentation
6660
);
6661
6662
// Define the method WSCreateGroup
6663
function WSCreateGroup($params)
6664
{
6665
    if (!WSHelperVerifyKey($params['secret_key'])) {
6666
        return returnError(WS_ERROR_SECRET_KEY);
6667
    }
6668
    $userGroup = new UserGroup();
6669
    $params = [
6670
        'name' => $params['name']
6671
    ];
6672
    return $userGroup->save($params);
6673
}
6674
6675
/* Create group Web Service end */
6676
6677
/* Update group Web Service start */
6678
// Register the data structures used by the service
6679
6680
// Input params for WSUpdateGroup
6681
$server->wsdl->addComplexType(
6682
    'updateGroup',
6683
    'complexType',
6684
    'struct',
6685
    'all',
6686
    '',
6687
    [
6688
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6689
        'id' => ['name' => 'id', 'type' => 'xsd:string'],
6690
        'name' => ['name' => 'name', 'type' => 'xsd:string'],
6691
        'description'   => ['name' => 'description', 'type' => 'xsd:string'],
6692
        'url' => ['name' => 'url', 'type' => 'xsd:string'],
6693
        'visibility' => ['name' => 'visibility', 'type' => 'xsd:string'],
6694
        'picture_uri' => ['name' => 'picture_uri', 'type' => 'xsd:string'],
6695
        'allow_member_group_to_leave' => ['name' => 'allow_member_group_to_leave', 'type' => 'xsd:string']
6696
    ]
6697
);
6698
6699
// Register the method to expose
6700
$server->register(
6701
    'WSUpdateGroup', // method name
6702
    ['updateGroup' => 'tns:updateGroup'], // input parameters
6703
    ['return' => 'xsd:string'], // output parameters
6704
    'urn:WSRegistration', // namespace
6705
    'urn:WSRegistration#WSUpdateGroup', // soapaction
6706
    'rpc', // style
6707
    'encoded', // use
6708
    'This service updates a group'              // documentation
6709
);
6710
6711
// Define the method WSUpdateGroup
6712
function WSUpdateGroup($params)
6713
{
6714
    if (!WSHelperVerifyKey($params['secret_key'])) {
6715
        return returnError(WS_ERROR_SECRET_KEY);
6716
    }
6717
    $params['allow_member_group_to_leave'] = null;
6718
    $userGroup = new UserGroup();
6719
6720
    return $userGroup->update($params);
6721
}
6722
6723
/* Update group Web Service end */
6724
6725
/* Delete group Web Service start */
6726
// Register the data structures used by the service
6727
6728
// Input params for WSDeleteGroup
6729
$server->wsdl->addComplexType(
6730
    'deleteGroup',
6731
    'complexType',
6732
    'struct',
6733
    'all',
6734
    '',
6735
    [
6736
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6737
        'id' => ['name' => 'id', 'type' => 'xsd:string']
6738
    ]
6739
);
6740
6741
// Register the method to expose
6742
$server->register(
6743
    'WSDeleteGroup', // method name
6744
    ['deleteGroup' => 'tns:deleteGroup'], // input parameters
6745
    ['return' => 'xsd:string'], // output parameters
6746
    'urn:WSRegistration', // namespace
6747
    'urn:WSRegistration#WSDeleteGroup', // soapaction
6748
    'rpc', // style
6749
    'encoded', // use
6750
    'This service deletes a group'              // documentation
6751
);
6752
6753
// Define the method WSDeleteGroup
6754
function WSDeleteGroup($params)
6755
{
6756
    if (!WSHelperVerifyKey($params['secret_key'])) {
6757
        return returnError(WS_ERROR_SECRET_KEY);
6758
    }
6759
    $userGroup = new UserGroup();
6760
6761
    return $userGroup->delete($params['id']);
6762
}
6763
6764
/* Delete group Web Service end */
6765
6766
/* Bind group to parent Web Service start */
6767
// Register the data structures used by the service
6768
6769
// Input params for GroupBindToParent
6770
$server->wsdl->addComplexType(
6771
    'groupBindToParent',
6772
    'complexType',
6773
    'struct',
6774
    'all',
6775
    '',
6776
    [
6777
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6778
        'id' => ['name' => 'id', 'type' => 'xsd:string'],
6779
        'parent_id' => ['name' => 'parent_id', 'type' => 'xsd:string']
6780
    ]
6781
);
6782
6783
// Register the method to expose
6784
$server->register(
6785
    'GroupBindToParent', // method name
6786
    ['groupBindToParent' => 'tns:groupBindToParent'], // input parameters
6787
    ['return' => 'xsd:string'], // output parameters
6788
    'urn:WSRegistration', // namespace
6789
    'urn:WSRegistration#GroupBindToParent', // soapaction
6790
    'rpc', // style
6791
    'encoded', // use
6792
    'This service binds a group to a parent'                // documentation
6793
);
6794
6795
// Define the method GroupBindToParent
6796
function GroupBindToParent($params)
6797
{
6798
    if (!WSHelperVerifyKey($params['secret_key'])) {
6799
        return returnError(WS_ERROR_SECRET_KEY);
6800
    }
6801
    $userGroup = new UserGroup();
6802
6803
    return $userGroup->setParentGroup($params['id'], $params['parent_id']);
6804
}
6805
6806
/* Bind group Web Service end */
6807
6808
/* Unbind group from parent Web Service start */
6809
// Register the data structures used by the service
6810
6811
// Input params for GroupUnbindFromParent
6812
$server->wsdl->addComplexType(
6813
    'groupUnbindFromParent',
6814
    'complexType',
6815
    'struct',
6816
    'all',
6817
    '',
6818
    [
6819
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6820
        'id' => ['name' => 'id', 'type' => 'xsd:string']
6821
    ]
6822
);
6823
6824
// Register the method to expose
6825
$server->register(
6826
    'GroupUnbindFromParent', // method name
6827
    ['groupUnbindFromParent' => 'tns:groupUnbindFromParent'], // input parameters
6828
    ['return' => 'xsd:string'], // output parameters
6829
    'urn:WSRegistration', // namespace
6830
    'urn:WSRegistration#GroupUnbindFromParent', // soapaction
6831
    'rpc', // style
6832
    'encoded', // use
6833
    'This service unbinds a group from its parent'                  // documentation
6834
);
6835
6836
// Define the method GroupUnbindFromParent
6837
function GroupUnbindFromParent($params)
6838
{
6839
    if (!WSHelperVerifyKey($params['secret_key'])) {
6840
        return returnError(WS_ERROR_SECRET_KEY);
6841
    }
6842
    $userGroup = new UserGroup();
6843
    return $userGroup->setParentGroup($params['id'], 0);
6844
}
6845
6846
/* Unbind group Web Service end */
6847
6848
/* Add user to group Web Service start */
6849
// Register the data structures used by the service
6850
6851
// Input params for WSAddUserToGroup
6852
$server->wsdl->addComplexType(
6853
    'addUserToGroup',
6854
    'complexType',
6855
    'struct',
6856
    'all',
6857
    '',
6858
    [
6859
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6860
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
6861
        'group_id' => ['name' => 'group_id', 'type' => 'xsd:string'],
6862
        'relation_type' => ['name' => 'relation_type', 'type' => 'xsd:string']
6863
    ]
6864
);
6865
6866
// Register the method to expose
6867
$server->register(
6868
    'WSAddUserToGroup', // method name
6869
    ['addUserToGroup' => 'tns:addUserToGroup'], // input parameters
6870
    ['return' => 'xsd:string'], // output parameters
6871
    'urn:WSRegistration', // namespace
6872
    'urn:WSRegistration#WSAddUserToGroup', // soapaction
6873
    'rpc', // style
6874
    'encoded', // use
6875
    'This service adds a user to a group'               // documentation
6876
);
6877
6878
// Define the method WSAddUserToGroup
6879
function WSAddUserToGroup($params)
6880
{
6881
    if (!WSHelperVerifyKey($params['secret_key'])) {
6882
        return returnError(WS_ERROR_SECRET_KEY);
6883
    }
6884
6885
    $userGroup = new UserGroup();
6886
6887
    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...
6888
        $params['group_id'],
6889
        [0 => $params['user_id']],
6890
        false,
6891
        $params['relation_type']
6892
    );
6893
}
6894
6895
/* Add user to group Web Service end */
6896
6897
/* Update user role in group Web Service start */
6898
// Register the data structures used by the service
6899
6900
// Input params for WSUpdateUserRoleInGroup
6901
$server->wsdl->addComplexType(
6902
    'updateUserRoleInGroup',
6903
    'complexType',
6904
    'struct',
6905
    'all',
6906
    '',
6907
    [
6908
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6909
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
6910
        'group_id' => ['name' => 'group_id', 'type' => 'xsd:string'],
6911
        'relation_type' => ['name' => 'relation_type', 'type' => 'xsd:string']
6912
    ]
6913
);
6914
6915
// Register the method to expose
6916
$server->register(
6917
    'WSUpdateUserRoleInGroup', // method name
6918
    ['updateUserRoleInGroup' => 'tns:updateUserRoleInGroup'], // input parameters
6919
    ['return' => 'xsd:string'], // output parameters
6920
    'urn:WSRegistration', // namespace
6921
    'urn:WSRegistration#WSUpdateUserRoleInGroup', // soapaction
6922
    'rpc', // style
6923
    'encoded', // use
6924
    'This service updates a user role in group'                     // documentation
6925
);
6926
6927
// Define the method WSUpdateUserRoleInGroup
6928
function WSUpdateUserRoleInGroup($params)
6929
{
6930
    if (!WSHelperVerifyKey($params['secret_key'])) {
6931
        return returnError(WS_ERROR_SECRET_KEY);
6932
    }
6933
    $userGroup = new UserGroup();
6934
6935
    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...
6936
        $params['user_id'],
6937
        $params['group_id'],
6938
        $params['relation_type']
6939
    );
6940
}
6941
6942
/* Update user role Web Service end */
6943
6944
/* Delete user from group Web Service start */
6945
// Register the data structures used by the service
6946
6947
// Input params for WSDeleteUserFromGroup
6948
$server->wsdl->addComplexType(
6949
    'deleteUserFromGroup',
6950
    'complexType',
6951
    'struct',
6952
    'all',
6953
    '',
6954
    [
6955
        'secret_key'   => ['name' => 'secret_key', 'type' => 'xsd:string'],
6956
        'user_id' => ['name' => 'user_id', 'type' => 'xsd:string'],
6957
        'group_id' => ['name' => 'group_id', 'type' => 'xsd:string']
6958
    ]
6959
);
6960
6961
// Register the method to expose
6962
$server->register(
6963
    'WSDeleteUserFromGroup', // method name
6964
    ['deleteUserFromGroup' => 'tns:deleteUserFromGroup'], // input parameters
6965
    ['return' => 'xsd:string'], // output parameters
6966
    'urn:WSRegistration', // namespace
6967
    'urn:WSRegistration#WSDeleteUserFromGroup', // soapaction
6968
    'rpc', // style
6969
    'encoded', // use
6970
    'This service deletes a user from a group'                  // documentation
6971
);
6972
6973
// Define the method WSDeleteUserFromGroup
6974
function WSDeleteUserFromGroup($params)
6975
{
6976
    if (!WSHelperVerifyKey($params['secret_key'])) {
6977
        return returnError(WS_ERROR_SECRET_KEY);
6978
    }
6979
    $userGroup = new UserGroup();
6980
6981
    return $userGroup->delete_user_rel_group(
6982
        $params['user_id'],
6983
        $params['group_id']
6984
    );
6985
}
6986
6987
/* Delete user from group Web Service end */
6988
6989
/** WSRegisterUserVisibilityToCourseCatalogue **/
6990
// Register the data structures used by the service
6991
6992
$server->wsdl->addComplexType(
6993
    'user_course_visibility',
6994
    'complexType',
6995
    'struct',
6996
    'all',
6997
    '',
6998
    [
6999
        'course_id' => ['name' => 'course_id', 'type' => 'tns:course_id'],
7000
        'user_id' => ['name' => 'user_id', 'type' => 'tns:user_id'],
7001
        'visible' => ['name' => 'status', 'type' => 'xsd:int'],
7002
    ]
7003
);
7004
7005
$server->wsdl->addComplexType(
7006
    'user_course_visibility_array',
7007
    'complexType',
7008
    'array',
7009
    '',
7010
    'SOAP-ENC:Array',
7011
    [],
7012
    [
7013
        ['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:user_course_visibility[]']
7014
    ],
7015
    'tns:user_course_visibility'
7016
);
7017
7018
$server->wsdl->addComplexType(
7019
    'registerUserToCourseCatalogue_arg',
7020
    'complexType',
7021
    'struct',
7022
    'all',
7023
    '',
7024
    [
7025
        'userscourses' => ['name' => 'userscourses', 'type' => 'tns:user_course_visibility_array'],
7026
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
7027
    ]
7028
);
7029
7030
$server->wsdl->addComplexType(
7031
    'registerUserToCourseCatalogue_return',
7032
    'complexType',
7033
    'struct',
7034
    'all',
7035
    '',
7036
    [
7037
        'original_user_id_value' => ['name' => 'original_user_id_value', 'type' => 'xsd:string'],
7038
        'original_course_id_value' => ['name' => 'original_course_id_value', 'type' => 'xsd:string'],
7039
        'visible' => ['name' => 'visible', 'type' => 'xsd:int'],
7040
        'result' => ['name' => 'result', 'type' => 'xsd:int'],
7041
    ]
7042
);
7043
7044
$server->wsdl->addComplexType(
7045
    'registerUserToCourseCatalogue_return_global',
7046
    'complexType',
7047
    'array',
7048
    '',
7049
    'SOAP-ENC:Array',
7050
    [],
7051
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:registerUserToCourseCatalogue_return[]']],
7052
    'tns:registerUserToCourseCatalogue_return'
7053
);
7054
7055
// Register the method to expose
7056
$server->register(
7057
    'WSAddUserVisibilityToCourseInCatalogue', // method name
7058
    ['registerUserToCourseCatalogue' => 'tns:registerUserToCourseCatalogue_arg'], // input parameters
7059
    ['return' => 'tns:registerUserToCourseCatalogue_return_global'],
7060
    'urn:WSRegistration', // namespace
7061
    'urn:WSRegistration#WSRegisterUserVisibilityToCourseCatalogue', // soapaction
7062
    'rpc', // style
7063
    'encoded', // use
7064
    'This service registers the visibility of users to course in catalogue' // documentation
7065
);
7066
7067
// define the method WSRegisterUserVisibilityToCourseInCatalogue
7068
function WSAddUserVisibilityToCourseInCatalogue($params)
7069
{
7070
    global $debug;
7071
    if (!WSHelperVerifyKey($params)) {
7072
        return returnError(WS_ERROR_SECRET_KEY);
7073
    }
7074
    if ($debug) {
7075
        error_log('WSAddUserVisibilityToCourseCatalogue params: '.print_r($params, 1));
7076
    }
7077
7078
    $results = [];
7079
    $userscourses = $params['userscourses'];
7080
    foreach ($userscourses as $usercourse) {
7081
        $original_course_id = $usercourse['course_id'];
7082
        $original_user_id   = $usercourse['user_id'];
7083
        $visible = $usercourse['visible'];
7084
7085
        $resultValue = 0;
7086
7087
        // Get user id
7088
        $userId = UserManager::get_user_id_from_original_id(
7089
            $original_user_id['original_user_id_value'],
7090
            $original_user_id['original_user_id_name']
7091
        );
7092
        if ($debug) {
7093
            error_log('WSAddUserVisibilityToCourseCatalogue userId: '.$userId);
7094
        }
7095
7096
        if ($userId == 0) {
7097
            // If user was not found, there was a problem
7098
            $resultValue = 0;
7099
        } else {
7100
            // User was found
7101
            $courseInfo = CourseManager::getCourseInfoFromOriginalId(
7102
                $original_course_id['original_course_id_value'],
7103
                $original_course_id['original_course_id_name']
7104
            );
7105
7106
            $courseCode = $courseInfo['code'];
7107
            if (empty($courseCode)) {
7108
                // Course was not found
7109
                $resultValue = 0;
7110
            } else {
7111
                if ($debug) {
7112
                    error_log('WSAddUserVisibilityToCourseCatalogue courseCode: '.$courseCode);
7113
                }
7114
                $result = CourseManager::addUserVisibilityToCourseInCatalogue($userId, $courseCode, $visible);
7115
                if ($result) {
7116
                    $resultValue = 1;
7117
                    if ($debug) {
7118
                        error_log('WSAddUserVisibilityToCourseCatalogue registered');
7119
                    }
7120
                } else {
7121
                    if ($debug) {
7122
                        error_log('WSAddUserVisibilityToCourseCatalogue NOT registered: ');
7123
                    }
7124
                }
7125
            }
7126
        }
7127
7128
        $results[] = [
7129
            'original_user_id_value' => $original_user_id['original_user_id_value'],
7130
            'original_course_id_value' => $original_course_id['original_course_id_value'],
7131
            'visible' => $visible,
7132
            'result' => $resultValue
7133
        ];
7134
    }
7135
7136
    return $results;
7137
}
7138
7139
// Register the method to expose
7140
$server->register(
7141
    'WSRemoveUserVisibilityToCourseInCatalogue', // method name
7142
    ['registerUserToCourseCatalogue' => 'tns:registerUserToCourseCatalogue_arg'], // input parameters
7143
    ['return' => 'tns:registerUserToCourseCatalogue_return_global'],
7144
    'urn:WSRegistration', // namespace
7145
    'urn:WSRegistration#WSRegisterUserVisibilityToCourseCatalogue', // soapaction
7146
    'rpc', // style
7147
    'encoded', // use
7148
    'This service removes the visibility of users to course in catalogue' // documentation
7149
);
7150
7151
// define the method WSRemoveUserVisibilityToCourseInCatalogue
7152
function WSRemoveUserVisibilityToCourseInCatalogue($params)
7153
{
7154
    global $debug;
7155
    if (!WSHelperVerifyKey($params)) {
7156
        return returnError(WS_ERROR_SECRET_KEY);
7157
    }
7158
    if ($debug) {
7159
        error_log('WSRemoveUserVisibilityToCourseInCatalogue params: '.print_r($params, 1));
7160
    }
7161
7162
    $results = [];
7163
    $userscourses = $params['userscourses'];
7164
    foreach ($userscourses as $usercourse) {
7165
        $original_course_id = $usercourse['course_id'];
7166
        $original_user_id   = $usercourse['user_id'];
7167
        $visible = $usercourse['visible'];
7168
7169
        $resultValue = 0;
7170
7171
        // Get user id
7172
        $userId = UserManager::get_user_id_from_original_id(
7173
            $original_user_id['original_user_id_value'],
7174
            $original_user_id['original_user_id_name']
7175
        );
7176
        if ($debug) {
7177
            error_log('WSRemoveUserVisibilityToCourseInCatalogue user_id: '.$userId);
7178
        }
7179
7180
        if ($userId == 0) {
7181
            // If user was not found, there was a problem
7182
            $resultValue = 0;
7183
        } else {
7184
            // User was found
7185
            $courseInfo = CourseManager::getCourseInfoFromOriginalId(
7186
                $original_course_id['original_course_id_value'],
7187
                $original_course_id['original_course_id_name']
7188
            );
7189
7190
            $courseCode = $courseInfo['code'];
7191
            if (empty($courseCode)) {
7192
                // Course was not found
7193
                $resultValue = 0;
7194
            } else {
7195
                if ($debug) {
7196
                    error_log('WSRemoveUserVisibilityToCourseInCatalogue courseCode: '.$courseCode);
7197
                }
7198
                $result = CourseManager::removeUserVisibilityToCourseInCatalogue($userId, $courseCode, $visible);
7199
                if ($result) {
7200
                    $resultValue = 1;
7201
                    if ($debug) {
7202
                        error_log('WSRemoveUserVisibilityToCourseInCatalogue removed');
7203
                    }
7204
                } else {
7205
                    if ($debug) {
7206
                        error_log('WSRemoveUserVisibilityToCourseInCatalogue NOT removed: ');
7207
                    }
7208
                }
7209
            }
7210
        }
7211
7212
        $results[] = [
7213
            'original_user_id_value' => $original_user_id['original_user_id_value'],
7214
            'original_course_id_value' => $original_course_id['original_course_id_value'],
7215
            'visible' => $visible,
7216
            'result' => $resultValue
7217
        ];
7218
    }
7219
7220
    return $results;
7221
}
7222
7223
// Add more webservices through hooks from plugins
7224
if (!empty($hook)) {
7225
    $hook->setEventData(['server' => $server]);
7226
    $res = $hook->notifyWSRegistration(HOOK_EVENT_TYPE_POST);
7227
    if (!empty($res['server'])) {
7228
        $server = $res['server'];
7229
    }
7230
}
7231
7232
// Use the request to (try to) invoke the service
7233
$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents('php://input');
7234
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
7235
7236
// If you send your data in utf8 then this value must be false.
7237
$decodeUTF8 = api_get_setting('registration.soap.php.decode_utf8');
7238
if ($decodeUTF8 === 'true') {
7239
    $server->decode_utf8 = true;
7240
} else {
7241
    $server->decode_utf8 = false;
7242
}
7243
$server->service($HTTP_RAW_POST_DATA);
7244