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