Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 6995 | Rev 16768 | 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
use Laminas\Db\Adapter\AdapterInterface;
16766 efrain 7
use LeadersLinked\Cache\CacheInterface;
1 www 8
use Laminas\Mvc\Controller\AbstractActionController;
9
use Laminas\Log\LoggerInterface;
10
use Laminas\View\Model\ViewModel;
11
use Laminas\View\Model\JsonModel;
12
 
13
use LeadersLinked\Library\Functions;
14
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
15
use LeadersLinked\Library\Image;
16
use LeadersLinked\Mapper\CompanyMicrolearningTopicMapper;
17
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleMapper;
18
use LeadersLinked\Model\CompanyMicrolearningCapsule;
19
use LeadersLinked\Form\CapsuleAddForm;
20
use LeadersLinked\Form\CapsuleEditForm;
21
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleUserMapper;
22
use LeadersLinked\Form\CapsuleForm;
23
use LeadersLinked\Mapper\QueryMapper;
24
use LeadersLinked\Mapper\UserMapper;
25
use LeadersLinked\Model\CompanyMicrolearningCapsuleUser;
26
 
27
class MicrolearningCapsuleController extends AbstractActionController
28
{
29
    /**
30
     *
31
     * @var AdapterInterface
32
     */
33
    private $adapter;
34
 
35
 
36
    /**
37
     *
16766 efrain 38
     * @var CacheInterface
1 www 39
     */
40
    private $cache;
41
 
42
    /**
43
     *
44
     * @var  LoggerInterface
45
     */
46
    private $logger;
47
 
48
 
49
    /**
50
     *
51
     * @var array
52
     */
53
    private $config;
54
 
55
    /**
56
     *
57
     * @param AdapterInterface $adapter
16766 efrain 58
     * @param CacheInterface $cache
1 www 59
     * @param LoggerInterface $logger
60
     * @param array $config
61
     */
62
    public function __construct($adapter, $cache , $logger,  $config)
63
    {
64
        $this->adapter      = $adapter;
65
        $this->cache        = $cache;
66
        $this->logger       = $logger;
67
        $this->config       = $config;
68
 
69
    }
70
 
71
    /**
72
     *
73
     * Generación del listado de perfiles
74
     * {@inheritDoc}
75
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
76
     */
77
    public function indexAction()
78
    {
79
        $request = $this->getRequest();
80
 
81
        $currentUserPlugin = $this->plugin('currentUserPlugin');
82
        $currentUser = $currentUserPlugin->getUser();
83
        $currentCompany = $currentUserPlugin->getCompany();
84
 
85
 
86
 
87
 
88
        $request = $this->getRequest();
89
        if($request->isGet()) {
90
 
91
 
92
            $headers  = $request->getHeaders();
93
 
94
            $isJson = false;
95
            if($headers->has('Accept')) {
96
                $accept = $headers->get('Accept');
97
 
98
                $prioritized = $accept->getPrioritized();
99
 
100
                foreach($prioritized as $key => $value) {
101
                    $raw = trim($value->getRaw());
102
 
103
                    if(!$isJson) {
104
                        $isJson = strpos($raw, 'json');
105
                    }
106
 
107
                }
108
            }
109
 
110
            if($isJson) {
111
 
112
 
16766 efrain 113
                $topic_uuid = Functions::sanitizeFilterString($this->params()->fromQuery('topic_uuid'));
1 www 114
 
6829 nelberth 115
                $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
116
                $topic = $topicMapper->fetchOneByUuid($topic_uuid);
1 www 117
 
6829 nelberth 118
                if(!$topic) {
1 www 119
                    return new JsonModel([
120
                       'success' => false,
121
                       'data' => 'ERROR_TOPIC_NOT_FOUND'
122
                    ]);
123
 
124
                }
125
 
6829 nelberth 126
                if($topic->company_id != $currentCompany->id) {
1 www 127
                    return new JsonModel([
128
                        'success'   => false,
129
                        'data'   => 'ERROR_UNAUTHORIZED'
130
                    ]);
131
                }
132
 
133
                $search = $this->params()->fromQuery('search', []);
16766 efrain 134
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);
1 www 135
 
136
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
6973 nelberth 137
                $page               = (intval($this->params()->fromQuery('start', 1), 10)/$records_x_page)+1;
1 www 138
                $order =  $this->params()->fromQuery('order', []);
139
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
16766 efrain 140
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : strtoupper(Functions::sanitizeFilterString($order[0]['dir']));
1 www 141
 
142
                $fields =  ['name'];
143
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';
144
 
145
                if(!in_array($order_direction, ['ASC', 'DESC'])) {
146
                    $order_direction = 'ASC';
147
                }
148
 
149
 
150
 
151
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
152
                $allowAdd = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/capsules/add');
153
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/capsules/edit');
154
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/capsules/delete');
155
                $allowUsers = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/capsules/users');
156
 
157
                $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
6829 nelberth 158
                $paginator = $capsuleMapper->fetchAllDataTableByCompanyIdAndTopicId($topic->company_id, $topic->id, $search, $page, $records_x_page, $order_field, $order_direction);
1 www 159
 
160
 
161
                $companyMicrolearningCapsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
162
                 $records = $paginator->getCurrentItems();
163
 
164
 
165
                $items = [];
166
                foreach($records as $record)
167
                {
168
 
169
                    //print_r($record);
170
 
6829 nelberth 171
                    $total_users        = $companyMicrolearningCapsuleUserMapper->fetchCountUsersByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $topic->id, $record->id);
172
                    $total_users_active = $companyMicrolearningCapsuleUserMapper->fetchCountUsersActiveByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $topic->id, $record->id);
1 www 173
 
174
 
175
 
176
                    switch($record->status) {
177
                        case  CompanyMicrolearningCapsule::STATUS_ACTIVE :
178
                            $status = 'LABEL_ACTIVE';
179
                            break;
180
 
181
                        case  CompanyMicrolearningCapsule::STATUS_INACTIVE :
182
                            $status = 'LABEL_INACTIVE';
183
                            break;
184
 
185
                        default :
186
                            $status = '';
187
                            break;
188
                    }
189
 
190
 
191
                    switch($record->privacy) {
192
                        case  CompanyMicrolearningCapsule::PRIVACY_PUBLIC :
193
                            $privacy = 'LABEL_PUBLIC';
194
                            break;
195
 
196
                        case  CompanyMicrolearningCapsule::PRIVACY_PRIVATE :
197
                            $privacy = 'LABEL_PRIVATE';
198
                            break;
199
 
200
                        default :
201
                            $privacy = '';
202
                            break;
203
                    }
204
 
205
                    switch($record->type) {
206
                        case  CompanyMicrolearningCapsule::TYPE_FREE :
207
                            $type = 'LABEL_FREE';
208
                            break;
209
 
210
                        case  CompanyMicrolearningCapsule::TYPE_PRIVATE :
211
                            $type = 'LABEL_PRIVATE';
212
                            break;
213
 
214
                        case  CompanyMicrolearningCapsule::TYPE_SELLING :
215
                            $type = 'LABEL_SELLING';
216
                            break;
217
 
218
 
219
                        default :
220
                            $privacy = '';
221
                            break;
222
                    }
223
 
224
                    $params = [
6829 nelberth 225
                        'topic_uuid'    => $topic->uuid,
1 www 226
                        'capsule_uuid'  => $record->uuid
227
                    ];
228
 
229
 
230
                    $item = [
231
 
232
                        'name' => $record->name,
233
                        'details' => [
234
                            'status' => $status,
235
                            'privacy' => $privacy,
236
                            'type' => $type,
237
                            'cost' => $record->cost,
238
                            'total_users' => $total_users,
239
                            'total_users_active' => $total_users_active,
240
                         ],
241
 
242
                        'images' => [
243
                            'image' => $this->url()->fromRoute('storage', ['type' => 'microlearning-capsule', 'code' => $record->uuid, 'filename' => $record->image]),
244
                            'marketplace' => $record->marketplace ?  $this->url()->fromRoute('storage', ['type' => 'microlearning-capsule', 'code' => $record->uuid, 'filename' => $record->marketplace]) : '',
245
                        ] ,
246
                        'actions' => [
247
                            'link_edit' => $allowEdit ? $this->url()->fromRoute('microlearning/content/capsules/edit', $params)  : '',
248
                            'link_delete' => $allowDelete ? $this->url()->fromRoute('microlearning/content/capsules/delete', $params)  : '',
249
                            'link_total_users' => $allowUsers && $total_users ? $this->url()->fromRoute('microlearning/content/capsules/users', [
6829 nelberth 250
                                'topic_uuid'    => $topic->uuid,
1 www 251
                                'capsule_uuid'  => $record->uuid,
252
                                'type' => 'all'
253
                             ])  : '',
254
                            'link_total_users_actives' => $allowUsers && $total_users_active ? $this->url()->fromRoute('microlearning/content/capsules/users', [
6829 nelberth 255
                                'topic_uuid'    => $topic->uuid,
1 www 256
                                'capsule_uuid'  => $record->uuid,
257
                                'type' => 'active'
258
                            ])  : '',
259
                        ] ,
260
 
261
 
262
                     ];
263
 
264
 
265
                    array_push($items, $item);
266
                }
267
 
268
 
269
 
270
                return new JsonModel([
271
                    'success' => true,
272
                    'data' => [
6829 nelberth 273
                        'link_add' => $allowAdd ? $this->url()->fromRoute('microlearning/content/capsules/add', ['topic_uuid' => $topic->uuid] )  : '',
1 www 274
                        'items' => $items,
275
                        'total' => $paginator->getTotalItemCount(),
276
                    ]
277
                ]);
278
 
279
 
280
 
281
 
282
 
283
 
284
            } else {
285
 
286
                $image_size = $this->config['leaderslinked.image_sizes.microlearning_image_upload'];
287
                $marketplace_size = $this->config['leaderslinked.image_sizes.marketplace'];
288
 
289
                $form = new CapsuleForm($this->adapter, $currentCompany->id);
290
                $formAdd = new CapsuleAddForm($currentCompany->internal);
291
                $formEdit = new CapsuleEditForm($currentCompany->internal);
292
 
293
                $this->layout()->setTemplate('layout/layout-backend.phtml');
294
                $viewModel = new ViewModel();
295
                $viewModel->setTemplate('leaders-linked/microlearning-capsules/index.phtml');
296
                $viewModel->setVariables([
297
                   'form' => $form,
298
                   'formAdd' => $formAdd,
299
                   'formEdit' => $formEdit,
300
                   'company_uuid' => $currentCompany->uuid,
301
                   'image_size' => $image_size,
302
                   'marketplace_size' => $marketplace_size,
303
 
304
                ]);
305
                return $viewModel ;
306
            }
307
 
308
        } else {
309
            return new JsonModel([
310
                'success' => false,
311
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
312
            ]);
313
        }
314
    }
315
 
316
    public function addAction()
317
    {
318
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
319
        $currentUser        = $currentUserPlugin->getUser();
320
        $currentCompany     = $currentUserPlugin->getCompany();
321
 
322
        $request    = $this->getRequest();
6829 nelberth 323
        $topic_uuid = $this->params()->fromRoute('topic_uuid');
1 www 324
 
6829 nelberth 325
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
326
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
327
        if(!$topic) {
1 www 328
            return new JsonModel([
329
                'success'   => false,
330
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
331
            ]);
332
        }
333
 
6829 nelberth 334
        if($topic->company_id != $currentCompany->id) {
1 www 335
            return new JsonModel([
336
                'success'   => false,
337
                'data'   => 'ERROR_UNAUTHORIZED'
338
            ]);
339
        }
340
 
341
 
342
        if($request->isPost()) {
343
            $form = new  CapsuleAddForm($currentCompany->internal);
344
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
345
 
346
            $form->setData($dataPost);
347
 
348
            if($form->isValid()) {
349
                $dataPost = (array) $form->getData();
350
 
351
                $hydrator = new ObjectPropertyHydrator();
352
                $capsule = new CompanyMicrolearningCapsule();
353
                $hydrator->hydrate($dataPost, $capsule);
354
 
6829 nelberth 355
                $capsule->company_id = $topic->company_id;
356
                $capsule->topic_id = $topic->id;
1458 efrain 357
                $capsule->image = '';
358
                $capsule->marketplace = '';
1 www 359
 
360
                $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
361
                if($capsuleMapper->insert($capsule)) {
362
 
363
                    $capsule = $capsuleMapper->fetchOne($capsule->id);
364
 
365
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_capsule'] .  $capsule->uuid;
366
                    if(!file_exists($target_path)) {
367
                        mkdir($target_path, 0755, true);
368
                    }
369
 
370
 
371
                    $files = $this->getRequest()->getFiles()->toArray();
6829 nelberth 372
 
6827 nelberth 373
                    $fileBase64Content = $this->params()->fromPost('file');
374
                    try {
375
 
376
                        $fileBase64Content = base64_decode($fileBase64Content);
6830 nelberth 377
                        $target_path = $this->config['leaderslinked.fullpath.microlearning_capsule'] . $capsule->uuid;
6854 nelberth 378
                        $capsule_filename      = 'capsule-' .uniqid() . '.jpg';
6830 nelberth 379
                        $capsule_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp';
380
                        if(!file_exists($capsule_tmp_filename)) {
381
                            mkdir($capsule_tmp_filename, 0755, true);
6827 nelberth 382
                        }
6830 nelberth 383
                        $capsule_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $capsule_filename;
384
                            file_put_contents($capsule_tmp_filename, $fileBase64Content);
6827 nelberth 385
 
386
                        list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
387
 
388
                        $crop_to_dimensions = false;
6830 nelberth 389
                        if(Image::uploadImage($capsule_tmp_filename, $target_path, $capsule_filename, $target_width, $target_height, $crop_to_dimensions )) {
390
                            $capsule->image = basename($capsule_filename);
391
                            $capsuleMapper->update($capsule);
6827 nelberth 392
                        }
393
                    } catch(\Throwable $e) {
394
                        error_log($e->getTraceAsString());
6871 nelberth 395
                    }
6827 nelberth 396
 
6872 nelberth 397
                    $fileBase64Content2 = $this->params()->fromPost('marketplace');
6871 nelberth 398
                    try {
399
 
6872 nelberth 400
                        $fileBase64Content2 = base64_decode($fileBase64Content2);
6943 nelberth 401
                        $target_path2 = $this->config['leaderslinked.fullpath.microlearning_capsule'] . $capsule->uuid;
6931 nelberth 402
                        $capsule_filename2  = 'marketplace-' .uniqid() . '.jpg';
403
                        $capsule_tmp_filename2 = 'data' . DIRECTORY_SEPARATOR . 'tmp';
404
                        if(!file_exists($capsule_tmp_filename2)) {
405
                            mkdir($capsule_tmp_filename2, 0755, true);
6871 nelberth 406
                        }
6931 nelberth 407
                        $capsule_tmp_filename2 = 'data' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $capsule_filename2;
408
                            file_put_contents($capsule_tmp_filename2, $fileBase64Content2);
6943 nelberth 409
 
6871 nelberth 410
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.marketplace']);
6827 nelberth 411
 
6871 nelberth 412
                        $crop_to_dimensions = false;
6931 nelberth 413
                        if(Image::uploadImage($capsule_tmp_filename2, $target_path2, $capsule_filename2, $target_width, $target_height, $crop_to_dimensions )) {
414
                            $capsule->marketplace = basename($capsule_filename2);
6871 nelberth 415
                            $capsuleMapper->update($capsule);
416
                        }
417
                    } catch(\Throwable $e) {
418
                        error_log($e->getTraceAsString());
419
                    }
6942 nelberth 420
 
6829 nelberth 421
                    /*
1 www 422
                    if(isset($files['file']) && empty($files['file']['error'])) {
423
                        $tmp_filename  = $files['file']['tmp_name'];
424
                        //$filename      = $this->normalizeString($files['file']['name']);
425
 
426
                        try {
427
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
428
 
429
                            $filename = 'capsule-' .uniqid() . '.png';
430
                            $crop_to_dimensions = true;
431
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
432
                                $capsule->image = $filename;
433
                                $capsuleMapper->update($capsule);
434
                            }
435
                        } catch(\Throwable $e) {
436
                            error_log($e->getTraceAsString());
437
                        }
438
                    }
6829 nelberth 439
                    */
1 www 440
 
441
 
6871 nelberth 442
                   /* if(isset($files['marketplace']) && empty($files['marketplace']['error'])) {
1 www 443
                        $tmp_filename  = $files['marketplace']['tmp_name'];
444
                        //$filename      = $this->normalizeString($files['marketplace']['name']);
445
 
446
                        try {
447
 
448
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.marketplace']);
449
 
450
                            $filename = 'marketplace-' .uniqid() . '.png';
451
                            $crop_to_dimensions = true;
452
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
453
                                $capsule->marketplace = $filename;
454
                                $capsuleMapper->update($capsule);
455
                            }
456
                        } catch(\Throwable $e) {
457
                            error_log($e->getTraceAsString());
458
                        }
459
                    }
6871 nelberth 460
                    */
6829 nelberth 461
                    $this->logger->info('Se agrego la cápsula ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1 www 462
 
463
                    $data = [
6945 nelberth 464
                        'success'   => true,
465
                        'data'   => 'LABEL_RECORD_ADDED'
1 www 466
                    ];
467
                } else {
468
                    $data = [
469
                        'success'   => false,
6829 nelberth 470
                        'data'      => $topicMapper->getError()
1 www 471
                    ];
472
 
473
                }
474
 
475
                return new JsonModel($data);
476
 
477
            } else {
478
                $messages = [];
479
                $form_messages = (array) $form->getMessages();
480
                foreach($form_messages  as $fieldname => $field_messages)
481
                {
482
 
483
                    $messages[$fieldname] = array_values($field_messages);
484
                }
485
 
486
                return new JsonModel([
487
                    'success'   => false,
488
                    'data'   => $messages
489
                ]);
490
            }
491
 
492
        } else {
493
            $data = [
494
                'success' => false,
495
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
496
            ];
497
 
498
            return new JsonModel($data);
499
        }
500
 
501
        return new JsonModel($data);
502
    }
503
 
504
    /**
505
     *
506
     * Borrar un perfil excepto el público
507
     * @return \Laminas\View\Model\JsonModel
508
     */
509
    public function deleteAction()
510
    {
511
        $currentUserPlugin = $this->plugin('currentUserPlugin');
512
        $currentUser    = $currentUserPlugin->getUser();
513
        $currentCompany = $currentUserPlugin->getCompany();
514
 
515
        $request        = $this->getRequest();
6829 nelberth 516
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
1 www 517
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
518
 
519
 
6829 nelberth 520
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
521
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
522
        if(!$topic) {
1 www 523
            return new JsonModel([
524
                'success'   => false,
525
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
526
            ]);
527
        }
528
 
6829 nelberth 529
        if($topic->company_id != $currentCompany->id) {
1 www 530
            return new JsonModel([
531
                'success'   => false,
532
                'data'   => 'ERROR_UNAUTHORIZED'
533
            ]);
534
        }
535
 
536
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
537
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
538
        if(!$capsule) {
539
            return new JsonModel([
540
                'success'   => false,
541
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
542
            ]);
543
        }
544
 
6829 nelberth 545
        if($capsule->topic_id != $topic->id) {
1 www 546
            return new JsonModel([
547
                'success'   => false,
548
                'data'   => 'ERROR_UNAUTHORIZED'
549
            ]);
550
        }
551
 
552
        if($request->isPost()) {
553
 
554
            $result =  $capsuleMapper->delete($capsule);
555
            if($result) {
556
                $this->logger->info('Se borro la cápsula : ' .  $capsule->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
557
                try {
558
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_capsule'] . $capsule->uuid;
559
                    if(file_exists($target_path)) {
560
                        Functions::rmDirRecursive($target_path);
561
                    }
562
                } catch(\Throwable $e) {
563
                    error_log($e->getTraceAsString());
564
                }
565
 
566
 
567
                $data = [
568
                    'success' => true,
569
                    'data' => 'LABEL_RECORD_DELETED'
570
                ];
571
            } else {
572
 
573
                $data = [
574
                    'success'   => false,
575
                    'data'      => $capsuleMapper->getError()
576
                ];
577
 
578
                return new JsonModel($data);
579
            }
580
 
581
        } else {
582
            $data = [
583
                'success' => false,
584
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
585
            ];
586
 
587
            return new JsonModel($data);
588
        }
589
 
590
        return new JsonModel($data);
591
    }
592
 
593
 
594
    public function editAction()
595
    {
596
        $currentUserPlugin = $this->plugin('currentUserPlugin');
597
        $currentUser    = $currentUserPlugin->getUser();
598
        $currentCompany = $currentUserPlugin->getCompany();
599
 
600
        $request    = $this->getRequest();
6829 nelberth 601
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
1 www 602
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
603
 
604
 
6829 nelberth 605
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
606
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
607
        if(!$topic) {
1 www 608
            return new JsonModel([
609
                'success'   => false,
610
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
611
            ]);
612
        }
613
 
614
 
615
 
6829 nelberth 616
        if($topic->company_id != $currentCompany->id) {
1 www 617
            return new JsonModel([
618
                'success'   => false,
619
                'data'   => 'ERROR_UNAUTHORIZED'
620
            ]);
621
        }
622
 
623
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
624
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
625
        if(!$capsule) {
626
            return new JsonModel([
627
                'success'   => false,
628
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
629
            ]);
630
        }
631
 
632
 
6829 nelberth 633
        if($capsule->topic_id != $topic->id) {
1 www 634
            return new JsonModel([
635
                'success'   => false,
636
                'data'   => 'ERROR_UNAUTHORIZED'
637
            ]);
638
        }
639
 
640
        if($request->isGet()) {
641
            $data = [
642
                'success' => true,
643
                'data' => [
644
                    'name' => $capsule->name,
645
                    'description' => $capsule->description,
646
                    'order' => $capsule->order,
647
                    'status' => $capsule->status,
648
                    'privacy' => $capsule->privacy,
649
                    'type' => $capsule->type,
6974 nelberth 650
                    'cost' => $capsule->cost,
6983 nelberth 651
                    'image' => $this->url()->fromRoute('storage', ['type' => 'microlearning-capsule', 'code' => $capsule->uuid, 'filename' => $capsule->image]),
652
                    'marketplace' =>  $this->url()->fromRoute('storage', ['type' => 'microlearning-capsule', 'code' => $capsule->uuid, 'filename' => $capsule->marketplace]),
6982 nelberth 653
 
1 www 654
                ]
655
            ];
656
 
657
            return new JsonModel($data);
658
        }
659
        else if($request->isPost()) {
660
            $form = new  CapsuleEditForm($currentCompany->internal);
661
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
662
 
663
            $form->setData($dataPost);
664
 
665
            if($form->isValid()) {
666
                $dataPost = (array) $form->getData();
667
 
668
                $hydrator = new ObjectPropertyHydrator();
669
                $hydrator->hydrate($dataPost, $capsule);
670
 
671
                $capsule->image = null;
672
                $capsule->marketplace = null;
673
 
674
                if($capsuleMapper->update($capsule)) {
675
 
676
                    $capsule = $capsuleMapper->fetchOne($capsule->id);
6990 nelberth 677
 
678
                    $fileBase64Content = $this->params()->fromPost('file');
6994 nelberth 679
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_capsule'] . $capsule->uuid;
6990 nelberth 680
                    try {
6995 nelberth 681
                        if($capsule->image) {
6990 nelberth 682
 
683
                            if(!image ::delete($target_path, $capsule->image)) {
684
                                return new JsonModel([
685
                                    'success'   => false,
686
                                    'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
687
                                ]);
688
                            }
689
                        }
690
 
691
                        $fileBase64Content = base64_decode($fileBase64Content);
6994 nelberth 692
 
6990 nelberth 693
                        $capsule_filename      = 'capsule-' .uniqid() . '.jpg';
694
                        $capsule_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp';
695
                        if(!file_exists($capsule_tmp_filename)) {
696
                            mkdir($capsule_tmp_filename, 0755, true);
697
                        }
698
                        $capsule_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $capsule_filename;
699
                            file_put_contents($capsule_tmp_filename, $fileBase64Content);
700
 
701
                        list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
702
 
703
                        $crop_to_dimensions = false;
704
                        if(Image::uploadImage($capsule_tmp_filename, $target_path, $capsule_filename, $target_width, $target_height, $crop_to_dimensions )) {
705
                            $capsule->image = basename($capsule_filename);
706
                            $capsuleMapper->update($capsule);
707
                        }
708
                    } catch(\Throwable $e) {
709
                        error_log($e->getTraceAsString());
710
                    }
711
 
712
                    $fileBase64Content2 = $this->params()->fromPost('marketplace');
713
                    try {
6995 nelberth 714
                        if($capsule->marketplace) {
6990 nelberth 715
 
716
                            if(!image ::delete($target_path, $capsule->marketplace)) {
717
                                return new JsonModel([
718
                                    'success'   => false,
719
                                    'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
720
                                ]);
721
                            }
722
                        }
723
                        $fileBase64Content2 = base64_decode($fileBase64Content2);
724
                        $capsule_filename2  = 'marketplace-' .uniqid() . '.jpg';
725
                        $capsule_tmp_filename2 = 'data' . DIRECTORY_SEPARATOR . 'tmp';
726
                        if(!file_exists($capsule_tmp_filename2)) {
727
                            mkdir($capsule_tmp_filename2, 0755, true);
728
                        }
729
                        $capsule_tmp_filename2 = 'data' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $capsule_filename2;
730
                            file_put_contents($capsule_tmp_filename2, $fileBase64Content2);
731
 
732
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.marketplace']);
733
 
734
                        $crop_to_dimensions = false;
6994 nelberth 735
                        if(Image::uploadImage($capsule_tmp_filename2, $target_path, $capsule_filename2, $target_width, $target_height, $crop_to_dimensions )) {
6990 nelberth 736
                            $capsule->marketplace = basename($capsule_filename2);
737
                            $capsuleMapper->update($capsule);
738
                        }
739
                    } catch(\Throwable $e) {
740
                        error_log($e->getTraceAsString());
741
                    }
742
                    /*
1 www 743
                    $files = $this->getRequest()->getFiles()->toArray();
744
                    if(isset($files['file']) && empty($files['file']['error'])) {
745
                        $tmp_filename  = $files['file']['tmp_name'];
746
                        //$filename      = $this->normalizeString($files['file']['name']);
747
 
748
                        try {
6829 nelberth 749
                            if($topic->image) {
1 www 750
 
751
                                if(!image ::delete($target_path, $capsule->image)) {
752
                                    return new JsonModel([
753
                                        'success'   => false,
754
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
755
                                    ]);
756
                                }
757
                            }
758
 
759
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
760
 
761
                            $filename = 'capsule-' .uniqid() . '.png';
762
                            $crop_to_dimensions = true;
763
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
764
                                $capsule->image = $filename;
765
                                $capsuleMapper->update($capsule);
766
                            }
767
                        } catch(\Throwable $e) {
768
                            error_log($e->getTraceAsString());
769
                        }
770
                    }
771
 
772
 
773
 
774
                    if(isset($files['marketplace']) && empty($files['marketplace']['error'])) {
775
                        $tmp_filename  = $files['marketplace']['tmp_name'];
776
                        //$filename      = $this->normalizeString($files['marketplace']['name']);
777
 
778
                        try {
6829 nelberth 779
                            if($topic->marketplace) {
1 www 780
 
781
                                if(!image ::delete($target_path, $capsule->marketplace)) {
782
                                    return new JsonModel([
783
                                        'success'   => false,
784
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
785
                                    ]);
786
                                }
787
                            }
788
 
789
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.marketplace']);
790
 
791
                            $filename = 'marketplace-' .uniqid() . '.png';
792
                            $crop_to_dimensions = true;
793
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
794
                                $capsule->marketplace = $filename;
795
                                $capsuleMapper->update($capsule);
796
                            }
797
                        } catch(\Throwable $e) {
798
                            error_log($e->getTraceAsString());
799
                        }
800
                    }
6990 nelberth 801
                    */
1 www 802
                    $this->logger->info('Se edito la cápsula ' . $capsule->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
803
 
804
                    $data = [
805
                        'success'   => true,
806
                        'data'   => 'LABEL_RECORD_UPDATED'
807
                    ];
808
                } else {
809
                    $data = [
810
                        'success'   => false,
811
                        'data'      => $capsuleMapper->getError()
812
                    ];
813
 
814
                }
815
 
816
                return new JsonModel($data);
817
 
818
            } else {
819
                $messages = [];
820
                $form_messages = (array) $form->getMessages();
821
                foreach($form_messages  as $fieldname => $field_messages)
822
                {
823
 
824
                    $messages[$fieldname] = array_values($field_messages);
825
                }
826
 
827
                return new JsonModel([
828
                    'success'   => false,
829
                    'data'   => $messages
830
                ]);
831
            }
832
        } else {
833
            $data = [
834
                'success' => false,
835
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
836
            ];
837
 
838
            return new JsonModel($data);
839
        }
840
 
841
        return new JsonModel($data);
842
    }
843
 
844
 
845
    public function usersAction()
846
    {
847
        $currentUserPlugin = $this->plugin('currentUserPlugin');
848
        $currentUser    = $currentUserPlugin->getUser();
849
        $currentCompany = $currentUserPlugin->getCompany();
850
 
851
        $request        = $this->getRequest();
6829 nelberth 852
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
1 www 853
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
854
        $type           = $this->params()->fromRoute('type');
855
 
856
 
6829 nelberth 857
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
858
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
859
        if(!$topic) {
1 www 860
            return new JsonModel([
861
                'success'   => false,
862
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
863
            ]);
864
        }
865
 
6829 nelberth 866
        if($topic->company_id != $currentCompany->id) {
1 www 867
            return new JsonModel([
868
                'success'   => false,
869
                'data'   => 'ERROR_UNAUTHORIZED'
870
            ]);
871
        }
872
 
873
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
874
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
875
        if(!$capsule) {
876
            return new JsonModel([
877
                'success'   => false,
878
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
879
            ]);
880
        }
881
 
6829 nelberth 882
        if($capsule->topic_id != $topic->id) {
1 www 883
            return new JsonModel([
884
                'success'   => false,
885
                'data'   => 'ERROR_UNAUTHORIZED'
886
            ]);
887
        }
888
 
889
        if($request->isGet()) {
890
 
891
 
892
            $queryMapper = QueryMapper::getInstance($this->adapter);
893
            $sql = $queryMapper->getSql();
894
            $select = $sql->select();
895
            $select->columns(['access', 'paid_from', 'paid_to', 'added_on']);
896
            $select->from(['tb1' => CompanyMicrolearningCapsuleUserMapper::_TABLE] );
897
            $select->join(['tb2' => UserMapper::_TABLE], 'tb1.user_id = tb2.id', ['uuid', 'first_name', 'last_name', 'email']);
898
            $select->where->equalTo('tb1.company_id', $capsule->company_id);
6829 nelberth 899
            $select->where->equalTo('tb1.topic_id', $capsule->topic_id);
1 www 900
            $select->where->equalTo('tb1.capsule_id', $capsule->id);
901
 
902
            if($type == 'active') {
903
                $now = date('Y-m-d H:i:s');
904
                $select->where->nest->equalTo('access', CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED)->or->nest()
905
                ->equalTo('access', CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD)
906
                ->and->lessThanOrEqualTo('paid_from', $now)->and->greaterThanOrEqualTo('paid_to', $now )->unnest()->unnest();
907
 
908
            }
909
 
910
 
911
            $select->order(['first_name', 'last_name', 'email']);
912
            $records  = $queryMapper->fetchAll($select);
913
 
914
 
915
            $items = [ ];
916
            foreach($records as $record)
917
            {
918
 
919
 
920
 
921
 
922
                switch($record['access'])
923
                {
924
                    case CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED :
925
                        $details['access'] = 'LABEL_UNLIMIT';
926
                        break;
927
 
928
                    case CompanyMicrolearningCapsuleUser::ACCESS_REVOKE :
929
                        $details['access'] = 'LABEL_REVOKED';
930
                        break;
931
 
932
                    case CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD :
933
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
934
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
935
 
936
                        $details['access'] = 'LABEL_PAY_PERIOD';
937
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
938
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
939
                        break;
940
 
941
                    case CompanyMicrolearningCapsuleUser::ACCESS_SUPENDED :
942
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
943
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
944
 
945
                        $details['access'] = 'LABEL_SUSPENDED';
946
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
947
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
948
                        break;
949
 
950
                    case CompanyMicrolearningCapsuleUser::ACCESS_CANCELLED :
951
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
952
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
953
 
954
                        $details['access'] = 'LABEL_CANCELLED';
955
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
956
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
957
                        break;
958
 
959
                }
960
 
961
 
962
                $item = [
963
                    'first_name' => $record['first_name'],
964
                    'last_name' => $record['last_name'],
965
                    'email' => $record['email'],
966
                    'details' => $details,
967
                ];
968
 
969
 
970
 
971
                array_push($items, $item);
972
 
973
 
974
            }
975
 
976
            return new JsonModel([
977
                'success' => true,
978
                'data' => [
6829 nelberth 979
                    'topic' => $topic->name,
1 www 980
                    'capsule' => $capsule->name,
981
                    'items' => $items,
982
                ]
983
            ]);
984
 
985
 
986
 
987
        } else {
988
            $data = [
989
                'success' => false,
990
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
991
            ];
992
 
993
            return new JsonModel($data);
994
        }
995
 
996
        return new JsonModel($data);
997
    }
998
 
999
}