Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17133 | Rev 17178 | 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;
16768 efrain 7
 
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
use LeadersLinked\Library\Functions;
13
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
14
use LeadersLinked\Library\Image;
17002 efrain 15
use LeadersLinked\Mapper\MicrolearningTopicMapper;
17101 stevensc 16
use LeadersLinked\Mapper\MicrolearningCapsuleMapper;
17002 efrain 17
use LeadersLinked\Model\MicrolearningTopic;
18
use LeadersLinked\Form\Microlearning\TopicAddForm;
19
use LeadersLinked\Form\Microlearning\TopicEditForm;
17081 stevensc 20
use LeadersLinked\Form\Microlearning\TopicForm;
17002 efrain 21
use LeadersLinked\Library\Storage;
17107 stevensc 22
use LeadersLinked\Model\MicrolearningTopicCapsule;
23
use LeadersLinked\Mapper\MicrolearningTopicCapsuleMapper;
1 www 24
 
25
 
26
class MicrolearningTopicController extends AbstractActionController
27
{
28
    /**
29
     *
16769 efrain 30
     * @var \Laminas\Db\Adapter\AdapterInterface
1 www 31
     */
32
    private $adapter;
33
 
34
    /**
35
     *
16769 efrain 36
     * @var \LeadersLinked\Cache\CacheInterface
1 www 37
     */
16769 efrain 38
    private $cache;
39
 
40
 
41
    /**
42
     *
43
     * @var \Laminas\Log\LoggerInterface
44
     */
1 www 45
    private $logger;
46
 
47
    /**
48
     *
49
     * @var array
50
     */
51
    private $config;
52
 
16769 efrain 53
 
1 www 54
    /**
55
     *
16769 efrain 56
     * @var \Laminas\Mvc\I18n\Translator
57
     */
58
    private $translator;
59
 
60
 
61
    /**
62
     *
63
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
64
     * @param \LeadersLinked\Cache\CacheInterface $cache
65
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
1 www 66
     * @param array $config
16769 efrain 67
     * @param \Laminas\Mvc\I18n\Translator $translator
1 www 68
     */
16769 efrain 69
    public function __construct($adapter, $cache, $logger, $config, $translator)
1 www 70
    {
16769 efrain 71
        $this->adapter      = $adapter;
72
        $this->cache        = $cache;
73
        $this->logger       = $logger;
74
        $this->config       = $config;
75
        $this->translator   = $translator;
1 www 76
    }
77
 
78
    /**
79
     *
80
     * Generación del listado de perfiles
81
     * {@inheritDoc}
82
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
83
     */
84
    public function indexAction()
85
    {
86
        $request = $this->getRequest();
87
        $currentUserPlugin = $this->plugin('currentUserPlugin');
88
        $currentCompany = $currentUserPlugin->getCompany();
89
        $currentUser    = $currentUserPlugin->getUser();
90
 
91
 
92
        $request = $this->getRequest();
93
        if($request->isGet()) {
94
 
95
 
96
            $headers  = $request->getHeaders();
97
 
98
            $isJson = false;
99
            if($headers->has('Accept')) {
100
                $accept = $headers->get('Accept');
101
 
102
                $prioritized = $accept->getPrioritized();
103
 
104
                foreach($prioritized as $key => $value) {
105
                    $raw = trim($value->getRaw());
106
 
107
                    if(!$isJson) {
108
                        $isJson = strpos($raw, 'json');
109
                    }
110
 
111
                }
112
            }
113
 
114
            if($isJson) {
115
                $search = $this->params()->fromQuery('search', []);
16766 efrain 116
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);
1 www 117
 
118
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
5655 nelberth 119
                $page               = (intval($this->params()->fromQuery('start', 1), 10)/$records_x_page)+1;
1 www 120
                $order =  $this->params()->fromQuery('order', []);
121
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
16766 efrain 122
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : strtoupper(Functions::sanitizeFilterString($order[0]['dir']));
1 www 123
 
124
                $fields =  ['name'];
125
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';
126
 
127
                if(!in_array($order_direction, ['ASC', 'DESC'])) {
128
                    $order_direction = 'ASC';
129
                }
130
 
131
 
132
 
133
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
134
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/edit');
135
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/delete');
136
 
137
 
17002 efrain 138
                $microlearningTopicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 139
 
17002 efrain 140
                $paginator = $microlearningTopicMapper->fetchAllDataTableByCompanyId($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);
1 www 141
 
17002 efrain 142
 
17018 efrain 143
                $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 144
                $path = $storage->getPathMicrolearningTopic();
145
 
1 www 146
                $records = $paginator->getCurrentItems();
147
 
148
                $items = [];
149
                foreach($records as $record)
150
                {
17002 efrain 151
 
1 www 152
                    switch($record->status) {
17002 efrain 153
                        case  MicrolearningTopic::STATUS_ACTIVE :
1 www 154
                            $status = 'LABEL_ACTIVE';
155
                            break;
156
 
17002 efrain 157
                        case  MicrolearningTopic::STATUS_INACTIVE :
1 www 158
                            $status = 'LABEL_INACTIVE';
159
                            break;
160
 
161
                        default :
162
                            $status = '';
163
                            break;
164
                    }
165
 
166
 
167
 
168
 
169
                    $item = [
170
 
171
                        'name' => $record->name,
172
                        'status' => $status,
17002 efrain 173
                        'image' => $storage->getGenericImage($path, $record->uuid, $record->image),
1 www 174
                        'actions' => [
175
                            'link_edit' => $allowEdit ? $this->url()->fromRoute('microlearning/content/topics/edit', ['id' => $record->uuid ])  : '',
176
                            'link_delete' => $allowDelete ? $this->url()->fromRoute('microlearning/content/topics/delete', ['id' => $record->uuid ]) : '',
177
                        ]
178
 
179
 
180
                    ];
181
 
182
 
183
                    array_push($items, $item);
184
                }
185
 
186
 
187
 
188
                return new JsonModel([
189
                    'success' => true,
190
                    'data' => [
191
                        'items' => $items,
192
                        'total' => $paginator->getTotalItemCount(),
193
                    ]
194
                ]);
195
 
196
 
197
 
198
            } else {
199
 
200
                $image_size = $this->config['leaderslinked.image_sizes.microlearning_image_upload'];
16945 efrain 201
 
17081 stevensc 202
 
17111 stevensc 203
                $form = new TopicForm($this->adapter);
204
                $formAdd = new TopicAddForm($this->adapter, $currentCompany->id);
205
                $formEdit = new TopicEditForm($this->adapter);
1 www 206
                $this->layout()->setTemplate('layout/layout-backend.phtml');
207
                $viewModel = new ViewModel();
208
                $viewModel->setTemplate('leaders-linked/microlearning-topics/index.phtml');
209
                $viewModel->setVariables([
17081 stevensc 210
                    'form' => $form,
1 www 211
                   'formAdd' => $formAdd,
212
                   'formEdit' => $formEdit,
213
                   'company_uuid' => $currentCompany->uuid,
214
                   'image_size' => $image_size,
16945 efrain 215
 
1 www 216
                ]);
217
                return $viewModel ;
218
            }
219
 
220
        } else {
221
            return new JsonModel([
222
                'success' => false,
223
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
224
            ]);
225
        }
226
    }
227
 
228
    public function addAction()
229
    {
230
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
231
        $currentCompany     = $currentUserPlugin->getCompany();
232
        $currentUser        = $currentUserPlugin->getUser();
233
 
234
        $request    = $this->getRequest();
16943 efrain 235
 
17162 stevensc 236
        if(!$request->isPost() && !$request->isGet()) {
17133 stevensc 237
            return new JsonModel([
238
                'success' => false,
239
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
240
            ]);
241
        }
17127 stevensc 242
 
17133 stevensc 243
        if($request->isGet()) {
244
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
1 www 245
 
17133 stevensc 246
            if(!$currentCompany) {
247
                return new JsonModel([
248
                    'success' => false,
249
                    'data' => 'ERROR_COMPANY_NOT_FOUND'
250
                ]);
251
            }
17127 stevensc 252
 
17133 stevensc 253
            $records = $currentCompany ? $capsuleMapper->fetchAllActiveByCompanyId($currentCompany->id) : $capsuleMapper->fetchAllActive();
254
            $capsules = [];
17127 stevensc 255
 
17133 stevensc 256
            foreach($records as $record) {
257
                array_push($capsules, [
258
                    'id' => $record->uuid,
259
                    'name' => $record->name,
260
                ]);
261
            }
17127 stevensc 262
 
17133 stevensc 263
            $data = [
264
                'success' => true,
265
                'data' => [
266
                    'capsules' => $capsules
267
                ]
268
            ];
17127 stevensc 269
 
17133 stevensc 270
            return new JsonModel($data);
271
        }
17127 stevensc 272
 
17133 stevensc 273
        if($request->isPost()) {
274
            $form = new TopicAddForm($this->adapter, $currentCompany->id);
275
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
276
 
277
            $form->setData($dataPost);
278
 
279
            if(!$form->isValid()) {
1 www 280
                $messages = [];
281
                $form_messages = (array) $form->getMessages();
17133 stevensc 282
 
1 www 283
                foreach($form_messages  as $fieldname => $field_messages)
284
                {
285
                    $messages[$fieldname] = array_values($field_messages);
286
                }
287
 
288
                return new JsonModel([
289
                    'success'   => false,
290
                    'data'   => $messages
291
                ]);
292
            }
17133 stevensc 293
 
294
            $dataPost = (array) $form->getData();
295
 
296
            $topic = new MicrolearningTopic();
297
            $topic->name = $dataPost['name'];
298
            $topic->description = $dataPost['description'];
299
            $topic->order = $dataPost['order'];
300
            $topic->status = $dataPost['status'];
301
            $topic->company_id = $currentCompany->id;
302
            $topic->image = '';
1 www 303
 
17133 stevensc 304
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
305
 
306
            if(!$topicMapper->insert($topic)) {
307
                $data = [
308
                    'success'   => false,
309
                    'data'      => $topicMapper->getError()
310
                ];
311
                return new JsonModel($data);
312
            }
313
 
314
            $topic = $topicMapper->fetchOne($topic->id);
315
 
316
            $capsuleUuids = $dataPost['capsule_id'];
17093 stevensc 317
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
17133 stevensc 318
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
319
 
320
            foreach ($capsuleUuids as $capsuleUuid) {
321
                $capsule = $capsuleMapper->fetchOneByUuid($capsuleUuid);
322
 
323
                if ($capsule) {
324
                    $topicCapsule = new MicrolearningTopicCapsule();
325
                    $topicCapsule->topic_id = $topic->id;
326
                    $topicCapsule->capsule_id = $capsule->id;
327
                    $topicCapsule->company_id = $currentCompany->id;
328
                    $topicCapsuleMapper->insert($topicCapsule);
329
                }
330
            }
331
 
332
            $storage = Storage::getInstance($this->config, $this->adapter);
333
            $storage->setFiles($request->getFiles()->toArray());
334
 
335
            if (!$storage->setCurrentFilename('file')) {
336
                return new JsonModel([
337
                    'success'   => false,
338
                    'data'      => 'ERROR_UPLOAD_IMAGE'
339
                ]);
340
            }
17101 stevensc 341
 
17133 stevensc 342
            $target_size = $this->config['leaderslinked.image_sizes.microlearning_image_size'];
343
            list($target_width, $target_height) = explode('x', $target_size);
344
 
345
            $source_filename = $storage->getTmpFilename();
346
            $filename = 'topic-' . uniqid() . '.png';
347
            $target_filename = $storage->composePathToFilename(
348
                Storage::TYPE_MICROLEARNING_TOPIC,
349
                $topic->uuid,
350
                $filename
351
            );
352
 
353
            if (!$storage->uploadImageCrop($source_filename, $target_filename, $target_width, $target_height)) {
17098 stevensc 354
                return new JsonModel([
17133 stevensc 355
                    'success'   => false,
356
                    'data'      => 'ERROR_UPLOAD_IMAGE'
17098 stevensc 357
                ]);
358
            }
17101 stevensc 359
 
17133 stevensc 360
            $topic->image = $filename;
17098 stevensc 361
 
17133 stevensc 362
            if(!$topicMapper->update($topic)) {
363
                return new JsonModel([
364
                    'success'   => false,
365
                    'data'      => $topicMapper->getError()
17093 stevensc 366
                ]);
367
            }
17133 stevensc 368
 
369
            $this->logger->info('Se agrego el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
370
 
1 www 371
            $data = [
17133 stevensc 372
                'success'   => true,
373
                'data'   => 'LABEL_RECORD_ADDED'
17093 stevensc 374
            ];
17133 stevensc 375
 
376
            return new JsonModel($data);
17093 stevensc 377
        }
1 www 378
    }
379
 
380
    /**
381
     *
382
     * Borrar un perfil excepto el público
383
     * @return \Laminas\View\Model\JsonModel
384
     */
385
    public function deleteAction()
386
    {
387
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
388
        $currentCompany     = $currentUserPlugin->getCompany();
389
        $currentUser        = $currentUserPlugin->getUser();
390
 
391
        $request    = $this->getRequest();
392
        $id   = $this->params()->fromRoute('id');
17133 stevensc 393
 
394
        if(!$request->isPost()) {
395
            return new JsonModel([
396
                'success'   => false,
397
                'data'   => 'ERROR_METHOD_NOT_ALLOWED'
398
            ]);
399
        }
400
 
17002 efrain 401
        $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 402
        $topic = $topicMapper->fetchOneByUuid($id);
17133 stevensc 403
 
1 www 404
        if(!$topic) {
405
            return new JsonModel([
406
                'success'   => false,
407
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
408
            ]);
409
        }
410
 
411
        if($topic->company_id != $currentCompany->id) {
412
            return new JsonModel([
413
                'success'   => false,
414
                'data'   => 'ERROR_UNAUTHORIZED'
415
            ]);
416
        }
417
 
17133 stevensc 418
        // Eliminar las relaciones con cápsulas primero
419
        $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
420
        if(!$topicCapsuleMapper->deleteByTopicId($topic->id)) {
421
            return new JsonModel([
422
                'success'   => false,
423
                'data'      => $topicCapsuleMapper->getError()
424
            ]);
425
        }
426
 
427
        // Eliminar archivos de almacenamiento
428
        $storage = Storage::getInstance($this->config, $this->adapter);
429
        $target_path = $storage->getPathMicrolearningTopic();
1 www 430
 
17133 stevensc 431
        if($topic->image) {
432
            if(!$storage->deleteFile($target_path, $topic->uuid, $topic->image)) {
1 www 433
                return new JsonModel([
434
                    'success'   => false,
17133 stevensc 435
                    'data'   => 'ERROR_DELETING_FILE'
1 www 436
                ]);
437
            }
17133 stevensc 438
        }
17002 efrain 439
 
17133 stevensc 440
        // Eliminar el tópico
441
        if(!$topicMapper->delete($topic)) {
442
            return new JsonModel([
443
                'success'   => false,
444
                'data'      => $topicMapper->getError()
445
            ]);
1 www 446
        }
17133 stevensc 447
 
448
        // Registrar la acción en el log
449
        $this->logger->info('Se borro el tópico : ' . $topic->name, [
450
            'user_id' => $currentUser->id,
451
            'ip' => Functions::getUserIP()
452
        ]);
1 www 453
 
17133 stevensc 454
        return new JsonModel([
455
            'success' => true,
456
            'data' => 'LABEL_RECORD_DELETED'
457
        ]);
1 www 458
    }
459
 
460
 
461
    public function editAction()
462
    {
463
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
464
        $currentCompany     = $currentUserPlugin->getCompany();
465
        $currentUser        = $currentUserPlugin->getUser();
466
 
467
        $request    = $this->getRequest();
468
        $id   = $this->params()->fromRoute('id');
469
 
17109 stevensc 470
 
471
 
17002 efrain 472
        $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 473
        $topic = $topicMapper->fetchOneByUuid($id);
474
        if(!$topic) {
475
            return new JsonModel([
476
                'success'   => false,
477
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
478
            ]);
479
        }
480
 
481
        if($topic->company_id != $currentCompany->id) {
482
            return new JsonModel([
483
                'success'   => false,
484
                'data'   => 'ERROR_UNAUTHORIZED'
485
            ]);
486
        }
487
 
488
        if($request->isGet()) {
17109 stevensc 489
 
17018 efrain 490
            $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 491
            $path = $storage->getPathMicrolearningTopic();
492
 
1 www 493
            $data = [
494
                'success' => true,
495
                'data' => [
496
                    'name' => $topic->name,
497
                    'description' => $topic->description,
498
                    'order' => $topic->order,
499
                    'status' => $topic->status,
17109 stevensc 500
                    'image'=> $storage->getGenericImage($path, $topic->uuid, $topic->image)
1 www 501
                ]
502
            ];
503
 
504
            return new JsonModel($data);
505
        }
506
        else if($request->isPost()) {
507
            $form = new  TopicEditForm();
508
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
509
 
510
            $form->setData($dataPost);
511
 
512
            if($form->isValid()) {
513
                $dataPost = (array) $form->getData();
514
 
515
                $hydrator = new ObjectPropertyHydrator();
516
                $hydrator->hydrate($dataPost, $topic);
517
                $topic->image = null;
16945 efrain 518
 
1 www 519
                if($topicMapper->update($topic)) {
520
                    $topic = $topicMapper->fetchOne($topic->id);
521
 
17002 efrain 522
                    $image = Image::getInstance($this->config);
523
                    $target_path = $image->getStorage()->getPathMicrolearningTopic();
1 www 524
 
17109 stevensc 525
 
1 www 526
                    $files = $this->getRequest()->getFiles()->toArray();
527
                    if(isset($files['file']) && empty($files['file']['error'])) {
528
                        $tmp_filename  = $files['file']['tmp_name'];
17109 stevensc 529
                        //$filename      = \LeadersLinked\Library\Functions::normalizeStringFilename($files['file']['name']);
1 www 530
 
531
                        try {
532
                            if($topic->image) {
17109 stevensc 533
 
17002 efrain 534
                                if(!$image->getStorage()->deleteFile($target_path, $topic->uuid, $topic->image)) {
1 www 535
                                    return new JsonModel([
536
                                        'success'   => false,
537
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
538
                                    ]);
539
                                }
540
                            }
541
 
542
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
543
 
544
                            $filename = 'topic-' .uniqid() . '.png';
16943 efrain 545
                            $crop_to_dimensions = false;
17002 efrain 546
                            $unlink_source = true;
547
 
17018 efrain 548
                            if($image->uploadProcessChangeSize($tmp_filename, $target_path, $topic->uuid, $filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
1 www 549
                                $topic->image = $filename;
550
                                $topicMapper->update($topic);
551
                            }
552
                        } catch(\Throwable $e) {
553
                            error_log($e->getTraceAsString());
554
                        }
555
                    }
556
 
17109 stevensc 557
 
558
 
559
 
1 www 560
                    $this->logger->info('Se edito el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
561
 
562
                    $data = [
563
                        'success'   => true,
564
                        'data'   => 'LABEL_RECORD_UPDATED'
16943 efrain 565
                    ];
1 www 566
                } else {
567
                    $data = [
568
                        'success'   => false,
569
                        'data'      => $topicMapper->getError()
570
                    ];
571
 
572
                }
573
 
574
                return new JsonModel($data);
575
 
576
            } else {
577
                $messages = [];
578
                $form_messages = (array) $form->getMessages();
579
                foreach($form_messages  as $fieldname => $field_messages)
580
                {
17109 stevensc 581
 
1 www 582
                    $messages[$fieldname] = array_values($field_messages);
583
                }
584
 
585
                return new JsonModel([
586
                    'success'   => false,
587
                    'data'   => $messages
588
                ]);
589
            }
590
        } else {
591
            $data = [
592
                'success' => false,
593
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
594
            ];
595
 
596
            return new JsonModel($data);
597
        }
17109 stevensc 598
 
599
        return new JsonModel($data);
1 www 600
    }
601
}