Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

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