Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 16769 | Rev 17002 | 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;
15
use LeadersLinked\Form\PostCreateForm;
16
use LeadersLinked\Form\PostEditForm;
17
use LeadersLinked\Model\Post;
18
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
19
use LeadersLinked\Library\Image;
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
    {
15559 anderson 179
 
1 www 180
        $currentUserPlugin = $this->plugin('currentUserPlugin');
181
        $currentUser = $currentUserPlugin->getUser();
15559 anderson 182
 
1 www 183
        $request    = $this->getRequest();
15559 anderson 184
        if ($request->isPost()) {
185
 
1 www 186
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
187
            $dataPost['status'] = empty($dataPost['status']) ? Post::STATUS_INACTIVE : $dataPost['status'];
15559 anderson 188
 
189
 
1 www 190
            $form = new PostCreateForm();
191
            $form->setData($dataPost);
15559 anderson 192
 
193
            if ($form->isValid()) {
1 www 194
                $dataPost = (array) $form->getData();
15559 anderson 195
 
1 www 196
                $hydrator = new ObjectPropertyHydrator();
197
                $post = new Post();
198
                $hydrator->hydrate($dataPost, $post);
199
 
15559 anderson 200
 
1 www 201
                $dt = \DateTime::createFromFormat('d/m/Y', $post->date);
202
                $post->date = $dt->format('Y-m-d');
15347 efrain 203
                $post->network_id = $currentUser->network_id;
1 www 204
                $post->image = '';
205
                $post->file  = '';
16998 efrain 206
                $post->user_id = $currentUser->id;
1 www 207
 
15559 anderson 208
 
1 www 209
                $postMapper = PostMapper::getInstance($this->adapter);
15559 anderson 210
                if ($postMapper->insert($post)) {
1 www 211
                    $post = $postMapper->fetchOne($post->id);
15559 anderson 212
 
213
 
1 www 214
                    $files = $this->getRequest()->getFiles()->toArray();
15559 anderson 215
 
1 www 216
                    $target_path = $this->config['leaderslinked.fullpath.post'] .  $post->uuid;
15559 anderson 217
                    if (!file_exists($target_path)) {
1 www 218
                        mkdir($target_path, 0755, true);
219
                    }
15559 anderson 220
 
221
 
222
                    if (isset($files['file']) && empty($files['file']['error'])) {
1 www 223
                        $tmp_filename       = $files['file']['tmp_name'];
224
                        $original_filename  = trim(strtolower($files['file']['name']));
225
 
226
                        $original_filename = Functions::normalizeString($original_filename);
15559 anderson 227
 
1 www 228
                        $parts = explode('.', $original_filename);
15559 anderson 229
                        $original_filename = $parts[0] . '.' . $parts[count($parts) - 1];
230
 
231
                        try {
232
                            $full_filename = $target_path  . DIRECTORY_SEPARATOR . $original_filename;
233
                            if (move_uploaded_file($tmp_filename, $full_filename)) {
1 www 234
                                $post->file = basename($full_filename);
235
                                $post->update($post);
236
                            }
15559 anderson 237
                        } catch (\Throwable $e) {
1 www 238
                            error_log($e->getTraceAsString());
239
                        }
240
                    }
15559 anderson 241
 
242
                    if (isset($files['image']) && empty($files['image']['error'])) {
1 www 243
                        $tmp_filename  = $files['image']['tmp_name'];
15559 anderson 244
 
1 www 245
                        try {
246
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.post']);
15559 anderson 247
 
248
                            $filename = 'image-' . uniqid() . '.png';
249
                            // $crop_to_dimensions = true;
15077 efrain 250
                            // if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
15559 anderson 251
 
252
                            if (Image::uploadImageWithoutCompletationSize($tmp_filename, $target_path, $filename, $target_width, $target_height)) {
1 www 253
                                $post->image = $filename;
254
                                $postMapper->update($post);
255
                            }
15559 anderson 256
                        } catch (\Throwable $e) {
1 www 257
                            error_log($e->getTraceAsString());
258
                        }
259
                    }
15559 anderson 260
 
1 www 261
                    $this->logger->info('Se agrego la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
15559 anderson 262
 
1 www 263
                    $data = [
264
                        'success'   => true,
265
                        'data'   => 'LABEL_RECORD_ADDED'
266
                    ];
267
                } else {
268
                    $data = [
269
                        'success'   => false,
270
                        'data'      => $postMapper->getError()
271
                    ];
272
                }
15559 anderson 273
 
1 www 274
                return new JsonModel($data);
275
            } else {
276
                $messages = [];
277
                $form_messages = (array) $form->getMessages();
15559 anderson 278
                foreach ($form_messages  as $fieldname => $field_messages) {
279
 
1 www 280
                    $messages[$fieldname] = array_values($field_messages);
281
                }
15559 anderson 282
 
1 www 283
                return new JsonModel([
284
                    'success'   => false,
285
                    'data'   => $messages
286
                ]);
287
            }
288
        } else {
289
            $data = [
290
                'success' => false,
291
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
292
            ];
15559 anderson 293
 
1 www 294
            return new JsonModel($data);
295
        }
15559 anderson 296
 
1 www 297
        return new JsonModel($data);
298
    }
15559 anderson 299
 
1 www 300
    /**
301
     *
302
     * Borrar un perfil excepto el público
303
     * @return \Laminas\View\Model\JsonModel
304
     */
305
    public function deleteAction()
306
    {
307
        $currentUserPlugin = $this->plugin('currentUserPlugin');
308
        $currentUser = $currentUserPlugin->getUser();
15559 anderson 309
 
1 www 310
        $request    = $this->getRequest();
311
        $id = $this->params()->fromRoute('id');
15559 anderson 312
 
313
 
314
 
1 www 315
        $postMapper = PostMapper::getInstance($this->adapter);
15347 efrain 316
        $post = $postMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
15559 anderson 317
 
318
        if (!$post) {
1 www 319
            return new JsonModel([
320
                'success' => false,
321
                'data' => 'ERROR_POST_NOT_FOUND'
322
            ]);
323
        }
15559 anderson 324
 
325
 
326
        if ($request->isPost()) {
327
 
1 www 328
            $post->status = Post::STATUS_DELETE;
15559 anderson 329
 
1 www 330
            $result =  $postMapper->update($post);
15559 anderson 331
            if ($result) {
1 www 332
                $this->logger->info('Se borro la noticia : ' .  $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
15559 anderson 333
 
334
 
1 www 335
                $data = [
336
                    'success' => true,
337
                    'data' => 'LABEL_POST_DELETED'
338
                ];
339
            } else {
15559 anderson 340
 
1 www 341
                $data = [
342
                    'success'   => false,
343
                    'data'      => $postMapper->getError()
344
                ];
15559 anderson 345
 
1 www 346
                return new JsonModel($data);
347
            }
348
        } else {
349
            $data = [
350
                'success' => false,
351
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
352
            ];
15559 anderson 353
 
1 www 354
            return new JsonModel($data);
355
        }
15559 anderson 356
 
1 www 357
        return new JsonModel($data);
358
    }
15559 anderson 359
 
360
 
1 www 361
    public function editAction()
362
    {
363
        $currentUserPlugin = $this->plugin('currentUserPlugin');
364
        $currentUser = $currentUserPlugin->getUser();
15559 anderson 365
 
1 www 366
        $request    = $this->getRequest();
367
        $id = $this->params()->fromRoute('id');
15559 anderson 368
 
1 www 369
        $postMapper = PostMapper::getInstance($this->adapter);
15347 efrain 370
        $post = $postMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
15559 anderson 371
 
372
        if (!$post) {
1 www 373
            return new JsonModel([
374
                'success' => false,
375
                'data' => 'ERROR_POST_NOT_FOUND'
376
            ]);
377
        }
15559 anderson 378
 
379
 
380
        if ($request->isGet()) {
381
 
1 www 382
            $dt = \DateTime::createFromFormat('Y-m-d', $post->date);
15559 anderson 383
 
1 www 384
            $data = [
385
                'success' => true,
386
                'data' => [
387
                    'title' => $post->title,
388
                    'status' => $post->status,
389
                    'description' => $post->description,
390
                    'url' => $post->url,
391
                    'date' => $dt->format('d/m/Y'),
392
                ]
393
            ];
15559 anderson 394
 
1 www 395
            return new JsonModel($data);
15559 anderson 396
        } else if ($request->isPost()) {
1 www 397
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
398
            $dataPost['status'] = empty($dataPost['status']) ? Post::STATUS_INACTIVE : $dataPost['status'];
15559 anderson 399
 
1 www 400
            $form = new PostEditForm();
401
            $form->setData($dataPost);
15559 anderson 402
 
403
            if ($form->isValid()) {
1 www 404
                $dataPost = (array) $form->getData();
15078 efrain 405
 
15559 anderson 406
 
15078 efrain 407
                $post->title        = $dataPost['title'];
408
                $post->description  = $dataPost['description'];
409
                $post->url          = isset($dataPost['url']) ? $dataPost['url'] : '';
410
                $post->status       = isset($dataPost['status']) ? $dataPost['status'] : Post::STATUS_INACTIVE;
15559 anderson 411
 
412
                $dt = \DateTime::createFromFormat('d/m/Y', $dataPost['date']);
1 www 413
                $post->date = $dt->format('Y-m-d');
15559 anderson 414
 
415
 
416
 
417
 
1 www 418
                $files = $this->getRequest()->getFiles()->toArray();
15559 anderson 419
 
1 www 420
                $target_path = $this->config['leaderslinked.fullpath.post'] .  $post->uuid;
15559 anderson 421
                if (!file_exists($target_path)) {
1 www 422
                    mkdir($target_path, 0755, true);
423
                }
15559 anderson 424
 
425
 
426
                if (isset($files['file']) && empty($files['file']['error'])) {
427
 
428
                    if ($post->file) {
1 www 429
                        Functions::deleteFilename($target_path, $post->file);
430
                    }
15559 anderson 431
 
432
 
1 www 433
                    $tmp_filename       = $files['file']['tmp_name'];
434
                    $original_filename  = trim(strtolower($files['file']['name']));
15559 anderson 435
 
1 www 436
                    $original_filename = Functions::normalizeString($original_filename);
15559 anderson 437
 
1 www 438
                    $parts = explode('.', $original_filename);
15559 anderson 439
                    $original_filename = $parts[0] . '.' . $parts[count($parts) - 1];
440
 
441
                    try {
442
                        $full_filename = $target_path  . DIRECTORY_SEPARATOR . $original_filename;
443
                        if (move_uploaded_file($tmp_filename, $full_filename)) {
1 www 444
                            $post->file = basename($full_filename);
445
                            $post->update($post);
446
                        }
15559 anderson 447
                    } catch (\Throwable $e) {
1 www 448
                        error_log($e->getTraceAsString());
449
                    }
450
                }
15559 anderson 451
 
452
                if (isset($files['image']) && empty($files['image']['error'])) {
453
 
454
                    if ($post->image) {
1 www 455
                        Functions::deleteFilename($target_path, $post->image);
456
                    }
15559 anderson 457
 
458
 
1 www 459
                    $tmp_filename  = $files['image']['tmp_name'];
15559 anderson 460
 
1 www 461
                    try {
462
                        list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.post']);
15559 anderson 463
 
464
                        $filename = 'image-' . uniqid() . '.png';
1 www 465
                        $crop_to_dimensions = true;
15559 anderson 466
                        if (Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
1 www 467
                            $post->image = $filename;
468
                            $postMapper->update($post);
469
                        }
15559 anderson 470
                    } catch (\Throwable $e) {
1 www 471
                        error_log($e->getTraceAsString());
472
                    }
15559 anderson 473
                }
15078 efrain 474
 
15559 anderson 475
 
476
 
477
                if ($postMapper->update($post)) {
1 www 478
                    $this->logger->info('Se edito la noticia ' . $post->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
15559 anderson 479
 
1 www 480
                    $data = [
481
                        'success'   => true,
482
                        'data'   => 'LABEL_RECORD_UPDATED'
483
                    ];
484
                } else {
485
                    $data = [
486
                        'success'   => false,
487
                        'data'      => $postMapper->getError()
488
                    ];
489
                }
15559 anderson 490
 
1 www 491
                return new JsonModel($data);
492
            } else {
493
                $messages = [];
494
                $form_messages = (array) $form->getMessages();
15559 anderson 495
                foreach ($form_messages  as $fieldname => $field_messages) {
496
 
1 www 497
                    $messages[$fieldname] = array_values($field_messages);
498
                }
15559 anderson 499
 
1 www 500
                return new JsonModel([
501
                    'success'   => false,
502
                    'data'   => $messages
503
                ]);
504
            }
505
        } else {
506
            $data = [
507
                'success' => false,
508
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
509
            ];
15559 anderson 510
 
1 www 511
            return new JsonModel($data);
512
        }
15559 anderson 513
 
1 www 514
        return new JsonModel($data);
515
    }
516
}