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