Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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