Completed
Push — master ( 9b8b24...6e1754 )
by Julito
58:58
created

WSEditUser()   F

Complexity

Conditions 19
Paths 4105

Size

Total Lines 131
Code Lines 87

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 87
nc 4105
nop 1
dl 0
loc 131
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(array('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
    array(
148
        'field_name'  => array('name' => 'field_name', 'type' => 'xsd:string'),
149
        'field_value' => array('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
    array(),
160
    array(array('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
    array(
171
        'firstname' => array('name' => 'firstname', 'type' => 'xsd:string'),
172
        'lastname' => array('name' => 'lastname', 'type' => 'xsd:string'),
173
        'status' => array('name' => 'status', 'type' => 'xsd:string'),
174
        'email' => array('name' => 'email', 'type' => 'xsd:string'),
175
        'loginname' => array('name' => 'loginname', 'type' => 'xsd:string'),
176
        'password' => array('name' => 'password', 'type' => 'xsd:string'),
177
        'language' => array('name' => 'language', 'type' => 'xsd:string'),
178
        'phone' => array('name' => 'phone', 'type' => 'xsd:string'),
179
        'expiration_date' => array('name' => 'expiration_date', 'type' => 'xsd:string'),
180
        'original_user_id_name' => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
181
        'original_user_id_value' => array('name' => 'original_user_id_value', 'type' => 'xsd:string'),
182
        'extra' => array('name' => 'extra', 'type' => 'tns:extrasList')
183
    )
184
);
185
186
$server->wsdl->addComplexType(
187
    'usersParamsList',
188
    'complexType',
189
    'array',
190
    '',
191
    'SOAP-ENC:Array',
192
    array(),
193
    array(array('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
    array(
204
        'users' => array('name' => 'users', 'type' => 'tns:usersParamsList'),
205
        'secret_key' => array('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
    array(
217
        'original_user_id_value' => array(
218
            'name' => 'original_user_id_value',
219
            'type' => 'xsd:string',
220
        ),
221
        'result' => array('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
    array(),
232
    array(
233
        array(
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
    array('createUsers' => 'tns:createUsers'), // input parameters
245
    array('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 = array();
263
    $orig_user_id_value = array();
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
434
    } // end principal foreach
435
436
    $count_results = count($results);
437
    $output = array();
438
    for ($i = 0; $i < $count_results; $i++) {
439
        $output[] = array(
440
            'original_user_id_value' => $orig_user_id_value[$i],
441
            'result' => $results[$i]
442
        );
443
    }
444
445
    return $output;
446
}
447
448
/* Register WSCreateUser function */
449
// Register the data structures used by the service
450
$server->wsdl->addComplexType(
451
    'createUser',
452
    'complexType',
453
    'struct',
454
    'all',
455
    '',
456
    array(
457
        'firstname' => array('name' => 'firstname', 'type' => 'xsd:string'),
458
        'lastname' => array('name' => 'lastname', 'type' => 'xsd:string'),
459
        'status' => array('name' => 'status', 'type' => 'xsd:string'),
460
        'email' => array('name' => 'email', 'type' => 'xsd:string'),
461
        'loginname' => array('name' => 'loginname', 'type' => 'xsd:string'),
462
        'password' => array('name' => 'password', 'type' => 'xsd:string'),
463
        'language' => array('name' => 'language', 'type' => 'xsd:string'),
464
        'phone' => array('name' => 'phone', 'type' => 'xsd:string'),
465
        'expiration_date' => array('name' => 'expiration_date', 'type' => 'xsd:string'),
466
        'original_user_id_name' => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
467
        'original_user_id_value' => array('name' => 'original_user_id_value', 'type' => 'xsd:string'),
468
        'extra' => array('name' => 'extra', 'type' => 'tns:extrasList'),
469
        'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
470
        'active' => array('name' => 'extra', 'type' => 'xsd:string')
471
    )
472
);
473
474
// Register the method to expose
475
$server->register(
476
    'WSCreateUser', // method name
477
    array('createUser' => 'tns:createUser'), // input parameters
478
    array('return' => 'xsd:string'), // output parameters
479
    'urn:WSRegistration', // namespace
480
    'urn:WSRegistration#WSCreateUser', // soapaction
481
    'rpc', // style
482
    'encoded', // use
483
    'This service adds a user'                   // documentation
484
);
485
486
// Define the method WSCreateUser
487
function WSCreateUser($params)
488
{
489
    global $debug;
490
491
    if (!WSHelperVerifyKey($params)) {
492
        return returnError(WS_ERROR_SECRET_KEY);
493
    }
494
495
    $firstName = $params['firstname'];
496
    $lastName = $params['lastname'];
497
    $status = $params['status'];
498
    $email = $params['email'];
499
    $loginName = $params['loginname'];
500
    $password = $params['password'];
501
    $official_code = '';
502
    $language = '';
503
    $phone = '';
504
    $picture_uri = '';
505
    $auth_source = PLATFORM_AUTH_SOURCE;
506
    $expiration_date = null;
507
    $active = !isset($params['active']) || !intval($params['active']) ? 0 : 1;
508
    $hr_dept_id = 0;
509
    $extra = null;
510
    $original_user_id_name = $params['original_user_id_name'];
511
    $original_user_id_value = $params['original_user_id_value'];
512
    $extra_list = $params['extra'];
513
    if (!empty($params['language'])) {
514
        $language = $params['language'];
515
    }
516
    if (!empty($params['phone'])) {
517
        $phone = $params['phone'];
518
    }
519
    if (!empty($params['expiration_date'])) {
520
        $expiration_date = $params['expiration_date'];
521
    }
522
523
    // check if exits x_user_id into user_field_values table
524
    $user_id = UserManager::get_user_id_from_original_id(
525
        $original_user_id_value,
526
        $original_user_id_name
527
    );
528
529
    $userManager = UserManager::getManager();
530
    $userRepository = UserManager::getRepository();
531
532
    if ($user_id > 0) {
533
        /** @var User $user */
534
        $user = $userRepository->find($user_id);
535
        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...
536
            if (!is_null($password)) {
537
                $user->setPlainPassword($password);
538
            }
539
            if (!is_null($auth_source)) {
540
                $user->setAuthSource($auth_source);
541
            }
542
543
            if (!empty($params['expiration_date'])) {
544
                $expiration_date = new DateTime($params['expiration_date']);
545
                $user->setExpirationDate($expiration_date);
546
            }
547
548
            $user->setLastname($lastName)
549
                ->setFirstname($firstName)
550
                ->setUsername($loginName)
551
                ->setEmail($email)
552
                ->setStatus($status)
553
                ->setOfficialCode($official_code)
554
                ->setPhone($phone)
555
                ->setHrDeptId($hr_dept_id)
556
                ->setActive(true);
557
            $userManager->updateUser($user, true);
558
559
            return $user_id;
560
        } else {
561
            return 0;
562
        }
563
    }
564
565
    // Default language
566
    if (empty($language)) {
567
        $language = api_get_setting('platformLanguage');
568
    }
569
570
    $creatorId = DEFAULT_ADMIN_USER_ID;
571
572
    // First check wether the login already exists
573
    if (!UserManager::is_username_available($loginName)) {
574
        if ($debug) error_log("Username $loginName is not available");
575
        return 0;
576
    }
577
578
    if (isset($original_user_id_name) && isset($original_user_id_value)) {
579
        $_SESSION['ws_'.$original_user_id_name] = $original_user_id_value;
580
    }
581
582
    /** @var User $user */
583
    $userId = UserManager::create_user(
584
        $firstName,
585
        $lastName,
586
        $status,
587
        $email,
588
        $loginName,
589
        $password,
590
        $official_code,
591
        $language,
592
        $phone,
593
        $picture_uri,
594
        $auth_source,
595
        $expiration_date,
596
        $active,
597
        $hr_dept_id,
598
        [],
599
        '',
600
        false,
601
        false,
602
        '',
603
        false,
604
        null,
605
        $creatorId
606
    );
607
608
    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...
609
        if (api_is_multiple_url_enabled()) {
610
            if (api_get_current_access_url_id() != -1) {
611
                UrlManager::add_user_to_url($userId, api_get_current_access_url_id());
612
            } else {
613
                UrlManager::add_user_to_url($userId, 1);
614
            }
615
        } else {
616
            // We add by default the access_url_user table with access_url_id = 1
617
            UrlManager::add_user_to_url($userId, 1);
618
        }
619
620
        // Save new fieldlabel into user_field table.
621
        UserManager::create_extra_field(
622
            $original_user_id_name,
623
            1,
624
            $original_user_id_name,
625
            ''
626
        );
627
        // Save the external system's id into user_field_value table.
628
        UserManager::update_extra_field_value(
629
            $userId,
630
            $original_user_id_name,
631
            $original_user_id_value
632
        );
633
634
        if (isset($original_user_id_name) && isset($original_user_id_value)) {
635
            unset($_SESSION['ws_'.$original_user_id_name]);
636
        }
637
638
        if (is_array($extra_list) && count($extra_list) > 0) {
639
            foreach ($extra_list as $extra) {
640
                $extra_field_name = $extra['field_name'];
641
                $extra_field_value = $extra['field_value'];
642
                // Save new field label into user_field table.
643
                UserManager::create_extra_field(
644
                    $extra_field_name,
645
                    1,
646
                    $extra_field_name,
647
                    ''
648
                );
649
                // Save the external system's id into user_field_value table.
650
                UserManager::update_extra_field_value(
651
                    $userId,
652
                    $extra_field_name,
653
                    $extra_field_value
654
                );
655
            }
656
        }
657
    } else {
658
        return 0;
659
    }
660
661
    return  $userId;
662
}
663
664
/* Register WSCreateUsersPasswordCrypted function */
665
// Register the data structures used by the service
666
// Prepare input params.
667
668
// Input params for editing users
669
$server->wsdl->addComplexType(
670
    'createUsersPassEncryptParams',
671
    'complexType',
672
    'struct',
673
    'all',
674
    '',
675
    array(
676
        'firstname' => array('name' => 'firstname', 'type' => 'xsd:string'),
677
        'lastname' => array('name' => 'lastname', 'type' => 'xsd:string'),
678
        'status' => array('name' => 'status', 'type' => 'xsd:string'),
679
        'email' => array('name' => 'email', 'type' => 'xsd:string'),
680
        'loginname' => array('name' => 'loginname', 'type' => 'xsd:string'),
681
        'password' => array('name' => 'password', 'type' => 'xsd:string'),
682
        'encrypt_method' => array('name' => 'encrypt_method', 'type' => 'xsd:string'),
683
        'language' => array('name' => 'language', 'type' => 'xsd:string'),
684
        'phone' => array('name' => 'phone', 'type' => 'xsd:string'),
685
        'expiration_date' => array('name' => 'expiration_date', 'type' => 'xsd:string'),
686
        'official_code' => array('name' => 'official_code', 'type' => 'xsd:string'),
687
        'original_user_id_name' => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
688
        'original_user_id_value'=> array('name' => 'original_user_id_value', 'type' => 'xsd:string'),
689
        'extra' => array('name' => 'extra', 'type' => 'tns:extrasList')
690
    )
691
);
692
693
$server->wsdl->addComplexType(
694
    'createUsersPassEncryptParamsList',
695
    'complexType',
696
    'array',
697
    '',
698
    'SOAP-ENC:Array',
699
    array(),
700
    array(
701
        array(
702
            'ref' => 'SOAP-ENC:arrayType',
703
            'wsdl:arrayType' => 'tns:createUsersPassEncryptParams[]'
704
        )
705
    ),
706
    'tns:createUsersPassEncryptParams'
707
);
708
709
// Register the data structures used by the service
710
$server->wsdl->addComplexType(
711
    'createUsersPasswordCrypted',
712
    'complexType',
713
    'struct',
714
    'all',
715
    '',
716
    array(
717
        'users' => array(
718
            'name' => 'users',
719
            'type' => 'tns:createUsersPassEncryptParamsList'
720
        ),
721
        'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string')
722
    )
723
);
724
725
// Prepare output params, in this case will return an array
726
$server->wsdl->addComplexType(
727
    'result_createUsersPassEncrypt',
728
    'complexType',
729
    'struct',
730
    'all',
731
    '',
732
    array(
733
        'original_user_id_value' => array(
734
            'name' => 'original_user_id_value',
735
            'type' => 'xsd:string'
736
        ),
737
        'result' => array('name' => 'result', 'type' => 'xsd:string')
738
    )
739
);
740
741
$server->wsdl->addComplexType(
742
    'results_createUsersPassEncrypt',
743
    'complexType',
744
    'array',
745
    '',
746
    'SOAP-ENC:Array',
747
    array(),
748
    array(
749
        array(
750
            'ref' => 'SOAP-ENC:arrayType',
751
            'wsdl:arrayType' => 'tns:result_createUsersPassEncrypt[]'
752
        )
753
    ),
754
    'tns:result_createUsersPassEncrypt'
755
);
756
757
// Register the method to expose
758
$server->register(
759
    'WSCreateUsersPasswordCrypted', // method name
760
    array('createUsersPasswordCrypted' => 'tns:createUsersPasswordCrypted'), // input parameters
761
    array('return' => 'tns:results_createUsersPassEncrypt'), // output parameters
762
    'urn:WSRegistration', // namespace
763
    'urn:WSRegistration#WSCreateUsersPasswordCrypted', // soapaction
764
    'rpc', // style
765
    'encoded', // use
766
    'This service adds users to the system'                                  // documentation
767
);
768
769
// Define the method WSCreateUsersPasswordCrypted
770
function WSCreateUsersPasswordCrypted($params)
771
{
772
    global $_configuration;
773
    if (!WSHelperVerifyKey($params)) {
774
        return returnError(WS_ERROR_SECRET_KEY);
775
    }
776
777
    // database table definition
778
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
779
    $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
780
    $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
781
782
    $users_params = $params['users'];
783
    $results = array();
784
    $orig_user_id_value = array();
785
786
    foreach ($users_params as $user_param) {
787
        $password = $user_param['password'];
788
        $encrypt_method = $user_param['encrypt_method'];
789
        $firstName = $user_param['firstname'];
790
        $lastName = $user_param['lastname'];
791
        $status = $user_param['status'];
792
        $email = $user_param['email'];
793
        $loginName = $user_param['loginname'];
794
        $official_code = $user_param['official_code'];
795
        $language = '';
796
        $phone = '';
797
        $picture_uri = '';
798
        $auth_source = PLATFORM_AUTH_SOURCE;
799
        $expiration_date = '';
800
        $active = 1;
801
        $hr_dept_id = 0;
802
        $extra = null;
803
        $original_user_id_name = $user_param['original_user_id_name'];
804
        $original_user_id_value = $user_param['original_user_id_value'];
805
        $orig_user_id_value[] = $user_param['original_user_id_value'];
806
        $extra_list = $user_param['extra'];
807
        $salt = '';
808
809
        if (!empty($_configuration['password_encryption'])) {
810
            if ($_configuration['password_encryption'] === $encrypt_method) {
811
                if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
812
                    $msg = "Encryption $encrypt_method is invalid";
813
                    $results[] = $msg;
814
                    continue;
815
                } else if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
816
                    $msg = "Encryption $encrypt_method is invalid";
817
                    $results[] = $msg;
818
                    continue;
819
                }
820
            } else {
821
                $msg = "This encryption $encrypt_method is not configured";
822
                $results[] = $msg;
823
                continue;
824
            }
825
        } else {
826
            $msg = 'The chamilo setting $_configuration["password_encryption"] is not configured';
827
            $results[] = $msg;
828
            continue;
829
        }
830
831
        if (is_array($extra_list) && count($extra_list) > 0) {
832
            foreach ($extra_list as $extra) {
833
                if ($extra['field_name'] == 'salt') {
834
                    $salt = $extra['field_value'];
835
                    break;
836
                }
837
            }
838
        }
839
840
        if (!empty($user_param['language'])) {
841
            $language = $user_param['language'];
842
        }
843
        if (!empty($user_param['phone'])) {
844
            $phone = $user_param['phone'];
845
        }
846
        if (!empty($user_param['expiration_date'])) {
847
            $expiration_date = $user_param['expiration_date'];
848
        }
849
850
        $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
851
852
        // Check whether x_user_id exists into user_field_values table.
853
        $sql = "SELECT value as field_value,item_id as user_id
854
                FROM $t_uf uf, $t_ufv ufv
855
                WHERE
856
                    uf.extra_field_type = $extraFieldType
857
                    ufv.field_id=uf.id AND
858
                    variable='$original_user_id_name' AND
859
                    value ='$original_user_id_value'";
860
        $res = Database::query($sql);
861
        $row = Database::fetch_row($res);
862
        $count_row = Database::num_rows($res);
863
        if ($count_row > 0) {
864
            // Check if user is not active.
865
            $sql = "SELECT user_id FROM $table_user 
866
                    WHERE user_id ='".$row[1]."' AND active= '0'";
867
            $resu = Database::query($sql);
868
            $r_check_user = Database::fetch_row($resu);
869
            $count_check_user = Database::num_rows($resu);
870
            if ($count_check_user > 0) {
871
                $sql = "UPDATE $table_user SET
872
                        lastname='".Database::escape_string($lastName)."',
873
                        firstname='".Database::escape_string($firstName)."',
874
                        username='".Database::escape_string($loginName)."',";
875
876
                if (!is_null($auth_source)) {
877
                    $sql .= " auth_source='".Database::escape_string($auth_source)."',";
878
                }
879
                $sql .= "
880
                        password='".Database::escape_string($password)."',
881
                        email='".Database::escape_string($email)."',
882
                        status='".Database::escape_string($status)."',
883
                        official_code='".Database::escape_string($official_code)."',
884
                        phone='".Database::escape_string($phone)."',
885
                        expiration_date='".Database::escape_string($expiration_date)."',
886
                        active='1',
887
                        hr_dept_id=".intval($hr_dept_id);
888
889
                $sql .= " WHERE user_id='".$r_check_user[0]."'";
890
                Database::query($sql);
891
892
                if (is_array($extra_list) && count($extra_list) > 0) {
893
                    foreach ($extra_list as $extra) {
894
                        $extra_field_name = $extra['field_name'];
895
                        $extra_field_value = $extra['field_value'];
896
                        // Save the external system's id into user_field_value table.
897
                        $res = UserManager::update_extra_field_value(
898
                            $r_check_user[0],
899
                            $extra_field_name,
900
                            $extra_field_value
901
                        );
902
                    }
903
                }
904
905
                $results[] = $r_check_user[0];
906
                continue;
907
            } else {
908
                $results[] = 0;
909
                continue; // User id already exits.
910
            }
911
        }
912
913
        // Default language.
914
        if (empty($language)) {
915
            $language = api_get_setting('platformLanguage');
916
        }
917
918
        $creator_id = DEFAULT_ADMIN_USER_ID;
919
920
        // First check wether the login already exists
921
        if (!UserManager::is_username_available($loginName)) {
922
            $results[] = 0;
923
            continue;
924
        }
925
926
        $sql = "INSERT INTO $table_user SET
927
                    lastname = '".Database::escape_string(trim($lastName))."',
928
                    firstname = '".Database::escape_string(trim($firstName))."',
929
                    username = '".Database::escape_string(trim($loginName))."',
930
                    status = '".Database::escape_string($status)."',
931
                    password = '".Database::escape_string($password)."',
932
                    email = '".Database::escape_string($email)."',
933
                    official_code    = '".Database::escape_string($official_code)."',
934
                    picture_uri     = '".Database::escape_string($picture_uri)."',
935
                    creator_id      = '".Database::escape_string($creator_id)."',
936
                    auth_source = '".Database::escape_string($auth_source)."',
937
                    phone = '".Database::escape_string($phone)."',
938
                    language = '".Database::escape_string($language)."',
939
                    registration_date = now(),
940
                    expiration_date = '".Database::escape_string($expiration_date)."',
941
                    hr_dept_id = '".Database::escape_string($hr_dept_id)."',
942
                    active = '".Database::escape_string($active)."'";
943
        $result = Database::query($sql);
944
        if ($result) {
945
            //echo "id returned";
946
            $return = Database::insert_id();
947
948
            $sql = "UPDATE $table_user SET user_id = id WHERE id = $return";
949
            Database::query($sql);
950
951
            if (api_is_multiple_url_enabled()) {
952
                if (api_get_current_access_url_id() != -1) {
953
                    UrlManager::add_user_to_url(
954
                        $return,
955
                        api_get_current_access_url_id()
956
                    );
957
                } else {
958
                    UrlManager::add_user_to_url($return, 1);
959
                }
960
            } else {
961
                // We add by default the access_url_user table with access_url_id = 1
962
                UrlManager::add_user_to_url($return, 1);
963
            }
964
            // Save new fieldlabel into user_field table.
965
            UserManager::create_extra_field(
966
                $original_user_id_name,
967
                1,
968
                $original_user_id_name,
969
                ''
970
            );
971
            // Save the remote system's id into user_field_value table.
972
            UserManager::update_extra_field_value(
973
                $return,
974
                $original_user_id_name,
975
                $original_user_id_value
976
            );
977
978
            if (is_array($extra_list) && count($extra_list) > 0) {
979
                foreach ($extra_list as $extra) {
980
                    $extra_field_name = $extra['field_name'];
981
                    $extra_field_value = $extra['field_value'];
982
                    // Save new fieldlabel into user_field table.
983
                    UserManager::create_extra_field(
984
                        $extra_field_name,
985
                        1,
986
                        $extra_field_name,
987
                        ''
988
                    );
989
                    // Save the external system's id into user_field_value table.
990
                    UserManager::update_extra_field_value(
991
                        $return,
992
                        $extra_field_name,
993
                        $extra_field_value
994
                    );
995
                }
996
            }
997
        } else {
998
            $results[] = 0;
999
            continue;
1000
        }
1001
        $results[] = $return;
1002
1003
    } // end principal foreach
1004
1005
    $count_results = count($results);
1006
    $output = array();
1007
    for ($i = 0; $i < $count_results; $i++) {
1008
        $output[] = array(
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
    array(
1026
        'user_id' => array('name' => 'course', 'type' => 'xsd:string'), // Chamilo user Id
1027
        'session_id' => array('name' => 'user_id', 'type' => 'xsd:string'), // Current Session course ID
1028
        'course_id' =>array('name' => 'courseId', 'type' => 'xsd:string'), // Course Real Id
1029
        'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
1030
        // optional
1031
        'original_user_id_name' => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
1032
        'original_user_id_value' => array('name' => 'original_user_id_value', 'type' => 'xsd:string'),
1033
        'original_course_id_name' => array('name' => 'original_course_id_name', 'type' => 'xsd:string'),
1034
        'original_course_id_value' => array('name' => 'original_course_id_value', 'type' => 'xsd:string'),
1035
        'original_session_id_name' => array('name' => 'original_session_id_name', 'type' => 'xsd:string'),
1036
        'original_session_id_value' => array('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
    array('SubscribeTeacherToSessionCourse' => 'tns:TeacherToSessionCourse'),
1104
    array('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) error_log('WSSubscribeTeacherToSessionCourse');
1122
1123
    if (!WSHelperVerifyKey($params)) {
1124
        return returnError(WS_ERROR_SECRET_KEY);
1125
    }
1126
1127
    if ($debug) error_log('Params '.print_r($params, 1));
1128
1129
    $params = parseCourseSessionUserParams($params);
1130
1131
    $userId = $params['user_id'];
1132
    $courseId = $params['course_id'];
1133
    $sessionId = $params['session_id'];
1134
    SessionManager::set_coach_to_course_session($userId, $sessionId, $courseId);
1135
    $coaches = SessionManager::getCoachesByCourseSession($sessionId, $courseId);
1136
1137
    $result = 0;
1138
1139
    if (!empty($coaches)) {
1140
        if ($debug) error_log('Coaches:  '.print_r($coaches, 1));
1141
        if (in_array($userId, $coaches)) {
1142
            $result = 1;
1143
        }
1144
    }
1145
1146
    if ($debug) error_log('Result:  '.$result);
1147
1148
    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...
1149
}
1150
1151
$server->register(
1152
    'WSUnsubscribeTeacherFromSessionCourse',
1153
    array('UnsubscribeTeacherFromSessionCourse' => 'tns:TeacherToSessionCourse'),
1154
    array('return' => 'xsd:string'),
1155
    'urn:WSRegistration',
1156
    'urn:WSRegistration#WSUnsubscribeTeacherFromSessionCourse',
1157
    'rpc',
1158
    'encoded',
1159
    'This webservice unsubscribe a teacher from a session course'
1160
);
1161
1162
/**
1163
 * Subscribe teacher to a session course
1164
 *
1165
 *  @param array $params - WSFunction parameters (include VerifyKey)
1166
 *  @return bool|null|soap_fault A simple boolean (true if teacher successful unsubscribed, false otherwise)
1167
 */
1168
function WSUnsubscribeTeacherFromSessionCourse($params)
1169
{
1170
    global $debug;
1171
1172
    if ($debug) error_log('WSSubscribeTeacherToSessionCourse');
1173
1174
    if (!WSHelperVerifyKey($params)) {
1175
        return returnError(WS_ERROR_SECRET_KEY);
1176
    }
1177
1178
    if ($debug) error_log('Params '.print_r($params, 1));
1179
1180
    $params = parseCourseSessionUserParams($params);
1181
1182
    $userId = $params['user_id'];
1183
    $courseId = $params['course_id'];
1184
    $sessionId = $params['session_id'];
1185
1186
    SessionManager::removeUsersFromCourseSession([$userId], $sessionId, $courseId);
1187
    $coaches = SessionManager::getCoachesByCourseSession($sessionId, $courseId);
1188
1189
    $result = 0;
1190
1191
    if (!empty($coaches)) {
1192
        if ($debug) error_log('Coaches:  '.print_r($coaches, 1));
1193
        if (!in_array($userId, $coaches)) {
1194
            $result = 1;
1195
        }
1196
    } else {
1197
        $result = 1;
1198
    }
1199
1200
    if ($debug) error_log('Final Result: '.$result);
1201
1202
    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...
1203
}
1204
1205
/* Register WSCreateUserPasswordCrypted function */
1206
// Register the data structures used by the service
1207
1208
//prepare input params
1209
1210
// Input params for editing users
1211
$server->wsdl->addComplexType(
1212
    'createUserPasswordCrypted',
1213
    'complexType',
1214
    'struct',
1215
    'all',
1216
    '',
1217
    array(
1218
        'firstname'                 => array('name' => 'firstname', 'type' => 'xsd:string'),
1219
        'lastname'                  => array('name' => 'lastname', 'type' => 'xsd:string'),
1220
        'status'                    => array('name' => 'status', 'type' => 'xsd:string'),
1221
        'email'                     => array('name' => 'email', 'type' => 'xsd:string'),
1222
        'loginname'                 => array('name' => 'loginname', 'type' => 'xsd:string'),
1223
        'password'                  => array('name' => 'password', 'type' => 'xsd:string'), //encripted password using the encrypt_method
1224
        'encrypt_method'            => array('name' => 'encrypt_method', 'type' => 'xsd:string'),
1225
        'language'                  => array('name' => 'language', 'type' => 'xsd:string'),
1226
        'phone'                     => array('name' => 'phone', 'type' => 'xsd:string'),
1227
        'expiration_date'           => array('name' => 'expiration_date', 'type' => 'xsd:string'),
1228
        'official_code'             => array('name' => 'official_code', 'type' => 'xsd:string'),
1229
        'original_user_id_name'     => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
1230
        'original_user_id_value'    => array('name' => 'original_user_id_value', 'type' => 'xsd:string'),
1231
        'extra'                     => array('name' => 'extra', 'type' => 'tns:extrasList'),
1232
        'secret_key'                => array('name' => 'secret_key', 'type' => 'xsd:string')
1233
    )
1234
);
1235
1236
// Register the method to expose
1237
$server->register(
1238
    'WSCreateUserPasswordCrypted', // method name
1239
    array('createUserPasswordCrypted' => 'tns:createUserPasswordCrypted'), // input parameters
1240
    array('return' => 'xsd:string'), // output parameters
1241
    'urn:WSRegistration', // namespace
1242
    'urn:WSRegistration#WSCreateUserPasswordCrypted', // soapaction
1243
    'rpc', // style
1244
    'encoded', // use
1245
    'This service adds users'                                               // documentation
1246
);
1247
1248
// Define the method WSCreateUserPasswordCrypted
1249
function WSCreateUserPasswordCrypted($params)
1250
{
1251
    global $_configuration, $debug;
1252
    $debug = 1;
1253
    if ($debug) error_log('WSCreateUserPasswordCrypted');
1254
    if ($debug) error_log(print_r($params, 1));
1255
1256
    if (!WSHelperVerifyKey($params)) {
1257
        return returnError(WS_ERROR_SECRET_KEY);
1258
    }
1259
1260
    // Database table definition.
1261
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1262
    $password = $params['password'];
1263
    $encrypt_method = $params['encrypt_method'];
1264
    $firstName = $params['firstname'];
1265
    $lastName = $params['lastname'];
1266
    $status = $params['status'];
1267
    $email = $params['email'];
1268
    $loginName = $params['loginname'];
1269
    $official_code = isset($params['official_code']) ? $params['official_code'] : '';
1270
    $language = '';
1271
    $phone = isset($params['phone']) ? $params['phone'] : '';
1272
    $picture_uri = '';
1273
    $auth_source = PLATFORM_AUTH_SOURCE;
1274
    $expiration_date = '';
1275
    $active = 1;
1276
    $hr_dept_id = 0;
1277
    $extra = null;
1278
    $original_user_id_name = $params['original_user_id_name'];
1279
    $original_user_id_value = $params['original_user_id_value'];
1280
    $extra_list = isset($params['extra']) ? $params['extra'] : '';
1281
1282
    if (!empty($_configuration['password_encryption'])) {
1283
        if ($_configuration['password_encryption'] === $encrypt_method) {
1284
            if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
1285
                $msg = "Encryption $encrypt_method is invalid";
1286
                if ($debug) error_log($msg);
1287
                return $msg;
1288
1289
            } elseif ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
1290
                $msg = "Encryption $encrypt_method is invalid";
1291
                if ($debug) error_log($msg);
1292
                return $msg;
1293
            }
1294
        } else {
1295
            $msg = "This encryption $encrypt_method is not configured";
1296
            if ($debug) error_log($msg);
1297
            return $msg;
1298
        }
1299
    } else {
1300
        $msg = 'The chamilo setting $_configuration["password_encryption"] is not configured';
1301
        if ($debug) error_log($msg);
1302
        return $msg;
1303
    }
1304
1305
    if (!empty($params['language'])) {
1306
        $language = $params['language'];
1307
    }
1308
    if (!empty($params['phone'])) {
1309
        $phone = $params['phone'];
1310
    }
1311
    if (!empty($params['expiration_date'])) {
1312
        $expiration_date = $params['expiration_date'];
1313
    }
1314
1315
    // Check whether x_user_id exists into user_field_values table.
1316
    $user_id = UserManager::get_user_id_from_original_id(
1317
        $original_user_id_value,
1318
        $original_user_id_name
1319
    );
1320
1321
    if ($debug) error_log('Ready to create user');
1322
1323
    if ($user_id > 0) {
1324
        if ($debug) error_log('User found with id: '.$user_id);
1325
1326
        // Check whether user is not active
1327
        //@todo why this condition exists??
1328
        $sql = "SELECT user_id FROM $table_user
1329
                WHERE user_id ='".$user_id."' AND active= '0' ";
1330
        $resu = Database::query($sql);
1331
        $r_check_user = Database::fetch_row($resu);
1332
        $count_check_user = Database::num_rows($resu);
1333
        if ($count_check_user > 0) {
1334
            if ($debug) error_log('User id: '.$user_id.' exists and is NOT active. Updating user and setting setting active = 1');
1335
            $sql = "UPDATE $table_user SET
1336
                    lastname='".Database::escape_string($lastName)."',
1337
                    firstname='".Database::escape_string($firstName)."',
1338
                    username='".Database::escape_string($loginName)."',";
1339
1340
            if (!is_null($auth_source)) {
1341
                $sql .= " auth_source='".Database::escape_string($auth_source)."',";
1342
            }
1343
            $sql .= "
1344
                    password='".Database::escape_string($password)."',
1345
                    email='".Database::escape_string($email)."',
1346
                    status='".Database::escape_string($status)."',
1347
                    official_code='".Database::escape_string($official_code)."',
1348
                    phone='".Database::escape_string($phone)."',
1349
                    expiration_date='".Database::escape_string($expiration_date)."',
1350
                    active='1',
1351
                    hr_dept_id=".intval($hr_dept_id)." 
1352
                WHERE user_id='".$r_check_user[0]."'";
1353
1354
            Database::query($sql);
1355
1356
            if (is_array($extra_list) && count($extra_list) > 0) {
1357
                foreach ($extra_list as $extra) {
1358
                    $extra_field_name = $extra['field_name'];
1359
                    $extra_field_value = $extra['field_value'];
1360
                    // Save the external system's id into user_field_value table.
1361
                    UserManager::update_extra_field_value(
1362
                        $r_check_user[0],
1363
                        $extra_field_name,
1364
                        $extra_field_value
1365
                    );
1366
                }
1367
            }
1368
            return $r_check_user[0];
1369
        } else {
1370
            if ($debug) error_log('User exists but is active. Cant be updated');
1371
            return 0;
1372
        }
1373
    } else {
1374
        if ($debug) error_log("User not found with original_id = $original_user_id_value and original_name = $original_user_id_name");
1375
    }
1376
1377
    // Default language.
1378
    if (empty($language)) {
1379
        $language = api_get_setting('platformLanguage');
1380
    }
1381
1382
    $creator_id = DEFAULT_ADMIN_USER_ID;
1383
1384
    // First check wether the login already exists
1385
    if (!UserManager::is_username_available($loginName)) {
1386
        if ($debug) error_log("Username $loginName is not available");
1387
        return 0;
1388
    }
1389
1390
    $queryExpirationDate = '';
1391
    if (!empty($params['expiration_date'])) $queryExpirationDate = "expiration_date     = '".Database::escape_string($expiration_date)."', ";
1392
1393
    $sql = "INSERT INTO $table_user SET
1394
            lastname            = '".Database::escape_string(trim($lastName))."',
1395
            firstname           = '".Database::escape_string(trim($firstName))."',
1396
            username            = '".Database::escape_string(trim($loginName))."',
1397
            username_canonical  = '".Database::escape_string(api_strtolower(trim($loginName)))."',
1398
            status              = '".Database::escape_string($status)."',
1399
            password            = '".Database::escape_string($password)."',
1400
            email               = '".Database::escape_string($email)."',
1401
            official_code       = '".Database::escape_string($official_code)."',
1402
            picture_uri         = '".Database::escape_string($picture_uri)."',
1403
            creator_id          = '".Database::escape_string($creator_id)."',
1404
            auth_source         = '".Database::escape_string($auth_source)."',
1405
            phone               = '".Database::escape_string($phone)."',
1406
            language            = '".Database::escape_string($language)."',
1407
            registration_date   = '".api_get_utc_datetime()."',
1408
            roles = 'a:0:{}', 
1409
            ".$queryExpirationDate."
1410
            hr_dept_id          = '".Database::escape_string($hr_dept_id)."',
1411
            active              = '".Database::escape_string($active)."'";
1412
1413
    Database::query($sql);
1414
    $return = Database::insert_id();
1415
    if ($return) {
1416
        $sql = "UPDATE $table_user SET user_id = id WHERE id = $return";
1417
        Database::query($sql);
1418
1419
        $url_id = api_get_current_access_url_id();
1420
        UrlManager::add_user_to_url($return, $url_id);
1421
        if ($debug) error_log("Adding user_id = $return to URL id $url_id ");
1422
1423
        // Create extra field for the original_user_id_name
1424
        UserManager::create_extra_field(
1425
            $original_user_id_name,
1426
            1,
1427
            $original_user_id_name,
1428
            ''
1429
        );
1430
        // Save the remote system's id into user_field_value table.
1431
        UserManager::update_extra_field_value(
1432
            $return,
1433
            $original_user_id_name,
1434
            $original_user_id_value
1435
        );
1436
1437
        // Create extra fields
1438
        if (is_array($extra_list) && count($extra_list) > 0) {
1439
            foreach ($extra_list as $extra) {
1440
                $extra_field_name   = $extra['field_name'];
1441
                $extra_field_value  = $extra['field_value'];
1442
                // save new fieldlabel into user_field table
1443
                UserManager::create_extra_field(
1444
                    $extra_field_name,
1445
                    1,
1446
                    $extra_field_name,
1447
                    ''
1448
                );
1449
                // save the external system's id into user_field_value table'
1450
                UserManager::update_extra_field_value(
1451
                    $return,
1452
                    $extra_field_name,
1453
                    $extra_field_value
1454
                );
1455
            }
1456
        }
1457
    } else {
1458
        if ($debug) error_log('Error while inserting a user');
1459
1460
        return 0;
1461
    }
1462
1463
    return $return;
1464
}
1465
1466
/* Register WSEditUsers function */
1467
// Register the data structures used by the service
1468
$server->wsdl->addComplexType(
1469
    'editUsersParams',
1470
    'complexType',
1471
    'struct',
1472
    'all',
1473
    '',
1474
    array(
1475
        'original_user_id_value' => array('name' => 'original_user_id_value', 'type' => 'xsd:string'),
1476
        'original_user_id_name' => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
1477
        'firstname' => array('name' => 'firstname', 'type' => 'xsd:string'),
1478
        'lastname' => array('name' => 'lastname', 'type' => 'xsd:string'),
1479
        'username' => array('name' => 'username', 'type' => 'xsd:string'),
1480
        'password' => array('name' => 'password', 'type' => 'xsd:string'),
1481
        'email' => array('name' => 'email', 'type' => 'xsd:string'),
1482
        'status' => array('name' => 'status', 'type' => 'xsd:string'),
1483
        'phone' => array('name' => 'phone', 'type' => 'xsd:string'),
1484
        'expiration_date' => array('name' => 'expiration_date', 'type' => 'xsd:string'),
1485
        'extra' => array('name' => 'extra', 'type' => 'tns:extrasList')
1486
    )
1487
);
1488
1489
$server->wsdl->addComplexType(
1490
    'editUsersParamsList',
1491
    'complexType',
1492
    'array',
1493
    '',
1494
    'SOAP-ENC:Array',
1495
    array(),
1496
    array(array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:editUsersParams[]')),
1497
    'tns:editUsersParams'
1498
);
1499
1500
$server->wsdl->addComplexType(
1501
    'editUsers',
1502
    'complexType',
1503
    'struct',
1504
    'all',
1505
    '',
1506
    array(
1507
        'users' => array('name' => 'users', 'type' => 'tns:editUsersParamsList'),
1508
        'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string')
1509
    )
1510
);
1511
1512
/* Register WSEditUserCredentials function */
1513
// Register the data structures used by the service
1514
$server->wsdl->addComplexType(
1515
    'editUserCredentials',
1516
    'complexType',
1517
    'struct',
1518
    'all',
1519
    '',
1520
    array(
1521
        'username' => array('name' => 'username', 'type' => 'xsd:string'),
1522
        'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
1523
        'password' => array('name' => 'password', 'type' => 'xsd:string'),
1524
        'original_user_id_name' => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
1525
        'original_user_id_value' => array('name' => 'original_user_id_value', 'type' => 'xsd:string')
1526
    )
1527
);
1528
1529
// Register the method to expose
1530
$server->register(
1531
    'WSEditUserCredentials', // method name
1532
    array('editUserCredentials' => 'tns:editUserCredentials'), // input parameters
1533
    array('return' => 'xsd:string'), // output parameters
1534
    'urn:WSRegistration', // namespace
1535
    'urn:WSRegistration#WSEditUserCredentials', // soapaction
1536
    'rpc', // style
1537
    'encoded', // use
1538
    'This service edits the username and password of a user'    // documentation
1539
);
1540
1541
/**
1542
 * Define the method WSEditUser
1543
 * @param array $params
1544
 * @return bool|int|null|soap_fault
1545
 * @throws \Doctrine\DBAL\DBALException
1546
 */
1547
function WSEditUserCredentials($params)
1548
{
1549
    if (!WSHelperVerifyKey($params)) {
1550
        return returnError(WS_ERROR_SECRET_KEY);
1551
    }
1552
1553
    $userManager = UserManager::getManager();
1554
    $userRepository = UserManager::getRepository();
1555
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1556
    $original_user_id_value = $params['original_user_id_value'];
1557
    $original_user_id_name = $params['original_user_id_name'];
1558
    $username = $params['username'];
1559
    $password = null;
1560
1561
    if (!empty($params['password'])) {
1562
        $password = $params['password'];
1563
    }
1564
1565
    // Get user id from the other system ID
1566
    $user_id = UserManager::get_user_id_from_original_id(
1567
        $original_user_id_value,
1568
        $original_user_id_name
1569
    );
1570
1571
    if ($user_id == 0) {
1572
        return 0;
1573
    } else {
1574
        $sql = "SELECT user_id FROM $table_user
1575
                WHERE user_id ='$user_id' AND active= '0'";
1576
        $resu = Database::query($sql);
1577
        $r_check_user = Database::fetch_row($resu);
1578
        if (!empty($r_check_user[0])) {
1579
            return 0;
1580
        }
1581
    }
1582
1583
    // Check whether username already exits.
1584
    $sql = "SELECT username FROM $table_user
1585
            WHERE username = '$username' AND user_id <> '$user_id'";
1586
    $res_un = Database::query($sql);
1587
    $r_username = Database::fetch_row($res_un);
1588
1589
    if (!empty($r_username[0])) {
1590
        return 0;
1591
    }
1592
1593
    /** @var User $user */
1594
    $user = $userRepository->find($user_id);
1595
    if ($user) {
1596
        $user->setUsername($username);
1597
        if (!is_null($password)) {
1598
            $user->setPlainPassword($password);
1599
        }
1600
1601
        $userManager->updateUser($user, true);
1602
1603
        return true;
1604
    }
1605
1606
    return false;
1607
}
1608
1609
// Prepare output params, in this case will return an array
1610
$server->wsdl->addComplexType(
1611
    'result_editUsers',
1612
    'complexType',
1613
    'struct',
1614
    'all',
1615
    '',
1616
    array(
1617
        'original_user_id_value' => array(
1618
            'name' => 'original_user_id_value',
1619
            'type' => 'xsd:string'
1620
        ),
1621
        'result' => array('name' => 'result', 'type' => 'xsd:string')
1622
    )
1623
);
1624
1625
$server->wsdl->addComplexType(
1626
    'results_editUsers',
1627
    'complexType',
1628
    'array',
1629
    '',
1630
    'SOAP-ENC:Array',
1631
    array(),
1632
    array(
1633
        array(
1634
            'ref' => 'SOAP-ENC:arrayType',
1635
            'wsdl:arrayType' => 'tns:result_editUsers[]'
1636
        )
1637
    ),
1638
    'tns:result_editUsers'
1639
);
1640
1641
// Register the method to expose
1642
$server->register(
1643
    'WSEditUsers', // method name
1644
    array('editUsers' => 'tns:editUsers'), // input parameters
1645
    array('return' => 'tns:results_editUsers'), // output parameters
1646
    'urn:WSRegistration', // namespace
1647
    'urn:WSRegistration#WSEditUsers', // soapaction
1648
    'rpc', // style
1649
    'encoded', // use
1650
    'This service edits a user from wiener'     // documentation
1651
);
1652
1653
// Define the method WSEditUsers
1654
function WSEditUsers($params)
1655
{
1656
    if (!WSHelperVerifyKey($params)) {
1657
        return returnError(WS_ERROR_SECRET_KEY);
1658
    }
1659
1660
    $userManager = UserManager::getManager();
1661
    $userRepository = UserManager::getRepository();
1662
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1663
1664
    $users_params = $params['users'];
1665
    $results = array();
1666
    $orig_user_id_value = array();
1667
1668
    foreach ($users_params as $user_param) {
1669
        $original_user_id_value = $user_param['original_user_id_value'];
1670
        $original_user_id_name = $user_param['original_user_id_name'];
1671
        $orig_user_id_value[] = $original_user_id_value;
1672
        $firstname = $user_param['firstname'];
1673
        $lastname = $user_param['lastname'];
1674
        $username = $user_param['username'];
1675
        $password = null;
1676
        $auth_source = null;
1677
        $email = $user_param['email'];
1678
        $status = $user_param['status'];
1679
        $official_code = '';
1680
        $phone = $user_param['phone'];
1681
        $expiration_date = $user_param['expiration_date'];
1682
        $creator_id = null;
1683
        $hr_dept_id = 0;
1684
        $extra = null;
1685
        $extra_list = $user_param['extra'];
1686
1687
        if (!empty($user_param['password'])) {
1688
            $password = $user_param['password'];
1689
        }
1690
1691
        // Get user id
1692
        $user_id = UserManager::get_user_id_from_original_id(
1693
            $original_user_id_value,
1694
            $original_user_id_name
1695
        );
1696
1697
        if ($user_id == 0) {
1698
            $results[] = 0; // Original_user_id_value doesn't exist.
1699
            continue;
1700
        } else {
1701
            $sql = "SELECT user_id FROM $table_user
1702
                    WHERE user_id ='$user_id' AND active= '0'";
1703
            $resu = Database::query($sql);
1704
            $r_check_user = Database::fetch_row($resu);
1705
            if (!empty($r_check_user[0])) {
1706
                $results[] = 0; // user_id is not active.
1707
                continue;
1708
            }
1709
        }
1710
1711
        // Check whether username already exits.
1712
        $sql = "SELECT username FROM $table_user
1713
                WHERE username = '$username' AND user_id <> '$user_id'";
1714
        $res_un = Database::query($sql);
1715
        $r_username = Database::fetch_row($res_un);
1716
1717
        if (!empty($r_username[0])) {
1718
            $results[] = 0; // username already exits.
1719
            continue;
1720
        }
1721
        // Edit lastname and firstname only if not empty
1722
1723
        /** @var User $user */
1724
        $user = $userRepository->find($user_id);
1725
1726
        if (!empty($lastname)) {
1727
            $user->setLastname($lastname);
1728
        }
1729
        if (!empty($firstname)) {
1730
            $user->setFirstname($firstname);
1731
        }
1732
        $user->setUsername($username);
1733
        if (!is_null($password)) {
1734
            $user->setPlainPassword($password);
1735
        }
1736
        if (!is_null($auth_source)) {
1737
            $user->setAuthSource($auth_source);
1738
        }
1739
1740
        // Exception for admins in case no status is provided in WS call...
1741
        $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
1742
        $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
1743
        $resadmin = Database::query($sqladmin);
1744
        $is_admin = Database::num_rows($resadmin);
1745
1746
        if (empty($status)) {
1747
            $status = 5;
1748
        }
1749
1750
        if ($is_admin) {
1751
            $status = 1;
1752
        }
1753
1754
        if (!empty($expiration_date)) {
1755
            $expiration_date = new DateTime($expiration_date);
1756
        }
1757
1758
        $user
1759
            ->setEmail($email)
1760
            ->setStatus($status)
1761
            ->setOfficialCode($official_code)
1762
            ->setPhone($phone)
1763
            ->setExpirationDate($expiration_date)
1764
            ->setHrDeptId($hr_dept_id)
1765
            ->setActive(true);
1766
1767
        if (!is_null($creator_id)) {
1768
            $user->setCreatorId($creator_id);
1769
        }
1770
1771
        $userManager->updateUser($user, true);
1772
1773
        if (is_array($extra_list) && count($extra_list) > 0) {
1774
            foreach ($extra_list as $extra) {
1775
                $extra_field_name = $extra['field_name'];
1776
                $extra_field_value = $extra['field_value'];
1777
                // Save the external system's id into user_field_value table.
1778
                UserManager::update_extra_field_value(
1779
                    $user_id,
1780
                    $extra_field_name,
1781
                    $extra_field_value
1782
                );
1783
            }
1784
        }
1785
1786
        $results[] = $user->getId();
1787
        continue;
1788
    }
1789
1790
    $count_results = count($results);
1791
    $output = array();
1792
    for ($i = 0; $i < $count_results; $i++) {
1793
        $output[] = array(
1794
            'original_user_id_value' => $orig_user_id_value[$i],
1795
            'result' => $results[$i],
1796
        );
1797
    }
1798
1799
    return $output;
1800
}
1801
1802
/* Register WSEditUser function */
1803
// Register the data structures used by the service
1804
$server->wsdl->addComplexType(
1805
    'editUser',
1806
    'complexType',
1807
    'struct',
1808
    'all',
1809
    '',
1810
    array(
1811
        'original_user_id_value' => array('name' => 'original_user_id_value', 'type' => 'xsd:string'),
1812
        'original_user_id_name' => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
1813
        'firstname' => array('name' => 'firstname', 'type' => 'xsd:string'),
1814
        'lastname' => array('name' => 'lastname', 'type' => 'xsd:string'),
1815
        'username' => array('name' => 'username', 'type' => 'xsd:string'),
1816
        'password' => array('name' => 'password', 'type' => 'xsd:string'),
1817
        'email' => array('name' => 'email', 'type' => 'xsd:string'),
1818
        'status' => array('name' => 'status', 'type' => 'xsd:string'),
1819
        'phone' => array('name' => 'phone', 'type' => 'xsd:string'),
1820
        'expiration_date' => array('name' => 'expiration_date', 'type' => 'xsd:string'),
1821
        'enable' => array('name' => 'enable', 'type' => 'xsd:boolean'),
1822
        'language' => array('name' => 'language', 'type' => 'xsd:string'),
1823
        'extra' => array('name' => 'extra', 'type' => 'tns:extrasList'),
1824
        'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string')
1825
    )
1826
);
1827
1828
// Register the method to expose
1829
$server->register(
1830
    'WSEditUser', // method name
1831
    array('editUser' => 'tns:editUser'), // input parameters
1832
    array('return' => 'xsd:string'), // output parameters
1833
    'urn:WSRegistration', // namespace
1834
    'urn:WSRegistration#WSEditUser', // soapaction
1835
    'rpc', // style
1836
    'encoded', // use
1837
    'This service edits a user from wiener'  // documentation
1838
);
1839
1840
// Define the method WSEditUser
1841
function WSEditUser($params)
1842
{
1843
    if (!WSHelperVerifyKey($params)) {
1844
        return returnError(WS_ERROR_SECRET_KEY);
1845
    }
1846
1847
    $userManager = UserManager::getManager();
1848
    $userRepository = UserManager::getRepository();
1849
1850
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
1851
1852
    $original_user_id_value = $params['original_user_id_value'];
1853
    $original_user_id_name = $params['original_user_id_name'];
1854
    $firstname = $params['firstname'];
1855
    $lastname = $params['lastname'];
1856
    $username = $params['username'];
1857
    $password = null;
1858
    $auth_source = null;
1859
    $email = $params['email'];
1860
    $status = $params['status'];
1861
    $official_code = '';
1862
    $phone = $params['phone'];
1863
    $picture_uri = '';
1864
    $expiration_date = $params['expiration_date'];
1865
    $enable = $params['enable'];
1866
    $language = $params['language'];
1867
    $creator_id = null;
1868
    $hr_dept_id = 0;
1869
    $extra = null;
1870
    $extra_list = $params['extra'];
1871
1872
    if (!empty($params['password'])) {
1873
        $password = $params['password'];
1874
    }
1875
1876
    // Get user id from id wiener
1877
    $user_id = UserManager::get_user_id_from_original_id(
1878
        $original_user_id_value,
1879
        $original_user_id_name
1880
    );
1881
1882
    if ($user_id == 0) {
1883
        return 0;
1884
    } else if (empty($enable)) {
1885
        $sql = "SELECT user_id FROM $table_user
1886
                WHERE user_id ='$user_id' AND active= '0'";
1887
        $resu = Database::query($sql);
1888
        $r_check_user = Database::fetch_row($resu);
1889
        if (!empty($r_check_user[0])) {
1890
            return 0;
1891
        }
1892
    }
1893
1894
    // Check whether username already exits.
1895
    $sql = "SELECT username FROM $table_user
1896
            WHERE username = '$username' AND user_id <> '$user_id'";
1897
    $res_un = Database::query($sql);
1898
    $r_username = Database::fetch_row($res_un);
1899
1900
    if (!empty($r_username[0])) {
1901
        return 0;
1902
    }
1903
1904
    /** @var User $user */
1905
    $user = $userRepository->find($user_id);
1906
1907
    if (!empty($lastname)) {
1908
        $user->setLastname($lastname);
1909
    }
1910
    if (!empty($firstname)) {
1911
        $user->setFirstname($firstname);
1912
    }
1913
    $user->setUsername($username);
1914
    if (!is_null($password)) {
1915
        $user->setPlainPassword($password);
1916
    }
1917
    if (!is_null($auth_source)) {
1918
        $user->setAuthSource($auth_source);
1919
    }
1920
1921
    // Exception for admins in case no status is provided in WS call...
1922
    $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
1923
    $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
1924
    $resadmin = Database::query($sqladmin);
1925
    $is_admin = Database::num_rows($resadmin);
1926
1927
    if (empty($status)) {
1928
        $status = 5;
1929
    }
1930
1931
    if ($is_admin) {
1932
        $status = 1;
1933
    }
1934
1935
    if (!empty($expiration_date)) {
1936
        $expiration_date = new DateTime($expiration_date);
1937
        $user->setExpirationDate($expiration_date);
1938
    }
1939
    if (!empty($language)) {
1940
        $user->setLanguage($language);
1941
    }
1942
1943
    $user
1944
        ->setEmail($email)
1945
        ->setStatus($status)
1946
        ->setOfficialCode($official_code)
1947
        ->setPhone($phone)
1948
        ->setPictureUri($picture_uri)
1949
        ->setHrDeptId($hr_dept_id)
1950
        ->setActive(true);
1951
1952
    if (!is_null($creator_id)) {
1953
        $user->setCreatorId($creator_id);
1954
    }
1955
1956
    $userManager->updateUser($user, true);
1957
1958
    if (is_array($extra_list) && count($extra_list) > 0) {
1959
        foreach ($extra_list as $extra) {
1960
            $extra_field_name = $extra['field_name'];
1961
            $extra_field_value = $extra['field_value'];
1962
            // Save the external system's id into user_field_value table.
1963
            UserManager::update_extra_field_value(
1964
                $user_id,
1965
                $extra_field_name,
1966
                $extra_field_value
1967
            );
1968
        }
1969
    }
1970
1971
    return  $user_id;
1972
}
1973
1974
/* Register WSEditUserWithPicture function */
1975
// Register the data structures used by the service
1976
$server->wsdl->addComplexType(
1977
    'editUserWithPicture',
1978
    'complexType',
1979
    'struct',
1980
    'all',
1981
    '',
1982
    array(
1983
        'original_user_id_value' => array('name' => 'original_user_id_value', 'type' => 'xsd:string'),
1984
        'original_user_id_name' => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
1985
        'firstname' => array('name' => 'firstname', 'type' => 'xsd:string'),
1986
        'lastname' => array('name' => 'lastname', 'type' => 'xsd:string'),
1987
        'username' => array('name' => 'username', 'type' => 'xsd:string'),
1988
        'password' => array('name' => 'password', 'type' => 'xsd:string'),
1989
        'email' => array('name' => 'email', 'type' => 'xsd:string'),
1990
        'status' => array('name' => 'status', 'type' => 'xsd:string'),
1991
        'phone' => array('name' => 'phone', 'type' => 'xsd:string'),
1992
        'expiration_date' => array('name' => 'expiration_date', 'type' => 'xsd:string'),
1993
        'extra' => array('name' => 'extra', 'type' => 'tns:extrasList'),
1994
        'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
1995
        'picture_url' => array('name' => 'picture_url', 'type' => 'xsd:string')
1996
    )
1997
);
1998
1999
// Register the method to expose
2000
$server->register(
2001
    'WSEditUserWithPicture', // method name
2002
    array('editUserWithPicture' => 'tns:editUserWithPicture'), // input parameters
2003
    array('return' => 'xsd:string'), // output parameters
2004
    'urn:WSRegistration', // namespace
2005
    'urn:WSRegistration#WSEditUserWithPicture', // soapaction
2006
    'rpc', // style
2007
    'encoded', // use
2008
    'This service edits a user from wiener'             // documentation
2009
);
2010
2011
// Define the method WSEditUserWithPicture
2012
function WSEditUserWithPicture($params)
2013
{
2014
    if (!WSHelperVerifyKey($params)) {
2015
        return returnError(WS_ERROR_SECRET_KEY);
2016
    }
2017
2018
    $userManager = UserManager::getManager();
2019
    $userRepository = UserManager::getRepository();
2020
2021
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
2022
2023
    $original_user_id_value = $params['original_user_id_value'];
2024
    $original_user_id_name = $params['original_user_id_name'];
2025
    $firstname = $params['firstname'];
2026
    $lastname = $params['lastname'];
2027
    $username = $params['username'];
2028
    $password = null;
2029
    $auth_source = null;
2030
    $email = $params['email'];
2031
    $expiration_date = null;
2032
    $status = $params['status'];
2033
    $phone = $params['phone'];
2034
    $picture_url = $params['picture_url'];
2035
    $pictureUri = '';
2036
    $creator_id = null;
2037
    $hr_dept_id = 0;
2038
    $extra = null;
2039
    $extra_list = $params['extra'];
2040
    if (!empty($params['expiration_date'])) {
2041
        $expiration_date = $params['expiration_date'];
2042
    }
2043
2044
    if (!empty($params['password'])) {
2045
        $password = $params['password'];
2046
    }
2047
2048
    // Get user id from external id
2049
    $user_id = UserManager::get_user_id_from_original_id(
2050
        $original_user_id_value,
2051
        $original_user_id_name
2052
    );
2053
2054
    // Get picture and generate uri.
2055
    $filename = basename($picture_url);
2056
    $tempDir = api_get_path(SYS_ARCHIVE_PATH);
2057
    // Make sure the file download was OK by checking the HTTP headers for OK
2058
    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

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