Proyectos de Subversion LeadersLinked - Backend

Rev

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

Rev Autor Línea Nro. Línea
1 www 1
<?php
2
declare(strict_types=1);
3
 
4
namespace LeadersLinked\Controller;
5
 
6
use Laminas\Db\Adapter\AdapterInterface;
16768 efrain 7
 
1 www 8
use Laminas\Mvc\Controller\AbstractActionController;
9
use Laminas\Log\LoggerInterface;
10
use Laminas\View\Model\ViewModel;
11
use Laminas\View\Model\JsonModel;
12
use LeadersLinked\Library\Functions;
13
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
14
use LeadersLinked\Library\Image;
15
use LeadersLinked\Mapper\CompanyMapper;
16
use LeadersLinked\Mapper\CompanyMicrolearningTopicMapper;
17
use LeadersLinked\Model\CompanyMicrolearningTopic;
18
use LeadersLinked\Form\TopicAddForm;
19
use LeadersLinked\Form\TopicEditForm;
20
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleMapper;
21
 
22
 
23
class MicrolearningTopicController extends AbstractActionController
24
{
25
    /**
26
     *
27
     * @var AdapterInterface
28
     */
29
    private $adapter;
30
 
31
    /**
32
     *
33
     * @var  LoggerInterface
34
     */
35
    private $logger;
36
 
37
    /**
38
     *
39
     * @var array
40
     */
41
    private $config;
42
 
43
    /**
44
     *
45
     * @param AdapterInterface $adapter
46
     * @param LoggerInterface $logger
47
     * @param array $config
48
     */
16768 efrain 49
    public function __construct($adapter, $logger, $config)
1 www 50
    {
16768 efrain 51
        $this->adapter = $adapter;
52
        $this->logger = $logger;
53
        $this->config = $config;
1 www 54
    }
55
 
56
    /**
57
     *
58
     * Generación del listado de perfiles
59
     * {@inheritDoc}
60
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
61
     */
62
    public function indexAction()
63
    {
64
        $request = $this->getRequest();
65
        $currentUserPlugin = $this->plugin('currentUserPlugin');
66
        $currentCompany = $currentUserPlugin->getCompany();
67
        $currentUser    = $currentUserPlugin->getUser();
68
 
69
 
70
        $request = $this->getRequest();
71
        if($request->isGet()) {
72
 
73
 
74
            $headers  = $request->getHeaders();
75
 
76
            $isJson = false;
77
            if($headers->has('Accept')) {
78
                $accept = $headers->get('Accept');
79
 
80
                $prioritized = $accept->getPrioritized();
81
 
82
                foreach($prioritized as $key => $value) {
83
                    $raw = trim($value->getRaw());
84
 
85
                    if(!$isJson) {
86
                        $isJson = strpos($raw, 'json');
87
                    }
88
 
89
                }
90
            }
91
 
92
            if($isJson) {
93
                $search = $this->params()->fromQuery('search', []);
16766 efrain 94
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);
1 www 95
 
96
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
5655 nelberth 97
                $page               = (intval($this->params()->fromQuery('start', 1), 10)/$records_x_page)+1;
1 www 98
                $order =  $this->params()->fromQuery('order', []);
99
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
16766 efrain 100
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : strtoupper(Functions::sanitizeFilterString($order[0]['dir']));
1 www 101
 
102
                $fields =  ['name'];
103
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';
104
 
105
                if(!in_array($order_direction, ['ASC', 'DESC'])) {
106
                    $order_direction = 'ASC';
107
                }
108
 
109
 
110
 
111
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
112
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/edit');
113
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/delete');
114
 
115
 
116
                $companyMicrolearningTopicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
117
 
118
                $paginator = $companyMicrolearningTopicMapper->fetchAllDataTableByCompanyId($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);
119
 
120
                $records = $paginator->getCurrentItems();
121
 
122
                $items = [];
123
                foreach($records as $record)
124
                {
125
 
126
                    //print_r($record);
127
 
128
 
129
                    switch($record->status) {
130
                        case  CompanyMicrolearningTopic::STATUS_ACTIVE :
131
                            $status = 'LABEL_ACTIVE';
132
                            break;
133
 
134
                        case  CompanyMicrolearningTopic::STATUS_INACTIVE :
135
                            $status = 'LABEL_INACTIVE';
136
                            break;
137
 
138
                        default :
139
                            $status = '';
140
                            break;
141
                    }
142
 
143
 
144
 
145
 
146
                    $item = [
147
 
148
                        'name' => $record->name,
149
                        'status' => $status,
150
                        'image' => $this->url()->fromRoute('storage', ['type' => 'microlearning-topic', 'code' => $record->uuid, 'filename' => $record->image]),
151
                        'actions' => [
152
                            'link_edit' => $allowEdit ? $this->url()->fromRoute('microlearning/content/topics/edit', ['id' => $record->uuid ])  : '',
153
                            'link_delete' => $allowDelete ? $this->url()->fromRoute('microlearning/content/topics/delete', ['id' => $record->uuid ]) : '',
154
                        ]
155
 
156
 
157
                    ];
158
 
159
 
160
                    array_push($items, $item);
161
                }
162
 
163
 
164
 
165
                return new JsonModel([
166
                    'success' => true,
167
                    'data' => [
168
                        'items' => $items,
169
                        'total' => $paginator->getTotalItemCount(),
170
                    ]
171
                ]);
172
 
173
 
174
 
175
            } else {
176
 
177
                $image_size = $this->config['leaderslinked.image_sizes.microlearning_image_upload'];
178
                $marketplace_size = $this->config['leaderslinked.image_sizes.marketplace'];
179
 
180
                $formAdd = new TopicAddForm();
181
                $formEdit = new TopicEditForm();
182
                $this->layout()->setTemplate('layout/layout-backend.phtml');
183
                $viewModel = new ViewModel();
184
                $viewModel->setTemplate('leaders-linked/microlearning-topics/index.phtml');
185
                $viewModel->setVariables([
186
                   'formAdd' => $formAdd,
187
                   'formEdit' => $formEdit,
188
                   'company_uuid' => $currentCompany->uuid,
189
                   'image_size' => $image_size,
190
                   'marketplace_size' => $marketplace_size,
191
                ]);
192
                return $viewModel ;
193
            }
194
 
195
        } else {
196
            return new JsonModel([
197
                'success' => false,
198
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
199
            ]);
200
        }
201
    }
202
 
203
    public function addAction()
204
    {
205
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
206
        $currentCompany     = $currentUserPlugin->getCompany();
207
        $currentUser        = $currentUserPlugin->getUser();
208
 
209
        $request    = $this->getRequest();
5579 nelberth 210
      /*  return new JsonModel([
5577 nelberth 211
            'success' => false,
212
            'data' => [
213
                'name'=>$this->params()->fromPost('file_base64_name'),
5578 nelberth 214
                'content'=>$this->params()->fromPost('file'),
5577 nelberth 215
            ]
5579 nelberth 216
        ]);*/
1 www 217
        if($request->isPost()) {
218
            $form = new  TopicAddForm();
219
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
220
 
221
            $form->setData($dataPost);
222
 
223
            if($form->isValid()) {
224
                $dataPost = (array) $form->getData();
225
 
226
                $hydrator = new ObjectPropertyHydrator();
227
                $topic = new CompanyMicrolearningTopic();
228
                $hydrator->hydrate($dataPost, $topic);
229
 
230
                $topic->company_id = $currentCompany->id;
231
                $topic->image = null;
232
 
233
 
234
 
235
                $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
236
                if($topicMapper->insert($topic)) {
237
                    $topic = $topicMapper->fetchOne($topic->id);
5581 nelberth 238
                    $fileBase64Content = $this->params()->fromPost('file');
5914 nelberth 239
 
5574 nelberth 240
                    try {
5581 nelberth 241
 
242
                        $fileBase64Content = base64_decode($fileBase64Content);
5574 nelberth 243
                        $target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] . $topic->uuid;
7115 nelberth 244
                        $topic_filename      = 'topic-' .uniqid() . '.jpg';
5581 nelberth 245
                        $topic_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp';
246
                        if(!file_exists($topic_tmp_filename)) {
247
                            mkdir($topic_tmp_filename, 0755, true);
5574 nelberth 248
                        }
5582 nelberth 249
                        $topic_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $topic_filename;
5581 nelberth 250
                            file_put_contents($topic_tmp_filename, $fileBase64Content);
5574 nelberth 251
 
252
                        list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
253
 
254
                        $crop_to_dimensions = false;
255
                        if(Image::uploadImage($topic_tmp_filename, $target_path, $topic_filename, $target_width, $target_height, $crop_to_dimensions )) {
256
                            $topic->image = basename($topic_filename);
257
                            $topicMapper->update($topic);
258
                        }
259
                    } catch(\Throwable $e) {
260
                        error_log($e->getTraceAsString());
5914 nelberth 261
                    }
1 www 262
 
263
                    $this->logger->info('Se agrego el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
264
 
265
                    $data = [
266
                        'success'   => true,
267
                        'data'   => 'LABEL_RECORD_ADDED'
268
                    ];
269
                } else {
270
                    $data = [
271
                        'success'   => false,
272
                        'data'      => $topicMapper->getError()
273
                    ];
274
 
275
                }
276
 
277
                return new JsonModel($data);
278
 
279
            } else {
280
                $messages = [];
281
                $form_messages = (array) $form->getMessages();
282
                foreach($form_messages  as $fieldname => $field_messages)
283
                {
284
 
285
                    $messages[$fieldname] = array_values($field_messages);
286
                }
287
 
288
                return new JsonModel([
289
                    'success'   => false,
290
                    'data'   => $messages
291
                ]);
292
            }
293
 
294
        } else {
295
            $data = [
296
                'success' => false,
297
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
298
            ];
299
 
300
            return new JsonModel($data);
301
        }
302
 
303
        return new JsonModel($data);
304
    }
305
 
306
    /**
307
     *
308
     * Borrar un perfil excepto el público
309
     * @return \Laminas\View\Model\JsonModel
310
     */
311
    public function deleteAction()
312
    {
313
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
314
        $currentCompany     = $currentUserPlugin->getCompany();
315
        $currentUser        = $currentUserPlugin->getUser();
316
 
317
        $request    = $this->getRequest();
318
        $id   = $this->params()->fromRoute('id');
319
 
320
 
321
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
322
        $topic = $topicMapper->fetchOneByUuid($id);
323
        if(!$topic) {
324
            return new JsonModel([
325
                'success'   => false,
326
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
327
            ]);
328
        }
329
 
330
        if($topic->company_id != $currentCompany->id) {
331
            return new JsonModel([
332
                'success'   => false,
333
                'data'   => 'ERROR_UNAUTHORIZED'
334
            ]);
335
        }
336
 
337
 
338
 
339
        if($request->isPost()) {
340
            $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
341
            $count = $capsuleMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
342
            if($count > 0 ) {
343
                return new JsonModel([
344
                    'success'   => false,
345
                    'data'   => 'ERROR_SQL_CANNOT_DELETE_OR_UPDATE_A_PARENT_ROW'
346
                ]);
347
            }
348
 
349
 
350
 
351
            $result = $topicMapper->delete($topic);
352
            if($result) {
353
                $this->logger->info('Se borro el tópico : ' .  $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
354
                try {
355
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] . DIRECTORY_SEPARATOR . $topic->uuid;
356
                    if(file_exists($target_path)) {
357
                        Functions::rmDirRecursive($target_path);
358
                    }
359
                } catch(\Throwable $e) {
360
                    error_log($e->getTraceAsString());
361
                }
362
 
363
 
364
                $data = [
365
                    'success' => true,
366
                    'data' => 'LABEL_RECORD_DELETED'
367
                ];
368
            } else {
369
 
370
                $data = [
371
                    'success'   => false,
372
                    'data'      => $topicMapper->getError()
373
                ];
374
 
375
                return new JsonModel($data);
376
            }
377
 
378
        } else {
379
            $data = [
380
                'success' => false,
381
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
382
            ];
383
 
384
            return new JsonModel($data);
385
        }
386
 
387
        return new JsonModel($data);
388
    }
389
 
390
 
391
    public function editAction()
392
    {
393
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
394
        $currentCompany     = $currentUserPlugin->getCompany();
395
        $currentUser        = $currentUserPlugin->getUser();
396
 
397
        $request    = $this->getRequest();
398
        $id   = $this->params()->fromRoute('id');
399
 
400
 
401
 
402
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
403
        $topic = $topicMapper->fetchOneByUuid($id);
404
        if(!$topic) {
405
            return new JsonModel([
406
                'success'   => false,
407
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
408
            ]);
409
        }
410
 
411
        if($topic->company_id != $currentCompany->id) {
412
            return new JsonModel([
413
                'success'   => false,
414
                'data'   => 'ERROR_UNAUTHORIZED'
415
            ]);
416
        }
417
 
418
        if($request->isGet()) {
419
            $data = [
420
                'success' => true,
421
                'data' => [
422
                    'name' => $topic->name,
423
                    'description' => $topic->description,
424
                    'order' => $topic->order,
425
                    'status' => $topic->status,
5915 nelberth 426
                    'image'=> $this->url()->fromRoute('storage', ['type' => 'microlearning-topic', 'code' => $topic->uuid, 'filename' => $topic->image])
1 www 427
                ]
428
            ];
429
 
430
            return new JsonModel($data);
431
        }
432
        else if($request->isPost()) {
433
            $form = new  TopicEditForm();
434
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
435
 
436
            $form->setData($dataPost);
437
 
438
            if($form->isValid()) {
439
                $dataPost = (array) $form->getData();
440
 
441
                $hydrator = new ObjectPropertyHydrator();
442
                $hydrator->hydrate($dataPost, $topic);
443
                $topic->image = null;
444
                $topic->marketplace = null;
445
 
446
                if($topicMapper->update($topic)) {
447
                    $topic = $topicMapper->fetchOne($topic->id);
5993 nelberth 448
                    $fileBase64Content = $this->params()->fromPost('file');
449
                    try {
7237 nelberth 450
                        $target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] . $topic->uuid;
7236 nelberth 451
                        if($topic->image) {
452
 
453
                            if(!image ::delete($target_path, $topic->image)) {
454
                                return new JsonModel([
455
                                    'success'   => false,
456
                                    'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
457
                                ]);
458
                            }
459
                        }
5993 nelberth 460
                        $fileBase64Content = base64_decode($fileBase64Content);
7237 nelberth 461
 
7115 nelberth 462
                        $topic_filename      = 'topic-' .uniqid() . '.jpg';
5993 nelberth 463
                        $topic_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp';
464
                        if(!file_exists($topic_tmp_filename)) {
465
                            mkdir($topic_tmp_filename, 0755, true);
466
                        }
467
                        $topic_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $topic_filename;
468
                            file_put_contents($topic_tmp_filename, $fileBase64Content);
469
 
470
                        list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
471
 
472
                        $crop_to_dimensions = false;
473
                        if(Image::uploadImage($topic_tmp_filename, $target_path, $topic_filename, $target_width, $target_height, $crop_to_dimensions )) {
474
                            $topic->image = basename($topic_filename);
475
                            $topicMapper->update($topic);
476
                        }
477
                    } catch(\Throwable $e) {
478
                        error_log($e->getTraceAsString());
479
                    }
480
 
481
                    $this->logger->info('Se agrego el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1 www 482
 
5993 nelberth 483
                    $data = [
484
                        'success'   => true,
5996 nelberth 485
                        'data'   => 'LABEL_RECORD_UPDATED'
5993 nelberth 486
                    ];
487
                    /*
488
                    $topic = $topicMapper->fetchOne($topic->id);
1 www 489
 
5993 nelberth 490
 
1 www 491
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] .  $topic->uuid;
492
                    if(!file_exists($target_path)) {
493
                        mkdir($target_path, 0755, true);
494
                    }
495
 
496
 
497
                    $files = $this->getRequest()->getFiles()->toArray();
498
                    if(isset($files['file']) && empty($files['file']['error'])) {
499
                        $tmp_filename  = $files['file']['tmp_name'];
500
                        //$filename      = $this->normalizeString($files['file']['name']);
501
 
502
                        try {
503
                            if($topic->image) {
504
 
505
                                if(!image ::delete($target_path, $topic->image)) {
506
                                    return new JsonModel([
507
                                        'success'   => false,
508
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
509
                                    ]);
510
                                }
511
                            }
512
 
513
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
514
 
515
                            $filename = 'topic-' .uniqid() . '.png';
516
                            $crop_to_dimensions = true;
517
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
518
                                $topic->image = $filename;
519
                                $topicMapper->update($topic);
520
                            }
521
                        } catch(\Throwable $e) {
522
                            error_log($e->getTraceAsString());
523
                        }
524
                    }
525
 
526
 
527
 
528
 
529
                    $this->logger->info('Se edito el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
530
 
531
                    $data = [
532
                        'success'   => true,
533
                        'data'   => 'LABEL_RECORD_UPDATED'
5993 nelberth 534
                    ];*/
1 www 535
                } else {
536
                    $data = [
537
                        'success'   => false,
538
                        'data'      => $topicMapper->getError()
539
                    ];
540
 
541
                }
542
 
543
                return new JsonModel($data);
544
 
545
            } else {
546
                $messages = [];
547
                $form_messages = (array) $form->getMessages();
548
                foreach($form_messages  as $fieldname => $field_messages)
549
                {
550
 
551
                    $messages[$fieldname] = array_values($field_messages);
552
                }
553
 
554
                return new JsonModel([
555
                    'success'   => false,
556
                    'data'   => $messages
557
                ]);
558
            }
559
        } else {
560
            $data = [
561
                'success' => false,
562
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
563
            ];
564
 
565
            return new JsonModel($data);
566
        }
567
 
568
        return new JsonModel($data);
569
    }
570
}