Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 1 | Rev 18 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 www 1
<?php
2
declare(strict_types=1);
3
 
4
namespace LeadersLinked\Controller;
5
 
6
 
7
use Laminas\Authentication\AuthenticationService;
8
use Laminas\Authentication\Result as AuthResult;
9
use Laminas\Db\Adapter\AdapterInterface;
10
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
11
use Laminas\Mvc\Controller\AbstractActionController;
12
use Laminas\Log\LoggerInterface;
13
use Laminas\View\Model\JsonModel;
14
 
15
use LeadersLinked\Authentication\AuthAdapter;
16
use LeadersLinked\Mapper\UserMapper;
17
use LeadersLinked\Mapper\EmailTemplateMapper;
18
use LeadersLinked\Model\User;
19
use LeadersLinked\Model\UserType;
20
 
21
use LeadersLinked\Library\QueueEmail;
22
use LeadersLinked\Library\Functions;
23
use LeadersLinked\Model\EmailTemplate;
24
use LeadersLinked\Mapper\UserPasswordMapper;
25
use LeadersLinked\Mapper\DeviceMapper;
26
use LeadersLinked\Model\Device;
27
use LeadersLinked\Mapper\ApplicationMapper;
28
use LeadersLinked\Model\Application;
29
use LeadersLinked\Validator\PasswordStrengthCheck;
30
 
31
use LeadersLinked\Mapper\CompanyMapper;
32
use LeadersLinked\Model\Company;
33
use LeadersLinked\Mapper\CompanyMicrolearningTopicMapper;
34
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleMapper;
35
use LeadersLinked\Mapper\CompanyMicrolearningSlideMapper;
36
use LeadersLinked\Model\CompanyMicrolearningSlide;
37
use LeadersLinked\Mapper\CompanyMicrolearningUserLogMapper;
38
use LeadersLinked\Mapper\CompanyMicrolearningUserProgressMapper;
39
use LeadersLinked\Mapper\CompanyMicrolearningQuizMapper;
40
use LeadersLinked\Mapper\CompanyMicrolearningQuestionMapper;
41
use LeadersLinked\Mapper\CompanyMicrolearningAnswerMapper;
42
use LeadersLinked\Model\CompanyMicrolearningUserProgress;
43
use LeadersLinked\Model\CompanyMicrolearningUserLog;
44
use LeadersLinked\Mapper\DeviceHistoryMapper;
45
use LeadersLinked\Model\DeviceHistory;
46
use LeadersLinked\Mapper\PushMapper;
47
use LeadersLinked\Model\Push;
48
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleUserMapper;
49
use LeadersLinked\Mapper\CompanyServiceMapper;
50
use LeadersLinked\Model\Service;
51
use LeadersLinked\Model\CompanyService;
52
use LeadersLinked\Model\CompanyMicrolearningCapsuleUser;
53
use LeadersLinked\Model\CompanyMicrolearningUserQuiz;
54
use LeadersLinked\Mapper\CompanyMicrolearningUserQuizMapper;
55
use LeadersLinked\Mapper\CompanyUserMapper;
56
use LeadersLinked\Model\CompanyUser;
57
use LeadersLinked\Mapper\CompanyMicrolearningUserMapper;
58
use LeadersLinked\Model\CompanyMicrolearningUser;
59
use LeadersLinked\Mapper\PushTemplateMapper;
60
use LeadersLinked\Model\PushTemplate;
61
 
62
 
63
class ServiceController extends AbstractActionController
64
{
65
 
66
 
67
    /**
68
     *
69
     * @var AdapterInterface
70
     */
71
    private $adapter;
72
 
73
 
74
    /**
75
     *
76
     * @var AbstractAdapter
77
     */
78
    private $cache;
79
 
80
    /**
81
     *
82
     * @var  LoggerInterface
83
     */
84
    private $logger;
85
 
86
    /**
87
     *
88
     * @var array
89
     */
90
    private $config;
91
 
92
    /**
93
     *
94
     * @param AdapterInterface $adapter
95
     * @param AbstractAdapter $cache
96
     * @param LoggerInterface $logger
97
     * @param array $config
98
     */
99
    public function __construct($adapter, $cache , $logger, $config)
100
    {
101
        $this->adapter      = $adapter;
102
        $this->cache        = $cache;
103
        $this->logger       = $logger;
104
        $this->config       = $config;
105
    }
106
 
107
    public function signoutAction()
108
    {
109
        $currentUser = $this->plugin('currentUserPlugin');
110
        if($currentUser->hasIdentity()) {
111
            $device_uuid = $currentUser->getDeviceId();
112
            if($device_uuid) {
113
                $deviceMapper = DeviceMapper::getInstance($this->adapter);
114
                $device = $deviceMapper->fetchOne($device_uuid);
115
                if($device) {
116
                    $deviceMapper->signout($device);
117
                }
118
            }
119
 
120
 
121
            $this->logger->info('Desconexión del mobile', ['user_id' => $currentUser->getUserId(), 'ip' => Functions::getUserIP()]);
122
        }
123
        $authService = new \Laminas\Authentication\AuthenticationService();
124
        $authService->clearIdentity();
125
 
126
        return new JsonModel([
127
            'success' => true,
128
            'data' => 'LABEL_SIGNOUT_SUCCESSFULL'
129
        ]);
130
    }
131
 
132
    public function fcmAction()
133
    {
134
        $request = $this->getRequest();
135
 
136
        if($request->isPost()) {
137
 
138
            $rawdata = file_get_contents("php://input");
139
            error_log('$rawdata = ' . $rawdata );
140
 
141
            $device_uuid      = filter_var($this->params()->fromPost('device_uuid', ''), FILTER_SANITIZE_STRING);
142
            $token          = filter_var($this->params()->fromPost('token', ''), FILTER_SANITIZE_STRING);
143
            $sync_id        = filter_var($this->params()->fromPost('sync_id', ''), FILTER_SANITIZE_NUMBER_INT);
144
 
145
            /*
146
            echo '$device_uuid = ' . $device_uuid .PHP_EOL;
147
            echo '$token = ' . $token .PHP_EOL;
148
            echo '$sync_id  = ' . $sync_id  .PHP_EOL;
149
            */
150
            $ok = $device_uuid && strlen($device_uuid) == 36 && $sync_id;
151
            $ok = $ok && strlen($token) <= 512;
152
 
153
 
154
            if(!$ok) {
155
                return new JsonModel([
156
                    'success' => false,
157
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID',
158
                ]);
159
            }
160
 
161
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
162
            $device = $deviceMapper->fetchOne($device_uuid);
163
            if(!$device) {
164
                return new JsonModel([
165
                    'success' => false,
166
                    'data' => 'ERROR_DEVICE_NOT_FOUND',
167
                ]);
168
            }
169
 
170
 
171
            $applicationMapper = ApplicationMapper::getInstance($this->adapter);
172
            $application = $applicationMapper->fetchOne($device->application_id);
173
            if(!$application) {
174
                return new JsonModel([
175
                    'success' => false,
176
                    'data' => 'ERROR_APPLICATION_NOT_FOUND',
177
                ]);
178
            }
179
 
180
            if($application->status == Application::STATUS_INACTIVE) {
181
                return new JsonModel([
182
                    'success' => false,
183
                    'data' => 'ERROR_APPLICATION_IS_INACTIVE',
184
                ]);
185
            }
186
 
187
            $device->token = $token;
188
            $device->ip = Functions::getUserIP();
189
            $result = $deviceMapper->update($device);
190
 
191
 
192
            if($result) {
193
                return new JsonModel([
194
                    'success' => true,
195
                    'data' => [
196
                        'sync_id' => $sync_id
197
                    ]
198
                ]);
199
            } else {
200
                return new JsonModel([
201
                    'success' => false,
202
                    'data' => 'ERROR_THERE_WAS_AN_ERROR',
203
                ]);
204
            }
205
 
206
        }
207
 
208
        return new JsonModel([
209
            'success' => false,
210
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
211
        ]);
212
    }
213
 
214
    public function checkSessionAction()
215
    {
216
        $request = $this->getRequest();
217
 
218
        if($request->isPost()) {
219
            $device_uuid  = trim(filter_var($this->params()->fromPost('device_id', ''), FILTER_SANITIZE_STRING));
220
            $secret     = trim(filter_var($this->params()->fromPost('secret', ''), FILTER_SANITIZE_STRING));
221
            $rand       = filter_var($this->params()->fromPost('rand', ''), FILTER_SANITIZE_NUMBER_INT);
222
            $created    = trim(filter_var($this->params()->fromPost('created', ''), FILTER_SANITIZE_STRING));
223
 
224
            if(!$device_uuid || !$secret || !$rand || !$created) {
225
                return new JsonModel([
226
                    'success' => false,
227
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
228
                ]);
229
            }
230
 
231
            $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s',  $created);
232
            if(!$dt) {
233
                return new JsonModel([
234
                    'success' => false,
235
                    'data' => 'ERROR_PARAMETERS_ARE_INCORRECTLY_FORMATTED'
236
                ]);
237
            }
238
 
239
 
240
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
241
            $device = $deviceMapper->fetchOne($device_uuid);
242
            if(!$device) {
243
                return new JsonModel([
244
                    'success' => false,
245
                    'data' => 'ERROR_DEVICE_NOT_FOUND'
246
                ]);
247
            }
248
 
249
 
250
            $passworVerification = md5($device->password . ':' . $created . ':'  . $rand);
251
            if($secret != $passworVerification) {
252
                return new JsonModel([
253
                    'success' => false,
254
                    'data' => 'ERROR_WEBSERVICE_PASSWORD'
255
                ]);
256
            }
257
 
258
 
259
            $userMapper = UserMapper::getInstance($this->adapter);
260
            $user = $userMapper->fetchOne($device->user_id);
261
 
262
            if(User::BLOCKED_YES == $user->blocked) {
263
                return new JsonModel([
264
                    'success' => false,
265
                    'data' => 'ERROR_USER_IS_BLOCKED'
266
                ]);
267
            }
268
 
269
            if(User::STATUS_INACTIVE == $user->status) {
270
                return new JsonModel([
271
                    'success' => false,
272
                    'data' =>'ERROR_USER_IS_INACTIVE'
273
                ]);
274
            }
275
 
276
 
277
            return new JsonModel([
278
                'success' => true,
279
                'data' => [
280
                    'user_uuid' => $device->user_uuid
281
                ]
282
            ]);
283
 
284
        }
285
 
286
        return new JsonModel([
287
            'success' => false,
288
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
289
        ]);
290
    }
291
 
292
    public function deviceAction()
293
    {
294
 
295
        $rawdata = file_get_contents("php://input");
296
        error_log('$rawdata = ' . $rawdata );
297
 
298
        $request = $this->getRequest();
299
 
300
        if($request->isPost()) {
301
            //print_r($_POST);
302
 
303
 
304
            $application_id = filter_var($this->params()->fromPost('application_id', 0), FILTER_SANITIZE_NUMBER_INT);
305
            $device_uuid    = filter_var($this->params()->fromPost('device_uuid', ''), FILTER_SANITIZE_STRING);
306
            $manufacturer   = filter_var($this->params()->fromPost('manufacturer', ''), FILTER_SANITIZE_STRING);
307
            $platform       = filter_var($this->params()->fromPost('platform', ''), FILTER_SANITIZE_STRING);
308
            $brand          = filter_var($this->params()->fromPost('brand', ''), FILTER_SANITIZE_STRING);
309
            $version        = filter_var($this->params()->fromPost('version', ''), FILTER_SANITIZE_STRING);
310
            $model          = filter_var($this->params()->fromPost('model', ''), FILTER_SANITIZE_STRING);
311
            $sync_id        = filter_var($this->params()->fromPost('sync_id', ''), FILTER_SANITIZE_NUMBER_INT);
312
 
313
            $ok = $application_id && $device_uuid && strlen($device_uuid) == 36 && $sync_id;
314
            $ok = $ok && strlen($manufacturer) <= 250;
315
            $ok = $ok && strlen($brand) <= 250;
316
            $ok = $ok && strlen($version) <= 250;
317
            $ok = $ok && strlen($model) <= 250;
318
 
319
            if(!$ok) {
320
                return new JsonModel([
321
                    'success' => false,
322
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID',
323
                ]);
324
            }
325
 
326
 
327
            $applicationMapper = ApplicationMapper::getInstance($this->adapter);
328
            $application = $applicationMapper->fetchOne($application_id);
329
            if(!$application) {
330
                return new JsonModel([
331
                    'success' => false,
332
                    'data' => 'ERROR_APPLICATION_NOT_FOUND',
333
                ]);
334
            }
335
 
336
            if($application->status == Application::STATUS_INACTIVE) {
337
                return new JsonModel([
338
                    'success' => false,
339
                    'data' => 'ERROR_APPLICATION_IS_INACTIVE',
340
                ]);
341
            }
342
 
343
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
344
            $device = $deviceMapper->fetchOne($device_uuid);
345
 
346
 
347
 
348
 
349
            if($device) {
350
                $device->platform       = $platform;
351
                $device->manufacturer   = $manufacturer;
352
                $device->brand          = $brand;
353
                $device->version        = $version;
354
                $device->model          = $model;
355
                $device->ip             = Functions::getUserIP();
356
                $result                 = $deviceMapper->update($device);
357
 
358
            } else {
359
                $device                 = new Device();
360
                $device->id             = $device_uuid;
361
                $device->application_id = $application->id;
362
                $device->manufacturer   = $manufacturer;
363
                $device->brand          = $brand;
364
                $device->version        = $version;
365
                $device->model          = $model;
366
                $device->platform       = $platform;
367
                $device->ip             = Functions::getUserIP();
368
                $device->aes            = Functions::generatePassword(16);
369
                $device->password       = Functions::generatePassword(32);
370
                $result                 = $deviceMapper->insert($device);
371
            }
372
 
373
 
374
 
375
            if($result) {
376
                return new JsonModel([
377
                    'success' => true,
378
                    'data' => [
379
                        'sync_id'   => $sync_id,
380
                        'aes'       => $device->aes,
381
                        'password'  => $device->password,
382
                    ]
383
                ]);
384
            } else {
385
                return new JsonModel([
386
                    'success' => false,
387
                    'data' => 'ERROR_THERE_WAS_AN_ERROR',
388
                ]);
389
            }
390
 
391
        }
392
 
393
        return new JsonModel([
394
            'success' => false,
395
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
396
        ]);
397
 
398
    }
399
 
400
    public function microlearningCheckChangesAction()
401
    {
402
        $request = $this->getRequest();
403
 
404
        if($request->isPost()) {
405
            $currentUserPlugin = $this->plugin('currentUserPlugin');
406
            $user = $currentUserPlugin->getUser();
407
 
408
            $rawdata = file_get_contents("php://input");
409
            error_log('$rawdata = ' . $rawdata );
410
 
411
 
412
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
413
 
414
 
415
            $device_uuid        = filter_var($this->params()->fromPost('device_uuid', ''), FILTER_SANITIZE_STRING);
416
            $max_date_changes   = filter_var($this->params()->fromPost('max_date_changes', ''), FILTER_SANITIZE_STRING);
417
            $max_ids            = filter_var($this->params()->fromPost('max_ids', ''), FILTER_SANITIZE_NUMBER_INT);
418
 
419
 
420
            $ids = [];
421
            for($i = 1; $i <= $max_ids; $i++)
422
            {
423
                $id = filter_var($this->params()->fromPost('id_' . $i, ''), FILTER_SANITIZE_STRING);
424
                if(empty($id)) {
425
                    continue;
426
                }
427
 
428
                $pattern = '/[A-Za-z0-9\-]+\|[A-Za-z0-9\-]+/';
429
                $matches = [];  preg_match($pattern, $id, $matches, PREG_OFFSET_CAPTURE);
430
                if(count($matches) > 1) {
431
                    array_push($ids, $matches[0]);
432
                }
433
 
434
            }
435
 
436
 
437
 
438
            if($max_date_changes) {
439
                $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $max_date_changes);
440
                if($dt) {
441
                  $max_date_changes = $dt->format('Y-m-d H:i:s');
442
                } else {
443
                    $max_date_changes = '';
444
                }
445
            } else {
446
                $max_date_changes = '';
447
            }
448
 
449
 
450
            error_log('device_uuid = ' . $device_uuid . ' max_date_changes = ' . $max_date_changes);
451
 
452
            $ok = $device_uuid && strlen($device_uuid);
453
 
454
            if(!$ok) {
455
                return new JsonModel([
456
                    'success' => false,
457
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID',
458
                ]);
459
            }
460
 
461
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
462
            $device = $deviceMapper->fetchOne($device_uuid);
463
 
464
 
465
            if(!$device) {
466
                return new JsonModel([
467
                    'success' => false,
468
                    'data' => 'ERROR_DEVICE_NOT_FOUND'
469
                ]);
470
            } else {
471
                $device->ip = Functions::getUserIP();
472
                $deviceMapper->update($device);
473
            }
474
 
475
            //Cargamos la fecha máxima del cambio
476
            $companyMicrolearningUserMapper = CompanyMicrolearningUserMapper::getInstance($this->adapter);
477
            $max_date_changes_db = $companyMicrolearningUserMapper->fetchMaxDateChanges($user->id);
478
 
479
            //Si la fecha es vacia agregamos la fecha máxima de la asignación de la capsula
480
            if(!$max_date_changes_db) {
481
                $companyUsers = [];
482
                $companyMicrolearningCapsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
483
                $capsules = $companyMicrolearningCapsuleUserMapper->fetchAllActiveByUserId($user->id);
484
                foreach($capsules as $capsule)
485
                {
486
 
487
 
488
 
489
                    if(empty($companyUsers[$capsule->company_id])) {
490
                        $companyUsers[$capsule->company_id] = $capsule->updated_on;
491
                    } else {
492
 
493
                        if($capsule->updated_on > $companyUsers[$capsule->company_id]) {
494
                            $companyUsers[$capsule->company_id] = $capsule->updated_on;
495
                        }
496
 
497
                    }
498
 
499
                }
500
 
501
                $max_date_changes_db = '';
502
                foreach($companyUsers as $company_id => $update_on)
503
                {
504
 
505
                    $max_date_changes_db = $max_date_changes_db < $update_on ? $update_on : $max_date_changes_db;
506
 
507
                    $companyMicrolearningUser = new CompanyMicrolearningUser();
508
                    $companyMicrolearningUser->company_id = $company_id;
509
                    $companyMicrolearningUser->user_id = $user->id;
510
                    $companyMicrolearningUser->added_on = $update_on;
511
                    $companyMicrolearningUser->updated_on = $update_on;
512
 
513
                    $companyMicrolearningUserMapper->insert($companyMicrolearningUser);
514
                }
515
            }
516
 
517
 
518
            error_log("max_date_changes = $max_date_changes, max_date_changes_db = $max_date_changes_db");
519
 
520
            //Si la que tiene el dispositivo es diferente a la fecha máxima almacenada
521
            $newCapsules = 0;
522
            if($max_date_changes != $max_date_changes_db) {
523
                if(is_array($ids)) {
524
                    $companyMicrolearningTopicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
525
                    $companyMicrolearningTopics = $companyMicrolearningTopicMapper->fetchAllActive();
526
 
527
                    $topics = [];
528
                    foreach($companyMicrolearningTopics as $topic)
529
                    {
530
                        $topics[$topic->id] = $topic->uuid;
531
                    }
532
 
533
                    $companyMicrolearningCapsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
534
                    $companyMicrolearningCapsules = $companyMicrolearningCapsuleMapper->fetchAllActiveAndPublic();
535
 
536
                    $capsules = [];
537
                    foreach($companyMicrolearningCapsules as $capsule)
538
                    {
539
                        $capsules[$capsule->id] = $capsule->uuid;
540
                    }
541
 
542
                    $companyMicrolearningCapsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
543
                    $user_capsules = $companyMicrolearningCapsuleUserMapper->fetchAllActiveByUserId($user->id);
544
 
545
                    foreach($user_capsules as $user_capsule)
546
                    {
547
                        $topic_uuid     = isset($topics[$user_capsule->topic_id]) ? $topics[$user_capsule->topic_id] : '';
548
                        $capsule_uuid   = isset($capsules[$user_capsule->capsule_id]) ?  $capsules[$user_capsule->capsule_id] : '';
549
 
550
                        if(!$topic_uuid || !$capsule_uuid) {
551
                            continue;
552
                        }
553
 
554
                        $key = $topic_uuid . '|' . $capsule_uuid;
555
                        if(!in_array($key, $ids)) {
556
                            $newCapsules++;
557
                        }
558
                    }
559
                }
560
            }
561
 
562
 
563
            //echo 'Vamos a lanzar un PUSH' . PHP_EOL;
564
            if($newCapsules) {
565
 
566
                if($device->token)
567
                {
568
 
569
                    $pushMapper = PushMapper::getInstance($this->adapter);
570
                    $pushTemplateMapper = PushTemplateMapper::getInstance($this->adapter);
571
                    $pushTemplate = $pushTemplateMapper->fetchOne(PushTemplate::ID_MICRO_LEARNING_NEW_CONTENT);
572
 
573
                    //echo 'PushTemplate' . PHP_EOL;
574
                    //print_r($pushTemplate);
575
 
576
                    $applicationMapper = ApplicationMapper::getInstance($this->adapter);
577
                    $application = $applicationMapper->fetchOne(Application::TWOGETSKILLS);
578
 
579
 
580
                    //echo 'Application';
581
                    //print_r($application);
582
                    if($pushTemplate && $application) {
583
                         $push = new Push();
584
                        $push->status = Push::STATUS_PENDING;
585
                        $push->data = json_encode([
586
                            'server' => [
587
                                'key' =>   $application->key,
588
                            ],
589
                            'push' => [
590
                                'registration_ids'   => [
591
                                    $device->token,
592
                                ],
593
                                'notification' => [
594
                                    'body' =>  $pushTemplate->body,
595
                                    'title' => $pushTemplate->title,
596
                                    'vibrate' => 1,
597
                                    'sound' =>  1,
598
 
599
 
600
                                ],
601
                                'data' => [
602
                                    'new_capsules' => $newCapsules,
603
                                ]
604
                            ]
605
                        ]);
606
                        $pushMapper->insert($push);
607
                    }
608
                }
609
 
610
                $dataSync = $this->getSyncData($user,false, false);
611
            } else {
612
                $dataSync = [];
613
            }
614
 
615
 
616
 
617
            //error_log('$max_date_changes_db = ' . $max_date_changes_db);
618
 
619
            $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $max_date_changes_db);
620
            if($dt) {
621
                $max_date_changes_db = $dt->format($serviceDatetimeFormat);
622
            } else {
623
                $max_date_changes_db = '';
624
            }
625
 
626
            $data = [
627
                'success'   => true,
628
                'data'      =>[
629
                    'user' => [
630
                        'uuid' => $user->uuid,
631
                        'first_name' => $user->first_name,
632
                        'last_name' => $user->last_name,
633
                        'email' => $user->email,
634
                        'image' => $this->url()->fromRoute('services/storage',['type' => 'user', 'code' => $user->uuid, 'filename' => $user->image], ['force_canonical' => true]),
635
                    ],
636
                    'max_date_changes' => $max_date_changes_db,
637
                    'topics'    => isset( $dataSync['topics'] ) ? $dataSync['topics'] : [],
638
                    'quizzes'   => isset( $dataSync['quizzes'] ) ? $dataSync['quizzes'] : [],
639
 
640
                ]
641
            ];
642
 
643
            //error_log(print_r($data, true));
644
 
645
            return new JsonModel($data);
646
        }
647
 
648
        return new JsonModel([
649
            'success' => false,
650
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
651
        ]);
652
 
653
    }
654
 
655
 
656
 
657
    public function microlearningRefreshAction()
658
    {
659
        $request = $this->getRequest();
660
 
661
        if($request->isGet()) {
662
            $currentUserPlugin = $this->plugin('currentUserPlugin');
663
            $user = $currentUserPlugin->getUser();
664
 
665
            $dataSync = $this->getSyncData($user,false, false);
666
 
667
            //Cargamos la fecha máxima del cambio
668
            $companyMicrolearningUserMapper = CompanyMicrolearningUserMapper::getInstance($this->adapter);
669
            $max_date_changes_db = $companyMicrolearningUserMapper->fetchMaxDateChanges($user->id);
670
 
671
            //Si la fecha es vacia agregamos la fecha máxima de la asignación de la capsula
672
            if(!$max_date_changes_db) {
673
                $companyUsers = [];
674
                $companyMicrolearningCapsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
675
                $capsules = $companyMicrolearningCapsuleUserMapper->fetchAllActiveByUserId($user->id);
676
                foreach($capsules as $capsule)
677
                {
678
 
679
 
680
 
681
                    if(empty($companyUsers[$capsule->company_id])) {
682
                        $companyUsers[$capsule->company_id] = $capsule->updated_on;
683
                    } else {
684
 
685
                        if($capsule->updated_on > $companyUsers[$capsule->company_id]) {
686
                            $companyUsers[$capsule->company_id] = $capsule->updated_on;
687
                        }
688
 
689
                    }
690
 
691
                }
692
 
693
                $max_date_changes_db = '';
694
                foreach($companyUsers as $company_id => $update_on)
695
                {
696
 
697
                    $max_date_changes_db = $max_date_changes_db < $update_on ? $update_on : $max_date_changes_db;
698
 
699
                    $companyMicrolearningUser = new CompanyMicrolearningUser();
700
                    $companyMicrolearningUser->company_id = $company_id;
701
                    $companyMicrolearningUser->user_id = $user->id;
702
                    $companyMicrolearningUser->added_on = $update_on;
703
                    $companyMicrolearningUser->updated_on = $update_on;
704
 
705
                    $companyMicrolearningUserMapper->insert($companyMicrolearningUser);
706
                }
707
            }
708
 
709
            $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $max_date_changes_db);
710
            if($dt) {
711
                $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
712
                $max_date_changes_db = $dt->format($serviceDatetimeFormat);
713
            } else {
714
                $max_date_changes_db = '';
715
            }
716
 
717
            return new JsonModel([
718
                'success'   => true,
719
                'data'      =>[
720
                    'user' => [
721
                        'uuid' => $user->uuid,
722
                        'first_name' => $user->first_name,
723
                        'last_name' => $user->last_name,
724
                        'email' => $user->email,
725
                        'image' => $this->url()->fromRoute('services/storage',['type' => 'user', 'code' => $user->uuid, 'filename' => $user->image], ['force_canonical' => true]),
726
                    ],
727
                    'max_date_changes' => $max_date_changes_db,
728
                    'topics'    => $dataSync['topics'],
729
                    'quizzes'   => $dataSync['quizzes'],
730
 
731
                ]
732
            ]);
733
        }
734
 
735
        return new JsonModel([
736
            'success' => false,
737
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
738
        ]);
739
    }
740
 
741
 
742
    public function signinAction()
743
    {
744
        $request = $this->getRequest();
745
 
746
        if($request->isPost()) {
747
 
748
 
749
            $rawdata = file_get_contents("php://input");
750
            error_log('$rawdata = ' . $rawdata );
751
 
752
 
753
            $application_id = filter_var($this->params()->fromPost('application_id', 0), FILTER_SANITIZE_NUMBER_INT);
754
            $device_uuid    = filter_var($this->params()->fromPost('device_uuid', ''), FILTER_SANITIZE_STRING);
755
            $email          = filter_var($this->params()->fromPost('email', ''), FILTER_SANITIZE_EMAIL);
756
            $password       = filter_var($this->params()->fromPost('password', ''), FILTER_SANITIZE_STRING);
757
            //$encrypter      = filter_var($this->params()->fromPost('encrypter', ''), FILTER_SANITIZE_STRING);
758
 
759
 
760
 
761
            $ok = $application_id && $device_uuid && strlen($device_uuid) == 36;
762
            $ok = $ok && $email && $password;
763
            //$ok = $ok && in_array($encrypter, ['CryptoJsAes','RNCryptor','AesCipher']);
764
 
765
            if(!$ok) {
766
                return new JsonModel([
767
                    'success' => false,
768
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID',
769
                ]);
770
            }
771
 
772
 
773
            $applicationMapper = ApplicationMapper::getInstance($this->adapter);
774
            $application = $applicationMapper->fetchOne($application_id);
775
            if(!$application) {
776
                return new JsonModel([
777
                    'success' => false,
778
                    'data' => 'ERROR_APPLICATION_NOT_FOUND',
779
                ]);
780
            }
781
 
782
            if($application->status == Application::STATUS_INACTIVE) {
783
                return new JsonModel([
784
                    'success' => false,
785
                    'data' => 'ERROR_APPLICATION_IS_INACTIVE',
786
                ]);
787
            }
788
 
789
 
790
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
791
            $device = $deviceMapper->fetchOne($device_uuid);
792
            if(!$device) {
793
                $device                 = new Device();
794
                $device->id             = $device_uuid;
795
                $device->application_id = $application->id;
796
                $device->ip             = Functions::getUserIP();
797
                $device->aes            = Functions::generatePassword(16);
798
                $device->password       = Functions::generatePassword(32);
799
                $result                 = $deviceMapper->insert($device);
800
 
801
                if(!$result) {
802
                    return new JsonModel([
803
                        'success' => false,
804
                        'data' => 'ERROR_DEVICE_NOT_FOUND',
805
                    ]);
806
                }
807
            }
808
 
809
            /*
810
            if($encrypter == 'CryptoJsAes') {
811
 
812
 
813
                $email = html_entity_decode($email);
814
                $password = html_entity_decode($password);
815
 
816
 
817
                ob_start();
818
 
819
                $email      = CryptoJsAes::decrypt($email, $device->aes);
820
                $password   = CryptoJsAes::decrypt($password, $device->aes);
821
 
822
                ob_end_clean();
823
 
824
                if(!$email || !$password) {
825
                    return new JsonModel([
826
                        'success' => false,
827
                        'data' => 'ERROR_WEBSERVICE_PASSWORD_ENCRYPTION_FAILED',
828
                    ]);
829
                }
830
            } else if($encrypter == 'RNCryptor') {
831
                $cryptor = new \RNCryptor\RNCryptor\Decryptor;
832
                $email = $cryptor->decrypt($email, $device->aes);
833
                $password = $cryptor->decrypt($password, $device->aes);
834
 
835
                if(!$email || !$password) {
836
                    return new JsonModel([
837
                        'success' => false,
838
                        'data' => 'ERROR_WEBSERVICE_PASSWORD_ENCRYPTION_FAILED',
839
                    ]);
840
                }
841
 
842
 
843
            } else if($encrypter == 'AesCipher') {
844
 
845
                $emailDecrypted = AesCipher::decrypt($device->aes,$email);
846
                $passwordDecrypted = AesCipher::decrypt($device->aes,$password);
847
                if($emailDecrypted->hasError() || $passwordDecrypted->hasError()) {
848
                    return new JsonModel([
849
                        'success' => false,
850
                        'data' => 'ERROR_WEBSERVICE_PASSWORD_ENCRYPTION_FAILED',
851
                    ]);
852
                }
853
 
854
                $email = $emailDecrypted->getData();
855
                $password = $passwordDecrypted->getData();
856
            } else {
857
                return new JsonModel([
858
                    'success' => false,
859
                    'data' => 'ERROR_WEBSERVICE_PASSWORD_ENCRYPTION_FAILED',
860
                ]);
861
            }*/
862
 
863
 
864
            $authAdapter = new AuthAdapter($this->adapter);
865
            $authAdapter->setData($email, $password);
866
 
867
            $authService = new AuthenticationService();
868
            $result = $authService->authenticate($authAdapter);
869
 
870
            if($result->getCode() == AuthResult::SUCCESS) {
871
 
872
                $userMapper = UserMapper::getInstance($this->adapter);
873
                $user = $userMapper->fetchOneByEmail($email);
874
 
875
 
876
                $device->user_id    = $user->id;
877
                $device->ip         = Functions::getUserIP();
878
                if($deviceMapper->update($device)) {
879
 
880
                    $ip = Functions::getUserIP();
881
 
882
                    $deviceHistoryMapper = DeviceHistoryMapper::getInstance($this->adapter);
883
                    $deviceHistory = $deviceHistoryMapper->fetchOneByDeviceIdAndUserIdAndIp($device->id, $user->id, $ip);
884
                    if($deviceHistory) {
885
                        $deviceHistoryMapper->update($deviceHistory);
886
                    } else {
887
                        $deviceHistory = new DeviceHistory();
888
                        $deviceHistory->device_id = $device->id;
889
                        $deviceHistory->user_id = $user->id;
890
                        $deviceHistory->ip = $ip;
891
                        $deviceHistoryMapper->insert($deviceHistory);
892
                    }
893
 
894
                    $pushMapper = PushMapper::getInstance($this->adapter);
895
 
896
                    $userDevices =  $deviceMapper->fetchAllByUserId($user->id);
897
                    foreach($userDevices as $userDevice)
898
                    {
899
 
900
 
901
                        if($userDevice->id != $device->id && $userDevice->token) {
902
 
903
                            $push = new Push();
904
                            $push->status = Push::STATUS_PENDING;
905
                            $push->data = json_encode([
906
                                'server' => [
907
                                    'key' =>   $application->key
908
                                 ],
909
                                 'push' => [
910
                                    'registration_ids'   => [
911
                                        $userDevice->token,
912
                                     ],
913
                                     /*'notification' => [
914
                                         'body' =>  'Se registro un inicio de sessión desde otro dispositivo',
915
                                         'title' => 'Inicio de sessión',
916
                                         'vibrate' => 1,
917
                                         'sound' =>  1
918
                                     ],*/
919
                                    'data' => [
920
                                        'command' => 'signout'
921
                                    ]
922
                                 ]
923
                             ]);
924
 
925
                            $pushMapper->insert($push);
926
 
927
                        }
928
                    }
929
 
930
 
931
                    $companyUsers = [];
932
                    $companyMicrolearningCapsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
933
                    $capsules = $companyMicrolearningCapsuleUserMapper->fetchAllActiveByUserId($user->id);
934
                    foreach($capsules as $capsule)
935
                    {
936
 
937
 
938
 
939
                        if(empty($companyUsers[$capsule->company_id])) {
940
                            $companyUsers[$capsule->company_id] = $capsule->updated_on;
941
                        } else {
942
 
943
                            if($capsule->updated_on > $companyUsers[$capsule->company_id]) {
944
                                $companyUsers[$capsule->company_id] = $capsule->updated_on;
945
                            }
946
 
947
                        }
948
 
949
                    }
950
 
951
                    $companyMicrolearningUserMapper = CompanyMicrolearningUserMapper::getInstance($this->adapter);
952
 
953
                    $maxDateChanges = $companyMicrolearningUserMapper->fetchMaxDateChanges($user->id);
954
                    if(!$maxDateChanges) {
955
 
956
 
957
                        $maxDateChanges = '';
958
                        foreach($companyUsers as $company_id => $update_on)
959
                        {
960
 
961
                            $maxDateChanges = $maxDateChanges < $update_on ? $update_on : $maxDateChanges;
962
 
963
                            $companyMicrolearningUser = new CompanyMicrolearningUser();
964
                            $companyMicrolearningUser->company_id = $company_id;
965
                            $companyMicrolearningUser->user_id = $user->id;
966
                            $companyMicrolearningUser->added_on = $update_on;
967
                            $companyMicrolearningUser->updated_on = $update_on;
968
 
969
                            $companyMicrolearningUserMapper->insert($companyMicrolearningUser);
970
                        }
971
 
972
 
973
                    }
974
 
975
 
976
 
977
                   $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $maxDateChanges);
978
                   if($dt) {
979
                       $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
980
                       $maxDateChanges = $dt->format($serviceDatetimeFormat);
981
                   } else {
982
                       $maxDateChanges = '';
983
                   }
984
 
985
 
986
                    $data = [
987
                        'success'   => true,
988
                        'data'      =>[
989
                            'user' => [
990
                                'uuid' => $user->uuid,
991
                                'first_name' => $user->first_name,
992
                                'last_name' => $user->last_name,
993
                                'email' => $user->email,
994
                                'image' => $this->url()->fromRoute('services/storage',['type' => 'user', 'code' => $user->uuid, 'filename' => $user->image], ['force_canonical' => true]),
995
 
996
                             ],
997
                            'max_date_changes' => $maxDateChanges,
998
                            'device' => [
999
                                'aes' => $device->aes,
1000
                                'password' => $device->password
1001
                            ]
1002
 
1003
                        ]
1004
                    ];
1005
 
1006
                    if($application->id == Application::TWOGETSKILLS) {
1007
                        $dataSync = $this->getSyncData($user);
1008
 
1009
                        $data['data']['topics'] = $dataSync['topics'];
1010
                        $data['data']['quizzes'] = $dataSync['quizzes'];
1011
                        $data['data']['userlog'] = $dataSync['userlog'];
1012
                        $data['data']['progress'] = $dataSync['progress'];
1013
                    }
1014
 
1015
 
1016
 
1017
                    return new JsonModel($data);
1018
 
1019
 
1020
 
1021
                } else {
1022
                    return new JsonModel([
1023
                        'success' => false,
1024
                        'data' => 'ERROR_THERE_WAS_AN_ERROR',
1025
                    ]);
1026
                }
1027
 
1028
 
1029
            } else {
1030
                $message = $result->getMessages()[0];
1031
                if(!in_array($message, ['ERROR_USER_NOT_FOUND', 'ERROR_USER_PROVIDER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
1032
                    'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
1033
                    'ERROR_ENTERED_PASS_INCORRECT_1'])) {
1034
                }
1035
 
1036
                switch($message)
1037
                {
1038
                    case 'ERROR_USER_NOT_FOUND' :
1039
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1040
                        break;
1041
 
1042
                    case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED' :
1043
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1044
                        break;
1045
 
1046
                    case 'ERROR_USER_IS_BLOCKED' :
1047
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1048
                        break;
1049
 
1050
                    case 'ERROR_USER_IS_INACTIVE' :
1051
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1052
                        break;
1053
 
1054
 
1055
                    case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1056
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1057
                        break;
1058
 
1059
 
1060
                    case 'ERROR_ENTERED_PASS_INCORRECT_2' :
1061
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1062
                        break;
1063
 
1064
 
1065
                    case 'ERROR_ENTERED_PASS_INCORRECT_1' :
1066
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1067
                        break;
1068
 
1069
 
1070
                    default :
1071
                        $message = 'ERROR_UNKNOWN';
1072
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1073
                        break;
1074
 
1075
 
1076
                }
1077
 
1078
 
1079
                return new JsonModel([
1080
                    'success'   => false,
1081
                    'data'   => $message
1082
                ]);
1083
            }
1084
 
1085
        }
1086
 
1087
        return new JsonModel([
1088
            'success' => false,
1089
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1090
        ]);
1091
 
1092
    }
1093
 
1094
 
1095
 
1096
 
1097
    public function storageAction()
1098
    {
1099
 
1100
        // Get the file name from GET variable.
1101
        $code       = $this->params()->fromRoute('code', '');
1102
        $fileName   = $this->params()->fromRoute('filename', '');
1103
        $type       = $this->params()->fromRoute('type', 'user');
1104
 
1105
 
1106
        $no_image = $this->config['leaderslinked.images_default.no_image'];
1107
        $path = '';
1108
        switch($type)
1109
        {
1110
            case 'user' :
1111
                $no_image = $this->config['leaderslinked.images_default.user_image'];
1112
                $path = $this->config['leaderslinked.fullpath.user'];
1113
                break;
1114
 
1115
 
1116
            case 'user-profile' :
1117
                $no_image = $this->config['leaderslinked.images_default.user_profile'];
1118
                $path = $this->config['leaderslinked.fullpath.user'];
1119
                break;
1120
 
1121
            case 'user-cover' :
1122
                $no_image = $this->config['leaderslinked.images_default.user_cover'];
1123
                $path = $this->config['leaderslinked.fullpath.user'];
1124
                break;
1125
 
1126
            case 'company' :
1127
                $no_image = $this->config['leaderslinked.images_default.company_profile'];
1128
                $path = $this->config['leaderslinked.fullpath.company'];
1129
                break;
1130
 
1131
            case 'company-cover' :
1132
                $no_image = $this->config['leaderslinked.images_default.company_cover'];
1133
                $path = $this->config['leaderslinked.fullpath.company'];
1134
                break;
1135
 
1136
            case 'group' :
1137
                $no_image = $this->config['leaderslinked.images_default.group_profile'];
1138
                $path = $this->config['leaderslinked.fullpath.group'];
1139
                break;
1140
 
1141
            case 'group-cover' :
1142
                $no_image = $this->config['leaderslinked.images_default.group_cover'];
1143
                $path = $this->config['leaderslinked.fullpath.group'];
1144
                break;
1145
 
1146
            case 'job' :
1147
                $path = $this->config['leaderslinked.fullpath.job'];
1148
                break;
1149
 
1150
            case 'chat' :
1151
                $path = $this->config['leaderslinked.fullpath.chat'];
1152
                break;
1153
 
1154
            case 'feed' :
1155
                $path = $this->config['leaderslinked.fullpath.feed'];
1156
                break;
1157
 
1158
            case 'post' :
1159
                $path = $this->config['leaderslinked.fullpath.post'];
1160
                break;
1161
 
1162
            case 'microlearning-topic' :
1163
                $path = $this->config['leaderslinked.fullpath.microlearning_topic'];
1164
                break;
1165
 
1166
            case 'microlearning-capsule' :
1167
                $path = $this->config['leaderslinked.fullpath.microlearning_capsule'];
1168
                break;
1169
 
1170
            case 'microlearning-slide' :
1171
                $path = $this->config['leaderslinked.fullpath.microlearning_slide'];
1172
                break;
1173
 
1174
            default :
1175
                $path = $this->config['leaderslinked.fullpath.image'];
1176
                break;
1177
 
1178
        }
1179
        if($code && $fileName) {
1180
            $request_fullpath = $path . $code . DIRECTORY_SEPARATOR . $fileName;
1181
        } else {
1182
            $request_fullpath = $no_image;
1183
        }
1184
 
1185
        if(empty($fileName)) {
1186
            $extensions     = explode('.',$request_fullpath);
1187
            $extension      = strtolower(trim($extensions[count($extensions)-1]));
1188
            if ($extension=='jpg' || $extension=='jpeg' || $extension=='gif' || $extension == 'png') {
1189
                $request_fullpath =  $no_image;
1190
            }
1191
        }
1192
 
1193
 
1194
        if(file_exists($request_fullpath)) {
1195
 
1196
            // Try to open file
1197
            if (!is_readable($request_fullpath)) {
1198
                return $this->getResponse()->setStatusCode(500);
1199
            }
1200
 
1201
            // Get file size in bytes.
1202
            $fileSize = filesize($request_fullpath);
1203
 
1204
            // Get MIME type of the file.
1205
            $mimeType = mime_content_type($request_fullpath);
1206
            if($mimeType===false) {
1207
                $mimeType = 'application/octet-stream';
1208
            }
1209
 
1210
            $request_fullpath = trim($request_fullpath);
1211
            $length = strlen($request_fullpath);
1212
            if(substr($request_fullpath, $length - 1) == '/') {
1213
                $request_fullpath = substr($request_fullpath, 0, $length - 1);
1214
            }
1215
 
1216
 
1217
            $filename = basename($request_fullpath);
1218
 
1219
            header('Content-type: ' . $mimeType);
1220
            readfile($request_fullpath);
1221
 
1222
 
1223
            exit;
1224
            //header("X-Sendfile: $request_fullpath");
1225
            //header("Content-type: application/octet-stream");
1226
            //header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
1227
 
1228
 
1229
            /*
1230
 
1231
 
1232
            if ($fd = fopen ($request_fullpath, "r")) {
1233
 
1234
                $fsize = filesize($request_fullpath);
1235
 
1236
                header("Content-type: $mimeType");
1237
                header("Accept-Ranges: bytes");
1238
 
1239
                //header("Content-Disposition: attachment; filename=\"$filename\"");
1240
 
1241
                header("Content-length: $fsize");
1242
                header("Cache-control: private");
1243
 
1244
                while(!feof($fd)) {
1245
                    $buffer = fread($fd, 2048);
1246
                    echo $buffer;
1247
                }
1248
            }
1249
 
1250
            fclose ($fd);
1251
            exit;*/
1252
 
1253
 
1254
            /*
1255
             $fileContent = file_get_contents($request_fullpath);
1256
            $response = $this->getResponse();
1257
            $headers = $response->getHeaders();
1258
            $headers->addHeaderLine('Accept-Ranges: bytes');
1259
            $headers->addHeaderLine('Content-type: ' . $mimeType);
1260
            $headers->addHeaderLine('Content-length: ' . $fileSize);
1261
 
1262
            /*
1263
            Date: Tue, 13 Jul 2021 03:11:42 GMT
1264
            Server: Apache/2.4.41 (Ubuntu)
1265
            Last-Modified: Mon, 28 Jun 2021 16:43:04 GMT
1266
            ETag: "54e4-5c5d62eed581e"
1267
            Accept-Ranges: bytes
1268
            Content-Length: 21732
1269
            Cache-Control: max-age=1
1270
            Expires: Tue, 13 Jul 2021 03:11:43 GMT
1271
            Keep-Alive: timeout=5, max=100
1272
            Connection: Keep-Alive
1273
            Content-Type: audio/mpeg
1274
            */
1275
 
1276
            /*
1277
            if($fileContent!==false) {
1278
                error_log($_SERVER['REQUEST_URI']);
1279
                error_log($request_fullpath);
1280
                return $response->setContent($fileContent);
1281
 
1282
                header('Content-Type: '.$mimeType );
1283
                readfile_chunked($filename);
1284
                exit;
1285
 
1286
            } else {
1287
                error_log('500');
1288
                $this->getResponse()->setStatusCode(500);
1289
                return;
1290
            }*/
1291
        } else {
1292
            error_log('404');
1293
            return $this->getResponse()->setStatusCode(404);
1294
        }
1295
 
1296
        return $this->getResponse();
1297
    }
1298
 
1299
 
1300
    public function syncAction()
1301
    {
1302
        $request = $this->getRequest();
1303
 
1304
        if($request->isPost()) {
1305
 
1306
            $rawdata = file_get_contents("php://input");
1307
            error_log('$rawdata = ' . $rawdata );
1308
 
1309
 
1310
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1311
 
1312
            $device_uuid    = filter_var($this->params()->fromPost('device_uuid', ''), FILTER_SANITIZE_STRING);
1313
            $sync_id        = filter_var($this->params()->fromPost('sync_id', ''), FILTER_SANITIZE_NUMBER_INT);
1314
            $data           = $this->params()->fromPost('data', '');
1315
 
1316
 
1317
 
1318
            error_log('device_uuid = ' . $device_uuid);
1319
            error_log('sync_id = ' . $sync_id);
1320
            error_log(print_r($data, true));
1321
 
1322
 
1323
            $ok = $device_uuid && strlen($device_uuid) == 36 && $data && $sync_id;
1324
 
1325
            if(!$ok) {
1326
                return new JsonModel([
1327
                    'success' => false,
1328
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID',
1329
                ]);
1330
            }
1331
 
1332
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
1333
            $device = $deviceMapper->fetchOne($device_uuid);
1334
 
1335
 
1336
            if(!$device) {
1337
                return new JsonModel([
1338
                    'success' => false,
1339
                    'data' => 'ERROR_DEVICE_NOT_FOUND'
1340
                ]);
1341
            } else {
1342
                $device->ip = Functions::getUserIP();
1343
                $deviceMapper->update($device);
1344
            }
1345
 
1346
 
1347
 
1348
            $data = json_decode($data, true);
1349
            $sync_type      = isset($data['sync_type']) ? filter_var($data['sync_type'], FILTER_SANITIZE_STRING) : '';
1350
            $user_uuid      = isset($data['user_uuid']) ? filter_var($data['user_uuid'], FILTER_SANITIZE_STRING) : '';
1351
            $company_uuid   = isset($data['company_uuid']) ? filter_var($data['company_uuid'], FILTER_SANITIZE_STRING) :  '';
1352
 
1353
    //
1354
 
1355
            if($user_uuid && $device->application_id = Application::TWOGETSKILLS  && $company_uuid && in_array($sync_type, ['microlearning-progress', 'microlearning-userlog', 'microlearning-quiz'])) {
1356
                $userMapper = UserMapper::getInstance($this->adapter);
1357
                $user = $userMapper->fetchOneByUuid($user_uuid);
1358
 
1359
                if(!$user) {
1360
                    return new JsonModel([
1361
                        'success' => false,
1362
                        'data' => [
1363
                            'sync_id' => $sync_id,
1364
                            'message' => 'ERROR_USER_NOT_FOUND',
1365
                            'fatal' => true
1366
                        ]
1367
                    ]);
1368
                }
1369
 
1370
 
1371
                if($user->status != User::STATUS_ACTIVE) {
1372
                    return new JsonModel([
1373
                        'success' => false,
1374
                        'data' => [
1375
                            'sync_id' => $sync_id,
1376
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
1377
                            'fatal' => true
1378
                        ]
1379
                    ]);
1380
                }
1381
 
1382
                $companyMapper = CompanyMapper::getInstance($this->adapter);
1383
                $company = $companyMapper->fetchOneByUuid($company_uuid);
1384
                if(!$company) {
1385
                    return new JsonModel([
1386
                        'success' => false,
1387
                        'data' => [
1388
                            'sync_id' => $sync_id,
1389
                            'message' => 'ERROR_COMPANY_NOT_FOUND',
1390
                            'fatal' => true
1391
                        ]
1392
                    ]);
1393
                }
1394
 
1395
                if($company->status != Company::STATUS_ACTIVE) {
1396
                    return new JsonModel([
1397
                        'success' => false,
1398
                        'data' => [
1399
                            'sync_id' => $sync_id,
1400
                            'message' => 'ERROR_COMPANY_IS_NOT_FOUND',
1401
                            'fatal' => true
1402
                        ]
1403
                    ]);
1404
                }
1405
 
1406
 
1407
 
1408
 
1409
 
1410
                $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
1411
                $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($company->id, Service::MICRO_LEARNING);
1412
                if(!$companyService) {
1413
                    return new JsonModel([
1414
                        'success' => false,
1415
                        'data' => [
1416
                            'sync_id' => $sync_id,
1417
                            'message' => 'ERROR_COMPANY_SERVICE_NOT_FOUND',
1418
                            'fatal' => true
1419
                        ]
1420
                    ]);
1421
                }
1422
 
1423
                $serviceActive = true;
1424
                $now = date('Y-m-d H:i:s');
1425
                if($companyService->status == CompanyService::ACTIVE) {
1426
 
1427
                    if($now < $companyService->paid_from || $now > $companyService->paid_to) {
1428
                        $serviceActive = false;
1429
                    }
1430
 
1431
                } else {
1432
                    $serviceActive = false;
1433
                }
1434
 
1435
                if( !$serviceActive) {
1436
                    return new JsonModel([
1437
                        'success' => false,
1438
                        'data' => [
1439
                            'sync_id' => $sync_id,
1440
                            'message' => 'ERROR_COMPANY_SERVICE_IS_NOT_ACTIVE',
1441
                            'fatal' => true
1442
                        ]
1443
                    ]);
1444
                }
1445
 
1446
                $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
1447
                $topic_uuid = isset($data['topic_uuid']) ? filter_var($data['topic_uuid'], FILTER_SANITIZE_STRING) :  '';
1448
                if($topic_uuid) {
1449
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
1450
 
1451
                    if(!$topic) {
1452
                        return new JsonModel([
1453
                            'success' => false,
1454
                            'data' => [
1455
                                'sync_id' => $sync_id,
1456
                                'message' => 'ERROR_TOPIC_NOT_FOUND',
1457
                            ]
1458
                        ]);
1459
                    }
1460
 
1461
                    if($topic->company_id != $company->id) {
1462
                        return new JsonModel([
1463
                            'success' => false,
1464
                            'data' => [
1465
                                'sync_id' => $sync_id,
1466
                                'message' => 'ERROR_INVALID_PARAMETERS_TOPIC_COMPANY',
1467
                            ]
1468
                        ]);
1469
                    }
1470
 
1471
                } else {
1472
                    $topic = null;
1473
                }
1474
 
1475
                $capsule_uuid     = isset($data['capsule_uuid']) ? filter_var($data['capsule_uuid'], FILTER_SANITIZE_STRING) :  '';
1476
                $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
1477
                if($capsule_uuid) {
1478
 
1479
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
1480
                    if(!$capsule) {
1481
                        return new JsonModel([
1482
                            'success' => false,
1483
                            'data' => [
1484
                                'sync_id' => $sync_id,
1485
                                'message' => 'ERROR_CAPSULE_NOT_FOUND',
1486
                            ]
1487
                        ]);
1488
                    }
1489
 
1490
                    if(!$topic || $capsule->topic_id != $topic->id) {
1491
                        return new JsonModel([
1492
                            'success' => false,
1493
                            'data' => [
1494
                                'sync_id' => $sync_id,
1495
                                'message' => 'ERROR_INVALID_PARAMETERS_CAPSULE_TOPIC',
1496
                            ]
1497
                        ]);
1498
                    }
1499
                } else {
1500
                    $capsule = null;
1501
                }
1502
 
1503
                if($capsule) {
1504
 
1505
                    $capsuleActive = true;
1506
                    $capsuleMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
1507
                    $capsuleUser = $capsuleMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
1508
 
1509
 
1510
                    $now = date('Y-m-d H:i:s');
1511
                    if($capsuleUser && in_array($capsuleUser->access, [CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED,CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD ])) {
1512
 
1513
 
1514
                        if($capsuleUser->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
1515
 
1516
                            if($now < $capsuleUser->paid_from || $now > $capsuleUser->paid_to) {
1517
                                $capsuleActive = false;;
1518
                            }
1519
                        }
1520
 
1521
                    } else {
1522
                        $capsuleActive = false;
1523
                    }
1524
 
1525
                    if(!$capsuleActive) {
1526
                        return new JsonModel([
1527
                            'success' => false,
1528
                            'data' => [
1529
                                'sync_id' => $sync_id,
1530
                                'message' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
1531
                            ]
1532
                        ]);
1533
                    }
1534
                }
1535
 
1536
                $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
1537
                $slide_uuid      = isset($data['slide_uuid']) ? filter_var($data['slide_uuid'], FILTER_SANITIZE_STRING) :  '';
1538
                if($slide_uuid) {
1539
                    $slide = $slideMapper->fetchOneByUuid($slide_uuid);
1540
                    if(!$slide) {
1541
                        return new JsonModel([
1542
                            'success' => false,
1543
                            'data' => [
1544
                                'sync_id' => $sync_id,
1545
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
1546
                            ]
1547
                        ]);
1548
                    }
1549
 
1550
                    if(!$capsule || $slide->capsule_id != $capsule->id) {
1551
                        return new JsonModel([
1552
                            'success' => false,
1553
                            'data' => [
1554
                                'sync_id' => $sync_id,
1555
                                'message' => 'ERROR_INVALID_PARAMETERS_SLIDE_CAPSULE',
1556
                            ]
1557
                        ]);
1558
                    }
1559
                } else {
1560
                    $slide = null;
1561
                }
1562
 
1563
                if($sync_type == 'microlearning-quiz') {
1564
                    $ok = true;
1565
 
1566
                    $quiz_uuid = isset($data['quiz_uuid']) ? $data['quiz_uuid'] : '';
1567
                    $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
1568
 
1569
                    $quiz = $quizMapper->fetchOneByUuid($quiz_uuid);
1570
                    if(!$quiz) {
1571
                        return new JsonModel([
1572
                            'success' => false,
1573
                            'data' => [
1574
                                'sync_id' => $sync_id,
1575
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
1576
                            ]
1577
                        ]);
1578
                    }
1579
 
1580
                    if(!$capsule || $slide->capsule_id != $capsule->id) {
1581
                        return new JsonModel([
1582
                            'success' => false,
1583
                            'data' => [
1584
                                'sync_id' => $sync_id,
1585
                                'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_SLIDE',
1586
                            ]
1587
                        ]);
1588
                    }
1589
 
1590
                    $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
1591
 
1592
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1593
                    if(!$dt) {
1594
                        $ok = false;
1595
                    } else {
1596
                        $added_on = $dt->format('Y-m-d H:i:s');
1597
                    }
1598
 
1599
 
1600
                    if(isset($data['points'])) {
1601
                        $points = intval($data['points'], 10);
1602
                    } else {
1603
                        $ok = false;
1604
                    }
1605
 
1606
 
1607
                    if(isset($data['pass'])) {
1608
                        $status = $data['pass'] == 'yes' ? CompanyMicrolearningUserQuiz::STATUS_PASS : CompanyMicrolearningUserQuiz::STATUS_FAIL;
1609
                    } else {
1610
                        $ok = false;
1611
                    }
1612
 
1613
 
1614
                    if(!$ok) {
1615
                        return new JsonModel([
1616
                            'success' => false,
1617
                            'data' => [
1618
                                'sync_id' => $sync_id,
1619
                                'message' => 'ERROR_INVALID_PARAMETERS',
1620
                            ]
1621
                        ]);
1622
                    }
1623
 
1624
 
1625
                    $array_response = [];
1626
                    $response = isset($data['response']) ? intval($data['response'], 10) : 0;
1627
                    for($i = 0; $i < $response; $i++)
1628
                    {
1629
                        $question_uuid = isset($data["response_{$i}_question_uuid"]) ? $data["response_{$i}_question_uuid"] : '';
1630
                        $answer_uuid = isset($data["response_{$i}_answer_uuid"]) ? $data["response_{$i}_answer_uuid"] : '';
1631
                        $value = isset($data["response_{$i}_value"]) ?  intval($data["response_{$i}_value"], 10) : 0;
1632
                        $points = isset($data["response_{$i}_points"]) ?  intval($data["response_{$i}_points"], 10) : 0;
1633
 
1634
                        if($question_uuid && $answer_uuid)
1635
                        {
1636
                            array_push($array_response, [
1637
                                'question_uuid' => $question_uuid,
1638
                                'answer_uuid' => $answer_uuid,
1639
                                'value' => $value,
1640
                                'points' => $points
1641
 
1642
                            ]);
1643
                        }
1644
 
1645
 
1646
                    }
1647
 
1648
 
1649
                    $userQuiz = new CompanyMicrolearningUserQuiz();
1650
                    $userQuiz->company_id = $company->id;
1651
                    $userQuiz->topic_id = $topic->id;
1652
                    $userQuiz->capsule_id = $capsule->id;
1653
                    $userQuiz->slide_id = $slide->id;
1654
                    $userQuiz->quiz_id = $quiz->id;
1655
                    $userQuiz->user_id = $user->id;
1656
                    $userQuiz->added_on = $added_on;
1657
                    $userQuiz->points = $points;
1658
                    $userQuiz->status = $status;
1659
                    $userQuiz->response = json_encode($array_response);
1660
 
1661
                    $userQuizMapper = CompanyMicrolearningUserQuizMapper::getInstance($this->adapter);
1662
 
1663
                    if($userQuizMapper->insert($userQuiz)) {
1664
                        return new JsonModel([
1665
                            'success' => true,
1666
                            'data' => [
1667
                                'sync_id' => $sync_id
1668
                            ]
1669
                        ]);
1670
                    } else {
1671
                        return new JsonModel([
1672
                            'success' => false,
1673
                            'data' => [
1674
                                'sync_id' => $sync_id,
1675
                                'message' => $userQuizMapper->getError()
1676
                            ]
1677
                        ]);
1678
                    }
1679
 
1680
                }
1681
 
1682
 
1683
                if($sync_type == 'microlearning-progress') {
1684
                    $ok = true;
1685
 
1686
                    $type = isset($data['type']) ? $data['type'] : '';
1687
                    switch($type)
1688
                    {
1689
                        case CompanyMicrolearningUserProgress::TYPE_TOPIC :
1690
                            if(!$topic) {
1691
                                $ok = false;
1692
                            }
1693
                            break;
1694
 
1695
                        case CompanyMicrolearningUserProgress::TYPE_CAPSULE :
1696
                            if(!$topic || !$capsule) {
1697
                                $ok = false;
1698
                            }
1699
                            break;
1700
 
1701
                        case CompanyMicrolearningUserProgress::TYPE_SLIDE :
1702
                            if(!$topic || !$capsule || !$slide) {
1703
                                $ok = false;
1704
                            }
1705
                            break;
1706
 
1707
                        default :
1708
                            $ok = false;
1709
                            break;
1710
 
1711
                    }
1712
 
1713
 
1714
                    $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
1715
                    $updated_on = isset($data['updated_on'])    ? filter_var($data['updated_on'], FILTER_SANITIZE_STRING) :  '';
1716
 
1717
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1718
                    if(!$dt) {
1719
                        $ok = false;
1720
                    } else {
1721
                        $added_on = $dt->format('Y-m-d H:i:s');
1722
                    }
1723
 
1724
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $updated_on );
1725
                    if(!$dt) {
1726
                        $ok = false;
1727
                    } else {
1728
                        $updated_on = $dt->format('Y-m-d H:i:s');
1729
                    }
1730
 
1731
                    if(!$ok) {
1732
                        return new JsonModel([
1733
                            'success' => false,
1734
                            'data' => [
1735
                                'sync_id' => $sync_id,
1736
                                'message' => 'ERROR_INVALID_PARAMETERS',
1737
                            ]
1738
                        ]);
1739
                    }
1740
 
1741
                           //$progress                   = isset($data['progress'])                  ? floatval($data['progress']) :  0;
1742
                    //$total_slides               = isset($data['total_slides'])              ? intval($data['total_slides'], 10) :  0;
1743
                    //$view_slides                = isset($data['view_slides'])               ? intval($data['view_slides'], 10) :  0;
1744
                    $returning                  = isset($data['returning'])                 ? intval($data['returning'], 10) :  0;
1745
                    $returning_after_completed  = isset($data['returning_after_completed']) ? intval($data['returning_after_completed'], 10) :  0;
1746
                    $completed                  = isset($data['completed'])                 ? intval($data['completed'], 10) :  0;
1747
 
1748
                    $progressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
1749
                    $recordProgress = null;
1750
                    switch($type) {
1751
                        case CompanyMicrolearningUserProgress::TYPE_TOPIC  :
1752
                            $recordProgress = $progressMapper->fetchOneByUserIdAndTopicId($user->id, $topic->id);
1753
 
1754
                            break;
1755
 
1756
                        case CompanyMicrolearningUserProgress::TYPE_CAPSULE  :
1757
                            $recordProgress = $progressMapper->fetchOneByUseridAndCapsuleId($user->id, $capsule->id);
1758
                            break;
1759
 
1760
                        case CompanyMicrolearningUserProgress::TYPE_SLIDE  :
1761
                            $recordProgress = $progressMapper->fetchOneByUserIdAndSlideId($user->id, $slide->id);
1762
                            break;
1763
 
1764
                        default :
1765
                            $recordProgress= null;
1766
                    }
1767
 
1768
 
1769
                    if(!$recordProgress) {
1770
                        $recordProgress = new CompanyMicrolearningUserProgress();
1771
 
1772
                        $recordProgress->user_id    = $user->id;
1773
                        $recordProgress->type       = $type;
1774
                        $recordProgress->company_id = $topic->company_id;
1775
                        $recordProgress->topic_id   = $topic->id;
1776
                        $recordProgress->capsule_id = $capsule ? $capsule->id : null;
1777
                        $recordProgress->slide_id   = $slide ? $slide->id : null;
1778
                        $recordProgress->added_on   = $added_on;
1779
                    }
1780
                    $recordProgress->returning                  = $returning;
1781
                    $recordProgress->returning_after_completed  = $returning_after_completed;
1782
                    $recordProgress->completed                  = $completed;
1783
 
1784
                    if($type == CompanyMicrolearningUserProgress::TYPE_TOPIC ) {
1785
 
1786
                        $capsule_ids = [];
1787
                        $companyMicrolearningCapsuleUser = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
1788
                        $records =  $companyMicrolearningCapsuleUser->fetchAllActiveByUserId($user->id);
1789
                        foreach($records as $record)
1790
                        {
1791
                            if($now >= $record->paid_from || $now <= $capsuleUser->paid_to) {
1792
                                if(!in_array($record->capsule_id, $capsule_ids)) {
1793
                                    array_push($capsule_ids, $record->capsule_id);
1794
                                }
1795
                            }
1796
                        }
1797
 
1798
                        $view_slides    = 0;
1799
                        $total_slides   = 0;
1800
                        foreach($capsule_ids as $capsule_id)
1801
                        {
1802
                            $view_slides    += $progressMapper->fetchCountAllSlideViewedByUserIdAndCapsuleId($user->id, $capsule_id);
1803
                            $total_slides   += $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $topic->id, $capsule_id);
1804
 
1805
                        }
1806
 
1807
 
1808
                        $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
1809
                        $recordProgress->total_slides   = $total_slides;
1810
                        $recordProgress->view_slides    = $view_slides;
1811
                    }
1812
                    else if($type == CompanyMicrolearningUserProgress::TYPE_CAPSULE ) {
1813
                        $view_slides    = $progressMapper->fetchCountAllSlideViewedByUserIdAndCapsuleId($user->id, $capsule->id);
1814
                        $total_slides   = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $capsule->topic_id, $capsule->id);
1815
 
1816
                        $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
1817
                        $recordProgress->total_slides   = $total_slides;
1818
                        $recordProgress->view_slides    = $view_slides;
1819
                    }
1820
                    else {
1821
                        $recordProgress->progress       = 0;
1822
                        $recordProgress->total_slides   = 0;
1823
                        $recordProgress->view_slides    = 0;
1824
                    }
1825
 
1826
                    $recordProgress->updated_on = $updated_on;
1827
 
1828
 
1829
 
1830
                    if($recordProgress->id) {
1831
                        $result = $progressMapper->update($recordProgress);
1832
                    } else {
1833
                        $result = $progressMapper->insert($recordProgress);
1834
                    }
1835
 
1836
                    if($result) {
1837
                        return new JsonModel([
1838
                            'success' => true,
1839
                            'data' => [
1840
                                'sync_id' => $sync_id
1841
                            ]
1842
                        ]);
1843
                    } else {
1844
                        return new JsonModel([
1845
                            'success' => false,
1846
                            'data' => [
1847
                                'sync_id' => $sync_id,
1848
                                'message' => $progressMapper->getError()
1849
                            ]
1850
                        ]);
1851
                    }
1852
                }
1853
 
1854
 
1855
 
1856
                if($sync_type == 'microlearning-userlog') {
1857
                    $activity   = isset($data['activity'])      ? filter_var($data['activity'], FILTER_SANITIZE_STRING)  :  '';
1858
                    $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
1859
 
1860
 
1861
                    if(empty($activity)) {
1862
                        $ok = false;
1863
                    }
1864
 
1865
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1866
                    if(!$dt) {
1867
                        $ok = false;
1868
                    } else {
1869
                        $added_on = $dt->format('Y-m-d H:i:s');
1870
                    }
1871
 
1872
                    if(!$ok) {
1873
                        return new JsonModel([
1874
                            'success' => false,
1875
                            'data' => [
1876
                                'sync_id' => $sync_id,
1877
                                'message' => 'ERROR_INVALID_PARAMETERS',
1878
                            ]
1879
                        ]);
1880
                    }
1881
 
1882
                    $userLog = new CompanyMicrolearningUserLog();
1883
                    $userLog->activity      = $activity;
1884
                    $userLog->user_id       = $user->id;
1885
                    $userLog->company_id    = $topic->company_id;
1886
                    $userLog->topic_id      = $topic->id;
1887
                    $userLog->capsule_id    = $capsule ? $capsule->id : null;
1888
                    $userLog->slide_id      = $slide ? $slide->id : null;
1889
                    $userLog->added_on      = $added_on;
1890
 
1891
 
1892
 
1893
                    $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
1894
                    if($userLogMapper->insert($userLog)) {
1895
                        return new JsonModel([
1896
                            'success' => true,
1897
                            'data' => [
1898
                                'sync_id' => $sync_id
1899
                            ]
1900
                        ]);
1901
                    } else {
1902
                        return new JsonModel([
1903
                            'success' => false,
1904
                            'data' => [
1905
                                'sync_id' => $sync_id,
1906
                                'message' => $userLogMapper->getError()
1907
                            ]
1908
                        ]);
1909
                    }
1910
                }
1911
 
1912
            }
1913
 
1914
 
1915
 
1916
 
1917
            if($user_uuid && $sync_type == 'userlog' && $device->application_id = Application::TWOGETSKILLS) {
1918
 
1919
                $userMapper = UserMapper::getInstance($this->adapter);
1920
                $user = $userMapper->fetchOneByUuid($user_uuid);
1921
 
1922
                if(!$user) {
1923
                    return new JsonModel([
1924
                        'success' => false,
1925
                        'data' => [
1926
                            'sync_id' => $sync_id,
1927
                            'message' => 'ERROR_USER_NOT_FOUND',
1928
                            'fatal' => true
1929
                        ]
1930
                    ]);
1931
                }
1932
 
1933
 
1934
                if($user->status != User::STATUS_ACTIVE) {
1935
                    return new JsonModel([
1936
                        'success' => false,
1937
                        'data' => [
1938
                            'sync_id' => $sync_id,
1939
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
1940
                            'fatal' => true
1941
                        ]
1942
                    ]);
1943
                }
1944
 
1945
                $activity   = isset($data['activity'])      ? filter_var($data['activity'], FILTER_SANITIZE_STRING)  :  '';
1946
                $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
1947
 
1948
                if(empty($activity)) {
1949
                    $ok = false;
1950
                }
1951
 
1952
                $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1953
                if(!$dt) {
1954
                    $ok = false;
1955
                } else {
1956
                    $added_on = $dt->format('Y-m-d H:i:s');
1957
                }
1958
 
1959
                if(!$ok) {
1960
                    return new JsonModel([
1961
                        'success' => false,
1962
                        'data' => [
1963
                            'sync_id' => $sync_id,
1964
                            'message' => 'ERROR_INVALID_PARAMETERS',
1965
                        ]
1966
                    ]);
1967
                }
1968
 
1969
                $userLog = new CompanyMicrolearningUserLog();
1970
                $userLog->company_id = null;
1971
                $userLog->user_id = $user->id;
1972
                $userLog->activity = $activity;
1973
                $userLog->added_on = $added_on;
1974
 
1975
 
1976
                $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
1977
                if($userLogMapper->insert($userLog)) {
1978
                    return new JsonModel([
1979
                        'success' => true,
1980
                        'data' => [
1981
                            'sync_id' => $sync_id
1982
                        ]
1983
                    ]);
1984
                } else {
1985
                    return new JsonModel([
1986
                        'success' => false,
1987
                        'data' => [
1988
                            'sync_id' => $sync_id,
1989
                            'message' => $userLogMapper->getError()
1990
                        ]
1991
                    ]);
1992
                }
1993
            }
1994
 
1995
            return new JsonModel([
1996
                'success' => true,
1997
                'data' => [
1998
                    'sync_id' => $sync_id
1999
                ]
2000
            ]);
2001
 
2002
        }
2003
 
2004
        return new JsonModel([
2005
            'success' => false,
2006
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2007
        ]);
2008
    }
2009
 
2010
 
2011
    public function syncBatchAction()
2012
    {
2013
        $request = $this->getRequest();
2014
 
2015
        if($request->isPost()) {
2016
 
2017
            $rawdata = file_get_contents("php://input");
2018
            error_log('$rawdata = ' . $rawdata );
2019
 
2020
 
2021
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
2022
 
2023
            $device_uuid = filter_var($this->params()->fromPost('device_uuid', ''), FILTER_SANITIZE_STRING);
2024
            $max_records = filter_var($this->params()->fromPost('max_records', 0), FILTER_SANITIZE_NUMBER_INT);
2025
 
2026
 
2027
 
2028
            error_log('device_uuid = ' . $device_uuid . ' max_records = ' . $max_records);
2029
 
2030
            $ok = $device_uuid && strlen($device_uuid) == 36 && $max_records;
2031
 
2032
            if(!$ok) {
2033
                return new JsonModel([
2034
                    'success' => false,
2035
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID',
2036
                ]);
2037
            }
2038
 
2039
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
2040
            $device = $deviceMapper->fetchOne($device_uuid);
2041
 
2042
 
2043
            if(!$device) {
2044
                return new JsonModel([
2045
                    'success' => false,
2046
                    'data' => 'ERROR_DEVICE_NOT_FOUND'
2047
                ]);
2048
            } else {
2049
                $device->ip = Functions::getUserIP();
2050
                $deviceMapper->update($device);
2051
            }
2052
 
2053
            $result_sync_ids = [];
2054
 
2055
 
2056
 
2057
 
16 efrain 2058
            $users = [];
2059
            $companies = [];
2060
            $company_services = [];
2061
            $topics = [];
2062
            $capsules = [];
2063
            $capsule_users = [];
2064
            $slides = [];
2065
            $quizzes = [];
2066
            $questions = [];
2067
            $answers = [];
2068
 
2069
            $userMapper = UserMapper::getInstance($this->adapter);
2070
            $companyMapper = CompanyMapper::getInstance($this->adapter);
2071
            $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
2072
            $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
2073
            $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
2074
            $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
2075
            $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
2076
            $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
2077
            $questionMapper = CompanyMicrolearningQuestionMapper::getInstance($this->adapter);
2078
            $answerMapper = CompanyMicrolearningAnswerMapper::getInstance($this->adapter);
2079
 
2080
 
2081
            $userProgressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
2082
            $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2083
 
1 www 2084
            for($i = 1; $i <= $max_records; $i++)
2085
            {
2086
                $sync_id        = filter_var($this->params()->fromPost('record_sync_id' . $i, ''), FILTER_SANITIZE_NUMBER_INT);
2087
                $record_data    = $this->params()->fromPost('record_data' . $i, '');
2088
 
2089
                if(empty($record_data) || empty($sync_id )) {
2090
                    continue;
2091
                }
2092
 
2093
                $record         = json_decode($record_data, true);
2094
                $sync_type      = isset($record['sync_type']) ? filter_var($record['sync_type'],  FILTER_SANITIZE_STRING) : '';
2095
                $user_uuid      = isset($record['user_uuid']) ? filter_var($record['user_uuid'],  FILTER_SANITIZE_STRING) : '';
2096
                $company_uuid   = isset($record['company_uuid']) ? filter_var($record['company_uuid'], FILTER_SANITIZE_STRING) : '';
2097
 
2098
                if(!$sync_id) {
2099
                    continue;
2100
                }
2101
 
2102
                /***** INICIO MICROLEARNING *****/
2103
 
2104
                if($user_uuid && $device->application_id = Application::TWOGETSKILLS  && $company_uuid && in_array($sync_type, ['microlearning-progress', 'microlearning-userlog', 'microlearning-quiz'])) {
2105
 
16 efrain 2106
 
2107
                    if(isset($users[$user_uuid])) {
2108
                        $user = $users[$user_uuid];
2109
                    } else {
2110
 
2111
                        $user = $userMapper->fetchOneByUuid($user_uuid);
2112
                        if($user) {
2113
                            $users[$user_uuid] = $user;
2114
                        }
2115
                    }
2116
 
2117
 
1 www 2118
                    if(!$user) {
2119
                        array_push($result_sync_ids, [
2120
                            'success' => false,
2121
                            'sync_id' => $sync_id,
2122
                            'message' => 'ERROR_USER_NOT_FOUND',
2123
                            'fatal' => true
2124
                        ]);
2125
                        continue;
2126
                    }
2127
 
2128
 
2129
                    if($user->status != User::STATUS_ACTIVE) {
2130
                        array_push($result_sync_ids, [
2131
                            'success' => false,
2132
                            'sync_id' => $sync_id,
2133
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
2134
                            'fatal' => true
2135
                        ]);
2136
                        continue;
2137
                    }
2138
 
16 efrain 2139
 
2140
                    if(isset($companies[$company_uuid])) {
2141
                        $company = $companies[$company_uuid];
2142
                    } else {
2143
                        $company = $companyMapper->fetchOneByUuid($company_uuid);
2144
                        if($company) {
2145
                            $companies[$company_uuid] = $company;
2146
                        }
2147
                    }
2148
 
2149
 
2150
 
2151
 
1 www 2152
                    if(!$company) {
2153
                        array_push($result_sync_ids, [
2154
                            'success' => false,
2155
                            'sync_id' => $sync_id,
2156
                            'message' => 'ERROR_COMPANY_NOT_FOUND',
2157
                            'fatal' => true
2158
                        ]);
2159
                        continue;
2160
                    }
2161
 
2162
                    if($company->status != Company::STATUS_ACTIVE) {
2163
                        array_push($result_sync_ids, [
2164
                            'success' => false,
2165
                            'sync_id' => $sync_id,
2166
                            'message' => 'ERROR_COMPANY_IS_NOT_FOUND',
2167
                            'fatal' => true
2168
                        ]);
2169
                        continue;
2170
                    }
2171
 
2172
 
2173
 
16 efrain 2174
                    $key = $company->id . '-' .  Service::MICRO_LEARNING;
2175
                    if(isset($company_services[$key])) {
2176
                        $companyService = $company_services[$key];
2177
                    } else {
2178
                        $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($company->id, Service::MICRO_LEARNING);
2179
                        if($companyService) {
2180
                            $company_services[$key] = $companyService;
2181
                        }
2182
                    }
1 www 2183
 
2184
                    if(!$companyService) {
2185
                        array_push($result_sync_ids, [
2186
                            'success' => false,
2187
                            'sync_id' => $sync_id,
2188
                            'message' => 'ERROR_COMPANY_SERVICE_NOT_FOUND',
2189
                            'fatal' => true
2190
                        ]);
2191
                        continue;
2192
                    }
2193
 
2194
                    $serviceActive = true;
2195
                    $now = date('Y-m-d H:i:s');
2196
                    if($companyService->status == CompanyService::ACTIVE) {
2197
 
2198
                        if($now < $companyService->paid_from || $now > $companyService->paid_to) {
2199
                            $serviceActive = false;
2200
                        }
2201
 
2202
                    } else {
2203
                        $serviceActive = false;
2204
                    }
2205
 
2206
                    if( !$serviceActive) {
2207
                        array_push($result_sync_ids, [
2208
                            'success' => false,
2209
                            'sync_id' => $sync_id,
2210
                            'message' => 'ERROR_COMPANY_SERVICE_IS_NOT_ACTIVE',
2211
                            'fatal' => true
2212
                        ]);
2213
                        continue;
2214
                    }
2215
 
16 efrain 2216
 
1 www 2217
                    $topic_uuid = isset($record['topic_uuid']) ? filter_var($record['topic_uuid'], FILTER_SANITIZE_STRING) :  '';
2218
                    if($topic_uuid) {
2219
 
16 efrain 2220
                        if(isset($topics[$topic_uuid])) {
2221
                            $topic = $topics[$topic_uuid];
2222
                        } else {
2223
                            $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2224
                            if($topic) {
2225
                                $topics[$topic_uuid] = $topic;
2226
                            }
2227
                        }
2228
 
1 www 2229
                        if(!$topic) {
2230
                            array_push($result_sync_ids, [
2231
                                'success' => false,
2232
                                'sync_id' => $sync_id,
2233
                                'message' => 'ERROR_TOPIC_NOT_FOUND',
2234
                            ]);
2235
                            continue;
2236
                        }
2237
 
2238
                        if($topic->company_id != $company->id) {
2239
                            array_push($result_sync_ids, [
2240
                                'success' => false,
2241
                                'sync_id' => $sync_id,
2242
                                'message' => 'ERROR_INVALID_PARAMETERS_TOPIC_COMPANY',
2243
                            ]);
2244
                            continue;
2245
                        }
2246
 
2247
                    } else {
2248
                        $topic = null;
2249
                    }
2250
 
2251
                    $capsule_uuid     = isset($record['capsule_uuid']) ? filter_var($record['capsule_uuid'], FILTER_SANITIZE_STRING) :  '';
16 efrain 2252
 
1 www 2253
                    if($capsule_uuid) {
2254
 
16 efrain 2255
                        if(isset($capsules[$capsule_uuid])) {
2256
                            $capsule = $capsules[$capsule_uuid];
2257
                        } else {
2258
                            $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2259
                            if($capsule) {
2260
                                $capsules[$capsule_uuid] = $capsule;
2261
                            }
2262
                        }
1 www 2263
                        if(!$capsule) {
2264
                            array_push($result_sync_ids, [
2265
                                'success' => false,
2266
                                'sync_id' => $sync_id,
2267
                                'message' => 'ERROR_CAPSULE_NOT_FOUND',
2268
                            ]);
2269
                            continue;
2270
                        }
2271
 
2272
                        if(!$topic || $capsule->topic_id != $topic->id) {
2273
                            array_push($result_sync_ids, [
2274
                                'success' => false,
2275
                                'sync_id' => $sync_id,
2276
                                'message' => 'ERROR_INVALID_PARAMETERS_CAPSULE_TOPIC',
2277
                            ]);
2278
                            continue;
2279
                        }
2280
                    } else {
2281
                        $capsule = null;
2282
                    }
2283
 
2284
                    if($capsule) {
2285
 
2286
                        $capsuleActive = true;
2287
 
16 efrain 2288
                        $key = $user->id . '-' . $capsule->id;
1 www 2289
 
16 efrain 2290
                        if(isset($capsule_users[$key])) {
2291
                            $capsuleUser = $capsule_users[$key];
2292
                        } else {
2293
 
2294
                            $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
2295
                            if($capsuleUser) {
2296
                                $capsule_users[$key] = $capsuleUser;
2297
                            }
2298
 
2299
                        }
2300
 
1 www 2301
                        $now = date('Y-m-d H:i:s');
2302
                        if($capsuleUser && in_array($capsuleUser->access, [CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED,CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD ])) {
2303
 
2304
 
2305
                            if($capsuleUser->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
2306
 
2307
                                if($now < $capsuleUser->paid_from || $now > $capsuleUser->paid_to) {
2308
                                    $capsuleActive = false;;
2309
                                }
2310
                            }
2311
 
2312
                        } else {
2313
                            $capsuleActive = false;
2314
                        }
2315
 
2316
                        if(!$capsuleActive) {
2317
                            array_push($result_sync_ids, [
2318
                                'success' => false,
2319
                                'sync_id' => $sync_id,
2320
                                'message' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
2321
                            ]);
2322
                            continue;
2323
                        }
2324
                    }
2325
 
16 efrain 2326
 
1 www 2327
                    $slide_uuid      = isset($record['slide_uuid']) ? filter_var($record['slide_uuid'], FILTER_SANITIZE_STRING) :  '';
2328
                    if($slide_uuid) {
16 efrain 2329
 
2330
                        if(isset($slides[$slide_uuid])) {
2331
                            $slide = $slides[$slide_uuid];
2332
                        } else {
2333
 
2334
                            $slide = $slideMapper->fetchOneByUuid($slide_uuid);
2335
                            if($slide) {
2336
                                $slides[$slide_uuid] = $slide;
2337
                            }
2338
                        }
1 www 2339
                        if(!$slide) {
2340
                            array_push($result_sync_ids, [
2341
                                'success' => false,
2342
                                'sync_id' => $sync_id,
2343
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
2344
                            ]);
2345
                            continue;
2346
                        }
2347
 
2348
                        if(!$capsule || $slide->capsule_id != $capsule->id) {
2349
                            array_push($result_sync_ids, [
2350
                                'success' => false,
2351
                                'sync_id' => $sync_id,
2352
                                'message' => 'ERROR_INVALID_PARAMETERS_SLIDE_CAPSULE',
2353
                            ]);
2354
                            continue;
2355
                        }
2356
                    } else {
2357
                        $slide = null;
2358
                    }
2359
 
2360
                    if($sync_type == 'microlearning-quiz') {
2361
                        $ok = true;
2362
 
2363
                        $quiz_uuid = isset($record['quiz_uuid']) ? $record['quiz_uuid'] : '';
16 efrain 2364
 
2365
                        if(isset($quizzes[$quiz_uuid])) {
2366
                            $quiz = $quizzes[$quiz_uuid];
2367
                        } else {
2368
                            $quiz = $quizMapper->fetchOneByUuid($quiz_uuid);
2369
                            if($quiz) {
2370
                                $quizzes[$quiz_uuid] = $quiz;
2371
                            }
2372
                        }
1 www 2373
                        if(!$quiz) {
2374
                            array_push($result_sync_ids, [
2375
                                'success' => false,
2376
                                'sync_id' => $sync_id,
2377
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
2378
                            ]);
2379
                            continue;
2380
                        }
2381
 
2382
                        if(!$capsule || $slide->capsule_id != $capsule->id) {
2383
                            array_push($result_sync_ids, [
2384
                                'success' => false,
2385
                                'sync_id' => $sync_id,
2386
                                'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_SLIDE',
2387
                            ]);
2388
                            continue;
2389
                        }
2390
 
2391
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2392
 
2393
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2394
                        if(!$dt) {
2395
                            $ok = false;
2396
                        } else {
2397
                            $added_on = $dt->format('Y-m-d H:i:s');
2398
                        }
2399
 
2400
                        if(isset($record['points'])) {
2401
                            $points = intval($record['points'], 10);
2402
                        } else {
2403
                            $ok = false;
2404
                        }
2405
 
2406
                        if(isset($record['pass'])) {
2407
                            $status = $record['pass'] == 'yes' ? CompanyMicrolearningUserQuiz::STATUS_PASS : CompanyMicrolearningUserQuiz::STATUS_FAIL;
2408
                        } else {
2409
                            $ok = false;
2410
                        }
2411
 
2412
                        if(!$ok) {
2413
                            array_push($result_sync_ids, [
2414
                                'success' => false,
2415
                                'sync_id' => $sync_id,
2416
                                'message' => 'ERROR_INVALID_PARAMETERS',
2417
                            ]);
2418
                            continue;
2419
                        }
2420
 
2421
                        $array_response = [];
2422
                        $response = isset($record['response']) ? intval($record['response'], 10) : 0;
2423
                        for($i = 0; $i < $response; $i++)
2424
                        {
2425
                            $question_uuid = isset($record["response_{$i}_question_uuid"]) ? $record["response_{$i}_question_uuid"] : '';
2426
                            $answer_uuid = isset($record["response_{$i}_answer_uuid"]) ? $record["response_{$i}_answer_uuid"] : '';
2427
                            $value = isset($record["response_{$i}_value"]) ?  intval($record["response_{$i}_value"], 10) : 0;
2428
                            $points = isset($record["response_{$i}_points"]) ?  intval($record["response_{$i}_points"], 10) : 0;
2429
 
16 efrain 2430
 
2431
                            if(isset($questions[$question_uuid])) {
2432
                                $question = $questions[$question_uuid];
2433
                            } else {
2434
                                $question = $questionMapper->fetchOneByUuid($question_uuid);
2435
                                if($question) {
2436
                                    $questions[$question_uuid] = $question;
2437
                                }
2438
                            }
2439
 
2440
                            if(!$question || $question->quiz_id != $quiz->id) {
2441
                                array_push($result_sync_ids, [
2442
                                    'success' => false,
2443
                                    'sync_id' => $sync_id,
2444
                                    'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_QUESTION_SLIDE',
1 www 2445
                                ]);
16 efrain 2446
                                continue;
2447
                            }
2448
 
2449
                            if(isset($answers[$answer_uuid])) {
2450
                                $answer = $answers[$answer_uuid];
2451
                            } else {
2452
                                $answer = $answerMapper->fetchOneByUuid($answer_uuid);
2453
                                if($answer) {
2454
                                    $answers[$answer_uuid] = $answer;
2455
                                }
2456
                            }
2457
 
2458
                            if($answer && $answer->question_id != $question->id) {
2459
                                array_push($result_sync_ids, [
2460
                                    'success' => false,
2461
                                    'sync_id' => $sync_id,
2462
                                    'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_ANSWER_SLIDE',
2463
                                ]);
2464
                                continue;
2465
                            }
2466
 
2467
                            array_push($array_response, [
2468
                                'question_uuid' => $question_uuid,
2469
                                'answer_uuid' => $answer_uuid,
2470
                                'value' => $value,
2471
                                'points' => $points
2472
                            ]);
1 www 2473
                        }
2474
 
2475
                        $userQuiz = new CompanyMicrolearningUserQuiz();
2476
                        $userQuiz->company_id = $company->id;
2477
                        $userQuiz->topic_id = $topic->id;
2478
                        $userQuiz->capsule_id = $capsule->id;
2479
                        $userQuiz->slide_id = $slide->id;
2480
                        $userQuiz->quiz_id = $quiz->id;
2481
                        $userQuiz->user_id = $user->id;
2482
                        $userQuiz->added_on = $added_on;
2483
                        $userQuiz->points = $points;
2484
                        $userQuiz->status = $status;
2485
                        $userQuiz->response = json_encode($array_response);
2486
 
2487
                        $userQuizMapper = CompanyMicrolearningUserQuizMapper::getInstance($this->adapter);
2488
 
2489
                        if($userQuizMapper->insert($userQuiz)) {
2490
                            array_push($result_sync_ids, [
2491
                                'success' => true,
2492
                                'sync_id' => $sync_id
2493
                            ]);
2494
                        } else {
2495
                            array_push($result_sync_ids, [
2496
                                'success' => false,
2497
                                'sync_id' => $sync_id,
2498
                                'message' => $userQuizMapper->getError()
2499
                            ]);
2500
                        }
2501
                        continue;
2502
                    }
2503
 
2504
                    if($sync_type == 'microlearning-progress') {
2505
                        $ok = true;
2506
 
2507
                        $type = isset($record['type']) ? $record['type'] : '';
2508
                        switch($type)
2509
                        {
2510
                            case CompanyMicrolearningUserProgress::TYPE_TOPIC :
2511
                                if(!$topic) {
2512
                                    $ok = false;
2513
                                }
2514
                                break;
2515
 
2516
                            case CompanyMicrolearningUserProgress::TYPE_CAPSULE :
2517
                                if(!$topic || !$capsule) {
2518
                                    $ok = false;
2519
                                }
2520
                                break;
2521
 
2522
                            case CompanyMicrolearningUserProgress::TYPE_SLIDE :
2523
                                if(!$topic || !$capsule || !$slide) {
2524
                                    $ok = false;
2525
                                }
2526
                                break;
2527
 
2528
                            default :
2529
                                $ok = false;
2530
                                break;
2531
                        }
2532
 
2533
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2534
                        $updated_on = isset($record['updated_on'])    ? filter_var($record['updated_on'], FILTER_SANITIZE_STRING) :  '';
2535
 
2536
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2537
                        if(!$dt) {
2538
                            $ok = false;
2539
                        } else {
2540
                            $added_on = $dt->format('Y-m-d H:i:s');
2541
                        }
2542
 
2543
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $updated_on );
2544
                        if(!$dt) {
2545
                            $ok = false;
2546
                        } else {
2547
                            $updated_on = $dt->format('Y-m-d H:i:s');
2548
                        }
2549
 
2550
                        if(!$ok) {
2551
                            array_push($result_sync_ids, [
2552
                                'success' => false,
2553
                                'sync_id' => $sync_id,
2554
                                'message' => 'ERROR_INVALID_PARAMETERS',
2555
                            ]);
2556
                            continue;
2557
                        }
2558
 
2559
                        //$progress                   = isset($record['progress'])                  ? floatval($record['progress']) :  0;
2560
                        //$total_slides               = isset($record['total_slides'])              ? intval($record['total_slides'], 10) :  0;
2561
                        //$view_slides                = isset($record['view_slides'])               ? intval($record['view_slides'], 10) :  0;
2562
                        $returning                  = isset($record['returning'])                 ? intval($record['returning'], 10) :  0;
2563
                        $returning_after_completed  = isset($record['returning_after_completed']) ? intval($record['returning_after_completed'], 10) :  0;
2564
                        $completed                  = isset($record['completed'])                 ? intval($record['completed'], 10) :  0;
2565
 
16 efrain 2566
 
1 www 2567
                        $recordProgress = null;
2568
                        switch($type) {
2569
                            case CompanyMicrolearningUserProgress::TYPE_TOPIC  :
16 efrain 2570
                                $recordProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($user->id, $topic->id);
1 www 2571
 
2572
                                break;
2573
 
2574
                            case CompanyMicrolearningUserProgress::TYPE_CAPSULE  :
16 efrain 2575
                                $recordProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($user->id, $capsule->id);
1 www 2576
                                break;
2577
 
2578
                            case CompanyMicrolearningUserProgress::TYPE_SLIDE  :
16 efrain 2579
                                $recordProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($user->id, $slide->id);
1 www 2580
                                break;
2581
 
2582
                            default :
2583
                                $recordProgress= null;
2584
                        }
2585
 
2586
 
2587
                        if(!$recordProgress) {
2588
                            $recordProgress = new CompanyMicrolearningUserProgress();
2589
 
2590
                            $recordProgress->user_id    = $user->id;
2591
                            $recordProgress->type       = $type;
2592
                            $recordProgress->company_id = $topic->company_id;
2593
                            $recordProgress->topic_id   = $topic->id;
2594
                            $recordProgress->capsule_id = $capsule ? $capsule->id : null;
2595
                            $recordProgress->slide_id   = $slide ? $slide->id : null;
2596
                            $recordProgress->added_on   = $added_on;
16 efrain 2597
                        } else {
2598
 
2599
                            if($recordProgress->updated_on > $updated_on) {
2600
                                array_push($result_sync_ids, [
2601
                                    'success' => true,
2602
                                    'sync_id' => $sync_id,
2603
                                ]);
2604
                                continue;
2605
                            }
2606
 
2607
 
2608
 
1 www 2609
                        }
2610
                        $recordProgress->returning                  = $returning;
2611
                        $recordProgress->returning_after_completed  = $returning_after_completed;
2612
                        $recordProgress->completed                  = $completed;
2613
 
2614
                        if($type == CompanyMicrolearningUserProgress::TYPE_TOPIC ) {
2615
 
2616
                            $capsule_ids = [];
2617
                            $companyMicrolearningCapsuleUser = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
2618
                            $records =  $companyMicrolearningCapsuleUser->fetchAllActiveByUserId($user->id);
2619
                            foreach($records as $record)
2620
                            {
2621
                                if($now >= $record->paid_from || $now <= $capsuleUser->paid_to) {
2622
                                    if(!in_array($record->capsule_id, $capsule_ids)) {
2623
                                        array_push($capsule_ids, $record->capsule_id);
2624
                                    }
2625
                                }
2626
                            }
2627
 
2628
                            $view_slides    = 0;
2629
                            $total_slides   = 0;
2630
                            foreach($capsule_ids as $capsule_id)
2631
                            {
16 efrain 2632
                                $view_slides    += $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndCapsuleId($user->id, $capsule_id);
1 www 2633
                                $total_slides   += $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $topic->id, $capsule_id);
2634
                            }
2635
 
2636
                            $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
2637
                            $recordProgress->total_slides   = $total_slides;
2638
                            $recordProgress->view_slides    = $view_slides;
2639
                        }
2640
                        else if($type == CompanyMicrolearningUserProgress::TYPE_CAPSULE ) {
16 efrain 2641
                            $view_slides    = $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndCapsuleId($user->id, $capsule->id);
1 www 2642
                            $total_slides   = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $capsule->topic_id, $capsule->id);
2643
 
2644
                            $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
2645
                            $recordProgress->total_slides   = $total_slides;
2646
                            $recordProgress->view_slides    = $view_slides;
2647
                        }
2648
                        else {
2649
                            $recordProgress->progress       = 0;
2650
                            $recordProgress->total_slides   = 0;
2651
                            $recordProgress->view_slides    = 0;
2652
                        }
2653
 
2654
                        $recordProgress->updated_on = $updated_on;
2655
 
2656
 
2657
 
2658
                        if($recordProgress->id) {
16 efrain 2659
                            $result = $userProgressMapper->update($recordProgress);
1 www 2660
                        } else {
16 efrain 2661
                            $result = $userProgressMapper->insert($recordProgress);
1 www 2662
                        }
2663
 
2664
                        if($result) {
2665
                            array_push($result_sync_ids, [
2666
                                'success' => true,
2667
                                'sync_id' => $sync_id
2668
                            ]);
2669
                        } else {
2670
                            array_push($result_sync_ids, [
2671
                                'success' => false,
2672
                                'sync_id' => $sync_id,
16 efrain 2673
                                'message' => $userProgressMapper->getError()
1 www 2674
                            ]);
2675
                        }
2676
                        continue;
2677
                    }
2678
 
2679
 
2680
 
2681
                    if($sync_type == 'microlearning-userlog') {
2682
                        $activity   = isset($record['activity'])      ? filter_var($record['activity'], FILTER_SANITIZE_STRING)  :  '';
2683
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2684
 
2685
 
2686
                        if(empty($activity)) {
2687
                            $ok = false;
2688
                        }
2689
 
2690
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2691
                        if(!$dt) {
2692
                            $ok = false;
2693
                        } else {
2694
                            $added_on = $dt->format('Y-m-d H:i:s');
2695
                        }
2696
 
2697
                        if(!$ok) {
2698
                            array_push($result_sync_ids, [
2699
                                'success' => false,
2700
                                'sync_id' => $sync_id,
2701
                                'message' => 'ERROR_INVALID_PARAMETERS',
2702
                            ]);
2703
                            continue;
2704
                        }
2705
 
2706
 
2707
 
2708
 
16 efrain 2709
                        $userLog = $userLogMapper->fetchLastBy($user->id);
2710
                        if($userLog) {
2711
                            $insert = $userLog->added_on <= $added_on;
2712
                        } else {
2713
                            $insert = true;
2714
                        }
2715
 
2716
 
2717
                        if($insert) {
2718
 
2719
                            $userLog = new CompanyMicrolearningUserLog();
2720
                            $userLog->activity      = $activity;
2721
                            $userLog->user_id       = $user->id;
2722
                            $userLog->company_id    = $topic->company_id;
2723
                            $userLog->topic_id      = $topic->id;
2724
                            $userLog->capsule_id    = $capsule ? $capsule->id : null;
2725
                            $userLog->slide_id      = $slide ? $slide->id : null;
2726
                            $userLog->added_on      = $added_on;
2727
 
2728
 
2729
 
2730
 
2731
                            if($userLogMapper->insert($userLog)) {
2732
                                array_push($result_sync_ids, [
2733
                                    'success' => true,
2734
                                    'sync_id' => $sync_id
2735
                                ]);
2736
                            } else {
2737
                                array_push($result_sync_ids, [
2738
                                    'success' => false,
2739
                                    'sync_id' => $sync_id,
2740
                                    'message' => $userLogMapper->getError()
2741
                                ]);
2742
                            }
2743
                        } else {
1 www 2744
                            array_push($result_sync_ids, [
2745
                                'success' => true,
16 efrain 2746
                                'sync_id' => $sync_id
1 www 2747
                            ]);
2748
                        }
2749
                        continue;
2750
                    }
2751
 
2752
                }
2753
 
2754
                /***** FIN MICROLEARNING *****/
2755
 
2756
 
2757
                /***** INICIO LOG DE USUARIO GENERAL *****/
2758
 
2759
                if($user_uuid && $sync_type == 'userlog' && $device->application_id = Application::TWOGETSKILLS) {
2760
 
2761
 
16 efrain 2762
                    if(isset($users[$user_uuid])) {
2763
                        $user = $users[$user_uuid];
2764
                    } else {
2765
                        $user = $userMapper->fetchOneByUuid($user_uuid);
2766
                        if($user) {
2767
                            $users[$user_uuid] = $user;
2768
                        }
2769
                    }
2770
 
2771
 
2772
 
2773
 
1 www 2774
                    if(!$user) {
2775
                        array_push($result_sync_ids, [
2776
                            'success' => false,
2777
                            'sync_id' => $sync_id,
2778
                            'message' => 'ERROR_USER_NOT_FOUND',
2779
                            'fatal' => true
2780
                        ]);
2781
                        continue;
2782
                    }
2783
 
2784
 
2785
                    if($user->status != User::STATUS_ACTIVE) {
2786
                        array_push($result_sync_ids, [
2787
                            'success' => false,
2788
                            'sync_id' => $sync_id,
2789
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
2790
                            'fatal' => true
2791
                        ]);
2792
                        continue;
2793
                    }
2794
 
2795
                    $activity   = isset($record['activity'])      ? filter_var($record['activity'], FILTER_SANITIZE_STRING)  :  '';
2796
                    $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2797
 
2798
                    if(empty($activity)) {
2799
                        $ok = false;
2800
                    }
2801
 
2802
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2803
                    if(!$dt) {
2804
                        $ok = false;
2805
                    } else {
2806
                        $added_on = $dt->format('Y-m-d H:i:s');
2807
                    }
2808
 
2809
                    if(!$ok) {
2810
                        array_push($result_sync_ids, [
2811
                            'success' => false,
2812
                            'sync_id' => $sync_id,
2813
                            'message' => 'ERROR_INVALID_PARAMETERS',
2814
                        ]);
2815
                        continue;
2816
                    }
2817
 
2818
 
16 efrain 2819
                    $userLog = $userLogMapper->fetchLastBy($user->id);
2820
                    if($userLog) {
2821
                        $insert = $userLog->added_on <= $added_on;
2822
                    } else {
2823
                        $insert = true;
2824
                    }
1 www 2825
 
16 efrain 2826
 
2827
                    if($insert) {
2828
                        $userLog = new CompanyMicrolearningUserLog();
2829
                        $userLog->company_id = null;
2830
                        $userLog->user_id = $user->id;
2831
                        $userLog->activity = $activity;
2832
                        $userLog->added_on = $added_on;
2833
 
2834
 
2835
                        $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2836
                        if($userLogMapper->insert($userLog)) {
2837
                            array_push($result_sync_ids, [
2838
                                'success' => true,
2839
                                'sync_id' => $sync_id
2840
                            ]);
2841
                        } else {
2842
                            array_push($result_sync_ids, [
2843
                                'success' => false,
2844
                                'sync_id' => $sync_id,
2845
                                'message' => $userLogMapper->getError()
2846
                            ]);
2847
                        }
2848
                    } else {
1 www 2849
                        array_push($result_sync_ids, [
2850
                            'success' => true,
2851
                            'sync_id' => $sync_id
2852
                        ]);
2853
                    }
2854
 
16 efrain 2855
 
2856
 
1 www 2857
                    continue;
2858
                }
2859
 
2860
                /***** FIN LOG DE USUARIO GENERAL ******/
2861
            }
2862
 
2863
            if( $result_sync_ids) {
2864
                return new JsonModel([
2865
                    'success' => true,
2866
                    'data' => $result_sync_ids
2867
                ]);
2868
            } else {
2869
                return new JsonModel([
2870
                    'success' => false,
2871
                    'data' => 'ERROR_INVALID_PARAMETERS'
2872
                ]);
2873
            }
2874
 
2875
 
2876
        }
2877
 
2878
        return new JsonModel([
2879
            'success' => false,
2880
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2881
        ]);
2882
    }
2883
 
2884
    /**
2885
     *
2886
     * @param User $user
2887
     * @param boolean $includeLogs
2888
     * @param boolean $includeProgress
2889
     * @return array[]
2890
     */
2891
    private function getSyncData($user, $includeLogs = true, $includeProgress = true)
2892
    {
2893
 
2894
        $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
2895
 
2896
        $data = [
2897
            'userlog'   => [],
2898
            'progress'  => [],
2899
            'topics'    => [],
2900
            'quizzes'   => [],
2901
        ];
2902
 
2903
 
2904
        $companies = [];
2905
        $companyMapper = CompanyMapper::getInstance($this->adapter);
2906
 
2907
        $topics = [];
2908
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
2909
 
2910
        $capsules = [];
2911
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
2912
 
2913
        $slides = [];
2914
        $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
2915
 
2916
        $quizzes = [];
2917
        $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
2918
 
2919
        $questions = [];
2920
        $questionMapper = CompanyMicrolearningQuestionMapper::getInstance($this->adapter);
2921
 
2922
        $answers = [];
2923
        $answerMapper = CompanyMicrolearningAnswerMapper::getInstance($this->adapter);
2924
 
2925
 
2926
        $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2927
 
2928
        if($includeLogs) {
2929
 
2930
            $records = $userLogMapper->fetchLast20ByUserId($user->id);
2931
            foreach($records as $record)
2932
            {
2933
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
2934
 
2935
                if($record->company_id) {
2936
 
2937
                    if(isset($companies[$record->company_id])) {
2938
                        $company = $companies[$record->company_id];
2939
                    } else {
2940
                        $company = $companyMapper->fetchOne($record->company_id);
2941
                        $companies[$record->company_id] = $company;
2942
                    }
2943
                } else {
2944
                    $company = null;
2945
                }
2946
 
2947
                if($record->topic_id) {
2948
 
2949
                    if(isset($topics[$record->topic_id])) {
2950
                        $topic = $topics[$record->topic_id];
2951
                    } else {
2952
                        $topic = $topicMapper->fetchOne($record->topic_id);
2953
                        $topics[$record->topic_id] = $topic;
2954
                    }
2955
                } else {
2956
                    $topic = null;
2957
                }
2958
 
2959
 
2960
                if($record->capsule_id) {
2961
 
2962
                    if(isset($capsules[$record->capsule_id])) {
2963
                        $capsule = $capsules[$record->capsule_id];
2964
                    } else {
2965
                        $capsule = $capsuleMapper->fetchOne($record->capsule_id);
2966
                        $capsules[$record->capsule_id] = $capsule;
2967
                    }
2968
                } else {
2969
                    $capsule = null;
2970
                }
2971
 
2972
 
2973
                if($record->slide_id) {
2974
 
2975
                    if(isset($slides[$record->slide_id])) {
2976
                        $slide = $slides[$record->slide_id];
2977
                    } else {
2978
                        $slide = $slideMapper->fetchOne($record->slide_id);
2979
                        $slides[$record->slide_id] = $slide;
2980
                    }
2981
                } else {
2982
                    $slide = null;
2983
                }
2984
 
2985
 
2986
                array_push($data['userlog'], [
2987
                    'user_uuid'     => $user->uuid,
2988
                    'company_uuid'  => $company ? $company->uuid : '',
2989
                    'topic_uuid'    => $topic ? $topic->uuid : '',
2990
                    'capsule_uuid'  => $capsule ? $capsule->uuid : '',
2991
                    'slide_uuid'    => $slide ? $slide->uuid : '',
2992
                    'activity'      => $record->activity,
2993
                    'added_on'      => $dt->format($serviceDatetimeFormat),
2994
                ]);
2995
 
2996
 
2997
            }
2998
        }
2999
 
3000
        if($includeProgress) {
3001
 
3002
            $userProgressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
3003
            $records = $userProgressMapper->fetchAllByUserId($user->id);
3004
            foreach($records as $record)
3005
            {
3006
                if($record->company_id) {
3007
 
3008
                    if(isset($companies[$record->company_id])) {
3009
                        $company = $companies[$record->company_id];
3010
                    } else {
3011
                        $company = $companyMapper->fetchOne($record->company_id);
3012
                        $companies[$record->company_id] = $company;
3013
                    }
3014
                } else {
3015
                    $company = null;
3016
                }
3017
 
3018
                if($record->topic_id) {
3019
 
3020
                    if(isset($topics[$record->topic_id])) {
3021
                        $topic = $topics[$record->topic_id];
3022
                    } else {
3023
                        $topic = $topicMapper->fetchOne($record->topic_id);
3024
                        $topics[$record->topic_id] = $topic;
3025
                    }
3026
                } else {
3027
                    $topic = null;
3028
                }
3029
 
3030
 
3031
                if($record->capsule_id) {
3032
 
3033
                    if(isset($capsules[$record->capsule_id])) {
3034
                        $capsule = $capsules[$record->capsule_id];
3035
                    } else {
3036
                        $capsule = $capsuleMapper->fetchOne($record->capsule_id);
3037
                        $capsules[$record->capsule_id] = $capsule;
3038
                    }
3039
                } else {
3040
                    $capsule = null;
3041
                }
3042
 
3043
 
3044
                if($record->slide_id) {
3045
 
3046
                    if(isset($slides[$record->slide_id])) {
3047
                        $slide = $slides[$record->slide_id];
3048
                    } else {
3049
                        $slide = $slideMapper->fetchOne($record->slide_id);
3050
                        $slides[$record->slide_id] = $slide;
3051
                    }
3052
                } else {
3053
                    $slide = null;
3054
                }
3055
 
3056
 
3057
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
3058
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $record->updated_on);
3059
 
3060
                array_push($data['progress'], [
3061
                    'user_uuid'                 => $user->uuid,
3062
                    'company_uuid'              => $company ? $company->uuid : '',
3063
                    'topic_uuid'                => $topic ? $topic->uuid : '',
3064
                    'capsule_uuid'              => $capsule ? $capsule->uuid : '',
3065
                    'slide_uuid'                => $slide ? $slide->uuid : '',
3066
                    'progress'                  => $record->progress ? $record->progress : 0,
3067
                    'total_slides'              => $record->total_slides ? $record->total_slides : 0,
3068
                    'view_slides'               => $record->view_slides ? $record->view_slides : 0,
3069
                    'type'                      => $record->type,
3070
                    'returning'                 => $record->returning ? $record->returning : 0,
3071
                    'returning_after_completed' => $record->returning_after_completed ? $record->returning_after_completed : 0,
3072
                    'completed'                 => $record->completed ? $record->completed : 0,
3073
                    'added_on'                  => $dtAddedOn->format($serviceDatetimeFormat),
3074
                    'updated_on'                => $dtUpdatedOn->format($serviceDatetimeFormat),
3075
                ]);
3076
            }
3077
        }
3078
 
3079
 
3080
        $now = date('Y-m-d H:i:s');
3081
        $companies_with_access  = [];
3082
        $topics_with_access     = [];
3083
        $capsules_with_access   = [];
3084
        $quizzes_with_access    = [];
3085
        $quizzes                = [];
3086
 
3087
 
3088
        $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
3089
        $records = $capsuleUserMapper->fetchAllActiveByUserId($user->id);
3090
 
3091
 
3092
        foreach($records as $record)
3093
        {
3094
            if($record->access != CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED && $record->access != CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
3095
                continue;
3096
            }
3097
            if($record->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
3098
                if($now < $record->paid_from || $now > $record->paid_to) {
3099
                    continue;
3100
                }
3101
            }
3102
 
3103
 
3104
            if(!in_array($record->company_id,$companies_with_access)) {
3105
                array_push($companies_with_access, $record->company_id);
3106
            }
3107
 
3108
            if(!in_array($record->topic_id,$topics_with_access)) {
3109
                array_push($topics_with_access, $record->topic_id);
3110
            }
3111
 
3112
            if(!in_array($record->capsule_id,$capsules_with_access)) {
3113
                array_push($capsules_with_access, $record->capsule_id);
3114
            }
3115
        }
3116
 
3117
 /*
3118
        echo '$companies_with_access ' . PHP_EOL;
3119
        print_r($companies_with_access);
3120
 
3121
        echo '$topics_with_access ' . PHP_EOL;
3122
        print_r($topics_with_access);
3123
 
3124
        echo '$capsules_with_access' . PHP_EOL;
3125
        print_r($capsules_with_access);
3126
        */
3127
 
3128
        $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
3129
        foreach($companies_with_access as $company_id)
3130
        {
3131
            $companyService =  $companyServiceMapper->fetchOneActiveByCompanyIdAndServiceId($company_id, Service::MICRO_LEARNING);
3132
 
3133
            //print_r($companyService); exit;
3134
 
3135
            if(!$companyService) {
3136
                continue;
3137
            }
3138
 
3139
 
3140
            if(isset($companies[$companyService->company_id])) {
3141
                $company = $companies[$companyService->company_id];
3142
            } else {
3143
                $company = $companyMapper->fetchOne($companyService->company_id);
3144
                $companies[$companyService->company_id] = $company;
3145
            }
3146
 
3147
            $topics = $topicMapper->fetchAllActiveByCompanyId($company_id);
3148
            foreach($topics as $topic)
3149
            {
3150
                if(!in_array($topic->id, $topics_with_access)) {
3151
                    continue;
3152
                }
3153
 
3154
                $record_capsules = [];
3155
                $capsules = $capsuleMapper->fetchAllActiveByCompanyIdAndTopicId($topic->company_id, $topic->id);
3156
                foreach($capsules as $capsule)
3157
                {
3158
                    if(!in_array($capsule->id, $capsules_with_access)) {
3159
                        continue;
3160
                    }
3161
 
3162
 
3163
                    $record_slides = [];
3164
                    $slides = $slideMapper->fetchAllByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
3165
                    foreach($slides as $slide)
3166
                    {
3167
                        if($slide->type == CompanyMicrolearningSlide::TYPE_QUIZ) {
3168
                            if(!in_array($slide->quiz_id, $quizzes_with_access)) {
3169
                                array_push($quizzes_with_access, $slide->quiz_id);
3170
                            }
3171
 
3172
                            if(isset($quizzes[$slide->quiz_id])) {
3173
                                $quiz = $quizzes[$slide->quiz_id];
3174
 
3175
                            } else {
3176
                                $quiz = $quizMapper->fetchOne($slide->quiz_id);
3177
                                $quizzes[$slide->quiz_id] =  $quiz;
3178
                            }
3179
                        } else {
3180
                            $quiz = null;
3181
                        }
3182
 
3183
 
3184
 
3185
                        array_push($record_slides, [
3186
                            'uuid' => $slide->uuid,
3187
                            'quiz_uuid' => $quiz ? $quiz->uuid : '',
3188
                            'name' => $slide->name ? $slide->name : '',
3189
                            'description' => $slide->description ? $slide->description : '',
3190
                            'position' => $slide->order,
3191
                            'type' => $slide->type,
3192
                            'background' => $slide->background ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-slide', 'code' => $slide->uuid, 'filename' => $slide->background], ['force_canonical' => true]) : '',
3193
                            'file' => $slide->file ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-slide', 'code' => $slide->uuid, 'filename' => $slide->file], ['force_canonical' => true]) : '',
3194
                        ]);
3195
                    }
3196
 
3197
                    array_push($record_capsules, [
3198
                        'uuid' => $capsule->uuid,
3199
                        'name' => $capsule->name ? $capsule->name : '',
3200
                        'description' => $capsule->description ? $capsule->description : '',
3201
                        'image' => $capsule->image ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-capsule', 'code' => $capsule->uuid, 'filename' => $capsule->image ], ['force_canonical' => true])  : '',
3202
                        'position' => $capsule->order,
3203
                        'slides' => $record_slides,
3204
                    ]);
3205
                }
3206
 
3207
                array_push($data['topics'], [
3208
                    'uuid' => $topic->uuid,
3209
                    'name' => $topic->name ? $topic->name : '',
3210
                    'description' => $topic->description ? $topic->description : '',
3211
                    'image' => $topic->image ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-topic', 'code' => $topic->uuid, 'filename' => $topic->image ], ['force_canonical' => true]) : '',
3212
                    'position' => $topic->order,
3213
                    'company_uuid' => $company->uuid,
3214
                    'company_name' => $company->name,
3215
                    'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
3216
                    'capsules' => $record_capsules
3217
                ]);
3218
            }
3219
        }
3220
 
3221
 
3222
 
3223
        foreach($quizzes_with_access as $quiz_id)
3224
        {
3225
            if(isset($quizzes[$quiz_id])) {
3226
                $quiz = $quizzes[$quiz_id];
3227
            } else {
3228
                $quiz = $quizMapper->fetchOne($quiz_id);
3229
                array_push($quizzes, $quiz);
3230
            }
3231
 
3232
            if(isset($companies[$quiz->company_id])) {
3233
                $company = $companies[$quiz->company_id];
3234
            } else {
3235
                $company = $companyMapper->fetchOne($quiz->company_id);
3236
                $companies[$quiz->company_id] = $company;
3237
            }
3238
 
3239
 
3240
            $record_questions = [];
3241
            $questions = $questionMapper->fetchAllByQuizId($quiz->id);
3242
            foreach($questions as $question)
3243
            {
3244
                $record_answers = [];
3245
 
3246
                $answers = $answerMapper->fetchAllByQuizIdAndQuestionId($question->quiz_id, $question->id);
3247
                foreach($answers as $answer)
3248
                {
3249
                    array_push($record_answers, [
3250
                        'uuid' => $answer->uuid,
3251
                        'text' => trim($answer->text),
3252
                        'correct' => $answer->correct ? $answer->correct  : 0 ,
3253
                        'points' => intval($answer->points, 10),
3254
                    ]);
3255
                }
3256
 
3257
                array_push($record_questions, [
3258
                    'uuid' => $question->uuid,
3259
                    'text' => trim($question->text),
3260
                    'type' => $question->type,
3261
                    'maxlength' => $question->maxlength,
3262
                    'points' => $question->points,
3263
                    'answers' => $record_answers,
3264
                ]);
3265
            }
3266
 
3267
 
3268
            array_push($data['quizzes'], [
3269
                'uuid' => $quiz->uuid,
3270
                'name' => $quiz->name,
3271
                'text' => trim($quiz->text ? $quiz->text : ''),
3272
                'failed' => trim($quiz->failed ? $quiz->failed : ''),
3273
                'points' => $quiz->points,
3274
                'minimum_points_required' => $quiz->minimum_points_required,
3275
                'max_time' => $quiz->max_time ? $quiz->max_time : 5,
3276
                'company_uuid' => $company->uuid,
3277
                'company_name' => $company->name,
3278
                'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
3279
                'questions' => $record_questions,
3280
            ]);
3281
        }
3282
        return $data;
3283
    }
3284
 
3285
 
3286
    /**
3287
     *
3288
     * @param string $filename
3289
     * @param boolean $retbytes
3290
     * @return boolean|number
3291
     */
3292
    private function readfile_chunked($filename, $retbytes = true) {
3293
        $buffer = '';
3294
        $cnt =0;;
3295
        $handle = fopen($filename,'rb');
3296
        if ($handle === false) {
3297
            return false;
3298
        }
3299
        while (!feof($handle)) {
3300
            $buffer = fread($handle, self::CHUNK_SIZE);
3301
            echo $buffer;
3302
            ob_flush();
3303
            flush();
3304
            if ($retbytes) {
3305
                $cnt += strlen($buffer);
3306
            }
3307
        }
3308
        $status = fclose($handle);
3309
        if ($retbytes && $status) {
3310
            return $cnt; // return num. bytes delivered like readfile() does.
3311
        }
3312
        return $status;
3313
    }
3314
}