Proyectos de Subversion LeadersLinked - Backend

Rev

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