Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 2446 | Rev 2498 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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