Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17017 | | 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
 
17018 efrain 124
                $storage = Storage::getInstance($this->config, $this->adapter);
17014 efrain 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'];
17018 efrain 231
                    $filename      = \LeadersLinked\Library\Functions::normalizeStringFilename($files['file']['name']);
17014 efrain 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
                }
17018 efrain 242
 
17014 efrain 243
                $habitContentMapper = HabitContentMapper::getInstance($this->adapter);
244
                if($habitContentMapper->insert($habitContent)) {
245
 
246
                    $habitContent = $habitContentMapper->fetchOne($habitContent->id);
247
 
248
 
17018 efrain 249
                    $storage        = Storage::getInstance($this->config, $this->adapter);
250
                    $target_path    = $storage->getPathHabitContent();
251
 
17014 efrain 252
 
253
 
254
                    if ($type == HabitContent::TYPE_DOCUMENT) {
255
 
256
 
17018 efrain 257
                        if($storage->moveAndPutFile($tmp_filename, $target_path, $habitContent->uuid,  $filename)) {
17014 efrain 258
                            $habitContent->file = $filename;
259
                            $habitContent->type = $type;
260
 
261
                            $habitContentMapper->update($habitContent);
262
                        }
263
 
264
                    } else if ($type == HabitContent::TYPE_IMAGE) {
265
                        $image = Image::getInstance($this->config);
17018 efrain 266
 
17014 efrain 267
 
268
                        $filename = substr($filename, 0, strrpos($filename, '.'))  . '.png';
17018 efrain 269
                        $full_tmp_filename = $image->uploadProcessWithOutChangeSize($tmp_filename, $filename);
270
 
271
 
272
                        if($full_tmp_filename) {
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
                            }
17014 efrain 279
                        }
280
                    }
281
                    if ($type == HabitContent::TYPE_VIDEO) {
282
                        try {
283
 
284
 
285
 
17018 efrain 286
                            if($storage->moveAndPutFile($tmp_filename, $target_path, $habitContent->uuid,  $filename)) {
17014 efrain 287
 
288
                                $habitContent->file = $filename;
289
                                $habitContent->type = $type;
290
 
291
                                if($habitContentMapper->update($habitContent)) {
292
 
293
                                    $videoConvert               = new \LeadersLinked\Model\VideoConvert();
294
                                    $videoConvert->uuid         = $habitContent->uuid;
295
                                    $videoConvert->filename     = $filename;
296
                                    $videoConvert->type         = \LeadersLinked\Model\VideoConvert::TYPE_HABIT_CONTENT;
297
 
298
                                    $videoConvertMapper = \LeadersLinked\Mapper\VideoConvertMapper::getInstance($this->adapter);
299
                                    $videoConvertMapper->insert($videoConvert);
300
                                }
301
                            }
302
 
303
                            // @unlink($full_filename);
304
                            //@unlink($generate_full_filename);
305
 
306
 
307
                        } catch (\Throwable $e) {
308
                            error_log($e->getTraceAsString());
309
                        }
310
                    }
311
 
312
 
313
 
314
 
315
 
316
                    $this->logger->info('Se agrego el contenido ' . $habitContent->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
317
 
318
                    $data = [
319
                        'success'   => true,
320
                        'data'   => 'LABEL_RECORD_ADDED'
321
                    ];
322
                } else {
323
                    $data = [
324
                        'success'   => false,
325
                        'data'      => $habitContentMapper->getError()
326
                    ];
327
 
328
                }
329
 
330
                return new JsonModel($data);
331
 
332
            } else {
333
                $messages = [];
334
                $form_messages = (array) $form->getMessages();
335
                foreach($form_messages  as $fieldname => $field_messages)
336
                {
337
 
338
                    $messages[$fieldname] = array_values($field_messages);
339
                }
340
 
341
                return new JsonModel([
342
                    'success'   => false,
343
                    'data'   => $messages
344
                ]);
345
            }
346
 
347
        } else {
348
            $data = [
349
                'success' => false,
350
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
351
            ];
352
 
353
            return new JsonModel($data);
354
        }
355
 
356
        return new JsonModel($data);
357
    }
358
 
359
    /**
360
     *
361
     * Borrar un perfil excepto el público
362
     * @return \Laminas\View\Model\JsonModel
363
     */
364
    public function deleteAction()
365
    {
366
        $currentUserPlugin = $this->plugin('currentUserPlugin');
367
        $currentUser    = $currentUserPlugin->getUser();
368
        $currentCompany = $currentUserPlugin->getCompany();
369
 
370
        $request        = $this->getRequest();
371
        $id         = $this->params()->fromRoute('id');
372
 
373
 
374
 
375
        $habitContentMapper = HabitContentMapper::getInstance($this->adapter);
376
        $habitContent = $habitContentMapper->fetchOneByUuid($id);
377
        if(!$habitContent) {
378
            return new JsonModel([
379
                'success'   => false,
380
                'data'   => 'ERROR_RECORD_NOT_FOUND'
381
            ]);
382
        }
383
 
384
        if($habitContent->company_id != $currentCompany->id) {
385
            return new JsonModel([
386
                'success'   => false,
387
                'data'   => 'ERROR_UNAUTHORIZED'
388
            ]);
389
        }
390
 
391
        if($request->isPost()) {
17018 efrain 392
 
393
 
17014 efrain 394
 
395
            $result =  $habitContentMapper->delete($habitContent);
396
            if($result) {
397
                $this->logger->info('Se borro el Content : ' .  $habitContent->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
398
 
399
                if($habitContent->file) {
400
 
17018 efrain 401
                    $storage = \LeadersLinked\Library\Storage::getInstance($this->config, $this->adapter);
402
 
403
                    $target_path = $storage->getPathHabitContent();
404
                    $storage->deleteDirectory($target_path, $habitContent->uuid);
17014 efrain 405
                }
406
 
407
                $data = [
408
                    'success' => true,
409
                    'data' => 'LABEL_RECORD_DELETED'
410
                ];
411
            } else {
412
 
413
                $data = [
414
                    'success'   => false,
415
                    'data'      => $habitContentMapper->getError()
416
                ];
417
 
418
                return new JsonModel($data);
419
            }
420
 
421
        } else {
422
            $data = [
423
                'success' => false,
424
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
425
            ];
426
 
427
            return new JsonModel($data);
428
        }
429
 
430
        return new JsonModel($data);
431
    }
432
 
433
 
434
    public function editAction()
435
    {
436
        $currentUserPlugin = $this->plugin('currentUserPlugin');
437
        $currentUser    = $currentUserPlugin->getUser();
438
        $currentCompany = $currentUserPlugin->getCompany();
439
 
440
        $request    = $this->getRequest();
441
        $id    = $this->params()->fromRoute('id');
442
 
443
 
444
        $habitContentMapper = HabitContentMapper::getInstance($this->adapter);
445
        $habitContent = $habitContentMapper->fetchOneByUuid($id);
446
        if(!$habitContent) {
447
            return new JsonModel([
448
                'success'   => false,
449
                'data'   => 'ERROR_RECORD_NOT_FOUND'
450
            ]);
451
        }
452
 
453
 
454
        if($habitContent->company_id != $currentCompany->id) {
455
            return new JsonModel([
456
                'success'   => false,
457
                'data'   => 'ERROR_UNAUTHORIZED'
458
            ]);
459
        }
460
 
461
        if($request->isGet()) {
17018 efrain 462
            $storage = Storage::getInstance($this->config, $this->adapter);
17014 efrain 463
 
464
 
465
            $data = [
466
                'success' => true,
467
                'data' => [
468
                    'name' => $habitContent->name,
469
                    'order' => $habitContent->order,
470
                    'status' => $habitContent->status,
471
                ]
472
            ];
473
 
474
            return new JsonModel($data);
475
        }
476
        else if($request->isPost()) {
477
            $form = new  HabitContentEditForm();
478
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
479
            $dataPost['status'] = empty($dataPost['status'])  ? HabitContent::STATUS_INACTIVE : $dataPost['status'];
480
 
481
 
482
            $form->setData($dataPost);
483
 
484
            if($form->isValid()) {
485
                $dataPost = (array) $form->getData();
486
 
487
                $habitContent->name = $dataPost['name'];
488
                $habitContent->order = $dataPost['order'];
489
                $habitContent->code = $dataPost['code'];
490
                $habitContent->status = $dataPost['status'];
491
 
492
                if($habitContentMapper->update($habitContent)) {
493
 
494
 
495
 
496
 
497
 
498
                    $this->logger->info('Se edito el Content' . $habitContent->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
499
 
500
                    $data = [
501
                        'success'   => true,
502
                        'data'   => 'LABEL_RECORD_UPDATED'
503
                    ];
504
                } else {
505
                    $data = [
506
                        'success'   => false,
507
                        'data'      => $habitContentMapper->getError()
508
                    ];
509
 
510
                }
511
 
512
                return new JsonModel($data);
513
 
514
            } else {
515
                $messages = [];
516
                $form_messages = (array) $form->getMessages();
517
                foreach($form_messages  as $fieldname => $field_messages)
518
                {
519
 
520
                    $messages[$fieldname] = array_values($field_messages);
521
                }
522
 
523
                return new JsonModel([
524
                    'success'   => false,
525
                    'data'   => $messages
526
                ]);
527
            }
528
        } else {
529
            $data = [
530
                'success' => false,
531
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
532
            ];
533
 
534
            return new JsonModel($data);
535
        }
536
 
537
        return new JsonModel($data);
538
    }
539
 
17018 efrain 540
 
17014 efrain 541
 
542
}