Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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