Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17018 | Rev 17275 | 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
15559 anderson 2
 
1 www 3
declare(strict_types=1);
4
 
5
namespace LeadersLinked\Controller;
6
 
7
use Laminas\Db\Adapter\AdapterInterface;
16768 efrain 8
 
1 www 9
use Laminas\Mvc\Controller\AbstractActionController;
10
use Laminas\Log\LoggerInterface;
11
use Laminas\View\Model\ViewModel;
12
use Laminas\View\Model\JsonModel;
13
use LeadersLinked\Library\Functions;
14
use LeadersLinked\Mapper\PostMapper;
17002 efrain 15
use LeadersLinked\Form\Post\PostCreateForm;
16
use LeadersLinked\Form\Post\PostEditForm;
1 www 17
use LeadersLinked\Model\Post;
18
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
17274 stevensc 19
use LeadersLinked\Library\Storage;
1 www 20
 
21
class PostController extends AbstractActionController
22
{
23
    /**
24
     *
16769 efrain 25
     * @var \Laminas\Db\Adapter\AdapterInterface
1 www 26
     */
27
    private $adapter;
16768 efrain 28
 
1 www 29
    /**
30
     *
16769 efrain 31
     * @var \LeadersLinked\Cache\CacheInterface
1 www 32
     */
16769 efrain 33
    private $cache;
34
 
35
 
36
    /**
37
     *
38
     * @var \Laminas\Log\LoggerInterface
39
     */
1 www 40
    private $logger;
16768 efrain 41
 
1 www 42
    /**
43
     *
44
     * @var array
45
     */
46
    private $config;
16768 efrain 47
 
16769 efrain 48
 
1 www 49
    /**
50
     *
16769 efrain 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
1 www 61
     * @param array $config
16769 efrain 62
     * @param \Laminas\Mvc\I18n\Translator $translator
1 www 63
     */
16769 efrain 64
    public function __construct($adapter, $cache, $logger, $config, $translator)
1 www 65
    {
16769 efrain 66
        $this->adapter      = $adapter;
67
        $this->cache        = $cache;
68
        $this->logger       = $logger;
69
        $this->config       = $config;
70
        $this->translator   = $translator;
1 www 71
    }
15559 anderson 72
 
1 www 73
    public function indexAction()
74
    {
15347 efrain 75
        $currentUserPlugin = $this->plugin('currentUserPlugin');
76
        $currentUser = $currentUserPlugin->getUser();
15559 anderson 77
 
15351 efrain 78
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
79
        $network = $currentNetworkPlugin->getNetwork();
15559 anderson 80
 
1 www 81
        $request = $this->getRequest();
15559 anderson 82
        if ($request->isGet()) {
83
 
84
 
1 www 85
            $headers  = $request->getHeaders();
15559 anderson 86
 
1 www 87
            $isJson = false;
15559 anderson 88
            if ($headers->has('Accept')) {
1 www 89
                $accept = $headers->get('Accept');
15559 anderson 90
 
1 www 91
                $prioritized = $accept->getPrioritized();
15559 anderson 92
 
93
                foreach ($prioritized as $key => $value) {
1 www 94
                    $raw = trim($value->getRaw());
15559 anderson 95
 
96
                    if (!$isJson) {
1 www 97
                        $isJson = strpos($raw, 'json');
98
                    }
99
                }
100
            }
101
 
15559 anderson 102
            if ($isJson) {
103
 
104
 
1 www 105
                $search = $this->params()->fromQuery('search', []);
16766 efrain 106
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);
15559 anderson 107
 
1 www 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);
16766 efrain 112
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : Functions::sanitizeFilterString(filter_var($order[0]['dir']));
15559 anderson 113
 
1 www 114
                $fields =  ['title', 'date'];
115
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'title';
15559 anderson 116
 
117
                if (!in_array($order_direction, ['ASC', 'DESC'])) {
1 www 118
                    $order_direction = 'ASC';
119
                }
15559 anderson 120
 
1 www 121
                $postMapper = PostMapper::getInstance($this->adapter);
15347 efrain 122
                $paginator = $postMapper->fetchAllDataTable($search, $currentUser->network_id, $page, $records_x_page, $order_field, $order_direction);
15559 anderson 123
 
1 www 124
                $items = [];
125
                $records = $paginator->getCurrentItems();
15559 anderson 126
                foreach ($records as $record) {
1 www 127
                    $dt = \DateTime::createFromFormat('Y-m-d', $record->date);
15559 anderson 128
 
1 www 129
                    $item = [
130
                        'title' => $record->title,
15559 anderson 131
                        'active' => $record->status,
1 www 132
                        'date' => $dt->format('d/m/Y'),
133
                        'actions' => [
15559 anderson 134
                            'link_edit' => $this->url()->fromRoute('publications/posts/edit', ['id' => $record->uuid]),
135
                            'link_delete' => $this->url()->fromRoute('publications/posts/delete', ['id' => $record->uuid]),
136
                            'link_view' => 'https://' . $network->main_hostname . '/post/' . $record->uuid,
137
                        ]
1 www 138
                    ];
15559 anderson 139
 
1 www 140
                    array_push($items, $item);
141
                }
15559 anderson 142
 
1 www 143
                return new JsonModel([
144
                    'success' => true,
145
                    'data' => [
146
                        'items' => $items,
147
                        'total' => $paginator->getTotalItemCount(),
148
                    ]
149
                ]);
15559 anderson 150
            } else {
1 www 151
                $image_size = $this->config['leaderslinked.image_sizes.post'];
15559 anderson 152
 
1 www 153
                $formAdd = new PostCreateForm();
154
                $formEdit = new PostEditForm();
15559 anderson 155
 
1 www 156
                $this->layout()->setTemplate('layout/layout-backend');
157
                $viewModel = new ViewModel();
158
                $viewModel->setTemplate('leaders-linked/posts/index.phtml');
159
                $viewModel->setVariables([
160
                    'formAdd' => $formAdd,
15559 anderson 161
                    'formEdit' => $formEdit,
1 www 162
                    'image_size' => $image_size,
15559 anderson 163
 
1 www 164
                ]);
15559 anderson 165
                return $viewModel;
1 www 166
            }
167
        } else {
168
            return new JsonModel([
169
                'success' => false,
170
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
171
            ]);;
172
        }
173
    }
15559 anderson 174
 
175
 
176
 
1 www 177
    public function addAction()
178
    {
17274 stevensc 179
        try {
180
            $request    = $this->getRequest();
181
 
182
            $currentUserPlugin = $this->plugin('currentUserPlugin');
183
            $currentUser = $currentUserPlugin->getUser();
184
 
185
            if(!$currentUser->is_admin) {
186
                return new JsonModel([
187
                    'success' => false,
188
                    'data' => 'ERROR_NOT_AUTHORIZED'
189
                ]);
190
            }
191
 
192
            if (!$request->isPost()) {
193
                return new JsonModel([
194
                    'success' => false,
195
                    'data' => 'ERROR_METHOD_NOT_ALLOWED'
196
                ]);
197
            }
198
 
1 www 199
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
200
            $dataPost['status'] = empty($dataPost['status']) ? Post::STATUS_INACTIVE : $dataPost['status'];
17274 stevensc 201
 
1 www 202
            $form = new PostCreateForm();
203
            $form->setData($dataPost);
17274 stevensc 204
 
205
            if (!$form->isValid()) {
1 www 206
                $messages = [];
207
                $form_messages = (array) $form->getMessages();
17274 stevensc 208
                foreach ($form_messages  as $fieldname => $field_messages)
209
                {
1 www 210
                    $messages[$fieldname] = array_values($field_messages);
211
                }
212
                return new JsonModel([
213
                    'success'   => false,
214
                    'data'   => $messages
215
                ]);
216
            }
17274 stevensc 217
 
218
            $dataPost = (array) $form->getData();
219
 
220
            $hydrator = new ObjectPropertyHydrator();
221
            $post = new Post();
222
            $hydrator->hydrate($dataPost, $post);
223
 
224
            $dt = \DateTime::createFromFormat('d/m/Y', $post->date);
225
            $post->date = $dt->format('Y-m-d');
226
            $post->network_id = $currentUser->network_id;
227
            $post->image = '';
228
            $post->file  = '';
229
            $post->user_id = $currentUser->id;
230
 
231
            $postMapper = PostMapper::getInstance($this->adapter);
232
 
233
            if (!$postMapper->insert($post)) {
234
                return new JsonModel([
235
                    'success'   => false,
236
                    'data'   => $postMapper->getError()
237
                ]);
238
            }
239
 
240
            $storage = Storage::getInstance($this->config, $this->adapter);
241
 
242
            $storage->setFiles($request->getFiles()->toArray());
243
 
244
            if(!$storage->setCurrentFile('file')) {
245
                return new JsonModel([
246
                    'success'   => false,
247
                    'data'   => 'ERROR_FILE_NOT_FOUND'
248
                ]);
249
            }
250
 
251
            $tmp_filename =  $storage->getTmpFilename();
252
            $filename = 'post-' . uniqid() . '.' . $storage->getExtension();
253
            $target_filename = $storage->composePathToFilename(
254
                Storage::TYPE_POST,
255
                $post->uuid,
256
                $filename
257
            );
258
 
259
            if(!$storage->putFile($tmp_filename, $target_filename)) {
260
                return new JsonModel([
261
                    'success'   => false,
262
                    'data'   => 'ERROR_UPLOAD_FILE'
263
                ]);
264
            }
265
 
266
            if(!$storage->setCurrentFile('image')) {
267
                return new JsonModel([
268
                    'success'   => false,
269
                    'data'   => 'ERROR_FILE_NOT_FOUND'
270
                ]);
271
            }
272
 
273
 
274
            $tmp_filename  = $storage->getTmpFilename();
275
            $filename = 'post-image-' . uniqid() . '.png';
276
            $target_filename = $storage->composePathToFilename(
277
                Storage::TYPE_POST,
278
                $post->uuid,
279
                $filename
280
            );
281
 
282
            $post->file = $filename;
283
 
284
            if(!$storage->uploadImageWithOutChangeSize($tmp_filename, $target_filename)) {
285
                return new JsonModel([
286
                    'success'   => false,
287
                    'data'   => 'ERROR_UPLOAD_IMAGE'
288
                ]);
289
            }
290
 
291
            $post->image = $filename;
292
 
293
            if(!$postMapper->update($post)) {
294
                return new JsonModel([
295
                    'success'   => false,
296
                    'data'   => $postMapper->getError()
297
                ]);
298
            }
299
 
300
            $this->logger->info('Se agrego la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
301
 
302
            return new JsonModel([
303
                'success' => true,
304
                'data'   => 'LABEL_RECORD_ADDED'
305
            ]);
306
        } catch (\Throwable $e) {
307
            $this->logger->error('Error al agregar la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP(), 'error' => $e->getTraceAsString()]);
308
            return new JsonModel([
309
                'success'   => false,
310
                'data'   => $e->getMessage()
311
            ]);
1 www 312
        }
313
    }
15559 anderson 314
 
1 www 315
    /**
316
     *
317
     * Borrar un perfil excepto el público
318
     * @return \Laminas\View\Model\JsonModel
319
     */
320
    public function deleteAction()
321
    {
17274 stevensc 322
        try {
323
            $request    = $this->getRequest();
324
 
325
            $currentUserPlugin = $this->plugin('currentUserPlugin');
326
            $currentUser = $currentUserPlugin->getUser();
15559 anderson 327
 
17274 stevensc 328
            $id = $this->params()->fromRoute('id');
15559 anderson 329
 
17274 stevensc 330
            if(!$currentUser->is_admin) {
331
                return new JsonModel([
332
                    'success' => false,
333
                    'data' => 'ERROR_NOT_AUTHORIZED'
334
                ]);
335
            }
15559 anderson 336
 
17274 stevensc 337
            if (!$request->isPost()) {
338
                return new JsonModel([
339
                    'success' => false,
340
                    'data' => 'ERROR_METHOD_NOT_ALLOWED'
341
                ]);
342
            }
15559 anderson 343
 
17274 stevensc 344
            $postMapper = PostMapper::getInstance($this->adapter);
345
            $post = $postMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
15559 anderson 346
 
17274 stevensc 347
            if (!$post) {
348
                return new JsonModel([
349
                    'success' => false,
350
                    'data' => 'ERROR_POST_NOT_FOUND'
351
                ]);
352
            }
15559 anderson 353
 
1 www 354
            $post->status = Post::STATUS_DELETE;
15559 anderson 355
 
17274 stevensc 356
            $storage = Storage::getInstance($this->config, $this->adapter);
357
            $post_path = $storage->getPathPost();
15559 anderson 358
 
17274 stevensc 359
            if($post->file) {
360
                $storage->deleteFile($post_path, $post->uuid, $post->file);
361
            }
362
            if($post->image) {
363
                $storage->deleteFile($post_path, $post->uuid, $post->image);
364
            }
15559 anderson 365
 
17274 stevensc 366
            if(!$postMapper->update($post)) {
367
                return new JsonModel([
1 www 368
                    'success'   => false,
17274 stevensc 369
                    'data'   => $postMapper->getError()
370
                ]);
371
            }
15559 anderson 372
 
17274 stevensc 373
            $this->logger->info('Se borro la noticia : ' .  $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
15559 anderson 374
 
17274 stevensc 375
            return new JsonModel([
376
                'success' => true,
377
                'data' => 'LABEL_POST_DELETED'
378
            ]);
379
        } catch (\Throwable $th) {
380
            $this->logger->error('Error al borrar la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP(), 'error' => $th->getTraceAsString()]);
381
            return new JsonModel([
382
                'success'   => false,
383
                'data'   => $th->getMessage()
384
            ]);
1 www 385
        }
386
    }
15559 anderson 387
 
388
 
1 www 389
    public function editAction()
390
    {
17274 stevensc 391
        try {
392
            $request    = $this->getRequest();
15559 anderson 393
 
17274 stevensc 394
            $currentUserPlugin = $this->plugin('currentUserPlugin');
395
            $currentUser = $currentUserPlugin->getUser();
15559 anderson 396
 
17274 stevensc 397
            $id = $this->params()->fromRoute('id');
15559 anderson 398
 
17274 stevensc 399
            if(!$currentUser->is_admin) {
400
                return new JsonModel([
401
                    'success' => false,
402
                    'data' => 'ERROR_NOT_AUTHORIZED'
403
                ]);
404
            }
15559 anderson 405
 
17274 stevensc 406
            if (!$request->isPost() && !$request->isGet()) {
407
                return new JsonModel([
408
                    'success' => false,
409
                    'data' => 'ERROR_METHOD_NOT_ALLOWED'
410
                ]);
411
            }
15559 anderson 412
 
17274 stevensc 413
            $postMapper = PostMapper::getInstance($this->adapter);
414
            $post = $postMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
15559 anderson 415
 
17274 stevensc 416
            if (!$post) {
417
                return new JsonModel([
418
                    'success' => false,
419
                    'data' => 'ERROR_POST_NOT_FOUND'
420
                ]);
421
            }
15559 anderson 422
 
423
 
17274 stevensc 424
            if ($request->isGet()) {
425
                $dt = \DateTime::createFromFormat('Y-m-d', $post->date);
426
                return new JsonModel([
427
                    'success' => true,
428
                    'data' => [
429
                        'title' => $post->title,
430
                        'status' => $post->status,
431
                        'description' => $post->description,
432
                        'url' => $post->url,
433
                        'date' => $dt->format('d/m/Y'),
434
                    ]
435
                ]);
436
            }
437
 
438
            if ($request->isPost()) {
439
                $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
440
                $dataPost['status'] = empty($dataPost['status']) ? Post::STATUS_INACTIVE : $dataPost['status'];
15559 anderson 441
 
17274 stevensc 442
                $form = new PostEditForm();
443
                $form->setData($dataPost);
15559 anderson 444
 
17274 stevensc 445
                if (!$form->isValid()) {
446
                    $messages = [];
447
                    $form_messages = (array) $form->getMessages();
448
                    foreach ($form_messages  as $fieldname => $field_messages)
449
                    {
450
                        $messages[$fieldname] = array_values($field_messages);
451
                    }
452
                    return new JsonModel([
453
                        'success'   => false,
454
                        'data'   => $messages
455
                    ]);
456
                }
457
 
1 www 458
                $dataPost = (array) $form->getData();
15078 efrain 459
 
460
                $post->title        = $dataPost['title'];
461
                $post->description  = $dataPost['description'];
462
                $post->url          = isset($dataPost['url']) ? $dataPost['url'] : '';
463
                $post->status       = isset($dataPost['status']) ? $dataPost['status'] : Post::STATUS_INACTIVE;
15559 anderson 464
 
465
                $dt = \DateTime::createFromFormat('d/m/Y', $dataPost['date']);
1 www 466
                $post->date = $dt->format('Y-m-d');
15559 anderson 467
 
17274 stevensc 468
                $storage = Storage::getInstance($this->config, $this->adapter);
469
                $post_path = $storage->getPathPost();
15559 anderson 470
 
17274 stevensc 471
                $storage->setFiles($request->getFiles()->toArray());
15559 anderson 472
 
17274 stevensc 473
                if($storage->setCurrentFile('file')) {
474
                    $tmp_filename =  $storage->getTmpFilename();
475
                    $filename = 'post-' . uniqid() . '.' . $storage->getExtension();
476
                    $target_filename = $storage->composePathToFilename(
477
                        Storage::TYPE_POST,
478
                        $post->uuid,
479
                        $filename
480
                    );
15559 anderson 481
 
17274 stevensc 482
                    if($post->file) {
483
                        $storage->deleteFile($post_path, $post->uuid, $post->file);
484
                    }
15559 anderson 485
 
17274 stevensc 486
                    if(!$storage->putFile($tmp_filename, $target_filename)) {
487
                        return new JsonModel([
488
                            'success'   => false,
489
                            'data'   => 'ERROR_UPLOAD_FILE'
490
                        ]);
1 www 491
                    }
15559 anderson 492
 
17274 stevensc 493
                    $post->file = $filename;
1 www 494
                }
15559 anderson 495
 
17274 stevensc 496
                if($storage->setCurrentFile('image')) {
497
                    $tmp_filename =  $storage->getTmpFilename();
498
                    $filename = 'post-image-' . uniqid() . '.png';
499
                    $target_filename = $storage->composePathToFilename(
500
                        Storage::TYPE_POST,
501
                        $post->uuid,
502
                        $filename
503
                    );
15559 anderson 504
 
505
                    if ($post->image) {
17274 stevensc 506
                        $storage->deleteFile($post_path, $post->uuid, $post->image);
1 www 507
                    }
15559 anderson 508
 
17274 stevensc 509
                    if(!$storage->uploadImageWithOutChangeSize($tmp_filename, $target_filename)) {
510
                        return new JsonModel([
511
                            'success'   => false,
512
                            'data'   => 'ERROR_UPLOAD_IMAGE'
513
                        ]);
514
                    }
15559 anderson 515
 
17274 stevensc 516
                    $post->image = $filename;
15559 anderson 517
                }
15078 efrain 518
 
17274 stevensc 519
                if(!$postMapper->update($post)) {
520
                    return new JsonModel([
1 www 521
                        'success'   => false,
17274 stevensc 522
                        'data'   => $postMapper->getError()
523
                    ]);
1 www 524
                }
15559 anderson 525
 
17274 stevensc 526
                $this->logger->info('Se edito la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
15559 anderson 527
 
1 www 528
                return new JsonModel([
17274 stevensc 529
                    'success'   => true,
530
                    'data'   => 'LABEL_RECORD_UPDATED'
1 www 531
                ]);
532
            }
17274 stevensc 533
        } catch (\Throwable $th) {
534
            $this->logger->error('Error al editar la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP(), 'error' => $th->getTraceAsString()]);
535
            return new JsonModel([
536
                'success'   => false,
537
                'data'   => $th->getMessage()
538
            ]);
1 www 539
        }
540
    }
541
}