Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

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