WSHelperVerifyKey()   F
last analyzed

Complexity

Conditions 11
Paths 448

Size

Total Lines 54
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 32
nc 448
nop 1
dl 0
loc 54
rs 3.9166
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * @package chamilo.webservices
6
 */
7
require_once __DIR__.'/../inc/global.inc.php';
8
9
api_protect_webservices();
10
11
ini_set('memory_limit', -1);
12
/*
13
ini_set('upload_max_filesize', '4000M');
14
ini_set('post_max_size', '4000M');
15
ini_set('max_execution_time', '80000');
16
ini_set('max_input_time', '80000');
17
*/
18
19
$debug = true;
20
21
define('WS_ERROR_SECRET_KEY', 1);
22
23
function return_error($code)
24
{
25
    $fault = null;
26
    switch ($code) {
27
        case WS_ERROR_SECRET_KEY:
28
            $fault = new soap_fault('Server', '', 'Secret key is not correct or params are not correctly set');
29
            break;
30
    }
31
32
    return $fault;
33
}
34
35
function WSHelperVerifyKey($params)
36
{
37
    global $_configuration, $debug;
38
    if (is_array($params)) {
39
        $secret_key = $params['secret_key'];
40
    } else {
41
        $secret_key = $params;
42
    }
43
    //error_log(print_r($params,1));
44
    $check_ip = false;
45
    $ip_matches = false;
46
    $ip = trim($_SERVER['REMOTE_ADDR']);
47
    // if we are behind a reverse proxy, assume it will send the
48
    // HTTP_X_FORWARDED_FOR header and use this IP instead
49
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
50
        list($ip1) = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
51
        $ip = trim($ip1);
52
    }
53
    if ($debug) {
54
        error_log("ip: $ip");
55
    }
56
    // Check if a file that limits access from webservices exists and contains
57
    // the restraining check
58
    if (is_file('webservice-auth-ip.conf.php')) {
59
        include 'webservice-auth-ip.conf.php';
60
        if ($debug) {
61
            error_log("webservice-auth-ip.conf.php file included");
62
        }
63
        if (!empty($ws_auth_ip)) {
64
            $check_ip = true;
65
            $ip_matches = api_check_ip_in_range($ip, $ws_auth_ip);
66
            if ($debug) {
67
                error_log("ip_matches: $ip_matches");
68
            }
69
        }
70
    }
71
72
    if ($debug) {
73
        error_log("checkip ".intval($check_ip));
74
    }
75
76
    if ($check_ip) {
77
        $security_key = $_configuration['security_key'];
78
    } else {
79
        $security_key = $ip.$_configuration['security_key'];
80
        //error_log($secret_key.'-'.$security_key);
81
    }
82
    $result = api_is_valid_secret_key($secret_key, $security_key);
83
    //error_log($secret_key.'-'.$security_key);
84
    if ($debug) {
85
        error_log('WSHelperVerifyKey result: '.intval($result));
86
    }
87
88
    return $result;
89
}
90
91
// Create the server instance
92
$server = new soap_server();
93
94
//$server->soap_defencoding = 'UTF-8';
95
96
// Initialize WSDL support
97
$server->configureWSDL('WSLP', 'urn:WSLP');
98
99
$server->wsdl->addComplexType(
100
    'params',
101
    'complexType',
102
    'struct',
103
    'all',
104
    '',
105
    [
106
        'course_id_name' => [
107
            'name' => 'course_id_name',
108
            'type' => 'xsd:string',
109
        ],
110
        'course_id_value' => [
111
            'name' => 'course_id_name',
112
            'type' => 'xsd:string',
113
        ],
114
        'session_id_name' => [
115
            'name' => 'session_id_name',
116
            'type' => 'xsd:string',
117
        ],
118
        'session_id_value' => [
119
            'name' => 'session_id_value',
120
            'type' => 'xsd:string',
121
        ],
122
        'file_data' => ['name' => 'file', 'type' => 'xsd:string'],
123
        'filename' => ['name' => 'filename', 'type' => 'xsd:string'],
124
        'lp_name' => ['name' => 'lp_name', 'type' => 'xsd:string'],
125
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
126
    ]
127
);
128
129
// Register the method to expose
130
$server->register(
131
    'WSImportLP', // method name
132
    ['params' => 'tns:params'], // input parameters
133
    ['return' => 'xsd:string'], // output parameters
134
    'urn:WSLP', // namespace
135
    'urn:WSLP#WSImportLP', // soapaction
136
    'rpc', // style
137
    'encoded', // use
138
    'This service adds users'                                               // documentation
139
);
140
141
/**
142
 * @param array $params
143
 *
144
 * @return int|string
145
 */
146
function WSImportLP($params)
147
{
148
    global $debug;
149
    if (!WSHelperVerifyKey($params)) {
150
        return return_error(WS_ERROR_SECRET_KEY);
151
    }
152
    if ($debug) {
153
        error_log('WSImportLP');
154
    }
155
156
    $courseIdName = $params['course_id_name'];
157
    $courseIdValue = $params['course_id_value'];
158
    $sessionIdName = isset($params['session_id_name']) ? $params['session_id_name'] : null;
159
    $sessionIdValue = isset($params['session_id_value']) ? $params['session_id_value'] : null;
160
161
    $lpName = $params['lp_name'];
162
163
    $courseInfo = CourseManager::getCourseInfoFromOriginalId(
164
        $courseIdValue,
165
        $courseIdName
166
    );
167
    $courseId = $courseInfo['real_id'];
168
169
    if (empty($courseInfo)) {
170
        if ($debug) {
171
            error_log('Course not found');
172
        }
173
174
        return 'Course not found';
175
    }
176
177
    $sessionId = 0;
178
    if (!empty($sessionIdName) && !empty($sessionIdValue)) {
179
        $sessionId = SessionManager::getSessionIdFromOriginalId(
180
            $sessionIdValue,
181
            $sessionIdName
182
        );
183
184
        if (empty($sessionId)) {
185
            if ($debug) {
186
                error_log('Session not found');
187
            }
188
189
            return 'Session not found';
190
        }
191
    }
192
193
    $proximity = 'local';
194
    $maker = 'Scorm';
195
    $maxScore = ''; //$_REQUEST['use_max_score']
196
197
    $oScorm = new scorm($courseInfo['code']);
198
    $fileData = base64_decode($params['file_data']);
199
200
    $uniqueFile = uniqid();
201
    $userId = 1; // admin
202
    $filePath = api_get_path(SYS_ARCHIVE_PATH).$uniqueFile;
203
    file_put_contents($filePath, $fileData);
204
205
    $fileName = $params['filename'];
206
207
    $fileInfo = [
208
        'tmp_name' => $filePath,
209
        'name' => $fileName,
210
    ];
211
212
    $manifest = $oScorm->import_package($fileInfo, '', $courseInfo);
213
214
    if (!$manifest) {
215
        if ($debug) {
216
            error_log('manifest.xml file not found');
217
        }
218
219
        return 'manifest.xml file not found';
220
    }
221
222
    $manifestData = $oScorm->parse_manifest($manifest);
223
224
    if (!empty($manifestData)) {
225
        $oScorm->import_manifest(
226
            $courseInfo['code'],
227
            $maxScore,
228
            $sessionId,
229
            $userId
230
        );
231
        $oScorm->set_name($lpName);
232
        $oScorm->set_proximity($proximity, $courseId);
233
        $oScorm->set_maker($maker, $courseId);
234
        //$oScorm->set_jslib('scorm_api.php');
235
236
        if ($debug) {
237
            error_log('scorm was added');
238
        }
239
240
        return 1;
241
    } else {
242
        if ($debug) {
243
            error_log('manifest data empty');
244
        }
245
246
        return 'manifest data empty';
247
    }
248
}
249
250
$server->wsdl->addComplexType(
251
    'paramsGetLpList',
252
    'complexType',
253
    'struct',
254
    'all',
255
    '',
256
    [
257
        'course_id_name' => [
258
            'name' => 'course_id_name',
259
            'type' => 'xsd:string',
260
        ],
261
        'course_id_value' => [
262
            'name' => 'course_id_name',
263
            'type' => 'xsd:string',
264
        ],
265
        'session_id_name' => [
266
            'name' => 'session_id_name',
267
            'type' => 'xsd:string',
268
        ],
269
        'session_id_value' => [
270
            'name' => 'session_id_value',
271
            'type' => 'xsd:string',
272
        ],
273
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
274
    ]
275
);
276
277
$server->wsdl->addComplexType(
278
    'lpListItem',
279
    'complexType',
280
    'struct',
281
    'all',
282
    '',
283
    [
284
        'id' => ['name' => 'id', 'type' => 'xsd:string'],
285
        'name' => ['name' => 'name', 'type' => 'xsd:string'],
286
    ]
287
);
288
289
$server->wsdl->addComplexType(
290
    'lpList',
291
    'complexType',
292
    'array',
293
    '',
294
    'SOAP-ENC:Array',
295
    [],
296
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:lpListItem[]']],
297
    'tns:lpListItem'
298
);
299
300
// Register the method to expose
301
$server->register(
302
    'WSGetLpList', // method name
303
    ['params' => 'tns:paramsGetLpList'], // input parameters
304
    ['return' => 'tns:lpList'], // output parameters
305
    'urn:WSLP', // namespace
306
    'urn:WSLP#WSGetLpList', // soapaction
307
    'rpc', // style
308
    'encoded', // use
309
    'This service adds users'                                               // documentation
310
);
311
312
/**
313
 * @param array $params
314
 *
315
 * @return int|string
316
 */
317
function WSGetLpList($params)
318
{
319
    global $debug;
320
    if (!WSHelperVerifyKey($params)) {
321
        return return_error(WS_ERROR_SECRET_KEY);
322
    }
323
324
    $courseIdName = $params['course_id_name'];
325
    $courseIdValue = $params['course_id_value'];
326
327
    $sessionIdName = isset($params['session_id_name']) ? $params['session_id_name'] : null;
328
    $sessionIdValue = isset($params['session_id_value']) ? $params['session_id_value'] : null;
329
330
    $courseInfo = CourseManager::getCourseInfoFromOriginalId(
331
        $courseIdValue,
332
        $courseIdName
333
    );
334
335
    if (empty($courseInfo)) {
336
        if ($debug) {
337
            error_log("Course not found: $courseIdName : $courseIdValue");
338
        }
339
340
        return 'Course not found';
341
    }
342
343
    $courseId = $courseInfo['real_id'];
344
345
    $sessionId = 0;
346
    if (!empty($sessionIdName) && !empty($sessionIdValue)) {
347
        $sessionId = SessionManager::get_session_id_from_original_id(
348
            $sessionIdValue,
349
            $sessionIdName
350
        );
351
352
        if (empty($sessionId)) {
353
            if ($debug) {
354
                error_log('Session not found');
355
            }
356
357
            return 'Session not found';
358
        }
359
    }
360
361
    $list = new LearnpathList(null, $courseInfo, $sessionId);
362
    $flatList = $list->get_flat_list();
363
    $result = [];
364
    foreach ($flatList as $id => $lp) {
365
        $result[] = [
366
            'id' => $id,
367
            'name' => $lp['lp_name'],
368
        ];
369
    }
370
371
    return $result;
372
}
373
374
$server->wsdl->addComplexType(
375
    'paramsDeleteLp',
376
    'complexType',
377
    'struct',
378
    'all',
379
    '',
380
    [
381
        'course_id_name' => [
382
            'name' => 'course_id_name',
383
            'type' => 'xsd:string',
384
        ],
385
        'course_id_value' => [
386
            'name' => 'course_id_name',
387
            'type' => 'xsd:string',
388
        ],
389
        'lp_id' => [
390
            'name' => 'lp_id',
391
            'type' => 'xsd:string',
392
        ],
393
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
394
    ]
395
);
396
397
// Register the method to expose
398
$server->register(
399
    'WSDeleteLp', // method name
400
    ['params' => 'tns:paramsDeleteLp'], // input parameters
401
    ['return' => 'xsd:string'], // output parameters
402
    'urn:WSLP', // namespace
403
    'urn:WSLP#WSDeleteLp', // soapaction
404
    'rpc', // style
405
    'encoded', // use
406
    'This service deletes a LP'                                               // documentation
407
);
408
409
/**
410
 * @param array $params
411
 *
412
 * @return int|string
413
 */
414
function WSDeleteLp($params)
415
{
416
    global $debug;
417
    if (!WSHelperVerifyKey($params)) {
418
        return return_error(WS_ERROR_SECRET_KEY);
419
    }
420
421
    $courseIdName = $params['course_id_name'];
422
    $courseIdValue = $params['course_id_value'];
423
    $lpId = $params['lp_id'];
424
425
    $sessionIdName = isset($params['session_id_name']) ? $params['session_id_name'] : null;
426
    $sessionIdValue = isset($params['session_id_value']) ? $params['session_id_value'] : null;
427
428
    $courseInfo = CourseManager::getCourseInfoFromOriginalId(
429
        $courseIdValue,
430
        $courseIdName
431
    );
432
433
    if (empty($courseInfo)) {
434
        if ($debug) {
435
            error_log("Course not found: $courseIdName : $courseIdValue");
436
        }
437
438
        return 'Course not found';
439
    }
440
    $courseId = $courseInfo['real_id'];
441
    $courseCode = $courseInfo['code'];
442
443
    $sessionId = 0;
444
445
    /*
446
    if (!empty($sessionIdName) && !empty($sessionIdValue)) {
447
        $sessionId = SessionManager::get_session_id_from_original_id(
448
            $sessionIdValue,
449
            $sessionIdName
450
        );
451
452
        if (empty($sessionId)) {
453
454
            if ($debug) error_log('Session not found');
455
            return 'Session not found';
456
        }
457
    }
458
    */
459
460
    $lp = new learnpath($courseCode, $lpId, null);
461
    if ($lp) {
0 ignored issues
show
introduced by
$lp is of type learnpath, thus it always evaluated to true.
Loading history...
462
        if ($debug) {
463
            error_log("LP deleted $lpId");
464
        }
465
466
        $course_dir = $courseInfo['directory'].'/document';
467
        $sys_course_path = api_get_path(SYS_COURSE_PATH);
468
        $base_work_dir = $sys_course_path.$course_dir;
469
470
        $items = $lp->get_flat_ordered_items_list($lpId, 0, $courseId);
471
472
        if (!empty($items)) {
473
            /** @var $item learnpathItem */
474
            foreach ($items as $itemId) {
475
                $item = new learnpathItem($itemId, null, $courseId);
476
477
                if ($item) {
478
                    $documentId = $item->get_path();
479
480
                    if ($debug) {
481
                        error_log("lp item id found #$itemId");
482
                    }
483
484
                    $documentInfo = DocumentManager::get_document_data_by_id(
485
                        $documentId,
486
                        $courseInfo['code'],
487
                        false,
488
                        $sessionId
489
                    );
490
491
                    if (!empty($documentInfo)) {
492
                        if ($debug) {
493
                            error_log("Document id deleted #$documentId");
494
                        }
495
                        DocumentManager::delete_document(
496
                            $courseInfo,
497
                            null,
498
                            $base_work_dir,
499
                            $sessionId,
500
                            $documentId
501
                        );
502
                    } else {
503
                        if ($debug) {
504
                            error_log("No document found for id #$documentId");
505
                        }
506
                    }
507
                } else {
508
                    if ($debug) {
509
                        error_log("Document not found #$itemId");
510
                    }
511
                }
512
            }
513
        }
514
515
        $lp->delete($courseInfo, $lpId, 'remove');
516
517
        return 1;
518
    }
519
520
    return 0;
521
}
522
523
$server->wsdl->addComplexType(
524
    'lpItem',
525
    'complexType',
526
    'struct',
527
    'all',
528
    '',
529
    [
530
        'data' => ['name' => 'data', 'type' => 'xsd:string'],
531
        'title' => ['name' => 'title', 'type' => 'xsd:string'],
532
        'filename' => ['name' => 'filename', 'type' => 'xsd:string'],
533
    ]
534
);
535
536
$server->wsdl->addComplexType(
537
    'lpItemList',
538
    'complexType',
539
    'array',
540
    '',
541
    'SOAP-ENC:Array',
542
    [],
543
    [['ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:lpItem[]']],
544
    'tns:lpItem'
545
);
546
547
$server->wsdl->addComplexType(
548
    'paramsCreateLp',
549
    'complexType',
550
    'struct',
551
    'all',
552
    '',
553
    [
554
        'course_id_name' => [
555
            'name' => 'course_id_name',
556
            'type' => 'xsd:string',
557
        ],
558
        'course_id_value' => [
559
            'name' => 'course_id_name',
560
            'type' => 'xsd:string',
561
        ],
562
        /*'session_id_name' => array(
563
            'name' => 'session_id_name',
564
            'type' => 'xsd:string',
565
        ),
566
        'session_id_value' => array(
567
            'name' => 'session_id_value',
568
            'type' => 'xsd:string',
569
        ),*/
570
        'lp_name' => [
571
            'name' => 'lp_name',
572
            'type' => 'xsd:string',
573
        ],
574
        'lp_item_list' => [
575
            'name' => 'lp_item_list',
576
            'type' => 'tns:lpItemList',
577
        ],
578
        'secret_key' => ['name' => 'secret_key', 'type' => 'xsd:string'],
579
    ]
580
);
581
582
// Register the method to expose
583
$server->register(
584
    'WSCreateLp', // method name
585
    ['params' => 'tns:paramsCreateLp'], // input parameters
586
    ['return' => 'xsd:string'], // output parameters
587
    'urn:WSLP', // namespace
588
    'urn:WSLP#WSCreateLp', // soapaction
589
    'rpc', // style
590
    'encoded', // use
591
    'This service creates a LP'                                               // documentation
592
);
593
594
/**
595
 * @param array $params
596
 *
597
 * @return soap_fault|null
598
 */
599
function WSCreateLp($params)
600
{
601
    global $debug;
602
    if (!WSHelperVerifyKey($params)) {
603
        return return_error(WS_ERROR_SECRET_KEY);
604
    }
605
606
    if ($debug) {
607
        error_log('WSCreateLp');
608
    }
609
610
    $courseIdName = $params['course_id_name'];
611
    $courseIdValue = $params['course_id_value'];
612
    $lpName = $params['lp_name'];
613
    $lpItemList = $params['lp_item_list'];
614
615
    /*$sessionIdName = isset($params['session_id_name']) ? $params['session_id_name'] : null;
616
    $sessionIdValue = isset($params['session_id_value']) ? $params['session_id_value'] : null;*/
617
618
    $courseInfo = CourseManager::getCourseInfoFromOriginalId(
619
        $courseIdValue,
620
        $courseIdName
621
    );
622
623
    if (empty($courseInfo)) {
624
        if ($debug) {
625
            error_log('Course not found');
626
        }
627
    }
628
629
    $userId = 1;
630
    $courseId = $courseInfo['real_id'];
631
    $courseCode = $courseInfo['code'];
632
633
    /*$sessionId = 0;
634
    if (!empty($sessionIdName) && !empty($sessionIdValue)) {
635
        $sessionId = SessionManager::get_session_id_from_original_id(
636
            $sessionIdValue,
637
            $sessionIdName
638
        );
639
640
        if (empty($sessionId)) {
641
642
            if ($debug) {
643
                error_log('Session not found');
644
            }
645
646
            return 'Session not found';
647
        }
648
    }*/
649
    if ($debug) {
650
        error_log('add_lp');
651
    }
652
    $lpId = learnpath::add_lp(
653
        $courseCode,
654
        $lpName,
655
        '',
656
        'chamilo',
657
        'manual',
658
        '',
659
        '',
660
        '',
661
        0,
662
        $userId
663
    );
664
665
    if ($lpId) {
666
        if ($debug) {
667
            error_log('LP created');
668
        }
669
670
        $lp = new learnpath($courseCode, $lpId, null);
671
672
        $previousId = 0;
673
        foreach ($lpItemList as $lpItem) {
674
            $info = pathinfo($lpItem['filename']);
675
            $extension = $info['extension'];
676
            $data = base64_decode($lpItem['data']);
677
678
            if ($debug) {
679
                error_log('create_document: '.$info['filename']);
680
            }
681
682
            $documentId = $lp->create_document(
683
                $courseInfo,
684
                $data,
685
                $info['filename'],
686
                $extension,
687
                0,
688
                $userId
689
            );
690
691
            if ($documentId) {
692
                if ($debug) {
693
                    error_log("Document created $documentId");
694
695
                    $itemId = $lp->add_item(
696
                        null,
697
                        $previousId,
698
                        'document',
699
                        $documentId,
700
                        $lpItem['title'],
701
                        '',
702
                        '',
703
                        0,
704
                        $userId
705
                    );
706
707
                    $previousId = $itemId;
708
709
                    if ($itemId) {
710
                        if ($debug) {
711
                            error_log("Item added");
712
                        }
713
                    } else {
714
                        if ($debug) {
715
                            error_log("Item not added");
716
                        }
717
                    }
718
                }
719
            } else {
720
                if ($debug) {
721
                    error_log("Document NOT created");
722
                }
723
            }
724
        }
725
726
        return 1;
727
    } else {
728
        if ($debug) {
729
            error_log('LP not created');
730
        }
731
    }
732
733
    return 0;
734
}
735
736
// Use the request to (try to) invoke the service
737
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
738
// If you send your data in utf8 then this value must be false.
739
if (isset($_configuration['registration.soap.php.decode_utf8'])) {
740
    if ($_configuration['registration.soap.php.decode_utf8']) {
741
        $server->decode_utf8 = true;
742
    } else {
743
        $server->decode_utf8 = false;
744
    }
745
}
746
$server->service($HTTP_RAW_POST_DATA);
747