Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 228 | Rev 231 | 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");
911
                error_log("Device UUID : ");
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
 
933
                $emailDecrypted = AesCipher::decrypt($device->aes,$email);
934
                $passwordDecrypted = AesCipher::decrypt($device->aes,$password);
935
                if($emailDecrypted->hasError() || $passwordDecrypted->hasError()) {
936
                    return new JsonModel([
937
                        'success' => false,
938
                        'data' => 'ERROR_WEBSERVICE_PASSWORD_ENCRYPTION_FAILED',
939
                    ]);
940
                }
941
 
942
                $email = $emailDecrypted->getData();
943
                $password = $passwordDecrypted->getData();
229 efrain 944
            } else {
945
                $email   = filter_var($email, FILTER_SANITIZE_EMAIL);
219 efrain 946
            }
1 www 947
 
948
 
949
            $authAdapter = new AuthAdapter($this->adapter);
950
            $authAdapter->setData($email, $password);
951
 
952
            $authService = new AuthenticationService();
953
            $result = $authService->authenticate($authAdapter);
954
 
955
            if($result->getCode() == AuthResult::SUCCESS) {
956
 
957
                $userMapper = UserMapper::getInstance($this->adapter);
958
                $user = $userMapper->fetchOneByEmail($email);
959
 
960
 
961
                $device->user_id    = $user->id;
962
                $device->ip         = Functions::getUserIP();
963
                if($deviceMapper->update($device)) {
964
 
965
                    $ip = Functions::getUserIP();
966
 
967
                    $deviceHistoryMapper = DeviceHistoryMapper::getInstance($this->adapter);
968
                    $deviceHistory = $deviceHistoryMapper->fetchOneByDeviceIdAndUserIdAndIp($device->id, $user->id, $ip);
969
                    if($deviceHistory) {
970
                        $deviceHistoryMapper->update($deviceHistory);
971
                    } else {
972
                        $deviceHistory = new DeviceHistory();
973
                        $deviceHistory->device_id = $device->id;
974
                        $deviceHistory->user_id = $user->id;
975
                        $deviceHistory->ip = $ip;
976
                        $deviceHistoryMapper->insert($deviceHistory);
977
                    }
978
 
979
                    $pushMapper = PushMapper::getInstance($this->adapter);
980
 
981
                    $userDevices =  $deviceMapper->fetchAllByUserId($user->id);
982
                    foreach($userDevices as $userDevice)
983
                    {
984
 
985
 
986
                        if($userDevice->id != $device->id && $userDevice->token) {
987
 
988
                            $push = new Push();
989
                            $push->status = Push::STATUS_PENDING;
990
                            $push->data = json_encode([
991
                                'server' => [
992
                                    'key' =>   $application->key
993
                                 ],
994
                                 'push' => [
995
                                    'registration_ids'   => [
996
                                        $userDevice->token,
997
                                     ],
998
                                     /*'notification' => [
999
                                         'body' =>  'Se registro un inicio de sessión desde otro dispositivo',
1000
                                         'title' => 'Inicio de sessión',
1001
                                         'vibrate' => 1,
1002
                                         'sound' =>  1
1003
                                     ],*/
1004
                                    'data' => [
1005
                                        'command' => 'signout'
1006
                                    ]
1007
                                 ]
1008
                             ]);
1009
 
1010
                            $pushMapper->insert($push);
1011
 
1012
                        }
1013
                    }
1014
 
1015
 
1016
                    $companyUsers = [];
1017
                    $companyMicrolearningCapsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
1018
                    $capsules = $companyMicrolearningCapsuleUserMapper->fetchAllActiveByUserId($user->id);
1019
                    foreach($capsules as $capsule)
1020
                    {
1021
 
1022
 
1023
 
1024
                        if(empty($companyUsers[$capsule->company_id])) {
1025
                            $companyUsers[$capsule->company_id] = $capsule->updated_on;
1026
                        } else {
1027
 
1028
                            if($capsule->updated_on > $companyUsers[$capsule->company_id]) {
1029
                                $companyUsers[$capsule->company_id] = $capsule->updated_on;
1030
                            }
1031
 
1032
                        }
1033
 
1034
                    }
1035
 
1036
                    $companyMicrolearningUserMapper = CompanyMicrolearningUserMapper::getInstance($this->adapter);
1037
 
1038
                    $maxDateChanges = $companyMicrolearningUserMapper->fetchMaxDateChanges($user->id);
1039
                    if(!$maxDateChanges) {
1040
 
1041
 
1042
                        $maxDateChanges = '';
1043
                        foreach($companyUsers as $company_id => $update_on)
1044
                        {
1045
 
1046
                            $maxDateChanges = $maxDateChanges < $update_on ? $update_on : $maxDateChanges;
1047
 
1048
                            $companyMicrolearningUser = new CompanyMicrolearningUser();
1049
                            $companyMicrolearningUser->company_id = $company_id;
1050
                            $companyMicrolearningUser->user_id = $user->id;
1051
                            $companyMicrolearningUser->added_on = $update_on;
1052
                            $companyMicrolearningUser->updated_on = $update_on;
1053
 
1054
                            $companyMicrolearningUserMapper->insert($companyMicrolearningUser);
1055
                        }
1056
 
1057
 
1058
                    }
1059
 
1060
 
1061
 
1062
                   $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $maxDateChanges);
1063
                   if($dt) {
1064
                       $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1065
                       $maxDateChanges = $dt->format($serviceDatetimeFormat);
1066
                   } else {
1067
                       $maxDateChanges = '';
1068
                   }
1069
 
1070
 
1071
                    $data = [
1072
                        'success'   => true,
1073
                        'data'      =>[
1074
                            'user' => [
1075
                                'uuid' => $user->uuid,
1076
                                'first_name' => $user->first_name,
1077
                                'last_name' => $user->last_name,
1078
                                'email' => $user->email,
1079
                                'image' => $this->url()->fromRoute('services/storage',['type' => 'user', 'code' => $user->uuid, 'filename' => $user->image], ['force_canonical' => true]),
1080
 
1081
                             ],
1082
                            'max_date_changes' => $maxDateChanges,
1083
                            'device' => [
1084
                                'aes' => $device->aes,
1085
                                'password' => $device->password
1086
                            ]
1087
 
1088
                        ]
1089
                    ];
1090
 
1091
                    if($application->id == Application::TWOGETSKILLS) {
1092
                        $dataSync = $this->getSyncData($user);
1093
 
1094
                        $data['data']['topics'] = $dataSync['topics'];
1095
                        $data['data']['quizzes'] = $dataSync['quizzes'];
1096
                        $data['data']['userlog'] = $dataSync['userlog'];
1097
                        $data['data']['progress'] = $dataSync['progress'];
52 efrain 1098
                        $data['data']['extended'] = $dataSync['extended'];
1 www 1099
                    }
1100
 
1101
 
1102
 
1103
                    return new JsonModel($data);
1104
 
1105
 
1106
 
1107
                } else {
1108
                    return new JsonModel([
1109
                        'success' => false,
1110
                        'data' => 'ERROR_THERE_WAS_AN_ERROR',
1111
                    ]);
1112
                }
1113
 
1114
 
1115
            } else {
1116
                $message = $result->getMessages()[0];
1117
                if(!in_array($message, ['ERROR_USER_NOT_FOUND', 'ERROR_USER_PROVIDER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
1118
                    'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
1119
                    'ERROR_ENTERED_PASS_INCORRECT_1'])) {
1120
                }
1121
 
1122
                switch($message)
1123
                {
1124
                    case 'ERROR_USER_NOT_FOUND' :
1125
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1126
                        break;
1127
 
1128
                    case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED' :
1129
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1130
                        break;
1131
 
1132
                    case 'ERROR_USER_IS_BLOCKED' :
1133
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1134
                        break;
1135
 
1136
                    case 'ERROR_USER_IS_INACTIVE' :
1137
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1138
                        break;
1139
 
1140
 
1141
                    case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1142
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1143
                        break;
1144
 
1145
 
1146
                    case 'ERROR_ENTERED_PASS_INCORRECT_2' :
1147
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1148
                        break;
1149
 
1150
 
1151
                    case 'ERROR_ENTERED_PASS_INCORRECT_1' :
1152
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1153
                        break;
1154
 
1155
 
1156
                    default :
1157
                        $message = 'ERROR_UNKNOWN';
1158
                        $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1159
                        break;
1160
 
1161
 
1162
                }
1163
 
1164
 
1165
                return new JsonModel([
1166
                    'success'   => false,
1167
                    'data'   => $message
1168
                ]);
1169
            }
1170
 
1171
        }
1172
 
1173
        return new JsonModel([
1174
            'success' => false,
1175
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1176
        ]);
1177
 
1178
    }
1179
 
1180
 
1181
 
1182
 
1183
    public function storageAction()
1184
    {
1185
 
1186
        // Get the file name from GET variable.
1187
        $code       = $this->params()->fromRoute('code', '');
1188
        $fileName   = $this->params()->fromRoute('filename', '');
1189
        $type       = $this->params()->fromRoute('type', 'user');
1190
 
1191
 
1192
        $no_image = $this->config['leaderslinked.images_default.no_image'];
1193
        $path = '';
1194
        switch($type)
1195
        {
1196
            case 'user' :
1197
                $no_image = $this->config['leaderslinked.images_default.user_image'];
1198
                $path = $this->config['leaderslinked.fullpath.user'];
1199
                break;
1200
 
1201
 
1202
            case 'user-profile' :
1203
                $no_image = $this->config['leaderslinked.images_default.user_profile'];
1204
                $path = $this->config['leaderslinked.fullpath.user'];
1205
                break;
1206
 
1207
            case 'user-cover' :
1208
                $no_image = $this->config['leaderslinked.images_default.user_cover'];
1209
                $path = $this->config['leaderslinked.fullpath.user'];
1210
                break;
1211
 
1212
            case 'company' :
1213
                $no_image = $this->config['leaderslinked.images_default.company_profile'];
1214
                $path = $this->config['leaderslinked.fullpath.company'];
1215
                break;
1216
 
1217
            case 'company-cover' :
1218
                $no_image = $this->config['leaderslinked.images_default.company_cover'];
1219
                $path = $this->config['leaderslinked.fullpath.company'];
1220
                break;
1221
 
1222
            case 'group' :
1223
                $no_image = $this->config['leaderslinked.images_default.group_profile'];
1224
                $path = $this->config['leaderslinked.fullpath.group'];
1225
                break;
1226
 
1227
            case 'group-cover' :
1228
                $no_image = $this->config['leaderslinked.images_default.group_cover'];
1229
                $path = $this->config['leaderslinked.fullpath.group'];
1230
                break;
1231
 
1232
            case 'job' :
1233
                $path = $this->config['leaderslinked.fullpath.job'];
1234
                break;
1235
 
1236
            case 'chat' :
1237
                $path = $this->config['leaderslinked.fullpath.chat'];
1238
                break;
1239
 
1240
            case 'feed' :
1241
                $path = $this->config['leaderslinked.fullpath.feed'];
1242
                break;
1243
 
1244
            case 'post' :
1245
                $path = $this->config['leaderslinked.fullpath.post'];
1246
                break;
1247
 
1248
            case 'microlearning-topic' :
1249
                $path = $this->config['leaderslinked.fullpath.microlearning_topic'];
1250
                break;
1251
 
1252
            case 'microlearning-capsule' :
1253
                $path = $this->config['leaderslinked.fullpath.microlearning_capsule'];
1254
                break;
1255
 
1256
            case 'microlearning-slide' :
1257
                $path = $this->config['leaderslinked.fullpath.microlearning_slide'];
1258
                break;
1259
 
1260
            default :
1261
                $path = $this->config['leaderslinked.fullpath.image'];
1262
                break;
1263
 
1264
        }
1265
        if($code && $fileName) {
1266
            $request_fullpath = $path . $code . DIRECTORY_SEPARATOR . $fileName;
1267
        } else {
1268
            $request_fullpath = $no_image;
1269
        }
1270
 
1271
        if(empty($fileName)) {
1272
            $extensions     = explode('.',$request_fullpath);
1273
            $extension      = strtolower(trim($extensions[count($extensions)-1]));
1274
            if ($extension=='jpg' || $extension=='jpeg' || $extension=='gif' || $extension == 'png') {
1275
                $request_fullpath =  $no_image;
1276
            }
1277
        }
1278
 
1279
 
1280
        if(file_exists($request_fullpath)) {
1281
 
1282
            // Try to open file
1283
            if (!is_readable($request_fullpath)) {
1284
                return $this->getResponse()->setStatusCode(500);
1285
            }
1286
 
1287
            // Get file size in bytes.
1288
            $fileSize = filesize($request_fullpath);
1289
 
1290
            // Get MIME type of the file.
1291
            $mimeType = mime_content_type($request_fullpath);
1292
            if($mimeType===false) {
1293
                $mimeType = 'application/octet-stream';
1294
            }
1295
 
1296
            $request_fullpath = trim($request_fullpath);
1297
            $length = strlen($request_fullpath);
1298
            if(substr($request_fullpath, $length - 1) == '/') {
1299
                $request_fullpath = substr($request_fullpath, 0, $length - 1);
1300
            }
1301
 
1302
 
1303
            $filename = basename($request_fullpath);
1304
 
1305
            header('Content-type: ' . $mimeType);
1306
            readfile($request_fullpath);
1307
 
1308
 
1309
            exit;
1310
            //header("X-Sendfile: $request_fullpath");
1311
            //header("Content-type: application/octet-stream");
1312
            //header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
1313
 
1314
 
1315
            /*
1316
 
1317
 
1318
            if ($fd = fopen ($request_fullpath, "r")) {
1319
 
1320
                $fsize = filesize($request_fullpath);
1321
 
1322
                header("Content-type: $mimeType");
1323
                header("Accept-Ranges: bytes");
1324
 
1325
                //header("Content-Disposition: attachment; filename=\"$filename\"");
1326
 
1327
                header("Content-length: $fsize");
1328
                header("Cache-control: private");
1329
 
1330
                while(!feof($fd)) {
1331
                    $buffer = fread($fd, 2048);
1332
                    echo $buffer;
1333
                }
1334
            }
1335
 
1336
            fclose ($fd);
1337
            exit;*/
1338
 
1339
 
1340
            /*
1341
             $fileContent = file_get_contents($request_fullpath);
1342
            $response = $this->getResponse();
1343
            $headers = $response->getHeaders();
1344
            $headers->addHeaderLine('Accept-Ranges: bytes');
1345
            $headers->addHeaderLine('Content-type: ' . $mimeType);
1346
            $headers->addHeaderLine('Content-length: ' . $fileSize);
1347
 
1348
            /*
1349
            Date: Tue, 13 Jul 2021 03:11:42 GMT
1350
            Server: Apache/2.4.41 (Ubuntu)
1351
            Last-Modified: Mon, 28 Jun 2021 16:43:04 GMT
1352
            ETag: "54e4-5c5d62eed581e"
1353
            Accept-Ranges: bytes
1354
            Content-Length: 21732
1355
            Cache-Control: max-age=1
1356
            Expires: Tue, 13 Jul 2021 03:11:43 GMT
1357
            Keep-Alive: timeout=5, max=100
1358
            Connection: Keep-Alive
1359
            Content-Type: audio/mpeg
1360
            */
1361
 
1362
            /*
1363
            if($fileContent!==false) {
1364
                error_log($_SERVER['REQUEST_URI']);
1365
                error_log($request_fullpath);
1366
                return $response->setContent($fileContent);
1367
 
1368
                header('Content-Type: '.$mimeType );
1369
                readfile_chunked($filename);
1370
                exit;
1371
 
1372
            } else {
1373
                error_log('500');
1374
                $this->getResponse()->setStatusCode(500);
1375
                return;
1376
            }*/
1377
        } else {
1378
            error_log('404');
1379
            return $this->getResponse()->setStatusCode(404);
1380
        }
1381
 
1382
        return $this->getResponse();
1383
    }
1384
 
1385
 
1386
    public function syncAction()
1387
    {
1388
        $request = $this->getRequest();
1389
 
1390
        if($request->isPost()) {
1391
 
221 efrain 1392
 
1 www 1393
 
1394
 
1395
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1396
 
1397
            $device_uuid    = filter_var($this->params()->fromPost('device_uuid', ''), FILTER_SANITIZE_STRING);
1398
            $sync_id        = filter_var($this->params()->fromPost('sync_id', ''), FILTER_SANITIZE_NUMBER_INT);
1399
            $data           = $this->params()->fromPost('data', '');
1400
 
1401
 
1402
 
41 efrain 1403
            //error_log('device_uuid = ' . $device_uuid);
1404
            //error_log('sync_id = ' . $sync_id);
1405
            //error_log(print_r($data, true));
221 efrain 1406
 
1407
 
1408
            $rawdata = file_get_contents("php://input");
1409
            error_log('$rawdata = ' . $rawdata );
1 www 1410
 
1411
            $ok = $device_uuid && strlen($device_uuid) == 36 && $data && $sync_id;
1412
 
1413
            if(!$ok) {
1414
                return new JsonModel([
1415
                    'success' => false,
1416
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID',
1417
                ]);
1418
            }
1419
 
1420
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
1421
            $device = $deviceMapper->fetchOne($device_uuid);
1422
 
1423
 
1424
            if(!$device) {
1425
                return new JsonModel([
1426
                    'success' => false,
1427
                    'data' => 'ERROR_DEVICE_NOT_FOUND'
1428
                ]);
1429
            } else {
1430
                $device->ip = Functions::getUserIP();
1431
                $deviceMapper->update($device);
1432
            }
1433
 
44 efrain 1434
 
41 efrain 1435
 
44 efrain 1436
 
1437
 
1438
            $data = json_decode($data, true);
1439
            $sync_type      = isset($data['sync_type']) ? filter_var($data['sync_type'], FILTER_SANITIZE_STRING) : '';
1440
            $user_uuid      = isset($data['user_uuid']) ? filter_var($data['user_uuid'], FILTER_SANITIZE_STRING) : '';
1441
            $company_uuid   = isset($data['company_uuid']) ? filter_var($data['company_uuid'], FILTER_SANITIZE_STRING) :  '';
1442
 
1443
 
41 efrain 1444
            $syncLog = new SyncLog();
224 efrain 1445
            $syncLog->data = json_encode($data);
44 efrain 1446
            $syncLog->type = $sync_type;
41 efrain 1447
            $syncLog->device_uuid = $device->id;
1448
            $syncLog->ip = Functions::getUserIP();
1449
 
222 efrain 1450
 
224 efrain 1451
 
222 efrain 1452
 
41 efrain 1453
            $syncLogMapper = SyncLogMapper::getInstance($this->adapter);
1454
            $syncLogMapper->insert($syncLog);
1455
 
1 www 1456
 
1457
    //
1458
 
1459
            if($user_uuid && $device->application_id = Application::TWOGETSKILLS  && $company_uuid && in_array($sync_type, ['microlearning-progress', 'microlearning-userlog', 'microlearning-quiz'])) {
1460
                $userMapper = UserMapper::getInstance($this->adapter);
1461
                $user = $userMapper->fetchOneByUuid($user_uuid);
1462
 
1463
                if(!$user) {
1464
                    return new JsonModel([
1465
                        'success' => false,
1466
                        'data' => [
1467
                            'sync_id' => $sync_id,
1468
                            'message' => 'ERROR_USER_NOT_FOUND',
1469
                            'fatal' => true
1470
                        ]
1471
                    ]);
1472
                }
1473
 
1474
 
1475
                if($user->status != User::STATUS_ACTIVE) {
1476
                    return new JsonModel([
1477
                        'success' => false,
1478
                        'data' => [
1479
                            'sync_id' => $sync_id,
1480
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
1481
                            'fatal' => true
1482
                        ]
1483
                    ]);
1484
                }
1485
 
1486
                $companyMapper = CompanyMapper::getInstance($this->adapter);
1487
                $company = $companyMapper->fetchOneByUuid($company_uuid);
1488
                if(!$company) {
1489
                    return new JsonModel([
1490
                        'success' => false,
1491
                        'data' => [
1492
                            'sync_id' => $sync_id,
1493
                            'message' => 'ERROR_COMPANY_NOT_FOUND',
1494
                            'fatal' => true
1495
                        ]
1496
                    ]);
1497
                }
1498
 
1499
                if($company->status != Company::STATUS_ACTIVE) {
1500
                    return new JsonModel([
1501
                        'success' => false,
1502
                        'data' => [
1503
                            'sync_id' => $sync_id,
1504
                            'message' => 'ERROR_COMPANY_IS_NOT_FOUND',
1505
                            'fatal' => true
1506
                        ]
1507
                    ]);
1508
                }
1509
 
1510
 
1511
 
1512
 
1513
 
1514
                $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
1515
                $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($company->id, Service::MICRO_LEARNING);
1516
                if(!$companyService) {
1517
                    return new JsonModel([
1518
                        'success' => false,
1519
                        'data' => [
1520
                            'sync_id' => $sync_id,
1521
                            'message' => 'ERROR_COMPANY_SERVICE_NOT_FOUND',
1522
                            'fatal' => true
1523
                        ]
1524
                    ]);
1525
                }
1526
 
1527
                $serviceActive = true;
1528
                $now = date('Y-m-d H:i:s');
1529
                if($companyService->status == CompanyService::ACTIVE) {
1530
 
1531
                    if($now < $companyService->paid_from || $now > $companyService->paid_to) {
1532
                        $serviceActive = false;
1533
                    }
1534
 
1535
                } else {
1536
                    $serviceActive = false;
1537
                }
1538
 
1539
                if( !$serviceActive) {
1540
                    return new JsonModel([
1541
                        'success' => false,
1542
                        'data' => [
1543
                            'sync_id' => $sync_id,
1544
                            'message' => 'ERROR_COMPANY_SERVICE_IS_NOT_ACTIVE',
1545
                            'fatal' => true
1546
                        ]
1547
                    ]);
1548
                }
1549
 
1550
                $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
1551
                $topic_uuid = isset($data['topic_uuid']) ? filter_var($data['topic_uuid'], FILTER_SANITIZE_STRING) :  '';
1552
                if($topic_uuid) {
1553
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
1554
 
1555
                    if(!$topic) {
1556
                        return new JsonModel([
1557
                            'success' => false,
1558
                            'data' => [
1559
                                'sync_id' => $sync_id,
1560
                                'message' => 'ERROR_TOPIC_NOT_FOUND',
1561
                            ]
1562
                        ]);
1563
                    }
1564
 
1565
                    if($topic->company_id != $company->id) {
1566
                        return new JsonModel([
1567
                            'success' => false,
1568
                            'data' => [
1569
                                'sync_id' => $sync_id,
1570
                                'message' => 'ERROR_INVALID_PARAMETERS_TOPIC_COMPANY',
1571
                            ]
1572
                        ]);
1573
                    }
1574
 
1575
                } else {
1576
                    $topic = null;
1577
                }
1578
 
1579
                $capsule_uuid     = isset($data['capsule_uuid']) ? filter_var($data['capsule_uuid'], FILTER_SANITIZE_STRING) :  '';
1580
                $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
1581
                if($capsule_uuid) {
1582
 
1583
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
1584
                    if(!$capsule) {
1585
                        return new JsonModel([
1586
                            'success' => false,
1587
                            'data' => [
1588
                                'sync_id' => $sync_id,
1589
                                'message' => 'ERROR_CAPSULE_NOT_FOUND',
1590
                            ]
1591
                        ]);
1592
                    }
1593
 
1594
                    if(!$topic || $capsule->topic_id != $topic->id) {
1595
                        return new JsonModel([
1596
                            'success' => false,
1597
                            'data' => [
1598
                                'sync_id' => $sync_id,
1599
                                'message' => 'ERROR_INVALID_PARAMETERS_CAPSULE_TOPIC',
1600
                            ]
1601
                        ]);
1602
                    }
1603
                } else {
1604
                    $capsule = null;
1605
                }
1606
 
1607
                if($capsule) {
1608
 
1609
                    $capsuleActive = true;
1610
                    $capsuleMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
1611
                    $capsuleUser = $capsuleMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
1612
 
1613
 
1614
                    $now = date('Y-m-d H:i:s');
1615
                    if($capsuleUser && in_array($capsuleUser->access, [CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED,CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD ])) {
1616
 
1617
 
1618
                        if($capsuleUser->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
1619
 
1620
                            if($now < $capsuleUser->paid_from || $now > $capsuleUser->paid_to) {
1621
                                $capsuleActive = false;;
1622
                            }
1623
                        }
1624
 
1625
                    } else {
1626
                        $capsuleActive = false;
1627
                    }
1628
 
1629
                    if(!$capsuleActive) {
1630
                        return new JsonModel([
1631
                            'success' => false,
1632
                            'data' => [
1633
                                'sync_id' => $sync_id,
1634
                                'message' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
1635
                            ]
1636
                        ]);
1637
                    }
1638
                }
1639
 
1640
                $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
1641
                $slide_uuid      = isset($data['slide_uuid']) ? filter_var($data['slide_uuid'], FILTER_SANITIZE_STRING) :  '';
1642
                if($slide_uuid) {
1643
                    $slide = $slideMapper->fetchOneByUuid($slide_uuid);
1644
                    if(!$slide) {
1645
                        return new JsonModel([
1646
                            'success' => false,
1647
                            'data' => [
1648
                                'sync_id' => $sync_id,
1649
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
1650
                            ]
1651
                        ]);
1652
                    }
1653
 
1654
                    if(!$capsule || $slide->capsule_id != $capsule->id) {
1655
                        return new JsonModel([
1656
                            'success' => false,
1657
                            'data' => [
1658
                                'sync_id' => $sync_id,
1659
                                'message' => 'ERROR_INVALID_PARAMETERS_SLIDE_CAPSULE',
1660
                            ]
1661
                        ]);
1662
                    }
1663
                } else {
1664
                    $slide = null;
1665
                }
1666
 
1667
                if($sync_type == 'microlearning-quiz') {
1668
                    $ok = true;
1669
 
1670
                    $quiz_uuid = isset($data['quiz_uuid']) ? $data['quiz_uuid'] : '';
1671
                    $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
1672
 
1673
                    $quiz = $quizMapper->fetchOneByUuid($quiz_uuid);
1674
                    if(!$quiz) {
1675
                        return new JsonModel([
1676
                            'success' => false,
1677
                            'data' => [
1678
                                'sync_id' => $sync_id,
1679
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
1680
                            ]
1681
                        ]);
1682
                    }
1683
 
1684
                    if(!$capsule || $slide->capsule_id != $capsule->id) {
1685
                        return new JsonModel([
1686
                            'success' => false,
1687
                            'data' => [
1688
                                'sync_id' => $sync_id,
1689
                                'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_SLIDE',
1690
                            ]
1691
                        ]);
1692
                    }
1693
 
1694
                    $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
1695
 
1696
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1697
                    if(!$dt) {
1698
                        $ok = false;
1699
                    } else {
1700
                        $added_on = $dt->format('Y-m-d H:i:s');
1701
                    }
1702
 
1703
 
1704
                    if(isset($data['points'])) {
1705
                        $points = intval($data['points'], 10);
1706
                    } else {
1707
                        $ok = false;
1708
                    }
1709
 
1710
 
1711
                    if(isset($data['pass'])) {
1712
                        $status = $data['pass'] == 'yes' ? CompanyMicrolearningUserQuiz::STATUS_PASS : CompanyMicrolearningUserQuiz::STATUS_FAIL;
1713
                    } else {
1714
                        $ok = false;
1715
                    }
1716
 
1717
 
1718
                    if(!$ok) {
1719
                        return new JsonModel([
1720
                            'success' => false,
1721
                            'data' => [
1722
                                'sync_id' => $sync_id,
1723
                                'message' => 'ERROR_INVALID_PARAMETERS',
1724
                            ]
1725
                        ]);
1726
                    }
1727
 
1728
 
1729
                    $array_response = [];
1730
                    $response = isset($data['response']) ? intval($data['response'], 10) : 0;
1731
                    for($i = 0; $i < $response; $i++)
1732
                    {
1733
                        $question_uuid = isset($data["response_{$i}_question_uuid"]) ? $data["response_{$i}_question_uuid"] : '';
1734
                        $answer_uuid = isset($data["response_{$i}_answer_uuid"]) ? $data["response_{$i}_answer_uuid"] : '';
1735
                        $value = isset($data["response_{$i}_value"]) ?  intval($data["response_{$i}_value"], 10) : 0;
1736
                        $points = isset($data["response_{$i}_points"]) ?  intval($data["response_{$i}_points"], 10) : 0;
1737
 
1738
                        if($question_uuid && $answer_uuid)
1739
                        {
1740
                            array_push($array_response, [
1741
                                'question_uuid' => $question_uuid,
1742
                                'answer_uuid' => $answer_uuid,
1743
                                'value' => $value,
1744
                                'points' => $points
1745
 
1746
                            ]);
1747
                        }
1748
 
1749
 
1750
                    }
1751
 
1752
 
1753
                    $userQuiz = new CompanyMicrolearningUserQuiz();
1754
                    $userQuiz->company_id = $company->id;
1755
                    $userQuiz->topic_id = $topic->id;
1756
                    $userQuiz->capsule_id = $capsule->id;
1757
                    $userQuiz->slide_id = $slide->id;
1758
                    $userQuiz->quiz_id = $quiz->id;
1759
                    $userQuiz->user_id = $user->id;
1760
                    $userQuiz->added_on = $added_on;
1761
                    $userQuiz->points = $points;
1762
                    $userQuiz->status = $status;
1763
                    $userQuiz->response = json_encode($array_response);
1764
 
1765
                    $userQuizMapper = CompanyMicrolearningUserQuizMapper::getInstance($this->adapter);
1766
 
1767
                    if($userQuizMapper->insert($userQuiz)) {
1768
                        return new JsonModel([
1769
                            'success' => true,
1770
                            'data' => [
1771
                                'sync_id' => $sync_id
1772
                            ]
1773
                        ]);
1774
                    } else {
1775
                        return new JsonModel([
1776
                            'success' => false,
1777
                            'data' => [
1778
                                'sync_id' => $sync_id,
1779
                                'message' => $userQuizMapper->getError()
1780
                            ]
1781
                        ]);
1782
                    }
1783
 
1784
                }
1785
 
1786
 
1787
                if($sync_type == 'microlearning-progress') {
1788
                    $ok = true;
1789
 
1790
                    $type = isset($data['type']) ? $data['type'] : '';
1791
                    switch($type)
1792
                    {
1793
                        case CompanyMicrolearningUserProgress::TYPE_TOPIC :
1794
                            if(!$topic) {
1795
                                $ok = false;
1796
                            }
1797
                            break;
1798
 
1799
                        case CompanyMicrolearningUserProgress::TYPE_CAPSULE :
1800
                            if(!$topic || !$capsule) {
1801
                                $ok = false;
1802
                            }
1803
                            break;
1804
 
1805
                        case CompanyMicrolearningUserProgress::TYPE_SLIDE :
1806
                            if(!$topic || !$capsule || !$slide) {
1807
                                $ok = false;
1808
                            }
1809
                            break;
1810
 
1811
                        default :
1812
                            $ok = false;
1813
                            break;
1814
 
1815
                    }
1816
 
1817
 
1818
                    $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
1819
                    $updated_on = isset($data['updated_on'])    ? filter_var($data['updated_on'], FILTER_SANITIZE_STRING) :  '';
1820
 
1821
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1822
                    if(!$dt) {
1823
                        $ok = false;
1824
                    } else {
1825
                        $added_on = $dt->format('Y-m-d H:i:s');
1826
                    }
1827
 
1828
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $updated_on );
1829
                    if(!$dt) {
1830
                        $ok = false;
1831
                    } else {
1832
                        $updated_on = $dt->format('Y-m-d H:i:s');
1833
                    }
1834
 
1835
                    if(!$ok) {
1836
                        return new JsonModel([
1837
                            'success' => false,
1838
                            'data' => [
1839
                                'sync_id' => $sync_id,
1840
                                'message' => 'ERROR_INVALID_PARAMETERS',
1841
                            ]
1842
                        ]);
1843
                    }
1844
 
1845
                           //$progress                   = isset($data['progress'])                  ? floatval($data['progress']) :  0;
1846
                    //$total_slides               = isset($data['total_slides'])              ? intval($data['total_slides'], 10) :  0;
1847
                    //$view_slides                = isset($data['view_slides'])               ? intval($data['view_slides'], 10) :  0;
1848
                    $returning                  = isset($data['returning'])                 ? intval($data['returning'], 10) :  0;
1849
                    $returning_after_completed  = isset($data['returning_after_completed']) ? intval($data['returning_after_completed'], 10) :  0;
1850
                    $completed                  = isset($data['completed'])                 ? intval($data['completed'], 10) :  0;
1851
 
1852
                    $progressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
1853
                    $recordProgress = null;
1854
                    switch($type) {
1855
                        case CompanyMicrolearningUserProgress::TYPE_TOPIC  :
1856
                            $recordProgress = $progressMapper->fetchOneByUserIdAndTopicId($user->id, $topic->id);
1857
 
1858
                            break;
1859
 
1860
                        case CompanyMicrolearningUserProgress::TYPE_CAPSULE  :
1861
                            $recordProgress = $progressMapper->fetchOneByUseridAndCapsuleId($user->id, $capsule->id);
1862
                            break;
1863
 
1864
                        case CompanyMicrolearningUserProgress::TYPE_SLIDE  :
1865
                            $recordProgress = $progressMapper->fetchOneByUserIdAndSlideId($user->id, $slide->id);
1866
                            break;
1867
 
1868
                        default :
1869
                            $recordProgress= null;
1870
                    }
1871
 
1872
 
1873
                    if(!$recordProgress) {
1874
                        $recordProgress = new CompanyMicrolearningUserProgress();
1875
 
1876
                        $recordProgress->user_id    = $user->id;
1877
                        $recordProgress->type       = $type;
1878
                        $recordProgress->company_id = $topic->company_id;
1879
                        $recordProgress->topic_id   = $topic->id;
1880
                        $recordProgress->capsule_id = $capsule ? $capsule->id : null;
1881
                        $recordProgress->slide_id   = $slide ? $slide->id : null;
1882
                        $recordProgress->added_on   = $added_on;
1883
                    }
1884
                    $recordProgress->returning                  = $returning;
1885
                    $recordProgress->returning_after_completed  = $returning_after_completed;
1886
                    $recordProgress->completed                  = $completed;
1887
 
1888
                    if($type == CompanyMicrolearningUserProgress::TYPE_TOPIC ) {
1889
 
1890
                        $capsule_ids = [];
1891
                        $companyMicrolearningCapsuleUser = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
1892
                        $records =  $companyMicrolearningCapsuleUser->fetchAllActiveByUserId($user->id);
1893
                        foreach($records as $record)
1894
                        {
1895
                            if($now >= $record->paid_from || $now <= $capsuleUser->paid_to) {
1896
                                if(!in_array($record->capsule_id, $capsule_ids)) {
1897
                                    array_push($capsule_ids, $record->capsule_id);
1898
                                }
1899
                            }
1900
                        }
1901
 
1902
                        $view_slides    = 0;
1903
                        $total_slides   = 0;
1904
                        foreach($capsule_ids as $capsule_id)
1905
                        {
1906
                            $view_slides    += $progressMapper->fetchCountAllSlideViewedByUserIdAndCapsuleId($user->id, $capsule_id);
1907
                            $total_slides   += $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $topic->id, $capsule_id);
1908
 
1909
                        }
1910
 
1911
 
1912
                        $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
1913
                        $recordProgress->total_slides   = $total_slides;
1914
                        $recordProgress->view_slides    = $view_slides;
1915
                    }
1916
                    else if($type == CompanyMicrolearningUserProgress::TYPE_CAPSULE ) {
1917
                        $view_slides    = $progressMapper->fetchCountAllSlideViewedByUserIdAndCapsuleId($user->id, $capsule->id);
1918
                        $total_slides   = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $capsule->topic_id, $capsule->id);
1919
 
1920
                        $recordProgress->progress       = $total_slides > 0 ? (($view_slides * 100) / $total_slides) : 0;
1921
                        $recordProgress->total_slides   = $total_slides;
1922
                        $recordProgress->view_slides    = $view_slides;
1923
                    }
1924
                    else {
1925
                        $recordProgress->progress       = 0;
1926
                        $recordProgress->total_slides   = 0;
1927
                        $recordProgress->view_slides    = 0;
1928
                    }
1929
 
1930
                    $recordProgress->updated_on = $updated_on;
1931
 
1932
 
1933
 
1934
                    if($recordProgress->id) {
1935
                        $result = $progressMapper->update($recordProgress);
1936
                    } else {
1937
                        $result = $progressMapper->insert($recordProgress);
1938
                    }
1939
 
1940
                    if($result) {
1941
                        return new JsonModel([
1942
                            'success' => true,
1943
                            'data' => [
1944
                                'sync_id' => $sync_id
1945
                            ]
1946
                        ]);
1947
                    } else {
1948
                        return new JsonModel([
1949
                            'success' => false,
1950
                            'data' => [
1951
                                'sync_id' => $sync_id,
1952
                                'message' => $progressMapper->getError()
1953
                            ]
1954
                        ]);
1955
                    }
1956
                }
1957
 
1958
 
1959
 
1960
                if($sync_type == 'microlearning-userlog') {
1961
                    $activity   = isset($data['activity'])      ? filter_var($data['activity'], FILTER_SANITIZE_STRING)  :  '';
1962
                    $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
1963
 
1964
 
1965
                    if(empty($activity)) {
1966
                        $ok = false;
1967
                    }
1968
 
1969
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
1970
                    if(!$dt) {
1971
                        $ok = false;
1972
                    } else {
1973
                        $added_on = $dt->format('Y-m-d H:i:s');
1974
                    }
1975
 
1976
                    if(!$ok) {
1977
                        return new JsonModel([
1978
                            'success' => false,
1979
                            'data' => [
1980
                                'sync_id' => $sync_id,
1981
                                'message' => 'ERROR_INVALID_PARAMETERS',
1982
                            ]
1983
                        ]);
1984
                    }
1985
 
1986
                    $userLog = new CompanyMicrolearningUserLog();
1987
                    $userLog->activity      = $activity;
1988
                    $userLog->user_id       = $user->id;
1989
                    $userLog->company_id    = $topic->company_id;
1990
                    $userLog->topic_id      = $topic->id;
1991
                    $userLog->capsule_id    = $capsule ? $capsule->id : null;
1992
                    $userLog->slide_id      = $slide ? $slide->id : null;
1993
                    $userLog->added_on      = $added_on;
1994
 
1995
 
1996
 
1997
                    $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
1998
                    if($userLogMapper->insert($userLog)) {
1999
                        return new JsonModel([
2000
                            'success' => true,
2001
                            'data' => [
2002
                                'sync_id' => $sync_id
2003
                            ]
2004
                        ]);
2005
                    } else {
2006
                        return new JsonModel([
2007
                            'success' => false,
2008
                            'data' => [
2009
                                'sync_id' => $sync_id,
2010
                                'message' => $userLogMapper->getError()
2011
                            ]
2012
                        ]);
2013
                    }
2014
                }
2015
 
2016
            }
2017
 
2018
 
2019
 
2020
 
2021
            if($user_uuid && $sync_type == 'userlog' && $device->application_id = Application::TWOGETSKILLS) {
2022
 
2023
                $userMapper = UserMapper::getInstance($this->adapter);
2024
                $user = $userMapper->fetchOneByUuid($user_uuid);
2025
 
2026
                if(!$user) {
2027
                    return new JsonModel([
2028
                        'success' => false,
2029
                        'data' => [
2030
                            'sync_id' => $sync_id,
2031
                            'message' => 'ERROR_USER_NOT_FOUND',
2032
                            'fatal' => true
2033
                        ]
2034
                    ]);
2035
                }
2036
 
2037
 
2038
                if($user->status != User::STATUS_ACTIVE) {
2039
                    return new JsonModel([
2040
                        'success' => false,
2041
                        'data' => [
2042
                            'sync_id' => $sync_id,
2043
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
2044
                            'fatal' => true
2045
                        ]
2046
                    ]);
2047
                }
2048
 
2049
                $activity   = isset($data['activity'])      ? filter_var($data['activity'], FILTER_SANITIZE_STRING)  :  '';
2050
                $added_on   = isset($data['added_on'])      ? filter_var($data['added_on'], FILTER_SANITIZE_STRING)  :  '';
2051
 
2052
                if(empty($activity)) {
2053
                    $ok = false;
2054
                }
2055
 
2056
                $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2057
                if(!$dt) {
2058
                    $ok = false;
2059
                } else {
2060
                    $added_on = $dt->format('Y-m-d H:i:s');
2061
                }
2062
 
2063
                if(!$ok) {
2064
                    return new JsonModel([
2065
                        'success' => false,
2066
                        'data' => [
2067
                            'sync_id' => $sync_id,
2068
                            'message' => 'ERROR_INVALID_PARAMETERS',
2069
                        ]
2070
                    ]);
2071
                }
2072
 
2073
                $userLog = new CompanyMicrolearningUserLog();
2074
                $userLog->company_id = null;
2075
                $userLog->user_id = $user->id;
2076
                $userLog->activity = $activity;
2077
                $userLog->added_on = $added_on;
2078
 
2079
 
2080
                $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2081
                if($userLogMapper->insert($userLog)) {
2082
                    return new JsonModel([
2083
                        'success' => true,
2084
                        'data' => [
2085
                            'sync_id' => $sync_id
2086
                        ]
2087
                    ]);
2088
                } else {
2089
                    return new JsonModel([
2090
                        'success' => false,
2091
                        'data' => [
2092
                            'sync_id' => $sync_id,
2093
                            'message' => $userLogMapper->getError()
2094
                        ]
2095
                    ]);
2096
                }
2097
            }
2098
 
2099
            return new JsonModel([
2100
                'success' => true,
2101
                'data' => [
2102
                    'sync_id' => $sync_id
2103
                ]
2104
            ]);
2105
 
2106
        }
2107
 
2108
        return new JsonModel([
2109
            'success' => false,
2110
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2111
        ]);
2112
    }
2113
 
2114
 
2115
    public function syncBatchAction()
2116
    {
2117
        $request = $this->getRequest();
2118
 
2119
        if($request->isPost()) {
2120
 
41 efrain 2121
 
1 www 2122
 
2123
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
2124
 
2125
            $device_uuid = filter_var($this->params()->fromPost('device_uuid', ''), FILTER_SANITIZE_STRING);
2126
            $max_records = filter_var($this->params()->fromPost('max_records', 0), FILTER_SANITIZE_NUMBER_INT);
41 efrain 2127
 
1 www 2128
            $ok = $device_uuid && strlen($device_uuid) == 36 && $max_records;
2129
 
2130
            if(!$ok) {
2131
                return new JsonModel([
2132
                    'success' => false,
2133
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID',
2134
                ]);
2135
            }
2136
 
2137
            $deviceMapper = DeviceMapper::getInstance($this->adapter);
2138
            $device = $deviceMapper->fetchOne($device_uuid);
2139
 
2140
 
2141
            if(!$device) {
2142
                return new JsonModel([
2143
                    'success' => false,
2144
                    'data' => 'ERROR_DEVICE_NOT_FOUND'
2145
                ]);
2146
            } else {
2147
                $device->ip = Functions::getUserIP();
2148
                $deviceMapper->update($device);
2149
            }
41 efrain 2150
 
2151
 
1 www 2152
 
41 efrain 2153
 
2154
            $syncLogMapper = SyncLogMapper::getInstance($this->adapter);
2155
 
2156
 
2157
 
1 www 2158
            $result_sync_ids = [];
2159
 
2160
 
2161
 
2162
 
16 efrain 2163
            $users = [];
2164
            $companies = [];
2165
            $company_services = [];
2166
            $topics = [];
2167
            $capsules = [];
2168
            $capsule_users = [];
2169
            $slides = [];
2170
            $quizzes = [];
2171
            $questions = [];
2172
            $answers = [];
2173
 
2174
            $userMapper = UserMapper::getInstance($this->adapter);
2175
            $companyMapper = CompanyMapper::getInstance($this->adapter);
2176
            $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
2177
            $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
2178
            $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
2179
            $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
2180
            $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
2181
            $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
2182
            $questionMapper = CompanyMicrolearningQuestionMapper::getInstance($this->adapter);
2183
            $answerMapper = CompanyMicrolearningAnswerMapper::getInstance($this->adapter);
2184
 
2185
 
2186
            $userProgressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
2187
            $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2188
 
1 www 2189
            for($i = 1; $i <= $max_records; $i++)
2190
            {
2191
                $sync_id        = filter_var($this->params()->fromPost('record_sync_id' . $i, ''), FILTER_SANITIZE_NUMBER_INT);
2192
                $record_data    = $this->params()->fromPost('record_data' . $i, '');
2193
 
2194
                if(empty($record_data) || empty($sync_id )) {
2195
                    continue;
2196
                }
41 efrain 2197
 
1 www 2198
 
45 efrain 2199
 
1 www 2200
                $record         = json_decode($record_data, true);
2201
                $sync_type      = isset($record['sync_type']) ? filter_var($record['sync_type'],  FILTER_SANITIZE_STRING) : '';
2202
                $user_uuid      = isset($record['user_uuid']) ? filter_var($record['user_uuid'],  FILTER_SANITIZE_STRING) : '';
2203
                $company_uuid   = isset($record['company_uuid']) ? filter_var($record['company_uuid'], FILTER_SANITIZE_STRING) : '';
2204
 
2205
                if(!$sync_id) {
2206
                    continue;
2207
                }
2208
 
45 efrain 2209
                $syncLog = new SyncLog();
2210
                $syncLog->data = $record_data;
2211
                $syncLog->type = $sync_type;
2212
                $syncLog->device_uuid = $device->id;
2213
                $syncLog->ip = Functions::getUserIP();
2214
                $syncLogMapper->insert($syncLog);
2215
 
1 www 2216
                /***** INICIO MICROLEARNING *****/
2217
 
2218
                if($user_uuid && $device->application_id = Application::TWOGETSKILLS  && $company_uuid && in_array($sync_type, ['microlearning-progress', 'microlearning-userlog', 'microlearning-quiz'])) {
2219
 
16 efrain 2220
 
2221
                    if(isset($users[$user_uuid])) {
2222
                        $user = $users[$user_uuid];
2223
                    } else {
2224
 
2225
                        $user = $userMapper->fetchOneByUuid($user_uuid);
2226
                        if($user) {
2227
                            $users[$user_uuid] = $user;
2228
                        }
2229
                    }
2230
 
2231
 
1 www 2232
                    if(!$user) {
2233
                        array_push($result_sync_ids, [
2234
                            'success' => false,
2235
                            'sync_id' => $sync_id,
2236
                            'message' => 'ERROR_USER_NOT_FOUND',
2237
                            'fatal' => true
2238
                        ]);
2239
                        continue;
2240
                    }
2241
 
2242
 
2243
                    if($user->status != User::STATUS_ACTIVE) {
2244
                        array_push($result_sync_ids, [
2245
                            'success' => false,
2246
                            'sync_id' => $sync_id,
2247
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
2248
                            'fatal' => true
2249
                        ]);
2250
                        continue;
2251
                    }
2252
 
16 efrain 2253
 
2254
                    if(isset($companies[$company_uuid])) {
2255
                        $company = $companies[$company_uuid];
2256
                    } else {
2257
                        $company = $companyMapper->fetchOneByUuid($company_uuid);
2258
                        if($company) {
2259
                            $companies[$company_uuid] = $company;
2260
                        }
2261
                    }
2262
 
2263
 
2264
 
2265
 
1 www 2266
                    if(!$company) {
2267
                        array_push($result_sync_ids, [
2268
                            'success' => false,
2269
                            'sync_id' => $sync_id,
2270
                            'message' => 'ERROR_COMPANY_NOT_FOUND',
2271
                            'fatal' => true
2272
                        ]);
2273
                        continue;
2274
                    }
2275
 
2276
                    if($company->status != Company::STATUS_ACTIVE) {
2277
                        array_push($result_sync_ids, [
2278
                            'success' => false,
2279
                            'sync_id' => $sync_id,
2280
                            'message' => 'ERROR_COMPANY_IS_NOT_FOUND',
2281
                            'fatal' => true
2282
                        ]);
2283
                        continue;
2284
                    }
2285
 
2286
 
2287
 
16 efrain 2288
                    $key = $company->id . '-' .  Service::MICRO_LEARNING;
2289
                    if(isset($company_services[$key])) {
2290
                        $companyService = $company_services[$key];
2291
                    } else {
2292
                        $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($company->id, Service::MICRO_LEARNING);
2293
                        if($companyService) {
2294
                            $company_services[$key] = $companyService;
2295
                        }
2296
                    }
1 www 2297
 
2298
                    if(!$companyService) {
2299
                        array_push($result_sync_ids, [
2300
                            'success' => false,
2301
                            'sync_id' => $sync_id,
2302
                            'message' => 'ERROR_COMPANY_SERVICE_NOT_FOUND',
2303
                            'fatal' => true
2304
                        ]);
2305
                        continue;
2306
                    }
2307
 
2308
                    $serviceActive = true;
2309
                    $now = date('Y-m-d H:i:s');
2310
                    if($companyService->status == CompanyService::ACTIVE) {
2311
 
2312
                        if($now < $companyService->paid_from || $now > $companyService->paid_to) {
2313
                            $serviceActive = false;
2314
                        }
2315
 
2316
                    } else {
2317
                        $serviceActive = false;
2318
                    }
2319
 
2320
                    if( !$serviceActive) {
2321
                        array_push($result_sync_ids, [
2322
                            'success' => false,
2323
                            'sync_id' => $sync_id,
2324
                            'message' => 'ERROR_COMPANY_SERVICE_IS_NOT_ACTIVE',
2325
                            'fatal' => true
2326
                        ]);
2327
                        continue;
2328
                    }
2329
 
16 efrain 2330
 
1 www 2331
                    $topic_uuid = isset($record['topic_uuid']) ? filter_var($record['topic_uuid'], FILTER_SANITIZE_STRING) :  '';
2332
                    if($topic_uuid) {
2333
 
16 efrain 2334
                        if(isset($topics[$topic_uuid])) {
2335
                            $topic = $topics[$topic_uuid];
2336
                        } else {
2337
                            $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2338
                            if($topic) {
2339
                                $topics[$topic_uuid] = $topic;
2340
                            }
2341
                        }
2342
 
1 www 2343
                        if(!$topic) {
2344
                            array_push($result_sync_ids, [
2345
                                'success' => false,
2346
                                'sync_id' => $sync_id,
2347
                                'message' => 'ERROR_TOPIC_NOT_FOUND',
2348
                            ]);
2349
                            continue;
2350
                        }
2351
 
2352
                        if($topic->company_id != $company->id) {
2353
                            array_push($result_sync_ids, [
2354
                                'success' => false,
2355
                                'sync_id' => $sync_id,
2356
                                'message' => 'ERROR_INVALID_PARAMETERS_TOPIC_COMPANY',
2357
                            ]);
2358
                            continue;
2359
                        }
2360
 
2361
                    } else {
2362
                        $topic = null;
2363
                    }
2364
 
2365
                    $capsule_uuid     = isset($record['capsule_uuid']) ? filter_var($record['capsule_uuid'], FILTER_SANITIZE_STRING) :  '';
16 efrain 2366
 
1 www 2367
                    if($capsule_uuid) {
2368
 
16 efrain 2369
                        if(isset($capsules[$capsule_uuid])) {
2370
                            $capsule = $capsules[$capsule_uuid];
2371
                        } else {
2372
                            $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2373
                            if($capsule) {
2374
                                $capsules[$capsule_uuid] = $capsule;
2375
                            }
2376
                        }
1 www 2377
                        if(!$capsule) {
2378
                            array_push($result_sync_ids, [
2379
                                'success' => false,
2380
                                'sync_id' => $sync_id,
2381
                                'message' => 'ERROR_CAPSULE_NOT_FOUND',
2382
                            ]);
2383
                            continue;
2384
                        }
2385
 
2386
                        if(!$topic || $capsule->topic_id != $topic->id) {
2387
                            array_push($result_sync_ids, [
2388
                                'success' => false,
2389
                                'sync_id' => $sync_id,
2390
                                'message' => 'ERROR_INVALID_PARAMETERS_CAPSULE_TOPIC',
2391
                            ]);
2392
                            continue;
2393
                        }
2394
                    } else {
2395
                        $capsule = null;
2396
                    }
2397
 
2398
                    if($capsule) {
2399
 
2400
                        $capsuleActive = true;
2401
 
16 efrain 2402
                        $key = $user->id . '-' . $capsule->id;
1 www 2403
 
16 efrain 2404
                        if(isset($capsule_users[$key])) {
2405
                            $capsuleUser = $capsule_users[$key];
2406
                        } else {
2407
 
2408
                            $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
2409
                            if($capsuleUser) {
2410
                                $capsule_users[$key] = $capsuleUser;
2411
                            }
2412
 
2413
                        }
2414
 
1 www 2415
                        $now = date('Y-m-d H:i:s');
2416
                        if($capsuleUser && in_array($capsuleUser->access, [CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED,CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD ])) {
2417
 
2418
 
2419
                            if($capsuleUser->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
2420
 
2421
                                if($now < $capsuleUser->paid_from || $now > $capsuleUser->paid_to) {
2422
                                    $capsuleActive = false;;
2423
                                }
2424
                            }
2425
 
2426
                        } else {
2427
                            $capsuleActive = false;
2428
                        }
2429
 
2430
                        if(!$capsuleActive) {
2431
                            array_push($result_sync_ids, [
2432
                                'success' => false,
2433
                                'sync_id' => $sync_id,
2434
                                'message' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
2435
                            ]);
2436
                            continue;
2437
                        }
2438
                    }
2439
 
16 efrain 2440
 
1 www 2441
                    $slide_uuid      = isset($record['slide_uuid']) ? filter_var($record['slide_uuid'], FILTER_SANITIZE_STRING) :  '';
2442
                    if($slide_uuid) {
16 efrain 2443
 
2444
                        if(isset($slides[$slide_uuid])) {
2445
                            $slide = $slides[$slide_uuid];
2446
                        } else {
2447
 
2448
                            $slide = $slideMapper->fetchOneByUuid($slide_uuid);
2449
                            if($slide) {
2450
                                $slides[$slide_uuid] = $slide;
2451
                            }
2452
                        }
1 www 2453
                        if(!$slide) {
2454
                            array_push($result_sync_ids, [
2455
                                'success' => false,
2456
                                'sync_id' => $sync_id,
2457
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
2458
                            ]);
2459
                            continue;
2460
                        }
2461
 
2462
                        if(!$capsule || $slide->capsule_id != $capsule->id) {
2463
                            array_push($result_sync_ids, [
2464
                                'success' => false,
2465
                                'sync_id' => $sync_id,
2466
                                'message' => 'ERROR_INVALID_PARAMETERS_SLIDE_CAPSULE',
2467
                            ]);
2468
                            continue;
2469
                        }
2470
                    } else {
2471
                        $slide = null;
2472
                    }
2473
 
2474
                    if($sync_type == 'microlearning-quiz') {
2475
                        $ok = true;
2476
 
2477
                        $quiz_uuid = isset($record['quiz_uuid']) ? $record['quiz_uuid'] : '';
16 efrain 2478
 
2479
                        if(isset($quizzes[$quiz_uuid])) {
2480
                            $quiz = $quizzes[$quiz_uuid];
2481
                        } else {
2482
                            $quiz = $quizMapper->fetchOneByUuid($quiz_uuid);
2483
                            if($quiz) {
2484
                                $quizzes[$quiz_uuid] = $quiz;
2485
                            }
2486
                        }
1 www 2487
                        if(!$quiz) {
2488
                            array_push($result_sync_ids, [
2489
                                'success' => false,
2490
                                'sync_id' => $sync_id,
2491
                                'message' => 'ERROR_SLIDE_NOT_FOUND',
2492
                            ]);
2493
                            continue;
2494
                        }
2495
 
2496
                        if(!$capsule || $slide->capsule_id != $capsule->id) {
2497
                            array_push($result_sync_ids, [
2498
                                'success' => false,
2499
                                'sync_id' => $sync_id,
2500
                                'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_SLIDE',
2501
                            ]);
2502
                            continue;
2503
                        }
2504
 
2505
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2506
 
2507
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2508
                        if(!$dt) {
2509
                            $ok = false;
2510
                        } else {
2511
                            $added_on = $dt->format('Y-m-d H:i:s');
2512
                        }
2513
 
2514
                        if(isset($record['points'])) {
2515
                            $points = intval($record['points'], 10);
2516
                        } else {
2517
                            $ok = false;
2518
                        }
2519
 
2520
                        if(isset($record['pass'])) {
2521
                            $status = $record['pass'] == 'yes' ? CompanyMicrolearningUserQuiz::STATUS_PASS : CompanyMicrolearningUserQuiz::STATUS_FAIL;
2522
                        } else {
2523
                            $ok = false;
2524
                        }
2525
 
2526
                        if(!$ok) {
2527
                            array_push($result_sync_ids, [
2528
                                'success' => false,
2529
                                'sync_id' => $sync_id,
2530
                                'message' => 'ERROR_INVALID_PARAMETERS',
2531
                            ]);
2532
                            continue;
2533
                        }
2534
 
2535
                        $array_response = [];
2536
                        $response = isset($record['response']) ? intval($record['response'], 10) : 0;
2537
                        for($i = 0; $i < $response; $i++)
2538
                        {
2539
                            $question_uuid = isset($record["response_{$i}_question_uuid"]) ? $record["response_{$i}_question_uuid"] : '';
2540
                            $answer_uuid = isset($record["response_{$i}_answer_uuid"]) ? $record["response_{$i}_answer_uuid"] : '';
2541
                            $value = isset($record["response_{$i}_value"]) ?  intval($record["response_{$i}_value"], 10) : 0;
2542
                            $points = isset($record["response_{$i}_points"]) ?  intval($record["response_{$i}_points"], 10) : 0;
2543
 
16 efrain 2544
 
2545
                            if(isset($questions[$question_uuid])) {
2546
                                $question = $questions[$question_uuid];
2547
                            } else {
2548
                                $question = $questionMapper->fetchOneByUuid($question_uuid);
2549
                                if($question) {
2550
                                    $questions[$question_uuid] = $question;
2551
                                }
2552
                            }
2553
 
2554
                            if(!$question || $question->quiz_id != $quiz->id) {
2555
                                array_push($result_sync_ids, [
2556
                                    'success' => false,
2557
                                    'sync_id' => $sync_id,
2558
                                    'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_QUESTION_SLIDE',
1 www 2559
                                ]);
16 efrain 2560
                                continue;
2561
                            }
2562
 
2563
                            if(isset($answers[$answer_uuid])) {
2564
                                $answer = $answers[$answer_uuid];
2565
                            } else {
2566
                                $answer = $answerMapper->fetchOneByUuid($answer_uuid);
2567
                                if($answer) {
2568
                                    $answers[$answer_uuid] = $answer;
2569
                                }
2570
                            }
2571
 
2572
                            if($answer && $answer->question_id != $question->id) {
2573
                                array_push($result_sync_ids, [
2574
                                    'success' => false,
2575
                                    'sync_id' => $sync_id,
2576
                                    'message' => 'ERROR_INVALID_PARAMETERS_QUIZ_ANSWER_SLIDE',
2577
                                ]);
2578
                                continue;
2579
                            }
2580
 
2581
                            array_push($array_response, [
2582
                                'question_uuid' => $question_uuid,
2583
                                'answer_uuid' => $answer_uuid,
2584
                                'value' => $value,
2585
                                'points' => $points
2586
                            ]);
1 www 2587
                        }
2588
 
2589
                        $userQuiz = new CompanyMicrolearningUserQuiz();
2590
                        $userQuiz->company_id = $company->id;
2591
                        $userQuiz->topic_id = $topic->id;
2592
                        $userQuiz->capsule_id = $capsule->id;
2593
                        $userQuiz->slide_id = $slide->id;
2594
                        $userQuiz->quiz_id = $quiz->id;
2595
                        $userQuiz->user_id = $user->id;
2596
                        $userQuiz->added_on = $added_on;
2597
                        $userQuiz->points = $points;
2598
                        $userQuiz->status = $status;
2599
                        $userQuiz->response = json_encode($array_response);
2600
 
2601
                        $userQuizMapper = CompanyMicrolearningUserQuizMapper::getInstance($this->adapter);
2602
 
2603
                        if($userQuizMapper->insert($userQuiz)) {
2604
                            array_push($result_sync_ids, [
2605
                                'success' => true,
2606
                                'sync_id' => $sync_id
2607
                            ]);
2608
                        } else {
2609
                            array_push($result_sync_ids, [
2610
                                'success' => false,
2611
                                'sync_id' => $sync_id,
2612
                                'message' => $userQuizMapper->getError()
2613
                            ]);
2614
                        }
2615
                        continue;
2616
                    }
2617
 
2618
                    if($sync_type == 'microlearning-progress') {
2619
                        $ok = true;
2620
 
2621
                        $type = isset($record['type']) ? $record['type'] : '';
2622
                        switch($type)
2623
                        {
2624
                            case CompanyMicrolearningUserProgress::TYPE_TOPIC :
2625
                                if(!$topic) {
2626
                                    $ok = false;
2627
                                }
2628
                                break;
2629
 
2630
                            case CompanyMicrolearningUserProgress::TYPE_CAPSULE :
2631
                                if(!$topic || !$capsule) {
2632
                                    $ok = false;
2633
                                }
2634
                                break;
2635
 
2636
                            case CompanyMicrolearningUserProgress::TYPE_SLIDE :
2637
                                if(!$topic || !$capsule || !$slide) {
2638
                                    $ok = false;
2639
                                }
2640
                                break;
2641
 
2642
                            default :
2643
                                $ok = false;
2644
                                break;
2645
                        }
2646
 
2647
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2648
                        $updated_on = isset($record['updated_on'])    ? filter_var($record['updated_on'], FILTER_SANITIZE_STRING) :  '';
2649
 
2650
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2651
                        if(!$dt) {
2652
                            $ok = false;
2653
                        } else {
2654
                            $added_on = $dt->format('Y-m-d H:i:s');
2655
                        }
2656
 
2657
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $updated_on );
2658
                        if(!$dt) {
2659
                            $ok = false;
2660
                        } else {
2661
                            $updated_on = $dt->format('Y-m-d H:i:s');
2662
                        }
2663
 
2664
                        if(!$ok) {
2665
                            array_push($result_sync_ids, [
2666
                                'success' => false,
2667
                                'sync_id' => $sync_id,
2668
                                'message' => 'ERROR_INVALID_PARAMETERS',
2669
                            ]);
2670
                            continue;
2671
                        }
2672
 
18 efrain 2673
                        $progress                   = isset($record['progress'])                  ? floatval($record['progress']) :  0;
2674
                        $total_slides               = isset($record['total_slides'])              ? intval($record['total_slides'], 10) :  0;
2675
                        $view_slides                = isset($record['view_slides'])               ? intval($record['view_slides'], 10) :  0;
1 www 2676
                        $returning                  = isset($record['returning'])                 ? intval($record['returning'], 10) :  0;
2677
                        $returning_after_completed  = isset($record['returning_after_completed']) ? intval($record['returning_after_completed'], 10) :  0;
2678
                        $completed                  = isset($record['completed'])                 ? intval($record['completed'], 10) :  0;
2679
 
16 efrain 2680
 
1 www 2681
                        $recordProgress = null;
2682
                        switch($type) {
2683
                            case CompanyMicrolearningUserProgress::TYPE_TOPIC  :
16 efrain 2684
                                $recordProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($user->id, $topic->id);
1 www 2685
 
2686
                                break;
2687
 
2688
                            case CompanyMicrolearningUserProgress::TYPE_CAPSULE  :
16 efrain 2689
                                $recordProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($user->id, $capsule->id);
1 www 2690
                                break;
2691
 
2692
                            case CompanyMicrolearningUserProgress::TYPE_SLIDE  :
16 efrain 2693
                                $recordProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($user->id, $slide->id);
1 www 2694
                                break;
2695
 
2696
                            default :
2697
                                $recordProgress= null;
2698
                        }
2699
 
2700
 
2701
                        if(!$recordProgress) {
2702
                            $recordProgress = new CompanyMicrolearningUserProgress();
2703
 
2704
                            $recordProgress->user_id    = $user->id;
2705
                            $recordProgress->type       = $type;
2706
                            $recordProgress->company_id = $topic->company_id;
2707
                            $recordProgress->topic_id   = $topic->id;
2708
                            $recordProgress->capsule_id = $capsule ? $capsule->id : null;
2709
                            $recordProgress->slide_id   = $slide ? $slide->id : null;
2710
                            $recordProgress->added_on   = $added_on;
43 efrain 2711
                        }
2712
                        /*
2713
                        else {
16 efrain 2714
 
2715
                            if($recordProgress->updated_on > $updated_on) {
2716
                                array_push($result_sync_ids, [
2717
                                    'success' => true,
2718
                                    'sync_id' => $sync_id,
2719
                                ]);
2720
                                continue;
2721
                            }
2722
 
2723
 
2724
 
43 efrain 2725
                        }*/
1 www 2726
                        $recordProgress->returning                  = $returning;
2727
                        $recordProgress->returning_after_completed  = $returning_after_completed;
2728
                        $recordProgress->completed                  = $completed;
2729
 
2730
                        if($type == CompanyMicrolearningUserProgress::TYPE_TOPIC ) {
2731
 
2732
                            $capsule_ids = [];
2733
                            $companyMicrolearningCapsuleUser = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
2734
                            $records =  $companyMicrolearningCapsuleUser->fetchAllActiveByUserId($user->id);
2735
                            foreach($records as $record)
2736
                            {
2737
                                if($now >= $record->paid_from || $now <= $capsuleUser->paid_to) {
2738
                                    if(!in_array($record->capsule_id, $capsule_ids)) {
2739
                                        array_push($capsule_ids, $record->capsule_id);
2740
                                    }
2741
                                }
2742
                            }
18 efrain 2743
 
2744
                            $recordProgress->progress       = $progress;
1 www 2745
                            $recordProgress->total_slides   = $total_slides;
2746
                            $recordProgress->view_slides    = $view_slides;
2747
                        }
2748
                        else if($type == CompanyMicrolearningUserProgress::TYPE_CAPSULE ) {
18 efrain 2749
 
2750
                            $recordProgress->progress       = $progress;
1 www 2751
                            $recordProgress->total_slides   = $total_slides;
2752
                            $recordProgress->view_slides    = $view_slides;
2753
                        }
2754
                        else {
2755
                            $recordProgress->progress       = 0;
2756
                            $recordProgress->total_slides   = 0;
2757
                            $recordProgress->view_slides    = 0;
2758
                        }
2759
 
2760
                        $recordProgress->updated_on = $updated_on;
2761
 
2762
 
2763
 
2764
                        if($recordProgress->id) {
16 efrain 2765
                            $result = $userProgressMapper->update($recordProgress);
1 www 2766
                        } else {
16 efrain 2767
                            $result = $userProgressMapper->insert($recordProgress);
1 www 2768
                        }
2769
 
2770
                        if($result) {
2771
                            array_push($result_sync_ids, [
2772
                                'success' => true,
2773
                                'sync_id' => $sync_id
2774
                            ]);
2775
                        } else {
2776
                            array_push($result_sync_ids, [
2777
                                'success' => false,
2778
                                'sync_id' => $sync_id,
16 efrain 2779
                                'message' => $userProgressMapper->getError()
1 www 2780
                            ]);
2781
                        }
2782
                        continue;
2783
                    }
2784
 
2785
 
2786
 
2787
                    if($sync_type == 'microlearning-userlog') {
2788
                        $activity   = isset($record['activity'])      ? filter_var($record['activity'], FILTER_SANITIZE_STRING)  :  '';
2789
                        $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2790
 
2791
 
2792
                        if(empty($activity)) {
2793
                            $ok = false;
2794
                        }
2795
 
2796
                        $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2797
                        if(!$dt) {
2798
                            $ok = false;
2799
                        } else {
2800
                            $added_on = $dt->format('Y-m-d H:i:s');
2801
                        }
2802
 
2803
                        if(!$ok) {
2804
                            array_push($result_sync_ids, [
2805
                                'success' => false,
2806
                                'sync_id' => $sync_id,
2807
                                'message' => 'ERROR_INVALID_PARAMETERS',
2808
                            ]);
2809
                            continue;
2810
                        }
2811
 
2812
 
2813
 
2814
 
16 efrain 2815
                        $userLog = $userLogMapper->fetchLastBy($user->id);
2816
                        if($userLog) {
2817
                            $insert = $userLog->added_on <= $added_on;
2818
                        } else {
2819
                            $insert = true;
2820
                        }
2821
 
2822
 
2823
                        if($insert) {
2824
 
2825
                            $userLog = new CompanyMicrolearningUserLog();
2826
                            $userLog->activity      = $activity;
2827
                            $userLog->user_id       = $user->id;
2828
                            $userLog->company_id    = $topic->company_id;
2829
                            $userLog->topic_id      = $topic->id;
2830
                            $userLog->capsule_id    = $capsule ? $capsule->id : null;
2831
                            $userLog->slide_id      = $slide ? $slide->id : null;
2832
                            $userLog->added_on      = $added_on;
2833
 
2834
 
2835
 
2836
 
2837
                            if($userLogMapper->insert($userLog)) {
2838
                                array_push($result_sync_ids, [
2839
                                    'success' => true,
2840
                                    'sync_id' => $sync_id
2841
                                ]);
2842
                            } else {
2843
                                array_push($result_sync_ids, [
2844
                                    'success' => false,
2845
                                    'sync_id' => $sync_id,
2846
                                    'message' => $userLogMapper->getError()
2847
                                ]);
2848
                            }
2849
                        } else {
1 www 2850
                            array_push($result_sync_ids, [
2851
                                'success' => true,
16 efrain 2852
                                'sync_id' => $sync_id
1 www 2853
                            ]);
2854
                        }
2855
                        continue;
2856
                    }
2857
 
2858
                }
2859
 
2860
                /***** FIN MICROLEARNING *****/
2861
 
2862
 
2863
                /***** INICIO LOG DE USUARIO GENERAL *****/
2864
 
2865
                if($user_uuid && $sync_type == 'userlog' && $device->application_id = Application::TWOGETSKILLS) {
2866
 
2867
 
16 efrain 2868
                    if(isset($users[$user_uuid])) {
2869
                        $user = $users[$user_uuid];
2870
                    } else {
2871
                        $user = $userMapper->fetchOneByUuid($user_uuid);
2872
                        if($user) {
2873
                            $users[$user_uuid] = $user;
2874
                        }
2875
                    }
2876
 
2877
 
2878
 
2879
 
1 www 2880
                    if(!$user) {
2881
                        array_push($result_sync_ids, [
2882
                            'success' => false,
2883
                            'sync_id' => $sync_id,
2884
                            'message' => 'ERROR_USER_NOT_FOUND',
2885
                            'fatal' => true
2886
                        ]);
2887
                        continue;
2888
                    }
2889
 
2890
 
2891
                    if($user->status != User::STATUS_ACTIVE) {
2892
                        array_push($result_sync_ids, [
2893
                            'success' => false,
2894
                            'sync_id' => $sync_id,
2895
                            'message' => 'ERROR_USER_IS_NOT_ACTIVE',
2896
                            'fatal' => true
2897
                        ]);
2898
                        continue;
2899
                    }
2900
 
2901
                    $activity   = isset($record['activity'])      ? filter_var($record['activity'], FILTER_SANITIZE_STRING)  :  '';
2902
                    $added_on   = isset($record['added_on'])      ? filter_var($record['added_on'], FILTER_SANITIZE_STRING)  :  '';
2903
 
2904
                    if(empty($activity)) {
2905
                        $ok = false;
2906
                    }
2907
 
2908
                    $dt = \DateTime::createFromFormat($serviceDatetimeFormat, $added_on);
2909
                    if(!$dt) {
2910
                        $ok = false;
2911
                    } else {
2912
                        $added_on = $dt->format('Y-m-d H:i:s');
2913
                    }
2914
 
2915
                    if(!$ok) {
2916
                        array_push($result_sync_ids, [
2917
                            'success' => false,
2918
                            'sync_id' => $sync_id,
2919
                            'message' => 'ERROR_INVALID_PARAMETERS',
2920
                        ]);
2921
                        continue;
2922
                    }
2923
 
2924
 
16 efrain 2925
                    $userLog = $userLogMapper->fetchLastBy($user->id);
2926
                    if($userLog) {
2927
                        $insert = $userLog->added_on <= $added_on;
2928
                    } else {
2929
                        $insert = true;
2930
                    }
1 www 2931
 
16 efrain 2932
 
2933
                    if($insert) {
2934
                        $userLog = new CompanyMicrolearningUserLog();
2935
                        $userLog->company_id = null;
2936
                        $userLog->user_id = $user->id;
2937
                        $userLog->activity = $activity;
2938
                        $userLog->added_on = $added_on;
2939
 
2940
 
2941
                        $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
2942
                        if($userLogMapper->insert($userLog)) {
2943
                            array_push($result_sync_ids, [
2944
                                'success' => true,
2945
                                'sync_id' => $sync_id
2946
                            ]);
2947
                        } else {
2948
                            array_push($result_sync_ids, [
2949
                                'success' => false,
2950
                                'sync_id' => $sync_id,
2951
                                'message' => $userLogMapper->getError()
2952
                            ]);
2953
                        }
2954
                    } else {
1 www 2955
                        array_push($result_sync_ids, [
2956
                            'success' => true,
2957
                            'sync_id' => $sync_id
2958
                        ]);
2959
                    }
2960
 
16 efrain 2961
 
2962
 
1 www 2963
                    continue;
2964
                }
2965
 
2966
                /***** FIN LOG DE USUARIO GENERAL ******/
2967
            }
2968
 
2969
            if( $result_sync_ids) {
2970
                return new JsonModel([
2971
                    'success' => true,
2972
                    'data' => $result_sync_ids
2973
                ]);
2974
            } else {
2975
                return new JsonModel([
2976
                    'success' => false,
2977
                    'data' => 'ERROR_INVALID_PARAMETERS'
2978
                ]);
2979
            }
2980
 
2981
 
2982
        }
2983
 
2984
        return new JsonModel([
2985
            'success' => false,
2986
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2987
        ]);
2988
    }
2989
 
2990
    /**
2991
     *
2992
     * @param User $user
2993
     * @param boolean $includeLogs
2994
     * @param boolean $includeProgress
2995
     * @return array[]
2996
     */
2997
    private function getSyncData($user, $includeLogs = true, $includeProgress = true)
2998
    {
2999
 
3000
        $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
3001
 
3002
        $data = [
3003
            'userlog'   => [],
3004
            'progress'  => [],
3005
            'topics'    => [],
3006
            'quizzes'   => [],
47 efrain 3007
            'extended'  => [],
1 www 3008
        ];
3009
 
3010
 
3011
        $companies = [];
3012
        $companyMapper = CompanyMapper::getInstance($this->adapter);
3013
 
3014
        $topics = [];
3015
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
3016
 
3017
        $capsules = [];
3018
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
3019
 
3020
        $slides = [];
3021
        $slideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
3022
 
3023
        $quizzes = [];
3024
        $quizMapper = CompanyMicrolearningQuizMapper::getInstance($this->adapter);
3025
 
3026
        $questions = [];
3027
        $questionMapper = CompanyMicrolearningQuestionMapper::getInstance($this->adapter);
3028
 
3029
        $answers = [];
3030
        $answerMapper = CompanyMicrolearningAnswerMapper::getInstance($this->adapter);
3031
 
3032
 
3033
        $userLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter);
3034
 
3035
        if($includeLogs) {
3036
 
54 efrain 3037
            //$records = $userLogMapper->fetchLast20ByUserId($user->id);
3038
            $records = $userLogMapper->fetchAllByUserId($user->id);
1 www 3039
            foreach($records as $record)
3040
            {
3041
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
3042
 
3043
                if($record->company_id) {
3044
 
3045
                    if(isset($companies[$record->company_id])) {
3046
                        $company = $companies[$record->company_id];
3047
                    } else {
3048
                        $company = $companyMapper->fetchOne($record->company_id);
3049
                        $companies[$record->company_id] = $company;
3050
                    }
3051
                } else {
3052
                    $company = null;
3053
                }
3054
 
3055
                if($record->topic_id) {
3056
 
3057
                    if(isset($topics[$record->topic_id])) {
3058
                        $topic = $topics[$record->topic_id];
3059
                    } else {
3060
                        $topic = $topicMapper->fetchOne($record->topic_id);
3061
                        $topics[$record->topic_id] = $topic;
3062
                    }
3063
                } else {
3064
                    $topic = null;
3065
                }
3066
 
3067
 
3068
                if($record->capsule_id) {
3069
 
3070
                    if(isset($capsules[$record->capsule_id])) {
3071
                        $capsule = $capsules[$record->capsule_id];
3072
                    } else {
3073
                        $capsule = $capsuleMapper->fetchOne($record->capsule_id);
3074
                        $capsules[$record->capsule_id] = $capsule;
3075
                    }
3076
                } else {
3077
                    $capsule = null;
3078
                }
3079
 
3080
 
3081
                if($record->slide_id) {
3082
 
3083
                    if(isset($slides[$record->slide_id])) {
3084
                        $slide = $slides[$record->slide_id];
3085
                    } else {
3086
                        $slide = $slideMapper->fetchOne($record->slide_id);
3087
                        $slides[$record->slide_id] = $slide;
3088
                    }
3089
                } else {
3090
                    $slide = null;
3091
                }
3092
 
3093
 
3094
                array_push($data['userlog'], [
3095
                    'user_uuid'     => $user->uuid,
3096
                    'company_uuid'  => $company ? $company->uuid : '',
3097
                    'topic_uuid'    => $topic ? $topic->uuid : '',
3098
                    'capsule_uuid'  => $capsule ? $capsule->uuid : '',
3099
                    'slide_uuid'    => $slide ? $slide->uuid : '',
3100
                    'activity'      => $record->activity,
3101
                    'added_on'      => $dt->format($serviceDatetimeFormat),
3102
                ]);
3103
 
3104
 
3105
            }
3106
        }
3107
 
3108
        if($includeProgress) {
3109
 
3110
            $userProgressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
3111
            $records = $userProgressMapper->fetchAllByUserId($user->id);
3112
            foreach($records as $record)
3113
            {
3114
                if($record->company_id) {
3115
 
3116
                    if(isset($companies[$record->company_id])) {
3117
                        $company = $companies[$record->company_id];
3118
                    } else {
3119
                        $company = $companyMapper->fetchOne($record->company_id);
3120
                        $companies[$record->company_id] = $company;
3121
                    }
3122
                } else {
3123
                    $company = null;
3124
                }
3125
 
3126
                if($record->topic_id) {
3127
 
3128
                    if(isset($topics[$record->topic_id])) {
3129
                        $topic = $topics[$record->topic_id];
3130
                    } else {
3131
                        $topic = $topicMapper->fetchOne($record->topic_id);
3132
                        $topics[$record->topic_id] = $topic;
3133
                    }
3134
                } else {
3135
                    $topic = null;
3136
                }
3137
 
3138
 
3139
                if($record->capsule_id) {
3140
 
3141
                    if(isset($capsules[$record->capsule_id])) {
3142
                        $capsule = $capsules[$record->capsule_id];
3143
                    } else {
3144
                        $capsule = $capsuleMapper->fetchOne($record->capsule_id);
3145
                        $capsules[$record->capsule_id] = $capsule;
3146
                    }
3147
                } else {
3148
                    $capsule = null;
3149
                }
3150
 
3151
 
3152
                if($record->slide_id) {
3153
 
3154
                    if(isset($slides[$record->slide_id])) {
3155
                        $slide = $slides[$record->slide_id];
3156
                    } else {
3157
                        $slide = $slideMapper->fetchOne($record->slide_id);
3158
                        $slides[$record->slide_id] = $slide;
3159
                    }
3160
                } else {
3161
                    $slide = null;
3162
                }
3163
 
3164
 
3165
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
3166
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $record->updated_on);
3167
 
3168
                array_push($data['progress'], [
3169
                    'user_uuid'                 => $user->uuid,
3170
                    'company_uuid'              => $company ? $company->uuid : '',
3171
                    'topic_uuid'                => $topic ? $topic->uuid : '',
3172
                    'capsule_uuid'              => $capsule ? $capsule->uuid : '',
3173
                    'slide_uuid'                => $slide ? $slide->uuid : '',
3174
                    'progress'                  => $record->progress ? $record->progress : 0,
3175
                    'total_slides'              => $record->total_slides ? $record->total_slides : 0,
3176
                    'view_slides'               => $record->view_slides ? $record->view_slides : 0,
3177
                    'type'                      => $record->type,
3178
                    'returning'                 => $record->returning ? $record->returning : 0,
3179
                    'returning_after_completed' => $record->returning_after_completed ? $record->returning_after_completed : 0,
3180
                    'completed'                 => $record->completed ? $record->completed : 0,
3181
                    'added_on'                  => $dtAddedOn->format($serviceDatetimeFormat),
3182
                    'updated_on'                => $dtUpdatedOn->format($serviceDatetimeFormat),
3183
                ]);
3184
            }
3185
        }
3186
 
3187
 
3188
        $now = date('Y-m-d H:i:s');
3189
        $companies_with_access  = [];
3190
        $topics_with_access     = [];
3191
        $capsules_with_access   = [];
3192
        $quizzes_with_access    = [];
3193
        $quizzes                = [];
3194
 
3195
 
3196
        $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
3197
        $records = $capsuleUserMapper->fetchAllActiveByUserId($user->id);
3198
 
3199
 
3200
        foreach($records as $record)
3201
        {
3202
            if($record->access != CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED && $record->access != CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
3203
                continue;
3204
            }
3205
            if($record->access == CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
3206
                if($now < $record->paid_from || $now > $record->paid_to) {
3207
                    continue;
3208
                }
3209
            }
3210
 
3211
 
3212
            if(!in_array($record->company_id,$companies_with_access)) {
3213
                array_push($companies_with_access, $record->company_id);
3214
            }
3215
 
3216
            if(!in_array($record->topic_id,$topics_with_access)) {
3217
                array_push($topics_with_access, $record->topic_id);
3218
            }
3219
 
3220
            if(!in_array($record->capsule_id,$capsules_with_access)) {
3221
                array_push($capsules_with_access, $record->capsule_id);
3222
            }
3223
        }
3224
 
3225
 /*
3226
        echo '$companies_with_access ' . PHP_EOL;
3227
        print_r($companies_with_access);
3228
 
3229
        echo '$topics_with_access ' . PHP_EOL;
3230
        print_r($topics_with_access);
3231
 
3232
        echo '$capsules_with_access' . PHP_EOL;
3233
        print_r($capsules_with_access);
3234
        */
3235
 
3236
        $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
3237
        foreach($companies_with_access as $company_id)
3238
        {
3239
            $companyService =  $companyServiceMapper->fetchOneActiveByCompanyIdAndServiceId($company_id, Service::MICRO_LEARNING);
3240
 
3241
            //print_r($companyService); exit;
3242
 
3243
            if(!$companyService) {
3244
                continue;
3245
            }
3246
 
3247
 
3248
            if(isset($companies[$companyService->company_id])) {
3249
                $company = $companies[$companyService->company_id];
3250
            } else {
3251
                $company = $companyMapper->fetchOne($companyService->company_id);
3252
                $companies[$companyService->company_id] = $company;
3253
            }
3254
 
3255
            $topics = $topicMapper->fetchAllActiveByCompanyId($company_id);
3256
            foreach($topics as $topic)
3257
            {
3258
                if(!in_array($topic->id, $topics_with_access)) {
3259
                    continue;
3260
                }
3261
 
3262
                $record_capsules = [];
3263
                $capsules = $capsuleMapper->fetchAllActiveByCompanyIdAndTopicId($topic->company_id, $topic->id);
3264
                foreach($capsules as $capsule)
3265
                {
3266
                    if(!in_array($capsule->id, $capsules_with_access)) {
3267
                        continue;
3268
                    }
3269
 
3270
 
3271
                    $record_slides = [];
3272
                    $slides = $slideMapper->fetchAllByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
3273
                    foreach($slides as $slide)
3274
                    {
3275
                        if($slide->type == CompanyMicrolearningSlide::TYPE_QUIZ) {
3276
                            if(!in_array($slide->quiz_id, $quizzes_with_access)) {
3277
                                array_push($quizzes_with_access, $slide->quiz_id);
3278
                            }
3279
 
3280
                            if(isset($quizzes[$slide->quiz_id])) {
3281
                                $quiz = $quizzes[$slide->quiz_id];
3282
 
3283
                            } else {
3284
                                $quiz = $quizMapper->fetchOne($slide->quiz_id);
3285
                                $quizzes[$slide->quiz_id] =  $quiz;
3286
                            }
3287
                        } else {
3288
                            $quiz = null;
3289
                        }
3290
 
3291
 
3292
 
3293
                        array_push($record_slides, [
3294
                            'uuid' => $slide->uuid,
3295
                            'quiz_uuid' => $quiz ? $quiz->uuid : '',
3296
                            'name' => $slide->name ? $slide->name : '',
3297
                            'description' => $slide->description ? $slide->description : '',
3298
                            'position' => $slide->order,
3299
                            'type' => $slide->type,
3300
                            'background' => $slide->background ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-slide', 'code' => $slide->uuid, 'filename' => $slide->background], ['force_canonical' => true]) : '',
3301
                            'file' => $slide->file ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-slide', 'code' => $slide->uuid, 'filename' => $slide->file], ['force_canonical' => true]) : '',
3302
                        ]);
3303
                    }
3304
 
3305
                    array_push($record_capsules, [
3306
                        'uuid' => $capsule->uuid,
3307
                        'name' => $capsule->name ? $capsule->name : '',
3308
                        'description' => $capsule->description ? $capsule->description : '',
3309
                        'image' => $capsule->image ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-capsule', 'code' => $capsule->uuid, 'filename' => $capsule->image ], ['force_canonical' => true])  : '',
3310
                        'position' => $capsule->order,
3311
                        'slides' => $record_slides,
3312
                    ]);
3313
                }
3314
 
3315
                array_push($data['topics'], [
3316
                    'uuid' => $topic->uuid,
3317
                    'name' => $topic->name ? $topic->name : '',
3318
                    'description' => $topic->description ? $topic->description : '',
3319
                    'image' => $topic->image ? $this->url()->fromRoute('services/storage',['type' => 'microlearning-topic', 'code' => $topic->uuid, 'filename' => $topic->image ], ['force_canonical' => true]) : '',
3320
                    'position' => $topic->order,
3321
                    'company_uuid' => $company->uuid,
3322
                    'company_name' => $company->name,
3323
                    'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
3324
                    'capsules' => $record_capsules
3325
                ]);
3326
            }
3327
        }
3328
 
3329
 
3330
 
3331
        foreach($quizzes_with_access as $quiz_id)
3332
        {
3333
            if(isset($quizzes[$quiz_id])) {
3334
                $quiz = $quizzes[$quiz_id];
3335
            } else {
3336
                $quiz = $quizMapper->fetchOne($quiz_id);
3337
                array_push($quizzes, $quiz);
3338
            }
3339
 
3340
            if(isset($companies[$quiz->company_id])) {
3341
                $company = $companies[$quiz->company_id];
3342
            } else {
3343
                $company = $companyMapper->fetchOne($quiz->company_id);
3344
                $companies[$quiz->company_id] = $company;
3345
            }
3346
 
3347
 
3348
            $record_questions = [];
3349
            $questions = $questionMapper->fetchAllByQuizId($quiz->id);
3350
            foreach($questions as $question)
3351
            {
3352
                $record_answers = [];
3353
 
3354
                $answers = $answerMapper->fetchAllByQuizIdAndQuestionId($question->quiz_id, $question->id);
3355
                foreach($answers as $answer)
3356
                {
3357
                    array_push($record_answers, [
3358
                        'uuid' => $answer->uuid,
3359
                        'text' => trim($answer->text),
3360
                        'correct' => $answer->correct ? $answer->correct  : 0 ,
3361
                        'points' => intval($answer->points, 10),
3362
                    ]);
3363
                }
3364
 
3365
                array_push($record_questions, [
3366
                    'uuid' => $question->uuid,
3367
                    'text' => trim($question->text),
3368
                    'type' => $question->type,
3369
                    'maxlength' => $question->maxlength,
3370
                    'points' => $question->points,
3371
                    'answers' => $record_answers,
3372
                ]);
3373
            }
3374
 
3375
 
3376
            array_push($data['quizzes'], [
3377
                'uuid' => $quiz->uuid,
3378
                'name' => $quiz->name,
3379
                'text' => trim($quiz->text ? $quiz->text : ''),
3380
                'failed' => trim($quiz->failed ? $quiz->failed : ''),
3381
                'points' => $quiz->points,
3382
                'minimum_points_required' => $quiz->minimum_points_required,
3383
                'max_time' => $quiz->max_time ? $quiz->max_time : 5,
3384
                'company_uuid' => $company->uuid,
3385
                'company_name' => $company->name,
3386
                'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
3387
                'questions' => $record_questions,
3388
            ]);
3389
        }
47 efrain 3390
 
3391
        $companyExtendUserMapper = CompanyMicrolearningExtendUserMapper::getInstance($this->adapter);
3392
        $companyExtendUserCompanyMapper = CompanyMicrolearningExtendUserCompanyMapper::getInstance($this->adapter);
3393
        $companyExtendUserFunctionMapper = CompanyMicrolearningExtendUserFunctionMapper::getInstance($this->adapter);
3394
        $companyExtendUserGroupMapper = CompanyMicrolearningExtendUserGroupMapper::getInstance($this->adapter);
3395
        $companyExtendUserInstitutionMapper = CompanyMicrolearningExtendUserInstitutionMapper::getInstance($this->adapter);
3396
        $companyExtendUserPartnerMapper = CompanyMicrolearningExtendUserPartnerMapper::getInstance($this->adapter);
3397
        $companyExtendUserProgramMapper = CompanyMicrolearningExtendUserProgramMapper::getInstance($this->adapter);
3398
        $companyExtendUserStudentTypeMapper = CompanyMicrolearningExtendUserStudentTypeMapper::getInstance($this->adapter);
3399
        $companyExtendUserSectorMapper = CompanyMicrolearningExtendUserSectorMapper::getInstance($this->adapter);
3400
 
3401
        $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
3402
        foreach($companies_with_access as $company_id)
3403
        {
3404
            $companyService =  $companyServiceMapper->fetchOneActiveByCompanyIdAndServiceId($company_id, Service::MICRO_LEARNING);
3405
 
3406
            //print_r($companyService); exit;
3407
 
3408
            if(!$companyService) {
3409
                continue;
3410
            }
3411
 
3412
 
3413
            if(isset($companies[$companyService->company_id])) {
3414
                $company = $companies[$companyService->company_id];
3415
            } else {
3416
                $company = $companyMapper->fetchOne($companyService->company_id);
3417
                $companies[$companyService->company_id] = $company;
3418
            }
3419
 
3420
            if(!$company) {
3421
                continue;
3422
            }
3423
 
3424
            $record = [
3425
                'company_uuid' => $company->uuid,
3426
                'company_name' => $company->name,
3427
                'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
48 efrain 3428
                'details' => [],
47 efrain 3429
            ];
3430
 
3431
            $companyExtendUser = $companyExtendUserMapper->fetchOneByCompanyIdAndUserId($company->id, $user->id);
3432
            if(!$companyExtendUser) {
3433
                continue;
3434
            }
3435
 
3436
            if($companyExtendUser->extend_company_id) {
3437
 
3438
                $extendedCompany = $companyExtendUserCompanyMapper->fetchOne($companyExtendUser->company_id);
3439
                if($extendedCompany) {
48 efrain 3440
                    array_push($record['details'],[
3441
                        'uuid' => $extendedCompany->uuid,
3442
                        'label' => 'LABEL_COMPANY',
3443
                        'value' => $extendedCompany->name
3444
                    ]);
47 efrain 3445
                }
3446
            }
3447
 
3448
            if($companyExtendUser->extend_function_id) {
3449
                $extendedFunction = $companyExtendUserFunctionMapper->fetchOne($companyExtendUser->extend_function_id);
3450
                if($extendedFunction) {
48 efrain 3451
                    array_push($record['details'],[
3452
                        'uuid' => $extendedFunction->uuid,
3453
                        'label' => 'LABEL_FUNCTION',
3454
                        'value' => $extendedFunction->name
3455
                    ]);
47 efrain 3456
                }
3457
            }
3458
 
3459
            if($companyExtendUser->extend_group_id) {
3460
                $extendedGroup = $companyExtendUserGroupMapper->fetchOne($companyExtendUser->extend_group_id);
3461
                if($extendedGroup) {
48 efrain 3462
                    array_push($record['details'],[
3463
                        'uuid' => $extendedGroup->uuid,
3464
                        'label' => 'LABEL_GROUP',
3465
                        'value' => $extendedGroup->name
3466
                    ]);
47 efrain 3467
                }
3468
            }
3469
 
3470
            if($companyExtendUser->extend_institution_id) {
3471
                $extendedInstitution= $companyExtendUserInstitutionMapper->fetchOne($companyExtendUser->extend_institution_id);
3472
                if($extendedInstitution) {
48 efrain 3473
                    array_push($record['details'],[
3474
                        'uuid' => $extendedInstitution->uuid,
3475
                        'label' => 'LABEL_INSTITUTION',
3476
                        'value' => $extendedInstitution->name
3477
                    ]);
47 efrain 3478
                }
3479
            }
3480
 
3481
            if($companyExtendUser->extend_program_id) {
3482
                $extendedProgram = $companyExtendUserProgramMapper->fetchOne($companyExtendUser->extend_program_id);
3483
                if($extendedProgram) {
48 efrain 3484
                    array_push($record['details'],[
3485
                        'uuid' => $extendedProgram->uuid,
3486
                        'label' => 'LABEL_PROGRAM',
3487
                        'value' => $extendedProgram->name
3488
                    ]);
3489
 
47 efrain 3490
                }
3491
            }
3492
 
3493
            if($companyExtendUser->extend_sector_id) {
3494
                $extendedSector = $companyExtendUserSectorMapper->fetchOne($companyExtendUser->extend_sector_id);
3495
                if($extendedSector) {
48 efrain 3496
                    array_push($record['details'],[
3497
                        'uuid' => $extendedSector->uuid,
3498
                        'label' => 'LABEL_SECTOR',
3499
                        'value' => $extendedSector->name
3500
                    ]);
47 efrain 3501
                }
3502
            }
3503
 
3504
            if($companyExtendUser->extend_partner_id) {
3505
                $extendedPartner = $companyExtendUserPartnerMapper->fetchOne($companyExtendUser->extend_partner_id);
3506
                if($extendedPartner) {
48 efrain 3507
                    array_push($record['details'],[
3508
                        'uuid' => $extendedPartner->uuid,
3509
                        'label' => 'LABEL_PARTNER',
3510
                        'value' => $extendedPartner->name
3511
                    ]);
47 efrain 3512
                }
3513
            }
3514
 
3515
            if($companyExtendUser->extend_student_type_id) {
3516
                $extendedStudentType = $companyExtendUserStudentTypeMapper->fetchOne($companyExtendUser->extend_student_type_id);
3517
                if($extendedStudentType) {
48 efrain 3518
                    array_push($record['details'],[
3519
                        'uuid' => $extendedStudentType->uuid,
3520
                        'label' => 'LABEL_TYPE',
3521
                        'value' => $extendedStudentType->name
3522
                    ]);
47 efrain 3523
                }
3524
            }
3525
 
3526
            array_push($data['extended'], $record);
3527
        }
3528
 
1 www 3529
        return $data;
3530
    }
3531
 
3532
 
3533
    /**
3534
     *
3535
     * @param string $filename
3536
     * @param boolean $retbytes
3537
     * @return boolean|number
3538
     */
3539
    private function readfile_chunked($filename, $retbytes = true) {
3540
        $buffer = '';
3541
        $cnt =0;;
3542
        $handle = fopen($filename,'rb');
3543
        if ($handle === false) {
3544
            return false;
3545
        }
3546
        while (!feof($handle)) {
3547
            $buffer = fread($handle, self::CHUNK_SIZE);
3548
            echo $buffer;
3549
            ob_flush();
3550
            flush();
3551
            if ($retbytes) {
3552
                $cnt += strlen($buffer);
3553
            }
3554
        }
3555
        $status = fclose($handle);
3556
        if ($retbytes && $status) {
3557
            return $cnt; // return num. bytes delivered like readfile() does.
3558
        }
3559
        return $status;
3560
    }
3561
}