Proyectos de Subversion LeadersLinked - Services

Rev

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