Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

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