Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 44 | Rev 46 | 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
 
44 efrain 1373
 
41 efrain 1374
 
44 efrain 1375
 
1376
 
1377
            $data = json_decode($data, true);
1378
            $sync_type      = isset($data['sync_type']) ? filter_var($data['sync_type'], FILTER_SANITIZE_STRING) : '';
1379
            $user_uuid      = isset($data['user_uuid']) ? filter_var($data['user_uuid'], FILTER_SANITIZE_STRING) : '';
1380
            $company_uuid   = isset($data['company_uuid']) ? filter_var($data['company_uuid'], FILTER_SANITIZE_STRING) :  '';
1381
 
1382
 
41 efrain 1383
            $syncLog = new SyncLog();
1384
            $syncLog->data = $data;
44 efrain 1385
            $syncLog->type = $sync_type;
41 efrain 1386
            $syncLog->device_uuid = $device->id;
1387
            $syncLog->ip = Functions::getUserIP();
1388
 
1389
            $syncLogMapper = SyncLogMapper::getInstance($this->adapter);
1390
            $syncLogMapper->insert($syncLog);
1391
 
1 www 1392
 
1393
    //
1394
 
1395
            if($user_uuid && $device->application_id = Application::TWOGETSKILLS  && $company_uuid && in_array($sync_type, ['microlearning-progress', 'microlearning-userlog', 'microlearning-quiz'])) {
1396
                $userMapper = UserMapper::getInstance($this->adapter);
1397
                $user = $userMapper->fetchOneByUuid($user_uuid);
1398
 
1399
                if(!$user) {
1400
                    return new JsonModel([
1401
                        'success' => false,
1402
                        'data' => [
1403
                            'sync_id' => $sync_id,
1404
                            'message' => 'ERROR_USER_NOT_FOUND',
1405
                            'fatal' => true
1406
                        ]
1407
                    ]);
1408
                }
1409
 
1410
 
1411
                if($user->status != User::STATUS_ACTIVE) {
1412
                    return new JsonModel([
1413
                        'success' => false,
1414
                        'data' => [
1415
                            'sync_id' => $sync_id,
1416
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
1417
                            'fatal' => true
1418
                        ]
1419
                    ]);
1420
                }
1421
 
1422
                $companyMapper = CompanyMapper::getInstance($this->adapter);
1423
                $company = $companyMapper->fetchOneByUuid($company_uuid);
1424
                if(!$company) {
1425
                    return new JsonModel([
1426
                        'success' => false,
1427
                        'data' => [
1428
                            'sync_id' => $sync_id,
1429
                            'message' => 'ERROR_COMPANY_NOT_FOUND',
1430
                            'fatal' => true
1431
                        ]
1432
                    ]);
1433
                }
1434
 
1435
                if($company->status != Company::STATUS_ACTIVE) {
1436
                    return new JsonModel([
1437
                        'success' => false,
1438
                        'data' => [
1439
                            'sync_id' => $sync_id,
1440
                            'message' => 'ERROR_COMPANY_IS_NOT_FOUND',
1441
                            'fatal' => true
1442
                        ]
1443
                    ]);
1444
                }
1445
 
1446
 
1447
 
1448
 
1449
 
1450
                $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
1451
                $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($company->id, Service::MICRO_LEARNING);
1452
                if(!$companyService) {
1453
                    return new JsonModel([
1454
                        'success' => false,
1455
                        'data' => [
1456
                            'sync_id' => $sync_id,
1457
                            'message' => 'ERROR_COMPANY_SERVICE_NOT_FOUND',
1458
                            'fatal' => true
1459
                        ]
1460
                    ]);
1461
                }
1462
 
1463
                $serviceActive = true;
1464
                $now = date('Y-m-d H:i:s');
1465
                if($companyService->status == CompanyService::ACTIVE) {
1466
 
1467
                    if($now < $companyService->paid_from || $now > $companyService->paid_to) {
1468
                        $serviceActive = false;
1469
                    }
1470
 
1471
                } else {
1472
                    $serviceActive = false;
1473
                }
1474
 
1475
                if( !$serviceActive) {
1476
                    return new JsonModel([
1477
                        'success' => false,
1478
                        'data' => [
1479
                            'sync_id' => $sync_id,
1480
                            'message' => 'ERROR_COMPANY_SERVICE_IS_NOT_ACTIVE',
1481
                            'fatal' => true
1482
                        ]
1483
                    ]);
1484
                }
1485
 
1486
                $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
1487
                $topic_uuid = isset($data['topic_uuid']) ? filter_var($data['topic_uuid'], FILTER_SANITIZE_STRING) :  '';
1488
                if($topic_uuid) {
1489
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
1490
 
1491
                    if(!$topic) {
1492
                        return new JsonModel([
1493
                            'success' => false,
1494
                            'data' => [
1495
                                'sync_id' => $sync_id,
1496
                                'message' => 'ERROR_TOPIC_NOT_FOUND',
1497
                            ]
1498
                        ]);
1499
                    }
1500
 
1501
                    if($topic->company_id != $company->id) {
1502
                        return new JsonModel([
1503
                            'success' => false,
1504
                            'data' => [
1505
                                'sync_id' => $sync_id,
1506
                                'message' => 'ERROR_INVALID_PARAMETERS_TOPIC_COMPANY',
1507
                            ]
1508
                        ]);
1509
                    }
1510
 
1511
                } else {
1512
                    $topic = null;
1513
                }
1514
 
1515
                $capsule_uuid     = isset($data['capsule_uuid']) ? filter_var($data['capsule_uuid'], FILTER_SANITIZE_STRING) :  '';
1516
                $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
1517
                if($capsule_uuid) {
1518
 
1519
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
1520
                    if(!$capsule) {
1521
                        return new JsonModel([
1522
                            'success' => false,
1523
                            'data' => [
1524
                                'sync_id' => $sync_id,
1525
                                'message' => 'ERROR_CAPSULE_NOT_FOUND',
1526
                            ]
1527
                        ]);
1528
                    }
1529
 
1530
                    if(!$topic || $capsule->topic_id != $topic->id) {
1531
                        return new JsonModel([
1532
                            'success' => false,
1533
                            'data' => [
1534
                                'sync_id' => $sync_id,
1535
                                'message' => 'ERROR_INVALID_PARAMETERS_CAPSULE_TOPIC',
1536
                            ]
1537
                        ]);
1538
                    }
1539
                } else {
1540
                    $capsule = null;
1541
                }
1542
 
1543
                if($capsule) {
1544
 
1545
                    $capsuleActive = true;
1546
                    $capsuleMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
1547
                    $capsuleUser = $capsuleMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
1548
 
1549
 
1550
                    $now = date('Y-m-d H:i:s');
1551
                    if($capsuleUser && in_array($capsuleUser->access, [CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED,CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD ])) {
1552
 
1553
 
1554
                        if($capsuleUser->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
1555
 
1556
                            if($now < $capsuleUser->paid_from || $now > $capsuleUser->paid_to) {
1557
                                $capsuleActive = false;;
1558
                            }
1559
                        }
1560
 
1561
                    } else {
1562
                        $capsuleActive = false;
1563
                    }
1564
 
1565
                    if(!$capsuleActive) {
1566
                        return new JsonModel([
1567
                            'success' => false,
1568
                            'data' => [
1569
                                'sync_id' => $sync_id,
1570
                                'message' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
1571
                            ]
1572
                        ]);
1573
                    }
1574
                }
1575
 
1576
                $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
1577
                $slide_uuid      = isset($data['slide_uuid']) ? filter_var($data['slide_uuid'], FILTER_SANITIZE_STRING) :  '';
1578
                if($slide_uuid) {
1579
                    $slide = $slideMapper->fetchOneByUuid($slide_uuid);
1580
                    if(!$slide) {
1581
                        return new JsonModel([
1582
                            'success' => false,
1583
                            'data' => [
1584
                                'sync_id' => $sync_id,
1585
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
1586
                            ]
1587
                        ]);
1588
                    }
1589
 
1590
                    if(!$capsule || $slide->capsule_id != $capsule->id) {
1591
                        return new JsonModel([
1592
                            'success' => false,
1593
                            'data' => [
1594
                                'sync_id' => $sync_id,
1595
                                'message' => 'ERROR_INVALID_PARAMETERS_SLIDE_CAPSULE',
1596
                            ]
1597
                        ]);
1598
                    }
1599
                } else {
1600
                    $slide = null;
1601
                }
1602
 
1603
                if($sync_type == 'microlearning-quiz') {
1604
                    $ok = true;
1605
 
1606
                    $quiz_uuid = isset($data['quiz_uuid']) ? $data['quiz_uuid'] : '';
1607
                    $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
1608
 
1609
                    $quiz = $quizMapper->fetchOneByUuid($quiz_uuid);
1610
                    if(!$quiz) {
1611
                        return new JsonModel([
1612
                            'success' => false,
1613
                            'data' => [
1614
                                'sync_id' => $sync_id,
1615
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
1616
                            ]
1617
                        ]);
1618
                    }
1619
 
1620
                    if(!$capsule || $slide->capsule_id != $capsule->id) {
1621
                        return new JsonModel([
1622
                            'success' => false,
1623
                            'data' => [
1624
                                'sync_id' => $sync_id,
1625
                                'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_SLIDE',
1626
                            ]
1627
                        ]);
1628
                    }
1629
 
1630
                    $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
1631
 
1632
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1633
                    if(!$dt) {
1634
                        $ok = false;
1635
                    } else {
1636
                        $added_on = $dt->format('Y-m-d H:i:s');
1637
                    }
1638
 
1639
 
1640
                    if(isset($data['points'])) {
1641
                        $points = intval($data['points'], 10);
1642
                    } else {
1643
                        $ok = false;
1644
                    }
1645
 
1646
 
1647
                    if(isset($data['pass'])) {
1648
                        $status = $data['pass'] == 'yes' ? CompanyMicrolearningUserQuiz::STATUS_PASS : CompanyMicrolearningUserQuiz::STATUS_FAIL;
1649
                    } else {
1650
                        $ok = false;
1651
                    }
1652
 
1653
 
1654
                    if(!$ok) {
1655
                        return new JsonModel([
1656
                            'success' => false,
1657
                            'data' => [
1658
                                'sync_id' => $sync_id,
1659
                                'message' => 'ERROR_INVALID_PARAMETERS',
1660
                            ]
1661
                        ]);
1662
                    }
1663
 
1664
 
1665
                    $array_response = [];
1666
                    $response = isset($data['response']) ? intval($data['response'], 10) : 0;
1667
                    for($i = 0; $i < $response; $i++)
1668
                    {
1669
                        $question_uuid = isset($data["response_{$i}_question_uuid"]) ? $data["response_{$i}_question_uuid"] : '';
1670
                        $answer_uuid = isset($data["response_{$i}_answer_uuid"]) ? $data["response_{$i}_answer_uuid"] : '';
1671
                        $value = isset($data["response_{$i}_value"]) ?  intval($data["response_{$i}_value"], 10) : 0;
1672
                        $points = isset($data["response_{$i}_points"]) ?  intval($data["response_{$i}_points"], 10) : 0;
1673
 
1674
                        if($question_uuid && $answer_uuid)
1675
                        {
1676
                            array_push($array_response, [
1677
                                'question_uuid' => $question_uuid,
1678
                                'answer_uuid' => $answer_uuid,
1679
                                'value' => $value,
1680
                                'points' => $points
1681
 
1682
                            ]);
1683
                        }
1684
 
1685
 
1686
                    }
1687
 
1688
 
1689
                    $userQuiz = new CompanyMicrolearningUserQuiz();
1690
                    $userQuiz->company_id = $company->id;
1691
                    $userQuiz->topic_id = $topic->id;
1692
                    $userQuiz->capsule_id = $capsule->id;
1693
                    $userQuiz->slide_id = $slide->id;
1694
                    $userQuiz->quiz_id = $quiz->id;
1695
                    $userQuiz->user_id = $user->id;
1696
                    $userQuiz->added_on = $added_on;
1697
                    $userQuiz->points = $points;
1698
                    $userQuiz->status = $status;
1699
                    $userQuiz->response = json_encode($array_response);
1700
 
1701
                    $userQuizMapper = CompanyMicrolearningUserQuizMapper::getInstance($this->adapter);
1702
 
1703
                    if($userQuizMapper->insert($userQuiz)) {
1704
                        return new JsonModel([
1705
                            'success' => true,
1706
                            'data' => [
1707
                                'sync_id' => $sync_id
1708
                            ]
1709
                        ]);
1710
                    } else {
1711
                        return new JsonModel([
1712
                            'success' => false,
1713
                            'data' => [
1714
                                'sync_id' => $sync_id,
1715
                                'message' => $userQuizMapper->getError()
1716
                            ]
1717
                        ]);
1718
                    }
1719
 
1720
                }
1721
 
1722
 
1723
                if($sync_type == 'microlearning-progress') {
1724
                    $ok = true;
1725
 
1726
                    $type = isset($data['type']) ? $data['type'] : '';
1727
                    switch($type)
1728
                    {
1729
                        case CompanyMicrolearningUserProgress::TYPE_TOPIC :
1730
                            if(!$topic) {
1731
                                $ok = false;
1732
                            }
1733
                            break;
1734
 
1735
                        case CompanyMicrolearningUserProgress::TYPE_CAPSULE :
1736
                            if(!$topic || !$capsule) {
1737
                                $ok = false;
1738
                            }
1739
                            break;
1740
 
1741
                        case CompanyMicrolearningUserProgress::TYPE_SLIDE :
1742
                            if(!$topic || !$capsule || !$slide) {
1743
                                $ok = false;
1744
                            }
1745
                            break;
1746
 
1747
                        default :
1748
                            $ok = false;
1749
                            break;
1750
 
1751
                    }
1752
 
1753
 
1754
                    $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
1755
                    $updated_on = isset($data['updated_on'])    ? filter_var($data['updated_on'], FILTER_SANITIZE_STRING) :  '';
1756
 
1757
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1758
                    if(!$dt) {
1759
                        $ok = false;
1760
                    } else {
1761
                        $added_on = $dt->format('Y-m-d H:i:s');
1762
                    }
1763
 
1764
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $updated_on );
1765
                    if(!$dt) {
1766
                        $ok = false;
1767
                    } else {
1768
                        $updated_on = $dt->format('Y-m-d H:i:s');
1769
                    }
1770
 
1771
                    if(!$ok) {
1772
                        return new JsonModel([
1773
                            'success' => false,
1774
                            'data' => [
1775
                                'sync_id' => $sync_id,
1776
                                'message' => 'ERROR_INVALID_PARAMETERS',
1777
                            ]
1778
                        ]);
1779
                    }
1780
 
1781
                           //$progress                   = isset($data['progress'])                  ? floatval($data['progress']) :  0;
1782
                    //$total_slides               = isset($data['total_slides'])              ? intval($data['total_slides'], 10) :  0;
1783
                    //$view_slides                = isset($data['view_slides'])               ? intval($data['view_slides'], 10) :  0;
1784
                    $returning                  = isset($data['returning'])                 ? intval($data['returning'], 10) :  0;
1785
                    $returning_after_completed  = isset($data['returning_after_completed']) ? intval($data['returning_after_completed'], 10) :  0;
1786
                    $completed                  = isset($data['completed'])                 ? intval($data['completed'], 10) :  0;
1787
 
1788
                    $progressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
1789
                    $recordProgress = null;
1790
                    switch($type) {
1791
                        case CompanyMicrolearningUserProgress::TYPE_TOPIC  :
1792
                            $recordProgress = $progressMapper->fetchOneByUserIdAndTopicId($user->id, $topic->id);
1793
 
1794
                            break;
1795
 
1796
                        case CompanyMicrolearningUserProgress::TYPE_CAPSULE  :
1797
                            $recordProgress = $progressMapper->fetchOneByUseridAndCapsuleId($user->id, $capsule->id);
1798
                            break;
1799
 
1800
                        case CompanyMicrolearningUserProgress::TYPE_SLIDE  :
1801
                            $recordProgress = $progressMapper->fetchOneByUserIdAndSlideId($user->id, $slide->id);
1802
                            break;
1803
 
1804
                        default :
1805
                            $recordProgress= null;
1806
                    }
1807
 
1808
 
1809
                    if(!$recordProgress) {
1810
                        $recordProgress = new CompanyMicrolearningUserProgress();
1811
 
1812
                        $recordProgress->user_id    = $user->id;
1813
                        $recordProgress->type       = $type;
1814
                        $recordProgress->company_id = $topic->company_id;
1815
                        $recordProgress->topic_id   = $topic->id;
1816
                        $recordProgress->capsule_id = $capsule ? $capsule->id : null;
1817
                        $recordProgress->slide_id   = $slide ? $slide->id : null;
1818
                        $recordProgress->added_on   = $added_on;
1819
                    }
1820
                    $recordProgress->returning                  = $returning;
1821
                    $recordProgress->returning_after_completed  = $returning_after_completed;
1822
                    $recordProgress->completed                  = $completed;
1823
 
1824
                    if($type == CompanyMicrolearningUserProgress::TYPE_TOPIC ) {
1825
 
1826
                        $capsule_ids = [];
1827
                        $companyMicrolearningCapsuleUser = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
1828
                        $records =  $companyMicrolearningCapsuleUser->fetchAllActiveByUserId($user->id);
1829
                        foreach($records as $record)
1830
                        {
1831
                            if($now >= $record->paid_from || $now <= $capsuleUser->paid_to) {
1832
                                if(!in_array($record->capsule_id, $capsule_ids)) {
1833
                                    array_push($capsule_ids, $record->capsule_id);
1834
                                }
1835
                            }
1836
                        }
1837
 
1838
                        $view_slides    = 0;
1839
                        $total_slides   = 0;
1840
                        foreach($capsule_ids as $capsule_id)
1841
                        {
1842
                            $view_slides    += $progressMapper->fetchCountAllSlideViewedByUserIdAndCapsuleId($user->id, $capsule_id);
1843
                            $total_slides   += $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $topic->id, $capsule_id);
1844
 
1845
                        }
1846
 
1847
 
1848
                        $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
1849
                        $recordProgress->total_slides   = $total_slides;
1850
                        $recordProgress->view_slides    = $view_slides;
1851
                    }
1852
                    else if($type == CompanyMicrolearningUserProgress::TYPE_CAPSULE ) {
1853
                        $view_slides    = $progressMapper->fetchCountAllSlideViewedByUserIdAndCapsuleId($user->id, $capsule->id);
1854
                        $total_slides   = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $capsule->topic_id, $capsule->id);
1855
 
1856
                        $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
1857
                        $recordProgress->total_slides   = $total_slides;
1858
                        $recordProgress->view_slides    = $view_slides;
1859
                    }
1860
                    else {
1861
                        $recordProgress->progress       = 0;
1862
                        $recordProgress->total_slides   = 0;
1863
                        $recordProgress->view_slides    = 0;
1864
                    }
1865
 
1866
                    $recordProgress->updated_on = $updated_on;
1867
 
1868
 
1869
 
1870
                    if($recordProgress->id) {
1871
                        $result = $progressMapper->update($recordProgress);
1872
                    } else {
1873
                        $result = $progressMapper->insert($recordProgress);
1874
                    }
1875
 
1876
                    if($result) {
1877
                        return new JsonModel([
1878
                            'success' => true,
1879
                            'data' => [
1880
                                'sync_id' => $sync_id
1881
                            ]
1882
                        ]);
1883
                    } else {
1884
                        return new JsonModel([
1885
                            'success' => false,
1886
                            'data' => [
1887
                                'sync_id' => $sync_id,
1888
                                'message' => $progressMapper->getError()
1889
                            ]
1890
                        ]);
1891
                    }
1892
                }
1893
 
1894
 
1895
 
1896
                if($sync_type == 'microlearning-userlog') {
1897
                    $activity   = isset($data['activity'])      ? filter_var($data['activity'], FILTER_SANITIZE_STRING)  :  '';
1898
                    $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
1899
 
1900
 
1901
                    if(empty($activity)) {
1902
                        $ok = false;
1903
                    }
1904
 
1905
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1906
                    if(!$dt) {
1907
                        $ok = false;
1908
                    } else {
1909
                        $added_on = $dt->format('Y-m-d H:i:s');
1910
                    }
1911
 
1912
                    if(!$ok) {
1913
                        return new JsonModel([
1914
                            'success' => false,
1915
                            'data' => [
1916
                                'sync_id' => $sync_id,
1917
                                'message' => 'ERROR_INVALID_PARAMETERS',
1918
                            ]
1919
                        ]);
1920
                    }
1921
 
1922
                    $userLog = new CompanyMicrolearningUserLog();
1923
                    $userLog->activity      = $activity;
1924
                    $userLog->user_id       = $user->id;
1925
                    $userLog->company_id    = $topic->company_id;
1926
                    $userLog->topic_id      = $topic->id;
1927
                    $userLog->capsule_id    = $capsule ? $capsule->id : null;
1928
                    $userLog->slide_id      = $slide ? $slide->id : null;
1929
                    $userLog->added_on      = $added_on;
1930
 
1931
 
1932
 
1933
                    $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
1934
                    if($userLogMapper->insert($userLog)) {
1935
                        return new JsonModel([
1936
                            'success' => true,
1937
                            'data' => [
1938
                                'sync_id' => $sync_id
1939
                            ]
1940
                        ]);
1941
                    } else {
1942
                        return new JsonModel([
1943
                            'success' => false,
1944
                            'data' => [
1945
                                'sync_id' => $sync_id,
1946
                                'message' => $userLogMapper->getError()
1947
                            ]
1948
                        ]);
1949
                    }
1950
                }
1951
 
1952
            }
1953
 
1954
 
1955
 
1956
 
1957
            if($user_uuid && $sync_type == 'userlog' && $device->application_id = Application::TWOGETSKILLS) {
1958
 
1959
                $userMapper = UserMapper::getInstance($this->adapter);
1960
                $user = $userMapper->fetchOneByUuid($user_uuid);
1961
 
1962
                if(!$user) {
1963
                    return new JsonModel([
1964
                        'success' => false,
1965
                        'data' => [
1966
                            'sync_id' => $sync_id,
1967
                            'message' => 'ERROR_USER_NOT_FOUND',
1968
                            'fatal' => true
1969
                        ]
1970
                    ]);
1971
                }
1972
 
1973
 
1974
                if($user->status != User::STATUS_ACTIVE) {
1975
                    return new JsonModel([
1976
                        'success' => false,
1977
                        'data' => [
1978
                            'sync_id' => $sync_id,
1979
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
1980
                            'fatal' => true
1981
                        ]
1982
                    ]);
1983
                }
1984
 
1985
                $activity   = isset($data['activity'])      ? filter_var($data['activity'], FILTER_SANITIZE_STRING)  :  '';
1986
                $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
1987
 
1988
                if(empty($activity)) {
1989
                    $ok = false;
1990
                }
1991
 
1992
                $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1993
                if(!$dt) {
1994
                    $ok = false;
1995
                } else {
1996
                    $added_on = $dt->format('Y-m-d H:i:s');
1997
                }
1998
 
1999
                if(!$ok) {
2000
                    return new JsonModel([
2001
                        'success' => false,
2002
                        'data' => [
2003
                            'sync_id' => $sync_id,
2004
                            'message' => 'ERROR_INVALID_PARAMETERS',
2005
                        ]
2006
                    ]);
2007
                }
2008
 
2009
                $userLog = new CompanyMicrolearningUserLog();
2010
                $userLog->company_id = null;
2011
                $userLog->user_id = $user->id;
2012
                $userLog->activity = $activity;
2013
                $userLog->added_on = $added_on;
2014
 
2015
 
2016
                $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2017
                if($userLogMapper->insert($userLog)) {
2018
                    return new JsonModel([
2019
                        'success' => true,
2020
                        'data' => [
2021
                            'sync_id' => $sync_id
2022
                        ]
2023
                    ]);
2024
                } else {
2025
                    return new JsonModel([
2026
                        'success' => false,
2027
                        'data' => [
2028
                            'sync_id' => $sync_id,
2029
                            'message' => $userLogMapper->getError()
2030
                        ]
2031
                    ]);
2032
                }
2033
            }
2034
 
2035
            return new JsonModel([
2036
                'success' => true,
2037
                'data' => [
2038
                    'sync_id' => $sync_id
2039
                ]
2040
            ]);
2041
 
2042
        }
2043
 
2044
        return new JsonModel([
2045
            'success' => false,
2046
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2047
        ]);
2048
    }
2049
 
2050
 
2051
    public function syncBatchAction()
2052
    {
2053
        $request = $this->getRequest();
2054
 
2055
        if($request->isPost()) {
2056
 
41 efrain 2057
 
1 www 2058
 
2059
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
2060
 
2061
            $device_uuid = filter_var($this->params()->fromPost('device_uuid', ''), FILTER_SANITIZE_STRING);
2062
            $max_records = filter_var($this->params()->fromPost('max_records', 0), FILTER_SANITIZE_NUMBER_INT);
41 efrain 2063
 
1 www 2064
            $ok = $device_uuid && strlen($device_uuid) == 36 && $max_records;
2065
 
2066
            if(!$ok) {
2067
                return new JsonModel([
2068
                    'success' => false,
2069
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID',
2070
                ]);
2071
            }
2072
 
2073
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
2074
            $device = $deviceMapper->fetchOne($device_uuid);
2075
 
2076
 
2077
            if(!$device) {
2078
                return new JsonModel([
2079
                    'success' => false,
2080
                    'data' => 'ERROR_DEVICE_NOT_FOUND'
2081
                ]);
2082
            } else {
2083
                $device->ip = Functions::getUserIP();
2084
                $deviceMapper->update($device);
2085
            }
41 efrain 2086
 
2087
 
1 www 2088
 
41 efrain 2089
 
2090
            $syncLogMapper = SyncLogMapper::getInstance($this->adapter);
2091
 
2092
 
2093
 
1 www 2094
            $result_sync_ids = [];
2095
 
2096
 
2097
 
2098
 
16 efrain 2099
            $users = [];
2100
            $companies = [];
2101
            $company_services = [];
2102
            $topics = [];
2103
            $capsules = [];
2104
            $capsule_users = [];
2105
            $slides = [];
2106
            $quizzes = [];
2107
            $questions = [];
2108
            $answers = [];
2109
 
2110
            $userMapper = UserMapper::getInstance($this->adapter);
2111
            $companyMapper = CompanyMapper::getInstance($this->adapter);
2112
            $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
2113
            $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
2114
            $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
2115
            $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
2116
            $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
2117
            $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
2118
            $questionMapper = CompanyMicrolearningQuestionMapper::getInstance($this->adapter);
2119
            $answerMapper = CompanyMicrolearningAnswerMapper::getInstance($this->adapter);
2120
 
2121
 
2122
            $userProgressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
2123
            $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2124
 
1 www 2125
            for($i = 1; $i <= $max_records; $i++)
2126
            {
2127
                $sync_id        = filter_var($this->params()->fromPost('record_sync_id' . $i, ''), FILTER_SANITIZE_NUMBER_INT);
2128
                $record_data    = $this->params()->fromPost('record_data' . $i, '');
2129
 
2130
                if(empty($record_data) || empty($sync_id )) {
2131
                    continue;
2132
                }
41 efrain 2133
 
1 www 2134
 
45 efrain 2135
 
1 www 2136
                $record         = json_decode($record_data, true);
2137
                $sync_type      = isset($record['sync_type']) ? filter_var($record['sync_type'],  FILTER_SANITIZE_STRING) : '';
2138
                $user_uuid      = isset($record['user_uuid']) ? filter_var($record['user_uuid'],  FILTER_SANITIZE_STRING) : '';
2139
                $company_uuid   = isset($record['company_uuid']) ? filter_var($record['company_uuid'], FILTER_SANITIZE_STRING) : '';
2140
 
2141
                if(!$sync_id) {
2142
                    continue;
2143
                }
2144
 
45 efrain 2145
                $syncLog = new SyncLog();
2146
                $syncLog->data = $record_data;
2147
                $syncLog->type = $sync_type;
2148
                $syncLog->device_uuid = $device->id;
2149
                $syncLog->ip = Functions::getUserIP();
2150
                $syncLogMapper->insert($syncLog);
2151
 
1 www 2152
                /***** INICIO MICROLEARNING *****/
2153
 
2154
                if($user_uuid && $device->application_id = Application::TWOGETSKILLS  && $company_uuid && in_array($sync_type, ['microlearning-progress', 'microlearning-userlog', 'microlearning-quiz'])) {
2155
 
16 efrain 2156
 
2157
                    if(isset($users[$user_uuid])) {
2158
                        $user = $users[$user_uuid];
2159
                    } else {
2160
 
2161
                        $user = $userMapper->fetchOneByUuid($user_uuid);
2162
                        if($user) {
2163
                            $users[$user_uuid] = $user;
2164
                        }
2165
                    }
2166
 
2167
 
1 www 2168
                    if(!$user) {
2169
                        array_push($result_sync_ids, [
2170
                            'success' => false,
2171
                            'sync_id' => $sync_id,
2172
                            'message' => 'ERROR_USER_NOT_FOUND',
2173
                            'fatal' => true
2174
                        ]);
2175
                        continue;
2176
                    }
2177
 
2178
 
2179
                    if($user->status != User::STATUS_ACTIVE) {
2180
                        array_push($result_sync_ids, [
2181
                            'success' => false,
2182
                            'sync_id' => $sync_id,
2183
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
2184
                            'fatal' => true
2185
                        ]);
2186
                        continue;
2187
                    }
2188
 
16 efrain 2189
 
2190
                    if(isset($companies[$company_uuid])) {
2191
                        $company = $companies[$company_uuid];
2192
                    } else {
2193
                        $company = $companyMapper->fetchOneByUuid($company_uuid);
2194
                        if($company) {
2195
                            $companies[$company_uuid] = $company;
2196
                        }
2197
                    }
2198
 
2199
 
2200
 
2201
 
1 www 2202
                    if(!$company) {
2203
                        array_push($result_sync_ids, [
2204
                            'success' => false,
2205
                            'sync_id' => $sync_id,
2206
                            'message' => 'ERROR_COMPANY_NOT_FOUND',
2207
                            'fatal' => true
2208
                        ]);
2209
                        continue;
2210
                    }
2211
 
2212
                    if($company->status != Company::STATUS_ACTIVE) {
2213
                        array_push($result_sync_ids, [
2214
                            'success' => false,
2215
                            'sync_id' => $sync_id,
2216
                            'message' => 'ERROR_COMPANY_IS_NOT_FOUND',
2217
                            'fatal' => true
2218
                        ]);
2219
                        continue;
2220
                    }
2221
 
2222
 
2223
 
16 efrain 2224
                    $key = $company->id . '-' .  Service::MICRO_LEARNING;
2225
                    if(isset($company_services[$key])) {
2226
                        $companyService = $company_services[$key];
2227
                    } else {
2228
                        $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($company->id, Service::MICRO_LEARNING);
2229
                        if($companyService) {
2230
                            $company_services[$key] = $companyService;
2231
                        }
2232
                    }
1 www 2233
 
2234
                    if(!$companyService) {
2235
                        array_push($result_sync_ids, [
2236
                            'success' => false,
2237
                            'sync_id' => $sync_id,
2238
                            'message' => 'ERROR_COMPANY_SERVICE_NOT_FOUND',
2239
                            'fatal' => true
2240
                        ]);
2241
                        continue;
2242
                    }
2243
 
2244
                    $serviceActive = true;
2245
                    $now = date('Y-m-d H:i:s');
2246
                    if($companyService->status == CompanyService::ACTIVE) {
2247
 
2248
                        if($now < $companyService->paid_from || $now > $companyService->paid_to) {
2249
                            $serviceActive = false;
2250
                        }
2251
 
2252
                    } else {
2253
                        $serviceActive = false;
2254
                    }
2255
 
2256
                    if( !$serviceActive) {
2257
                        array_push($result_sync_ids, [
2258
                            'success' => false,
2259
                            'sync_id' => $sync_id,
2260
                            'message' => 'ERROR_COMPANY_SERVICE_IS_NOT_ACTIVE',
2261
                            'fatal' => true
2262
                        ]);
2263
                        continue;
2264
                    }
2265
 
16 efrain 2266
 
1 www 2267
                    $topic_uuid = isset($record['topic_uuid']) ? filter_var($record['topic_uuid'], FILTER_SANITIZE_STRING) :  '';
2268
                    if($topic_uuid) {
2269
 
16 efrain 2270
                        if(isset($topics[$topic_uuid])) {
2271
                            $topic = $topics[$topic_uuid];
2272
                        } else {
2273
                            $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2274
                            if($topic) {
2275
                                $topics[$topic_uuid] = $topic;
2276
                            }
2277
                        }
2278
 
1 www 2279
                        if(!$topic) {
2280
                            array_push($result_sync_ids, [
2281
                                'success' => false,
2282
                                'sync_id' => $sync_id,
2283
                                'message' => 'ERROR_TOPIC_NOT_FOUND',
2284
                            ]);
2285
                            continue;
2286
                        }
2287
 
2288
                        if($topic->company_id != $company->id) {
2289
                            array_push($result_sync_ids, [
2290
                                'success' => false,
2291
                                'sync_id' => $sync_id,
2292
                                'message' => 'ERROR_INVALID_PARAMETERS_TOPIC_COMPANY',
2293
                            ]);
2294
                            continue;
2295
                        }
2296
 
2297
                    } else {
2298
                        $topic = null;
2299
                    }
2300
 
2301
                    $capsule_uuid     = isset($record['capsule_uuid']) ? filter_var($record['capsule_uuid'], FILTER_SANITIZE_STRING) :  '';
16 efrain 2302
 
1 www 2303
                    if($capsule_uuid) {
2304
 
16 efrain 2305
                        if(isset($capsules[$capsule_uuid])) {
2306
                            $capsule = $capsules[$capsule_uuid];
2307
                        } else {
2308
                            $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2309
                            if($capsule) {
2310
                                $capsules[$capsule_uuid] = $capsule;
2311
                            }
2312
                        }
1 www 2313
                        if(!$capsule) {
2314
                            array_push($result_sync_ids, [
2315
                                'success' => false,
2316
                                'sync_id' => $sync_id,
2317
                                'message' => 'ERROR_CAPSULE_NOT_FOUND',
2318
                            ]);
2319
                            continue;
2320
                        }
2321
 
2322
                        if(!$topic || $capsule->topic_id != $topic->id) {
2323
                            array_push($result_sync_ids, [
2324
                                'success' => false,
2325
                                'sync_id' => $sync_id,
2326
                                'message' => 'ERROR_INVALID_PARAMETERS_CAPSULE_TOPIC',
2327
                            ]);
2328
                            continue;
2329
                        }
2330
                    } else {
2331
                        $capsule = null;
2332
                    }
2333
 
2334
                    if($capsule) {
2335
 
2336
                        $capsuleActive = true;
2337
 
16 efrain 2338
                        $key = $user->id . '-' . $capsule->id;
1 www 2339
 
16 efrain 2340
                        if(isset($capsule_users[$key])) {
2341
                            $capsuleUser = $capsule_users[$key];
2342
                        } else {
2343
 
2344
                            $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
2345
                            if($capsuleUser) {
2346
                                $capsule_users[$key] = $capsuleUser;
2347
                            }
2348
 
2349
                        }
2350
 
1 www 2351
                        $now = date('Y-m-d H:i:s');
2352
                        if($capsuleUser && in_array($capsuleUser->access, [CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED,CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD ])) {
2353
 
2354
 
2355
                            if($capsuleUser->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
2356
 
2357
                                if($now < $capsuleUser->paid_from || $now > $capsuleUser->paid_to) {
2358
                                    $capsuleActive = false;;
2359
                                }
2360
                            }
2361
 
2362
                        } else {
2363
                            $capsuleActive = false;
2364
                        }
2365
 
2366
                        if(!$capsuleActive) {
2367
                            array_push($result_sync_ids, [
2368
                                'success' => false,
2369
                                'sync_id' => $sync_id,
2370
                                'message' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
2371
                            ]);
2372
                            continue;
2373
                        }
2374
                    }
2375
 
16 efrain 2376
 
1 www 2377
                    $slide_uuid      = isset($record['slide_uuid']) ? filter_var($record['slide_uuid'], FILTER_SANITIZE_STRING) :  '';
2378
                    if($slide_uuid) {
16 efrain 2379
 
2380
                        if(isset($slides[$slide_uuid])) {
2381
                            $slide = $slides[$slide_uuid];
2382
                        } else {
2383
 
2384
                            $slide = $slideMapper->fetchOneByUuid($slide_uuid);
2385
                            if($slide) {
2386
                                $slides[$slide_uuid] = $slide;
2387
                            }
2388
                        }
1 www 2389
                        if(!$slide) {
2390
                            array_push($result_sync_ids, [
2391
                                'success' => false,
2392
                                'sync_id' => $sync_id,
2393
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
2394
                            ]);
2395
                            continue;
2396
                        }
2397
 
2398
                        if(!$capsule || $slide->capsule_id != $capsule->id) {
2399
                            array_push($result_sync_ids, [
2400
                                'success' => false,
2401
                                'sync_id' => $sync_id,
2402
                                'message' => 'ERROR_INVALID_PARAMETERS_SLIDE_CAPSULE',
2403
                            ]);
2404
                            continue;
2405
                        }
2406
                    } else {
2407
                        $slide = null;
2408
                    }
2409
 
2410
                    if($sync_type == 'microlearning-quiz') {
2411
                        $ok = true;
2412
 
2413
                        $quiz_uuid = isset($record['quiz_uuid']) ? $record['quiz_uuid'] : '';
16 efrain 2414
 
2415
                        if(isset($quizzes[$quiz_uuid])) {
2416
                            $quiz = $quizzes[$quiz_uuid];
2417
                        } else {
2418
                            $quiz = $quizMapper->fetchOneByUuid($quiz_uuid);
2419
                            if($quiz) {
2420
                                $quizzes[$quiz_uuid] = $quiz;
2421
                            }
2422
                        }
1 www 2423
                        if(!$quiz) {
2424
                            array_push($result_sync_ids, [
2425
                                'success' => false,
2426
                                'sync_id' => $sync_id,
2427
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
2428
                            ]);
2429
                            continue;
2430
                        }
2431
 
2432
                        if(!$capsule || $slide->capsule_id != $capsule->id) {
2433
                            array_push($result_sync_ids, [
2434
                                'success' => false,
2435
                                'sync_id' => $sync_id,
2436
                                'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_SLIDE',
2437
                            ]);
2438
                            continue;
2439
                        }
2440
 
2441
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2442
 
2443
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2444
                        if(!$dt) {
2445
                            $ok = false;
2446
                        } else {
2447
                            $added_on = $dt->format('Y-m-d H:i:s');
2448
                        }
2449
 
2450
                        if(isset($record['points'])) {
2451
                            $points = intval($record['points'], 10);
2452
                        } else {
2453
                            $ok = false;
2454
                        }
2455
 
2456
                        if(isset($record['pass'])) {
2457
                            $status = $record['pass'] == 'yes' ? CompanyMicrolearningUserQuiz::STATUS_PASS : CompanyMicrolearningUserQuiz::STATUS_FAIL;
2458
                        } else {
2459
                            $ok = false;
2460
                        }
2461
 
2462
                        if(!$ok) {
2463
                            array_push($result_sync_ids, [
2464
                                'success' => false,
2465
                                'sync_id' => $sync_id,
2466
                                'message' => 'ERROR_INVALID_PARAMETERS',
2467
                            ]);
2468
                            continue;
2469
                        }
2470
 
2471
                        $array_response = [];
2472
                        $response = isset($record['response']) ? intval($record['response'], 10) : 0;
2473
                        for($i = 0; $i < $response; $i++)
2474
                        {
2475
                            $question_uuid = isset($record["response_{$i}_question_uuid"]) ? $record["response_{$i}_question_uuid"] : '';
2476
                            $answer_uuid = isset($record["response_{$i}_answer_uuid"]) ? $record["response_{$i}_answer_uuid"] : '';
2477
                            $value = isset($record["response_{$i}_value"]) ?  intval($record["response_{$i}_value"], 10) : 0;
2478
                            $points = isset($record["response_{$i}_points"]) ?  intval($record["response_{$i}_points"], 10) : 0;
2479
 
16 efrain 2480
 
2481
                            if(isset($questions[$question_uuid])) {
2482
                                $question = $questions[$question_uuid];
2483
                            } else {
2484
                                $question = $questionMapper->fetchOneByUuid($question_uuid);
2485
                                if($question) {
2486
                                    $questions[$question_uuid] = $question;
2487
                                }
2488
                            }
2489
 
2490
                            if(!$question || $question->quiz_id != $quiz->id) {
2491
                                array_push($result_sync_ids, [
2492
                                    'success' => false,
2493
                                    'sync_id' => $sync_id,
2494
                                    'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_QUESTION_SLIDE',
1 www 2495
                                ]);
16 efrain 2496
                                continue;
2497
                            }
2498
 
2499
                            if(isset($answers[$answer_uuid])) {
2500
                                $answer = $answers[$answer_uuid];
2501
                            } else {
2502
                                $answer = $answerMapper->fetchOneByUuid($answer_uuid);
2503
                                if($answer) {
2504
                                    $answers[$answer_uuid] = $answer;
2505
                                }
2506
                            }
2507
 
2508
                            if($answer && $answer->question_id != $question->id) {
2509
                                array_push($result_sync_ids, [
2510
                                    'success' => false,
2511
                                    'sync_id' => $sync_id,
2512
                                    'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_ANSWER_SLIDE',
2513
                                ]);
2514
                                continue;
2515
                            }
2516
 
2517
                            array_push($array_response, [
2518
                                'question_uuid' => $question_uuid,
2519
                                'answer_uuid' => $answer_uuid,
2520
                                'value' => $value,
2521
                                'points' => $points
2522
                            ]);
1 www 2523
                        }
2524
 
2525
                        $userQuiz = new CompanyMicrolearningUserQuiz();
2526
                        $userQuiz->company_id = $company->id;
2527
                        $userQuiz->topic_id = $topic->id;
2528
                        $userQuiz->capsule_id = $capsule->id;
2529
                        $userQuiz->slide_id = $slide->id;
2530
                        $userQuiz->quiz_id = $quiz->id;
2531
                        $userQuiz->user_id = $user->id;
2532
                        $userQuiz->added_on = $added_on;
2533
                        $userQuiz->points = $points;
2534
                        $userQuiz->status = $status;
2535
                        $userQuiz->response = json_encode($array_response);
2536
 
2537
                        $userQuizMapper = CompanyMicrolearningUserQuizMapper::getInstance($this->adapter);
2538
 
2539
                        if($userQuizMapper->insert($userQuiz)) {
2540
                            array_push($result_sync_ids, [
2541
                                'success' => true,
2542
                                'sync_id' => $sync_id
2543
                            ]);
2544
                        } else {
2545
                            array_push($result_sync_ids, [
2546
                                'success' => false,
2547
                                'sync_id' => $sync_id,
2548
                                'message' => $userQuizMapper->getError()
2549
                            ]);
2550
                        }
2551
                        continue;
2552
                    }
2553
 
2554
                    if($sync_type == 'microlearning-progress') {
2555
                        $ok = true;
2556
 
2557
                        $type = isset($record['type']) ? $record['type'] : '';
2558
                        switch($type)
2559
                        {
2560
                            case CompanyMicrolearningUserProgress::TYPE_TOPIC :
2561
                                if(!$topic) {
2562
                                    $ok = false;
2563
                                }
2564
                                break;
2565
 
2566
                            case CompanyMicrolearningUserProgress::TYPE_CAPSULE :
2567
                                if(!$topic || !$capsule) {
2568
                                    $ok = false;
2569
                                }
2570
                                break;
2571
 
2572
                            case CompanyMicrolearningUserProgress::TYPE_SLIDE :
2573
                                if(!$topic || !$capsule || !$slide) {
2574
                                    $ok = false;
2575
                                }
2576
                                break;
2577
 
2578
                            default :
2579
                                $ok = false;
2580
                                break;
2581
                        }
2582
 
2583
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2584
                        $updated_on = isset($record['updated_on'])    ? filter_var($record['updated_on'], FILTER_SANITIZE_STRING) :  '';
2585
 
2586
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2587
                        if(!$dt) {
2588
                            $ok = false;
2589
                        } else {
2590
                            $added_on = $dt->format('Y-m-d H:i:s');
2591
                        }
2592
 
2593
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $updated_on );
2594
                        if(!$dt) {
2595
                            $ok = false;
2596
                        } else {
2597
                            $updated_on = $dt->format('Y-m-d H:i:s');
2598
                        }
2599
 
2600
                        if(!$ok) {
2601
                            array_push($result_sync_ids, [
2602
                                'success' => false,
2603
                                'sync_id' => $sync_id,
2604
                                'message' => 'ERROR_INVALID_PARAMETERS',
2605
                            ]);
2606
                            continue;
2607
                        }
2608
 
18 efrain 2609
                        $progress                   = isset($record['progress'])                  ? floatval($record['progress']) :  0;
2610
                        $total_slides               = isset($record['total_slides'])              ? intval($record['total_slides'], 10) :  0;
2611
                        $view_slides                = isset($record['view_slides'])               ? intval($record['view_slides'], 10) :  0;
1 www 2612
                        $returning                  = isset($record['returning'])                 ? intval($record['returning'], 10) :  0;
2613
                        $returning_after_completed  = isset($record['returning_after_completed']) ? intval($record['returning_after_completed'], 10) :  0;
2614
                        $completed                  = isset($record['completed'])                 ? intval($record['completed'], 10) :  0;
2615
 
16 efrain 2616
 
1 www 2617
                        $recordProgress = null;
2618
                        switch($type) {
2619
                            case CompanyMicrolearningUserProgress::TYPE_TOPIC  :
16 efrain 2620
                                $recordProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($user->id, $topic->id);
1 www 2621
 
2622
                                break;
2623
 
2624
                            case CompanyMicrolearningUserProgress::TYPE_CAPSULE  :
16 efrain 2625
                                $recordProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($user->id, $capsule->id);
1 www 2626
                                break;
2627
 
2628
                            case CompanyMicrolearningUserProgress::TYPE_SLIDE  :
16 efrain 2629
                                $recordProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($user->id, $slide->id);
1 www 2630
                                break;
2631
 
2632
                            default :
2633
                                $recordProgress= null;
2634
                        }
2635
 
2636
 
2637
                        if(!$recordProgress) {
2638
                            $recordProgress = new CompanyMicrolearningUserProgress();
2639
 
2640
                            $recordProgress->user_id    = $user->id;
2641
                            $recordProgress->type       = $type;
2642
                            $recordProgress->company_id = $topic->company_id;
2643
                            $recordProgress->topic_id   = $topic->id;
2644
                            $recordProgress->capsule_id = $capsule ? $capsule->id : null;
2645
                            $recordProgress->slide_id   = $slide ? $slide->id : null;
2646
                            $recordProgress->added_on   = $added_on;
43 efrain 2647
                        }
2648
                        /*
2649
                        else {
16 efrain 2650
 
2651
                            if($recordProgress->updated_on > $updated_on) {
2652
                                array_push($result_sync_ids, [
2653
                                    'success' => true,
2654
                                    'sync_id' => $sync_id,
2655
                                ]);
2656
                                continue;
2657
                            }
2658
 
2659
 
2660
 
43 efrain 2661
                        }*/
1 www 2662
                        $recordProgress->returning                  = $returning;
2663
                        $recordProgress->returning_after_completed  = $returning_after_completed;
2664
                        $recordProgress->completed                  = $completed;
2665
 
2666
                        if($type == CompanyMicrolearningUserProgress::TYPE_TOPIC ) {
2667
 
2668
                            $capsule_ids = [];
2669
                            $companyMicrolearningCapsuleUser = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
2670
                            $records =  $companyMicrolearningCapsuleUser->fetchAllActiveByUserId($user->id);
2671
                            foreach($records as $record)
2672
                            {
2673
                                if($now >= $record->paid_from || $now <= $capsuleUser->paid_to) {
2674
                                    if(!in_array($record->capsule_id, $capsule_ids)) {
2675
                                        array_push($capsule_ids, $record->capsule_id);
2676
                                    }
2677
                                }
2678
                            }
18 efrain 2679
 
2680
                            $recordProgress->progress       = $progress;
1 www 2681
                            $recordProgress->total_slides   = $total_slides;
2682
                            $recordProgress->view_slides    = $view_slides;
2683
                        }
2684
                        else if($type == CompanyMicrolearningUserProgress::TYPE_CAPSULE ) {
18 efrain 2685
 
2686
                            $recordProgress->progress       = $progress;
1 www 2687
                            $recordProgress->total_slides   = $total_slides;
2688
                            $recordProgress->view_slides    = $view_slides;
2689
                        }
2690
                        else {
2691
                            $recordProgress->progress       = 0;
2692
                            $recordProgress->total_slides   = 0;
2693
                            $recordProgress->view_slides    = 0;
2694
                        }
2695
 
2696
                        $recordProgress->updated_on = $updated_on;
2697
 
2698
 
2699
 
2700
                        if($recordProgress->id) {
16 efrain 2701
                            $result = $userProgressMapper->update($recordProgress);
1 www 2702
                        } else {
16 efrain 2703
                            $result = $userProgressMapper->insert($recordProgress);
1 www 2704
                        }
2705
 
2706
                        if($result) {
2707
                            array_push($result_sync_ids, [
2708
                                'success' => true,
2709
                                'sync_id' => $sync_id
2710
                            ]);
2711
                        } else {
2712
                            array_push($result_sync_ids, [
2713
                                'success' => false,
2714
                                'sync_id' => $sync_id,
16 efrain 2715
                                'message' => $userProgressMapper->getError()
1 www 2716
                            ]);
2717
                        }
2718
                        continue;
2719
                    }
2720
 
2721
 
2722
 
2723
                    if($sync_type == 'microlearning-userlog') {
2724
                        $activity   = isset($record['activity'])      ? filter_var($record['activity'], FILTER_SANITIZE_STRING)  :  '';
2725
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2726
 
2727
 
2728
                        if(empty($activity)) {
2729
                            $ok = false;
2730
                        }
2731
 
2732
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2733
                        if(!$dt) {
2734
                            $ok = false;
2735
                        } else {
2736
                            $added_on = $dt->format('Y-m-d H:i:s');
2737
                        }
2738
 
2739
                        if(!$ok) {
2740
                            array_push($result_sync_ids, [
2741
                                'success' => false,
2742
                                'sync_id' => $sync_id,
2743
                                'message' => 'ERROR_INVALID_PARAMETERS',
2744
                            ]);
2745
                            continue;
2746
                        }
2747
 
2748
 
2749
 
2750
 
16 efrain 2751
                        $userLog = $userLogMapper->fetchLastBy($user->id);
2752
                        if($userLog) {
2753
                            $insert = $userLog->added_on <= $added_on;
2754
                        } else {
2755
                            $insert = true;
2756
                        }
2757
 
2758
 
2759
                        if($insert) {
2760
 
2761
                            $userLog = new CompanyMicrolearningUserLog();
2762
                            $userLog->activity      = $activity;
2763
                            $userLog->user_id       = $user->id;
2764
                            $userLog->company_id    = $topic->company_id;
2765
                            $userLog->topic_id      = $topic->id;
2766
                            $userLog->capsule_id    = $capsule ? $capsule->id : null;
2767
                            $userLog->slide_id      = $slide ? $slide->id : null;
2768
                            $userLog->added_on      = $added_on;
2769
 
2770
 
2771
 
2772
 
2773
                            if($userLogMapper->insert($userLog)) {
2774
                                array_push($result_sync_ids, [
2775
                                    'success' => true,
2776
                                    'sync_id' => $sync_id
2777
                                ]);
2778
                            } else {
2779
                                array_push($result_sync_ids, [
2780
                                    'success' => false,
2781
                                    'sync_id' => $sync_id,
2782
                                    'message' => $userLogMapper->getError()
2783
                                ]);
2784
                            }
2785
                        } else {
1 www 2786
                            array_push($result_sync_ids, [
2787
                                'success' => true,
16 efrain 2788
                                'sync_id' => $sync_id
1 www 2789
                            ]);
2790
                        }
2791
                        continue;
2792
                    }
2793
 
2794
                }
2795
 
2796
                /***** FIN MICROLEARNING *****/
2797
 
2798
 
2799
                /***** INICIO LOG DE USUARIO GENERAL *****/
2800
 
2801
                if($user_uuid && $sync_type == 'userlog' && $device->application_id = Application::TWOGETSKILLS) {
2802
 
2803
 
16 efrain 2804
                    if(isset($users[$user_uuid])) {
2805
                        $user = $users[$user_uuid];
2806
                    } else {
2807
                        $user = $userMapper->fetchOneByUuid($user_uuid);
2808
                        if($user) {
2809
                            $users[$user_uuid] = $user;
2810
                        }
2811
                    }
2812
 
2813
 
2814
 
2815
 
1 www 2816
                    if(!$user) {
2817
                        array_push($result_sync_ids, [
2818
                            'success' => false,
2819
                            'sync_id' => $sync_id,
2820
                            'message' => 'ERROR_USER_NOT_FOUND',
2821
                            'fatal' => true
2822
                        ]);
2823
                        continue;
2824
                    }
2825
 
2826
 
2827
                    if($user->status != User::STATUS_ACTIVE) {
2828
                        array_push($result_sync_ids, [
2829
                            'success' => false,
2830
                            'sync_id' => $sync_id,
2831
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
2832
                            'fatal' => true
2833
                        ]);
2834
                        continue;
2835
                    }
2836
 
2837
                    $activity   = isset($record['activity'])      ? filter_var($record['activity'], FILTER_SANITIZE_STRING)  :  '';
2838
                    $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2839
 
2840
                    if(empty($activity)) {
2841
                        $ok = false;
2842
                    }
2843
 
2844
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2845
                    if(!$dt) {
2846
                        $ok = false;
2847
                    } else {
2848
                        $added_on = $dt->format('Y-m-d H:i:s');
2849
                    }
2850
 
2851
                    if(!$ok) {
2852
                        array_push($result_sync_ids, [
2853
                            'success' => false,
2854
                            'sync_id' => $sync_id,
2855
                            'message' => 'ERROR_INVALID_PARAMETERS',
2856
                        ]);
2857
                        continue;
2858
                    }
2859
 
2860
 
16 efrain 2861
                    $userLog = $userLogMapper->fetchLastBy($user->id);
2862
                    if($userLog) {
2863
                        $insert = $userLog->added_on <= $added_on;
2864
                    } else {
2865
                        $insert = true;
2866
                    }
1 www 2867
 
16 efrain 2868
 
2869
                    if($insert) {
2870
                        $userLog = new CompanyMicrolearningUserLog();
2871
                        $userLog->company_id = null;
2872
                        $userLog->user_id = $user->id;
2873
                        $userLog->activity = $activity;
2874
                        $userLog->added_on = $added_on;
2875
 
2876
 
2877
                        $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2878
                        if($userLogMapper->insert($userLog)) {
2879
                            array_push($result_sync_ids, [
2880
                                'success' => true,
2881
                                'sync_id' => $sync_id
2882
                            ]);
2883
                        } else {
2884
                            array_push($result_sync_ids, [
2885
                                'success' => false,
2886
                                'sync_id' => $sync_id,
2887
                                'message' => $userLogMapper->getError()
2888
                            ]);
2889
                        }
2890
                    } else {
1 www 2891
                        array_push($result_sync_ids, [
2892
                            'success' => true,
2893
                            'sync_id' => $sync_id
2894
                        ]);
2895
                    }
2896
 
16 efrain 2897
 
2898
 
1 www 2899
                    continue;
2900
                }
2901
 
2902
                /***** FIN LOG DE USUARIO GENERAL ******/
2903
            }
2904
 
2905
            if( $result_sync_ids) {
2906
                return new JsonModel([
2907
                    'success' => true,
2908
                    'data' => $result_sync_ids
2909
                ]);
2910
            } else {
2911
                return new JsonModel([
2912
                    'success' => false,
2913
                    'data' => 'ERROR_INVALID_PARAMETERS'
2914
                ]);
2915
            }
2916
 
2917
 
2918
        }
2919
 
2920
        return new JsonModel([
2921
            'success' => false,
2922
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2923
        ]);
2924
    }
2925
 
2926
    /**
2927
     *
2928
     * @param User $user
2929
     * @param boolean $includeLogs
2930
     * @param boolean $includeProgress
2931
     * @return array[]
2932
     */
2933
    private function getSyncData($user, $includeLogs = true, $includeProgress = true)
2934
    {
2935
 
2936
        $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
2937
 
2938
        $data = [
2939
            'userlog'   => [],
2940
            'progress'  => [],
2941
            'topics'    => [],
2942
            'quizzes'   => [],
2943
        ];
2944
 
2945
 
2946
        $companies = [];
2947
        $companyMapper = CompanyMapper::getInstance($this->adapter);
2948
 
2949
        $topics = [];
2950
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
2951
 
2952
        $capsules = [];
2953
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
2954
 
2955
        $slides = [];
2956
        $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
2957
 
2958
        $quizzes = [];
2959
        $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
2960
 
2961
        $questions = [];
2962
        $questionMapper = CompanyMicrolearningQuestionMapper::getInstance($this->adapter);
2963
 
2964
        $answers = [];
2965
        $answerMapper = CompanyMicrolearningAnswerMapper::getInstance($this->adapter);
2966
 
2967
 
2968
        $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2969
 
2970
        if($includeLogs) {
2971
 
2972
            $records = $userLogMapper->fetchLast20ByUserId($user->id);
2973
            foreach($records as $record)
2974
            {
2975
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
2976
 
2977
                if($record->company_id) {
2978
 
2979
                    if(isset($companies[$record->company_id])) {
2980
                        $company = $companies[$record->company_id];
2981
                    } else {
2982
                        $company = $companyMapper->fetchOne($record->company_id);
2983
                        $companies[$record->company_id] = $company;
2984
                    }
2985
                } else {
2986
                    $company = null;
2987
                }
2988
 
2989
                if($record->topic_id) {
2990
 
2991
                    if(isset($topics[$record->topic_id])) {
2992
                        $topic = $topics[$record->topic_id];
2993
                    } else {
2994
                        $topic = $topicMapper->fetchOne($record->topic_id);
2995
                        $topics[$record->topic_id] = $topic;
2996
                    }
2997
                } else {
2998
                    $topic = null;
2999
                }
3000
 
3001
 
3002
                if($record->capsule_id) {
3003
 
3004
                    if(isset($capsules[$record->capsule_id])) {
3005
                        $capsule = $capsules[$record->capsule_id];
3006
                    } else {
3007
                        $capsule = $capsuleMapper->fetchOne($record->capsule_id);
3008
                        $capsules[$record->capsule_id] = $capsule;
3009
                    }
3010
                } else {
3011
                    $capsule = null;
3012
                }
3013
 
3014
 
3015
                if($record->slide_id) {
3016
 
3017
                    if(isset($slides[$record->slide_id])) {
3018
                        $slide = $slides[$record->slide_id];
3019
                    } else {
3020
                        $slide = $slideMapper->fetchOne($record->slide_id);
3021
                        $slides[$record->slide_id] = $slide;
3022
                    }
3023
                } else {
3024
                    $slide = null;
3025
                }
3026
 
3027
 
3028
                array_push($data['userlog'], [
3029
                    'user_uuid'     => $user->uuid,
3030
                    'company_uuid'  => $company ? $company->uuid : '',
3031
                    'topic_uuid'    => $topic ? $topic->uuid : '',
3032
                    'capsule_uuid'  => $capsule ? $capsule->uuid : '',
3033
                    'slide_uuid'    => $slide ? $slide->uuid : '',
3034
                    'activity'      => $record->activity,
3035
                    'added_on'      => $dt->format($serviceDatetimeFormat),
3036
                ]);
3037
 
3038
 
3039
            }
3040
        }
3041
 
3042
        if($includeProgress) {
3043
 
3044
            $userProgressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
3045
            $records = $userProgressMapper->fetchAllByUserId($user->id);
3046
            foreach($records as $record)
3047
            {
3048
                if($record->company_id) {
3049
 
3050
                    if(isset($companies[$record->company_id])) {
3051
                        $company = $companies[$record->company_id];
3052
                    } else {
3053
                        $company = $companyMapper->fetchOne($record->company_id);
3054
                        $companies[$record->company_id] = $company;
3055
                    }
3056
                } else {
3057
                    $company = null;
3058
                }
3059
 
3060
                if($record->topic_id) {
3061
 
3062
                    if(isset($topics[$record->topic_id])) {
3063
                        $topic = $topics[$record->topic_id];
3064
                    } else {
3065
                        $topic = $topicMapper->fetchOne($record->topic_id);
3066
                        $topics[$record->topic_id] = $topic;
3067
                    }
3068
                } else {
3069
                    $topic = null;
3070
                }
3071
 
3072
 
3073
                if($record->capsule_id) {
3074
 
3075
                    if(isset($capsules[$record->capsule_id])) {
3076
                        $capsule = $capsules[$record->capsule_id];
3077
                    } else {
3078
                        $capsule = $capsuleMapper->fetchOne($record->capsule_id);
3079
                        $capsules[$record->capsule_id] = $capsule;
3080
                    }
3081
                } else {
3082
                    $capsule = null;
3083
                }
3084
 
3085
 
3086
                if($record->slide_id) {
3087
 
3088
                    if(isset($slides[$record->slide_id])) {
3089
                        $slide = $slides[$record->slide_id];
3090
                    } else {
3091
                        $slide = $slideMapper->fetchOne($record->slide_id);
3092
                        $slides[$record->slide_id] = $slide;
3093
                    }
3094
                } else {
3095
                    $slide = null;
3096
                }
3097
 
3098
 
3099
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
3100
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $record->updated_on);
3101
 
3102
                array_push($data['progress'], [
3103
                    'user_uuid'                 => $user->uuid,
3104
                    'company_uuid'              => $company ? $company->uuid : '',
3105
                    'topic_uuid'                => $topic ? $topic->uuid : '',
3106
                    'capsule_uuid'              => $capsule ? $capsule->uuid : '',
3107
                    'slide_uuid'                => $slide ? $slide->uuid : '',
3108
                    'progress'                  => $record->progress ? $record->progress : 0,
3109
                    'total_slides'              => $record->total_slides ? $record->total_slides : 0,
3110
                    'view_slides'               => $record->view_slides ? $record->view_slides : 0,
3111
                    'type'                      => $record->type,
3112
                    'returning'                 => $record->returning ? $record->returning : 0,
3113
                    'returning_after_completed' => $record->returning_after_completed ? $record->returning_after_completed : 0,
3114
                    'completed'                 => $record->completed ? $record->completed : 0,
3115
                    'added_on'                  => $dtAddedOn->format($serviceDatetimeFormat),
3116
                    'updated_on'                => $dtUpdatedOn->format($serviceDatetimeFormat),
3117
                ]);
3118
            }
3119
        }
3120
 
3121
 
3122
        $now = date('Y-m-d H:i:s');
3123
        $companies_with_access  = [];
3124
        $topics_with_access     = [];
3125
        $capsules_with_access   = [];
3126
        $quizzes_with_access    = [];
3127
        $quizzes                = [];
3128
 
3129
 
3130
        $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
3131
        $records = $capsuleUserMapper->fetchAllActiveByUserId($user->id);
3132
 
3133
 
3134
        foreach($records as $record)
3135
        {
3136
            if($record->access != CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED && $record->access != CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
3137
                continue;
3138
            }
3139
            if($record->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
3140
                if($now < $record->paid_from || $now > $record->paid_to) {
3141
                    continue;
3142
                }
3143
            }
3144
 
3145
 
3146
            if(!in_array($record->company_id,$companies_with_access)) {
3147
                array_push($companies_with_access, $record->company_id);
3148
            }
3149
 
3150
            if(!in_array($record->topic_id,$topics_with_access)) {
3151
                array_push($topics_with_access, $record->topic_id);
3152
            }
3153
 
3154
            if(!in_array($record->capsule_id,$capsules_with_access)) {
3155
                array_push($capsules_with_access, $record->capsule_id);
3156
            }
3157
        }
3158
 
3159
 /*
3160
        echo '$companies_with_access ' . PHP_EOL;
3161
        print_r($companies_with_access);
3162
 
3163
        echo '$topics_with_access ' . PHP_EOL;
3164
        print_r($topics_with_access);
3165
 
3166
        echo '$capsules_with_access' . PHP_EOL;
3167
        print_r($capsules_with_access);
3168
        */
3169
 
3170
        $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
3171
        foreach($companies_with_access as $company_id)
3172
        {
3173
            $companyService =  $companyServiceMapper->fetchOneActiveByCompanyIdAndServiceId($company_id, Service::MICRO_LEARNING);
3174
 
3175
            //print_r($companyService); exit;
3176
 
3177
            if(!$companyService) {
3178
                continue;
3179
            }
3180
 
3181
 
3182
            if(isset($companies[$companyService->company_id])) {
3183
                $company = $companies[$companyService->company_id];
3184
            } else {
3185
                $company = $companyMapper->fetchOne($companyService->company_id);
3186
                $companies[$companyService->company_id] = $company;
3187
            }
3188
 
3189
            $topics = $topicMapper->fetchAllActiveByCompanyId($company_id);
3190
            foreach($topics as $topic)
3191
            {
3192
                if(!in_array($topic->id, $topics_with_access)) {
3193
                    continue;
3194
                }
3195
 
3196
                $record_capsules = [];
3197
                $capsules = $capsuleMapper->fetchAllActiveByCompanyIdAndTopicId($topic->company_id, $topic->id);
3198
                foreach($capsules as $capsule)
3199
                {
3200
                    if(!in_array($capsule->id, $capsules_with_access)) {
3201
                        continue;
3202
                    }
3203
 
3204
 
3205
                    $record_slides = [];
3206
                    $slides = $slideMapper->fetchAllByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
3207
                    foreach($slides as $slide)
3208
                    {
3209
                        if($slide->type == CompanyMicrolearningSlide::TYPE_QUIZ) {
3210
                            if(!in_array($slide->quiz_id, $quizzes_with_access)) {
3211
                                array_push($quizzes_with_access, $slide->quiz_id);
3212
                            }
3213
 
3214
                            if(isset($quizzes[$slide->quiz_id])) {
3215
                                $quiz = $quizzes[$slide->quiz_id];
3216
 
3217
                            } else {
3218
                                $quiz = $quizMapper->fetchOne($slide->quiz_id);
3219
                                $quizzes[$slide->quiz_id] =  $quiz;
3220
                            }
3221
                        } else {
3222
                            $quiz = null;
3223
                        }
3224
 
3225
 
3226
 
3227
                        array_push($record_slides, [
3228
                            'uuid' => $slide->uuid,
3229
                            'quiz_uuid' => $quiz ? $quiz->uuid : '',
3230
                            'name' => $slide->name ? $slide->name : '',
3231
                            'description' => $slide->description ? $slide->description : '',
3232
                            'position' => $slide->order,
3233
                            'type' => $slide->type,
3234
                            'background' => $slide->background ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-slide', 'code' => $slide->uuid, 'filename' => $slide->background], ['force_canonical' => true]) : '',
3235
                            'file' => $slide->file ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-slide', 'code' => $slide->uuid, 'filename' => $slide->file], ['force_canonical' => true]) : '',
3236
                        ]);
3237
                    }
3238
 
3239
                    array_push($record_capsules, [
3240
                        'uuid' => $capsule->uuid,
3241
                        'name' => $capsule->name ? $capsule->name : '',
3242
                        'description' => $capsule->description ? $capsule->description : '',
3243
                        'image' => $capsule->image ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-capsule', 'code' => $capsule->uuid, 'filename' => $capsule->image ], ['force_canonical' => true])  : '',
3244
                        'position' => $capsule->order,
3245
                        'slides' => $record_slides,
3246
                    ]);
3247
                }
3248
 
3249
                array_push($data['topics'], [
3250
                    'uuid' => $topic->uuid,
3251
                    'name' => $topic->name ? $topic->name : '',
3252
                    'description' => $topic->description ? $topic->description : '',
3253
                    'image' => $topic->image ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-topic', 'code' => $topic->uuid, 'filename' => $topic->image ], ['force_canonical' => true]) : '',
3254
                    'position' => $topic->order,
3255
                    'company_uuid' => $company->uuid,
3256
                    'company_name' => $company->name,
3257
                    'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
3258
                    'capsules' => $record_capsules
3259
                ]);
3260
            }
3261
        }
3262
 
3263
 
3264
 
3265
        foreach($quizzes_with_access as $quiz_id)
3266
        {
3267
            if(isset($quizzes[$quiz_id])) {
3268
                $quiz = $quizzes[$quiz_id];
3269
            } else {
3270
                $quiz = $quizMapper->fetchOne($quiz_id);
3271
                array_push($quizzes, $quiz);
3272
            }
3273
 
3274
            if(isset($companies[$quiz->company_id])) {
3275
                $company = $companies[$quiz->company_id];
3276
            } else {
3277
                $company = $companyMapper->fetchOne($quiz->company_id);
3278
                $companies[$quiz->company_id] = $company;
3279
            }
3280
 
3281
 
3282
            $record_questions = [];
3283
            $questions = $questionMapper->fetchAllByQuizId($quiz->id);
3284
            foreach($questions as $question)
3285
            {
3286
                $record_answers = [];
3287
 
3288
                $answers = $answerMapper->fetchAllByQuizIdAndQuestionId($question->quiz_id, $question->id);
3289
                foreach($answers as $answer)
3290
                {
3291
                    array_push($record_answers, [
3292
                        'uuid' => $answer->uuid,
3293
                        'text' => trim($answer->text),
3294
                        'correct' => $answer->correct ? $answer->correct  : 0 ,
3295
                        'points' => intval($answer->points, 10),
3296
                    ]);
3297
                }
3298
 
3299
                array_push($record_questions, [
3300
                    'uuid' => $question->uuid,
3301
                    'text' => trim($question->text),
3302
                    'type' => $question->type,
3303
                    'maxlength' => $question->maxlength,
3304
                    'points' => $question->points,
3305
                    'answers' => $record_answers,
3306
                ]);
3307
            }
3308
 
3309
 
3310
            array_push($data['quizzes'], [
3311
                'uuid' => $quiz->uuid,
3312
                'name' => $quiz->name,
3313
                'text' => trim($quiz->text ? $quiz->text : ''),
3314
                'failed' => trim($quiz->failed ? $quiz->failed : ''),
3315
                'points' => $quiz->points,
3316
                'minimum_points_required' => $quiz->minimum_points_required,
3317
                'max_time' => $quiz->max_time ? $quiz->max_time : 5,
3318
                'company_uuid' => $company->uuid,
3319
                'company_name' => $company->name,
3320
                'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
3321
                'questions' => $record_questions,
3322
            ]);
3323
        }
3324
        return $data;
3325
    }
3326
 
3327
 
3328
    /**
3329
     *
3330
     * @param string $filename
3331
     * @param boolean $retbytes
3332
     * @return boolean|number
3333
     */
3334
    private function readfile_chunked($filename, $retbytes = true) {
3335
        $buffer = '';
3336
        $cnt =0;;
3337
        $handle = fopen($filename,'rb');
3338
        if ($handle === false) {
3339
            return false;
3340
        }
3341
        while (!feof($handle)) {
3342
            $buffer = fread($handle, self::CHUNK_SIZE);
3343
            echo $buffer;
3344
            ob_flush();
3345
            flush();
3346
            if ($retbytes) {
3347
                $cnt += strlen($buffer);
3348
            }
3349
        }
3350
        $status = fclose($handle);
3351
        if ($retbytes && $status) {
3352
            return $cnt; // return num. bytes delivered like readfile() does.
3353
        }
3354
        return $status;
3355
    }
3356
}