Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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