Proyectos de Subversion LeadersLinked - Backend

Rev

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