Proyectos de Subversion LeadersLinked - Backend

Rev

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