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
    {
143
        $currentUser = $this->plugin('currentUserPlugin');
144
        if($currentUser->hasIdentity()) {
145
            $device_uuid = $currentUser->getDeviceId();
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
 
155
            $this->logger->info('Desconexión del mobile', ['user_id' => $currentUser->getUserId(), 'ip' => Functions::getUserIP()]);
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");
985
            error_log('url = ' . $_SERVER['REQUEST_URI']);
986
            error_log('query = ' . $_SERVER['QUERY_STRING']);
987
            error_log('$rawdata = ' . $rawdata );
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
 
1064
 
1065
 
1066
            if($encrypter == 'CryptoJsAes') {
1067
 
1068
 
1069
                $email = html_entity_decode($email);
1070
                $password = html_entity_decode($password);
1071
 
1072
 
1073
                ob_start();
1074
 
1075
                $email      = CryptoJsAes::decrypt($email, $device->aes);
1076
                $password   = CryptoJsAes::decrypt($password, $device->aes);
1077
 
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
 
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);
1093
 
1094
                $cryptor = new \RNCryptor\RNCryptor\Decryptor;
1095
                $email = $cryptor->decrypt($email, $device->aes);
1096
                $password = $cryptor->decrypt($password, $device->aes);
1097
 
1098
                error_log("Email Decrypted : " . $email . PHP_EOL);
1099
                error_log("Password Decrypted : " . $password . PHP_EOL);
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
 
218 efrain 1111
                error_log("AesEncryption");
215 efrain 1112
                error_log("Device UUID : " . $device->id);
1113
                error_log("AES : " . $device->aes);
1114
                error_log("Email Encrypted : " . $email);
1115
                error_log("Password Encrypted : " . $password);
1116
 
218 efrain 1117
 
222 efrain 1118
                $easyAES = new EasyAES($device->aes);
223 efrain 1119
                $email = $easyAES->decrypt($email);
1120
                $password = $easyAES->decrypt($password);
222 efrain 1121
 
218 efrain 1122
 
215 efrain 1123
                error_log("Email Decrypted : " . $email . PHP_EOL);
1124
                error_log("Password Decrypted : " . $password . PHP_EOL);
1125
 
1126
                if(!$email || !$password) {
1127
                    return new JsonModel([
1128
                        'success' => false,
216 efrain 1129
                        'data' => 'ERROR_WEBSERVICE_PASSWORD_ENCRYPTION_FAILED 3',
215 efrain 1130
                    ]);
1131
                }
1132
 
1133
 
1 efrain 1134
            } else if($encrypter == 'AesCipher') {
1135
 
1136
                error_log("AesCipher");
1137
                error_log("Device UUID : " . $device->id);
1138
                error_log("AES : " . $device->aes);
1139
                error_log("Email Encrypted : " . $email);
1140
                error_log("Password Encrypted : " . $password);
1141
 
1142
                $emailDecrypted = AesCipher::decrypt($device->aes,$email);
1143
                $passwordDecrypted = AesCipher::decrypt($device->aes,$password);
1144
                if($emailDecrypted->hasError() || $passwordDecrypted->hasError()) {
1145
                    return new JsonModel([
1146
                        'success' => false,
216 efrain 1147
                        'data' => 'ERROR_WEBSERVICE_PASSWORD_ENCRYPTION_FAILED 4',
1 efrain 1148
                    ]);
1149
                }
1150
 
1151
                $email = $emailDecrypted->getData();
1152
                $password = $passwordDecrypted->getData();
1153
 
1154
                error_log("Email Decrypted : " . $email . PHP_EOL);
1155
                error_log("Password Decrypted : " . $password . PHP_EOL);
1156
 
1157
            } else {
1158
                $email   = filter_var($email, FILTER_SANITIZE_EMAIL);
1159
            }
1160
 
1161
            $companyMapper = CompanyMapper::getInstance($this->adapter);
1162
            $company = $companyMapper->fetchOne($applicationVariant->company_id);
1163
 
1164
 
1165
            $authAdapter = new AuthAdapter($this->adapter);
1166
            $authAdapter->setData($email, $password, $company->network_id);
1167
 
1168
            $authService = new AuthenticationService();
1169
            $result = $authService->authenticate($authAdapter);
1170
 
1171
            $ip = Functions::getUserIP();
1172
            if($result->getCode() == AuthResult::SUCCESS) {
1173
 
1174
                $userMapper = UserMapper::getInstance($this->adapter);
1175
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $company->network_id);
1176
 
1177
 
1178
                $device->user_id    = $user->id;
1179
                $device->ip         = $ip;
1180
 
1181
                if ($application_id && $variant_id) {
1182
                    $device->application_id = $application_id;
1183
                    $device->variant_id = $variant_id;
1184
                }
1185
 
1186
                if($deviceMapper->update($device)) {
1187
 
1188
 
1189
 
1190
                    $deviceHistoryMapper = DeviceHistoryMapper::getInstance($this->adapter);
1191
                    $deviceHistory = $deviceHistoryMapper->fetchOneByDeviceIdAndUserIdAndIp($device->id, $user->id, $ip);
1192
                    if($deviceHistory) {
1193
                        $deviceHistory->ip = $ip;
1194
                        $deviceHistoryMapper->update($deviceHistory);
1195
                    } else {
1196
                        $deviceHistory = new DeviceHistory();
1197
                        $deviceHistory->device_id = $device->id;
1198
                        $deviceHistory->user_id = $user->id;
1199
                        $deviceHistory->ip = $ip;
1200
                        $deviceHistoryMapper->insert($deviceHistory);
1201
                    }
1202
 
1203
                    $pushMapper = PushMapper::getInstance($this->adapter);
1204
 
1205
                    $userDevices =  $deviceMapper->fetchAllByUserIdAndApplicationId($user->id, $device->application_id);
1206
                    foreach($userDevices as $userDevice)
1207
                    {
1208
 
1209
                        if($userDevice->id != $device->id ) {
1210
                            $deviceMapper->releaseUserFormDevice($userDevice);
1211
 
1212
 
1213
                            if($userDevice->token) {
1214
 
1215
                                $key = $application->key;
1216
                                if ($device->variant_id) {
1217
                                    $applicationVariant = $applicationVariantMapper->fetchOneByApplicationIdAndVariantId($application->id, $variant_id);
1218
                                    if($applicationVariant) {
1219
                                        $key = $applicationVariant->key;
1220
 
1221
                                    } else {
1222
                                        $applicationVariant = $applicationVariantMapper->fetchOneByApplicationIdAndDefault($application->id);
1223
                                        if($applicationVariant) {
1224
                                            $key = $applicationVariant->key;
1225
                                        }
1226
                                    }
1227
                                }
1228
 
1229
 
1230
                                $push = new Push();
1231
                                $push->status = Push::STATUS_PENDING;
1232
                                $push->data = json_encode([
1233
                                    'server' => [
1234
                                        'key' =>  $key,
1235
                                     ],
1236
                                     'push' => [
1237
                                        'registration_ids'   => [
1238
                                            $userDevice->token,
1239
                                         ],
1240
                                         'notification' => [
1241
                                             'body' =>  'Se registro un inicio de sesión en otro dispositivo',
1242
                                             'title' => 'Nuevo inicio de sesión',
1243
                                             'vibrate' => 1,
1244
                                             'sound' =>  1
1245
                                         ],
1246
                                        'data' => [
1247
                                            'command' => 'signout'
1248
                                        ]
1249
                                     ]
1250
                                 ]);
1251
 
1252
                                $pushMapper->insert($push);
1253
 
1254
                            }
1255
                        }
1256
                    }
1257
 
1258
 
1259
                    $companyUsers = [];
1260
                    $companyMicrolearningCapsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
1261
                    $capsules = $companyMicrolearningCapsuleUserMapper->fetchAllActiveByUserId($user->id);
1262
                    foreach($capsules as $capsule)
1263
                    {
1264
 
1265
 
1266
 
1267
                        if(empty($companyUsers[$capsule->company_id])) {
1268
                            $companyUsers[$capsule->company_id] = $capsule->updated_on;
1269
                        } else {
1270
 
1271
                            if($capsule->updated_on > $companyUsers[$capsule->company_id]) {
1272
                                $companyUsers[$capsule->company_id] = $capsule->updated_on;
1273
                            }
1274
 
1275
                        }
1276
 
1277
                    }
1278
 
1279
                    $companyMicrolearningUserMapper = CompanyMicrolearningUserMapper::getInstance($this->adapter);
1280
 
1281
                    $maxDateChanges = $companyMicrolearningUserMapper->fetchMaxDateChanges($user->id);
1282
                    if(!$maxDateChanges) {
1283
 
1284
 
1285
                        $maxDateChanges = '';
1286
                        foreach($companyUsers as $company_id => $update_on)
1287
                        {
1288
 
1289
                            $maxDateChanges = $maxDateChanges < $update_on ? $update_on : $maxDateChanges;
1290
 
1291
                            $companyMicrolearningUser = new CompanyMicrolearningUser();
1292
                            $companyMicrolearningUser->company_id = $company_id;
1293
                            $companyMicrolearningUser->user_id = $user->id;
1294
                            $companyMicrolearningUser->added_on = $update_on;
1295
                            $companyMicrolearningUser->updated_on = $update_on;
1296
 
1297
                            $companyMicrolearningUserMapper->insert($companyMicrolearningUser);
1298
                        }
1299
 
1300
 
1301
                    }
1302
 
1303
 
1304
 
1305
                   $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $maxDateChanges);
1306
                   if($dt) {
1307
                       $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1308
                       $maxDateChanges = $dt->format($serviceDatetimeFormat);
1309
                   } else {
1310
                       $maxDateChanges = '';
1311
                   }
1312
 
1313
 
1314
                    $data = [
1315
                        'success'   => true,
1316
                        'data'      =>[
1317
                            'user' => [
1318
                                'uuid' => $user->uuid,
1319
                                'first_name' => $user->first_name,
1320
                                'last_name' => $user->last_name,
1321
                                'email' => $user->email,
1322
                                'image' => $this->url()->fromRoute('services/storage',['type' => 'user', 'code' => $user->uuid, 'filename' => $user->image], ['force_canonical' => true]),
1323
 
1324
                             ],
1325
                            'max_date_changes' => $maxDateChanges,
1326
                            'device' => [
1327
                                'aes' => $device->aes,
1328
                                'password' => $device->password
1329
                            ]
1330
 
1331
                        ]
1332
                    ];
1333
 
1334
                    if($application->id == Application::TWOGETSKILLS) {
1335
                        $dataSync = $this->getSyncData($user);
1336
 
1337
                        $data['data']['topics'] = $dataSync['topics'];
1338
                        $data['data']['quizzes'] = $dataSync['quizzes'];
1339
                        $data['data']['userlog'] = $dataSync['userlog'];
1340
                        $data['data']['progress'] = $dataSync['progress'];
1341
                        $data['data']['extended'] = $dataSync['extended'];
1342
                    }
1343
 
1344
 
1345
 
1346
                    return new JsonModel($data);
1347
 
1348
 
1349
 
1350
                } else {
1351
                    return new JsonModel([
1352
                        'success' => false,
1353
                        'data' => 'ERROR_THERE_WAS_AN_ERROR',
1354
                    ]);
1355
                }
1356
 
1357
 
1358
            } else {
1359
                $message = $result->getMessages()[0];
1360
                if(!in_array($message, ['ERROR_USER_NOT_FOUND', 'ERROR_USER_PROVIDER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
1361
                    'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
1362
                    'ERROR_ENTERED_PASS_INCORRECT_1', 'ERROR_USER_REQUEST_ACCESS_IS_PENDING', 'ERROR_USER_REQUEST_ACCESS_IS_REJECTED'  ])) {
1363
                }
1364
 
1365
                switch($message)
1366
                {
1367
                    case 'ERROR_USER_NOT_FOUND' :
1368
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1369
                        break;
1370
 
1371
                    case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED' :
1372
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1373
                        break;
1374
 
1375
                    case 'ERROR_USER_IS_BLOCKED' :
1376
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1377
                        break;
1378
 
1379
                    case 'ERROR_USER_IS_INACTIVE' :
1380
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1381
                        break;
1382
 
1383
 
1384
                    case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1385
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1386
                        break;
1387
 
1388
 
1389
                    case 'ERROR_ENTERED_PASS_INCORRECT_2' :
1390
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1391
                        break;
1392
 
1393
 
1394
                    case 'ERROR_ENTERED_PASS_INCORRECT_1' :
1395
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1396
                        break;
1397
 
1398
 
1399
                    case 'ERROR_USER_REQUEST_ACCESS_IS_PENDING' :
1400
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Falta verificar que pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
1401
                        break;
1402
 
1403
                    case  'ERROR_USER_REQUEST_ACCESS_IS_REJECTED' :
1404
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Rechazado por no pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
1405
                        break;
1406
 
1407
 
1408
                    default :
1409
                        $message = 'ERROR_UNKNOWN';
1410
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1411
                        break;
1412
 
1413
 
1414
                }
1415
 
1416
 
1417
                return new JsonModel([
1418
                    'success'   => false,
1419
                    'data'   => $message
1420
                ]);
1421
            }
1422
 
1423
        }
1424
 
1425
        return new JsonModel([
1426
            'success' => false,
1427
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1428
        ]);
1429
 
1430
    }
1431
 
1432
 
1433
 
1434
 
1435
    public function storageAction()
1436
    {
1437
 
1438
        // Get the file name from GET variable.
1439
        $code       = $this->params()->fromRoute('code', '');
1440
        $fileName   = $this->params()->fromRoute('filename', '');
1441
        $type       = $this->params()->fromRoute('type', 'user');
1442
 
1443
 
1444
        $no_image = $this->config['leaderslinked.images_default.no_image'];
1445
        $path = '';
1446
        switch($type)
1447
        {
1448
            case 'user' :
1449
                $no_image = $this->config['leaderslinked.images_default.user_image'];
1450
                $path = $this->config['leaderslinked.fullpath.user'];
1451
                break;
1452
 
1453
 
1454
            case 'user-profile' :
1455
                $no_image = $this->config['leaderslinked.images_default.user_profile'];
1456
                $path = $this->config['leaderslinked.fullpath.user'];
1457
                break;
1458
 
1459
            case 'user-cover' :
1460
                $no_image = $this->config['leaderslinked.images_default.user_cover'];
1461
                $path = $this->config['leaderslinked.fullpath.user'];
1462
                break;
1463
 
1464
            case 'company' :
1465
                $no_image = $this->config['leaderslinked.images_default.company_profile'];
1466
                $path = $this->config['leaderslinked.fullpath.company'];
1467
                break;
1468
 
1469
            case 'company-cover' :
1470
                $no_image = $this->config['leaderslinked.images_default.company_cover'];
1471
                $path = $this->config['leaderslinked.fullpath.company'];
1472
                break;
1473
 
1474
            case 'group' :
1475
                $no_image = $this->config['leaderslinked.images_default.group_profile'];
1476
                $path = $this->config['leaderslinked.fullpath.group'];
1477
                break;
1478
 
1479
            case 'group-cover' :
1480
                $no_image = $this->config['leaderslinked.images_default.group_cover'];
1481
                $path = $this->config['leaderslinked.fullpath.group'];
1482
                break;
1483
 
1484
            case 'job' :
1485
                $path = $this->config['leaderslinked.fullpath.job'];
1486
                break;
1487
 
1488
            case 'chat' :
1489
                $path = $this->config['leaderslinked.fullpath.chat'];
1490
                break;
1491
 
1492
            case 'feed' :
1493
                $path = $this->config['leaderslinked.fullpath.feed'];
1494
                break;
1495
 
1496
            case 'post' :
1497
                $path = $this->config['leaderslinked.fullpath.post'];
1498
                break;
1499
 
1500
            case 'microlearning-topic' :
1501
                $path = $this->config['leaderslinked.fullpath.microlearning_topic'];
1502
                break;
1503
 
1504
            case 'microlearning-capsule' :
1505
                $path = $this->config['leaderslinked.fullpath.microlearning_capsule'];
1506
                break;
1507
 
1508
            case 'microlearning-slide' :
1509
                $path = $this->config['leaderslinked.fullpath.microlearning_slide'];
1510
                break;
1511
 
1512
            default :
1513
                $path = $this->config['leaderslinked.fullpath.image'];
1514
                break;
1515
 
1516
        }
1517
        if($code && $fileName) {
1518
            $request_fullpath = $path . $code . DIRECTORY_SEPARATOR . $fileName;
1519
        } else {
1520
            $request_fullpath = $no_image;
1521
        }
1522
 
1523
        if(empty($fileName)) {
1524
            $extensions     = explode('.',$request_fullpath);
1525
            $extension      = strtolower(trim($extensions[count($extensions)-1]));
1526
            if ($extension=='jpg' || $extension=='jpeg' || $extension=='gif' || $extension == 'png') {
1527
                $request_fullpath =  $no_image;
1528
            }
1529
        }
1530
 
1531
 
1532
        if(file_exists($request_fullpath)) {
1533
 
1534
            // Try to open file
1535
            if (!is_readable($request_fullpath)) {
1536
                return $this->getResponse()->setStatusCode(500);
1537
            }
1538
 
1539
            // Get file size in bytes.
1540
            $fileSize = filesize($request_fullpath);
1541
 
1542
            // Get MIME type of the file.
1543
            $mimeType = mime_content_type($request_fullpath);
1544
            if($mimeType===false) {
1545
                $mimeType = 'application/octet-stream';
1546
            }
1547
 
1548
            $request_fullpath = trim($request_fullpath);
1549
            $length = strlen($request_fullpath);
1550
            if(substr($request_fullpath, $length - 1) == '/') {
1551
                $request_fullpath = substr($request_fullpath, 0, $length - 1);
1552
            }
1553
 
1554
 
1555
            $filename = basename($request_fullpath);
1556
 
1557
            header('Content-type: ' . $mimeType);
1558
            readfile($request_fullpath);
1559
 
1560
 
1561
            exit;
1562
            //header("X-Sendfile: $request_fullpath");
1563
            //header("Content-type: application/octet-stream");
1564
            //header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
1565
 
1566
 
1567
            /*
1568
 
1569
 
1570
            if ($fd = fopen ($request_fullpath, "r")) {
1571
 
1572
                $fsize = filesize($request_fullpath);
1573
 
1574
                header("Content-type: $mimeType");
1575
                header("Accept-Ranges: bytes");
1576
 
1577
                //header("Content-Disposition: attachment; filename=\"$filename\"");
1578
 
1579
                header("Content-length: $fsize");
1580
                header("Cache-control: private");
1581
 
1582
                while(!feof($fd)) {
1583
                    $buffer = fread($fd, 2048);
1584
                    echo $buffer;
1585
                }
1586
            }
1587
 
1588
            fclose ($fd);
1589
            exit;*/
1590
 
1591
 
1592
            /*
1593
             $fileContent = file_get_contents($request_fullpath);
1594
            $response = $this->getResponse();
1595
            $headers = $response->getHeaders();
1596
            $headers->addHeaderLine('Accept-Ranges: bytes');
1597
            $headers->addHeaderLine('Content-type: ' . $mimeType);
1598
            $headers->addHeaderLine('Content-length: ' . $fileSize);
1599
 
1600
            /*
1601
            Date: Tue, 13 Jul 2021 03:11:42 GMT
1602
            Server: Apache/2.4.41 (Ubuntu)
1603
            Last-Modified: Mon, 28 Jun 2021 16:43:04 GMT
1604
            ETag: "54e4-5c5d62eed581e"
1605
            Accept-Ranges: bytes
1606
            Content-Length: 21732
1607
            Cache-Control: max-age=1
1608
            Expires: Tue, 13 Jul 2021 03:11:43 GMT
1609
            Keep-Alive: timeout=5, max=100
1610
            Connection: Keep-Alive
1611
            Content-Type: audio/mpeg
1612
            */
1613
 
1614
            /*
1615
            if($fileContent!==false) {
1616
                error_log($_SERVER['REQUEST_URI']);
1617
                error_log($request_fullpath);
1618
                return $response->setContent($fileContent);
1619
 
1620
                header('Content-Type: '.$mimeType );
1621
                readfile_chunked($filename);
1622
                exit;
1623
 
1624
            } else {
1625
                error_log('500');
1626
                $this->getResponse()->setStatusCode(500);
1627
                return;
1628
            }*/
1629
        } else {
1630
            error_log('404');
1631
            return $this->getResponse()->setStatusCode(404);
1632
        }
1633
 
1634
        return $this->getResponse();
1635
    }
1636
 
1637
 
1638
    public function syncAction()
1639
    {
1640
        $request = $this->getRequest();
1641
 
1642
        if($request->isPost()) {
1643
 
1644
 
1645
 
1646
 
1647
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1648
 
1649
            $device_uuid    = Functions::sanitizeFilterString($this->params()->fromPost('device_uuid', ''));
1650
            $sync_id        = filter_var($this->params()->fromPost('sync_id', ''), FILTER_SANITIZE_NUMBER_INT);
1651
            $data           = $this->params()->fromPost('data', '');
1652
            $application_id = filter_var($this->params()->fromPost('application_id', 0), FILTER_SANITIZE_NUMBER_INT);
1653
            $variant_id     = filter_var($this->params()->fromPost('variant_id', 0), FILTER_SANITIZE_NUMBER_INT);
1654
 
1655
 
1656
            //error_log('device_uuid = ' . $device_uuid);
1657
            //error_log('sync_id = ' . $sync_id);
1658
            //error_log(print_r($data, true));
1659
 
1660
 
1661
            //$rawdata = file_get_contents("php://input");
1662
           // error_log('$rawdata = ' . $rawdata );
1663
 
1664
            $ok = $device_uuid && strlen($device_uuid) == 36 && $data && $sync_id;
1665
 
1666
            if(!$ok) {
1667
                return new JsonModel([
1668
                    'success' => false,
1669
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID',
1670
                ]);
1671
            }
1672
 
1673
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
1674
            $device = $deviceMapper->fetchOne($device_uuid);
1675
 
1676
 
1677
            if(!$device) {
1678
                return new JsonModel([
1679
                    'success' => false,
1680
                    'data' => 'ERROR_DEVICE_NOT_FOUND'
1681
                ]);
1682
            } else {
1683
 
1684
                if ($application_id && $variant_id) {
1685
                    $applicationMapper = ApplicationMapper::getInstance($this->adapter);
1686
                    $application = $applicationMapper->fetchOne($application_id);
1687
                    if(!$application) {
1688
                        return new JsonModel([
1689
                            'success' => false,
1690
                            'data' => 'ERROR_APPLICATION_NOT_FOUND',
1691
                        ]);
1692
                    }
1693
 
1694
                    if($application->status == Application::STATUS_INACTIVE) {
1695
                        return new JsonModel([
1696
                            'success' => false,
1697
                            'data' => 'ERROR_APPLICATION_IS_INACTIVE',
1698
                        ]);
1699
                    }
1700
 
1701
                    $applicationVariantMapper = ApplicationVariantMapper::getInstance($this->adapter);
1702
                    if ($variant_id) {
1703
                        $applicationVariant = $applicationVariantMapper->fetchOneByApplicationIdAndVariantId($application->id, $variant_id);
1704
                        if(!$applicationVariant) {
1705
 
1706
                            return new JsonModel([
1707
                                'success' => false,
1708
                                'data' => 'ERROR_APPLICATION_VARIANT_IS_INVALID',
1709
                            ]);
1710
                        }
1711
                    } else {
1712
                        $applicationVariant = $applicationVariantMapper->fetchOneByApplicationIdAndDefault($application->id);
1713
                    }
1714
 
1715
 
1716
                    $device->application_id = $application->id;
1717
                    $device->variant_id = $applicationVariant->variant_id;
1718
                }
1719
 
1720
                $device->ip = Functions::getUserIP();
1721
                $deviceMapper->update($device);
1722
            }
1723
 
1724
 
1725
 
1726
 
1727
 
1728
            $data = json_decode($data, true);
1729
            $sync_type      = isset($data['sync_type']) ? Functions::sanitizeFilterString($data['sync_type']) : '';
1730
            $user_uuid      = isset($data['user_uuid']) ? Functions::sanitizeFilterString($data['user_uuid']) : '';
1731
            $company_uuid   = isset($data['company_uuid']) ? Functions::sanitizeFilterString($data['company_uuid']) :  '';
1732
 
1733
 
1734
            $syncLog = new SyncLog();
1735
            $syncLog->data = json_encode($data);
1736
            $syncLog->type = $sync_type;
1737
            $syncLog->device_uuid = $device->id;
1738
            $syncLog->ip = Functions::getUserIP();
1739
 
1740
 
1741
 
1742
 
1743
            $syncLogMapper = SyncLogMapper::getInstance($this->adapter);
1744
            $syncLogMapper->insert($syncLog);
1745
 
167 efrain 1746
 
1 efrain 1747
            if($user_uuid && $device->application_id = Application::TWOGETSKILLS  && $company_uuid && in_array($sync_type, ['microlearning-progress', 'microlearning-userlog', 'microlearning-quiz'])) {
1748
                $userMapper = UserMapper::getInstance($this->adapter);
1749
                $user = $userMapper->fetchOneByUuid($user_uuid);
1750
 
1751
 
1752
 
1753
                if(!$user) {
1754
                    return new JsonModel([
1755
                        'success' => false,
1756
                        'data' => [
1757
                            'sync_id' => $sync_id,
1758
                            'message' => 'ERROR_USER_NOT_FOUND',
1759
                            'fatal' => true
1760
                        ]
1761
                    ]);
1762
                }
1763
 
1764
 
1765
                if($user->status != User::STATUS_ACTIVE) {
1766
                    return new JsonModel([
1767
                        'success' => false,
1768
                        'data' => [
1769
                            'sync_id' => $sync_id,
1770
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
1771
                            'fatal' => true
1772
                        ]
1773
                    ]);
1774
                }
1775
 
1776
                $companyMapper = CompanyMapper::getInstance($this->adapter);
1777
                $company = $companyMapper->fetchOneByUuid($company_uuid);
1778
                if(!$company) {
1779
                    return new JsonModel([
1780
                        'success' => false,
1781
                        'data' => [
1782
                            'sync_id' => $sync_id,
1783
                            'message' => 'ERROR_COMPANY_NOT_FOUND',
1784
                            'fatal' => true
1785
                        ]
1786
                    ]);
1787
                }
1788
 
1789
                if($company->status != Company::STATUS_ACTIVE) {
1790
                    return new JsonModel([
1791
                        'success' => false,
1792
                        'data' => [
1793
                            'sync_id' => $sync_id,
1794
                            'message' => 'ERROR_COMPANY_IS_NOT_FOUND',
1795
                            'fatal' => true
1796
                        ]
1797
                    ]);
1798
                }
1799
 
1800
 
1801
 
1802
 
1803
 
1804
                $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
1805
                $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($company->id, Service::MICRO_LEARNING);
1806
                if(!$companyService) {
1807
                    return new JsonModel([
1808
                        'success' => false,
1809
                        'data' => [
1810
                            'sync_id' => $sync_id,
1811
                            'message' => 'ERROR_COMPANY_SERVICE_NOT_FOUND',
1812
                            'fatal' => true
1813
                        ]
1814
                    ]);
1815
                }
1816
 
1817
                $serviceActive = true;
1818
                $now = date('Y-m-d H:i:s');
1819
                if($companyService->status == CompanyService::ACTIVE) {
1820
 
1821
                    if($now < $companyService->paid_from || $now > $companyService->paid_to) {
1822
                        $serviceActive = false;
1823
                    }
1824
 
1825
                } else {
1826
                    $serviceActive = false;
1827
                }
1828
 
1829
                if( !$serviceActive) {
1830
                    return new JsonModel([
1831
                        'success' => false,
1832
                        'data' => [
1833
                            'sync_id' => $sync_id,
1834
                            'message' => 'ERROR_COMPANY_SERVICE_IS_NOT_ACTIVE',
1835
                            'fatal' => true
1836
                        ]
1837
                    ]);
1838
                }
1839
 
1840
                $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
1841
                $topic_uuid = isset($data['topic_uuid']) ? Functions::sanitizeFilterString($data['topic_uuid']) :  '';
1842
                if($topic_uuid) {
1843
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
1844
 
1845
                    if(!$topic) {
1846
                        return new JsonModel([
1847
                            'success' => false,
1848
                            'data' => [
1849
                                'sync_id' => $sync_id,
1850
                                'message' => 'ERROR_TOPIC_NOT_FOUND',
1851
                            ]
1852
                        ]);
1853
                    }
1854
 
1855
                    if($topic->company_id != $company->id) {
1856
                        return new JsonModel([
1857
                            'success' => false,
1858
                            'data' => [
1859
                                'sync_id' => $sync_id,
1860
                                'message' => 'ERROR_INVALID_PARAMETERS_TOPIC_COMPANY',
1861
                            ]
1862
                        ]);
1863
                    }
1864
 
1865
                } else {
1866
                    $topic = null;
1867
                }
1868
 
1869
                $capsule_uuid     = isset($data['capsule_uuid']) ? Functions::sanitizeFilterString($data['capsule_uuid']) :  '';
1870
                $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
1871
                if($capsule_uuid) {
1872
 
1873
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
1874
                    if(!$capsule) {
1875
                        return new JsonModel([
1876
                            'success' => false,
1877
                            'data' => [
1878
                                'sync_id' => $sync_id,
1879
                                'message' => 'ERROR_CAPSULE_NOT_FOUND',
1880
                            ]
1881
                        ]);
1882
                    }
1883
 
1884
                    if(!$topic || $capsule->topic_id != $topic->id) {
1885
                        return new JsonModel([
1886
                            'success' => false,
1887
                            'data' => [
1888
                                'sync_id' => $sync_id,
1889
                                'message' => 'ERROR_INVALID_PARAMETERS_CAPSULE_TOPIC',
1890
                            ]
1891
                        ]);
1892
                    }
1893
                } else {
1894
                    $capsule = null;
1895
                }
1896
 
1897
                if($capsule) {
1898
 
1899
                    $capsuleActive = true;
1900
                    $capsuleMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
1901
                    $capsuleUser = $capsuleMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
1902
 
1903
 
1904
                    $now = date('Y-m-d H:i:s');
1905
                    if($capsuleUser && in_array($capsuleUser->access, [CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED,CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD ])) {
1906
 
1907
 
1908
                        if($capsuleUser->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
1909
 
1910
                            if($now < $capsuleUser->paid_from || $now > $capsuleUser->paid_to) {
1911
                                $capsuleActive = false;;
1912
                            }
1913
                        }
1914
 
1915
                    } else {
1916
                        $capsuleActive = false;
1917
                    }
1918
 
1919
                    if(!$capsuleActive) {
1920
                        return new JsonModel([
1921
                            'success' => false,
1922
                            'data' => [
1923
                                'sync_id' => $sync_id,
1924
                                'message' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
1925
                            ]
1926
                        ]);
1927
                    }
1928
                }
1929
 
1930
 
1931
 
1932
                $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
1933
                $slide_uuid      = isset($data['slide_uuid']) ? Functions::sanitizeFilterString($data['slide_uuid']) :  '';
1934
 
1935
 
1936
                if($slide_uuid) {
1937
 
1938
                    $slide = $slideMapper->fetchOneByUuid($slide_uuid);
1939
                    if(!$slide) {
1940
                        return new JsonModel([
1941
                            'success' => false,
1942
                            'data' => [
1943
                                'sync_id' => $sync_id,
1944
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
1945
                            ]
1946
                        ]);
1947
                    }
1948
 
1949
                    if(!$capsule || $slide->capsule_id != $capsule->id) {
1950
                        return new JsonModel([
1951
                            'success' => false,
1952
                            'data' => [
1953
                                'sync_id' => $sync_id,
1954
                                'message' => 'ERROR_INVALID_PARAMETERS_SLIDE_CAPSULE',
1955
                            ]
1956
                        ]);
1957
                    }
1958
                } else {
1959
                    $slide = null;
1960
                }
1961
 
1962
 
1963
 
1964
 
1965
                if($sync_type == 'microlearning-quiz') {
1966
                    $ok = true;
1967
 
1968
                    $quiz_uuid = isset($data['quiz_uuid']) ? $data['quiz_uuid'] : '';
1969
                    $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
1970
 
1971
                    $quiz = $quizMapper->fetchOneByUuid($quiz_uuid);
1972
                    if(!$quiz) {
1973
                        return new JsonModel([
1974
                            'success' => false,
1975
                            'data' => [
1976
                                'sync_id' => $sync_id,
1977
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
1978
                            ]
1979
                        ]);
1980
                    }
1981
 
1982
                    if(!$capsule || $slide->capsule_id != $capsule->id) {
1983
                        return new JsonModel([
1984
                            'success' => false,
1985
                            'data' => [
1986
                                'sync_id' => $sync_id,
1987
                                'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_SLIDE',
1988
                            ]
1989
                        ]);
1990
                    }
1991
 
1992
                    $added_on   = isset($data['added_on'])      ? Functions::sanitizeFilterString($data['added_on'])  :  '';
1993
 
1994
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1995
                    if(!$dt) {
1996
                        $ok = false;
1997
                    } else {
1998
                        $added_on = $dt->format('Y-m-d H:i:s');
1999
                    }
2000
 
2001
 
2002
                    if(isset($data['points'])) {
2003
                        $points = intval($data['points'], 10);
2004
                    } else {
2005
                        $ok = false;
2006
                    }
2007
 
2008
 
2009
                    if(isset($data['pass'])) {
2010
                        $status = $data['pass'] == 'yes' ? CompanyMicrolearningUserQuiz::STATUS_PASS : CompanyMicrolearningUserQuiz::STATUS_FAIL;
2011
                    } else {
2012
                        $ok = false;
2013
                    }
2014
 
2015
 
2016
                    if(!$ok) {
2017
                        return new JsonModel([
2018
                            'success' => false,
2019
                            'data' => [
2020
                                'sync_id' => $sync_id,
2021
                                'message' => 'ERROR_INVALID_PARAMETERS 1',
2022
                            ]
2023
                        ]);
2024
                    }
2025
 
2026
 
2027
                    $array_response = [];
2028
                    $response = isset($data['response']) ? intval($data['response'], 10) : 0;
2029
                    for($i = 0; $i < $response; $i++)
2030
                    {
2031
                        $question_uuid = isset($data["response_{$i}_question_uuid"]) ? $data["response_{$i}_question_uuid"] : '';
2032
                        $answer_uuid = isset($data["response_{$i}_answer_uuid"]) ? $data["response_{$i}_answer_uuid"] : '';
2033
                        $value = isset($data["response_{$i}_value"]) ?  intval($data["response_{$i}_value"], 10) : 0;
2034
                        $points = isset($data["response_{$i}_points"]) ?  intval($data["response_{$i}_points"], 10) : 0;
2035
 
2036
                        if($question_uuid && $answer_uuid)
2037
                        {
2038
                            array_push($array_response, [
2039
                                'question_uuid' => $question_uuid,
2040
                                'answer_uuid' => $answer_uuid,
2041
                                'value' => $value,
2042
                                'points' => $points
2043
 
2044
                            ]);
2045
                        }
2046
 
2047
 
2048
                    }
2049
 
2050
 
2051
                    $userQuiz = new CompanyMicrolearningUserQuiz();
2052
                    $userQuiz->company_id = $company->id;
2053
                    $userQuiz->topic_id = $topic->id;
2054
                    $userQuiz->capsule_id = $capsule->id;
2055
                    $userQuiz->slide_id = $slide->id;
2056
                    $userQuiz->quiz_id = $quiz->id;
2057
                    $userQuiz->user_id = $user->id;
2058
                    $userQuiz->added_on = $added_on;
2059
                    $userQuiz->points = $points;
2060
                    $userQuiz->status = $status;
2061
                    $userQuiz->response = json_encode($array_response);
2062
 
2063
                    $userQuizMapper = CompanyMicrolearningUserQuizMapper::getInstance($this->adapter);
2064
 
2065
                    if($userQuizMapper->insert($userQuiz)) {
2066
                        return new JsonModel([
2067
                            'success' => true,
2068
                            'data' => [
2069
                                'sync_id' => $sync_id
2070
                            ]
2071
                        ]);
2072
                    } else {
2073
                        return new JsonModel([
2074
                            'success' => false,
2075
                            'data' => [
2076
                                'sync_id' => $sync_id,
2077
                                'message' => $userQuizMapper->getError()
2078
                            ]
2079
                        ]);
2080
                    }
2081
 
2082
                }
2083
 
2084
 
2085
                if($sync_type == 'microlearning-progress') {
2086
                    $ok = true;
2087
 
2088
 
2089
                    $type = isset($data['type']) ? $data['type'] : '';
2090
                    switch($type)
2091
                    {
2092
                        case CompanyMicrolearningUserProgress::TYPE_TOPIC :
2093
                            if(!$topic) {
2094
                                $ok = false;
2095
                            }
2096
                            break;
2097
 
2098
                        case CompanyMicrolearningUserProgress::TYPE_CAPSULE :
2099
                            if(!$topic || !$capsule) {
2100
                                $ok = false;
2101
                            }
2102
                            break;
2103
 
2104
                        case CompanyMicrolearningUserProgress::TYPE_SLIDE :
2105
                            if(!$topic || !$capsule || !$slide) {
2106
                                $ok = false;
2107
                            }
2108
                            break;
2109
 
2110
                        default :
2111
                            $ok = false;
2112
                            break;
2113
 
2114
                    }
2115
 
2116
 
2117
                    $added_on   = isset($data['added_on'])      ? Functions::sanitizeFilterString($data['added_on'])  :  '';
2118
                    $updated_on = isset($data['updated_on'])    ? Functions::sanitizeFilterString($data['updated_on']) :  '';
2119
 
2120
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2121
                    if(!$dt) {
2122
                        $ok = false;
2123
                    } else {
2124
                        $added_on = $dt->format('Y-m-d H:i:s');
2125
                    }
2126
 
2127
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $updated_on );
2128
                    if(!$dt) {
2129
                        $ok = false;
2130
                    } else {
2131
                        $updated_on = $dt->format('Y-m-d H:i:s');
2132
                    }
2133
 
2134
                    if(!$ok) {
2135
                        return new JsonModel([
2136
                            'success' => false,
2137
                            'data' => [
2138
                                'sync_id' => $sync_id,
2139
                                'message' => 'ERROR_INVALID_PARAMETERS 2',
2140
                            ]
2141
                        ]);
2142
                    }
2143
 
2144
                           //$progress                   = isset($data['progress'])                  ? floatval($data['progress']) :  0;
2145
                    //$total_slides               = isset($data['total_slides'])              ? intval($data['total_slides'], 10) :  0;
2146
                    //$view_slides                = isset($data['view_slides'])               ? intval($data['view_slides'], 10) :  0;
2147
                    $returning                  = isset($data['returning'])                 ? intval($data['returning'], 10) :  0;
2148
                    $returning_after_completed  = isset($data['returning_after_completed']) ? intval($data['returning_after_completed'], 10) :  0;
2149
                    $completed                  = isset($data['completed'])                 ? intval($data['completed'], 10) :  0;
2150
 
2151
                    $progressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
2152
                    $recordProgress = null;
2153
                    switch($type) {
2154
                        case CompanyMicrolearningUserProgress::TYPE_TOPIC  :
2155
                            $recordProgress = $progressMapper->fetchOneByUserIdAndTopicId($user->id, $topic->id);
2156
 
2157
                            break;
2158
 
2159
                        case CompanyMicrolearningUserProgress::TYPE_CAPSULE  :
2160
                            $recordProgress = $progressMapper->fetchOneByUseridAndCapsuleId($user->id, $capsule->id);
2161
                            break;
2162
 
2163
                        case CompanyMicrolearningUserProgress::TYPE_SLIDE  :
2164
                            $recordProgress = $progressMapper->fetchOneByUserIdAndSlideId($user->id, $slide->id);
2165
                            break;
2166
 
2167
                        default :
2168
                            $recordProgress= null;
2169
                    }
2170
 
2171
 
2172
                    if(!$recordProgress) {
2173
                        $recordProgress = new CompanyMicrolearningUserProgress();
2174
 
2175
                        $recordProgress->user_id    = $user->id;
2176
                        $recordProgress->type       = $type;
2177
                        $recordProgress->company_id = $topic->company_id;
2178
                        $recordProgress->topic_id   = $topic->id;
2179
                        $recordProgress->capsule_id = $capsule ? $capsule->id : null;
2180
                        $recordProgress->slide_id   = $slide ? $slide->id : null;
2181
                        $recordProgress->added_on   = $added_on;
2182
                    }
2183
                    $recordProgress->returning                  = $returning;
2184
                    $recordProgress->returning_after_completed  = $returning_after_completed;
2185
                    $recordProgress->completed                  = $completed;
2186
 
2187
                    if($type == CompanyMicrolearningUserProgress::TYPE_TOPIC ) {
2188
 
2189
                        $capsule_ids = [];
2190
                        $companyMicrolearningCapsuleUser = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
2191
                        $records =  $companyMicrolearningCapsuleUser->fetchAllActiveByUserId($user->id);
2192
                        foreach($records as $record)
2193
                        {
2194
                            if($now >= $record->paid_from || $now <= $capsuleUser->paid_to) {
2195
                                if(!in_array($record->capsule_id, $capsule_ids)) {
2196
                                    array_push($capsule_ids, $record->capsule_id);
2197
                                }
2198
                            }
2199
                        }
2200
 
2201
                        $view_slides    = 0;
2202
                        $total_slides   = 0;
2203
                        foreach($capsule_ids as $capsule_id)
2204
                        {
2205
                            $view_slides    += $progressMapper->fetchCountAllSlideViewedByUserIdAndCapsuleId($user->id, $capsule_id);
2206
                            $total_slides   += $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $topic->id, $capsule_id);
2207
 
2208
                        }
2209
 
2210
 
2211
                        $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
2212
                        $recordProgress->total_slides   = $total_slides;
2213
                        $recordProgress->view_slides    = $view_slides;
2214
                    }
2215
                    else if($type == CompanyMicrolearningUserProgress::TYPE_CAPSULE ) {
2216
                        $view_slides    = $progressMapper->fetchCountAllSlideViewedByUserIdAndCapsuleId($user->id, $capsule->id);
2217
                        $total_slides   = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $capsule->topic_id, $capsule->id);
2218
 
2219
                        $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
2220
                        $recordProgress->total_slides   = $total_slides;
2221
                        $recordProgress->view_slides    = $view_slides;
2222
                    }
2223
                    else {
2224
                        $recordProgress->progress       = 0;
2225
                        $recordProgress->total_slides   = 0;
2226
                        $recordProgress->view_slides    = 0;
2227
                    }
2228
 
2229
                    $recordProgress->updated_on = $updated_on;
2230
 
2231
 
2232
 
2233
                    if($recordProgress->id) {
2234
                        $result = $progressMapper->update($recordProgress);
2235
                    } else {
2236
                        $result = $progressMapper->insert($recordProgress);
2237
                    }
2238
 
2239
                    if($result) {
2240
                        return new JsonModel([
2241
                            'success' => true,
2242
                            'data' => [
2243
                                'sync_id' => $sync_id
2244
                            ]
2245
                        ]);
2246
                    } else {
2247
                        return new JsonModel([
2248
                            'success' => false,
2249
                            'data' => [
2250
                                'sync_id' => $sync_id,
2251
                                'message' => $progressMapper->getError()
2252
                            ]
2253
                        ]);
2254
                    }
2255
                }
2256
 
2257
 
2258
 
2259
                if($sync_type == 'microlearning-userlog') {
2260
                    $activity   = isset($data['activity'])      ? Functions::sanitizeFilterString($data['activity'])  :  '';
2261
                    $added_on   = isset($data['added_on'])      ? Functions::sanitizeFilterString($data['added_on'])  :  '';
2262
 
2263
 
2264
                    if(empty($activity)) {
2265
                        $ok = false;
2266
                    }
2267
 
2268
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2269
                    if(!$dt) {
2270
                        $ok = false;
2271
                    } else {
2272
                        $added_on = $dt->format('Y-m-d H:i:s');
2273
                    }
2274
 
2275
                    if(!$ok) {
2276
                        return new JsonModel([
2277
                            'success' => false,
2278
                            'data' => [
2279
                                'sync_id' => $sync_id,
2280
                                'message' => 'ERROR_INVALID_PARAMETERS 3',
2281
                            ]
2282
                        ]);
2283
                    }
2284
 
2285
                    $userLog = new CompanyMicrolearningUserLog();
2286
                    $userLog->activity      = $activity;
2287
                    $userLog->user_id       = $user->id;
2288
                    $userLog->company_id    = $topic->company_id;
2289
                    $userLog->topic_id      = $topic->id;
2290
                    $userLog->capsule_id    = $capsule ? $capsule->id : null;
2291
                    $userLog->slide_id      = $slide ? $slide->id : null;
2292
                    $userLog->added_on      = $added_on;
2293
 
2294
 
2295
 
2296
                    $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2297
                    if($userLogMapper->insert($userLog)) {
2298
                        return new JsonModel([
2299
                            'success' => true,
2300
                            'data' => [
2301
                                'sync_id' => $sync_id
2302
                            ]
2303
                        ]);
2304
                    } else {
2305
                        return new JsonModel([
2306
                            'success' => false,
2307
                            'data' => [
2308
                                'sync_id' => $sync_id,
2309
                                'message' => $userLogMapper->getError()
2310
                            ]
2311
                        ]);
2312
                    }
2313
                }
2314
 
2315
            }
2316
 
2317
 
2318
 
2319
 
2320
            if($user_uuid && $sync_type == 'userlog' && $device->application_id = Application::TWOGETSKILLS) {
2321
 
2322
                $userMapper = UserMapper::getInstance($this->adapter);
2323
                $user = $userMapper->fetchOneByUuid($user_uuid);
2324
 
2325
                if(!$user) {
2326
                    return new JsonModel([
2327
                        'success' => false,
2328
                        'data' => [
2329
                            'sync_id' => $sync_id,
2330
                            'message' => 'ERROR_USER_NOT_FOUND',
2331
                            'fatal' => true
2332
                        ]
2333
                    ]);
2334
                }
2335
 
2336
 
2337
                if($user->status != User::STATUS_ACTIVE) {
2338
                    return new JsonModel([
2339
                        'success' => false,
2340
                        'data' => [
2341
                            'sync_id' => $sync_id,
2342
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
2343
                            'fatal' => true
2344
                        ]
2345
                    ]);
2346
                }
2347
 
2348
                $activity   = isset($data['activity'])      ? Functions::sanitizeFilterString($data['activity'])  :  '';
2349
                $added_on   = isset($data['added_on'])      ? Functions::sanitizeFilterString($data['added_on'])  :  '';
2350
 
2351
                if(empty($activity)) {
2352
                    $ok = false;
2353
                }
2354
 
2355
                $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2356
                if(!$dt) {
2357
                    $ok = false;
2358
                } else {
2359
                    $added_on = $dt->format('Y-m-d H:i:s');
2360
                }
2361
 
2362
                if(!$ok) {
2363
                    return new JsonModel([
2364
                        'success' => false,
2365
                        'data' => [
2366
                            'sync_id' => $sync_id,
2367
                            'message' => 'ERROR_INVALID_PARAMETERS 4',
2368
                        ]
2369
                    ]);
2370
                }
2371
 
2372
                $userLog = new CompanyMicrolearningUserLog();
2373
                $userLog->company_id = null;
2374
                $userLog->user_id = $user->id;
2375
                $userLog->activity = $activity;
2376
                $userLog->added_on = $added_on;
2377
 
2378
 
2379
                $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2380
                if($userLogMapper->insert($userLog)) {
2381
                    return new JsonModel([
2382
                        'success' => true,
2383
                        'data' => [
2384
                            'sync_id' => $sync_id
2385
                        ]
2386
                    ]);
2387
                } else {
2388
                    return new JsonModel([
2389
                        'success' => false,
2390
                        'data' => [
2391
                            'sync_id' => $sync_id,
2392
                            'message' => $userLogMapper->getError()
2393
                        ]
2394
                    ]);
2395
                }
2396
            }
2397
 
2398
            return new JsonModel([
2399
                'success' => true,
2400
                'data' => [
2401
                    'sync_id' => $sync_id
2402
                ]
2403
            ]);
2404
 
2405
        }
2406
 
2407
        return new JsonModel([
2408
            'success' => false,
2409
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2410
        ]);
2411
    }
2412
 
2413
 
2414
    public function syncBatchAction()
2415
    {
2416
        $request = $this->getRequest();
2417
 
2418
        if($request->isPost()) {
2419
 
2420
            $rawdata = file_get_contents("php://input");
2421
            error_log('$rawdata = ' . $rawdata );
2422
            error_log(print_r($_POST, true));
2423
 
2424
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
2425
 
2426
            $device_uuid = Functions::sanitizeFilterString($this->params()->fromPost('device_uuid', ''));
2427
            $application_id = filter_var($this->params()->fromPost('application_id', 0), FILTER_SANITIZE_NUMBER_INT);
2428
            $variant_id     = filter_var($this->params()->fromPost('variant_id', 0), FILTER_SANITIZE_NUMBER_INT);
2429
            $max_records = filter_var($this->params()->fromPost('max_records', 0), FILTER_SANITIZE_NUMBER_INT);
2430
 
2431
 
2432
 
2433
 
2434
            $ok = $device_uuid && strlen($device_uuid) == 36 && $max_records;
2435
 
2436
            if(!$ok) {
2437
                return new JsonModel([
2438
                    'success' => false,
2439
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID',
2440
                ]);
2441
            }
2442
 
2443
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
2444
            $device = $deviceMapper->fetchOne($device_uuid);
2445
 
2446
 
2447
            if(!$device) {
2448
                return new JsonModel([
2449
                    'success' => false,
2450
                    'data' => 'ERROR_DEVICE_NOT_FOUND'
2451
                ]);
2452
            } else {
2453
 
2454
                if ($application_id && $variant_id) {
2455
                    $applicationMapper = ApplicationMapper::getInstance($this->adapter);
2456
                    $application = $applicationMapper->fetchOne($application_id);
2457
                    if(!$application) {
2458
                        return new JsonModel([
2459
                            'success' => false,
2460
                            'data' => 'ERROR_APPLICATION_NOT_FOUND',
2461
                        ]);
2462
                    }
2463
 
2464
                    if($application->status == Application::STATUS_INACTIVE) {
2465
                        return new JsonModel([
2466
                            'success' => false,
2467
                            'data' => 'ERROR_APPLICATION_IS_INACTIVE',
2468
                        ]);
2469
                    }
2470
 
2471
                    $applicationVariantMapper = ApplicationVariantMapper::getInstance($this->adapter);
2472
                    if ($variant_id) {
2473
                        $applicationVariant = $applicationVariantMapper->fetchOneByApplicationIdAndVariantId($application->id, $variant_id);
2474
                        if(!$applicationVariant) {
2475
 
2476
                            return new JsonModel([
2477
                                'success' => false,
2478
                                'data' => 'ERROR_APPLICATION_VARIANT_IS_INVALID',
2479
                            ]);
2480
                        }
2481
                    } else {
2482
                        $applicationVariant = $applicationVariantMapper->fetchOneByApplicationIdAndDefault($application->id);
2483
                    }
2484
 
2485
 
2486
                    $device->application_id = $application->id;
2487
                    $device->variant_id = $applicationVariant->variant_id;
2488
                }
2489
 
2490
 
2491
                $device->ip = Functions::getUserIP();
2492
                $deviceMapper->update($device);
2493
            }
2494
 
2495
 
2496
 
2497
 
2498
            $syncLogMapper = SyncLogMapper::getInstance($this->adapter);
2499
 
2500
 
2501
 
2502
            $result_sync_ids = [];
2503
 
2504
 
2505
 
2506
 
2507
            $users = [];
2508
            $companies = [];
2509
            $company_services = [];
2510
            $topics = [];
2511
            $capsules = [];
2512
            $capsule_users = [];
2513
            $slides = [];
2514
            $quizzes = [];
2515
            $questions = [];
2516
            $answers = [];
2517
 
2518
            $userMapper = UserMapper::getInstance($this->adapter);
2519
            $companyMapper = CompanyMapper::getInstance($this->adapter);
2520
            $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
2521
            $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
2522
            $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
2523
            $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
2524
            $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
2525
            $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
2526
            $questionMapper = CompanyMicrolearningQuestionMapper::getInstance($this->adapter);
2527
            $answerMapper = CompanyMicrolearningAnswerMapper::getInstance($this->adapter);
2528
 
2529
 
2530
            $userProgressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
2531
            $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2532
 
2533
 
2534
            for($i = 1; $i <= $max_records; $i++)
2535
            {
2536
                $sync_id        = filter_var($this->params()->fromPost('record_sync_id' . $i, ''), FILTER_SANITIZE_NUMBER_INT);
2537
                $record_data    = $this->params()->fromPost('record_data' . $i, '');
2538
 
2539
 
2540
 
2541
                if(empty($record_data) || empty($sync_id )) {
2542
                    continue;
2543
                }
2544
 
2545
 
2546
                $record         = json_decode($record_data, true);
2547
                $sync_type      = isset($record['sync_type']) ? Functions::sanitizeFilterString($record['sync_type']) : '';
2548
                $user_uuid      = isset($record['user_uuid']) ? Functions::sanitizeFilterString($record['user_uuid']) : '';
2549
                $company_uuid   = isset($record['company_uuid']) ? Functions::sanitizeFilterString($record['company_uuid']) : '';
2550
 
2551
 
2552
 
2553
 
2554
 
2555
 
2556
                if(!$sync_id) {
2557
                    continue;
2558
                }
2559
 
2560
                $syncLog = new SyncLog();
2561
                $syncLog->data = $record_data;
2562
                $syncLog->type = $sync_type;
2563
                $syncLog->device_uuid = $device->id;
2564
                $syncLog->ip = Functions::getUserIP();
2565
                $syncLogMapper->insert($syncLog);
2566
 
2567
                /***** INICIO MICROLEARNING *****/
2568
 
2569
                if($user_uuid && $device->application_id = Application::TWOGETSKILLS  && $company_uuid && in_array($sync_type, ['microlearning-progress', 'microlearning-userlog', 'microlearning-quiz'])) {
2570
 
2571
 
2572
                    if(isset($users[$user_uuid])) {
2573
                        $user = $users[$user_uuid];
2574
                    } else {
2575
 
2576
                        $user = $userMapper->fetchOneByUuid($user_uuid);
2577
                        if($user) {
2578
                            $users[$user_uuid] = $user;
2579
                        }
2580
                    }
2581
 
2582
 
2583
                    if(!$user) {
2584
                        array_push($result_sync_ids, [
2585
                            'success' => false,
2586
                            'sync_id' => $sync_id,
2587
                            'message' => 'ERROR_USER_NOT_FOUND',
2588
                            'fatal' => true
2589
                        ]);
2590
                        continue;
2591
                    }
2592
 
2593
 
2594
                    if($user->status != User::STATUS_ACTIVE) {
2595
                        array_push($result_sync_ids, [
2596
                            'success' => false,
2597
                            'sync_id' => $sync_id,
2598
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
2599
                            'fatal' => true
2600
                        ]);
2601
                        continue;
2602
                    }
2603
 
2604
 
2605
                    if(isset($companies[$company_uuid])) {
2606
                        $company = $companies[$company_uuid];
2607
                    } else {
2608
                        $company = $companyMapper->fetchOneByUuid($company_uuid);
2609
                        if($company) {
2610
                            $companies[$company_uuid] = $company;
2611
                        }
2612
                    }
2613
 
2614
 
2615
 
2616
 
2617
                    if(!$company) {
2618
                        array_push($result_sync_ids, [
2619
                            'success' => false,
2620
                            'sync_id' => $sync_id,
2621
                            'message' => 'ERROR_COMPANY_NOT_FOUND',
2622
                            'fatal' => true
2623
                        ]);
2624
                        continue;
2625
                    }
2626
 
2627
                    if($company->status != Company::STATUS_ACTIVE) {
2628
                        array_push($result_sync_ids, [
2629
                            'success' => false,
2630
                            'sync_id' => $sync_id,
2631
                            'message' => 'ERROR_COMPANY_IS_NOT_FOUND',
2632
                            'fatal' => true
2633
                        ]);
2634
                        continue;
2635
                    }
2636
 
2637
 
2638
 
2639
                    $key = $company->id . '-' .  Service::MICRO_LEARNING;
2640
                    if(isset($company_services[$key])) {
2641
                        $companyService = $company_services[$key];
2642
                    } else {
2643
                        $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($company->id, Service::MICRO_LEARNING);
2644
                        if($companyService) {
2645
                            $company_services[$key] = $companyService;
2646
                        }
2647
                    }
2648
 
2649
                    if(!$companyService) {
2650
                        array_push($result_sync_ids, [
2651
                            'success' => false,
2652
                            'sync_id' => $sync_id,
2653
                            'message' => 'ERROR_COMPANY_SERVICE_NOT_FOUND',
2654
                            'fatal' => true
2655
                        ]);
2656
                        continue;
2657
                    }
2658
 
2659
                    $serviceActive = true;
2660
                    $now = date('Y-m-d H:i:s');
2661
                    if($companyService->status == CompanyService::ACTIVE) {
2662
 
2663
                        if($now < $companyService->paid_from || $now > $companyService->paid_to) {
2664
                            $serviceActive = false;
2665
                        }
2666
 
2667
                    } else {
2668
                        $serviceActive = false;
2669
                    }
2670
 
2671
                    if( !$serviceActive) {
2672
                        array_push($result_sync_ids, [
2673
                            'success' => false,
2674
                            'sync_id' => $sync_id,
2675
                            'message' => 'ERROR_COMPANY_SERVICE_IS_NOT_ACTIVE',
2676
                            'fatal' => true
2677
                        ]);
2678
                        continue;
2679
                    }
2680
 
2681
 
2682
                    $topic_uuid = isset($record['topic_uuid']) ?   Functions::sanitizeFilterString($record['topic_uuid']) :  '';
2683
                    if($topic_uuid) {
2684
 
2685
                        if(isset($topics[$topic_uuid])) {
2686
                            $topic = $topics[$topic_uuid];
2687
                        } else {
2688
                            $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2689
                            if($topic) {
2690
                                $topics[$topic_uuid] = $topic;
2691
                            }
2692
                        }
2693
 
2694
                        if(!$topic) {
2695
                            error_log(print_r($record, true));
2696
 
2697
                            array_push($result_sync_ids, [
2698
                                'success' => false,
2699
                                'sync_id' => $sync_id,
2700
                                'message' => 'ERROR_TOPIC_NOT_FOUND',
2701
                            ]);
2702
                            continue;
2703
                        }
2704
 
2705
                        if($topic->company_id != $company->id) {
2706
                            array_push($result_sync_ids, [
2707
                                'success' => false,
2708
                                'sync_id' => $sync_id,
2709
                                'message' => 'ERROR_INVALID_PARAMETERS_TOPIC_COMPANY',
2710
                            ]);
2711
                            continue;
2712
                        }
2713
 
2714
                    } else {
2715
                        $topic = null;
2716
                    }
2717
 
2718
                    $capsule_uuid     = isset($record['capsule_uuid']) ? Functions::sanitizeFilterString($record['capsule_uuid']) :  '';
2719
 
2720
                    if($capsule_uuid) {
2721
 
2722
                        if(isset($capsules[$capsule_uuid])) {
2723
                            $capsule = $capsules[$capsule_uuid];
2724
                        } else {
2725
                            $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2726
                            if($capsule) {
2727
                                $capsules[$capsule_uuid] = $capsule;
2728
                            }
2729
                        }
2730
                        if(!$capsule) {
2731
                            error_log(print_r($record, true));
2732
 
2733
                            array_push($result_sync_ids, [
2734
                                'success' => false,
2735
                                'sync_id' => $sync_id,
2736
                                'message' => 'ERROR_CAPSULE_NOT_FOUND',
2737
                            ]);
2738
                            continue;
2739
                        }
2740
 
2741
                        if(!$topic || $capsule->topic_id != $topic->id) {
2742
                            array_push($result_sync_ids, [
2743
                                'success' => false,
2744
                                'sync_id' => $sync_id,
2745
                                'message' => 'ERROR_INVALID_PARAMETERS_CAPSULE_TOPIC',
2746
                            ]);
2747
                            continue;
2748
                        }
2749
                    } else {
2750
                        $capsule = null;
2751
                    }
2752
 
2753
                    if($capsule) {
2754
 
2755
                        $capsuleActive = true;
2756
 
2757
                        $key = $user->id . '-' . $capsule->id;
2758
 
2759
                        if(isset($capsule_users[$key])) {
2760
                            $capsuleUser = $capsule_users[$key];
2761
                        } else {
2762
 
2763
                            $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
2764
                            if($capsuleUser) {
2765
                                $capsule_users[$key] = $capsuleUser;
2766
                            }
2767
 
2768
                        }
2769
 
2770
                        $now = date('Y-m-d H:i:s');
2771
                        if($capsuleUser && in_array($capsuleUser->access, [CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED,CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD ])) {
2772
 
2773
 
2774
                            if($capsuleUser->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
2775
 
2776
                                if($now < $capsuleUser->paid_from || $now > $capsuleUser->paid_to) {
2777
                                    $capsuleActive = false;;
2778
                                }
2779
                            }
2780
 
2781
                        } else {
2782
                            $capsuleActive = false;
2783
                        }
2784
 
2785
                        if(!$capsuleActive) {
2786
                            array_push($result_sync_ids, [
2787
                                'success' => false,
2788
                                'sync_id' => $sync_id,
2789
                                'message' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
2790
                            ]);
2791
                            continue;
2792
                        }
2793
                    }
2794
 
2795
 
2796
                    $slide_uuid      = $record['slide_uuid'] ? Functions::sanitizeFilterString($record['slide_uuid']) :  '';
2797
                    if($slide_uuid) {
2798
 
2799
                        if(isset($slides[$slide_uuid])) {
2800
                            $slide = $slides[$slide_uuid];
2801
                        } else {
2802
 
2803
                            $slide = $slideMapper->fetchOneByUuid($slide_uuid);
2804
                            if($slide) {
2805
                                $slides[$slide_uuid] = $slide;
2806
                            }
2807
                        }
2808
                        if(!$slide) {
2809
                            error_log(print_r($record, true));
2810
 
2811
                            array_push($result_sync_ids, [
2812
                                'success' => false,
2813
                                'sync_id' => $sync_id,
2814
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
2815
                            ]);
2816
                            continue;
2817
                        }
2818
 
2819
                        if(!$capsule || $slide->capsule_id != $capsule->id) {
2820
                            array_push($result_sync_ids, [
2821
                                'success' => false,
2822
                                'sync_id' => $sync_id,
2823
                                'message' => 'ERROR_INVALID_PARAMETERS_SLIDE_CAPSULE',
2824
                            ]);
2825
                            continue;
2826
                        }
2827
                    } else {
2828
                        $slide = null;
2829
                    }
2830
 
2831
                    if($sync_type == 'microlearning-quiz') {
2832
                        $ok = true;
2833
 
2834
                        $quiz_uuid = isset($record['quiz_uuid']) ? $record['quiz_uuid'] : '';
2835
 
2836
                        if(isset($quizzes[$quiz_uuid])) {
2837
                            $quiz = $quizzes[$quiz_uuid];
2838
                        } else {
2839
                            $quiz = $quizMapper->fetchOneByUuid($quiz_uuid);
2840
                            if($quiz) {
2841
                                $quizzes[$quiz_uuid] = $quiz;
2842
                            }
2843
                        }
2844
                        if(!$quiz) {
2845
                            array_push($result_sync_ids, [
2846
                                'success' => false,
2847
                                'sync_id' => $sync_id,
2848
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
2849
                            ]);
2850
                            continue;
2851
                        }
2852
 
2853
                        if(!$capsule || $slide->capsule_id != $capsule->id) {
2854
                            array_push($result_sync_ids, [
2855
                                'success' => false,
2856
                                'sync_id' => $sync_id,
2857
                                'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_SLIDE',
2858
                            ]);
2859
                            continue;
2860
                        }
2861
 
2862
                        $added_on   = isset($record['added_on'])      ? Functions::sanitizeFilterString($record['added_on'])  :  '';
2863
 
2864
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2865
                        if(!$dt) {
2866
                            $ok = false;
2867
                        } else {
2868
                            $added_on = $dt->format('Y-m-d H:i:s');
2869
                        }
2870
 
2871
                        if(isset($record['points'])) {
2872
                            $points = intval($record['points'], 10);
2873
                        } else {
2874
                            $ok = false;
2875
                        }
2876
 
2877
                        if(isset($record['pass'])) {
2878
                            $status = $record['pass'] == 'yes' ? CompanyMicrolearningUserQuiz::STATUS_PASS : CompanyMicrolearningUserQuiz::STATUS_FAIL;
2879
                        } else {
2880
                            $ok = false;
2881
                        }
2882
 
2883
                        if(!$ok) {
2884
                            array_push($result_sync_ids, [
2885
                                'success' => false,
2886
                                'sync_id' => $sync_id,
2887
                                'message' => 'ERROR_INVALID_PARAMETERS 9',
2888
                            ]);
2889
                            continue;
2890
                        }
2891
 
2892
                        $array_response = [];
2893
                        $response = isset($record['response']) ? intval($record['response'], 10) : 0;
2894
                        for($i = 0; $i < $response; $i++)
2895
                        {
2896
                            $question_uuid = isset($record["response_{$i}_question_uuid"]) ? $record["response_{$i}_question_uuid"] : '';
2897
                            $answer_uuid = isset($record["response_{$i}_answer_uuid"]) ? $record["response_{$i}_answer_uuid"] : '';
2898
                            $value = isset($record["response_{$i}_value"]) ?  intval($record["response_{$i}_value"], 10) : 0;
2899
                            $points = isset($record["response_{$i}_points"]) ?  intval($record["response_{$i}_points"], 10) : 0;
2900
 
2901
 
2902
                            if(isset($questions[$question_uuid])) {
2903
                                $question = $questions[$question_uuid];
2904
                            } else {
2905
                                $question = $questionMapper->fetchOneByUuid($question_uuid);
2906
                                if($question) {
2907
                                    $questions[$question_uuid] = $question;
2908
                                }
2909
                            }
2910
 
2911
                            if(!$question || $question->quiz_id != $quiz->id) {
2912
                                array_push($result_sync_ids, [
2913
                                    'success' => false,
2914
                                    'sync_id' => $sync_id,
2915
                                    'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_QUESTION_SLIDE',
2916
                                ]);
2917
                                continue;
2918
                            }
2919
 
2920
                            if(isset($answers[$answer_uuid])) {
2921
                                $answer = $answers[$answer_uuid];
2922
                            } else {
2923
                                $answer = $answerMapper->fetchOneByUuid($answer_uuid);
2924
                                if($answer) {
2925
                                    $answers[$answer_uuid] = $answer;
2926
                                }
2927
                            }
2928
 
2929
                            if($answer && $answer->question_id != $question->id) {
2930
                                array_push($result_sync_ids, [
2931
                                    'success' => false,
2932
                                    'sync_id' => $sync_id,
2933
                                    'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_ANSWER_SLIDE',
2934
                                ]);
2935
                                continue;
2936
                            }
2937
 
2938
                            array_push($array_response, [
2939
                                'question_uuid' => $question_uuid,
2940
                                'answer_uuid' => $answer_uuid,
2941
                                'value' => $value,
2942
                                'points' => $points
2943
                            ]);
2944
                        }
2945
 
2946
                        $userQuiz = new CompanyMicrolearningUserQuiz();
2947
                        $userQuiz->company_id = $company->id;
2948
                        $userQuiz->topic_id = $topic->id;
2949
                        $userQuiz->capsule_id = $capsule->id;
2950
                        $userQuiz->slide_id = $slide->id;
2951
                        $userQuiz->quiz_id = $quiz->id;
2952
                        $userQuiz->user_id = $user->id;
2953
                        $userQuiz->added_on = $added_on;
2954
                        $userQuiz->points = $points;
2955
                        $userQuiz->status = $status;
2956
                        $userQuiz->response = json_encode($array_response);
2957
 
2958
                        $userQuizMapper = CompanyMicrolearningUserQuizMapper::getInstance($this->adapter);
2959
 
2960
                        if($userQuizMapper->insert($userQuiz)) {
2961
                            array_push($result_sync_ids, [
2962
                                'success' => true,
2963
                                'sync_id' => $sync_id
2964
                            ]);
2965
                        } else {
2966
                            array_push($result_sync_ids, [
2967
                                'success' => false,
2968
                                'sync_id' => $sync_id,
2969
                                'message' => $userQuizMapper->getError()
2970
                            ]);
2971
                        }
2972
                        continue;
2973
                    }
2974
 
2975
                    if($sync_type == 'microlearning-progress') {
2976
                        $ok = true;
2977
 
2978
                        $type = isset($record['type']) ? $record['type'] : '';
2979
                        switch($type)
2980
                        {
2981
                            case CompanyMicrolearningUserProgress::TYPE_TOPIC :
2982
                                if(!$topic) {
2983
                                    $ok = false;
2984
                                }
2985
                                break;
2986
 
2987
                            case CompanyMicrolearningUserProgress::TYPE_CAPSULE :
2988
                                if(!$topic || !$capsule) {
2989
                                    $ok = false;
2990
                                }
2991
                                break;
2992
 
2993
                            case CompanyMicrolearningUserProgress::TYPE_SLIDE :
2994
                                if(!$topic || !$capsule || !$slide) {
2995
                                    $ok = false;
2996
                                }
2997
                                break;
2998
 
2999
                            default :
3000
                                $ok = false;
3001
                                break;
3002
                        }
3003
 
3004
                        $added_on   = isset($record['added_on'])      ? Functions::sanitizeFilterString($record['added_on'])  :  '';
3005
                        $updated_on = isset($record['updated_on'])    ? Functions::sanitizeFilterString($record['updated_on']) :  '';
3006
 
3007
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
3008
                        if(!$dt) {
3009
                            $ok = false;
3010
                        } else {
3011
                            $added_on = $dt->format('Y-m-d H:i:s');
3012
                        }
3013
 
3014
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $updated_on );
3015
                        if(!$dt) {
3016
                            $ok = false;
3017
                        } else {
3018
                            $updated_on = $dt->format('Y-m-d H:i:s');
3019
                        }
3020
 
3021
                        if(!$ok) {
3022
                            array_push($result_sync_ids, [
3023
                                'success' => false,
3024
                                'sync_id' => $sync_id,
3025
                                'message' => 'ERROR_INVALID_PARAMETERS 10',
3026
                            ]);
3027
                            continue;
3028
                        }
3029
 
3030
                        $progress                   = isset($record['progress'])                  ? floatval($record['progress']) :  0;
3031
                        $total_slides               = isset($record['total_slides'])              ? intval($record['total_slides'], 10) :  0;
3032
                        $view_slides                = isset($record['view_slides'])               ? intval($record['view_slides'], 10) :  0;
3033
                        $returning                  = isset($record['returning'])                 ? intval($record['returning'], 10) :  0;
3034
                        $returning_after_completed  = isset($record['returning_after_completed']) ? intval($record['returning_after_completed'], 10) :  0;
3035
                        $completed                  = isset($record['completed'])                 ? intval($record['completed'], 10) :  0;
3036
 
3037
 
3038
                        $recordProgress = null;
3039
                        switch($type) {
3040
                            case CompanyMicrolearningUserProgress::TYPE_TOPIC  :
3041
                                $recordProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($user->id, $topic->id);
3042
 
3043
                                break;
3044
 
3045
                            case CompanyMicrolearningUserProgress::TYPE_CAPSULE  :
3046
                                $recordProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($user->id, $capsule->id);
3047
                                break;
3048
 
3049
                            case CompanyMicrolearningUserProgress::TYPE_SLIDE  :
3050
                                $recordProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($user->id, $slide->id);
3051
                                break;
3052
 
3053
                            default :
3054
                                $recordProgress= null;
3055
                        }
3056
 
3057
 
3058
                        if(!$recordProgress) {
3059
                            $recordProgress = new CompanyMicrolearningUserProgress();
3060
 
3061
                            $recordProgress->user_id    = $user->id;
3062
                            $recordProgress->type       = $type;
3063
                            $recordProgress->company_id = $topic->company_id;
3064
                            $recordProgress->topic_id   = $topic->id;
3065
                            $recordProgress->capsule_id = $capsule ? $capsule->id : null;
3066
                            $recordProgress->slide_id   = $slide ? $slide->id : null;
3067
                            $recordProgress->added_on   = $added_on;
3068
                        }
3069
                        /*
3070
                        else {
3071
 
3072
                            if($recordProgress->updated_on > $updated_on) {
3073
                                array_push($result_sync_ids, [
3074
                                    'success' => true,
3075
                                    'sync_id' => $sync_id,
3076
                                ]);
3077
                                continue;
3078
                            }
3079
 
3080
 
3081
 
3082
                        }*/
3083
                        $recordProgress->returning                  = $returning;
3084
                        $recordProgress->returning_after_completed  = $returning_after_completed;
3085
                        $recordProgress->completed                  = $completed;
3086
 
3087
                        if($type == CompanyMicrolearningUserProgress::TYPE_TOPIC ) {
3088
 
3089
                            $capsule_ids = [];
3090
                            $companyMicrolearningCapsuleUser = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
3091
                            $records =  $companyMicrolearningCapsuleUser->fetchAllActiveByUserId($user->id);
3092
                            foreach($records as $record)
3093
                            {
3094
                                if($now >= $record->paid_from || $now <= $capsuleUser->paid_to) {
3095
                                    if(!in_array($record->capsule_id, $capsule_ids)) {
3096
                                        array_push($capsule_ids, $record->capsule_id);
3097
                                    }
3098
                                }
3099
                            }
3100
 
3101
                            $recordProgress->progress       = $progress;
3102
                            $recordProgress->total_slides   = $total_slides;
3103
                            $recordProgress->view_slides    = $view_slides;
3104
                        }
3105
                        else if($type == CompanyMicrolearningUserProgress::TYPE_CAPSULE ) {
3106
 
3107
                            $recordProgress->progress       = $progress;
3108
                            $recordProgress->total_slides   = $total_slides;
3109
                            $recordProgress->view_slides    = $view_slides;
3110
                        }
3111
                        else {
3112
                            $recordProgress->progress       = 0;
3113
                            $recordProgress->total_slides   = 0;
3114
                            $recordProgress->view_slides    = 0;
3115
                        }
3116
 
3117
                        $recordProgress->updated_on = $updated_on;
3118
 
3119
 
3120
 
3121
                        if($recordProgress->id) {
3122
                            $result = $userProgressMapper->update($recordProgress);
3123
                        } else {
3124
                            $result = $userProgressMapper->insert($recordProgress);
3125
                        }
3126
 
3127
                        if($result) {
3128
                            array_push($result_sync_ids, [
3129
                                'success' => true,
3130
                                'sync_id' => $sync_id
3131
                            ]);
3132
                        } else {
3133
                            array_push($result_sync_ids, [
3134
                                'success' => false,
3135
                                'sync_id' => $sync_id,
3136
                                'message' => $userProgressMapper->getError()
3137
                            ]);
3138
                        }
3139
                        continue;
3140
                    }
3141
 
3142
 
3143
 
3144
                    if($sync_type == 'microlearning-userlog') {
3145
                        $activity   = isset($record['activity'])      ? Functions::sanitizeFilterString($record['activity'])  :  '';
3146
                        $added_on   = isset($record['added_on'])      ? Functions::sanitizeFilterString($record['added_on'])  :  '';
3147
 
3148
                        if(empty($activity)) {
3149
                            $ok = false;
3150
                        }
3151
 
3152
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
3153
                        if(!$dt) {
3154
                            $ok = false;
3155
                        } else {
3156
                            $added_on = $dt->format('Y-m-d H:i:s');
3157
                        }
3158
 
3159
                        if(!$ok) {
3160
                            array_push($result_sync_ids, [
3161
                                'success' => false,
3162
                                'sync_id' => $sync_id,
3163
                                'message' => 'ERROR_INVALID_PARAMETERS 11',
3164
                            ]);
3165
                            continue;
3166
                        }
3167
 
3168
 
3169
 
3170
 
3171
                        $userLog = $userLogMapper->fetchLastBy($user->id);
3172
                        if($userLog) {
3173
                            $insert = $userLog->added_on <= $added_on;
3174
                        } else {
3175
                            $insert = true;
3176
                        }
3177
 
3178
 
3179
                        if($insert) {
3180
 
3181
                            $userLog = new CompanyMicrolearningUserLog();
3182
                            $userLog->activity      = $activity;
3183
                            $userLog->user_id       = $user->id;
3184
                            $userLog->company_id    = $topic->company_id;
3185
                            $userLog->topic_id      = $topic->id;
3186
                            $userLog->capsule_id    = $capsule ? $capsule->id : null;
3187
                            $userLog->slide_id      = $slide ? $slide->id : null;
3188
                            $userLog->added_on      = $added_on;
3189
 
3190
 
3191
 
3192
 
3193
                            if($userLogMapper->insert($userLog)) {
3194
                                array_push($result_sync_ids, [
3195
                                    'success' => true,
3196
                                    'sync_id' => $sync_id
3197
                                ]);
3198
                            } else {
3199
                                array_push($result_sync_ids, [
3200
                                    'success' => false,
3201
                                    'sync_id' => $sync_id,
3202
                                    'message' => $userLogMapper->getError()
3203
                                ]);
3204
                            }
3205
                        } else {
3206
                            array_push($result_sync_ids, [
3207
                                'success' => true,
3208
                                'sync_id' => $sync_id
3209
                            ]);
3210
                        }
3211
                        continue;
3212
                    }
3213
 
3214
                }
3215
 
3216
                /***** FIN MICROLEARNING *****/
3217
 
3218
 
3219
                /***** INICIO LOG DE USUARIO GENERAL *****/
3220
 
3221
                if($user_uuid && $sync_type == 'userlog' && $device->application_id = Application::TWOGETSKILLS) {
3222
 
3223
 
3224
 
3225
                    if(isset($users[$user_uuid])) {
3226
                        $user = $users[$user_uuid];
3227
                    } else {
3228
                        $user = $userMapper->fetchOneByUuid($user_uuid);
3229
                        if($user) {
3230
                            $users[$user_uuid] = $user;
3231
                        }
3232
                    }
3233
 
3234
 
3235
 
3236
 
3237
                    if(!$user) {
3238
                        array_push($result_sync_ids, [
3239
                            'success' => false,
3240
                            'sync_id' => $sync_id,
3241
                            'message' => 'ERROR_USER_NOT_FOUND',
3242
                            'fatal' => true
3243
                        ]);
3244
                        continue;
3245
                    }
3246
 
3247
 
3248
                    if($user->status != User::STATUS_ACTIVE) {
3249
                        array_push($result_sync_ids, [
3250
                            'success' => false,
3251
                            'sync_id' => $sync_id,
3252
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
3253
                            'fatal' => true
3254
                        ]);
3255
                        continue;
3256
                    }
3257
 
3258
                    $activity   = isset($record['activity'])      ? Functions::sanitizeFilterString($record['activity'])  :  '';
3259
                    $added_on   = isset($record['added_on'])      ? Functions::sanitizeFilterString($record['added_on'])  :  '';
3260
 
3261
                    if(empty($activity)) {
3262
                        $ok = false;
3263
                    }
3264
 
3265
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
3266
                    if(!$dt) {
3267
                        $ok = false;
3268
                    } else {
3269
                        $added_on = $dt->format('Y-m-d H:i:s');
3270
                    }
3271
 
3272
                    if(!$ok) {
3273
                        array_push($result_sync_ids, [
3274
                            'success' => false,
3275
                            'sync_id' => $sync_id,
3276
                            'message' => 'ERROR_INVALID_PARAMETERS 12',
3277
                        ]);
3278
                        continue;
3279
                    }
3280
 
3281
 
3282
                    $userLog = $userLogMapper->fetchLastBy($user->id);
3283
                    if($userLog) {
3284
                        $insert = $userLog->added_on <= $added_on;
3285
                    } else {
3286
                        $insert = true;
3287
                    }
3288
 
3289
 
3290
                    if($insert) {
3291
                        $userLog = new CompanyMicrolearningUserLog();
3292
                        $userLog->company_id = null;
3293
                        $userLog->user_id = $user->id;
3294
                        $userLog->activity = $activity;
3295
                        $userLog->added_on = $added_on;
3296
 
3297
 
3298
                        $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
3299
                        if($userLogMapper->insert($userLog)) {
3300
                            array_push($result_sync_ids, [
3301
                                'success' => true,
3302
                                'sync_id' => $sync_id
3303
                            ]);
3304
                        } else {
3305
                            array_push($result_sync_ids, [
3306
                                'success' => false,
3307
                                'sync_id' => $sync_id,
3308
                                'message' => $userLogMapper->getError()
3309
                            ]);
3310
                        }
3311
                    } else {
3312
                        array_push($result_sync_ids, [
3313
                            'success' => true,
3314
                            'sync_id' => $sync_id
3315
                        ]);
3316
                    }
3317
 
3318
 
3319
 
3320
                    continue;
3321
                }
3322
 
3323
                /***** FIN LOG DE USUARIO GENERAL ******/
3324
            }
3325
 
3326
            if( $result_sync_ids) {
3327
                return new JsonModel([
3328
                    'success' => true,
3329
                    'data' => $result_sync_ids
3330
                ]);
3331
            } else {
3332
                return new JsonModel([
3333
                    'success' => false,
3334
                    'data' => 'ERROR_INVALID_PARAMETERS 13'
3335
                ]);
3336
            }
3337
 
3338
 
3339
        }
3340
 
3341
        return new JsonModel([
3342
            'success' => false,
3343
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
3344
        ]);
3345
    }
3346
 
3347
    public function deleteAccountAction()
3348
    {
3349
        $rawdata = file_get_contents("php://input");
3350
        error_log('url = ' . $_SERVER['REQUEST_URI']);
3351
        error_log('query = ' . $_SERVER['QUERY_STRING']);
3352
        error_log('$rawdata = ' . $rawdata );
3353
 
3354
 
3355
        $currentUserPlugin = $this->plugin('currentUserPlugin');
3356
        $user = $currentUserPlugin->getUser();
3357
 
3358
 
3359
 
3360
        $request = $this->getRequest();
3361
 
3362
        if($request->isGet()) {
3363
 
3364
            $this->sendEmailDeleteAccountKey($user);
3365
 
3366
 
3367
            return new JsonModel([
3368
                'success' => true,
3369
                'data' => [
3370
                    'message' => 'LABEL_DELETE_ACCOUNT_WE_HAVE_SENT_A_CONFIRMATION_CODE'
3371
                ]
3372
            ]);
3373
 
3374
        } else  if($request->isPost()) {
3375
 
3376
            $code = $this->params()->fromPost('code');
3377
            if(empty($code) || $code != $user->delete_account_key) {
3378
 
3379
                $this->sendEmailDeleteAccountKey($user);
3380
 
3381
                return new JsonModel([
3382
                    'success' => false,
3383
                    'data' => [
3384
                        'message' => 'ERROR_DELETE_ACCOUNT_CONFIRMATION_CODE_IS_WRONG'
3385
                    ]
3386
                ]);
3387
            }
3388
 
3389
            $delete_account_generated_on = strtotime($user->delete_account_generated_on);
3390
            $expiry_time = $delete_account_generated_on + $this->config['leaderslinked.security.delete_account_expired'];
3391
 
3392
 
3393
            if (time() > $expiry_time) {
3394
 
3395
                $this->sendEmailDeleteAccountKey($user) ;
3396
 
3397
                return new JsonModel([
3398
                    'success' => false,
3399
                    'data' => [
3400
                        'message' => 'ERROR_DELETE_ACCOUNT_CONFIRMATION_CODE_EXPIRED'
3401
                    ]
3402
                ]);
3403
 
3404
 
3405
            }
3406
 
3407
            $userDeleted  = new UserDeleted();
3408
            $userDeleted->user_id = $user->id;
3409
            $userDeleted->first_name = $user->first_name;
3410
            $userDeleted->last_name = $user->last_name;
3411
            $userDeleted->email = $user->email;
3412
            $userDeleted->image = $user->image;
3413
            $userDeleted->phone = $user->phone;
3414
            $userDeleted->pending = UserDeleted::PENDING_YES;
3415
 
3416
 
3417
            $userDeletedMapper = UserDeletedMapper::getInstance($this->adapter);
3418
            if ($userDeletedMapper->insert($userDeleted)) {
3419
 
3420
                $this->sendEmailDeleteAccountCompleted($user);
3421
 
3422
                $user->first_name = 'LABEL_DELETE_ACCOUNT_FIRST_NAME';
3423
                $user->last_name = 'LABEL_DELETE_ACCOUNT_LAST_NAME';
3424
                $user->email = 'user-deleted-' . uniqid() . '@leaderslinked.com';
3425
                $user->image = '';
3426
                $user->usertype_id = UserType::USER_DELETED;
3427
                $user->status = User::STATUS_DELETED;
3428
                $user->delete_account_key = '';
3429
                $user->delete_account_generated_on = '';
3430
 
3431
                $userMapper = UserMapper::getInstance($this->adapter);
3432
                if($userMapper->update($user)) {
3433
 
3434
 
3435
 
3436
                    return new JsonModel([
3437
                        'success' => true,
3438
                        'data' => [
3439
                            'message' => 'LABEL_DELETE_ACCOUNT_WE_HAVE_STARTED_DELETING_YOUR_DATA',
3440
                        ]
3441
                    ]);
3442
 
3443
 
3444
                } else {
3445
                    return new JsonModel([
3446
                        'success' => false,
3447
                        'data' => [
3448
                            'message' => $userDeletedMapper->getError()
3449
                        ]
3450
                    ]);
3451
                }
3452
 
3453
 
3454
 
3455
            } else {
3456
                return new JsonModel([
3457
                    'success' => false,
3458
                    'data' => [
3459
                        'message' => $userDeletedMapper->getError()
3460
                    ]
3461
                ]);
3462
            }
3463
 
3464
 
3465
 
3466
 
3467
 
3468
        }
3469
 
3470
 
3471
            return new JsonModel([
3472
                'success' => false,
3473
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
3474
            ]);
3475
    }
3476
 
3477
 
3478
    private function sendEmailDeleteAccountKey($user)
3479
    {
3480
        $delete_account_key = Functions::generatePassword(8);
3481
 
3482
        $userMapper = UserMapper::getInstance($this->adapter);
3483
        $userMapper->updateDeleteAccountKey($user->id, $delete_account_key);
3484
 
3485
        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
3486
        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_DELETE_ACCOUNT_CODE, $user->network_id);
3487
        if($emailTemplate) {
3488
            $arrayCont = [
3489
                'firstname' => $user->first_name,
3490
                'lastname'  => $user->last_name,
3491
                'code'      => $delete_account_key,
3492
                'link'      => ''
3493
            ];
3494
 
3495
            $email = new QueueEmail($this->adapter);
3496
            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
3497
        }
3498
    }
3499
 
3500
 
3501
    private function sendEmailDeleteAccountCompleted($user)
3502
    {
3503
 
3504
        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
3505
        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_DELETE_ACCOUNT_COMPLETED, $user->network_id);
3506
        if($emailTemplate) {
3507
            $arrayCont = [
3508
                'firstname' => $user->first_name,
3509
                'lastname'  => $user->last_name,
3510
                'code'      => '',
3511
                'link'      => ''
3512
            ];
3513
 
3514
            $email = new QueueEmail($this->adapter);
3515
            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
3516
        }
3517
    }
3518
 
3519
 
3520
    /**
3521
     *
3522
     * @param User $user
3523
     * @param boolean $includeLogs
3524
     * @param boolean $includeProgress
3525
     * @return array[]
3526
     */
3527
    private function getSyncData($user, $includeLogs = true, $includeProgress = true)
3528
    {
3529
 
3530
        $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
3531
 
3532
        $data = [
3533
            'userlog'   => [],
3534
            'progress'  => [],
3535
            'topics'    => [],
3536
            'quizzes'   => [],
3537
            'extended'  => [],
3538
        ];
3539
 
3540
 
3541
        $companies = [];
3542
        $companyMapper = CompanyMapper::getInstance($this->adapter);
3543
 
3544
        $topics = [];
3545
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
3546
 
3547
        $capsules = [];
3548
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
3549
 
3550
        $slides = [];
3551
        $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
3552
 
3553
        $quizzes = [];
3554
        $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
3555
 
3556
        $questions = [];
3557
        $questionMapper = CompanyMicrolearningQuestionMapper::getInstance($this->adapter);
3558
 
3559
        $answers = [];
3560
        $answerMapper = CompanyMicrolearningAnswerMapper::getInstance($this->adapter);
3561
 
3562
 
3563
        $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
3564
 
3565
        if($includeLogs) {
3566
 
3567
            //$records = $userLogMapper->fetchLast20ByUserId($user->id);
3568
            $records = $userLogMapper->fetchAllByUserId($user->id);
3569
            foreach($records as $record)
3570
            {
3571
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
3572
 
3573
                if($record->company_id) {
3574
 
3575
                   if(isset($companies[$record->company_id])) {
3576
                        $company = $companies[$record->company_id];
3577
                    } else {
3578
                        $company = $companyMapper->fetchOne($record->company_id);
3579
                        $companies[$record->company_id] = $company;
3580
                    }
3581
                } else {
3582
                    $company = null;
3583
                }
3584
 
3585
                if($record->topic_id) {
3586
 
3587
                    if(isset($topics[$record->topic_id])) {
3588
                        $topic = $topics[$record->topic_id];
3589
                    } else {
3590
                        $topic = $topicMapper->fetchOne($record->topic_id);
3591
                        $topics[$record->topic_id] = $topic;
3592
                    }
3593
                } else {
3594
                    $topic = null;
3595
                }
3596
 
3597
 
3598
                if($record->capsule_id) {
3599
 
3600
                    if(isset($capsules[$record->capsule_id])) {
3601
                        $capsule = $capsules[$record->capsule_id];
3602
                    } else {
3603
                        $capsule = $capsuleMapper->fetchOne($record->capsule_id);
3604
                        $capsules[$record->capsule_id] = $capsule;
3605
                    }
3606
                } else {
3607
                    $capsule = null;
3608
                }
3609
 
3610
 
3611
                if($record->slide_id) {
3612
 
3613
                    if(isset($slides[$record->slide_id])) {
3614
                        $slide = $slides[$record->slide_id];
3615
                    } else {
3616
                        $slide = $slideMapper->fetchOne($record->slide_id);
3617
                        $slides[$record->slide_id] = $slide;
3618
                    }
3619
                } else {
3620
                    $slide = null;
3621
                }
3622
 
3623
 
3624
                array_push($data['userlog'], [
3625
                    'user_uuid'     => $user->uuid,
3626
                    'company_uuid'  => $company ? $company->uuid : '',
3627
                    'topic_uuid'    => $topic ? $topic->uuid : '',
3628
                    'capsule_uuid'  => $capsule ? $capsule->uuid : '',
3629
                    'slide_uuid'    => $slide ? $slide->uuid : '',
3630
                    'activity'      => $record->activity,
3631
                    'added_on'      => $dt->format($serviceDatetimeFormat),
3632
                ]);
3633
 
3634
 
3635
            }
3636
        }
3637
 
3638
        if($includeProgress) {
3639
 
3640
            $userProgressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
3641
            $records = $userProgressMapper->fetchAllByUserId($user->id);
3642
            foreach($records as $record)
3643
            {
3644
                if($record->company_id) {
3645
 
3646
                    if(isset($companies[$record->company_id])) {
3647
                        $company = $companies[$record->company_id];
3648
                    } else {
3649
                        $company = $companyMapper->fetchOne($record->company_id);
3650
                        $companies[$record->company_id] = $company;
3651
                    }
3652
                } else {
3653
                    $company = null;
3654
                }
3655
 
3656
                if($record->topic_id) {
3657
 
3658
                    if(isset($topics[$record->topic_id])) {
3659
                        $topic = $topics[$record->topic_id];
3660
                    } else {
3661
                        $topic = $topicMapper->fetchOne($record->topic_id);
3662
                        $topics[$record->topic_id] = $topic;
3663
                    }
3664
                } else {
3665
                    $topic = null;
3666
                }
3667
 
3668
 
3669
                if($record->capsule_id) {
3670
 
3671
                    if(isset($capsules[$record->capsule_id])) {
3672
                        $capsule = $capsules[$record->capsule_id];
3673
                    } else {
3674
                        $capsule = $capsuleMapper->fetchOne($record->capsule_id);
3675
                        $capsules[$record->capsule_id] = $capsule;
3676
                    }
3677
                } else {
3678
                    $capsule = null;
3679
                }
3680
 
3681
 
3682
                if($record->slide_id) {
3683
 
3684
                    if(isset($slides[$record->slide_id])) {
3685
                        $slide = $slides[$record->slide_id];
3686
                    } else {
3687
                        $slide = $slideMapper->fetchOne($record->slide_id);
3688
                        $slides[$record->slide_id] = $slide;
3689
                    }
3690
                } else {
3691
                    $slide = null;
3692
                }
3693
 
3694
 
3695
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
3696
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $record->updated_on);
3697
 
3698
                array_push($data['progress'], [
3699
                    'user_uuid'                 => $user->uuid,
3700
                    'company_uuid'              => $company ? $company->uuid : '',
3701
                    'topic_uuid'                => $topic ? $topic->uuid : '',
3702
                    'capsule_uuid'              => $capsule ? $capsule->uuid : '',
3703
                    'slide_uuid'                => $slide ? $slide->uuid : '',
3704
                    'progress'                  => $record->progress ? $record->progress : 0,
3705
                    'total_slides'              => $record->total_slides ? $record->total_slides : 0,
3706
                    'view_slides'               => $record->view_slides ? $record->view_slides : 0,
3707
                    'type'                      => $record->type,
3708
                    'returning'                 => $record->returning ? $record->returning : 0,
3709
                    'returning_after_completed' => $record->returning_after_completed ? $record->returning_after_completed : 0,
3710
                    'completed'                 => $record->completed ? $record->completed : 0,
3711
                    'added_on'                  => $dtAddedOn->format($serviceDatetimeFormat),
3712
                    'updated_on'                => $dtUpdatedOn->format($serviceDatetimeFormat),
3713
                ]);
3714
            }
3715
        }
3716
 
3717
 
3718
        $now = date('Y-m-d H:i:s');
3719
        $companies_with_access  = [];
3720
        $topics_with_access     = [];
3721
        $capsules_with_access   = [];
3722
        $quizzes_with_access    = [];
3723
        $quizzes                = [];
3724
 
3725
 
3726
        $capsuleCommentMapper = CompanyMicrolearningCapsuleCommentMapper::getInstance($this->adapter);
3727
        $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
3728
        $records = $capsuleUserMapper->fetchAllActiveByUserId($user->id);
3729
 
3730
 
3731
        foreach($records as $record)
3732
        {
3733
            if($record->access != CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED && $record->access != CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
3734
                continue;
3735
            }
3736
            if($record->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
3737
                if($now < $record->paid_from || $now > $record->paid_to) {
3738
                    continue;
3739
                }
3740
            }
3741
 
3742
 
3743
            if(!in_array($record->company_id,$companies_with_access)) {
3744
                array_push($companies_with_access, $record->company_id);
3745
            }
3746
 
3747
            if(!in_array($record->topic_id,$topics_with_access)) {
3748
                array_push($topics_with_access, $record->topic_id);
3749
            }
3750
 
3751
            if(!in_array($record->capsule_id,$capsules_with_access)) {
3752
                array_push($capsules_with_access, $record->capsule_id);
3753
            }
3754
        }
3755
 
3756
 /*
3757
        echo '$companies_with_access ' . PHP_EOL;
3758
        print_r($companies_with_access);
3759
 
3760
        echo '$topics_with_access ' . PHP_EOL;
3761
        print_r($topics_with_access);
3762
 
3763
        echo '$capsules_with_access' . PHP_EOL;
3764
        print_r($capsules_with_access);
3765
        */
3766
 
3767
        $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
3768
        foreach($companies_with_access as $company_id)
3769
        {
3770
            $companyService =  $companyServiceMapper->fetchOneActiveByCompanyIdAndServiceId($company_id, Service::MICRO_LEARNING);
3771
 
3772
            //print_r($companyService); exit;
3773
 
3774
            if(!$companyService) {
3775
                continue;
3776
            }
3777
 
3778
 
3779
            if(isset($companies[$companyService->company_id])) {
3780
                $company = $companies[$companyService->company_id];
3781
            } else {
3782
                $company = $companyMapper->fetchOne($companyService->company_id);
3783
                $companies[$companyService->company_id] = $company;
3784
            }
3785
 
3786
            $topics = $topicMapper->fetchAllActiveByCompanyId($company_id);
3787
            foreach($topics as $topic)
3788
            {
3789
                if(!in_array($topic->id, $topics_with_access)) {
3790
                    continue;
3791
                }
3792
 
3793
                $record_capsules = [];
3794
                $capsules = $capsuleMapper->fetchAllActiveByCompanyIdAndTopicId($topic->company_id, $topic->id);
3795
                foreach($capsules as $capsule)
3796
                {
3797
                    if(!in_array($capsule->id, $capsules_with_access)) {
3798
                        continue;
3799
                    }
3800
 
3801
 
3802
                    $record_slides = [];
3803
                    $slides = $slideMapper->fetchAllByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
3804
                    foreach($slides as $slide)
3805
                    {
3806
                        if($slide->type == CompanyMicrolearningSlide::TYPE_QUIZ) {
3807
                            if(!in_array($slide->quiz_id, $quizzes_with_access)) {
3808
                                array_push($quizzes_with_access, $slide->quiz_id);
3809
                            }
3810
 
3811
                            if(isset($quizzes[$slide->quiz_id])) {
3812
                                $quiz = $quizzes[$slide->quiz_id];
3813
 
3814
                            } else {
3815
                                $quiz = $quizMapper->fetchOne($slide->quiz_id);
3816
                                $quizzes[$slide->quiz_id] =  $quiz;
3817
                            }
3818
                        } else {
3819
                            $quiz = null;
3820
                        }
3821
 
3822
 
3823
                        $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $slide->added_on);
3824
                        $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $slide->updated_on);
3825
 
3826
                        array_push($record_slides, [
3827
                            'uuid' => $slide->uuid,
3828
                            'quiz_uuid' => $quiz ? $quiz->uuid : '',
3829
                            'name' => $slide->name ? $slide->name : '',
3830
                            'description' => $slide->description ? $slide->description : '',
3831
                            'position' => $slide->order,
3832
                            'type' => $slide->type,
3833
                            'background' => $slide->background ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-slide', 'code' => $slide->uuid, 'filename' => $slide->background], ['force_canonical' => true]) : '',
3834
                            'file' => $slide->file ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-slide', 'code' => $slide->uuid, 'filename' => $slide->file], ['force_canonical' => true]) : '',
3835
                            'added_on'  => $dtAddedOn->format($serviceDatetimeFormat),
3836
                            'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
3837
                        ]);
3838
                    }
3839
 
3840
                    $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $capsule->added_on);
3841
                    $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $capsule->updated_on);
3842
 
3843
                    $dataCountrAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->topic_id, $capsule->id);
3844
 
3845
 
3846
 
3847
                    array_push($record_capsules, [
3848
                        'uuid' => $capsule->uuid,
3849
                        'name' => $capsule->name ? $capsule->name : '',
3850
                        'description' => $capsule->description ? $capsule->description : '',
3851
                        'image' => $capsule->image ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-capsule', 'code' => $capsule->uuid, 'filename' => $capsule->image ], ['force_canonical' => true])  : '',
3852
                        'position' => $capsule->order,
3853
                        'slides' => $record_slides,
3854
                        'link_comments' => $this->url()->fromRoute('services/microlearning/capsules/comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
3855
                        'link_comment_add' => $this->url()->fromRoute('services/microlearning/capsules/comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
3856
                        'total_comments' => strval($dataCountrAndRatingAverage['total_comments']),
3857
                        'total_rating' => strval($dataCountrAndRatingAverage['total_rating']),
3858
                        'added_on'  => $dtAddedOn->format($serviceDatetimeFormat),
3859
                        'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
3860
                    ]);
3861
                }
3862
 
3863
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $topic->added_on);
3864
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $topic->updated_on);
3865
 
3866
                array_push($data['topics'], [
3867
                    'uuid' => $topic->uuid,
3868
                    'name' => $topic->name ? $topic->name : '',
3869
                    'description' => $topic->description ? $topic->description : '',
3870
                    'image' => $topic->image ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-topic', 'code' => $topic->uuid, 'filename' => $topic->image ], ['force_canonical' => true]) : '',
3871
                    'position' => $topic->order,
3872
                    'company_uuid' => $company->uuid,
3873
                    'company_name' => $company->name,
3874
                    'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
3875
                    'capsules' => $record_capsules,
3876
                    'added_on'  => $dtAddedOn->format($serviceDatetimeFormat),
3877
                    'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
3878
 
3879
                ]);
3880
 
3881
 
3882
 
3883
 
3884
            }
3885
        }
3886
 
3887
 
3888
 
3889
        foreach($quizzes_with_access as $quiz_id)
3890
        {
3891
            if(isset($quizzes[$quiz_id])) {
3892
                $quiz = $quizzes[$quiz_id];
3893
            } else {
3894
                $quiz = $quizMapper->fetchOne($quiz_id);
3895
                array_push($quizzes, $quiz);
3896
            }
3897
 
3898
            if(isset($companies[$quiz->company_id])) {
3899
                $company = $companies[$quiz->company_id];
3900
            } else {
3901
                $company = $companyMapper->fetchOne($quiz->company_id);
3902
                $companies[$quiz->company_id] = $company;
3903
            }
3904
 
3905
 
3906
            $record_questions = [];
3907
            $questions = $questionMapper->fetchAllByQuizId($quiz->id);
3908
            foreach($questions as $question)
3909
            {
3910
                $record_answers = [];
3911
 
3912
                $answers = $answerMapper->fetchAllByQuizIdAndQuestionId($question->quiz_id, $question->id);
3913
                foreach($answers as $answer)
3914
                {
3915
 
3916
                    $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->added_on);
3917
                    $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->updated_on);
3918
 
3919
                    array_push($record_answers, [
3920
                        'uuid' => $answer->uuid,
3921
                        'text' => trim($answer->text),
3922
                        'correct' => $answer->correct ? $answer->correct  : 0 ,
3923
                        'points' => strval(intval($answer->points, 10)),
3924
                        'added_on'  => $dtAddedOn->format($serviceDatetimeFormat),
3925
                        'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
3926
                    ]);
3927
                }
3928
 
3929
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->added_on);
3930
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->updated_on);
3931
 
3932
                array_push($record_questions, [
3933
                    'uuid'          => $question->uuid,
3934
                    'text'          => trim($question->text),
3935
                    'type'          => $question->type,
3936
                    'maxlength'     => strval($question->maxlength),
3937
                    'points'        => strval($question->points),
3938
                    'answers'       => $record_answers,
3939
                    'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
3940
                    'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
3941
                ]);
3942
            }
3943
 
3944
            $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->added_on);
3945
            $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->updated_on);
3946
 
3947
 
3948
            array_push($data['quizzes'], [
3949
                'uuid' => $quiz->uuid,
3950
                'name' => $quiz->name,
3951
                'text' => trim($quiz->text ? $quiz->text : ''),
3952
                'failed' => trim($quiz->failed ? $quiz->failed : ''),
3953
                'points' => strval($quiz->points),
3954
                'minimum_points_required' => strval($quiz->minimum_points_required),
3955
                'max_time' => $quiz->max_time ? $quiz->max_time : 5,
3956
                'company_uuid' => $company->uuid,
3957
                'company_name' => $company->name,
3958
                'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
3959
                'questions'     => $record_questions,
3960
                'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
3961
                'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
3962
            ]);
3963
        }
3964
 
3965
        $companyExtendUserMapper = CompanyMicrolearningExtendUserMapper::getInstance($this->adapter);
3966
        $companyExtendUserCompanyMapper = CompanyMicrolearningExtendUserCompanyMapper::getInstance($this->adapter);
3967
        $companyExtendUserFunctionMapper = CompanyMicrolearningExtendUserFunctionMapper::getInstance($this->adapter);
3968
        $companyExtendUserGroupMapper = CompanyMicrolearningExtendUserGroupMapper::getInstance($this->adapter);
3969
        $companyExtendUserInstitutionMapper = CompanyMicrolearningExtendUserInstitutionMapper::getInstance($this->adapter);
3970
        $companyExtendUserPartnerMapper = CompanyMicrolearningExtendUserPartnerMapper::getInstance($this->adapter);
3971
        $companyExtendUserProgramMapper = CompanyMicrolearningExtendUserProgramMapper::getInstance($this->adapter);
3972
        $companyExtendUserStudentTypeMapper = CompanyMicrolearningExtendUserStudentTypeMapper::getInstance($this->adapter);
3973
        $companyExtendUserSectorMapper = CompanyMicrolearningExtendUserSectorMapper::getInstance($this->adapter);
3974
 
3975
        $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
3976
        foreach($companies_with_access as $company_id)
3977
        {
3978
            $companyService =  $companyServiceMapper->fetchOneActiveByCompanyIdAndServiceId($company_id, Service::MICRO_LEARNING);
3979
 
3980
            //print_r($companyService); exit;
3981
 
3982
            if(!$companyService) {
3983
                continue;
3984
            }
3985
 
3986
 
3987
            if(isset($companies[$companyService->company_id])) {
3988
                $company = $companies[$companyService->company_id];
3989
            } else {
3990
                $company = $companyMapper->fetchOne($companyService->company_id);
3991
                $companies[$companyService->company_id] = $company;
3992
            }
3993
 
3994
            if(!$company) {
3995
                continue;
3996
            }
3997
 
3998
            $record = [
3999
                'company_uuid' => $company->uuid,
4000
                'company_name' => $company->name,
4001
                'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
4002
                'details' => [],
4003
            ];
4004
 
4005
            $companyExtendUser = $companyExtendUserMapper->fetchOneByCompanyIdAndUserId($company->id, $user->id);
4006
            if(!$companyExtendUser) {
4007
                continue;
4008
            }
4009
 
4010
            if($companyExtendUser->extend_company_id) {
4011
 
4012
                $extendedCompany = $companyExtendUserCompanyMapper->fetchOne($companyExtendUser->company_id);
4013
                if($extendedCompany) {
4014
                    array_push($record['details'],[
4015
                        'uuid' => $extendedCompany->uuid,
4016
                        'label' => 'LABEL_COMPANY',
4017
                        'value' => $extendedCompany->name
4018
                    ]);
4019
                }
4020
            }
4021
 
4022
            if($companyExtendUser->extend_function_id) {
4023
                $extendedFunction = $companyExtendUserFunctionMapper->fetchOne($companyExtendUser->extend_function_id);
4024
                if($extendedFunction) {
4025
                    array_push($record['details'],[
4026
                        'uuid' => $extendedFunction->uuid,
4027
                        'label' => 'LABEL_FUNCTION',
4028
                        'value' => $extendedFunction->name
4029
                    ]);
4030
                }
4031
            }
4032
 
4033
            if($companyExtendUser->extend_group_id) {
4034
                $extendedGroup = $companyExtendUserGroupMapper->fetchOne($companyExtendUser->extend_group_id);
4035
                if($extendedGroup) {
4036
                    array_push($record['details'],[
4037
                        'uuid' => $extendedGroup->uuid,
4038
                        'label' => 'LABEL_GROUP',
4039
                        'value' => $extendedGroup->name
4040
                    ]);
4041
                }
4042
            }
4043
 
4044
            if($companyExtendUser->extend_institution_id) {
4045
                $extendedInstitution= $companyExtendUserInstitutionMapper->fetchOne($companyExtendUser->extend_institution_id);
4046
                if($extendedInstitution) {
4047
                    array_push($record['details'],[
4048
                        'uuid' => $extendedInstitution->uuid,
4049
                        'label' => 'LABEL_INSTITUTION',
4050
                        'value' => $extendedInstitution->name
4051
                    ]);
4052
                }
4053
            }
4054
 
4055
            if($companyExtendUser->extend_program_id) {
4056
                $extendedProgram = $companyExtendUserProgramMapper->fetchOne($companyExtendUser->extend_program_id);
4057
                if($extendedProgram) {
4058
                    array_push($record['details'],[
4059
                        'uuid' => $extendedProgram->uuid,
4060
                        'label' => 'LABEL_PROGRAM',
4061
                        'value' => $extendedProgram->name
4062
                    ]);
4063
 
4064
                }
4065
            }
4066
 
4067
            if($companyExtendUser->extend_sector_id) {
4068
                $extendedSector = $companyExtendUserSectorMapper->fetchOne($companyExtendUser->extend_sector_id);
4069
                if($extendedSector) {
4070
                    array_push($record['details'],[
4071
                        'uuid' => $extendedSector->uuid,
4072
                        'label' => 'LABEL_SECTOR',
4073
                        'value' => $extendedSector->name
4074
                    ]);
4075
                }
4076
            }
4077
 
4078
            if($companyExtendUser->extend_partner_id) {
4079
                $extendedPartner = $companyExtendUserPartnerMapper->fetchOne($companyExtendUser->extend_partner_id);
4080
                if($extendedPartner) {
4081
                    array_push($record['details'],[
4082
                        'uuid' => $extendedPartner->uuid,
4083
                        'label' => 'LABEL_PARTNER',
4084
                        'value' => $extendedPartner->name
4085
                    ]);
4086
                }
4087
            }
4088
 
4089
            if($companyExtendUser->extend_student_type_id) {
4090
                $extendedStudentType = $companyExtendUserStudentTypeMapper->fetchOne($companyExtendUser->extend_student_type_id);
4091
                if($extendedStudentType) {
4092
                    array_push($record['details'],[
4093
                        'uuid' => $extendedStudentType->uuid,
4094
                        'label' => 'LABEL_TYPE',
4095
                        'value' => $extendedStudentType->name
4096
                    ]);
4097
                }
4098
            }
4099
 
4100
            array_push($data['extended'], $record);
4101
        }
4102
 
4103
        return $data;
4104
    }
4105
 
4106
 
4107
    /**
4108
     *
4109
     * @param string $filename
4110
     * @param boolean $retbytes
4111
     * @return boolean|number
4112
     */
4113
    private function readfile_chunked($filename, $retbytes = true) {
4114
        $buffer = '';
4115
        $cnt =0;;
4116
        $handle = fopen($filename,'rb');
4117
        if ($handle === false) {
4118
            return false;
4119
        }
4120
        while (!feof($handle)) {
4121
            $buffer = fread($handle, self::CHUNK_SIZE);
4122
            echo $buffer;
4123
            ob_flush();
4124
            flush();
4125
            if ($retbytes) {
4126
                $cnt += strlen($buffer);
4127
            }
4128
        }
4129
        $status = fclose($handle);
4130
        if ($retbytes && $status) {
4131
            return $cnt; // return num. bytes delivered like readfile() does.
4132
        }
4133
        return $status;
4134
    }
4135
}
4136
 
4137