Proyectos de Subversion LeadersLinked - Backend

Rev

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