Proyectos de Subversion LeadersLinked - Backend

Rev

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