Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17018 | Rev 17093 | 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
 
313
        } else {
314
            $data = [
315
                'success' => false,
316
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
317
            ];
318
 
319
            return new JsonModel($data);
320
        }
321
 
322
        return new JsonModel($data);
323
    }
324
 
325
    /**
326
     *
327
     * Borrar un perfil excepto el público
328
     * @return \Laminas\View\Model\JsonModel
329
     */
330
    public function deleteAction()
331
    {
332
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
333
        $currentCompany     = $currentUserPlugin->getCompany();
334
        $currentUser        = $currentUserPlugin->getUser();
335
 
336
        $request    = $this->getRequest();
337
        $id   = $this->params()->fromRoute('id');
338
 
339
 
17002 efrain 340
        $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 341
        $topic = $topicMapper->fetchOneByUuid($id);
342
        if(!$topic) {
343
            return new JsonModel([
344
                'success'   => false,
345
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
346
            ]);
347
        }
348
 
349
        if($topic->company_id != $currentCompany->id) {
350
            return new JsonModel([
351
                'success'   => false,
352
                'data'   => 'ERROR_UNAUTHORIZED'
353
            ]);
354
        }
355
 
356
 
357
 
358
        if($request->isPost()) {
17002 efrain 359
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
1 www 360
            $count = $capsuleMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
361
            if($count > 0 ) {
362
                return new JsonModel([
363
                    'success'   => false,
364
                    'data'   => 'ERROR_SQL_CANNOT_DELETE_OR_UPDATE_A_PARENT_ROW'
365
                ]);
366
            }
367
 
368
 
369
 
370
            $result = $topicMapper->delete($topic);
371
            if($result) {
372
                $this->logger->info('Se borro el tópico : ' .  $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
373
 
17018 efrain 374
                $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 375
                $target_path = $storage->getPathMicrolearningTopic();
1 www 376
 
17002 efrain 377
                $storage->deleteFile($target_path, $topic->uuid, $topic->image);
378
 
379
 
380
 
1 www 381
                $data = [
382
                    'success' => true,
383
                    'data' => 'LABEL_RECORD_DELETED'
384
                ];
385
            } else {
386
 
387
                $data = [
388
                    'success'   => false,
389
                    'data'      => $topicMapper->getError()
390
                ];
391
 
392
                return new JsonModel($data);
393
            }
394
 
395
        } else {
396
            $data = [
397
                'success' => false,
398
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
399
            ];
400
 
401
            return new JsonModel($data);
402
        }
403
 
404
        return new JsonModel($data);
405
    }
406
 
407
 
408
    public function editAction()
409
    {
410
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
411
        $currentCompany     = $currentUserPlugin->getCompany();
412
        $currentUser        = $currentUserPlugin->getUser();
413
 
414
        $request    = $this->getRequest();
415
        $id   = $this->params()->fromRoute('id');
416
 
417
 
418
 
17002 efrain 419
        $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 420
        $topic = $topicMapper->fetchOneByUuid($id);
421
        if(!$topic) {
422
            return new JsonModel([
423
                'success'   => false,
424
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
425
            ]);
426
        }
427
 
428
        if($topic->company_id != $currentCompany->id) {
429
            return new JsonModel([
430
                'success'   => false,
431
                'data'   => 'ERROR_UNAUTHORIZED'
432
            ]);
433
        }
434
 
435
        if($request->isGet()) {
17002 efrain 436
 
17018 efrain 437
            $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 438
            $path = $storage->getPathMicrolearningTopic();
439
 
1 www 440
            $data = [
441
                'success' => true,
442
                'data' => [
443
                    'name' => $topic->name,
444
                    'description' => $topic->description,
445
                    'order' => $topic->order,
446
                    'status' => $topic->status,
17002 efrain 447
                    'image'=> $storage->getGenericImage($path, $topic->uuid, $topic->image)
1 www 448
                ]
449
            ];
450
 
451
            return new JsonModel($data);
452
        }
453
        else if($request->isPost()) {
454
            $form = new  TopicEditForm();
455
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
456
 
457
            $form->setData($dataPost);
458
 
459
            if($form->isValid()) {
460
                $dataPost = (array) $form->getData();
461
 
462
                $hydrator = new ObjectPropertyHydrator();
463
                $hydrator->hydrate($dataPost, $topic);
464
                $topic->image = null;
16945 efrain 465
 
1 www 466
                if($topicMapper->update($topic)) {
467
                    $topic = $topicMapper->fetchOne($topic->id);
468
 
17002 efrain 469
                    $image = Image::getInstance($this->config);
470
                    $target_path = $image->getStorage()->getPathMicrolearningTopic();
1 www 471
 
472
 
473
                    $files = $this->getRequest()->getFiles()->toArray();
474
                    if(isset($files['file']) && empty($files['file']['error'])) {
475
                        $tmp_filename  = $files['file']['tmp_name'];
17018 efrain 476
                        //$filename      = \LeadersLinked\Library\Functions::normalizeStringFilename($files['file']['name']);
1 www 477
 
478
                        try {
479
                            if($topic->image) {
480
 
17002 efrain 481
                                if(!$image->getStorage()->deleteFile($target_path, $topic->uuid, $topic->image)) {
1 www 482
                                    return new JsonModel([
483
                                        'success'   => false,
484
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
485
                                    ]);
486
                                }
487
                            }
488
 
489
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
490
 
491
                            $filename = 'topic-' .uniqid() . '.png';
16943 efrain 492
                            $crop_to_dimensions = false;
17002 efrain 493
                            $unlink_source = true;
494
 
17018 efrain 495
                            if($image->uploadProcessChangeSize($tmp_filename, $target_path, $topic->uuid, $filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
1 www 496
                                $topic->image = $filename;
497
                                $topicMapper->update($topic);
498
                            }
499
                        } catch(\Throwable $e) {
500
                            error_log($e->getTraceAsString());
501
                        }
502
                    }
503
 
504
 
505
 
506
 
507
                    $this->logger->info('Se edito el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
508
 
509
                    $data = [
510
                        'success'   => true,
511
                        'data'   => 'LABEL_RECORD_UPDATED'
16943 efrain 512
                    ];
1 www 513
                } else {
514
                    $data = [
515
                        'success'   => false,
516
                        'data'      => $topicMapper->getError()
517
                    ];
518
 
519
                }
520
 
521
                return new JsonModel($data);
522
 
523
            } else {
524
                $messages = [];
525
                $form_messages = (array) $form->getMessages();
526
                foreach($form_messages  as $fieldname => $field_messages)
527
                {
528
 
529
                    $messages[$fieldname] = array_values($field_messages);
530
                }
531
 
532
                return new JsonModel([
533
                    'success'   => false,
534
                    'data'   => $messages
535
                ]);
536
            }
537
        } else {
538
            $data = [
539
                'success' => false,
540
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
541
            ];
542
 
543
            return new JsonModel($data);
544
        }
545
 
546
        return new JsonModel($data);
547
    }
548
}