Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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