Completed
Push — 1.10.x ( ba0bf0...97c0d2 )
by Angel Fernando Quiroz
44:06
created

registration.soap.php ➔ WSEditUserWithPicture()   F

Complexity

Conditions 19
Paths 4121

Size

Total Lines 149
Code Lines 92

Duplication

Lines 12
Ratio 8.05 %
Metric Value
cc 19
eloc 92
nc 4121
nop 1
dl 12
loc 149
rs 2

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.

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 '../inc/global.inc.php';
11
$libpath = api_get_path(LIBRARY_PATH);
12
13
$debug = true;
14
15
define('WS_ERROR_SECRET_KEY', 1);
16
define('WS_ERROR_NOT_FOUND_RESULT', 2);
17
define('WS_ERROR_INVALID_INPUT', 3);
18
define('WS_ERROR_SETTING', 4);
19
20
/**
21
 * @param string $code
22
 * @return null|soap_fault
23
 */
24 View Code Duplication
function returnError($code)
25
{
26
    $fault = null;
27
    switch ($code) {
28
        case WS_ERROR_SECRET_KEY:
29
            $fault = new soap_fault('Server', '', 'Secret key is not correct or params are not correctly set');
30
            break;
31
        case WS_ERROR_NOT_FOUND_RESULT:
32
            $fault = new soap_fault('Server', '', 'No result was found for this query');
33
            break;
34
        case WS_ERROR_INVALID_INPUT:
35
            $fault = new soap_fault('Server', '', 'The input variables are invalid o are not correctly set');
36
            break;
37
        case WS_ERROR_SETTING:
38
            $fault = new soap_fault('Server', '', 'Please check the configuration for this webservice');
39
            break;
40
    }
41
    return $fault;
42
}
43
44
/**
45
 * @param array $params
46
 * @return bool
47
 */
48 View Code Duplication
function WSHelperVerifyKey($params)
0 ignored issues
show
Best Practice introduced by
The function WSHelperVerifyKey() has been defined more than once; this definition is ignored, only the first definition in main/webservices/access_url.php (L43-93) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
49
{
50
    global $_configuration, $debug;
51
    if (is_array($params)) {
52
        $secret_key = $params['secret_key'];
53
    } else {
54
        $secret_key = $params;
55
    }
56
    //error_log(print_r($params,1));
57
    $check_ip = false;
58
    $ip_matches = false;
59
    $ip = trim($_SERVER['REMOTE_ADDR']);
60
    // if we are behind a reverse proxy, assume it will send the
61
    // HTTP_X_FORWARDED_FOR header and use this IP instead
62
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
63
        list($ip1) = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
64
        $ip = trim($ip1);
65
    }
66
    if ($debug)
67
        error_log("ip: $ip");
68
    // Check if a file that limits access from webservices exists and contains
69
    // the restraining check
70
    if (is_file('webservice-auth-ip.conf.php')) {
71
        include 'webservice-auth-ip.conf.php';
72
        if ($debug)
73
            error_log("webservice-auth-ip.conf.php file included");
74
        if (!empty($ws_auth_ip)) {
0 ignored issues
show
Bug introduced by
The variable $ws_auth_ip seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
75
            $check_ip = true;
76
            $ip_matches = api_check_ip_in_range($ip, $ws_auth_ip);
77
            if ($debug)
78
                error_log("ip_matches: $ip_matches");
79
        }
80
    }
81
82
    if ($debug) {
83
        error_log("checkip " . intval($check_ip));
84
    }
85
86
    if ($check_ip) {
87
        $security_key = $_configuration['security_key'];
88
    } else {
89
        $security_key = $ip.$_configuration['security_key'];
90
        //error_log($secret_key.'-'.$security_key);
91
    }
92
93
    $result = api_is_valid_secret_key($secret_key, $security_key);
94
95
    if ($debug)
96
        error_log('WSHelperVerifyKey result: '.intval($result));
97
    return $result;
98
}
99
100
// Create the server instance
101
$server = new soap_server();
102
103
/** @var HookWSRegistration $hook */
104
$hook = HookWSRegistration::create();
105 View Code Duplication
if (!empty($hook)) {
106
    $hook->setEventData(array('server' => $server));
107
    $res = $hook->notifyWSRegistration(HOOK_EVENT_TYPE_PRE);
108
    if (!empty($res['server'])) {
109
        $server = $res['server'];
110
    }
111
}
112
113
$server->soap_defencoding = 'UTF-8';
114
115
// Initialize WSDL support
116
$server->configureWSDL('WSRegistration', 'urn:WSRegistration');
117
118
/* Register WSCreateUsers function */
119
// Register the data structures used by the service
120
121
// Prepare input params
122
$server->wsdl->addComplexType(
123
    'extras',
124
    'complexType',
125
    'struct',
126
    'all',
127
    '',
128
    array(
129
        'field_name'  => array('name' => 'field_name', 'type' => 'xsd:string'),
130
        'field_value' => array('name' => 'field_value', 'type' => 'xsd:string')
131
    )
132
);
133
134
$server->wsdl->addComplexType(
135
    'extrasList',
136
    'complexType',
137
    'array',
138
    '',
139
    'SOAP-ENC:Array',
140
    array(),
141
    array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType' => 'tns:extras[]')),
142
    'tns:extras'
143
);
144
145
$server->wsdl->addComplexType(
146
    'usersParams',
147
    'complexType',
148
    'struct',
149
    'all',
150
    '',
151
    array(
152
        'firstname' => array('name' => 'firstname', 'type' => 'xsd:string'),
153
        'lastname' => array('name' => 'lastname', 'type' => 'xsd:string'),
154
        'status' => array('name' => 'status', 'type' => 'xsd:string'),
155
        'email' => array('name' => 'email', 'type' => 'xsd:string'),
156
        'loginname' => array('name' => 'loginname', 'type' => 'xsd:string'),
157
        'password' => array('name' => 'password', 'type' => 'xsd:string'),
158
        'language' => array('name' => 'language', 'type' => 'xsd:string'),
159
        'phone' => array('name' => 'phone', 'type' => 'xsd:string'),
160
        'expiration_date' => array('name' => 'expiration_date', 'type' => 'xsd:string'),
161
        'original_user_id_name' => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
162
        'original_user_id_value' => array('name' => 'original_user_id_value', 'type' => 'xsd:string'),
163
        'extra' => array('name' => 'extra', 'type' => 'tns:extrasList')
164
    )
165
);
166
167
$server->wsdl->addComplexType(
168
    'usersParamsList',
169
    'complexType',
170
    'array',
171
    '',
172
    'SOAP-ENC:Array',
173
    array(),
174
    array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType' => 'tns:usersParams[]')),
175
    'tns:usersParams'
176
);
177
178
$server->wsdl->addComplexType(
179
    'createUsers',
180
    'complexType',
181
    'struct',
182
    'all',
183
    '',
184
    array(
185
        'users' => array('name' => 'users', 'type' => 'tns:usersParamsList'),
186
        'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string')
187
    )
188
);
189
190
// Prepare output params, in this case will return an array
191
$server->wsdl->addComplexType(
192
    'result_createUsers',
193
    'complexType',
194
    'struct',
195
    'all',
196
    '',
197
    array(
198
        'original_user_id_value' => array(
199
            'name' => 'original_user_id_value',
200
            'type' => 'xsd:string',
201
        ),
202
        'result' => array('name' => 'result', 'type' => 'xsd:string')
203
    )
204
);
205
206
$server->wsdl->addComplexType(
207
    'results_createUsers',
208
    'complexType',
209
    'array',
210
    '',
211
    'SOAP-ENC:Array',
212
    array(),
213
    array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType' => 'tns:result_createUsers[]')),'tns:result_createUsers'
214
);
215
216
// Register the method to expose
217
$server->register('WSCreateUsers',                 // method name
218
    array('createUsers' => 'tns:createUsers'),     // input parameters
219
    array('return' => 'tns:results_createUsers'),  // output parameters
220
    'urn:WSRegistration',                          // namespace
221
    'urn:WSRegistration#WSCreateUsers',            // soapaction
222
    'rpc',                                         // style
223
    'encoded',                                     // use
224
    'This service adds a user'                     // documentation
225
);
226
227
228
// Define the method WSCreateUsers
229
function WSCreateUsers($params) {
230
231
    global $_user;
232
233
    if (!WSHelperVerifyKey($params)) {
234
        return returnError(WS_ERROR_SECRET_KEY);
235
    }
236
237
    $users_params = $params['users'];
238
    $results = array();
239
    $orig_user_id_value = array();
240
241
    $userManager = UserManager::getManager();
242
    $userRepository = UserManager::getRepository();
243
244
    foreach ($users_params as $user_param) {
245
246
        $firstName = $user_param['firstname'];
247
        $lastName = $user_param['lastname'];
248
        $status = $user_param['status'];
249
        $email = $user_param['email'];
250
        $loginName = $user_param['loginname'];
251
        $password = $user_param['password'];
252
        $official_code = '';
253
        $language = '';
254
        $phone = '';
255
        $picture_uri = '';
256
        $auth_source = PLATFORM_AUTH_SOURCE;
257
        $expiration_date = '';
258
        $active = 1;
259
        $hr_dept_id = 0;
260
        $extra = null;
261
        $original_user_id_name = $user_param['original_user_id_name'];
262
        $original_user_id_value = $user_param['original_user_id_value'];
263
        $orig_user_id_value[] = $user_param['original_user_id_value'];
264
        $extra_list = $user_param['extra'];
265
        if (!empty($user_param['language'])) {
266
            $language = $user_param['language'];
267
        }
268
        if (!empty($user_param['phone'])) {
269
            $phone = $user_param['phone'];
270
        }
271
        if (!empty($user_param['expiration_date'])) {
272
            $expiration_date = $user_param['expiration_date'];
273
        }
274
275
        // Check if exits x_user_id into user_field_values table.
276
        $user_id = UserManager::get_user_id_from_original_id(
277
            $original_user_id_value,
278
            $original_user_id_name
279
        );
280
        if ($user_id > 0) {
281
            /** @var User $user */
282
            $user = $userRepository->find($user_id);
283
284
            if ($user && $user->isActive() == false) {
285
                if (!is_null($password)) {
286
                    $user->setPlainPassword($password);
287
                }
288
                if (!is_null($auth_source)) {
289
                    $user->setAuthSource($auth_source);
290
                }
291
292
                if (!empty($user_param['expiration_date'])) {
293
                    $expiration_date = new DateTime($user_param['expiration_date']);
294
                }
295
296
                $user->setLastname($lastName)
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class FOS\UserBundle\Model\User as the method setStatus() does only exist in the following sub-classes of FOS\UserBundle\Model\User: Chamilo\UserBundle\Entity\User. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
297
                    ->setFirstname($firstName)
298
                    ->setUsername($loginName)
299
                    ->setEmail($email)
300
                    ->setStatus($status)
301
                    ->setOfficialCode($official_code)
302
                    ->setPhone($phone)
303
                    ->setExpirationDate($expiration_date)
304
                    ->setHrDeptId($hr_dept_id)
305
                    ->setActive(true);
306
                $userManager->updateUser($user, true);
307
                $results[] = $user_id;
308
                continue;
309
                //return $r_check_user[0];
310
            } else {
311
                $results[] = 0;
312
                continue;
313
                //return 0;
314
                // user id already exits.
315
            }
316
        }
317
318
        // Default language.
319
        if (empty($language)) {
320
            $language = api_get_setting('platformLanguage');
321
        }
322
323
        if (!empty($_user['user_id'])) {
324
            $creator_id = $_user['user_id'];
325
        } else {
326
            $creator_id = '';
327
        }
328
329
        // First check wether the login already exists.
330
        if (!UserManager::is_username_available($loginName)) {
331
            if (api_set_failure('login-pass already taken')) {
332
                $results[] = 0;
333
                continue;
334
            }
335
        }
336
337
        $userId = UserManager::create_user(
338
            $firstName,
339
            $lastName,
340
            $status,
341
            $email,
342
            $loginName,
343
            $password,
344
            $official_code,
345
            $language,
346
            $phone,
347
            $picture_uri,
348
            $auth_source,
349
            $expiration_date,
350
            $active,
351
            $hr_dept_id
352
        );
353
354
        if ($userId) {
355 View Code Duplication
            if (api_is_multiple_url_enabled()) {
356
                if (api_get_current_access_url_id() != -1) {
357
                    UrlManager::add_user_to_url($userId, api_get_current_access_url_id());
358
                } else {
359
                    UrlManager::add_user_to_url($userId, 1);
360
                }
361
            } else {
362
                // We add by default the access_url_user table with access_url_id = 1
363
                UrlManager::add_user_to_url($userId, 1);
364
            }
365
366
            // Save new field label into user_field table.
367
            UserManager::create_extra_field(
368
                $original_user_id_name,
369
                1,
370
                $original_user_id_name,
371
                ''
372
            );
373
            // Save the external system's id into user_field_value table.
374
            UserManager::update_extra_field_value(
375
                $userId,
0 ignored issues
show
Bug introduced by
It seems like $userId defined by \UserManager::create_use..., $active, $hr_dept_id) on line 337 can also be of type boolean; however, UserManager::update_extra_field_value() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
376
                $original_user_id_name,
377
                $original_user_id_value
378
            );
379
380 View Code Duplication
            if (is_array($extra_list) && count($extra_list) > 0) {
381
                foreach ($extra_list as $extra) {
382
                    $extra_field_name = $extra['field_name'];
383
                    $extra_field_value = $extra['field_value'];
384
                    // Save new field label into user_field table.
385
                    UserManager::create_extra_field(
386
                        $extra_field_name,
387
                        1,
388
                        $extra_field_name,
389
                        ''
390
                    );
391
                    // Save the external system's id into user_field_value table.
392
                    UserManager::update_extra_field_value(
393
                        $userId,
0 ignored issues
show
Bug introduced by
It seems like $userId defined by \UserManager::create_use..., $active, $hr_dept_id) on line 337 can also be of type boolean; however, UserManager::update_extra_field_value() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
394
                        $extra_field_name,
395
                        $extra_field_value
396
                    );
397
                }
398
            }
399
        } else {
400
            $results[] = 0;
401
            continue;
402
        }
403
404
        $results[] =  $userId;
405
406
    } // end principal foreach
407
408
    $count_results = count($results);
409
    $output = array();
410
    for ($i = 0; $i < $count_results; $i++) {
411
        $output[] = array(
412
            'original_user_id_value' => $orig_user_id_value[$i],
413
            'result' => $results[$i],
414
        );
415
    }
416
417
    return $output;
418
}
419
420
/* Register WSCreateUser function */
421
// Register the data structures used by the service
422
423
424
$server->wsdl->addComplexType(
425
    'createUser',
426
    'complexType',
427
    'struct',
428
    'all',
429
    '',
430
    array(
431
        'firstname' => array('name' => 'firstname', 'type' => 'xsd:string'),
432
        'lastname' => array('name' => 'lastname', 'type' => 'xsd:string'),
433
        'status' => array('name' => 'status', 'type' => 'xsd:string'),
434
        'email' => array('name' => 'email', 'type' => 'xsd:string'),
435
        'loginname' => array('name' => 'loginname', 'type' => 'xsd:string'),
436
        'password' => array('name' => 'password', 'type' => 'xsd:string'),
437
        'language' => array('name' => 'language', 'type' => 'xsd:string'),
438
        'phone' => array('name' => 'phone', 'type' => 'xsd:string'),
439
        'expiration_date' => array('name' => 'expiration_date', 'type' => 'xsd:string'),
440
        'original_user_id_name' => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
441
        'original_user_id_value' => array('name' => 'original_user_id_value', 'type' => 'xsd:string'),
442
        'extra' => array('name' => 'extra', 'type' => 'tns:extrasList'),
443
        'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
444
        'active' => array('name' => 'extra', 'type' => 'xsd:string')
445
    )
446
);
447
448
449
// Register the method to expose
450
$server->register('WSCreateUser',                // method name
451
    array('createUser' => 'tns:createUser'),     // input parameters
452
    array('return' => 'xsd:string'),             // output parameters
453
    'urn:WSRegistration',                        // namespace
454
    'urn:WSRegistration#WSCreateUser',           // soapaction
455
    'rpc',                                       // style
456
    'encoded',                                   // use
457
    'This service adds a user'                   // documentation
458
);
459
460
461
// Define the method WSCreateUser
462
function WSCreateUser($params) {
463
    global $_user, $_configuration, $debug;
464
465
    if (!WSHelperVerifyKey($params)) {
466
        return returnError(WS_ERROR_SECRET_KEY);
467
    }
468
469
    $firstName = $params['firstname'];
470
    $lastName = $params['lastname'];
471
    $status = $params['status'];
472
    $email = $params['email'];
473
    $loginName = $params['loginname'];
474
    $password = $params['password'];
475
    $official_code = '';
476
    $language = '';
477
    $phone = '';
478
    $picture_uri = '';
479
    $auth_source = PLATFORM_AUTH_SOURCE;
480
    $expiration_date = null;
481
    $expirationDateStatement = '';
482
    $active = !isset($params['active']) || !intval($params['active']) ? 0 : 1;
483
    $hr_dept_id = 0;
484
    $extra = null;
485
    $original_user_id_name = $params['original_user_id_name'];
486
    $original_user_id_value = $params['original_user_id_value'];
487
    $extra_list = $params['extra'];
488
    if (!empty($params['language'])) {
489
        $language = $params['language'];
490
    }
491
    if (!empty($params['phone'])) {
492
        $phone = $params['phone'];
493
    }
494
    if (!empty($params['expiration_date'])) {
495
        $expiration_date = $params['expiration_date'];
496
        //$expirationDateStatement = " expiration_date = '".Database::escape_string($expiration_date)."', ";
497
    }
498
499
    // check if exits x_user_id into user_field_values table
500
    $user_id = UserManager::get_user_id_from_original_id(
501
        $original_user_id_value,
502
        $original_user_id_name
503
    );
504
505
    $userManager = UserManager::getManager();
506
    $userRepository = UserManager::getRepository();
507
508
    if ($user_id > 0) {
509
510
        /** @var User $user */
511
        $user = $userRepository->find($user_id);
512
513
        if ($user && $user->isActive() == false) {
514
            if (!is_null($password)) {
515
                $user->setPlainPassword($password);
516
            }
517
            if (!is_null($auth_source)) {
518
                $user->setAuthSource($auth_source);
519
            }
520
521
            if (!empty($params['expiration_date'])) {
522
                $expiration_date = new DateTime($params['expiration_date']);
523
            }
524
525
            $user->setLastname($lastName)
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class FOS\UserBundle\Model\User as the method setStatus() does only exist in the following sub-classes of FOS\UserBundle\Model\User: Chamilo\UserBundle\Entity\User. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
526
                ->setFirstname($firstName)
527
                ->setUsername($loginName)
528
                ->setEmail($email)
529
                ->setStatus($status)
530
                ->setOfficialCode($official_code)
531
                ->setPhone($phone)
532
                ->setExpirationDate($expiration_date)
533
                ->setHrDeptId($hr_dept_id)
534
                ->setActive(true);
535
            $userManager->updateUser($user, true);
536
537
            return $user_id;
538
        } else {
539
            return 0;
540
        }
541
    }
542
543
    // Default language
544
    if (empty($language)) {
545
        $language = api_get_setting('platformLanguage');
546
    }
547
548
    if (!empty($_user['user_id'])) {
549
        $creator_id = $_user['user_id'];
550
    } else {
551
        $creator_id = '';
552
    }
553
554
    // First check wether the login already exists
555
    if (!UserManager::is_username_available($loginName)) {
556
        if ($debug) error_log("Username $loginName is not available");
557
        return 0;
558
    }
559
560
    if (isset($original_user_id_name) && isset($original_user_id_value)) {
561
        $_SESSION['ws_' . $original_user_id_name] = $original_user_id_value;
562
    }
563
564
    /** @var User $user */
565
    $userId = UserManager::create_user(
566
        $firstName,
567
        $lastName,
568
        $status,
569
        $email,
570
        $loginName,
571
        $password,
572
        $official_code,
573
        $language,
574
        $phone,
575
        $picture_uri,
576
        $auth_source,
577
        $expiration_date,
578
        $active,
579
        $hr_dept_id
580
    );
581
582
    if ($userId) {
583 View Code Duplication
        if (api_is_multiple_url_enabled()) {
584
            if (api_get_current_access_url_id() != -1) {
585
                UrlManager::add_user_to_url($userId, api_get_current_access_url_id());
586
            } else {
587
                UrlManager::add_user_to_url($userId, 1);
588
            }
589
        } else {
590
            // We add by default the access_url_user table with access_url_id = 1
591
            UrlManager::add_user_to_url($userId, 1);
592
        }
593
594
        // Save new fieldlabel into user_field table.
595
        UserManager::create_extra_field(
596
            $original_user_id_name,
597
            1,
598
            $original_user_id_name,
599
            ''
600
        );
601
        // Save the external system's id into user_field_value table.
602
        UserManager::update_extra_field_value(
603
            $userId,
0 ignored issues
show
Bug introduced by
It seems like $userId defined by \UserManager::create_use..., $active, $hr_dept_id) on line 565 can also be of type boolean; however, UserManager::update_extra_field_value() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
604
            $original_user_id_name,
605
            $original_user_id_value
606
        );
607
608
        if (isset($original_user_id_name) && isset($original_user_id_value)) {
609
            unset($_SESSION['ws_' . $original_user_id_name]);
610
        }
611
612 View Code Duplication
        if (is_array($extra_list) && count($extra_list) > 0) {
613
            foreach ($extra_list as $extra) {
614
                $extra_field_name = $extra['field_name'];
615
                $extra_field_value = $extra['field_value'];
616
                // Save new field label into user_field table.
617
                UserManager::create_extra_field(
618
                    $extra_field_name,
619
                    1,
620
                    $extra_field_name,
621
                    ''
622
                );
623
                // Save the external system's id into user_field_value table.
624
                UserManager::update_extra_field_value(
625
                    $userId,
0 ignored issues
show
Bug introduced by
It seems like $userId defined by \UserManager::create_use..., $active, $hr_dept_id) on line 565 can also be of type boolean; however, UserManager::update_extra_field_value() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

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

This check looks for function calls that miss required arguments.

Loading history...
2041
    }
2042
2043
    if ($user_id == 0) {
2044
        return 0;
2045
    } else {
2046
        $sql = "SELECT id FROM $table_user WHERE id =$user_id AND active= 0";
2047
        $resu = Database::query($sql);
2048
        $r_check_user = Database::fetch_row($resu);
2049
        if (!empty($r_check_user[0])) {
2050
            return 0;
2051
        }
2052
    }
2053
2054
    // Check whether username already exits.
2055
    $sql = "SELECT username FROM $table_user WHERE username = '$username' AND id <> $user_id";
2056
    $res_un = Database::query($sql);
2057
    $r_username = Database::fetch_row($res_un);
2058
2059
    if (!empty($r_username[0])) {
2060
        return 0;
2061
    }
2062
2063
2064
    /** @var User $user */
2065
    $user = $userRepository->find($user_id);
2066
2067
    if (!empty($lastname)) {
2068
        $user->setLastname($lastname);
2069
        //$sql .= " lastname='".Database::escape_string($lastname)."', ";
2070
    }
2071
    if (!empty($firstname)) {
2072
        $user->setFirstname($firstname);
2073
        //$sql .= " firstname='".Database::escape_string($firstname)."', ";
2074
    }
2075
    $user->setUsername($username);
2076
    //$sql .= " username='".Database::escape_string($username)."',";
2077
    if (!is_null($password)) {
2078
        //$password = $_configuration['password_encryption'] ? api_get_encrypted_password($password) : $password;
2079
        //$sql .= " password='".Database::escape_string($password)."',";
2080
        $user->setPlainPassword($password);
2081
    }
2082
    if (!is_null($auth_source)) {
2083
        $user->setAuthSource($auth_source);
2084
    }
2085
2086
    // Exception for admins in case no status is provided in WS call...
2087
    $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
2088
    $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
2089
    $resadmin = Database::query($sqladmin);
2090
    $is_admin = Database::num_rows($resadmin);
2091
2092
    if (empty($status)) {
2093
        $status = $user->getStatus();
2094
    }
2095
2096
    if ($is_admin) {
2097
        $status = 1;
2098
    }
2099
2100
    if (!empty($expiration_date)) {
2101
        $expiration_date = new DateTime($expiration_date);
2102
    }
2103
2104
    $user
2105
        ->setEmail($email)
2106
        ->setStatus($status)
2107
        ->setPhone($phone)
2108
        ->setExpirationDate($expiration_date)
2109
        ->setHrDeptId($hr_dept_id)
2110
        ->setActive(true)
2111
        ->setPictureUri($pictureUri);;
0 ignored issues
show
Security Bug introduced by
It seems like $pictureUri defined by \UserManager::update_use..., $tempDir . $filename) on line 2040 can also be of type false; however, Chamilo\UserBundle\Entity\User::setPictureUri() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

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

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
6326
        $sessionData['extra'] = SessionManager::getFilteredExtraFields($params['id'], $fieldsToInclude);
6327
    }
6328
6329
    return array($sessionData);
6330
}
6331
6332
/* Fetch session Web Service end */
6333
6334
/* Register WSCertificatesList function */
6335
// Register the data structures used by the service
6336
$server->wsdl->addComplexType(
6337
    'certificateDetails',
6338
    'complexType',
6339
    'struct',
6340
    'all',
6341
    '',
6342
    array(
6343
        'id' => array('name' => 'id', 'type' => 'xsd:int'),
6344
        'username' => array('name' => 'username', 'type' => 'xsd:string'),
6345
        'course_code' => array('name' => 'course_code', 'type' => 'xsd:string'),
6346
        'session_id' => array('name' => 'session_id', 'type' => 'xsd:int'),
6347
        'cat_id' => array('name' => 'cat_id', 'type' => 'xsd:int'),
6348
        'created_at' => array('name' => 'created_at', 'type' => 'xsd:string'),
6349
        'path_certificate' => array('name' => 'path_certificate', 'type' => 'xsd:string')
6350
    )
6351
);
6352
6353
$server->wsdl->addComplexType(
6354
    'certificatesList',
6355
    'complexType',
6356
    'array',
6357
    '',
6358
    'SOAP-ENC:Array',
6359
    array(),
6360
    array(
6361
        array('ref'=>'SOAP-ENC:arrayType',
6362
            'wsdl:arrayType'=>'tns:certificateDetails[]')
6363
    ),
6364
    'tns:certificateDetails'
6365
);
6366
// Register the method to expose
6367
$server->register(
6368
    'WSCertificatesList',                           // method name
6369
    array(
6370
        'startingDate' => 'xsd:string',             // input parameters
6371
        'endingDate' => 'xsd:string'
6372
    ),
6373
    array('return' => 'tns:certificatesList'),      // output parameters
6374
    'urn:WSRegistration',                           // namespace
6375
    'urn:WSRegistration#WSCertificatesList',        // soapaction
6376
    'rpc',                                          // style
6377
    'encoded',                                      // use
6378
    'This service returns a list of certificates'   // documentation
6379
);
6380
6381
function WSCertificatesList($startingDate = '', $endingDate = '')
6382
{
6383
    global $_configuration;
6384
    $certificatesCron = api_get_setting('add_gradebook_certificates_cron_task_enabled');
6385
    if ($certificatesCron === 'true') {
6386
        require_once api_get_path(SYS_CODE_PATH).'cron/add_gradebook_certificates.php';
6387
    }
6388
    $result = array();
6389
    $certificateTable = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
6390
    $userTable = Database::get_main_table(TABLE_MAIN_USER);
6391
    $categoryTable = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
6392
6393
    $query = "SELECT
6394
                    certificate.id,
6395
                    user.username,
6396
                    category.course_code,
6397
                    category.session_id,
6398
                    certificate.user_id,
6399
                    certificate.cat_id,
6400
                    certificate.created_at,
6401
                    certificate.path_certificate
6402
                FROM $certificateTable AS certificate
6403
                JOIN $userTable AS user
6404
                ON certificate.user_id = user.user_id
6405
                JOIN $categoryTable AS category
6406
                ON certificate.cat_id = category.id";
6407
6408
    if (!empty($startingDate) && !empty($endingDate)) {
6409
        $query .= " WHERE certificate.created_at BETWEEN '$startingDate' AND '$endingDate'";
6410
    } else if (!empty($startingDate)) {
6411
        $query .= " WHERE certificate.created_at >= '$startingDate'";
6412
    } else if (!empty($endingDate)) {
6413
        $query .= " WHERE certificate.created_at <= '$endingDate'";
6414
    }
6415
6416
    $queryResult = Database::query($query);
6417
    while ($row = Database::fetch_array($queryResult)) {
6418
        $userPath = USermanager::getUserPathById($row['user_id'], 'web');
6419
        $row['path_certificate'] = $userPath.'/certificate'.$row['path_certificate'];
6420
        $result[] = $row;
6421
    }
6422
6423
    return $result;
6424
}
6425
6426
/* Create group Web Service start */
6427
// Register the data structures used by the service
6428
6429
// Input params for WSCreateGroup
6430
$server->wsdl->addComplexType(
6431
    'createGroup',
6432
    'complexType',
6433
    'struct',
6434
    'all',
6435
    '',
6436
    array(
6437
        'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
6438
        'name' => array('name' => 'name', 'type' => 'xsd:string')
6439
    )
6440
);
6441
6442
// Register the method to expose
6443
$server->register('WSCreateGroup',              // method name
6444
    array('createGroup' => 'tns:createGroup'),  // input parameters
6445
    array('return' => 'xsd:string'),            // output parameters
6446
    'urn:WSRegistration',                       // namespace
6447
    'urn:WSRegistration#WSCreateGroup',         // soapaction
6448
    'rpc',                                      // style
6449
    'encoded',                                  // use
6450
    'This service adds a group'                 // documentation
6451
);
6452
6453
// Define the method WSCreateGroup
6454 View Code Duplication
function WSCreateGroup($params)
6455
{
6456
    if (!WSHelperVerifyKey($params['secret_key'])) {
6457
        return returnError(WS_ERROR_SECRET_KEY);
6458
    }
6459
    $userGroup = new UserGroup();
6460
    $params = [
6461
        'name' => $params['name']
6462
    ];
6463
    return $userGroup->save($params);
6464
    //return GroupPortalManager::add($params['name'], null, null, 1);
6465
}
6466
6467
/* Create group Web Service end */
6468
6469
/* Update group Web Service start */
6470
// Register the data structures used by the service
6471
6472
// Input params for WSUpdateGroup
6473
$server->wsdl->addComplexType(
6474
    'updateGroup',
6475
    'complexType',
6476
    'struct',
6477
    'all',
6478
    '',
6479
    array(
6480
        'secret_key'   => array('name' => 'secret_key', 'type' => 'xsd:string'),
6481
        'id' => array('name' => 'id', 'type' => 'xsd:string'),
6482
        'name' => array('name' => 'name', 'type' => 'xsd:string'),
6483
        'description'   => array('name' => 'description', 'type' => 'xsd:string'),
6484
        'url' => array('name' => 'url', 'type' => 'xsd:string'),
6485
        'visibility' => array('name' => 'visibility', 'type' => 'xsd:string'),
6486
        'picture_uri' => array('name' => 'picture_uri', 'type' => 'xsd:string'),
6487
        'allow_member_group_to_leave' => array('name' => 'allow_member_group_to_leave', 'type' => 'xsd:string')
6488
    )
6489
);
6490
6491
// Register the method to expose
6492
$server->register('WSUpdateGroup',              // method name
6493
    array('updateGroup' => 'tns:updateGroup'),  // input parameters
6494
    array('return' => 'xsd:string'),            // output parameters
6495
    'urn:WSRegistration',                       // namespace
6496
    'urn:WSRegistration#WSUpdateGroup',         // soapaction
6497
    'rpc',                                      // style
6498
    'encoded',                                  // use
6499
    'This service updates a group'              // documentation
6500
);
6501
6502
// Define the method WSUpdateGroup
6503 View Code Duplication
function WSUpdateGroup($params)
6504
{
6505
    if (!WSHelperVerifyKey($params['secret_key'])) {
6506
        return returnError(WS_ERROR_SECRET_KEY);
6507
    }
6508
    $params['allow_member_group_to_leave'] = null;
6509
6510
    $userGroup = new UserGroup();
6511
    return $userGroup->update($params);
6512
6513
    /*return GroupPortalManager::update(
6514
        $params['id'],
6515
        $params['name'],
6516
        $params['description'],
6517
        $params['url'],
6518
        $params['visibility'],
6519
        $params['picture_uri'],
6520
        $params['allow_member_group_to_leave']
6521
    );*/
6522
}
6523
6524
/* Update group Web Service end */
6525
6526
/* Delete group Web Service start */
6527
// Register the data structures used by the service
6528
6529
// Input params for WSDeleteGroup
6530
$server->wsdl->addComplexType(
6531
    'deleteGroup',
6532
    'complexType',
6533
    'struct',
6534
    'all',
6535
    '',
6536
    array(
6537
        'secret_key'   => array('name' => 'secret_key', 'type' => 'xsd:string'),
6538
        'id' => array('name' => 'id', 'type' => 'xsd:string')
6539
    )
6540
);
6541
6542
// Register the method to expose
6543
$server->register('WSDeleteGroup',              // method name
6544
    array('deleteGroup' => 'tns:deleteGroup'),  // input parameters
6545
    array('return' => 'xsd:string'),            // output parameters
6546
    'urn:WSRegistration',                       // namespace
6547
    'urn:WSRegistration#WSDeleteGroup',         // soapaction
6548
    'rpc',                                      // style
6549
    'encoded',                                  // use
6550
    'This service deletes a group'              // documentation
6551
);
6552
6553
// Define the method WSDeleteGroup
6554 View Code Duplication
function WSDeleteGroup($params)
6555
{
6556
    if (!WSHelperVerifyKey($params['secret_key'])) {
6557
        return returnError(WS_ERROR_SECRET_KEY);
6558
    }
6559
    $userGroup = new UserGroup();
6560
6561
    return $userGroup->delete($params['id']);
6562
6563
    //return GroupPortalManager::delete($params['id']);
6564
}
6565
6566
/* Delete group Web Service end */
6567
6568
/* Bind group to parent Web Service start */
6569
// Register the data structures used by the service
6570
6571
// Input params for GroupBindToParent
6572
$server->wsdl->addComplexType(
6573
    'groupBindToParent',
6574
    'complexType',
6575
    'struct',
6576
    'all',
6577
    '',
6578
    array(
6579
        'secret_key'   => array('name' => 'secret_key', 'type' => 'xsd:string'),
6580
        'id' => array('name' => 'id', 'type' => 'xsd:string'),
6581
        'parent_id' => array('name' => 'parent_id', 'type' => 'xsd:string')
6582
    )
6583
);
6584
6585
// Register the method to expose
6586
$server->register('GroupBindToParent',                      // method name
6587
    array('groupBindToParent' => 'tns:groupBindToParent'),  // input parameters
6588
    array('return' => 'xsd:string'),                        // output parameters
6589
    'urn:WSRegistration',                                   // namespace
6590
    'urn:WSRegistration#GroupBindToParent',                 // soapaction
6591
    'rpc',                                                  // style
6592
    'encoded',                                              // use
6593
    'This service binds a group to a parent'                // documentation
6594
);
6595
6596
// Define the method GroupBindToParent
6597 View Code Duplication
function GroupBindToParent($params)
6598
{
6599
    if (!WSHelperVerifyKey($params['secret_key'])) {
6600
        return returnError(WS_ERROR_SECRET_KEY);
6601
    }
6602
    $userGroup = new UserGroup();
6603
6604
    return $userGroup->set_parent_group($params['id'], $params['parent_id']);
6605
6606
    //return GroupPortalManager::set_parent_group($params['id'], $params['parent_id']);
6607
}
6608
6609
/* Bind group Web Service end */
6610
6611
/* Unbind group from parent Web Service start */
6612
// Register the data structures used by the service
6613
6614
// Input params for GroupUnbindFromParent
6615
$server->wsdl->addComplexType(
6616
    'groupUnbindFromParent',
6617
    'complexType',
6618
    'struct',
6619
    'all',
6620
    '',
6621
    array(
6622
        'secret_key'   => array('name' => 'secret_key', 'type' => 'xsd:string'),
6623
        'id' => array('name' => 'id', 'type' => 'xsd:string')
6624
    )
6625
);
6626
6627
// Register the method to expose
6628
$server->register('GroupUnbindFromParent',                          // method name
6629
    array('groupUnbindFromParent' => 'tns:groupUnbindFromParent'),  // input parameters
6630
    array('return' => 'xsd:string'),                                // output parameters
6631
    'urn:WSRegistration',                                           // namespace
6632
    'urn:WSRegistration#GroupUnbindFromParent',                     // soapaction
6633
    'rpc',                                                          // style
6634
    'encoded',                                                      // use
6635
    'This service unbinds a group from its parent'                  // documentation
6636
);
6637
6638
// Define the method GroupUnbindFromParent
6639 View Code Duplication
function GroupUnbindFromParent($params)
6640
{
6641
    if (!WSHelperVerifyKey($params['secret_key'])) {
6642
        return returnError(WS_ERROR_SECRET_KEY);
6643
    }
6644
    $userGroup = new UserGroup();
6645
    return $userGroup->set_parent_group($params['id'], 0);
6646
}
6647
6648
/* Unbind group Web Service end */
6649
6650
/* Add user to group Web Service start */
6651
// Register the data structures used by the service
6652
6653
// Input params for WSAddUserToGroup
6654
$server->wsdl->addComplexType(
6655
    'addUserToGroup',
6656
    'complexType',
6657
    'struct',
6658
    'all',
6659
    '',
6660
    array(
6661
        'secret_key'   => array('name' => 'secret_key', 'type' => 'xsd:string'),
6662
        'user_id' => array('name' => 'user_id', 'type' => 'xsd:string'),
6663
        'group_id' => array('name' => 'group_id', 'type' => 'xsd:string')
6664
    )
6665
);
6666
6667
// Register the method to expose
6668
$server->register('WSAddUserToGroup',                   // method name
6669
    array('addUserToGroup' => 'tns:addUserToGroup'),    // input parameters
6670
    array('return' => 'xsd:string'),                    // output parameters
6671
    'urn:WSRegistration',                               // namespace
6672
    'urn:WSRegistration#WSAddUserToGroup',              // soapaction
6673
    'rpc',                                              // style
6674
    'encoded',                                          // use
6675
    'This service adds a user to a group'               // documentation
6676
);
6677
6678
// Define the method WSAddUserToGroup
6679 View Code Duplication
function WSAddUserToGroup($params)
6680
{
6681
    if (!WSHelperVerifyKey($params['secret_key'])) {
6682
        return returnError(WS_ERROR_SECRET_KEY);
6683
    }
6684
6685
    $userGroup = new UserGroup();
6686
6687
    return $userGroup->add_user_to_group($params['user_id'], $params['group_id']);
6688
}
6689
6690
/* Add user to group Web Service end */
6691
6692
/* Update user role in group Web Service start */
6693
// Register the data structures used by the service
6694
6695
// Input params for WSUpdateUserRoleInGroup
6696
$server->wsdl->addComplexType(
6697
    'updateUserRoleInGroup',
6698
    'complexType',
6699
    'struct',
6700
    'all',
6701
    '',
6702
    array(
6703
        'secret_key'   => array('name' => 'secret_key', 'type' => 'xsd:string'),
6704
        'user_id' => array('name' => 'user_id', 'type' => 'xsd:string'),
6705
        'group_id' => array('name' => 'group_id', 'type' => 'xsd:string'),
6706
        'relation_type' => array('name' => 'relation_type', 'type' => 'xsd:string')
6707
    )
6708
);
6709
6710
// Register the method to expose
6711
$server->register('WSUpdateUserRoleInGroup',                        // method name
6712
    array('updateUserRoleInGroup' => 'tns:updateUserRoleInGroup'),  // input parameters
6713
    array('return' => 'xsd:string'),                                // output parameters
6714
    'urn:WSRegistration',                                           // namespace
6715
    'urn:WSRegistration#WSUpdateUserRoleInGroup',                   // soapaction
6716
    'rpc',                                                          // style
6717
    'encoded',                                                      // use
6718
    'This service updates a user role in group'                     // documentation
6719
);
6720
6721
// Define the method WSUpdateUserRoleInGroup
6722 View Code Duplication
function WSUpdateUserRoleInGroup($params)
6723
{
6724
    if (!WSHelperVerifyKey($params['secret_key'])) {
6725
        return returnError(WS_ERROR_SECRET_KEY);
6726
    }
6727
    $userGroup = new UserGroup();
6728
6729
    return $userGroup->update_user_role(
6730
        $params['user_id'],
6731
        $params['group_id'],
6732
        $params['relation_type']
6733
    );
6734
}
6735
6736
/* Update user role Web Service end */
6737
6738
/* Delete user from group Web Service start */
6739
// Register the data structures used by the service
6740
6741
// Input params for WSDeleteUserFromGroup
6742
$server->wsdl->addComplexType(
6743
    'deleteUserFromGroup',
6744
    'complexType',
6745
    'struct',
6746
    'all',
6747
    '',
6748
    array(
6749
        'secret_key'   => array('name' => 'secret_key', 'type' => 'xsd:string'),
6750
        'user_id' => array('name' => 'user_id', 'type' => 'xsd:string'),
6751
        'group_id' => array('name' => 'group_id', 'type' => 'xsd:string')
6752
    )
6753
);
6754
6755
// Register the method to expose
6756
$server->register('WSDeleteUserFromGroup',                      // method name
6757
    array('deleteUserFromGroup' => 'tns:deleteUserFromGroup'),  // input parameters
6758
    array('return' => 'xsd:string'),                            // output parameters
6759
    'urn:WSRegistration',                                       // namespace
6760
    'urn:WSRegistration#WSDeleteUserFromGroup',                 // soapaction
6761
    'rpc',                                                      // style
6762
    'encoded',                                                  // use
6763
    'This service deletes a user from a group'                  // documentation
6764
);
6765
6766
// Define the method WSDeleteUserFromGroup
6767 View Code Duplication
function WSDeleteUserFromGroup($params)
6768
{
6769
    if (!WSHelperVerifyKey($params['secret_key'])) {
6770
        return returnError(WS_ERROR_SECRET_KEY);
6771
    }
6772
    $userGroup = new UserGroup();
6773
6774
    return $userGroup->delete_user_rel_group(
6775
        $params['user_id'],
6776
        $params['group_id']
6777
    );
6778
}
6779
6780
6781
/* Delete user from group Web Service end */
6782
6783
// Add more webservices through hooks from plugins
6784 View Code Duplication
if (!empty($hook)) {
6785
    $hook->setEventData(array('server' => $server));
6786
    $res = $hook->notifyWSRegistration(HOOK_EVENT_TYPE_POST);
6787
    if (!empty($res['server'])) {
6788
        $server = $res['server'];
6789
    }
6790
}
6791
6792
// Use the request to (try to) invoke the service
6793
$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents('php://input');
6794
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
6795
6796
// If you send your data in utf8 then this value must be false.
6797
$decodeUTF8 = api_get_setting('registration.soap.php.decode_utf8');
6798
if ($decodeUTF8 === 'true') {
6799
    $server->decode_utf8 = true;
6800
} else {
6801
    $server->decode_utf8 = false;
6802
}
6803
$server->service($HTTP_RAW_POST_DATA);
6804