WSAssignSkill()   B
last analyzed

Complexity

Conditions 8
Paths 13

Size

Total Lines 54
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 32
nc 13
nop 1
dl 0
loc 54
rs 8.1635
c 0
b 0
f 0

How to fix   Long Method   

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
3
/* For licensing terms, see /license.txt */
4
5
use Skill as SkillManager;
6
7
require_once __DIR__.'/../inc/global.inc.php';
8
9
api_protect_webservices();
10
11
ini_set('memory_limit', -1);
12
13
/*
14
ini_set('upload_max_filesize', '4000M');
15
ini_set('post_max_size', '4000M');
16
ini_set('max_execution_time', '80000');
17
ini_set('max_input_time', '80000');
18
*/
19
20
$debug = true;
21
22
define('WS_ERROR_SECRET_KEY', 1);
23
24
function return_error($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
    }
32
33
    return $fault;
34
}
35
36
function WSHelperVerifyKey($params)
37
{
38
    global $_configuration, $debug;
39
    if (is_array($params)) {
40
        $secret_key = $params['secret_key'];
41
    } else {
42
        $secret_key = $params;
43
    }
44
    //error_log(print_r($params,1));
45
    $check_ip = false;
46
    $ip_matches = false;
47
    $ip = trim($_SERVER['REMOTE_ADDR']);
48
    // if we are behind a reverse proxy, assume it will send the
49
    // HTTP_X_FORWARDED_FOR header and use this IP instead
50
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
51
        list($ip1) = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
52
        $ip = trim($ip1);
53
    }
54
    if ($debug) {
55
        error_log("ip: $ip");
56
    }
57
    // Check if a file that limits access from webservices exists and contains
58
    // the restraining check
59
    if (is_file('webservice-auth-ip.conf.php')) {
60
        include 'webservice-auth-ip.conf.php';
61
        if ($debug) {
62
            error_log("webservice-auth-ip.conf.php file included");
63
        }
64
        if (!empty($ws_auth_ip)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ws_auth_ip seems to never exist and therefore empty should always be true.
Loading history...
65
            $check_ip = true;
66
            $ip_matches = api_check_ip_in_range($ip, $ws_auth_ip);
67
            if ($debug) {
68
                error_log("ip_matches: $ip_matches");
69
            }
70
        }
71
    }
72
73
    if ($debug) {
74
        error_log("checkip ".intval($check_ip));
75
    }
76
77
    if ($check_ip) {
78
        $security_key = $_configuration['security_key'];
79
    } else {
80
        $security_key = $ip.$_configuration['security_key'];
81
        //error_log($secret_key.'-'.$security_key);
82
    }
83
    $result = api_is_valid_secret_key($secret_key, $security_key);
84
    //error_log($secret_key.'-'.$security_key);
85
    if ($debug) {
86
        error_log('WSHelperVerifyKey result: '.intval($result));
87
    }
88
89
    return $result;
90
}
91
92
// Create the server instance
93
$server = new soap_server();
94
//$server->soap_defencoding = 'UTF-8';
95
96
// Initialize WSDL support
97
$server->configureWSDL('WSGradebook', 'urn:WSGradebook');
98
99
$server->wsdl->addComplexType(
100
    'WSGradebookScoreParams',
101
    'complexType',
102
    'struct',
103
    'all',
104
    '',
105
    [
106
        'item_id' => [
107
            'name' => 'item_id',
108
            'type' => 'xsd:string',
109
        ],
110
        'item_type' => [
111
            'name' => 'item_type',
112
            'type' => 'xsd:string',
113
        ],
114
        'email' => [
115
            'name' => 'email',
116
            'type' => 'xsd:string',
117
        ],
118
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
119
    ]
120
);
121
122
$server->wsdl->addComplexType(
123
    'returnItemScore',
124
    'complexType',
125
    'struct',
126
    'sequence',
127
    '',
128
    [
129
        'score' => ['name' => 'score', 'type' => 'xsd:string'],
130
        'date' => ['name' => 'date', 'type' => 'xsd:string'],
131
        'counter' => ['name' => 'counter', 'type' => 'xsd:string'],
132
    ]
133
);
134
135
// Register the method to expose
136
$server->register(
137
    'WSGetGradebookUserItemScore', // method name
138
    ['params' => 'tns:WSGradebookScoreParams'], // input parameters
139
    ['return' => 'tns:returnItemScore'], // output parameters
140
    'urn:WSGradebook', // namespace
141
    'urn:WSGradebook#WSGetGradebookUserItemScore', // soapaction
142
    'rpc', // style
143
    'encoded', // use
144
    'get gradebook item user result'
145
);
146
147
/**
148
 * @param array $params
149
 *
150
 * @return int|string
151
 */
152
function WSGetGradebookUserItemScore($params)
153
{
154
    if (!WSHelperVerifyKey($params)) {
155
        return return_error(WS_ERROR_SECRET_KEY);
156
    }
157
158
    $itemId = $params['item_id'];
159
    $itemType = $params['item_type'];
160
    $email = $params['email'];
161
    $userInfo = api_get_user_info_from_email($email);
162
163
    if (empty($userInfo)) {
164
        return new soap_fault('Server', '', 'User not found');
165
    }
166
167
    $em = Database::getManager();
168
169
    $score = [];
170
    switch ($itemType) {
171
        case 'link':
172
            /** @var \Chamilo\CoreBundle\Entity\GradebookLink $link */
173
            $link = $em->getRepository('ChamiloCoreBundle:GradebookLink')->find($itemId);
174
            if (empty($link)) {
175
                return new soap_fault('Server', '', 'gradebook link not found');
176
            }
177
178
            $links = AbstractLink::load($link->getId());
179
            switch ($link->getType()) {
180
                case LINK_EXERCISE:
181
                    /** @var ExerciseLink $link */
182
                    foreach ($links as $link) {
183
                        $link->set_session_id($link->getCategory()->get_session_id());
184
                        $score = $link->calc_score($userInfo['user_id']);
185
                        break;
186
                    }
187
188
                    if (empty($score)) {
189
                        // If no score found then try exercises from base course.
190
                        /** @var ExerciseLink $link */
191
                        foreach ($links as $link) {
192
                            $link->checkBaseExercises = true;
193
                            $link->set_session_id($link->getCategory()->get_session_id());
194
                            $score = $link->calc_score($userInfo['user_id']);
195
                            break;
196
                        }
197
                    }
198
                    break;
199
                case LINK_STUDENTPUBLICATION:
200
                    /** @var StudentPublicationLink $link */
201
                    foreach ($links as $link) {
202
                        $link->set_session_id($link->getCategory()->get_session_id());
203
                        $score = $link->calc_score($userInfo['user_id']);
204
                        break;
205
                    }
206
                    break;
207
            }
208
            break;
209
        case 'evaluation':
210
            //$evaluation = $em->getRepository('ChamiloCoreBundle:GradebookEvaluation')->find($itemId);
211
            break;
212
    }
213
214
    if (!empty($score)) {
215
        $result = ExerciseLib::show_score($score[0], $score[1], false);
216
        $result = strip_tags($result);
217
218
        return ['score' => $result, 'date' => $score[2], 'counter' => $score[3]];
219
    }
220
221
    return new soap_fault('Server', '', 'Score not found');
222
}
223
224
$server->wsdl->addComplexType(
225
    'WSGradebookCategoryScoreParams',
226
    'complexType',
227
    'struct',
228
    'all',
229
    '',
230
    [
231
        'course_code' => [
232
            'name' => 'course_code',
233
            'type' => 'xsd:string',
234
        ],
235
        'session_id' => [
236
            'name' => 'session_id',
237
            'type' => 'xsd:string',
238
        ],
239
        'email' => [
240
            'name' => 'email',
241
            'type' => 'xsd:string',
242
        ],
243
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
244
    ]
245
);
246
247
// Register the method to expose
248
$server->register(
249
    'WSGetGradebookCategoryUserScore', // method name
250
    ['params' => 'tns:WSGradebookCategoryScoreParams'], // input parameters
251
    ['return' => 'xsd:string'], // output parameters
252
    'urn:WSGradebook', // namespace
253
    'urn:WSGradebook#WSGetGradebookCategoryUserScore', // soapaction
254
    'rpc', // style
255
    'encoded'
256
);
257
258
/**
259
 * @param array $params
260
 *
261
 * @return int|string
262
 */
263
function WSGetGradebookCategoryUserScore($params)
264
{
265
    if (!WSHelperVerifyKey($params)) {
266
        return return_error(WS_ERROR_SECRET_KEY);
267
    }
268
    $courseCode = $params['course_code'];
269
    $sessionId = (int) $params['session_id'];
270
    if (!empty($sessionId)) {
271
        $sessionInfo = api_get_session_info($sessionId);
272
        if (empty($sessionInfo)) {
273
            return new soap_fault('Server', '', 'Session not found');
274
        }
275
    }
276
277
    $email = $params['email'];
278
    $userInfo = api_get_user_info_from_email($email);
279
280
    if (empty($userInfo)) {
281
        return new soap_fault('Server', '', 'User not found');
282
    }
283
    $userId = $userInfo['user_id'];
284
    $courseInfo = api_get_course_info($courseCode);
285
    if (empty($courseInfo)) {
286
        return new soap_fault('Server', '', 'Course not found');
287
    }
288
289
    $cats = Category::load(null,
290
        null,
291
        $courseCode,
292
        null,
293
        null,
294
        $sessionId
295
    );
296
297
    /** @var Category $category */
298
    $category = isset($cats[0]) ? $cats[0] : null;
299
    $scorecourse_display = null;
300
301
    if (!empty($category)) {
302
        $categoryCourse = Category::load($category->get_id());
303
        $category = isset($categoryCourse[0]) ? $categoryCourse[0] : null;
304
        $allevals = $category->get_evaluations($userId, true);
0 ignored issues
show
Bug introduced by
The method get_evaluations() does not exist on null. ( Ignorable by Annotation )

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

304
        /** @scrutinizer ignore-call */ 
305
        $allevals = $category->get_evaluations($userId, true);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
305
        $alllinks = $category->get_links($userId, true);
306
307
        $allEvalsLinks = array_merge($allevals, $alllinks);
308
        $main_weight = $category->get_weight();
309
        $scoredisplay = ScoreDisplay::instance();
310
        $item_value_total = 0;
311
        /** @var AbstractLink $item */
312
        foreach ($allEvalsLinks as $item) {
313
            $item->set_session_id($sessionId);
314
            $item->set_course_code($courseCode);
315
            $score = $item->calc_score($userId);
316
            if (!empty($score)) {
317
                $divide = $score[1] == 0 ? 1 : $score[1];
318
                $item_value = $score[0] / $divide * $item->get_weight();
319
                $item_value_total += $item_value;
320
            }
321
        }
322
323
        $item_total = $main_weight;
324
        $total_score = [$item_value_total, $item_total];
325
        $score = $scoredisplay->display_score($total_score, SCORE_DIV_PERCENT);
326
        $score = strip_tags($score);
327
328
        return $score;
329
    }
330
331
    if (empty($category)) {
332
        return new soap_fault('Server', '', 'Gradebook category not found');
333
    }
334
335
    return new soap_fault('Server', '', 'Score not found');
336
}
337
338
$server->wsdl->addComplexType(
339
    'WSLpProgressParams',
340
    'complexType',
341
    'struct',
342
    'all',
343
    '',
344
    [
345
        'course_code' => [
346
            'name' => 'course_code',
347
            'type' => 'xsd:string',
348
        ],
349
        'session_id' => [
350
            'name' => 'session_id',
351
            'type' => 'xsd:string',
352
        ],
353
        'lp_id' => [
354
            'name' => 'lp_id',
355
            'type' => 'xsd:string',
356
        ],
357
        'email' => [
358
            'name' => 'email',
359
            'type' => 'xsd:string',
360
        ],
361
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
362
    ]
363
);
364
365
// Register the method to expose
366
$server->register(
367
    'WSGetLpProgress', // method name
368
    ['params' => 'tns:WSLpProgressParams'], // input parameters
369
    ['return' => 'xsd:string'], // output parameters
370
    'urn:WSGradebook', // namespace
371
    'urn:WSGradebook#WSGetLpProgress', // soapaction
372
    'rpc', // style
373
    'encoded'
374
);
375
376
/**
377
 * @param array $params
378
 *
379
 * @return int|string
380
 */
381
function WSGetLpProgress($params)
382
{
383
    if (!WSHelperVerifyKey($params)) {
384
        return return_error(WS_ERROR_SECRET_KEY);
385
    }
386
387
    $courseCode = $params['course_code'];
388
    $courseInfo = api_get_course_info($courseCode);
389
    if (empty($courseInfo)) {
390
        return new soap_fault('Server', '', 'Course not found');
391
    }
392
393
    $sessionId = (int) $params['session_id'];
394
    if (!empty($sessionId)) {
395
        $sessionInfo = api_get_session_info($sessionId);
396
        if (empty($sessionInfo)) {
397
            return new soap_fault('Server', '', 'Session not found');
398
        }
399
    }
400
401
    $email = $params['email'];
402
    $userInfo = api_get_user_info_from_email($email);
403
    $userId = $userInfo['user_id'];
404
405
    if (empty($userInfo)) {
406
        return new soap_fault('Server', '', 'User not found');
407
    }
408
409
    $lpId = $params['lp_id'];
410
    $lp = new learnpath($courseCode, $lpId, $userId);
411
412
    if (empty($lp)) {
413
        return new soap_fault('Server', '', 'LP not found');
414
    }
415
416
    return $lp->progress_db;
417
}
418
419
$server->wsdl->addComplexType(
420
    'WSAssignSkillParams',
421
    'complexType',
422
    'struct',
423
    'all',
424
    '',
425
    [
426
        'skill_id' => [
427
            'name' => 'skill_id',
428
            'type' => 'xsd:string',
429
        ],
430
        'level' => [
431
            'name' => 'level',
432
            'type' => 'xsd:string',
433
        ],
434
        'justification' => [
435
            'name' => 'justification',
436
            'type' => 'xsd:string',
437
        ],
438
        'email' => [
439
            'name' => 'email',
440
            'type' => 'xsd:string',
441
        ],
442
        'author_email' => [
443
            'name' => 'author_email',
444
            'type' => 'xsd:string',
445
        ],
446
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
447
    ]
448
);
449
450
// Register the method to expose
451
$server->register(
452
    'WSAssignSkill', // method name
453
    ['params' => 'tns:WSAssignSkillParams'], // input parameters
454
    ['return' => 'xsd:string'], // output parameters
455
    'urn:WSGradebook', // namespace
456
    'urn:WSGradebook:WSAssignSkill', // soapaction
457
    'rpc', // style
458
    'encoded'
459
);
460
461
/**
462
 * @param array $params
463
 *
464
 * @return int|string
465
 */
466
function WSAssignSkill($params)
467
{
468
    if (!WSHelperVerifyKey($params)) {
469
        return return_error(WS_ERROR_SECRET_KEY);
470
    }
471
472
    $em = Database::getManager();
473
    $skillManager = new SkillManager();
474
475
    $skillId = isset($params['skill_id']) ? $params['skill_id'] : 0;
476
    $skillRepo = $em->getRepository('ChamiloCoreBundle:Skill');
477
    $skill = $skillRepo->find($skillId);
478
479
    if (empty($skill)) {
480
        return new soap_fault('Server', '', 'Skill not found');
481
    }
482
483
    $justification = $params['justification'];
484
485
    if (strlen($justification) < 10) {
486
        return new soap_fault('Server', '', 'Justification smaller than 10 chars');
487
    }
488
489
    $level = (int) $params['level'];
490
491
    $email = $params['email'];
492
    $userInfo = api_get_user_info_from_email($email);
493
494
    if (empty($userInfo)) {
495
        return new soap_fault('Server', '', 'User not found');
496
    }
497
498
    $email = $params['author_email'];
499
    $authorInfo = api_get_user_info_from_email($email);
500
501
    if (empty($authorInfo)) {
502
        return new soap_fault('Server', '', 'Author not found');
503
    }
504
505
    $userId = $userInfo['user_id'];
506
    $user = api_get_user_entity($userId);
507
    $skillUser = $skillManager->addSkillToUserBadge(
508
        $user,
509
        $skill,
510
        $level,
511
        $justification,
512
        $authorInfo['id']
513
    );
514
515
    if (!empty($skillUser)) {
516
        return 1;
517
    }
518
519
    return 0;
520
}
521
522
// Use the request to (try to) invoke the service
523
$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents('php://input');
524
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
525
526
// If you send your data in utf8 then this value must be false.
527
$decodeUTF8 = api_get_setting('registration.soap.php.decode_utf8');
528
if ($decodeUTF8 === 'true') {
529
    $server->decode_utf8 = true;
530
} else {
531
    $server->decode_utf8 = false;
532
}
533
$server->service($HTTP_RAW_POST_DATA);
534