Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17108 | Rev 17111 | 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
 
203
                $form = new TopicForm($this->adapter, $currentCompany->id);
1 www 204
                $formAdd = new TopicAddForm();
205
                $formEdit = new TopicEditForm();
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
 
1 www 236
        if($request->isPost()) {
237
            $form = new  TopicAddForm();
238
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
239
 
240
            $form->setData($dataPost);
241
 
242
            if($form->isValid()) {
243
                $dataPost = (array) $form->getData();
244
 
245
                $hydrator = new ObjectPropertyHydrator();
17002 efrain 246
                $topic = new MicrolearningTopic();
1 www 247
                $hydrator->hydrate($dataPost, $topic);
248
 
249
                $topic->company_id = $currentCompany->id;
250
                $topic->image = null;
251
 
252
 
253
 
17002 efrain 254
                $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 255
                if($topicMapper->insert($topic)) {
256
                    $topic = $topicMapper->fetchOne($topic->id);
16943 efrain 257
 
17107 stevensc 258
                    // Handle capsule associations
259
                    if (!empty($dataPost['capsule_uuid'])) {
260
                        $capsuleUuids = is_array($dataPost['capsule_uuid']) ? $dataPost['capsule_uuid'] : [$dataPost['capsule_uuid']];
261
                        $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
262
                        $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
263
 
264
                        foreach ($capsuleUuids as $capsuleUuid) {
265
                            $capsule = $capsuleMapper->fetchOneByUuid($capsuleUuid);
266
                            if ($capsule) {
267
                                $topicCapsule = new MicrolearningTopicCapsule();
268
                                $topicCapsule->topic_id = $topic->id;
269
                                $topicCapsule->capsule_id = $capsule->id;
270
                                $topicCapsule->company_id = $currentCompany->id;
271
                                $topicCapsuleMapper->insert($topicCapsule);
272
                            }
273
                        }
274
                    }
275
 
17002 efrain 276
                    $image = Image::getInstance($this->config);
277
                    $target_path = $image->getStorage()->getPathMicrolearningTopic();
16943 efrain 278
 
279
 
280
                    $files = $this->getRequest()->getFiles()->toArray();
281
                    if(isset($files['file']) && empty($files['file']['error'])) {
282
                        $tmp_filename  = $files['file']['tmp_name'];
17018 efrain 283
                        // $filename      = $\LeadersLinked\Library\Functions::normalizeStringFilename($files['file']['name']);
5574 nelberth 284
 
16943 efrain 285
                        try {
286
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
287
 
288
                            $filename = 'topic-' .uniqid() . '.png';
289
                            $crop_to_dimensions = false;
17002 efrain 290
                            $unlink_source = true;
291
 
17018 efrain 292
                            if($image->uploadProcessChangeSize($tmp_filename, $target_path, $topic->uuid, $filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
16943 efrain 293
                                $topic->image = $filename;
294
                                $topicMapper->update($topic);
295
                            }
296
                        } catch(\Throwable $e) {
297
                            error_log($e->getTraceAsString());
5574 nelberth 298
                        }
16943 efrain 299
                    }
300
 
1 www 301
 
302
                    $this->logger->info('Se agrego el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
303
 
304
                    $data = [
305
                        'success'   => true,
306
                        'data'   => 'LABEL_RECORD_ADDED'
307
                    ];
308
                } else {
309
                    $data = [
310
                        'success'   => false,
311
                        'data'      => $topicMapper->getError()
312
                    ];
313
 
314
                }
315
 
316
                return new JsonModel($data);
317
 
318
            } else {
319
                $messages = [];
320
                $form_messages = (array) $form->getMessages();
321
                foreach($form_messages  as $fieldname => $field_messages)
322
                {
323
 
324
                    $messages[$fieldname] = array_values($field_messages);
325
                }
326
 
327
                return new JsonModel([
328
                    'success'   => false,
329
                    'data'   => $messages
330
                ]);
331
            }
332
 
17093 stevensc 333
        }
17101 stevensc 334
        else if($request->isGet()) {
17093 stevensc 335
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
17101 stevensc 336
 
337
            if(!$currentCompany) {
17098 stevensc 338
                return new JsonModel([
339
                    'success' => false,
17101 stevensc 340
                    'data' => 'ERROR_COMPANY_NOT_FOUND'
17098 stevensc 341
                ]);
342
            }
17101 stevensc 343
 
17106 stevensc 344
            $records = $currentCompany ? $capsuleMapper->fetchAllActiveByCompanyId($currentCompany->id) : $capsuleMapper->fetchAllActive();
17100 stevensc 345
            $capsules = [];
17098 stevensc 346
 
347
            foreach($records as $record) {
17093 stevensc 348
                array_push($capsules, [
349
                    'id' => $record->uuid,
350
                    'name' => $record->name,
351
                ]);
352
            }
17097 stevensc 353
 
1 www 354
            $data = [
17093 stevensc 355
                'success' => true,
356
                'data' => [
17106 stevensc 357
                    'capsules' => $capsules
17093 stevensc 358
                ]
359
            ];
360
        }
361
        else {
362
            $data = [
1 www 363
                'success' => false,
364
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
365
            ];
366
        }
367
 
368
        return new JsonModel($data);
369
    }
370
 
371
    /**
372
     *
373
     * Borrar un perfil excepto el público
374
     * @return \Laminas\View\Model\JsonModel
375
     */
376
    public function deleteAction()
377
    {
378
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
379
        $currentCompany     = $currentUserPlugin->getCompany();
380
        $currentUser        = $currentUserPlugin->getUser();
381
 
382
        $request    = $this->getRequest();
383
        $id   = $this->params()->fromRoute('id');
384
 
385
 
17002 efrain 386
        $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 387
        $topic = $topicMapper->fetchOneByUuid($id);
388
        if(!$topic) {
389
            return new JsonModel([
390
                'success'   => false,
391
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
392
            ]);
393
        }
394
 
395
        if($topic->company_id != $currentCompany->id) {
396
            return new JsonModel([
397
                'success'   => false,
398
                'data'   => 'ERROR_UNAUTHORIZED'
399
            ]);
400
        }
401
 
402
 
403
 
404
        if($request->isPost()) {
17002 efrain 405
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
1 www 406
            $count = $capsuleMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
407
            if($count > 0 ) {
408
                return new JsonModel([
409
                    'success'   => false,
410
                    'data'   => 'ERROR_SQL_CANNOT_DELETE_OR_UPDATE_A_PARENT_ROW'
411
                ]);
412
            }
413
 
414
 
415
 
416
            $result = $topicMapper->delete($topic);
417
            if($result) {
418
                $this->logger->info('Se borro el tópico : ' .  $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
419
 
17018 efrain 420
                $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 421
                $target_path = $storage->getPathMicrolearningTopic();
1 www 422
 
17002 efrain 423
                $storage->deleteFile($target_path, $topic->uuid, $topic->image);
424
 
425
 
426
 
1 www 427
                $data = [
428
                    'success' => true,
429
                    'data' => 'LABEL_RECORD_DELETED'
430
                ];
431
            } else {
432
 
433
                $data = [
434
                    'success'   => false,
435
                    'data'      => $topicMapper->getError()
436
                ];
437
 
438
                return new JsonModel($data);
439
            }
440
 
441
        } else {
442
            $data = [
443
                'success' => false,
444
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
445
            ];
446
 
447
            return new JsonModel($data);
448
        }
449
 
450
        return new JsonModel($data);
451
    }
452
 
453
 
454
    public function editAction()
455
    {
456
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
457
        $currentCompany     = $currentUserPlugin->getCompany();
458
        $currentUser        = $currentUserPlugin->getUser();
459
 
460
        $request    = $this->getRequest();
461
        $id   = $this->params()->fromRoute('id');
462
 
17109 stevensc 463
 
464
 
17002 efrain 465
        $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 466
        $topic = $topicMapper->fetchOneByUuid($id);
467
        if(!$topic) {
468
            return new JsonModel([
469
                'success'   => false,
470
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
471
            ]);
472
        }
473
 
474
        if($topic->company_id != $currentCompany->id) {
475
            return new JsonModel([
476
                'success'   => false,
477
                'data'   => 'ERROR_UNAUTHORIZED'
478
            ]);
479
        }
480
 
481
        if($request->isGet()) {
17109 stevensc 482
 
17018 efrain 483
            $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 484
            $path = $storage->getPathMicrolearningTopic();
485
 
1 www 486
            $data = [
487
                'success' => true,
488
                'data' => [
489
                    'name' => $topic->name,
490
                    'description' => $topic->description,
491
                    'order' => $topic->order,
492
                    'status' => $topic->status,
17109 stevensc 493
                    'image'=> $storage->getGenericImage($path, $topic->uuid, $topic->image)
1 www 494
                ]
495
            ];
496
 
497
            return new JsonModel($data);
498
        }
499
        else if($request->isPost()) {
500
            $form = new  TopicEditForm();
501
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
502
 
503
            $form->setData($dataPost);
504
 
505
            if($form->isValid()) {
506
                $dataPost = (array) $form->getData();
507
 
508
                $hydrator = new ObjectPropertyHydrator();
509
                $hydrator->hydrate($dataPost, $topic);
510
                $topic->image = null;
16945 efrain 511
 
1 www 512
                if($topicMapper->update($topic)) {
513
                    $topic = $topicMapper->fetchOne($topic->id);
514
 
17002 efrain 515
                    $image = Image::getInstance($this->config);
516
                    $target_path = $image->getStorage()->getPathMicrolearningTopic();
1 www 517
 
17109 stevensc 518
 
1 www 519
                    $files = $this->getRequest()->getFiles()->toArray();
520
                    if(isset($files['file']) && empty($files['file']['error'])) {
521
                        $tmp_filename  = $files['file']['tmp_name'];
17109 stevensc 522
                        //$filename      = \LeadersLinked\Library\Functions::normalizeStringFilename($files['file']['name']);
1 www 523
 
524
                        try {
525
                            if($topic->image) {
17109 stevensc 526
 
17002 efrain 527
                                if(!$image->getStorage()->deleteFile($target_path, $topic->uuid, $topic->image)) {
1 www 528
                                    return new JsonModel([
529
                                        'success'   => false,
530
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
531
                                    ]);
532
                                }
533
                            }
534
 
535
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
536
 
537
                            $filename = 'topic-' .uniqid() . '.png';
16943 efrain 538
                            $crop_to_dimensions = false;
17002 efrain 539
                            $unlink_source = true;
540
 
17018 efrain 541
                            if($image->uploadProcessChangeSize($tmp_filename, $target_path, $topic->uuid, $filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
1 www 542
                                $topic->image = $filename;
543
                                $topicMapper->update($topic);
544
                            }
545
                        } catch(\Throwable $e) {
546
                            error_log($e->getTraceAsString());
547
                        }
548
                    }
549
 
17109 stevensc 550
 
551
 
552
 
1 www 553
                    $this->logger->info('Se edito el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
554
 
555
                    $data = [
556
                        'success'   => true,
557
                        'data'   => 'LABEL_RECORD_UPDATED'
16943 efrain 558
                    ];
1 www 559
                } else {
560
                    $data = [
561
                        'success'   => false,
562
                        'data'      => $topicMapper->getError()
563
                    ];
564
 
565
                }
566
 
567
                return new JsonModel($data);
568
 
569
            } else {
570
                $messages = [];
571
                $form_messages = (array) $form->getMessages();
572
                foreach($form_messages  as $fieldname => $field_messages)
573
                {
17109 stevensc 574
 
1 www 575
                    $messages[$fieldname] = array_values($field_messages);
576
                }
577
 
578
                return new JsonModel([
579
                    'success'   => false,
580
                    'data'   => $messages
581
                ]);
582
            }
583
        } else {
584
            $data = [
585
                'success' => false,
586
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
587
            ];
588
 
589
            return new JsonModel($data);
590
        }
17109 stevensc 591
 
592
        return new JsonModel($data);
1 www 593
    }
594
}