Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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