Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 4777 | Rev 6849 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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