Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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