Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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