Test Setup Failed
Push — master ( f71949...6c6bd7 )
by Julito
55:21
created

Sepe   D

Complexity

Total Complexity 146

Size/Duplication

Total Lines 1205
Duplicated Lines 20.25 %

Coupling/Cohesion

Components 2
Dependencies 1

Importance

Changes 0
Metric Value
dl 244
loc 1205
rs 4.4102
c 0
b 0
f 0
wmc 146
lcom 2
cbo 1

9 Methods

Rating   Name   Duplication   Size   Complexity  
C crearCentro() 0 90 11
B obtenerDatosCentro() 0 88 3
D obtenerAccion() 83 395 52
B obtenerListaAcciones() 0 50 5
B eliminarAccion() 0 45 4
A undoFixDate() 11 11 3
A fixDate() 11 11 3
A checkAuth() 0 7 2
F crearAccion() 139 481 63

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Sepe often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Sepe, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Class Sepe
5
 */
6
class Sepe
7
{
8
    
9
    /**
10
     * @param crearCentroInput[] $crearCentroInput
11
     *
12
     * @return array
13
     */
14
    public function crearCentro($crearCentroInput)
15
    {
16
        /* Tracking log */
17
        $tableLog = Database::get_main_table('plugin_sepe_log');
18
        $paramsLog = array(
19
            'ip' => $_SERVER['REMOTE_ADDR'],
20
            'action' => "crearCentro",
21
            'fecha' => date("Y-m-d H:i:s")
22
        );
23
        Database::insert($tableLog, $paramsLog);
24
        /* End tracking log */
25
        
26
        // Code
27
        $crearCentroInput = $crearCentroInput->DATOS_IDENTIFICATIVOS;
28
        $centerOrigin = $crearCentroInput->ID_CENTRO->ORIGEN_CENTRO;
29
        $centerCode = $crearCentroInput->ID_CENTRO->CODIGO_CENTRO;
30
        $centerName = $crearCentroInput->NOMBRE_CENTRO;
31
        $urlPlatform = $crearCentroInput->URL_PLATAFORMA;
32
        $urlTracking = $crearCentroInput->URL_SEGUIMIENTO;
33
        $phone = $crearCentroInput->TELEFONO;
34
        $mail = $crearCentroInput->EMAIL;
35
36
        if (empty($centerOrigin) ||
37
            empty($centerCode) ||
38
            empty($centerName) ||
39
            empty($urlPlatform) ||
40
            empty($urlTracking) ||
41
            empty($phone) ||
42
            empty($mail)
43
        ) {
44
            error_log('no data');
45
            return array(
46
                "RESPUESTA_DATOS_CENTRO" => array(
47
                    "CODIGO_RETORNO" => "2",
48
                    "ETIQUETA_ERROR" => "Error en parametro",
49
                    "DATOS_IDENTIFICATIVOS" => $crearCentroInput
50
                )
51
            );
52
        }
53
54
        $table = Database::get_main_table('plugin_sepe_center');
55
56
        // Check if exists data in table
57
        if (Database::count_rows($table) > 0) {
0 ignored issues
show
Deprecated Code introduced by
The method Database::count_rows() has been deprecated.

This method has been deprecated.

Loading history...
58
            // Check if exists actions
59
            $table_actions = Database::get_main_table('plugin_sepe_actions');
60
            if (Database::count_rows($table_actions) > 0) {
0 ignored issues
show
Deprecated Code introduced by
The method Database::count_rows() has been deprecated.

This method has been deprecated.

Loading history...
61
                return array(
62
                    "RESPUESTA_DATOS_CENTRO" => array(
63
                        "CODIGO_RETORNO" => "1",
64
                        "ETIQUETA_ERROR" => "Centro con acciones",
65
                        "DATOS_IDENTIFICATIVOS" => $crearCentroInput
66
                    )
67
                );
68
            } else {
69
                $sql = "DELETE FROM $table";
70
                Database::query($sql);
71
            }
72
        }
73
74
        $params = array(
75
            'center_origin' => $centerOrigin,
76
            'center_code' => $centerCode,
77
            'center_name' => $centerName,
78
            'url' => $urlPlatform,
79
            'tracking_url' => $urlTracking,
80
            'phone' => $phone,
81
            'mail' => $mail,
82
        );
83
84
        $id = Database::insert($table, $params);
85
86
        if (empty($id)) {
87
            return array(
88
                "RESPUESTA_DATOS_CENTRO" => array(
89
                    "CODIGO_RETORNO" => "-1",
90
                    "ETIQUETA_ERROR" => "Problema base de datos",
91
                    "DATOS_IDENTIFICATIVOS" => $crearCentroInput
92
                )
93
            );
94
        } else {
95
            return array(
96
                "RESPUESTA_DATOS_CENTRO" => array(
97
                    "CODIGO_RETORNO" => "0",
98
                    "ETIQUETA_ERROR" => "Correcto",
99
                    "DATOS_IDENTIFICATIVOS" => $crearCentroInput
100
                )
101
            );
102
        }
103
    }
104
105
    /**
106
     *
107
     * @return array
108
     */
109
    public function obtenerDatosCentro()
110
    {
111
        /* Tracking Log */
112
        $tableLog = Database::get_main_table('plugin_sepe_log');
113
        $paramsLog = array(
114
            'ip' => $_SERVER['REMOTE_ADDR'],
115
            'action' => "obtenerDatosCentro",
116
            'fecha' => date("Y-m-d H:i:s")
117
        );
118
        Database::insert($tableLog, $paramsLog);
119
        /* End tracking log */
120
        
121
        // Code
122
        $table = Database::get_main_table('plugin_sepe_center');
123
124
        // Comprobamos si existen datos almacenados previamente
125
        if (Database::count_rows($table) > 0) {
0 ignored issues
show
Deprecated Code introduced by
The method Database::count_rows() has been deprecated.

This method has been deprecated.

Loading history...
126
            //Hay datos en la tabla;
127
            $sql = "SELECT * FROM $table;";
128
            $rs = Database::query($sql);
129
            if (!$rs) {
130
                return array(
131
                    "CODIGO_RETORNO" => "-1",
132
                    "ETIQUETA_ERROR" => "Problema acceso base de datos",
133
                    "DATOS_IDENTIFICATIVOS" => ''
134
                );
135
            } else {
136
                $row = Database::fetch_assoc($rs);
137
                $centerOrigin = $row['center_origin'];
138
                $centerCode = $row['center_code'];
139
                $centerName = $row['center_name'];
140
                $urlPlatform = $row['url'];
141
                $urlTracking = $row['tracking_url'];
142
                $phone = $row['phone'];
143
                $mail = $row['mail'];
144
145
                $data = new stdClass();
146
                $data->ID_CENTRO = new stdClass();
147
                $data->ID_CENTRO->ORIGEN_CENTRO = $centerOrigin;
148
                $data->ID_CENTRO->CODIGO_CENTRO = $centerCode;
149
                $data->NOMBRE_CENTRO = $centerName;
150
                $data->URL_PLATAFORMA = $urlPlatform;
151
                $data->URL_SEGUIMIENTO = $urlTracking;
152
                $data->TELEFONO = $phone;
153
                $data->EMAIL = $mail;
154
155
                $obj = new stdClass();
156
                $obj->CODIGO_RETORNO = 0;
157
                $obj->ETIQUETA_ERROR = 'Correcto';
158
                $obj->DATOS_IDENTIFICATIVOS = new SoapVar($data, SOAP_ENC_OBJECT);
159
160
                $result = new stdClass();
161
                $result->RESPUESTA_DATOS_CENTRO = new SoapVar($obj, SOAP_ENC_OBJECT);
162
163
                return $result;
164
            }
165
        } else {
166
            $data = new stdClass();
167
            $data->ID_CENTRO = new stdClass();
168
            $data->ID_CENTRO->ORIGEN_CENTRO = '';
169
            $data->ID_CENTRO->CODIGO_CENTRO = '';
170
            $data->NOMBRE_CENTRO = '';
171
            $data->URL_PLATAFORMA = '';
172
            $data->URL_SEGUIMIENTO = '';
173
            $data->TELEFONO = '';
174
            $data->EMAIL = '';
175
176
            $obj = new stdClass();
177
            $obj->CODIGO_RETORNO = 0;
178
            $obj->ETIQUETA_ERROR = 'Correcto';
179
            $obj->DATOS_IDENTIFICATIVOS = new SoapVar($data, SOAP_ENC_OBJECT);
180
181
            $result = new stdClass();
182
            $result->RESPUESTA_DATOS_CENTRO = new SoapVar($obj, SOAP_ENC_OBJECT);
183
            //error_log('Sin datos en la BD');
184
            /*
185
            $data = new stdClass();
186
            $obj = new stdClass();
187
            $obj->CODIGO_RETORNO = '-1';
188
            $obj->ETIQUETA_ERROR = 'Sin datos';
189
            $obj->DATOS_IDENTIFICATIVOS = new SoapVar($data, SOAP_ENC_OBJECT);
190
191
            $result = new stdClass();
192
            $result->RESPUESTA_DATOS_CENTRO = new SoapVar($obj, SOAP_ENC_OBJECT);
193
            */
194
            return $result; 
195
        }
196
    }
197
198
    /**
199
     * @param $crearAccionInput
200
     * @return array
201
     */
202
    public function crearAccion($crearAccionInput)
203
    {
204
        /* Tracking Log */
205
        $tableLog = Database::get_main_table('plugin_sepe_log');
206
        $paramsLog = array(
207
            'ip' => $_SERVER['REMOTE_ADDR'],
208
            'action' => "crearAccion",
209
            'fecha' => date("Y-m-d H:i:s")
210
        );
211
        Database::insert($tableLog, $paramsLog);
212
        /* End tracking log */
213
        
214
        $array = json_decode(json_encode($crearAccionInput), true);
215
        $crearAccionInputArray = (array) $array;
216
        // Code
217
        $actionOrigin = $crearAccionInput->ACCION_FORMATIVA->ID_ACCION->ORIGEN_ACCION;
218
        $actionCode = $crearAccionInput->ACCION_FORMATIVA->ID_ACCION->CODIGO_ACCION;
219
        $situation = $crearAccionInput->ACCION_FORMATIVA->SITUACION;
220
        $specialtyOrigin = $crearAccionInput->ACCION_FORMATIVA->ID_ESPECIALIDAD_PRINCIPAL->ORIGEN_ESPECIALIDAD;
221
        $professionalArea = $crearAccionInput->ACCION_FORMATIVA->ID_ESPECIALIDAD_PRINCIPAL->AREA_PROFESIONAL;
222
        $specialtyCode = $crearAccionInput->ACCION_FORMATIVA->ID_ESPECIALIDAD_PRINCIPAL->CODIGO_ESPECIALIDAD;
223
        $duration = $crearAccionInput->ACCION_FORMATIVA->DURACION;
224
        $startDate = $crearAccionInput->ACCION_FORMATIVA->FECHA_INICIO;
225
        $endDate = $crearAccionInput->ACCION_FORMATIVA->FECHA_FIN;
226
        $fullItineraryIndicator = $crearAccionInput->ACCION_FORMATIVA->IND_ITINERARIO_COMPLETO;
227
        $financingType = $crearAccionInput->ACCION_FORMATIVA->TIPO_FINANCIACION;
228
        $attendeesCount = $crearAccionInput->ACCION_FORMATIVA->NUMERO_ASISTENTES;
229
        $actionName = $crearAccionInput->ACCION_FORMATIVA->DESCRIPCION_ACCION->DENOMINACION_ACCION;
230
        $globalInfo = $crearAccionInput->ACCION_FORMATIVA->DESCRIPCION_ACCION->INFORMACION_GENERAL;
231
        $schedule = $crearAccionInput->ACCION_FORMATIVA->DESCRIPCION_ACCION->HORARIOS;
232
        $requerements = $crearAccionInput->ACCION_FORMATIVA->DESCRIPCION_ACCION->REQUISITOS;
233
        $contactAction = $crearAccionInput->ACCION_FORMATIVA->DESCRIPCION_ACCION->CONTACTO_ACCION;
234
      
235
236 View Code Duplication
        if (empty($actionOrigin) || empty($actionCode)) {
237
            error_log('2 - error en parametros - l244');
238
            return array(
239
                "RESPUESTA_OBT_ACCION" => array(
240
                    "CODIGO_RETORNO"=>"2",
241
                    "ETIQUETA_ERROR"=>"Error en parametro",
242
                    "ACCION_FORMATIVA"=> $crearAccionInputArray['ACCION_FORMATIVA']
243
                )
244
            );
245
        }
246
247
        // Comprobamos si existen datos almacenados previamente
248
        $table = Database::get_main_table('plugin_sepe_actions');
249
        $sql = "SELECT action_origin FROM $table
250
                WHERE action_origin='".$actionOrigin."' AND action_code='".$actionCode."';";
251
        $rs = Database::query($sql);
252
253
        if (Database::num_rows($rs) > 0) {
254
            return array(
255
                "RESPUESTA_OBT_ACCION" => array(
256
                    "CODIGO_RETORNO"=>"1",
257
                    "ETIQUETA_ERROR"=>"Acción existente",
258
                    "ACCION_FORMATIVA"=>$crearAccionInputArray['ACCION_FORMATIVA']
259
                )
260
            );
261
            
262
        }
263
264
        $startDate = self::fixDate($startDate);
265
        $endDate = self::fixDate($endDate);
266
267
        $sql = "INSERT INTO $table (action_origin, action_code, situation, specialty_origin, professional_area, specialty_code, duration, start_date, end_date, full_itinerary_indicator, financing_type, attendees_count, action_name, global_info, schedule, requirements, contact_action)
268
                VALUES ('".$actionOrigin."','".$actionCode."','".$situation."','".$specialtyOrigin."','".$professionalArea."','".$specialtyCode."','".$duration."','".$startDate."','".$endDate."','".$fullItineraryIndicator."','".$financingType."','".$attendeesCount."','".$actionName."','".$globalInfo."','".$schedule."','".$requerements."','".$contactAction."')";
269
270
        $rs = Database::query($sql);
271 View Code Duplication
        if (!$rs) {
272
            return array(
273
                "RESPUESTA_OBT_ACCION" => array(
274
                    "CODIGO_RETORNO"=>"-1",
275
                    "ETIQUETA_ERROR"=>"Problema base de datos - insertando acciones formativas",
276
                    "ACCION_FORMATIVA"=>$crearAccionInputArray['ACCION_FORMATIVA']
277
                )
278
            );
279
        }
280
        $actionId = Database::insert_id();
281
282
        // DATOS ESPECIALIDADES DE LA ACCION
283
        $table = Database::get_main_table('plugin_sepe_specialty');
284
285
        $specialties = $crearAccionInput->ACCION_FORMATIVA->ESPECIALIDADES_ACCION;
286
        foreach ($specialties as $specialtyList) {
287
            if (!is_array($specialtyList)) {
288
                $auxList = array();
289
                $auxList[] = $specialtyList;
290
                $specialtyList = $auxList;    
291
            }
292
            foreach ($specialtyList as $specialty) {
293
                $specialtyOrigin = $specialty->ID_ESPECIALIDAD->ORIGEN_ESPECIALIDAD;
294
                $professionalArea = $specialty->ID_ESPECIALIDAD->AREA_PROFESIONAL;
295
                $specialtyCode = $specialty->ID_ESPECIALIDAD->CODIGO_ESPECIALIDAD;
296
                $centerOrigin = $specialty->CENTRO_IMPARTICION->ORIGEN_CENTRO;
297
                $centerCode = $specialty->CENTRO_IMPARTICION->CODIGO_CENTRO;
298
                $startDate = $specialty->FECHA_INICIO;
299
                $endDate = $specialty->FECHA_FIN;
300
301
                $modalityImpartition = $specialty->MODALIDAD_IMPARTICION;
302
                $classroomHours = $specialty->DATOS_DURACION->HORAS_PRESENCIAL;
303
                $distanceHours = $specialty->DATOS_DURACION->HORAS_TELEFORMACION;
304
305
                $morningParticipansNumber = null;
306
                $morningAccessNumber = null;
307
                $morningTotalDuration = null;
308
309 View Code Duplication
                if (isset($specialty->USO->HORARIO_MANANA)) {
310
                    $morningParticipansNumber = $specialty->USO->HORARIO_MANANA->NUM_PARTICIPANTES;
311
                    $morningAccessNumber = $specialty->USO->HORARIO_MANANA->NUMERO_ACCESOS;
312
                    $morningTotalDuration = $specialty->USO->HORARIO_MANANA->DURACION_TOTAL;
313
                }
314
315
                $afternoonParticipantNumber = null;
316
                $afternoonAccessNumber = null;
317
                $afternoonTotalDuration = null;
318
319 View Code Duplication
                if (isset($specialty->USO->HORARIO_TARDE)) {
320
                    $afternoonParticipantNumber = $specialty->USO->HORARIO_TARDE->NUM_PARTICIPANTES;
321
                    $afternoonAccessNumber = $specialty->USO->HORARIO_TARDE->NUMERO_ACCESOS;
322
                    $afternoonTotalDuration = $specialty->USO->HORARIO_TARDE->DURACION_TOTAL;
323
                }
324
325
                $nightParticipantsNumber = null;
326
                $nightAccessNumber = null;
327
                $nightTotalDuration = null;
328
329 View Code Duplication
                if (isset($specialty->USO->HORARIO_NOCHE)) {
330
                    $nightParticipantsNumber = $specialty->USO->HORARIO_NOCHE->NUM_PARTICIPANTES;
331
                    $nightAccessNumber = $specialty->USO->HORARIO_NOCHE->NUMERO_ACCESOS;
332
                    $nightTotalDuration = $specialty->USO->HORARIO_NOCHE->DURACION_TOTAL;
333
                }
334
335
                $attendeesCount = null;
336
                $learningActivityCount = null;
337
                $attemptCount = null;
338
                $evaluationActivityCount = null;
339
340
                if (isset($specialty->USO->SEGUIMIENTO_EVALUACION)) {
341
                    $attendeesCount = $specialty->USO->SEGUIMIENTO_EVALUACION->NUM_PARTICIPANTES;
342
                    $learningActivityCount = $specialty->USO->SEGUIMIENTO_EVALUACION->NUMERO_ACTIVIDADES_APRENDIZAJE;
343
                    $attemptCount = $specialty->USO->SEGUIMIENTO_EVALUACION->NUMERO_INTENTOS;
344
                    $evaluationActivityCount = $specialty->USO->SEGUIMIENTO_EVALUACION->NUMERO_ACTIVIDADES_EVALUACION;
345
                }
346
347
                $startDate = self::fixDate($startDate);
348
                $endDate = self::fixDate($endDate);
349
350
                $params = array(
351
                    'action_id' => $actionId,
352
                    'specialty_origin' => $specialtyOrigin,
353
                    'professional_area' => $professionalArea,
354
                    'specialty_code' =>$specialtyCode ,
355
                    'center_origin' => $centerOrigin,
356
                    'center_code' => $centerCode,
357
                    'start_date' => $startDate ,
358
                    'end_date' => $endDate,
359
                    'modality_impartition' => $modalityImpartition,
360
                    'classroom_hours' => $classroomHours,
361
                    'distance_hours' => $distanceHours,
362
                    'mornings_participants_number' => $morningParticipansNumber,
363
                    'mornings_access_number' => $morningAccessNumber,
364
                    'morning_total_duration' => $morningTotalDuration,
365
                    'afternoon_participants_number' => $afternoonParticipantNumber,
366
                    'afternoon_access_number' => $afternoonAccessNumber,
367
                    'afternoon_total_duration' => $afternoonTotalDuration,
368
                    'night_participants_number' => $nightParticipantsNumber,
369
                    'night_access_number' => $nightAccessNumber,
370
                    'night_total_duration' => $nightTotalDuration,
371
                    'attendees_count' => $attendeesCount,
372
                    'learning_activity_count' => $learningActivityCount ,
373
                    'attempt_count' => $attemptCount,
374
                    'evaluation_activity_count' => $evaluationActivityCount
375
                );
376
377
                $specialtyId = Database::insert($table, $params);
378
379 View Code Duplication
                if (empty($specialtyId)) {
380
                    return array(
381
                        "RESPUESTA_OBT_ACCION" => array(
382
                            "CODIGO_RETORNO" => "-1",
383
                            "ETIQUETA_ERROR" => "Problema base de datos - insertando datos de especialidad de la accion",
384
                            "ACCION_FORMATIVA" => $crearAccionInputArray['ACCION_FORMATIVA']
385
                        )
386
                    );
387
                }
388
389
                
390
                if ($specialtyId) {
391
                    $tableSpecialtyClassroom = Database::get_main_table('plugin_sepe_specialty_classroom');
392
                    $tableCenters = Database::get_main_table('plugin_sepe_centers');
393
                    foreach ($specialty->CENTROS_SESIONES_PRESENCIALES->CENTRO_PRESENCIAL as $centroList) {
394
                        if (!is_array($centroList)) {
395
                            $auxList = array();
396
                            $auxList[] = $centroList;
397
                            $centroList = $auxList;    
398
                        }
399
                        foreach ($centroList as $centro) {
400
                            $centerOrigin = $centro->ORIGEN_CENTRO;
401
                            $centerCode = $centro->CODIGO_CENTRO;
402
                            $sql = "SELECT id FROM $tableCenters WHERE center_origin='".$centerOrigin."' AND center_code='".$centerCode."';";
403
                            $res = Database::query($sql);
404 View Code Duplication
                            if (Database::num_rows($res)>0) {
405
                                $aux_row = Database::fetch_assoc($res);
406
                                $centerId = $aux_row['id'];
407
                            } else {
408
                                $sql = "INSERT INTO $tableCenters (center_origin, center_code)
409
                                        VALUES ('" . $centerOrigin . "','" . $centerCode . "');";
410
                                Database::query($sql);
411
                                $centerId = Database::insert_id();
412
                            }
413
                            $sql = "INSERT INTO $tableSpecialtyClassroom (specialty_id, center_id)
414
                                    VALUES ('" . $specialtyId . "','" . $centerId . "')";
415
                            Database::query($sql);
416
                            $id = Database::insert_id();
417
                                
418 View Code Duplication
                            if (empty($id)) {
419
                                return array(
420
                                    "RESPUESTA_OBT_ACCION" => array(
421
                                        "CODIGO_RETORNO" => "-1",
422
                                        "ETIQUETA_ERROR" => "Problema base de datos - insertando centro presenciales",
423
                                        "ACCION_FORMATIVA" => $crearAccionInputArray['ACCION_FORMATIVA']
424
                                    )
425
                                );
426
                            }
427
                        }
428
                    }
429
430
                    $tableTutors = Database::get_main_table('plugin_sepe_tutors');
431
                    $tableSpecialityTutors = Database::get_main_table('plugin_sepe_specialty_tutors');
432
433
                    if (!empty($specialty->TUTORES_FORMADORES)) {
434
                        foreach ($specialty->TUTORES_FORMADORES as $tutorList) {
435
                            if (!is_array($tutorList)) {
436
                                $auxList = array();
437
                                $auxList[] = $tutorList;
438
                                $tutorList = $auxList;    
439
                            }
440
                            foreach ($tutorList as $tutor) {
441
                                $documentType = $tutor->ID_TUTOR->TIPO_DOCUMENTO;
442
                                $documentNumber = $tutor->ID_TUTOR->NUM_DOCUMENTO;
443
                                $documentLetter = $tutor->ID_TUTOR->LETRA_NIF;
444
                                $tutorAccreditation = $tutor->ACREDITACION_TUTOR;
445
                                $professionalExperience = $tutor->EXPERIENCIA_PROFESIONAL;
446
                                $teachingCompetence = $tutor->COMPETENCIA_DOCENTE;
447
                                $experienceTeleforming = $tutor->EXPERIENCIA_MODALIDAD_TELEFORMACION;
448
                                $trainingTeleforming = $tutor->FORMACION_MODALIDAD_TELEFORMACION;
449
                                
450
                                /* check tutor not exists */
451
                                $sql = "SELECT id FROM $tableTutors WHERE 
452
                                document_type='".$documentType."' AND document_number='".$documentNumber."' AND document_letter='".$documentLetter."';";
453
                                $res = Database::query($sql);
454 View Code Duplication
                                if (Database::num_rows($res)>0) {
455
                                    $aux_row = Database::fetch_assoc($res);
456
                                    $tutorId = $aux_row['id'];
457
                                } else {
458
                                    $sql = "INSERT INTO $tableTutors (document_type, document_number, document_letter)
459
                                        VALUES ('" . $documentType . "','" . $documentNumber . "','" . $documentLetter . "');";
460
                                    Database::query($sql);
461
                                    $tutorId = Database::insert_id();
462
                                }
463 View Code Duplication
                                if (empty($tutorId)) {
464
                                    return array(
465
                                        "RESPUESTA_OBT_ACCION" => array(
466
                                            "CODIGO_RETORNO" => "-1",
467
                                            "ETIQUETA_ERROR" => "Problema base de datos - insertando tutores",
468
                                            "ACCION_FORMATIVA" => $crearAccionInputArray['ACCION_FORMATIVA']
469
                                        )
470
                                    );
471
                                }
472
                                $sql = "INSERT INTO $tableSpecialityTutors (specialty_id, tutor_id, tutor_accreditation, professional_experience, teaching_competence, experience_teleforming, training_teleforming)
473
                                        VALUES ('" . $specialtyId . "','" . $tutorId . "','" . $tutorAccreditation . "','" . $professionalExperience . "','" . $teachingCompetence . "','" . $experienceTeleforming . "','" . $trainingTeleforming . "');";
474
                                Database::query($sql);
475
                            }
476
                        }
477
                    }
478
                }
479
            }
480
        }
481
        // DATOS PARTICIPANTES
482
        $tableParticipants = Database::get_main_table('plugin_sepe_participants');
483
        $tableTutorsCompany = Database::get_main_table('plugin_sepe_tutors_company');
484
        $participants = $crearAccionInput->ACCION_FORMATIVA->PARTICIPANTES;
485
        foreach ($participants as $participantList) {
486
            if (!is_array($participantList)) {
487
                $auxList = array();
488
                $auxList[] = $participantList;
489
                $participantList = $auxList;    
490
            }
491
            foreach ($participantList as $participant) {
492
                $documentType = $participant->ID_PARTICIPANTE->TIPO_DOCUMENTO;
493
                $documentNumber = $participant->ID_PARTICIPANTE->NUM_DOCUMENTO;
494
                $documentLetter = $participant->ID_PARTICIPANTE->LETRA_NIF;
495
                $keyCompetence = $participant->INDICADOR_COMPETENCIAS_CLAVE;
496
                $contractId = null;
497
                $companyFiscalNumber = null;
498
                $documentTypeCompany = null;
499
                $documentNumberCompany = null;
500
                $documentLetterCompany = null;
501
                $documentTypeTraining = null;
502
                $documentNumberTraining = null;
503
                $documentLetterTraining = null;
504
                $tutorIdCompany = null;
505
                $tutorIdTraining = null;
506
507
                if (isset($participant->CONTRATO_FORMACION)) {
508
                    $contractId = isset($participant->CONTRATO_FORMACION->ID_CONTRATO_CFA) ? $participant->CONTRATO_FORMACION->ID_CONTRATO_CFA : null;
509
                    $companyFiscalNumber = isset($participant->CONTRATO_FORMACION->CIF_EMPRESA) ? $participant->CONTRATO_FORMACION->CIF_EMPRESA : null;
510
                    $documentTypeCompany = isset($participant->CONTRATO_FORMACION->ID_TUTOR_EMPRESA->TIPO_DOCUMENTO) ? $participant->CONTRATO_FORMACION->ID_TUTOR_EMPRESA->TIPO_DOCUMENTO : null;
511
                    $documentNumberCompany = isset($participant->CONTRATO_FORMACION->ID_TUTOR_EMPRESA->NUM_DOCUMENTO) ? $participant->CONTRATO_FORMACION->ID_TUTOR_EMPRESA->NUM_DOCUMENTO : null;
512
                    $documentLetterCompany = isset($participant->CONTRATO_FORMACION->ID_TUTOR_EMPRESA->LETRA_NIF) ? $participant->CONTRATO_FORMACION->ID_TUTOR_EMPRESA->LETRA_NIF : null;
513 View Code Duplication
                    if (!empty($documentTypeCompany) || !empty($documentNumberCompany) || !empty($documentLetterCompany)) {
514
                        $tmp_e = Database::query('SELECT id FROM '.$tableTutorsCompany.' WHERE document_type="'.$documentTypeCompany.'" AND document_number="'.$documentNumberCompany.'" AND document_letter="'.$documentLetterCompany.'";');
515
                        if (Database::num_rows($tmp_e)>0) {
516
                            $row_tmp = Database::fetch_assoc($tmp_e);
517
                            $tutorIdCompany = $row_tmp['id'];
518
                            Database::query("UPDATE $tableTutorsCompany SET company='1' WHERE id='".$tutorIdCompany."'");
519
                        } else {
520
                            $params_tmp = array(
521
                                'document_type' => $documentTypeCompany,
522
                                'document_number' => $documentNumberCompany,
523
                                'document_letter' => $documentLetterCompany,
524
                                'company' => '1'
525
                            );
526
                            $tutorIdCompany = Database::insert($tableTutorsCompany, $params_tmp);
527
                        }
528
                    }
529
                    
530
                    $documentTypeTraining = isset($participant->CONTRATO_FORMACION->ID_TUTOR_FORMACION->TIPO_DOCUMENTO) ? $participant->CONTRATO_FORMACION->ID_TUTOR_FORMACION->TIPO_DOCUMENTO : null;
531
                    $documentNumberTraining = isset($participant->CONTRATO_FORMACION->ID_TUTOR_FORMACION->NUM_DOCUMENTO) ? $participant->CONTRATO_FORMACION->ID_TUTOR_FORMACION->NUM_DOCUMENTO : null;
532
                    $documentLetterTraining = isset($participant->CONTRATO_FORMACION->ID_TUTOR_FORMACION->LETRA_NIF) ? $participant->CONTRATO_FORMACION->ID_TUTOR_FORMACION->LETRA_NIF : null;
533 View Code Duplication
                    if (!empty($documentTypeTraining) || !empty($documentNumberTraining) || !empty($documentLetterTraining)) {
534
                        $tmp_f = Database::query('SELECT id FROM '.$tableTutorsCompany.' WHERE document_type="'.$documentTypeTraining.'" AND document_number="'.$documentNumberTraining.'" AND document_letter="'.$documentLetterTraining.'";');
535
                        if (Database::num_rows($tmp_f)>0) {
536
                            $row_tmp = Database::fetch_assoc($tmp_f);
537
                            $tutorIdTraining = $row_tmp['id'];
538
                            Database::query("UPDATE $tableTutorsCompany SET training='1' WHERE id='".$tutorIdTraining."'");
539
                        } else {
540
                            $params_tmp = array(
541
                                'document_type' => $documentTypeTraining,
542
                                'document_number' => $documentNumberTraining,
543
                                'document_letter' => $documentLetterTraining,
544
                                'training' => '1'
545
                            );
546
                            $tutorIdTraining = Database::insert($tableTutorsCompany, $params_tmp);
547
                        }
548
                    }
549
                }
550
551
                $params = array(
552
                    'action_id' => $actionId,
553
                    'document_type' => $documentType,
554
                    'document_number' => $documentNumber,
555
                    'document_letter' => $documentLetter,
556
                    'key_competence' => $keyCompetence,
557
                    'contract_id' => $contractId,
558
                    'company_fiscal_number' => $companyFiscalNumber,
559
                    'company_tutor_id' => $tutorIdCompany,
560
                    'training_tutor_id' => $tutorIdTraining
561
                );
562
                $participantId = Database::insert($tableParticipants, $params);
563 View Code Duplication
                if (empty($participantId)) {
564
                    return array(
565
                        "RESPUESTA_OBT_ACCION" => array(
566
                            "CODIGO_RETORNO" => "-1",
567
                            "ETIQUETA_ERROR" => "Problema base de datos - insertando participantes",
568
                            "ACCION_FORMATIVA" => $crearAccionInputArray['ACCION_FORMATIVA']
569
                        )
570
                    );
571
                }
572
573
                $participantId = Database::insert_id();
574
                
575
                foreach ($participant->ESPECIALIDADES_PARTICIPANTE as $valueList) {
576
                    if (!is_array($participantList)) {
577
                        $auxList = array();
578
                        $auxList[] = $valueList;
579
                        $valueList = $auxList;    
580
                    }
581
                    foreach ($valueList as $value) {
582
                        $specialtyOrigin = null;
583
                        $professionalArea = null;
584
                        $specialtyCode = null;
585
586
                        if (isset($value->ID_ESPECIALIDAD)) {
587
                            $specialtyOrigin = $value->ID_ESPECIALIDAD->ORIGEN_ESPECIALIDAD;
588
                            $professionalArea = $value->ID_ESPECIALIDAD->AREA_PROFESIONAL;
589
                            $specialtyCode = $value->ID_ESPECIALIDAD->CODIGO_ESPECIALIDAD;
590
                        }
591
592
                        $registrationDate = $value->FECHA_ALTA;
593
                        $leavingDate = $value->FECHA_BAJA;
594
595
                        $centerOrigin = null;
596
                        $centerCode = null;
597
                        $startDate = null;
598
                        $endDate = null;
599
600
                        if (!empty($value->EVALUACION_FINAL)) {
601
                            $startDate = isset($value->EVALUACION_FINAL->FECHA_INICIO) ? $value->EVALUACION_FINAL->FECHA_INICIO : null;
602
                            $endDate = isset($value->EVALUACION_FINAL->FECHA_FIN) ? $value->EVALUACION_FINAL->FECHA_FIN : null;
603
                            if (!empty($value->EVALUACION_FINAL->CENTRO_PRESENCIAL_EVALUACION)) {
604
                                $centerOrigin = $value->EVALUACION_FINAL->CENTRO_PRESENCIAL_EVALUACION->ORIGEN_CENTRO;
605
                                $centerCode = $value->EVALUACION_FINAL->CENTRO_PRESENCIAL_EVALUACION->CODIGO_CENTRO;
606
                            }
607
                        }
608
609
                        $finalResult = null;
610
                        $finalQualification = null;
611
                        $finalScore = null;
612
613
                        if (isset($value->RESULTADOS)) {
614
                            $finalResult = isset($value->RESULTADOS->RESULTADO_FINAL) ? $value->RESULTADOS->RESULTADO_FINAL : null;
615
                            $finalQualification = isset($value->RESULTADOS->CALIFICACION_FINAL) ? $value->RESULTADOS->CALIFICACION_FINAL : null;
616
                            $finalScore = isset($value->RESULTADOS->PUNTUACION_FINAL) ? $value->RESULTADOS->PUNTUACION_FINAL : null;
617
                        }
618
619
                        $registrationDate = self::fixDate($registrationDate);
620
                        $leavingDate = self::fixDate($leavingDate);
621
622
                        $startDate = self::fixDate($startDate);
623
                        $endDate = self::fixDate($endDate);
624
                        
625
                        $table_aux = Database::get_main_table('plugin_sepe_participants_specialty');
626
                        $sql = "INSERT INTO $table_aux (participant_id,specialty_origin,professional_area,specialty_code,registration_date,leaving_date,center_origin,center_code,start_date,end_date,final_result,final_qualification,final_score)
627
                                VALUES ('" . $participantId . "','" . $specialtyOrigin . "','" . $professionalArea . "','" . $specialtyCode . "','" . $registrationDate . "','" . $leavingDate . "','" . $centerOrigin . "','" . $centerCode . "','" . $startDate . "','" . $endDate . "','" . $finalResult . "','" . $finalQualification . "','" . $finalScore . "');";
628
                        Database::query($sql);
629
                        $participantSpecialtyId = Database::insert_id();
630 View Code Duplication
                        if (empty($participantSpecialtyId)) {
631
                            return array(
632
                                "RESPUESTA_OBT_ACCION" => array(
633
                                    "CODIGO_RETORNO" => "-1",
634
                                    "ETIQUETA_ERROR" => "Problema base de datos - insertando especialidad participante",
635
                                    "ACCION_FORMATIVA" => $crearAccionInputArray['ACCION_FORMATIVA']
636
                                )
637
                            );
638
                        }
639
640
                        foreach ($value->TUTORIAS_PRESENCIALES as $tutorialList) {
641
                            if (!is_array($tutorialList)) {
642
                                $auxList = array();
643
                                $auxList[] = $tutorialList;
644
                                $tutorialList = $auxList;    
645
                            }
646
                            foreach ($tutorialList as $tutorial) {
647
                                $centerOrigin = $tutorial->CENTRO_PRESENCIAL_TUTORIA->ORIGEN_CENTRO;
648
                                $centerCode = $tutorial->CENTRO_PRESENCIAL_TUTORIA->CODIGO_CENTRO;
649
                                $startDate = $tutorial->FECHA_INICIO;
650
                                $endDate = $tutorial->FECHA_FIN;
651
    
652
                                $startDate = self::fixDate($startDate);
653
                                $endDate = self::fixDate($endDate);
654
                                
655
                                $table_aux2 = Database::get_main_table('plugin_sepe_participants_specialty_tutorials');
656
                                $sql = "INSERT INTO $table_aux2 (participant_specialty_id,center_origin,center_code,start_date,end_date)
657
                                        VALUES ('" . $participantSpecialtyId . "','" . $centerOrigin . "','" . $centerCode . "','" . $startDate . "','" . $endDate . "');";
658
                                $rs = Database::query($sql);
659 View Code Duplication
                                if (!$rs) {
660
                                    return array(
661
                                        "RESPUESTA_OBT_ACCION" => array(
662
                                            "CODIGO_RETORNO" => "-1",
663
                                            "ETIQUETA_ERROR" => "Problema base de datos - insertando tutorias presenciales participante",
664
                                            "ACCION_FORMATIVA" => $crearAccionInputArray['ACCION_FORMATIVA']
665
                                        )
666
                                    );
667
                                }
668
                            }
669
                        }
670
                    }
671
                }
672
            }
673
        }
674
675
        $obtenerAccionInput = new stdClass();
676
        $obtenerAccionInput->ID_ACCION = new stdClass();
677
        $obtenerAccionInput->ID_ACCION->ORIGEN_ACCION = $actionOrigin;
678
        $obtenerAccionInput->ID_ACCION->CODIGO_ACCION = $actionCode;
679
680
        $result = self::obtenerAccion($obtenerAccionInput);
681
        return $result;
682
    }
683
684
    public function obtenerAccion($obtenerAccionInput)
685
    {
686
        /* Tracking Log */
687
        $tableLog = Database::get_main_table('plugin_sepe_log');
688
        $paramsLog = array(
689
            'ip' => $_SERVER['REMOTE_ADDR'],
690
            'action' => "obtenerAccion",
691
            'fecha' => date("Y-m-d H:i:s")
692
        );
693
        Database::insert($tableLog, $paramsLog);
694
695
        /* End tracking log */
696
        
697
        $actionOrigin = $obtenerAccionInput->ID_ACCION->ORIGEN_ACCION;
698
        $actionCode = $obtenerAccionInput->ID_ACCION->CODIGO_ACCION;
699
700 View Code Duplication
        if (empty($actionOrigin) || empty($actionCode)) {
701
            return array(
702
                "RESPUESTA_OBT_ACCION" => array(
703
                    "CODIGO_RETORNO" => "2",
704
                    "ETIQUETA_ERROR" => "Error en parametro",
705
                    "ACCION_FORMATIVA" => ""
706
                )
707
            );
708
        }
709
710
        $table = Database::get_main_table('plugin_sepe_actions');
711
        $tableCenters = Database::get_main_table('plugin_sepe_centers');
712
        $classRoomTable = Database::get_main_table('plugin_sepe_specialty_classroom');
713
        $tutorTable = Database::get_main_table('plugin_sepe_tutors');
714
        $specialityTutorTable = Database::get_main_table('plugin_sepe_specialty_tutors');
715
        $participantsSpecialityTable = Database::get_main_table('plugin_sepe_participants_specialty');
716
        $participantsSpecialityTutorialsTable = Database::get_main_table('plugin_sepe_participants_specialty_tutorials');
717
        $tableTutorsCompany = Database::get_main_table('plugin_sepe_tutors_company');
718
719
        // Comprobamos si existen datos almacenados previamente
720
        $sql = "SELECT *
721
                FROM $table
722
                WHERE
723
                    action_origin='".$actionOrigin."' AND
724
                    action_code='".$actionCode."';";
725
        $rs = Database::query($sql);
726
        if (Database::num_rows($rs) > 0) {
727
            $row = Database::fetch_assoc($rs);
728
            $mainSpecialty = array(
729
                'ORIGEN_ESPECIALIDAD' => $row['specialty_origin'],
730
                'AREA_PROFESIONAL' => $row['professional_area'],
731
                'CODIGO_ESPECIALIDAD' => $row['specialty_code']
732
            );
733
            $actionDescription = array(
734
                'DENOMINACION_ACCION' => $row['action_name'],
735
                'INFORMACION_GENERAL' => $row['global_info'],
736
                'HORARIOS' => $row['schedule'],
737
                'REQUISITOS' => $row['requirements'],
738
                'CONTACTO_ACCION' => $row['contact_action']
739
            );
740
741
            $tableSpeciality = Database::get_main_table('plugin_sepe_specialty');
742
            $tableParticipants = Database::get_main_table('plugin_sepe_participants');
743
            $sql = "SELECT * FROM $tableSpeciality
744
                    WHERE action_id ='".$row['id']."'";
745
            $rs = Database::query($sql);
746
            $specialty = array();
747
            if (Database::num_rows($rs) > 0) {
748
                while ($aux = Database::fetch_assoc($rs)) {
749
                    $specialtyId = $aux['id'];
750
                    $sql = "SELECT * FROM $classRoomTable
751
                            WHERE specialty_id='" . $specialtyId . "'";
752
                    $resultClassroom = Database::query($sql);
753 View Code Duplication
                    if (Database::num_rows($resultClassroom) === 0) {
754
                        return array(
755
                            "RESPUESTA_OBT_ACCION" => array(
756
                                "CODIGO_RETORNO" => "-1",
757
                                "ETIQUETA_ERROR" => "Problema base de datos - consulta de centros presenciales",
758
                                "ACCION_FORMATIVA" => ''
759
                            )
760
                        );
761
                    }
762
763
                    $classroomCenterList = new ArrayObject();
764
                    while ($tmp = Database::fetch_assoc($resultClassroom)) {
765
                        $sql = "SELECT * FROM $tableCenters WHERE id='".$tmp['center_id']."';";
766
                        $resultCenter = Database::query($sql);
767
                        $auxCenter = Database::fetch_assoc($resultCenter);
768
                        
769
                        $classroomCenter = new stdClass();
770
                        $classroomCenter->ORIGEN_CENTRO = $auxCenter['center_origin'];
771
                        $classroomCenter->CODIGO_CENTRO = $auxCenter['center_code'];
772
                        $classroomCenter = new SoapVar($classroomCenter, SOAP_ENC_OBJECT, null, null, 'CENTRO_PRESENCIAL');
773
                        $classroomCenterList->append($classroomCenter);
774
                    }
775
                    $sql = "SELECT * FROM $specialityTutorTable
776
                            WHERE specialty_id='" . $specialtyId . "'";
777
                    $resultSpecialtyTutor = Database::query($sql);
778
779
                    $trainingTutors = new ArrayObject();
780
                    if (Database::num_rows($resultSpecialtyTutor)) {
781
                        while ($tmp_aux = Database::fetch_assoc($resultSpecialtyTutor)) {
782
                            $sql = "SELECT * FROM $tutorTable
783
                                    WHERE id='" . $tmp_aux['tutor_id'] . "'
784
                                    LIMIT 1";
785
                              $rs_tutor = Database::query($sql);
786
                            if (Database::num_rows($rs_tutor)) {
787
                                $tmp = Database::fetch_assoc($rs_tutor);
788
789
                                $obj = new stdClass();
790
                                $obj->ID_TUTOR = new stdClass();
791
                                $obj->ID_TUTOR->TIPO_DOCUMENTO = $tmp['document_type'];
792
                                $obj->ID_TUTOR->NUM_DOCUMENTO = $tmp['document_number'];
793
                                $obj->ID_TUTOR->LETRA_NIF = $tmp['document_letter'];
794
795
                                $obj->ACREDITACION_TUTOR = $tmp_aux['tutor_accreditation'];
796
                                $obj->EXPERIENCIA_PROFESIONAL = $tmp_aux['professional_experience'];
797
                                $obj->COMPETENCIA_DOCENTE = $tmp_aux['teaching_competence'];
798
                                $obj->EXPERIENCIA_MODALIDAD_TELEFORMACION = $tmp_aux['experience_teleforming'];
799
                                $obj->FORMACION_MODALIDAD_TELEFORMACION = $tmp_aux['training_teleforming'];
800
801
                                $obj = new SoapVar($obj, SOAP_ENC_OBJECT, null, null, 'TUTOR_FORMADOR');
802
                                $trainingTutors->append($obj);
803
                            }
804
                        }
805
                    }
806
807
                    $params = new ArrayObject();
808
                    $idEspecialidad = new stdClass();
809
                    $idEspecialidad->ORIGEN_ESPECIALIDAD = $aux['specialty_origin'];
810
                    $idEspecialidad->AREA_PROFESIONAL = $aux['professional_area'];
811
                    $idEspecialidad->CODIGO_ESPECIALIDAD = $aux['specialty_code'];
812
813
                    $params[0] = new SoapVar($idEspecialidad, SOAP_ENC_OBJECT, NULL, null, 'ID_ESPECIALIDAD', null);
814
815
                    $centroImparticion = new stdClass();
816
                    $centroImparticion->ORIGEN_CENTRO = $aux['center_origin'];
817
                    $centroImparticion->CODIGO_CENTRO = $aux['center_code'];
818
819
                    $params[1] = new SoapVar($centroImparticion, SOAP_ENC_OBJECT, NULL, null, 'CENTRO_IMPARTICION', null);
820
                    $params[2] = new SoapVar(self::undoFixDate($aux['start_date']), XSD_STRING, NULL, null, 'FECHA_INICIO', null);
821
                    $params[3] = new SoapVar(self::undoFixDate($aux['end_date']), XSD_STRING, NULL, null, 'FECHA_FIN', null);
822
                    $params[4] = new SoapVar($aux['modality_impartition'], XSD_STRING, NULL, null, 'MODALIDAD_IMPARTICION', null);
823
824
                    $obj = new stdClass();
825
                    $obj->HORAS_PRESENCIAL = $aux['classroom_hours'];
826
                    $obj->HORAS_TELEFORMACION = $aux['distance_hours'];
827
828
                    $params[5] = new SoapVar($obj, SOAP_ENC_OBJECT, NULL, null, 'DATOS_DURACION', null);
829
                    $params[6] = new SoapVar($classroomCenterList, SOAP_ENC_OBJECT, null, null, 'CENTROS_SESIONES_PRESENCIALES', null);
830
                    $params[7] = new SoapVar($trainingTutors, SOAP_ENC_OBJECT, null, null, 'TUTORES_FORMADORES', null);
831
832
                    $obj = new stdClass();
833
834 View Code Duplication
                    if (!empty($aux['mornings_participants_number']) ||
835
                        !empty($aux['mornings_access_number']) ||
836
                        !empty($aux['morning_total_duration'])
837
                    ) {
838
                        $obj->HORARIO_MANANA = new stdClass();
839
                        $obj->HORARIO_MANANA->NUM_PARTICIPANTES = $aux['mornings_participants_number'];
840
                        $obj->HORARIO_MANANA->NUMERO_ACCESOS = $aux['mornings_access_number'];
841
                        $obj->HORARIO_MANANA->DURACION_TOTAL = $aux['morning_total_duration'];
842
                    }
843
844 View Code Duplication
                    if (!empty($aux['afternoon_participants_number']) ||
845
                        !empty($aux['afternoon_access_number']) ||
846
                        !empty($aux['afternoon_total_duration'])
847
                    ) {
848
                        $obj->HORARIO_TARDE = new stdClass();
849
                        $obj->HORARIO_TARDE->NUM_PARTICIPANTES = $aux['afternoon_participants_number'];
850
                        $obj->HORARIO_TARDE->NUMERO_ACCESOS = $aux['afternoon_access_number'];
851
                        $obj->HORARIO_TARDE->DURACION_TOTAL = $aux['afternoon_total_duration'];
852
                    }
853
854 View Code Duplication
                    if (!empty($aux['night_participants_number'])  ||
855
                        !empty($aux['night_access_number'])  ||
856
                        !empty($aux['night_total_duration'])
857
                    ) {
858
                        $obj->HORARIO_NOCHE = new stdClass();
859
                        $obj->HORARIO_NOCHE->NUM_PARTICIPANTES = $aux['night_participants_number'];
860
                        $obj->HORARIO_NOCHE->NUMERO_ACCESOS = $aux['night_access_number'];
861
                        $obj->HORARIO_NOCHE->DURACION_TOTAL = $aux['night_total_duration'];
862
                    }
863
864
                    if (!empty($aux['attendees_count'])  ||
865
                        !empty($aux['learning_activity_count'])  ||
866
                        !empty($aux['attempt_count'])  ||
867
                        !empty($aux['evaluation_activity_count'])
868
                    ) {
869
                        $obj->SEGUIMIENTO_EVALUACION = new stdClass();
870
                        $obj->SEGUIMIENTO_EVALUACION->NUM_PARTICIPANTES = $aux['attendees_count'];
871
                        $obj->SEGUIMIENTO_EVALUACION->NUMERO_ACTIVIDADES_APRENDIZAJE = $aux['learning_activity_count'];
872
                        $obj->SEGUIMIENTO_EVALUACION->NUMERO_INTENTOS = $aux['attempt_count'];
873
                        $obj->SEGUIMIENTO_EVALUACION->NUMERO_ACTIVIDADES_EVALUACION = $aux['evaluation_activity_count'];
874
                    }
875
876
                    $params[8] = new SoapVar($obj, SOAP_ENC_OBJECT, null, null, 'USO', null);
877
                    $specialty[] = new SoapVar($params, SOAP_ENC_OBJECT, null, null, 'ESPECIALIDAD');
878
                }
879
            } else {
880
                return array(
881
                    "RESPUESTA_OBT_ACCION" => array(
882
                        "CODIGO_RETORNO"=>"-1",
883
                        "ETIQUETA_ERROR"=>"Problema base de datos - consulta especialidad de accion",
884
                        "ACCION_FORMATIVA"=>''
885
                    )
886
                );
887
            }
888
889
            $sql = "SELECT * FROM $tableParticipants
890
                    WHERE action_id ='".$row['id']."'";
891
            $resultParticipants = Database::query($sql);
892
            $specialtyMainParticipant = array();
893
            if (Database::num_rows($resultParticipants)) {
894
                while ($aux = Database::fetch_assoc($resultParticipants)) {
895
                    $participantId = $aux['id'];
896
897
                    $sql = "SELECT * FROM $participantsSpecialityTable
898
                            WHERE participant_id='" . $participantId . "'";
899
                    $resultParticipantSpecialty = Database::query($sql);
900
                    
901
                    $namespace = null;
902
                    $specialtyParticipant = array();
903
                    while ($tmp = Database::fetch_assoc($resultParticipantSpecialty)) {
904
                        $participantSpecialtyId = $tmp['id'];
905
                        $sql = "SELECT * FROM $participantsSpecialityTutorialsTable
906
                                WHERE participant_specialty_id='" . $participantSpecialtyId . "'";
907
                        $resultTutorials = Database::query($sql);
908
                        $classroomTutorials = new ArrayObject();
909
910
                        while ($tmp2 = Database::fetch_assoc($resultTutorials)) {
911
                            $obj = new stdClass();
912
                            $obj->CENTRO_PRESENCIAL_TUTORIA = new stdClass();
913
                            $obj->CENTRO_PRESENCIAL_TUTORIA->ORIGEN_CENTRO = $tmp2['center_origin'];
914
                            $obj->CENTRO_PRESENCIAL_TUTORIA->CODIGO_CENTRO = $tmp2['center_code'];
915
                            $startDate = self::undoFixDate($tmp2['start_date']);
916
                            if (!empty($startDate)) {
917
                                $obj->FECHA_INICIO = $startDate;
918
                            }
919
                            $endDate = self::undoFixDate($tmp2['end_date']);
920
                            if (!empty($endDate)) {
921
                                $obj->FECHA_FIN = $endDate;
922
                            }
923
924
                            $obj = new SoapVar($obj, SOAP_ENC_OBJECT, null, null, 'TUTORIA_PRESENCIAL');
925
                            $classroomTutorials->append($obj);
926
                        }
927
928
                        $obj = new stdClass();
929
                        $obj->ID_ESPECIALIDAD = new stdClass();
930
                        $obj->ID_ESPECIALIDAD->ORIGEN_ESPECIALIDAD = $tmp['specialty_origin'];
931
                        $obj->ID_ESPECIALIDAD->AREA_PROFESIONAL = $tmp['professional_area'];
932
                        $obj->ID_ESPECIALIDAD->CODIGO_ESPECIALIDAD = $tmp['specialty_code'];
933
934
                        $registrationDate = self::undoFixDate($tmp['registration_date']);
935
936
                        // @todo check which is correct send 0000/00/00 or empty
937
                        if (!empty($registrationDate)) {
938
                            $obj->FECHA_ALTA = $registrationDate;
939
                        }
940
941
                        $leavingDate = self::undoFixDate($tmp['leaving_date']);
942
                        if (!empty($leavingDate)) {
943
                            $obj->FECHA_BAJA = $leavingDate;
944
                        }
945
946
                        $obj->TUTORIAS_PRESENCIALES = new SoapVar($classroomTutorials, SOAP_ENC_OBJECT, null, null, 'TUTORIAS_PRESENCIALES', null);
947
                        $obj->EVALUACION_FINAL = new stdClass();
948
949
                        if (!empty($tmp['center_origin']) && !empty($tmp['center_code'])) {
950
                            $obj->EVALUACION_FINAL->CENTRO_PRESENCIAL_EVALUACION = new stdClass();
951
                            $obj->EVALUACION_FINAL->CENTRO_PRESENCIAL_EVALUACION->ORIGEN_CENTRO = $tmp['center_origin'];
952
                            $obj->EVALUACION_FINAL->CENTRO_PRESENCIAL_EVALUACION->CODIGO_CENTRO = $tmp['center_code'];
953
                        }
954
955
                        $startDate = self::undoFixDate($tmp['start_date']);
956
                        if (!empty($startDate)) {
957
                            $obj->EVALUACION_FINAL->FECHA_INICIO = $startDate;
958
                        }
959
960
                        $endDate = self::undoFixDate($tmp['end_date']);
961
962
                        if (!empty($endDate)) {
963
                            $obj->EVALUACION_FINAL->FECHA_FIN = $endDate;
964
                        }
965
966
                        $obj->RESULTADOS = new stdClass();
967
968
                        if (isset($tmp['final_result']) && $tmp['final_result'] != '') {
969
                            $obj->RESULTADOS->RESULTADO_FINAL = $tmp['final_result'];
970
                        }
971
                        if (isset($tmp['final_qualification']) && $tmp['final_qualification'] != '') {
972
                            $obj->RESULTADOS->CALIFICACION_FINAL = $tmp['final_qualification'];
973
                        }
974
975
                        if (isset($tmp['final_score']) && $tmp['final_score'] != '') {
976
                            $obj->RESULTADOS->PUNTUACION_FINAL = $tmp['final_score'];
977
                        }
978
                        $specialtyParticipant[] = new SoapVar($obj, SOAP_ENC_OBJECT, null, null, 'ESPECIALIDAD');
979
                    }
980
981
                    $params = new stdClass();
982
                    $params->ID_PARTICIPANTE = new stdClass();
983
                    $params->ID_PARTICIPANTE->TIPO_DOCUMENTO = $aux['document_type'];
984
                    $params->ID_PARTICIPANTE->NUM_DOCUMENTO = $aux['document_number'];
985
                    $params->ID_PARTICIPANTE->LETRA_NIF = $aux['document_letter'];
986
                    $params->INDICADOR_COMPETENCIAS_CLAVE = $aux['key_competence'];
987
988
                    $params->CONTRATO_FORMACION = new stdClass();
989
990
                    if (!empty($aux['contract_id'])) {
991
                        $params->CONTRATO_FORMACION->ID_CONTRATO_CFA = $aux['contract_id'];
992
                    }
993
994
                    if (!empty($aux['company_fiscal_number'])) {
995
                        $params->CONTRATO_FORMACION->CIF_EMPRESA = $aux['company_fiscal_number'];
996
                    }
997
998 View Code Duplication
                    if (!empty($aux['company_tutor_id'])) {
999
                        $resultCompany = Database::query("SELECT * FROM $tableTutorsCompany WHERE id='".$aux['company_tutor_id']."';");
1000
                        $auxCompany = Database::fetch_assoc($resultCompany);
1001
                        if (!empty($auxCompany['document_type']) ||
1002
                         !empty($auxCompany['document_number']) ||
1003
                         !empty($auxCompany['document_letter'])
1004
                            ) {
1005
                            $params->CONTRATO_FORMACION->ID_TUTOR_EMPRESA = new stdClass();
1006
                            $params->CONTRATO_FORMACION->ID_TUTOR_EMPRESA->TIPO_DOCUMENTO = $auxCompany['document_type'];
1007
                            $params->CONTRATO_FORMACION->ID_TUTOR_EMPRESA->NUM_DOCUMENTO = $auxCompany['document_number'];
1008
                            $params->CONTRATO_FORMACION->ID_TUTOR_EMPRESA->LETRA_NIF = $auxCompany['document_letter'];
1009
                        }
1010
                    }
1011 View Code Duplication
                    if (!empty($aux['training_tutor_id'])) {
1012
                        $resultTraining = Database::query("SELECT * FROM $tableTutorsCompany WHERE id='".$aux['training_tutor_id']."';");
1013
                        $auxTraining = Database::fetch_assoc($resultTraining);
1014
                        if (!empty($auxTraining['document_type']) ||
1015
                            !empty($auxTraining['document_number']) ||
1016
                            !empty($auxTraining['document_letter'])
1017
                        ) {
1018
                            $params->CONTRATO_FORMACION->ID_TUTOR_FORMACION = new stdClass();
1019
                            $params->CONTRATO_FORMACION->ID_TUTOR_FORMACION->TIPO_DOCUMENTO = $auxTraining['document_type'];
1020
                            $params->CONTRATO_FORMACION->ID_TUTOR_FORMACION->NUM_DOCUMENTO = $auxTraining['document_number'];
1021
                            $params->CONTRATO_FORMACION->ID_TUTOR_FORMACION->LETRA_NIF = $auxTraining['document_letter'];
1022
                        }
1023
                    }
1024
1025
1026
                    $params->ESPECIALIDADES_PARTICIPANTE = new SoapVar(
1027
                        $specialtyParticipant,
1028
                        SOAP_ENC_OBJECT,
1029
                        null,
1030
                        null,
1031
                        'ESPECIALIDADES_PARTICIPANTE'
1032
                    );
1033
                    $specialtyMainParticipant[] = new SoapVar(
1034
                        $params,
1035
                        SOAP_ENC_OBJECT,
1036
                        null,
1037
                        null,
1038
                        'PARTICIPANTE'
1039
                    );
1040
                }
1041
            }
1042
1043
            $result = new stdClass();
1044
1045
            $result->RESPUESTA_OBT_ACCION = new stdClass();
1046
            $result->RESPUESTA_OBT_ACCION->CODIGO_RETORNO = 0;
1047
            $result->RESPUESTA_OBT_ACCION->ETIQUETA_ERROR = 'Correcto';
1048
1049
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA = new stdClass();
1050
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->ID_ACCION = new stdClass();
1051
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->ID_ACCION->ORIGEN_ACCION = $actionOrigin;
1052
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->ID_ACCION->CODIGO_ACCION = $actionCode;
1053
1054
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->SITUACION = $row['situation'];
1055
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->ID_ESPECIALIDAD_PRINCIPAL = $mainSpecialty;
1056
1057
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->DURACION = $row['duration'];
1058
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->FECHA_INICIO = self::undoFixDate($row['start_date']);
1059
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->FECHA_FIN = self::undoFixDate($row['end_date']);
1060
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->IND_ITINERARIO_COMPLETO = $row['full_itinerary_indicator'];
1061
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->TIPO_FINANCIACION = $row['financing_type'];
1062
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->NUMERO_ASISTENTES = $row['attendees_count'];
1063
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->DESCRIPCION_ACCION = $actionDescription;
1064
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->ESPECIALIDADES_ACCION = $specialty;
1065
            $result->RESPUESTA_OBT_ACCION->ACCION_FORMATIVA->PARTICIPANTES = $specialtyMainParticipant;
1066
1067
            return $result;
1068
        } else {
1069
            // Existe la accion
1070
            return array(
1071
                "RESPUESTA_OBT_ACCION" => array(
1072
                    "CODIGO_RETORNO" => "1",
1073
                    "ETIQUETA_ERROR" => "Acción inexistente",
1074
                    "ACCION_FORMATIVA" => ""
1075
                )
1076
            );
1077
        }
1078
    }
1079
1080
    public function obtenerListaAcciones()
1081
    {
1082
        /* Tracking Log */
1083
        $tableLog = Database::get_main_table('plugin_sepe_log');
1084
        $paramsLog = array(
1085
            'ip' => $_SERVER['REMOTE_ADDR'],
1086
            'action' => "obtenerListaAcciones",
1087
            'fecha' => date("Y-m-d H:i:s")
1088
        );
1089
        Database::insert($tableLog, $paramsLog);
1090
        /* End tracking log */
1091
        
1092
        $table = Database::get_main_table('plugin_sepe_actions');
1093
1094
        $sql = "SELECT action_origin, action_code FROM $table";
1095
        $rs = Database::query($sql);
1096
1097
        if (!$rs) {
1098
            error_log('Problema base de datos ');
1099
            return array(
1100
                "RESPUESTA_OBT_LISTA_ACCIONES" => array(
1101
                    "CODIGO_RETORNO" => "-1",
1102
                    "ETIQUETA_ERROR" => "Problema base de datos - consulta acciones disponible",
1103
                    "LISTA_ACCIONES" => ''
1104
                )
1105
            );
1106
        }
1107
1108
        $list = array();
1109
        if (Database::num_rows($rs)) {
1110
            while ($row = Database::fetch_assoc($rs)) {
1111
                $params = new stdClass();
1112
                $params->ORIGEN_ACCION = $row['action_origin'];
1113
                $params->CODIGO_ACCION = $row['action_code'];
1114
1115
                $list[] = new SoapVar($params, SOAP_ENC_OBJECT);
1116
            }
1117
        }
1118
1119
        $result = new stdClass();
1120
        $result->RESPUESTA_OBT_LISTA_ACCIONES = new stdClass();
1121
        $result->RESPUESTA_OBT_LISTA_ACCIONES->CODIGO_RETORNO = 0;
1122
        $result->RESPUESTA_OBT_LISTA_ACCIONES->ETIQUETA_ERROR = 'Correcto';
1123
1124
        if (!empty($list)) {
1125
            $result->RESPUESTA_OBT_LISTA_ACCIONES->ID_ACCION = $list;
1126
        }
1127
1128
        return $result;
1129
    }
1130
1131
    public function eliminarAccion($eliminarAccionInput)
1132
    {
1133
        /* Tracking Log */
1134
        $tableLog = Database::get_main_table('plugin_sepe_log');
1135
        $paramsLog = array(
1136
            'ip' => $_SERVER['REMOTE_ADDR'],
1137
            'action' => "eliminarAccion",
1138
            'fecha' => date("Y-m-d H:i:s")
1139
        );
1140
        Database::insert($tableLog, $paramsLog);
1141
        /* End tracking log */
1142
        
1143
        $actionOrigin = $eliminarAccionInput->ID_ACCION->ORIGEN_ACCION;
1144
        $actionCode = $eliminarAccionInput->ID_ACCION->CODIGO_ACCION;
1145
1146
        if (empty($actionOrigin) || empty($actionCode)) {
1147
            return array(
1148
                "RESPUESTA_ELIMINAR_ACCION" => array(
1149
                    "CODIGO_RETORNO" => "2",
1150
                    "ETIQUETA_ERROR" => "Error en parametro"
1151
                )
1152
            );
1153
        }
1154
        
1155
        $table = Database::get_main_table('plugin_sepe_actions');
1156
        $sql = "DELETE FROM $table
1157
                WHERE action_origin='".$actionOrigin."' AND action_code='".$actionCode."';";
1158
        
1159
        $rs = Database::query($sql);
1160
        if (!$rs) {
1161
            return array(
1162
                "RESPUESTA_ELIMINAR_ACCION" => array(
1163
                    "CODIGO_RETORNO" => "-1",
1164
                    "ETIQUETA_ERROR" => "Problema base de datos - consulta acciones disponible"
1165
                )
1166
            );
1167
        }
1168
        
1169
        return array(
1170
            "RESPUESTA_ELIMINAR_ACCION" => array(
1171
                "CODIGO_RETORNO" => "0",
1172
                "ETIQUETA_ERROR" => "Correcto"
1173
            )
1174
        );
1175
    }
1176
1177
    // yyyy-mm-dd to dd/mm/yyyy
1178 View Code Duplication
    public static function undoFixDate($date)
1179
    {
1180
        if ($date == '0000-00-00' || empty($date)) {
1181
            return null;
1182
        }
1183
1184
        $date = explode('-', $date);
1185
        //
1186
        $date = $date[2].'/'.$date[1].'/'.$date[0];
1187
        return $date;
1188
    }
1189
1190
    // dd/mm/yyyy to yyyy-mm-dd
1191 View Code Duplication
    public static function fixDate($date)
1192
    {
1193
        if ($date == '00/00/0000' || empty($date)) {
1194
            return null;
1195
        }
1196
1197
        $date = explode('/', $date);
1198
        // Year-month-day
1199
        $date = $date[2].'-'.$date[1].'-'.$date[0];
1200
        return $date;
1201
    }
1202
1203
    protected function checkAuth()
1204
    {
1205
        if (!$this->authenticated) {
1206
//            HTML_Output::error(403);
1207
            error_log('403');
1208
        }
1209
    }
1210
}
1211