Proyectos de Subversion LeadersLinked - Services

Rev

| Ultima modificación | Ver Log |

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