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