Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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