Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

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