Proyectos de Subversion LeadersLinked - Backend

Rev

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