Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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