Proyectos de Subversion LeadersLinked - Services

Rev

Rev 560 | Rev 562 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
/**
4
 *
5
 * Controlador: Mis Perfiles
6
 *
7
 */
8
 
9
declare(strict_types=1);
10
 
11
namespace LeadersLinked\Controller;
12
 
13
use Laminas\Db\Adapter\AdapterInterface;
14
 
15
use Laminas\Mvc\Controller\AbstractActionController;
16
use Laminas\Log\LoggerInterface;
17
use Laminas\View\Model\ViewModel;
18
use Laminas\View\Model\JsonModel;
19
use LeadersLinked\Library\Functions;
20
use LeadersLinked\Mapper\KnowledgeAreaCategoryMapper;
21
use LeadersLinked\Mapper\KnowledgeAreaCategoryUserMapper;
22
use LeadersLinked\Mapper\UserMapper;
23
use LeadersLinked\Model\KnowledgeAreaCategory;
24
use LeadersLinked\Model\KnowledgeAreaCategoryUser;
25
use LeadersLinked\Form\KnowledgeArea\KnowledgeAreaCreateForm;
26
use LeadersLinked\Mapper\KnowledgeAreaContentMapper;
27
use LeadersLinked\Model\KnowledgeAreaContent;
28
use LeadersLinked\Form\KnowledgeArea\KnowledgeAreaEditForm;
29
use LeadersLinked\Mapper\CommentMapper;
30
use LeadersLinked\Form\KnowledgeArea\CommentForm;
31
use LeadersLinked\Model\Comment;
32
use LeadersLinked\Mapper\ContentReactionMapper;
33
use LeadersLinked\Model\ContentReaction;
34
use LeadersLinked\Mapper\KnowledgeAreaCategoryJobDescriptionMapper;
35
use LeadersLinked\Mapper\OrganizationPositionMapper;
242 efrain 36
use LeadersLinked\Model\User;
283 www 37
use LeadersLinked\Library\Storage;
1 efrain 38
 
39
class KnowledgeAreaController extends AbstractActionController
40
{
41
    /**
42
     *
43
     * @var \Laminas\Db\Adapter\AdapterInterface
44
     */
45
    private $adapter;
46
 
47
    /**
48
     *
49
     * @var \LeadersLinked\Cache\CacheInterface
50
     */
51
    private $cache;
52
 
53
 
54
    /**
55
     *
56
     * @var \Laminas\Log\LoggerInterface
57
     */
58
    private $logger;
59
 
60
    /**
61
     *
62
     * @var array
63
     */
64
    private $config;
65
 
66
 
67
    /**
68
     *
69
     * @var \Laminas\Mvc\I18n\Translator
70
     */
71
    private $translator;
72
 
73
 
74
    /**
75
     *
76
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
77
     * @param \LeadersLinked\Cache\CacheInterface $cache
78
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
79
     * @param array $config
80
     * @param \Laminas\Mvc\I18n\Translator $translator
81
     */
82
    public function __construct($adapter, $cache, $logger, $config, $translator)
83
    {
84
        $this->adapter      = $adapter;
85
        $this->cache        = $cache;
86
        $this->logger       = $logger;
87
        $this->config       = $config;
88
        $this->translator   = $translator;
89
    }
90
 
91
    /**
92
     *
93
     * Generación del listado de perfiles
94
     * {@inheritDoc}
95
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
96
     */
97
    public function indexAction()
98
    {
99
        $currentUserPlugin = $this->plugin('currentUserPlugin');
100
        $currentUser = $currentUserPlugin->getUser();
101
 
102
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
103
        $currentNetwork = $currentNetworkPlugin->getNetwork();
104
 
105
        $request = $this->getRequest();
106
        if ($request->isGet()) {
107
 
108
 
109
 
110
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
111
                $allowAdd       = $acl->isAllowed($currentUser->usertype_id, 'knowledge-area/add') ? 1 : 0;
112
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'knowledge-area/edit');
113
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'knowledge-area/delete');
114
                $allowView = $acl->isAllowed($currentUser->usertype_id, 'knowledge-area/view');
115
 
116
 
117
 
118
                $category_filter_id = Functions::sanitizeFilterString($this->params()->fromQuery('category_id'));
119
                $search = Functions::sanitizeFilterString($this->params()->fromQuery('search'));
120
                $page   = intval($this->params()->fromQuery('start', 1), 10);
121
 
122
                $order_field        = 'added_on';
123
                $order_direction    = 'asc';
124
                $records_x_page     = 12;
125
 
126
 
127
 
128
                $category_with_edition_ids = [];
129
                $category_with_edition_uuids = [];
130
                $category_ids = [];
131
                $categories = [];
132
 
133
 
134
                $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
135
 
136
                $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
137
                $records =  $knowledgeAreaCategoryUserMapper->fetchAllByUserId($currentUser->id);
138
 
139
 
140
 
141
                foreach ($records as $record) {
142
                    if ($record->role == KnowledgeAreaCategoryUser::ROLE_ADMINISTRATOR || $record->role == KnowledgeAreaCategoryUser::ROLE_USER) {
143
 
144
                        array_push($category_with_edition_ids, $record->category_id);
145
 
146
                        $knowledgeAreaCategory = $knowledgeAreaCategoryMapper->fetchOne($record->category_id);
147
                        if($knowledgeAreaCategory) {
148
                            array_push($category_with_edition_uuids, $knowledgeAreaCategory->uuid);
149
                        }
150
 
151
                    }
152
 
153
                    array_push($category_ids, $record->category_id);
154
                }
155
 
156
                $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
157
 
158
                if ($category_ids) {
159
                    $records =  $knowledgeAreaCategoryMapper->fetchAllByIds($category_ids);
160
                    foreach ($records as $record) {
161
                        if (!isset($categories[$record->id])) {
162
 
163
                            $categories[$record->id] = [
164
                                'uuid' => $record->uuid,
165
                                'name' => $record->name,
166
                            ];
167
                        }
168
                    }
169
                }
170
 
171
 
172
 
173
                $records =  $knowledgeAreaCategoryMapper->fetchAllPublicByNetworkId($currentNetwork->id);
174
                foreach ($records as $record) {
175
                    if (!isset($categories[$record->id])) {
176
 
177
                        $categories[$record->id] = [
178
                            'uuid' => $record->uuid,
179
                            'name' => $record->name,
180
                        ];
181
                    }
182
                }
183
 
184
 
185
                uasort($categories, function ($a, $b) {
186
                    return $a['name'] <=> $b['name'];
187
                });
188
 
189
 
190
                if ($category_filter_id) {
191
                    $categoryFilter = $knowledgeAreaCategoryMapper->fetchOneByUuid($category_filter_id);
192
                    if ($categoryFilter) {
193
                        $category_ids = [$categoryFilter->id];
194
                    } else {
195
                        $category_ids = [];
196
                    }
197
                }
283 www 198
 
333 www 199
                $storage = Storage::getInstance($this->config, $this->adapter);
283 www 200
                $path = $storage->getPathKnowledgeArea();
1 efrain 201
 
202
                $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
203
                $paginator = $knowledgeAreaContentMapper->fetchAllDataTableByCategoryIds($category_ids,  $search, $page, $records_x_page, $order_field, $order_direction);
204
 
205
 
206
                $items = [];
207
                $records = $paginator->getCurrentItems();
208
                foreach ($records as $record)
209
                {
210
 
211
 
212
                    if (!isset($categories[$record->category_id])) {
213
                        $category = $knowledgeAreaCategoryMapper->fetchOne($record->category_id);
214
                        if ($category) {
215
                            $categories[$category->id] = [
216
                                'uuid' =>  $category->uuid,
217
                                'name' =>  $category->name,
218
                            ];
219
                        }
220
                    }
221
 
222
 
223
 
224
 
225
 
226
                    $description = strip_tags($record->description);
227
                    if (strlen($description) > 120) {
228
                        $description = substr($description, 0, 120) . '...';
229
                    }
230
 
231
                    $item = [
561 stevensc 232
                        'image' => $storage->getGenericImage($path, ($categories[$record->category_id]['uuid'] ?? null), $record->image),
1 efrain 233
                        'title' => $record->title,
234
                        'description' => $description,
235
                        'category' => $categories[$record->category_id]['name'],
236
                        'link_view' => $allowView ?  $this->url()->fromRoute('knowledge-area/view', ['id' => $record->uuid]) : '',
242 efrain 237
 
1 efrain 238
                    ];
239
 
240
 
241
 
242
                    if (in_array($record->category_id, $category_with_edition_ids)) {
243
                        $item['link_edit'] = $allowEdit ?  $this->url()->fromRoute('knowledge-area/edit', ['id' => $record->uuid]) : '';
244
                        $item['link_delete'] = $allowDelete ? $this->url()->fromRoute('knowledge-area/delete', ['id' => $record->uuid]) : '';
245
                    }
246
 
247
                    array_push($items, $item);
248
                }
249
 
250
 
251
 
252
                $image_size = $this->config['leaderslinked.image_sizes.knowledge_area'];
253
 
254
                return new JsonModel([
255
                    'success' => true,
256
                    'data' => [
257
                        'items' => $items,
258
                        'total' => $paginator->getTotalItemCount(),
259
                        'page' => $paginator->getCurrentPageNumber(),
260
                        'total_pages' => $paginator->getPages()->pageCount,
261
                        'categories' => $categories,
262
                        'categories_with_edition' => $category_with_edition_uuids,
263
                        'link_add' => $allowAdd ? $this->url()->fromRoute('knowledge-area/add') : '',
264
                        'image_size' => $image_size,
265
                        'content_edit' => count($category_with_edition_ids) > 0,
266
 
267
                    ]
268
                ]);
269
 
270
        } else {
271
            return new JsonModel([
272
                'success' => false,
273
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
274
            ]);
275
        }
276
    }
277
 
278
    public function addAction()
279
    {
280
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
281
        $currentUser        = $currentUserPlugin->getUser();
282
 
283
        $request            = $this->getRequest();
284
 
285
        if ($request->isPost()) {
286
            $category_with_edition_ids = [];
287
            $category_ids = [];
288
 
289
 
290
            $categories = [];
291
 
292
 
293
            $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
294
            $records =  $knowledgeAreaCategoryUserMapper->fetchAllByUserId($currentUser->id);
295
            foreach ($records as $record) {
296
                if ($record->role == KnowledgeAreaCategoryUser::ROLE_ADMINISTRATOR || $record->role == KnowledgeAreaCategoryUser::ROLE_USER) {
297
 
298
                    array_push($category_with_edition_ids, $record->category_id);
299
                }
300
 
301
                array_push($category_ids, $record->category_id);
302
            }
303
 
304
            $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
305
 
306
            if ($category_ids) {
307
                $records =  $knowledgeAreaCategoryMapper->fetchAllByIds($category_ids);
308
                foreach ($records as $record) {
309
                    if ($record->status == KnowledgeAreaCategory::STATUS_ACTIVE) {
310
 
311
                        $categories[$record->id] = [
312
                            'uuid' => $record->uuid,
313
                            'name' => $record->name,
314
                        ];
315
                    }
316
                }
317
            }
318
 
319
 
320
 
321
            $categories = array_values($categories);
322
            usort($categories, function ($a, $b) {
323
                return $a['name'] <=> $b['name'];
324
            });
325
 
326
 
327
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
328
            $form = new KnowledgeAreaCreateForm($this->adapter, $category_with_edition_ids);
329
 
330
            $form->setData($dataPost);
331
 
332
            if ($form->isValid()) {
333
                $dataPost = (array) $form->getData();
334
 
335
                $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
336
                $knowledgeAreaCategory = $knowledgeAreaCategoryMapper->fetchOneByUuid($dataPost['category_id']);
337
 
338
 
339
                $knowledgeAreaContent = new KnowledgeAreaContent();
340
                $knowledgeAreaContent->network_id = $knowledgeAreaCategory->network_id;
341
                $knowledgeAreaContent->company_id = $knowledgeAreaCategory->company_id;
342
                $knowledgeAreaContent->category_id = $knowledgeAreaCategory->id;
343
                $knowledgeAreaContent->user_id = $currentUser->id;
344
                $knowledgeAreaContent->title = $dataPost['title'];
345
                $knowledgeAreaContent->description = $dataPost['description'];
346
                $knowledgeAreaContent->link = $dataPost['link'];
347
 
348
                $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
349
                if ($knowledgeAreaContentMapper->insert($knowledgeAreaContent)) {
350
                    $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOne($knowledgeAreaContent->id);
351
 
561 stevensc 352
                    // Se instancia la clase Storage para manejar el almacenamiento de archivos.
353
                    // La clase Image fue eliminada debido a que no se encontraba o estaba obsoleta.
334 www 354
                    $storage = Storage::getInstance($this->config, $this->adapter);
561 stevensc 355
                    // Obtiene la ruta base para los archivos del área de conocimiento.
356
                    // $target_path = $storage->getPathKnowledgeArea(); // No longer needed directly here, composePathTo methods use storagePath internally
1 efrain 357
 
358
                    $files = $this->getRequest()->getFiles()->toArray();
359
 
561 stevensc 360
                    // Manejo del archivo de imagen principal.
1 efrain 361
                    if (isset($files['image']) && empty($files['image']['error'])) {
560 stevensc 362
                        $tmp_image_name  = $files['image']['tmp_name'];
363
                        $original_image_name_parts = explode('.',  $files['image']['name']);
561 stevensc 364
                        // Genera un nombre de archivo único y normalizado, forzando la extensión .png.
560 stevensc 365
                        $final_image_filename = Functions::normalizeString(uniqid() . '-' . $original_image_name_parts[0] . '.png');
334 www 366
 
561 stevensc 367
                        // Obtener dimensiones para el redimensionamiento de la imagen del área de conocimiento.
368
                        list($target_width_str, $target_height_str) = explode('x', $this->config['leaderslinked.image_sizes.knowledge_area']);
369
                        $target_width = (int)$target_width_str;
370
                        $target_height = (int)$target_height_str;
371
 
560 stevensc 372
                        $uuid_path_segment = $knowledgeAreaCategory->uuid;
561 stevensc 373
 
374
                        // Construye la ruta completa del directorio de destino usando el UUID de la categoría.
375
                        $full_target_dir = $storage->composePathToDirectory(Storage::TYPE_KNOWLEDGE_AREA, $uuid_path_segment);
376
                        // Crea el directorio si no existe.
377
                        if (!is_dir($full_target_dir)) {
378
                            mkdir($full_target_dir, 0775, true);
560 stevensc 379
                        }
561 stevensc 380
                        // Construye la ruta completa del archivo de destino.
381
                        $full_target_path_for_image = $storage->composePathToFilename(Storage::TYPE_KNOWLEDGE_AREA, $uuid_path_segment, $final_image_filename);
334 www 382
 
561 stevensc 383
                        // Sube y redimensiona la imagen usando el método de la clase Storage.
384
                        if ($storage->uploadImageResize($tmp_image_name, $full_target_path_for_image, $target_width, $target_height)) {
385
                            $knowledgeAreaContent->image = $final_image_filename; // Guarda solo el nombre del archivo.
560 stevensc 386
                            $knowledgeAreaContentMapper->update($knowledgeAreaContent);
334 www 387
                        }
1 efrain 388
                    }
389
 
561 stevensc 390
                    // Manejo del archivo adjunto.
1 efrain 391
                    if (isset($files['attachment']) && empty($files['attachment']['error'])) {
560 stevensc 392
                        $tmp_attachment_name   = $files['attachment']['tmp_name'];
561 stevensc 393
                        // Normaliza el nombre del archivo adjunto, manteniendo su extensión original.
560 stevensc 394
                        $final_attachment_filename = Functions::normalizeString($files['attachment']['name']);
283 www 395
 
560 stevensc 396
                        $uuid_path_segment = $knowledgeAreaCategory->uuid;
561 stevensc 397
                        // Necesitamos la ruta base para los adjuntos si composePathToDirectory no se usa aquí directamente
398
                        $base_attachment_path = $storage->getPathKnowledgeArea();
399
                        $full_target_dir_for_attachment = $base_attachment_path . DIRECTORY_SEPARATOR . $uuid_path_segment;
560 stevensc 400
                        if (!is_dir($full_target_dir_for_attachment)) {
401
                            mkdir($full_target_dir_for_attachment, 0775, true);
402
                        }
403
                        $full_target_path_for_attachment = $full_target_dir_for_attachment . DIRECTORY_SEPARATOR . $final_attachment_filename;
404
 
561 stevensc 405
                        // Mueve el archivo adjunto subido a su ubicación final.
560 stevensc 406
                        if ($storage->moveUploadedFile($tmp_attachment_name, $full_target_path_for_attachment)) {
561 stevensc 407
                            $knowledgeAreaContent->attachment = $final_attachment_filename; // Guarda solo el nombre del archivo.
1 efrain 408
                            $knowledgeAreaContentMapper->update($knowledgeAreaContent);
409
                        }
410
                    }
411
 
412
                    $this->logger->info('Se agrego el contenido ' . $knowledgeAreaContent->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
413
 
414
                    $data = [
415
                        'success'   => true,
416
                        'data'   => 'LABEL_RECORD_ADDED'
417
                    ];
418
                } else {
419
                    $data = [
420
                        'success'   => false,
421
                        'data'      => $knowledgeAreaContentMapper->getError()
422
                    ];
423
                }
424
 
425
                return new JsonModel($data);
426
            } else {
427
                $messages = [];
428
                $form_messages = (array) $form->getMessages();
429
                foreach ($form_messages  as $fieldname => $field_messages) {
430
 
431
                    $messages[$fieldname] = array_values($field_messages);
432
                }
433
 
434
                return new JsonModel([
435
                    'success'   => false,
436
                    'data'   => $messages
437
                ]);
438
            }
439
        } else {
440
            $data = [
441
                'success' => false,
442
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
443
            ];
444
 
445
            return new JsonModel($data);
446
        }
447
 
448
        return new JsonModel($data);
449
    }
450
 
451
    public function deleteAction()
452
    {
453
        $currentUserPlugin = $this->plugin('currentUserPlugin');
454
        $currentUser    = $currentUserPlugin->getUser();
455
 
456
 
457
        $request    = $this->getRequest();
458
        $id         = $this->params()->fromRoute('id');
459
 
460
 
461
 
462
        $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
463
        $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
464
        if (!$knowledgeAreaContent) {
465
            return new JsonModel([
466
                'success'   => false,
467
                'data'   => 'ERROR_RECORD_NOT_FOUND'
468
            ]);
469
        }
470
 
471
 
472
 
473
        $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
474
        $knowledgeAreaCategoryUser = $knowledgeAreaCategoryUserMapper->fetchOneByCategoryIdAndUserId($knowledgeAreaContent->category_id, $currentUser->id);
475
 
476
        $ok = false;
477
        if ($knowledgeAreaCategoryUser) {
478
 
479
            if ($knowledgeAreaCategoryUser->role == KnowledgeAreaCategoryUser::ROLE_EDITOR) {
480
                $ok = $knowledgeAreaContent->user_id == $currentUser->id;
481
            }
482
 
483
            if ($knowledgeAreaCategoryUser->role == KnowledgeAreaCategoryUser::ROLE_ADMINISTRATOR) {
484
                $ok = true;
485
            }
486
        }
487
 
488
        if (!$ok) {
489
            return new JsonModel([
490
                'success'   => false,
491
                'data'   => 'ERROR_KNOWLEDGE_AREA_YOU_DO_NOT_HAVE_PERMISSION'
492
            ]);
493
        }
494
 
495
        if ($request->isPost()) {
496
 
497
            $result =  $knowledgeAreaContentMapper->delete($knowledgeAreaContent);
498
            if ($result) {
499
                $this->logger->info('Se borro el cotenido : ' .  $knowledgeAreaContent->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
500
 
283 www 501
 
333 www 502
                $storage = Storage::getInstance($this->config, $this->adapter);
283 www 503
                $target_path = $storage->getPathKnowledgeArea();
504
 
505
 
506
                if($knowledgeAreaContent->attachment) {
507
                    $storage->deleteFile($target_path, $knowledgeAreaContent->uuid, $knowledgeAreaContent->attachment);
508
                }
509
 
510
 
511
 
1 efrain 512
                if ($knowledgeAreaContent->image) {
283 www 513
                    $storage->deleteFile($target_path, $knowledgeAreaContent->uuid, $knowledgeAreaContent->image);
1 efrain 514
                }
515
 
516
                $data = [
517
                    'success' => true,
518
                    'data' => 'LABEL_RECORD_DELETED'
519
                ];
520
            } else {
521
 
522
                $data = [
523
                    'success'   => false,
524
                    'data'      => $knowledgeAreaContentMapper->getError()
525
                ];
526
 
527
                return new JsonModel($data);
528
            }
529
        } else {
530
            $data = [
531
                'success' => false,
532
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
533
            ];
534
 
535
            return new JsonModel($data);
536
        }
537
 
538
        return new JsonModel($data);
539
    }
540
 
541
 
542
    public function editAction()
543
    {
544
        $currentUserPlugin = $this->plugin('currentUserPlugin');
545
        $currentUser    = $currentUserPlugin->getUser();
546
 
547
        $request    = $this->getRequest();
548
        $id    = $this->params()->fromRoute('id');
549
 
550
        $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
551
        $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
552
        if (!$knowledgeAreaContent) {
553
            return new JsonModel([
554
                'success'   => false,
555
                'data'   => 'ERROR_RECORD_NOT_FOUND'
556
            ]);
557
        }
558
 
559
 
560
 
561
        $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
562
        $knowledgeAreaCategoryUser = $knowledgeAreaCategoryUserMapper->fetchOneByCategoryIdAndUserId($knowledgeAreaContent->category_id, $currentUser->id);
563
 
564
        $ok = false;
565
        if ($knowledgeAreaCategoryUser) {
566
 
567
            if ($knowledgeAreaCategoryUser->role == KnowledgeAreaCategoryUser::ROLE_EDITOR) {
568
                $ok = $knowledgeAreaContent->user_id == $currentUser->id;
569
            }
570
 
571
            if ($knowledgeAreaCategoryUser->role == KnowledgeAreaCategoryUser::ROLE_ADMINISTRATOR) {
572
                $ok = true;
573
            }
574
        }
575
 
576
        if (!$ok) {
577
            return new JsonModel([
578
                'success'   => false,
579
                'data'   => 'ERROR_KNOWLEDGE_AREA_YOU_DO_NOT_HAVE_PERMISSION'
580
            ]);
581
        }
582
 
583
        if ($request->isGet()) {
584
 
585
 
586
            $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
587
            $knowledgeAreaCategory = $knowledgeAreaCategoryMapper->fetchOne($knowledgeAreaContent->category_id);
588
 
589
 
590
 
591
            $data = [
592
                'success' => true,
593
                'data' => [
594
                    'category_id' => $knowledgeAreaCategory->uuid,
595
                    'title' => $knowledgeAreaContent->title,
596
                    'description' => $knowledgeAreaContent->description,
597
                    'link' => $knowledgeAreaContent->link,
598
                ]
599
            ];
600
 
601
            return new JsonModel($data);
602
        } else if ($request->isPost()) {
603
            $category_with_edition_ids = [];
604
            $category_ids = [];
605
 
606
 
607
            $categories = [];
608
 
609
 
610
            $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
611
            $records =  $knowledgeAreaCategoryUserMapper->fetchAllByUserId($currentUser->id);
612
            foreach ($records as $record) {
613
                if ($record->role == KnowledgeAreaCategoryUser::ROLE_ADMINISTRATOR || $record->role == KnowledgeAreaCategoryUser::ROLE_USER) {
614
 
615
                    array_push($category_with_edition_ids, $record->category_id);
616
                }
617
 
618
                array_push($category_ids, $record->category_id);
619
            }
620
 
621
            $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
622
 
623
            if ($category_ids) {
624
                $records =  $knowledgeAreaCategoryMapper->fetchAllByIds($category_ids);
625
                foreach ($records as $record) {
626
                    if ($record->status == KnowledgeAreaCategory::STATUS_ACTIVE) {
627
 
628
                        $categories[$record->id] = [
629
                            'uuid' => $record->uuid,
630
                            'name' => $record->name,
631
                        ];
632
                    }
633
                }
634
            }
635
 
636
 
637
 
638
            $categories = array_values($categories);
639
            usort($categories, function ($a, $b) {
640
                return $a['name'] <=> $b['name'];
641
            });
642
 
643
 
644
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
645
            $form = new KnowledgeAreaEditForm($this->adapter, $category_with_edition_ids);
646
            $form->setData($dataPost);
647
 
648
            if ($form->isValid()) {
649
                $dataPost = (array) $form->getData();
650
 
651
 
652
                $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
653
                $knowledgeAreaCategory = $knowledgeAreaCategoryMapper->fetchOneByUuid($dataPost['category_id']);
654
 
655
 
656
 
657
                $knowledgeAreaContent->category_id = $knowledgeAreaCategory->id;
658
                $knowledgeAreaContent->title = $dataPost['title'];
659
                $knowledgeAreaContent->description = $dataPost['description'];
660
 
661
 
662
                if ($knowledgeAreaContentMapper->update($knowledgeAreaContent)) {
663
 
561 stevensc 664
                    // Se instancia la clase Storage para manejar el almacenamiento de archivos.
334 www 665
                    $storage = Storage::getInstance($this->config, $this->adapter);
561 stevensc 666
                    // Obtiene la ruta base para los archivos del área de conocimiento.
667
                    // $target_path = $storage->getPathKnowledgeArea(); // No longer needed directly here, composePathTo methods use storagePath internally
1 efrain 668
 
669
                    $files = $this->getRequest()->getFiles()->toArray();
670
 
561 stevensc 671
                    // Manejo de la actualización de la imagen principal.
1 efrain 672
                    if (isset($files['image']) && empty($files['image']['error'])) {
283 www 673
 
561 stevensc 674
                        // Si existe una imagen previa, se elimina.
1 efrain 675
                        if ($knowledgeAreaContent->image) {
560 stevensc 676
                            $storage->deleteFile($target_path, $knowledgeAreaContent->uuid, $knowledgeAreaContent->image);
1 efrain 677
                        }
678
 
560 stevensc 679
                        $tmp_image_name  = $files['image']['tmp_name'];
680
                        $original_image_name_parts = explode('.',  $files['image']['name']);
561 stevensc 681
                        // Genera un nombre de archivo único y normalizado para la nueva imagen, forzando .png.
560 stevensc 682
                        $final_image_filename = Functions::normalizeString(uniqid() . '-' . $original_image_name_parts[0] . '.png');
334 www 683
 
561 stevensc 684
                        // Obtener dimensiones para el redimensionamiento de la imagen del área de conocimiento.
685
                        list($target_width_str, $target_height_str) = explode('x', $this->config['leaderslinked.image_sizes.knowledge_area']);
686
                        $target_width = (int)$target_width_str;
687
                        $target_height = (int)$target_height_str;
688
 
689
                        $uuid_path_segment = $knowledgeAreaCategory->uuid;
283 www 690
 
561 stevensc 691
                        // Construye la ruta completa del directorio de destino.
692
                        $full_target_dir = $storage->composePathToDirectory(Storage::TYPE_KNOWLEDGE_AREA, $uuid_path_segment);
693
                        // Crea el directorio si no existe.
694
                        if (!is_dir($full_target_dir)) {
695
                            mkdir($full_target_dir, 0775, true);
560 stevensc 696
                        }
561 stevensc 697
                        $full_target_path_for_image = $storage->composePathToFilename(Storage::TYPE_KNOWLEDGE_AREA, $uuid_path_segment, $final_image_filename);
334 www 698
 
561 stevensc 699
                        // Sube y redimensiona la imagen.
700
                        if ($storage->uploadImageResize($tmp_image_name, $full_target_path_for_image, $target_width, $target_height)) {
560 stevensc 701
                            $knowledgeAreaContent->image = $final_image_filename;
702
                            $knowledgeAreaContentMapper->update($knowledgeAreaContent);
1 efrain 703
                        }
334 www 704
 
1 efrain 705
                    }
706
 
561 stevensc 707
                    // Manejo de la actualización del archivo adjunto.
1 efrain 708
                    if (isset($files['attachment']) && empty($files['attachment']['error'])) {
560 stevensc 709
                        $tmp_attachment_name   = $files['attachment']['tmp_name'];
561 stevensc 710
                        // Normaliza el nombre del nuevo archivo adjunto.
560 stevensc 711
                        $final_attachment_filename = Functions::normalizeString($files['attachment']['name']);
283 www 712
 
561 stevensc 713
                        // Si existe un adjunto previo, se elimina.
1 efrain 714
                        if ($knowledgeAreaContent->attachment) {
560 stevensc 715
                            $storage->deleteFile($target_path, $knowledgeAreaContent->uuid, $knowledgeAreaContent->attachment);
1 efrain 716
                        }
561 stevensc 717
 
718
                        // Construye la ruta completa del directorio de destino para el adjunto.
719
                        $uuid_path_segment = $knowledgeAreaCategory->uuid; // Similar al comentario de la imagen.
560 stevensc 720
                        $full_target_dir_for_attachment = $target_path . DIRECTORY_SEPARATOR . $uuid_path_segment;
721
                        if (!is_dir($full_target_dir_for_attachment)) {
722
                            mkdir($full_target_dir_for_attachment, 0775, true);
723
                        }
724
                        $full_target_path_for_attachment = $full_target_dir_for_attachment . DIRECTORY_SEPARATOR . $final_attachment_filename;
725
 
561 stevensc 726
                        // Mueve el nuevo archivo adjunto a su ubicación final.
560 stevensc 727
                        if ($storage->moveUploadedFile($tmp_attachment_name, $full_target_path_for_attachment)) {
728
                            $knowledgeAreaContent->attachment = $final_attachment_filename;
1 efrain 729
                            $knowledgeAreaContentMapper->update($knowledgeAreaContent);
730
                        }
731
                    }
732
 
733
                    $this->logger->info('Se edito el contenido ' . $knowledgeAreaContent->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
734
 
735
                    $data = [
736
                        'success'   => true,
737
                        'data'   => 'LABEL_RECORD_UPDATED'
738
                    ];
739
                } else {
740
                    $data = [
741
                        'success'   => false,
742
                        'data'      => $knowledgeAreaContentMapper->getError()
743
                    ];
744
                }
745
 
746
                return new JsonModel($data);
747
            } else {
748
                $messages = [];
749
                $form_messages = (array) $form->getMessages();
750
                foreach ($form_messages  as $fieldname => $field_messages) {
751
 
752
                    $messages[$fieldname] = array_values($field_messages);
753
                }
754
 
755
                return new JsonModel([
756
                    'success'   => false,
757
                    'data'   => $messages
758
                ]);
759
            }
760
        } else {
761
            $data = [
762
                'success' => false,
763
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
764
            ];
765
 
766
            return new JsonModel($data);
767
        }
768
 
769
        return new JsonModel($data);
770
    }
771
 
772
 
773
    public function viewAction()
774
    {
775
        $currentUserPlugin = $this->plugin('currentUserPlugin');
776
        $currentUser    = $currentUserPlugin->getUser();
777
 
778
        $request    = $this->getRequest();
779
        $id    = $this->params()->fromRoute('id');
780
 
781
        $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
782
        $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
783
        if (!$knowledgeAreaContent) {
784
            return new JsonModel([
785
                'success'   => false,
786
                'data'   => 'ERROR_RECORD_NOT_FOUND'
787
            ]);
788
        }
789
 
790
 
791
 
792
        $request = $this->getRequest();
793
        if ($request->isGet()) {
794
 
795
 
796
            $knowledgeAreaCategoryMapper = KnowledgeAreaCategoryMapper::getInstance($this->adapter);
797
            $knowledgeAreaCategory = $knowledgeAreaCategoryMapper->fetchOne($knowledgeAreaContent->category_id);
798
 
799
 
800
 
801
            $ok = false;
802
            if ($knowledgeAreaCategory->privacy == KnowledgeAreaCategory::PRIVACY_COMPANY) {
803
 
804
                $knowledgeAreaCategoryUserMapper = KnowledgeAreaCategoryUserMapper::getInstance($this->adapter);
805
                $knowledgeAreaCategoryUser = $knowledgeAreaCategoryUserMapper->fetchOneByCategoryIdAndUserId($knowledgeAreaContent->category_id, $currentUser->id);
806
 
807
 
808
                if ($knowledgeAreaCategoryUser) {
809
                    $ok = true;
810
                }
811
            }
812
            if ($knowledgeAreaCategory->privacy == KnowledgeAreaCategory::PRIVACY_PUBLIC) {
813
                $ok = true;
814
            }
815
 
816
            if (!$ok) {
817
                return new JsonModel([
818
                    'success'   => false,
819
                    'data'   => 'ERROR_KNOWLEDGE_AREA_YOU_DO_NOT_HAVE_PERMISSION'
820
                ]);
821
            }
822
 
823
            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
824
            $contentReaction = $contentReactionMapper->fetchOneByKnowledgeAreaIdAndUserId($knowledgeAreaContent->id, $currentUser->id);
825
 
826
 
333 www 827
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 828
            $path = $storage->getPathKnowledgeArea();
1 efrain 829
 
830
                return new JsonModel([
831
                    'success' => true,
832
                    'data' => [
833
                        'category' => $knowledgeAreaCategory->name,
834
                        'title' => $knowledgeAreaContent->title,
835
                        'description' => $knowledgeAreaContent->description,
836
                        'link' => $knowledgeAreaContent->link,
283 www 837
                        'image' =>  $storage->getGenericImage($path, $knowledgeAreaContent->uuid,  $knowledgeAreaContent->image),
838
                        'attachment' =>  $knowledgeAreaContent->attachment ? $storage->getGenericFile($path, $knowledgeAreaContent->uuid,  $knowledgeAreaContent->attachment) : '',
1 efrain 839
                        'reaction' => $contentReaction ? $contentReaction->reaction : '',
242 efrain 840
                        'routeComments' => $this->url()->fromRoute('knowledge-area/comments', ['id' => $knowledgeAreaContent->uuid],['force_canonical' => true]),
841
                        'routeCommentAdd' => $this->url()->fromRoute('knowledge-area/comments/add', ['id' => $knowledgeAreaContent->uuid],['force_canonical' => true]),
842
                        'routeSaveReaction' => $this->url()->fromRoute('knowledge-area/save-reaction', ['id' => $knowledgeAreaContent->uuid],['force_canonical' => true]),
843
                        'routeDeleteReaction' => $this->url()->fromRoute('knowledge-area/delete-reaction', ['id' => $knowledgeAreaContent->uuid],['force_canonical' => true]),
844
                        'routeReactions' => $this->url()->fromRoute('knowledge-area/reactions', ['id' => $knowledgeAreaContent->uuid],['force_canonical' => true]),
1 efrain 845
                    ]
846
                ]);
847
 
848
        } else {
849
            $data = [
850
                'success' => false,
851
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
852
            ];
853
 
854
            return new JsonModel($data);
855
        }
856
 
857
        return new JsonModel($data);
858
    }
242 efrain 859
 
860
    public function reactionsAction()
861
    {
862
        $id = $this->params()->fromRoute('id');
863
 
864
        $request = $this->getRequest();
865
        $request = $this->getRequest();
866
        if ($request->isGet()) {
867
 
868
            $currentUserPlugin = $this->plugin('currentUserPlugin');
869
            $currentUser = $currentUserPlugin->getUser();
870
 
871
            $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
872
            $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
873
            if (!$knowledgeAreaContent || $knowledgeAreaContent->network_id != $currentUser->network_id) {
874
                return new JsonModel([
875
                    'success'   => false,
876
                    'data'   => 'ERROR_RECORD_NOT_FOUND'
877
                ]);
878
            }
879
 
880
 
881
 
882
            $userMapper = UserMapper::getInstance($this->adapter);
883
 
884
            $items = [];
885
 
333 www 886
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 887
            $path = $storage->getPathKnowledgeArea();
888
 
242 efrain 889
            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
890
            $records = $contentReactionMapper->fetchAllByKnowledgeAreaId($knowledgeAreaContent->id);
891
 
892
            foreach($records as $record)
893
            {
894
                $user = $userMapper->fetchOne($record->user_id);
895
                if($user && $user->status == User::STATUS_ACTIVE) {
896
 
897
                    array_push($items, [
898
                        'first_name' => $user->first_name,
899
                        'last_name' => $user->last_name,
900
                        'email' => $user->email,
283 www 901
                        'image' => $storage->getGenericImage($path, $user->uuid, $user->image),
242 efrain 902
                        'reaction' => $record->reaction,
903
                    ]);
904
                }
905
            }
906
 
907
            $response = [
908
                'success' => true,
909
                'data' => $items
910
            ];
911
 
912
            return new JsonModel($response);
913
 
914
 
915
 
916
 
917
        } else {
918
            $response = [
919
                'success' => false,
920
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
921
            ];
922
 
923
            return new JsonModel($response);
924
        }
925
    }
1 efrain 926
 
927
 
928
    public function addCommentAction()
929
    {
930
        $currentUserPlugin = $this->plugin('currentUserPlugin');
931
        $currentUser    = $currentUserPlugin->getUser();
932
 
933
        $id = $this->params()->fromRoute('id');
934
 
935
        $request = $this->getRequest();
936
        if ($request->isPost()) {
937
 
938
            $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
939
            $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
940
            if (!$knowledgeAreaContent || $knowledgeAreaContent->network_id != $currentUser->network_id) {
941
                return new JsonModel([
942
                    'success'   => false,
943
                    'data'   => 'ERROR_RECORD_NOT_FOUND'
944
                ]);
945
            }
946
 
947
 
948
 
949
 
950
            $dataPost = $request->getPost()->toArray();
951
            $form = new CommentForm();
952
            $form->setData($dataPost);
953
 
954
            if ($form->isValid()) {
242 efrain 955
 
1 efrain 956
                $dataPost = (array) $form->getData();
957
 
958
                $comment = new Comment();
959
                $comment->network_id = $currentUser->network_id;
960
                $comment->comment = $dataPost['comment'];
961
                $comment->user_id = $currentUser->id;
962
                $comment->knowledge_area_id = $knowledgeAreaContent->id;
963
                $comment->relational = Comment::RELATIONAL_KNOWLEDGE_AREA;
964
 
965
                $commentMapper = CommentMapper::getInstance($this->adapter);
966
                $now = $commentMapper->getDatebaseNow();
967
 
968
                if ($commentMapper->insert($comment)) {
969
 
970
                    $total_comments = $commentMapper->fetchCountCommentByKnowledgeAreaId($comment->knowledge_area_id);
971
 
972
                    $knowledgeAreaContent->total_comments = $total_comments;
973
                    $knowledgeAreaContentMapper->update($knowledgeAreaContent);
974
 
975
                    $response = [
976
                        'success'   => true,
977
                        'data'   => $this->renderComment($comment->id, $now),
978
                        'total_comments' => $total_comments
979
                    ];
980
 
981
                    return new JsonModel($response);
982
                } else {
983
 
984
                    $response = [
985
                        'success'   => false,
986
                        'data'   => $commentMapper->getError()
987
                    ];
988
 
989
                    return new JsonModel($response);
990
                }
991
            } else {
992
                $message = '';;
993
                $form_messages = (array) $form->getMessages();
994
                foreach ($form_messages  as $fieldname => $field_messages) {
995
                    foreach ($field_messages as $key => $value) {
996
                        $message = $value;
997
                    }
998
                }
999
 
1000
                $response = [
1001
                    'success'   => false,
1002
                    'data'   => $message
1003
                ];
1004
 
1005
                return new JsonModel($response);
1006
            }
1007
        } else {
1008
            $response = [
1009
                'success' => false,
1010
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1011
            ];
1012
 
1013
            return new JsonModel($response);
1014
        }
1015
    }
1016
 
1017
 
1018
 
1019
    public function deleteCommentAction()
1020
    {
1021
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1022
        $currentUser    = $currentUserPlugin->getUser();
1023
 
1024
        $request = $this->getRequest();
1025
        if ($request->isPost()) {
1026
 
1027
            $id = $this->params()->fromRoute('id');
1028
            $comment = $this->params()->fromRoute('comment');
1029
 
1030
 
1031
            $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
1032
            $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
1033
 
1034
 
1035
 
1036
            if ($knowledgeAreaContent && $knowledgeAreaContent->network_id == $currentUser->network_id) {
1037
 
1038
                $commentMapper = CommentMapper::getInstance($this->adapter);
1039
                $comment = $commentMapper->fetchOneByUuid($comment);
1040
 
1041
 
1042
                if ($comment && $comment->knowledge_area_id == $knowledgeAreaContent->id && $comment->user_id == $currentUser->id) {
1043
 
1044
                    $comment->status = Comment::STATUS_DELETED;
1045
 
1046
                    if ($commentMapper->update($comment)) {
1047
 
1048
                        $total_comments = $commentMapper->fetchCountCommentByKnowledgeAreaId($knowledgeAreaContent->id);
1049
                        $knowledgeAreaContent->total_comments = $total_comments;
1050
                        $knowledgeAreaContentMapper->update($knowledgeAreaContent);
1051
 
1052
                        $response = [
1053
                            'success' => true,
1054
                            'data' => 'LABEL_COMMENT_WAS_DELETED',
1055
                            'total_comments' => $total_comments
1056
                        ];
1057
                    } else {
1058
                        $response = [
1059
                            'success' => false,
1060
                            'data' => $commentMapper->getError()
1061
                        ];
1062
                    }
1063
                } else {
1064
                    $response = [
1065
                        'success' => false,
1066
                        'data' => 'ERROR_COMMENT_NOT_FOUND'
1067
                    ];
1068
                }
1069
            } else {
1070
                $response = [
1071
                    'success' => false,
1072
                    'data' => 'ERROR_COMMENT_NOT_FOUND'
1073
                ];
1074
            }
1075
        } else {
1076
            $response = [
1077
                'success' => false,
1078
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1079
            ];
1080
        }
1081
 
1082
        return new JsonModel($response);
1083
    }
1084
 
1085
 
1086
 
1087
    public function saveReactionAction()
1088
    {
1089
 
1090
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1091
        $currentUser    = $currentUserPlugin->getUser();
1092
 
1093
        $id = $this->params()->fromRoute('id');
1094
        $reaction  = $this->params()->fromPost('reaction');
1095
 
1096
        $request = $this->getRequest();
1097
        if ($request->isPost()) {
1098
 
1099
            $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
1100
            $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
1101
            if (!$knowledgeAreaContent || $knowledgeAreaContent->network_id != $currentUser->network_id) {
1102
                return new JsonModel([
1103
                    'success'   => false,
1104
                    'data'   => 'ERROR_RECORD_NOT_FOUND'
1105
                ]);
1106
            }
1107
 
1108
            $reactions = [
1109
                ContentReaction::REACTION_RECOMMENDED,
1110
                ContentReaction::REACTION_SUPPORT,
1111
                ContentReaction::REACTION_LOVE,
1112
                ContentReaction::REACTION_INTEREST,
1113
                ContentReaction::REACTION_FUN
1114
 
1115
            ];
1116
            if(!in_array($reaction, $reactions)) {
1117
                $response = [
1118
                    'success' => false,
1119
                    'data' => 'ERROR_REACTION_NOT_FOUND'
1120
                ];
1121
                return new JsonModel($response);
1122
            }
1123
 
1124
            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
1125
            $contentReaction = $contentReactionMapper->fetchOneByKnowledgeAreaIdAndUserId($knowledgeAreaContent->id, $currentUser->id);
1126
 
1127
            if ($contentReaction) {
1128
                $contentReaction->reaction = $reaction;
1129
 
1130
                $result = $contentReactionMapper->update($contentReaction);
1131
            } else {
1132
                $contentReaction = new ContentReaction();
1133
                $contentReaction->user_id = $currentUser->id;
1134
                $contentReaction->knowledge_area_id = $knowledgeAreaContent->id;
1135
                $contentReaction->relational = ContentReaction::RELATIONAL_KNOWLEDGE_AREA;
1136
                $contentReaction->reaction = $reaction;
1137
 
1138
                $result = $contentReactionMapper->insert($contentReaction);
1139
            }
1140
 
1141
 
1142
 
1143
            if ($result) {
1144
 
1145
                $reactions = $contentReactionMapper->fetchCountByKnowledgeAreaId($knowledgeAreaContent->id);
1146
                $response = [
1147
                    'success' => true,
1148
                    'data' => [
1149
                        'reactions' => $reactions
1150
                    ]
1151
                ];
1152
            } else {
1153
                $response = [
1154
                    'success' => false,
1155
                    'data' => $contentReactionMapper->getError()
1156
                ];
1157
            }
1158
            return new JsonModel($response);
1159
        }
1160
 
1161
        $response = [
1162
            'success' => false,
1163
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1164
        ];
1165
        return new JsonModel($response);
1166
    }
1167
 
1168
    public function deleteReactionAction()
1169
    {
1170
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1171
        $currentUser    = $currentUserPlugin->getUser();
1172
 
1173
        $id = $this->params()->fromRoute('id');
1174
 
1175
        $request = $this->getRequest();
1176
        if ($request->isPost()) {
1177
 
1178
 
1179
            $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
1180
            $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
1181
            if (!$knowledgeAreaContent || $knowledgeAreaContent->network_id != $currentUser->network_id) {
1182
                return new JsonModel([
1183
                    'success'   => false,
1184
                    'data'   => 'ERROR_RECORD_NOT_FOUND'
1185
                ]);
1186
            }
1187
 
1188
            $contentReactionMapper = ContentReactionMapper::getInstance($this->adapter);
1189
            $contentReaction = $contentReactionMapper->fetchOneByKnowledgeAreaIdAndUserId($knowledgeAreaContent->id, $currentUser->id);
1190
 
1191
            if (!$contentReaction) {
1192
                $response = [
1193
                    'success' => false,
1194
                    'data' => 'ERROR_DUPLICATE_ACTION'
1195
                ];
1196
                return new JsonModel($response);
1197
            }
1198
 
1199
            if ($contentReactionMapper->deleteByKnowledgeAreaIdAndUserId($knowledgeAreaContent->id, $currentUser->id)) {
1200
                $reactions = $contentReactionMapper->fetchCountByKnowledgeAreaId($knowledgeAreaContent->id);
1201
 
1202
                $response = [
1203
                    'success' => true,
1204
                    'data' => [
1205
                        'reactions' => $reactions
1206
                    ]
1207
                ];
1208
            } else {
1209
                $response = [
1210
                    'success' => false,
1211
                    'data' => $contentReactionMapper->getError()
1212
                ];
1213
            }
1214
            return new JsonModel($response);
1215
        }
1216
 
1217
        $response = [
1218
            'success' => false,
1219
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1220
        ];
1221
        return new JsonModel($response);
1222
    }
1223
 
1224
    public function commentsAction()
1225
    {
1226
        $id = $this->params()->fromRoute('id');
1227
 
1228
        $request = $this->getRequest();
1229
        if ($request->isGet()) {
1230
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1231
            $currentUser = $currentUserPlugin->getUser();
1232
 
1233
            $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
1234
            $now = $knowledgeAreaContentMapper->getDatebaseNow();
1235
 
1236
            $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOneByUuid($id);
1237
            if (!$knowledgeAreaContent || $knowledgeAreaContent->network_id != $currentUser->network_id) {
1238
                return new JsonModel([
1239
                    'success'   => false,
1240
                    'data'   => 'ERROR_RECORD_NOT_FOUND'
1241
                ]);
1242
            }
1243
 
1244
            $commentMapper = CommentMapper::getInstance($this->adapter);
1245
            $records = $commentMapper->fetchAllPublishedByKnowledgeAreaId($knowledgeAreaContent->id);
1246
 
1247
            $comments = [];
1248
            foreach ($records as $record) {
1249
                $comment = $this->renderComment($record->id, $now);
1250
                array_push($comments, $comment);
1251
            }
1252
 
1253
            $response = [
1254
                'success' => true,
1255
                'data' => $comments
1256
            ];
1257
 
1258
            return new JsonModel($response);
1259
        } else {
1260
 
1261
 
1262
 
1263
            $response = [
1264
                'success' => false,
1265
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1266
            ];
1267
 
1268
 
1269
            return new JsonModel($response);
1270
        }
1271
    }
1272
 
1273
 
1274
 
1275
 
1276
    private function renderComment($comment_id, $now)
1277
    {
1278
        $item = [];
1279
 
1280
        $commentMapper = CommentMapper::getInstance($this->adapter);
1281
        $record = $commentMapper->fetchOne($comment_id);
1282
 
1283
        $knowledgeAreaContentMapper = KnowledgeAreaContentMapper::getInstance($this->adapter);
1284
        $knowledgeAreaContent = $knowledgeAreaContentMapper->fetchOne($record->knowledge_area_id);
1285
 
283 www 1286
 
1287
 
1 efrain 1288
        if ($record) {
333 www 1289
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1290
 
1291
 
1 efrain 1292
            $userMapper = UserMapper::getInstance($this->adapter);
1293
 
1294
            $user = $userMapper->fetchOne($record->user_id);
1295
 
1296
            $item['unique'] = uniqid();
283 www 1297
            $item['user_image'] = $storage->getUserImage($user);
1 efrain 1298
            $item['user_url'] = $this->url()->fromRoute('profile/view', ['id' => $user->uuid]);
1299
            $item['user_name'] = $user->first_name . ' ' . $user->last_name;
1300
            $item['time_elapsed'] = Functions::timeAgo($record->added_on, $now);
1301
            $item['comment'] = $record->comment;
1302
            $item['link_delete'] = $this->url()->fromRoute('knowledge-area/comments/delete', ['id' => $knowledgeAreaContent->uuid, 'comment' => $record->uuid]);
1303
        }
1304
        return $item;
1305
    }
1306
}