Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 16 | Ir a la última revisión | | 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
 
2058
            for($i = 1; $i <= $max_records; $i++)
2059
            {
2060
                $sync_id        = filter_var($this->params()->fromPost('record_sync_id' . $i, ''), FILTER_SANITIZE_NUMBER_INT);
2061
                $record_data    = $this->params()->fromPost('record_data' . $i, '');
2062
 
2063
                if(empty($record_data) || empty($sync_id )) {
2064
                    continue;
2065
                }
2066
 
2067
                $record         = json_decode($record_data, true);
2068
                $sync_type      = isset($record['sync_type']) ? filter_var($record['sync_type'],  FILTER_SANITIZE_STRING) : '';
2069
                $user_uuid      = isset($record['user_uuid']) ? filter_var($record['user_uuid'],  FILTER_SANITIZE_STRING) : '';
2070
                $company_uuid   = isset($record['company_uuid']) ? filter_var($record['company_uuid'], FILTER_SANITIZE_STRING) : '';
2071
 
2072
                if(!$sync_id) {
2073
                    continue;
2074
                }
2075
 
2076
                /***** INICIO MICROLEARNING *****/
2077
 
2078
                if($user_uuid && $device->application_id = Application::TWOGETSKILLS  && $company_uuid && in_array($sync_type, ['microlearning-progress', 'microlearning-userlog', 'microlearning-quiz'])) {
2079
                    $userMapper = UserMapper::getInstance($this->adapter);
2080
                    $user = $userMapper->fetchOneByUuid($user_uuid);
2081
 
2082
                    if(!$user) {
2083
                        array_push($result_sync_ids, [
2084
                            'success' => false,
2085
                            'sync_id' => $sync_id,
2086
                            'message' => 'ERROR_USER_NOT_FOUND',
2087
                            'fatal' => true
2088
                        ]);
2089
                        continue;
2090
                    }
2091
 
2092
 
2093
                    if($user->status != User::STATUS_ACTIVE) {
2094
                        array_push($result_sync_ids, [
2095
                            'success' => false,
2096
                            'sync_id' => $sync_id,
2097
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
2098
                            'fatal' => true
2099
                        ]);
2100
                        continue;
2101
                    }
2102
 
2103
                    $companyMapper = CompanyMapper::getInstance($this->adapter);
2104
                    $company = $companyMapper->fetchOneByUuid($company_uuid);
2105
                    if(!$company) {
2106
                        array_push($result_sync_ids, [
2107
                            'success' => false,
2108
                            'sync_id' => $sync_id,
2109
                            'message' => 'ERROR_COMPANY_NOT_FOUND',
2110
                            'fatal' => true
2111
                        ]);
2112
                        continue;
2113
                    }
2114
 
2115
                    if($company->status != Company::STATUS_ACTIVE) {
2116
                        array_push($result_sync_ids, [
2117
                            'success' => false,
2118
                            'sync_id' => $sync_id,
2119
                            'message' => 'ERROR_COMPANY_IS_NOT_FOUND',
2120
                            'fatal' => true
2121
                        ]);
2122
                        continue;
2123
                    }
2124
 
2125
 
2126
 
2127
 
2128
 
2129
                    $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
2130
                    $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($company->id, Service::MICRO_LEARNING);
2131
                    if(!$companyService) {
2132
                        array_push($result_sync_ids, [
2133
                            'success' => false,
2134
                            'sync_id' => $sync_id,
2135
                            'message' => 'ERROR_COMPANY_SERVICE_NOT_FOUND',
2136
                            'fatal' => true
2137
                        ]);
2138
                        continue;
2139
                    }
2140
 
2141
                    $serviceActive = true;
2142
                    $now = date('Y-m-d H:i:s');
2143
                    if($companyService->status == CompanyService::ACTIVE) {
2144
 
2145
                        if($now < $companyService->paid_from || $now > $companyService->paid_to) {
2146
                            $serviceActive = false;
2147
                        }
2148
 
2149
                    } else {
2150
                        $serviceActive = false;
2151
                    }
2152
 
2153
                    if( !$serviceActive) {
2154
                        array_push($result_sync_ids, [
2155
                            'success' => false,
2156
                            'sync_id' => $sync_id,
2157
                            'message' => 'ERROR_COMPANY_SERVICE_IS_NOT_ACTIVE',
2158
                            'fatal' => true
2159
                        ]);
2160
                        continue;
2161
                    }
2162
 
2163
                    $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
2164
                    $topic_uuid = isset($record['topic_uuid']) ? filter_var($record['topic_uuid'], FILTER_SANITIZE_STRING) :  '';
2165
                    if($topic_uuid) {
2166
                        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2167
 
2168
                        if(!$topic) {
2169
                            array_push($result_sync_ids, [
2170
                                'success' => false,
2171
                                'sync_id' => $sync_id,
2172
                                'message' => 'ERROR_TOPIC_NOT_FOUND',
2173
                            ]);
2174
                            continue;
2175
                        }
2176
 
2177
                        if($topic->company_id != $company->id) {
2178
                            array_push($result_sync_ids, [
2179
                                'success' => false,
2180
                                'sync_id' => $sync_id,
2181
                                'message' => 'ERROR_INVALID_PARAMETERS_TOPIC_COMPANY',
2182
                            ]);
2183
                            continue;
2184
                        }
2185
 
2186
                    } else {
2187
                        $topic = null;
2188
                    }
2189
 
2190
                    $capsule_uuid     = isset($record['capsule_uuid']) ? filter_var($record['capsule_uuid'], FILTER_SANITIZE_STRING) :  '';
2191
                    $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
2192
                    if($capsule_uuid) {
2193
 
2194
                        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2195
                        if(!$capsule) {
2196
                            array_push($result_sync_ids, [
2197
                                'success' => false,
2198
                                'sync_id' => $sync_id,
2199
                                'message' => 'ERROR_CAPSULE_NOT_FOUND',
2200
                            ]);
2201
                            continue;
2202
                        }
2203
 
2204
                        if(!$topic || $capsule->topic_id != $topic->id) {
2205
                            array_push($result_sync_ids, [
2206
                                'success' => false,
2207
                                'sync_id' => $sync_id,
2208
                                'message' => 'ERROR_INVALID_PARAMETERS_CAPSULE_TOPIC',
2209
                            ]);
2210
                            continue;
2211
                        }
2212
                    } else {
2213
                        $capsule = null;
2214
                    }
2215
 
2216
                    if($capsule) {
2217
 
2218
                        $capsuleActive = true;
2219
                        $capsuleMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
2220
                        $capsuleUser = $capsuleMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
2221
 
2222
 
2223
                        $now = date('Y-m-d H:i:s');
2224
                        if($capsuleUser && in_array($capsuleUser->access, [CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED,CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD ])) {
2225
 
2226
 
2227
                            if($capsuleUser->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
2228
 
2229
                                if($now < $capsuleUser->paid_from || $now > $capsuleUser->paid_to) {
2230
                                    $capsuleActive = false;;
2231
                                }
2232
                            }
2233
 
2234
                        } else {
2235
                            $capsuleActive = false;
2236
                        }
2237
 
2238
                        if(!$capsuleActive) {
2239
                            array_push($result_sync_ids, [
2240
                                'success' => false,
2241
                                'sync_id' => $sync_id,
2242
                                'message' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
2243
                            ]);
2244
                            continue;
2245
                        }
2246
                    }
2247
 
2248
                    $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
2249
                    $slide_uuid      = isset($record['slide_uuid']) ? filter_var($record['slide_uuid'], FILTER_SANITIZE_STRING) :  '';
2250
                    if($slide_uuid) {
2251
                        $slide = $slideMapper->fetchOneByUuid($slide_uuid);
2252
                        if(!$slide) {
2253
                            array_push($result_sync_ids, [
2254
                                'success' => false,
2255
                                'sync_id' => $sync_id,
2256
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
2257
                            ]);
2258
                            continue;
2259
                        }
2260
 
2261
                        if(!$capsule || $slide->capsule_id != $capsule->id) {
2262
                            array_push($result_sync_ids, [
2263
                                'success' => false,
2264
                                'sync_id' => $sync_id,
2265
                                'message' => 'ERROR_INVALID_PARAMETERS_SLIDE_CAPSULE',
2266
                            ]);
2267
                            continue;
2268
                        }
2269
                    } else {
2270
                        $slide = null;
2271
                    }
2272
 
2273
                    if($sync_type == 'microlearning-quiz') {
2274
                        $ok = true;
2275
 
2276
                        $quiz_uuid = isset($record['quiz_uuid']) ? $record['quiz_uuid'] : '';
2277
                        $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
2278
 
2279
                        $quiz = $quizMapper->fetchOneByUuid($quiz_uuid);
2280
                        if(!$quiz) {
2281
                            array_push($result_sync_ids, [
2282
                                'success' => false,
2283
                                'sync_id' => $sync_id,
2284
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
2285
                            ]);
2286
                            continue;
2287
                        }
2288
 
2289
                        if(!$capsule || $slide->capsule_id != $capsule->id) {
2290
                            array_push($result_sync_ids, [
2291
                                'success' => false,
2292
                                'sync_id' => $sync_id,
2293
                                'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_SLIDE',
2294
                            ]);
2295
                            continue;
2296
                        }
2297
 
2298
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2299
 
2300
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2301
                        if(!$dt) {
2302
                            $ok = false;
2303
                        } else {
2304
                            $added_on = $dt->format('Y-m-d H:i:s');
2305
                        }
2306
 
2307
                        if(isset($record['points'])) {
2308
                            $points = intval($record['points'], 10);
2309
                        } else {
2310
                            $ok = false;
2311
                        }
2312
 
2313
                        if(isset($record['pass'])) {
2314
                            $status = $record['pass'] == 'yes' ? CompanyMicrolearningUserQuiz::STATUS_PASS : CompanyMicrolearningUserQuiz::STATUS_FAIL;
2315
                        } else {
2316
                            $ok = false;
2317
                        }
2318
 
2319
                        if(!$ok) {
2320
                            array_push($result_sync_ids, [
2321
                                'success' => false,
2322
                                'sync_id' => $sync_id,
2323
                                'message' => 'ERROR_INVALID_PARAMETERS',
2324
                            ]);
2325
                            continue;
2326
                        }
2327
 
2328
                        $array_response = [];
2329
                        $response = isset($record['response']) ? intval($record['response'], 10) : 0;
2330
                        for($i = 0; $i < $response; $i++)
2331
                        {
2332
                            $question_uuid = isset($record["response_{$i}_question_uuid"]) ? $record["response_{$i}_question_uuid"] : '';
2333
                            $answer_uuid = isset($record["response_{$i}_answer_uuid"]) ? $record["response_{$i}_answer_uuid"] : '';
2334
                            $value = isset($record["response_{$i}_value"]) ?  intval($record["response_{$i}_value"], 10) : 0;
2335
                            $points = isset($record["response_{$i}_points"]) ?  intval($record["response_{$i}_points"], 10) : 0;
2336
 
2337
                            if($question_uuid && $answer_uuid)
2338
                            {
2339
                                array_push($array_response, [
2340
                                    'question_uuid' => $question_uuid,
2341
                                    'answer_uuid' => $answer_uuid,
2342
                                    'value' => $value,
2343
                                    'points' => $points
2344
                                ]);
2345
                            }
2346
                        }
2347
 
2348
                        $userQuiz = new CompanyMicrolearningUserQuiz();
2349
                        $userQuiz->company_id = $company->id;
2350
                        $userQuiz->topic_id = $topic->id;
2351
                        $userQuiz->capsule_id = $capsule->id;
2352
                        $userQuiz->slide_id = $slide->id;
2353
                        $userQuiz->quiz_id = $quiz->id;
2354
                        $userQuiz->user_id = $user->id;
2355
                        $userQuiz->added_on = $added_on;
2356
                        $userQuiz->points = $points;
2357
                        $userQuiz->status = $status;
2358
                        $userQuiz->response = json_encode($array_response);
2359
 
2360
                        $userQuizMapper = CompanyMicrolearningUserQuizMapper::getInstance($this->adapter);
2361
 
2362
                        if($userQuizMapper->insert($userQuiz)) {
2363
                            array_push($result_sync_ids, [
2364
                                'success' => true,
2365
                                'sync_id' => $sync_id
2366
                            ]);
2367
                        } else {
2368
                            array_push($result_sync_ids, [
2369
                                'success' => false,
2370
                                'sync_id' => $sync_id,
2371
                                'message' => $userQuizMapper->getError()
2372
                            ]);
2373
                        }
2374
                        continue;
2375
                    }
2376
 
2377
                    if($sync_type == 'microlearning-progress') {
2378
                        $ok = true;
2379
 
2380
                        $type = isset($record['type']) ? $record['type'] : '';
2381
                        switch($type)
2382
                        {
2383
                            case CompanyMicrolearningUserProgress::TYPE_TOPIC :
2384
                                if(!$topic) {
2385
                                    $ok = false;
2386
                                }
2387
                                break;
2388
 
2389
                            case CompanyMicrolearningUserProgress::TYPE_CAPSULE :
2390
                                if(!$topic || !$capsule) {
2391
                                    $ok = false;
2392
                                }
2393
                                break;
2394
 
2395
                            case CompanyMicrolearningUserProgress::TYPE_SLIDE :
2396
                                if(!$topic || !$capsule || !$slide) {
2397
                                    $ok = false;
2398
                                }
2399
                                break;
2400
 
2401
                            default :
2402
                                $ok = false;
2403
                                break;
2404
                        }
2405
 
2406
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2407
                        $updated_on = isset($record['updated_on'])    ? filter_var($record['updated_on'], FILTER_SANITIZE_STRING) :  '';
2408
 
2409
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2410
                        if(!$dt) {
2411
                            $ok = false;
2412
                        } else {
2413
                            $added_on = $dt->format('Y-m-d H:i:s');
2414
                        }
2415
 
2416
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $updated_on );
2417
                        if(!$dt) {
2418
                            $ok = false;
2419
                        } else {
2420
                            $updated_on = $dt->format('Y-m-d H:i:s');
2421
                        }
2422
 
2423
                        if(!$ok) {
2424
                            array_push($result_sync_ids, [
2425
                                'success' => false,
2426
                                'sync_id' => $sync_id,
2427
                                'message' => 'ERROR_INVALID_PARAMETERS',
2428
                            ]);
2429
                            continue;
2430
                        }
2431
 
2432
                        //$progress                   = isset($record['progress'])                  ? floatval($record['progress']) :  0;
2433
                        //$total_slides               = isset($record['total_slides'])              ? intval($record['total_slides'], 10) :  0;
2434
                        //$view_slides                = isset($record['view_slides'])               ? intval($record['view_slides'], 10) :  0;
2435
                        $returning                  = isset($record['returning'])                 ? intval($record['returning'], 10) :  0;
2436
                        $returning_after_completed  = isset($record['returning_after_completed']) ? intval($record['returning_after_completed'], 10) :  0;
2437
                        $completed                  = isset($record['completed'])                 ? intval($record['completed'], 10) :  0;
2438
 
2439
                        $progressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
2440
                        $recordProgress = null;
2441
                        switch($type) {
2442
                            case CompanyMicrolearningUserProgress::TYPE_TOPIC  :
2443
                                $recordProgress = $progressMapper->fetchOneByUserIdAndTopicId($user->id, $topic->id);
2444
 
2445
                                break;
2446
 
2447
                            case CompanyMicrolearningUserProgress::TYPE_CAPSULE  :
2448
                                $recordProgress = $progressMapper->fetchOneByUseridAndCapsuleId($user->id, $capsule->id);
2449
                                break;
2450
 
2451
                            case CompanyMicrolearningUserProgress::TYPE_SLIDE  :
2452
                                $recordProgress = $progressMapper->fetchOneByUserIdAndSlideId($user->id, $slide->id);
2453
                                break;
2454
 
2455
                            default :
2456
                                $recordProgress= null;
2457
                        }
2458
 
2459
 
2460
                        if(!$recordProgress) {
2461
                            $recordProgress = new CompanyMicrolearningUserProgress();
2462
 
2463
                            $recordProgress->user_id    = $user->id;
2464
                            $recordProgress->type       = $type;
2465
                            $recordProgress->company_id = $topic->company_id;
2466
                            $recordProgress->topic_id   = $topic->id;
2467
                            $recordProgress->capsule_id = $capsule ? $capsule->id : null;
2468
                            $recordProgress->slide_id   = $slide ? $slide->id : null;
2469
                            $recordProgress->added_on   = $added_on;
2470
                        }
2471
                        $recordProgress->returning                  = $returning;
2472
                        $recordProgress->returning_after_completed  = $returning_after_completed;
2473
                        $recordProgress->completed                  = $completed;
2474
 
2475
                        if($type == CompanyMicrolearningUserProgress::TYPE_TOPIC ) {
2476
 
2477
                            $capsule_ids = [];
2478
                            $companyMicrolearningCapsuleUser = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
2479
                            $records =  $companyMicrolearningCapsuleUser->fetchAllActiveByUserId($user->id);
2480
                            foreach($records as $record)
2481
                            {
2482
                                if($now >= $record->paid_from || $now <= $capsuleUser->paid_to) {
2483
                                    if(!in_array($record->capsule_id, $capsule_ids)) {
2484
                                        array_push($capsule_ids, $record->capsule_id);
2485
                                    }
2486
                                }
2487
                            }
2488
 
2489
                            $view_slides    = 0;
2490
                            $total_slides   = 0;
2491
                            foreach($capsule_ids as $capsule_id)
2492
                            {
2493
                                $view_slides    += $progressMapper->fetchCountAllSlideCompletedByUserIdAndCapsuleId($user->id, $capsule_id);
2494
                                $total_slides   += $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $topic->id, $capsule_id);
2495
                            }
2496
 
2497
                            $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
2498
                            $recordProgress->total_slides   = $total_slides;
2499
                            $recordProgress->view_slides    = $view_slides;
2500
                        }
2501
                        else if($type == CompanyMicrolearningUserProgress::TYPE_CAPSULE ) {
2502
                            $view_slides    = $progressMapper->fetchCountAllSlideCompletedByUserIdAndCapsuleId($user->id, $capsule->id);
2503
                            $total_slides   = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $capsule->topic_id, $capsule->id);
2504
 
2505
                            $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
2506
                            $recordProgress->total_slides   = $total_slides;
2507
                            $recordProgress->view_slides    = $view_slides;
2508
                        }
2509
                        else {
2510
                            $recordProgress->progress       = 0;
2511
                            $recordProgress->total_slides   = 0;
2512
                            $recordProgress->view_slides    = 0;
2513
                        }
2514
 
2515
                        $recordProgress->updated_on = $updated_on;
2516
 
2517
 
2518
 
2519
                        if($recordProgress->id) {
2520
                            $result = $progressMapper->update($recordProgress);
2521
                        } else {
2522
                            $result = $progressMapper->insert($recordProgress);
2523
                        }
2524
 
2525
                        if($result) {
2526
                            array_push($result_sync_ids, [
2527
                                'success' => true,
2528
                                'sync_id' => $sync_id
2529
                            ]);
2530
                        } else {
2531
                            array_push($result_sync_ids, [
2532
                                'success' => false,
2533
                                'sync_id' => $sync_id,
2534
                                'message' => $progressMapper->getError()
2535
                            ]);
2536
                        }
2537
                        continue;
2538
                    }
2539
 
2540
 
2541
 
2542
                    if($sync_type == 'microlearning-userlog') {
2543
                        $activity   = isset($record['activity'])      ? filter_var($record['activity'], FILTER_SANITIZE_STRING)  :  '';
2544
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2545
 
2546
 
2547
                        if(empty($activity)) {
2548
                            $ok = false;
2549
                        }
2550
 
2551
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2552
                        if(!$dt) {
2553
                            $ok = false;
2554
                        } else {
2555
                            $added_on = $dt->format('Y-m-d H:i:s');
2556
                        }
2557
 
2558
                        if(!$ok) {
2559
                            array_push($result_sync_ids, [
2560
                                'success' => false,
2561
                                'sync_id' => $sync_id,
2562
                                'message' => 'ERROR_INVALID_PARAMETERS',
2563
                            ]);
2564
                            continue;
2565
                        }
2566
 
2567
                        $userLog = new CompanyMicrolearningUserLog();
2568
                        $userLog->activity      = $activity;
2569
                        $userLog->user_id       = $user->id;
2570
                        $userLog->company_id    = $topic->company_id;
2571
                        $userLog->topic_id      = $topic->id;
2572
                        $userLog->capsule_id    = $capsule ? $capsule->id : null;
2573
                        $userLog->slide_id      = $slide ? $slide->id : null;
2574
                        $userLog->added_on      = $added_on;
2575
 
2576
 
2577
 
2578
                        $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2579
                        if($userLogMapper->insert($userLog)) {
2580
                            array_push($result_sync_ids, [
2581
                                'success' => true,
2582
                                'sync_id' => $sync_id
2583
                            ]);
2584
                        } else {
2585
                            array_push($result_sync_ids, [
2586
                                'success' => false,
2587
                                'sync_id' => $sync_id,
2588
                                'message' => $userLogMapper->getError()
2589
                            ]);
2590
                        }
2591
                        continue;
2592
                    }
2593
 
2594
                }
2595
 
2596
                /***** FIN MICROLEARNING *****/
2597
 
2598
 
2599
                /***** INICIO LOG DE USUARIO GENERAL *****/
2600
 
2601
                if($user_uuid && $sync_type == 'userlog' && $device->application_id = Application::TWOGETSKILLS) {
2602
 
2603
                    $userMapper = UserMapper::getInstance($this->adapter);
2604
                    $user = $userMapper->fetchOneByUuid($user_uuid);
2605
 
2606
                    if(!$user) {
2607
                        array_push($result_sync_ids, [
2608
                            'success' => false,
2609
                            'sync_id' => $sync_id,
2610
                            'message' => 'ERROR_USER_NOT_FOUND',
2611
                            'fatal' => true
2612
                        ]);
2613
                        continue;
2614
                    }
2615
 
2616
 
2617
                    if($user->status != User::STATUS_ACTIVE) {
2618
                        array_push($result_sync_ids, [
2619
                            'success' => false,
2620
                            'sync_id' => $sync_id,
2621
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
2622
                            'fatal' => true
2623
                        ]);
2624
                        continue;
2625
                    }
2626
 
2627
                    $activity   = isset($record['activity'])      ? filter_var($record['activity'], FILTER_SANITIZE_STRING)  :  '';
2628
                    $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2629
 
2630
                    if(empty($activity)) {
2631
                        $ok = false;
2632
                    }
2633
 
2634
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2635
                    if(!$dt) {
2636
                        $ok = false;
2637
                    } else {
2638
                        $added_on = $dt->format('Y-m-d H:i:s');
2639
                    }
2640
 
2641
                    if(!$ok) {
2642
                        array_push($result_sync_ids, [
2643
                            'success' => false,
2644
                            'sync_id' => $sync_id,
2645
                            'message' => 'ERROR_INVALID_PARAMETERS',
2646
                        ]);
2647
                        continue;
2648
                    }
2649
 
2650
                    $userLog = new CompanyMicrolearningUserLog();
2651
                    $userLog->company_id = null;
2652
                    $userLog->user_id = $user->id;
2653
                    $userLog->activity = $activity;
2654
                    $userLog->added_on = $added_on;
2655
 
2656
 
2657
                    $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2658
                    if($userLogMapper->insert($userLog)) {
2659
                        array_push($result_sync_ids, [
2660
                            'success' => true,
2661
                            'sync_id' => $sync_id
2662
                        ]);
2663
                    } else {
2664
                        array_push($result_sync_ids, [
2665
                            'success' => false,
2666
                            'sync_id' => $sync_id,
2667
                            'message' => $userLogMapper->getError()
2668
                        ]);
2669
                    }
2670
 
2671
                    continue;
2672
                }
2673
 
2674
                /***** FIN LOG DE USUARIO GENERAL ******/
2675
            }
2676
 
2677
            if( $result_sync_ids) {
2678
                return new JsonModel([
2679
                    'success' => true,
2680
                    'data' => $result_sync_ids
2681
                ]);
2682
            } else {
2683
                return new JsonModel([
2684
                    'success' => false,
2685
                    'data' => 'ERROR_INVALID_PARAMETERS'
2686
                ]);
2687
            }
2688
 
2689
 
2690
        }
2691
 
2692
        return new JsonModel([
2693
            'success' => false,
2694
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2695
        ]);
2696
    }
2697
 
2698
    /**
2699
     *
2700
     * @param User $user
2701
     * @param boolean $includeLogs
2702
     * @param boolean $includeProgress
2703
     * @return array[]
2704
     */
2705
    private function getSyncData($user, $includeLogs = true, $includeProgress = true)
2706
    {
2707
 
2708
        $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
2709
 
2710
        $data = [
2711
            'userlog'   => [],
2712
            'progress'  => [],
2713
            'topics'    => [],
2714
            'quizzes'   => [],
2715
        ];
2716
 
2717
 
2718
        $companies = [];
2719
        $companyMapper = CompanyMapper::getInstance($this->adapter);
2720
 
2721
        $topics = [];
2722
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
2723
 
2724
        $capsules = [];
2725
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
2726
 
2727
        $slides = [];
2728
        $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
2729
 
2730
        $quizzes = [];
2731
        $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
2732
 
2733
        $questions = [];
2734
        $questionMapper = CompanyMicrolearningQuestionMapper::getInstance($this->adapter);
2735
 
2736
        $answers = [];
2737
        $answerMapper = CompanyMicrolearningAnswerMapper::getInstance($this->adapter);
2738
 
2739
 
2740
        $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2741
 
2742
        if($includeLogs) {
2743
 
2744
            $records = $userLogMapper->fetchLast20ByUserId($user->id);
2745
            foreach($records as $record)
2746
            {
2747
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
2748
 
2749
                if($record->company_id) {
2750
 
2751
                    if(isset($companies[$record->company_id])) {
2752
                        $company = $companies[$record->company_id];
2753
                    } else {
2754
                        $company = $companyMapper->fetchOne($record->company_id);
2755
                        $companies[$record->company_id] = $company;
2756
                    }
2757
                } else {
2758
                    $company = null;
2759
                }
2760
 
2761
                if($record->topic_id) {
2762
 
2763
                    if(isset($topics[$record->topic_id])) {
2764
                        $topic = $topics[$record->topic_id];
2765
                    } else {
2766
                        $topic = $topicMapper->fetchOne($record->topic_id);
2767
                        $topics[$record->topic_id] = $topic;
2768
                    }
2769
                } else {
2770
                    $topic = null;
2771
                }
2772
 
2773
 
2774
                if($record->capsule_id) {
2775
 
2776
                    if(isset($capsules[$record->capsule_id])) {
2777
                        $capsule = $capsules[$record->capsule_id];
2778
                    } else {
2779
                        $capsule = $capsuleMapper->fetchOne($record->capsule_id);
2780
                        $capsules[$record->capsule_id] = $capsule;
2781
                    }
2782
                } else {
2783
                    $capsule = null;
2784
                }
2785
 
2786
 
2787
                if($record->slide_id) {
2788
 
2789
                    if(isset($slides[$record->slide_id])) {
2790
                        $slide = $slides[$record->slide_id];
2791
                    } else {
2792
                        $slide = $slideMapper->fetchOne($record->slide_id);
2793
                        $slides[$record->slide_id] = $slide;
2794
                    }
2795
                } else {
2796
                    $slide = null;
2797
                }
2798
 
2799
 
2800
                array_push($data['userlog'], [
2801
                    'user_uuid'     => $user->uuid,
2802
                    'company_uuid'  => $company ? $company->uuid : '',
2803
                    'topic_uuid'    => $topic ? $topic->uuid : '',
2804
                    'capsule_uuid'  => $capsule ? $capsule->uuid : '',
2805
                    'slide_uuid'    => $slide ? $slide->uuid : '',
2806
                    'activity'      => $record->activity,
2807
                    'added_on'      => $dt->format($serviceDatetimeFormat),
2808
                ]);
2809
 
2810
 
2811
            }
2812
        }
2813
 
2814
        if($includeProgress) {
2815
 
2816
            $userProgressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
2817
            $records = $userProgressMapper->fetchAllByUserId($user->id);
2818
            foreach($records as $record)
2819
            {
2820
                if($record->company_id) {
2821
 
2822
                    if(isset($companies[$record->company_id])) {
2823
                        $company = $companies[$record->company_id];
2824
                    } else {
2825
                        $company = $companyMapper->fetchOne($record->company_id);
2826
                        $companies[$record->company_id] = $company;
2827
                    }
2828
                } else {
2829
                    $company = null;
2830
                }
2831
 
2832
                if($record->topic_id) {
2833
 
2834
                    if(isset($topics[$record->topic_id])) {
2835
                        $topic = $topics[$record->topic_id];
2836
                    } else {
2837
                        $topic = $topicMapper->fetchOne($record->topic_id);
2838
                        $topics[$record->topic_id] = $topic;
2839
                    }
2840
                } else {
2841
                    $topic = null;
2842
                }
2843
 
2844
 
2845
                if($record->capsule_id) {
2846
 
2847
                    if(isset($capsules[$record->capsule_id])) {
2848
                        $capsule = $capsules[$record->capsule_id];
2849
                    } else {
2850
                        $capsule = $capsuleMapper->fetchOne($record->capsule_id);
2851
                        $capsules[$record->capsule_id] = $capsule;
2852
                    }
2853
                } else {
2854
                    $capsule = null;
2855
                }
2856
 
2857
 
2858
                if($record->slide_id) {
2859
 
2860
                    if(isset($slides[$record->slide_id])) {
2861
                        $slide = $slides[$record->slide_id];
2862
                    } else {
2863
                        $slide = $slideMapper->fetchOne($record->slide_id);
2864
                        $slides[$record->slide_id] = $slide;
2865
                    }
2866
                } else {
2867
                    $slide = null;
2868
                }
2869
 
2870
 
2871
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
2872
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $record->updated_on);
2873
 
2874
                array_push($data['progress'], [
2875
                    'user_uuid'                 => $user->uuid,
2876
                    'company_uuid'              => $company ? $company->uuid : '',
2877
                    'topic_uuid'                => $topic ? $topic->uuid : '',
2878
                    'capsule_uuid'              => $capsule ? $capsule->uuid : '',
2879
                    'slide_uuid'                => $slide ? $slide->uuid : '',
2880
                    'progress'                  => $record->progress ? $record->progress : 0,
2881
                    'total_slides'              => $record->total_slides ? $record->total_slides : 0,
2882
                    'view_slides'               => $record->view_slides ? $record->view_slides : 0,
2883
                    'type'                      => $record->type,
2884
                    'returning'                 => $record->returning ? $record->returning : 0,
2885
                    'returning_after_completed' => $record->returning_after_completed ? $record->returning_after_completed : 0,
2886
                    'completed'                 => $record->completed ? $record->completed : 0,
2887
                    'added_on'                  => $dtAddedOn->format($serviceDatetimeFormat),
2888
                    'updated_on'                => $dtUpdatedOn->format($serviceDatetimeFormat),
2889
                ]);
2890
            }
2891
        }
2892
 
2893
 
2894
        $now = date('Y-m-d H:i:s');
2895
        $companies_with_access  = [];
2896
        $topics_with_access     = [];
2897
        $capsules_with_access   = [];
2898
        $quizzes_with_access    = [];
2899
        $quizzes                = [];
2900
 
2901
 
2902
        $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
2903
        $records = $capsuleUserMapper->fetchAllActiveByUserId($user->id);
2904
 
2905
 
2906
        foreach($records as $record)
2907
        {
2908
            if($record->access != CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED && $record->access != CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
2909
                continue;
2910
            }
2911
            if($record->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
2912
                if($now < $record->paid_from || $now > $record->paid_to) {
2913
                    continue;
2914
                }
2915
            }
2916
 
2917
 
2918
            if(!in_array($record->company_id,$companies_with_access)) {
2919
                array_push($companies_with_access, $record->company_id);
2920
            }
2921
 
2922
            if(!in_array($record->topic_id,$topics_with_access)) {
2923
                array_push($topics_with_access, $record->topic_id);
2924
            }
2925
 
2926
            if(!in_array($record->capsule_id,$capsules_with_access)) {
2927
                array_push($capsules_with_access, $record->capsule_id);
2928
            }
2929
        }
2930
 
2931
 /*
2932
        echo '$companies_with_access ' . PHP_EOL;
2933
        print_r($companies_with_access);
2934
 
2935
        echo '$topics_with_access ' . PHP_EOL;
2936
        print_r($topics_with_access);
2937
 
2938
        echo '$capsules_with_access' . PHP_EOL;
2939
        print_r($capsules_with_access);
2940
        */
2941
 
2942
        $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
2943
        foreach($companies_with_access as $company_id)
2944
        {
2945
            $companyService =  $companyServiceMapper->fetchOneActiveByCompanyIdAndServiceId($company_id, Service::MICRO_LEARNING);
2946
 
2947
            //print_r($companyService); exit;
2948
 
2949
            if(!$companyService) {
2950
                continue;
2951
            }
2952
 
2953
 
2954
            if(isset($companies[$companyService->company_id])) {
2955
                $company = $companies[$companyService->company_id];
2956
            } else {
2957
                $company = $companyMapper->fetchOne($companyService->company_id);
2958
                $companies[$companyService->company_id] = $company;
2959
            }
2960
 
2961
            $topics = $topicMapper->fetchAllActiveByCompanyId($company_id);
2962
            foreach($topics as $topic)
2963
            {
2964
                if(!in_array($topic->id, $topics_with_access)) {
2965
                    continue;
2966
                }
2967
 
2968
                $record_capsules = [];
2969
                $capsules = $capsuleMapper->fetchAllActiveByCompanyIdAndTopicId($topic->company_id, $topic->id);
2970
                foreach($capsules as $capsule)
2971
                {
2972
                    if(!in_array($capsule->id, $capsules_with_access)) {
2973
                        continue;
2974
                    }
2975
 
2976
 
2977
                    $record_slides = [];
2978
                    $slides = $slideMapper->fetchAllByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
2979
                    foreach($slides as $slide)
2980
                    {
2981
                        if($slide->type == CompanyMicrolearningSlide::TYPE_QUIZ) {
2982
                            if(!in_array($slide->quiz_id, $quizzes_with_access)) {
2983
                                array_push($quizzes_with_access, $slide->quiz_id);
2984
                            }
2985
 
2986
                            if(isset($quizzes[$slide->quiz_id])) {
2987
                                $quiz = $quizzes[$slide->quiz_id];
2988
 
2989
                            } else {
2990
                                $quiz = $quizMapper->fetchOne($slide->quiz_id);
2991
                                $quizzes[$slide->quiz_id] =  $quiz;
2992
                            }
2993
                        } else {
2994
                            $quiz = null;
2995
                        }
2996
 
2997
 
2998
 
2999
                        array_push($record_slides, [
3000
                            'uuid' => $slide->uuid,
3001
                            'quiz_uuid' => $quiz ? $quiz->uuid : '',
3002
                            'name' => $slide->name ? $slide->name : '',
3003
                            'description' => $slide->description ? $slide->description : '',
3004
                            'position' => $slide->order,
3005
                            'type' => $slide->type,
3006
                            'background' => $slide->background ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-slide', 'code' => $slide->uuid, 'filename' => $slide->background], ['force_canonical' => true]) : '',
3007
                            'file' => $slide->file ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-slide', 'code' => $slide->uuid, 'filename' => $slide->file], ['force_canonical' => true]) : '',
3008
                        ]);
3009
                    }
3010
 
3011
                    array_push($record_capsules, [
3012
                        'uuid' => $capsule->uuid,
3013
                        'name' => $capsule->name ? $capsule->name : '',
3014
                        'description' => $capsule->description ? $capsule->description : '',
3015
                        'image' => $capsule->image ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-capsule', 'code' => $capsule->uuid, 'filename' => $capsule->image ], ['force_canonical' => true])  : '',
3016
                        'position' => $capsule->order,
3017
                        'slides' => $record_slides,
3018
                    ]);
3019
                }
3020
 
3021
                array_push($data['topics'], [
3022
                    'uuid' => $topic->uuid,
3023
                    'name' => $topic->name ? $topic->name : '',
3024
                    'description' => $topic->description ? $topic->description : '',
3025
                    'image' => $topic->image ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-topic', 'code' => $topic->uuid, 'filename' => $topic->image ], ['force_canonical' => true]) : '',
3026
                    'position' => $topic->order,
3027
                    'company_uuid' => $company->uuid,
3028
                    'company_name' => $company->name,
3029
                    'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
3030
                    'capsules' => $record_capsules
3031
                ]);
3032
            }
3033
        }
3034
 
3035
 
3036
 
3037
        foreach($quizzes_with_access as $quiz_id)
3038
        {
3039
            if(isset($quizzes[$quiz_id])) {
3040
                $quiz = $quizzes[$quiz_id];
3041
            } else {
3042
                $quiz = $quizMapper->fetchOne($quiz_id);
3043
                array_push($quizzes, $quiz);
3044
            }
3045
 
3046
            if(isset($companies[$quiz->company_id])) {
3047
                $company = $companies[$quiz->company_id];
3048
            } else {
3049
                $company = $companyMapper->fetchOne($quiz->company_id);
3050
                $companies[$quiz->company_id] = $company;
3051
            }
3052
 
3053
 
3054
            $record_questions = [];
3055
            $questions = $questionMapper->fetchAllByQuizId($quiz->id);
3056
            foreach($questions as $question)
3057
            {
3058
                $record_answers = [];
3059
 
3060
                $answers = $answerMapper->fetchAllByQuizIdAndQuestionId($question->quiz_id, $question->id);
3061
                foreach($answers as $answer)
3062
                {
3063
                    array_push($record_answers, [
3064
                        'uuid' => $answer->uuid,
3065
                        'text' => trim($answer->text),
3066
                        'correct' => $answer->correct ? $answer->correct  : 0 ,
3067
                        'points' => intval($answer->points, 10),
3068
                    ]);
3069
                }
3070
 
3071
                array_push($record_questions, [
3072
                    'uuid' => $question->uuid,
3073
                    'text' => trim($question->text),
3074
                    'type' => $question->type,
3075
                    'maxlength' => $question->maxlength,
3076
                    'points' => $question->points,
3077
                    'answers' => $record_answers,
3078
                ]);
3079
            }
3080
 
3081
 
3082
            array_push($data['quizzes'], [
3083
                'uuid' => $quiz->uuid,
3084
                'name' => $quiz->name,
3085
                'text' => trim($quiz->text ? $quiz->text : ''),
3086
                'failed' => trim($quiz->failed ? $quiz->failed : ''),
3087
                'points' => $quiz->points,
3088
                'minimum_points_required' => $quiz->minimum_points_required,
3089
                'max_time' => $quiz->max_time ? $quiz->max_time : 5,
3090
                'company_uuid' => $company->uuid,
3091
                'company_name' => $company->name,
3092
                'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
3093
                'questions' => $record_questions,
3094
            ]);
3095
        }
3096
        return $data;
3097
    }
3098
 
3099
 
3100
    /**
3101
     *
3102
     * @param string $filename
3103
     * @param boolean $retbytes
3104
     * @return boolean|number
3105
     */
3106
    private function readfile_chunked($filename, $retbytes = true) {
3107
        $buffer = '';
3108
        $cnt =0;;
3109
        $handle = fopen($filename,'rb');
3110
        if ($handle === false) {
3111
            return false;
3112
        }
3113
        while (!feof($handle)) {
3114
            $buffer = fread($handle, self::CHUNK_SIZE);
3115
            echo $buffer;
3116
            ob_flush();
3117
            flush();
3118
            if ($retbytes) {
3119
                $cnt += strlen($buffer);
3120
            }
3121
        }
3122
        $status = fclose($handle);
3123
        if ($retbytes && $status) {
3124
            return $cnt; // return num. bytes delivered like readfile() does.
3125
        }
3126
        return $status;
3127
    }
3128
}