Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17016 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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