Passed
Push — master ( 447a4c...2f567c )
by Julito
09:40
created

WSAssignSkill()   B

Complexity

Conditions 8
Paths 13

Size

Total Lines 54
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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