Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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