Proyectos de Subversion LeadersLinked - Backend

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
10273 eleazar 1
<?php
11317 eleazar 2
declare(strict_types=1);
10273 eleazar 3
 
11317 eleazar 4
namespace LeadersLinked\Controller;
10273 eleazar 5
 
11985 eleazar 6
 
11317 eleazar 7
use Laminas\Db\Adapter\AdapterInterface;
8
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
9
use Laminas\Mvc\Controller\AbstractActionController;
11985 eleazar 10
use Laminas\Log\LoggerInterface;
11
use Laminas\View\Model\ViewModel;
12
use Laminas\View\Model\JsonModel;
13
 
14
use LeadersLinked\Mapper\CompanyMapper;
15
use LeadersLinked\Mapper\CompanyUserMapper;
16
use LeadersLinked\Form\CreateFeedForm;
11798 eleazar 17
use LeadersLinked\Form\CommentForm;
18
use LeadersLinked\Form\CommentAnswerForm;
19
use LeadersLinked\Model\Comment;
20
use LeadersLinked\Mapper\CommentMapper;
21
use LeadersLinked\Mapper\FeedMapper;
22
use LeadersLinked\Mapper\GroupMapper;
11985 eleazar 23
use LeadersLinked\Model\Feed;
24
use LeadersLinked\Mapper\QueryMapper;
11317 eleazar 25
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
11795 eleazar 26
use LeadersLinked\Library\Image;
27
use LeadersLinked\Model\VideoConvert;
28
use LeadersLinked\Mapper\VideoConvertMapper;
29
use LeadersLinked\Mapper\LikeMapper;
30
use Laminas\Paginator\Adapter\DbSelect;
31
use Laminas\Paginator\Paginator;
32
use LeadersLinked\Mapper\UserMapper;
33
use LeadersLinked\Library\Functions;
34
use LeadersLinked\Model\Company;
35
use LeadersLinked\Model\UserType;
11985 eleazar 36
use Laminas\Authentication\AuthenticationService;
37
use Laminas\Authentication\Result as AuthResult;
38
use Laminas\Mvc\I18n\Translator;
39
use LeadersLinked\Mapper\MyTrainerQuestionsMapper;
40
use LeadersLinked\Mapper\FeedTopicMapper;
12376 eleazar 41
use LeadersLinked\Mapper\TopicMapper;
11985 eleazar 42
use LeadersLinked\Form\MyTrainerQuestionForm;
43
use LeadersLinked\Model\MyTrainerQuestions;
10601 eleazar 44
 
11709 eleazar 45
use LeadersLinked\Model\FeedTopic;
11317 eleazar 46
use LeadersLinked\Form\TopicForm;
14740 efrain 47
use LeadersLinked\Mapper\UtilMapper;
10601 eleazar 48
 
11317 eleazar 49
class MyTrainerAnswerController extends AbstractActionController
50
{
51
    /**
52
     *
53
     * @var AdapterInterface
54
     */
55
    private $adapter;
56
 
57
 
58
    /**
59
     *
60
     * @var AbstractAdapter
61
     */
62
    private $cache;
63
 
64
    /**
65
     *
66
     * @var  LoggerInterface
67
     */
68
    private $logger;
69
 
70
    /**
71
     *
72
     * @var array
73
     */
74
    private $config;
75
 
76
 
77
 
78
    /**
79
     *
80
     * @param AdapterInterface $adapter
81
     * @param AbstractAdapter $cache
82
     * @param LoggerInterface $logger
83
     * @param array $config
84
     */
85
    public function __construct($adapter, $cache , $logger, $config)
86
    {
87
        $this->adapter      = $adapter;
88
        $this->cache        = $cache;
89
        $this->logger       = $logger;
90
        $this->config       = $config;
91
 
92
 
10273 eleazar 93
    }
10601 eleazar 94
 
11873 eleazar 95
    public function indexAction()
96
    {
97
        $currentUserPlugin = $this->plugin('currentUserPlugin');
98
        $currentUser = $currentUserPlugin->getUser();
99
        $currentCompany = $currentUserPlugin->getCompany();
11882 eleazar 100
        $id =  $this->params()->fromRoute('id');
12603 eleazar 101
 
11982 eleazar 102
        $feedMapper = FeedMapper::getInstance($this->adapter);
103
        $title  = $feedMapper->fetchOneByUuid($id);
12621 eleazar 104
 
11837 eleazar 105
        $request = $this->getRequest();
11873 eleazar 106
        if($request->isGet()) {
107
            $headers  = $request->getHeaders();
108
 
109
            $isJson = false;
110
            if($headers->has('Accept')) {
111
                $accept = $headers->get('Accept');
112
 
113
                $prioritized = $accept->getPrioritized();
114
 
115
                foreach($prioritized as $key => $value) {
116
                    $raw = trim($value->getRaw());
117
 
118
                    if(!$isJson) {
119
                        $isJson = strpos($raw, 'json');
120
                    }
12707 eleazar 121
 
11873 eleazar 122
                }
123
            }
12471 eleazar 124
 
125
            $form = new CreateFeedForm($this->adapter);
12794 eleazar 126
 
127
            $tagsMapper = TopicMapper::getInstance($this->adapter);
12470 eleazar 128
            $topicsMapper = FeedTopicMapper::getInstance($this->adapter);
12590 eleazar 129
            $feedTopic = $topicsMapper->fetchOneByFeedId($title->id);
12816 eleazar 130
            $answer = $feedMapper->fetchAllByMytAnswer($title->related_feed);
12707 eleazar 131
            $topicRelationships = $topicsMapper->fetchAllByTopicId($feedTopic->topic_id);
12794 eleazar 132
            $tags = $topicsMapper->fetchAllByFeedId($title->id);
12707 eleazar 133
                foreach ($topicRelationships as $rel) {
134
 
12708 eleazar 135
                    if ($question = $feedMapper->fetchOne($rel->feed_id)) {
12707 eleazar 136
                        $questions [] = $question;
137
                    }
12580 eleazar 138
                }
12794 eleazar 139
 
140
                foreach($tags as $tel){
12796 eleazar 141
                    $badge = $tagsMapper->fetchOne($tel->topic_id);
12794 eleazar 142
                    $badges [] = $badge;
143
                }
12798 eleazar 144
 
12819 eleazar 145
 
11873 eleazar 146
            $this->layout()->setTemplate('layout/layout-backend');
147
            $viewModel = new ViewModel();
11877 eleazar 148
            $viewModel->setTemplate('leaders-linked/my-trainer-answer/index.phtml');
11873 eleazar 149
            $viewModel->setVariables([
11878 eleazar 150
                'form'      => $form,
11882 eleazar 151
                'id'        => $id,
11982 eleazar 152
                'title_title' => $title->title,
153
                'title_description' => $title->description,
12520 eleazar 154
                'questions' => $questions,
12798 eleazar 155
                'badges' => $badges,
12811 eleazar 156
                'date' => $title->added_on,
12819 eleazar 157
                'answer' => $answer,
12501 eleazar 158
 
11873 eleazar 159
            ]);
160
            return $viewModel ;
12707 eleazar 161
 
162
 
11873 eleazar 163
        } else {
164
            return new JsonModel([
165
                'success' => false,
166
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
167
            ]);
168
        }
169
    }
11944 eleazar 170
 
11971 eleazar 171
    public function timelineAction(){
11944 eleazar 172
         $currentUserPlugin = $this->plugin('currentUserPlugin');
173
         $currentUser = $currentUserPlugin->getUser();
174
         $currentCompany = $currentUserPlugin->getCompany();
11945 eleazar 175
         $request = $this->getRequest();
11944 eleazar 176
         if($request->isGet()) {
177
 
11952 eleazar 178
            $feed_uuid =  $this->params()->fromRoute('id');
179
                     if(!isset($feed_uuid)){
180
                    $data = [
181
                        'success'   => false,
182
                        'data'   => 'ERROR_INVALID_PARAMETER'
183
                    ];
11944 eleazar 184
 
11952 eleazar 185
                    return new JsonModel($data);
186
            }
187
 
188
            $items = [];
189
            $feedMapper = FeedMapper::getInstance($this->adapter);
11953 eleazar 190
            $feed  = $feedMapper->fetchOneByUuid($feed_uuid);
11954 eleazar 191
            $feeds = $feedMapper->fetchAllByMytAnswer($feed->related_feed);
11957 eleazar 192
 
193
            if (!$feeds) {
11952 eleazar 194
                $data = [
195
                    'success' => false,
196
                    'data' => 'ERROR_RECORD_NOT_FOUND'
197
                ];
198
                      return new JsonModel($data);
199
            }
200
 
11955 eleazar 201
            $items = [];
14740 efrain 202
 
203
            $utilMapper = UtilMapper::getInstance($this->adapter);
204
            $now = $utilMapper->getDatebaseNow();
11955 eleazar 205
 
206
 
207
            foreach($feeds as $solution)
208
            {
14740 efrain 209
                $items = $this->renderFeed($solution->id, $now);
11955 eleazar 210
            }
11962 eleazar 211
 
11952 eleazar 212
               $response = [
213
                    'success' => true,
214
                    'data' => [
11959 eleazar 215
                        'items' =>$items,
11952 eleazar 216
                        'feed_title'=>$feed->title,
217
                        'topic_title'=>$feed->description
218
                    ]
219
                ];
220
                      return new JsonModel($response);
221
        }
11944 eleazar 222
    }
11873 eleazar 223
 
11971 eleazar 224
    public function feedAction() {
11967 eleazar 225
 
226
        $currentUserPlugin = $this->plugin('currentUserPlugin');
227
        $currentUser = $currentUserPlugin->getUser();
228
        $currentCompany = $currentUserPlugin->getCompany();
229
 
230
 
231
 
232
 
11837 eleazar 233
 
11967 eleazar 234
        $request = $this->getRequest();
235
        if($request->isGet()) {
236
 
237
 
11972 eleazar 238
            $page = (int) $this->params()->fromQuery('page');
11967 eleazar 239
            $myt_id =  $this->params()->fromRoute('id');
240
 
241
 
242
            $feedMapper = FeedMapper::getInstance($this->adapter);
243
            $myt  = $feedMapper->fetchOneByUuid($myt_id);
244
            $queryMapper = QueryMapper::getInstance($this->adapter);
245
            $select = $queryMapper->getSql()->select(FeedMapper::_TABLE);
11973 eleazar 246
            $select->columns(['id']);
11967 eleazar 247
            $select->where->equalTo('status', Feed::STATUS_PUBLISHED);
248
            $select->where->equalTo('company_id',$currentCompany->id);
249
            $select->where->equalTo('related_feed', $myt->id);
250
            $select->where->and->equalTo('type', Feed::TYPE_MYT_ANSWER);
251
            $select->order('added_on desc');
252
 
253
 
254
            $dbSelect = new DbSelect($select, $this->adapter);
255
            $paginator = new Paginator($dbSelect);
256
            $paginator->setCurrentPageNumber($page ? $page : 1);
257
            $paginator->setItemCountPerPage(10);
258
 
259
            $items = [];
260
            $feeds = $paginator->getCurrentItems();
11980 eleazar 261
 
14740 efrain 262
 
263
            $utilMapper = UtilMapper::getInstance($this->adapter);
264
            $now = $utilMapper->getDatebaseNow();
265
 
11967 eleazar 266
            foreach($feeds as $feed)
267
            {
14740 efrain 268
                $items[] = $this->renderFeed($feed->id, $now);
11967 eleazar 269
            }
270
 
271
            $response = [
272
                'success' => true,
273
                'data' => [
274
                    'total' => [
275
                        'count' => $paginator->getTotalItemCount(),
276
                        'pages' => $paginator->getPages()->pageCount,
277
                    ],
278
                    'current' => [
279
                        'items'    => $items,
280
                        'page'     => $paginator->getCurrentPageNumber(),
281
                        'count'    => $paginator->getCurrentItemCount(),
282
                    ]
283
                ]
284
            ];
285
 
286
            return new JsonModel($response);
287
        }
288
 
289
        $response = [
290
            'success' => false,
291
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
292
        ];
293
 
294
 
295
        return new JsonModel($response);
296
    }
297
 
11336 eleazar 298
    public function addAction() {
299
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
300
        $currentCompany     = $currentUserPlugin->getCompany();
301
        $currentUser        = $currentUserPlugin->getUser();
302
 
11787 eleazar 303
        $id =  $this->params()->fromRoute('id');
11343 eleazar 304
        $questionsMapper = FeedMapper::getInstance($this->adapter);
11787 eleazar 305
        $question = $questionsMapper->fetchOneByUuid($id);
11336 eleazar 306
        $request    = $this->getRequest();
307
        try{
308
        if($request->isPost()) {
309
            $form = new  CreateFeedForm($this->adapter);
11710 eleazar 310
 
311
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
11336 eleazar 312
            $categoriesId = $dataPost['category_id'] ?? [];
313
            $dataPost['category_id'] = null;
314
            $form->setData($dataPost);
315
 
316
            if($form->isValid()) {
317
 
318
                $dataPost = (array) $form->getData();
319
                $hydrator = new ObjectPropertyHydrator();
320
                $feed = new Feed();
321
                $hydrator->hydrate($dataPost, $feed);
322
 
323
                $feed->user_id = $currentUser->id;
324
                $feed->company_id = $currentCompany->id;
325
                $feed->user_id          = $currentUser->id;
11343 eleazar 326
                $feed->type             = Feed::TYPE_MYT_ANSWER;
11336 eleazar 327
                $feed->posted_or_shared = Feed::POSTED;
328
                $feed->shared_with      = Feed::SHARE_WITH_PUBLIC;
11343 eleazar 329
                $feed->related_feed = $question->id;
11336 eleazar 330
 
11710 eleazar 331
                $feed->total_comments   = 0;
332
                $feed->total_shared     = 0;
333
 
334
 
335
                $files = $this->getRequest()->getFiles()->toArray();
336
                $file_type = '';
337
                if(isset($files['file']) && empty($files['file']['error'])) {
338
                    $feed_tmp_filename  = $files['file']['tmp_name'];
339
                    $feed_filename      = $this->normalizeString($files['file']['name']);
340
 
341
                    $mime_type = mime_content_type($feed_tmp_filename);
342
                    if($mime_type == 'image/jpg' || $mime_type == 'image/jpeg' || $mime_type == 'image/png') {
343
                        $file_type = Feed::FILE_TYPE_IMAGE;
344
                    } else if($mime_type == 'video/webm' || $mime_type == 'video/mpeg' || $mime_type == 'video/mpg' || $mime_type == 'video/mp4') {
345
                        $file_type = Feed::FILE_TYPE_VIDEO;
346
                    } else if($mime_type == 'application/pdf') {
347
                        $file_type = Feed::FILE_TYPE_DOCUMENT;
348
                    }
349
                }
350
 
11336 eleazar 351
                $feedMapper = FeedMapper::getInstance($this->adapter);
352
 
353
                if($feedMapper->insert($feed)) {
11343 eleazar 354
                    $feed = $feedMapper->fetchOne($feed->id);
355
                    $category = new FeedTopic();
356
                    $feedMapper->update($feed);
11705 eleazar 357
 
11336 eleazar 358
 
11705 eleazar 359
                        $feed = $feedMapper->fetchOne($feed->id);
360
 
361
                        if( $file_type == Feed::FILE_TYPE_DOCUMENT) {
362
                            try {
363
                                $target_path = $this->config['leaderslinked.fullpath.feed'] . $feed->uuid;
364
                                if(!file_exists($target_path)) {
365
                                    mkdir($target_path, 0755);
366
                                }
367
 
368
                                $full_filename = $target_path  . DIRECTORY_SEPARATOR .$feed_filename;
369
                                $result = move_uploaded_file($feed_tmp_filename , $full_filename);
370
                                if($result) {
371
 
372
                                    $feed->file_type = $file_type;
373
                                    $feed->file_name = basename($feed_filename);
374
                                    $feedMapper->update($feed);
375
                                } else {
376
                                    error_log('no se pudo mover o renombrar el documento : ' . $feed_tmp_filename . ' al directorio : ' . $full_filename );
377
                                }
378
                            } catch(\Throwable $e) {
379
                                error_log($e->getTraceAsString());
380
                            }
381
                        }
382
                        if( $file_type == Feed::FILE_TYPE_IMAGE) {
383
                            try {
384
                                $target_path = $this->config['leaderslinked.fullpath.feed'] . $feed->uuid;
385
                                if(!file_exists($target_path)) {
386
                                    mkdir($target_path, 0755);
387
                                }
388
 
389
                                list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.feed_image_size']);
390
 
391
                                $feed_filename = substr($feed_filename, 0, strrpos($feed_filename, '.'))  . '.png';
392
                                $crop_to_dimensions = false;
393
                                if(Image::uploadImage($feed_tmp_filename, $target_path, $feed_filename, $target_width, $target_height, $crop_to_dimensions )) {
394
                                    $feed->file_type = $file_type;
395
                                    $feed->file_name = basename($feed_filename);
396
                                    $feedMapper->update($feed);
397
                                }
398
                            } catch(\Throwable $e) {
399
                                error_log($e->getTraceAsString());
400
                            }
401
                        }
402
                        if( $file_type == Feed::FILE_TYPE_VIDEO) {
403
                            try {
404
                                $target_path = $this->config['leaderslinked.fullpath.feed'] . $feed->uuid;
405
                                if(!file_exists($target_path)) {
406
                                    mkdir($target_path, 0755);
407
                                }
408
 
409
                                $full_filename = $target_path  . DIRECTORY_SEPARATOR . $feed_filename;
410
 
411
                                $result = move_uploaded_file($feed_tmp_filename , $full_filename);
412
                                if($result) {
413
 
414
                                    $size = $this->config['leaderslinked.image_sizes.feed_image_size'];
415
                                    $getFromSecound = 2;
416
 
417
                                    //extracción del cover
418
                                    $generateFileName = substr($feed_filename, 0, strrpos($feed_filename, '.'));
419
                                    $generateFile =  $target_path  . DIRECTORY_SEPARATOR . $generateFileName .  '.png';
420
                                    $cmd            = "/usr/bin/ffmpeg -i $full_filename -an -ss $getFromSecound -s $size $generateFile";
421
                                    exec($cmd);
422
 
423
 
424
                                    $feed->file_type = $file_type;
425
                                    $feed->file_name = basename($feed_filename);
426
                                    $feed->file_image_preview = basename($generateFile);
427
                                    $feedMapper->update($feed);
428
 
429
                                    $videoConvert = new VideoConvert();
430
                                    $videoConvert->filename = $full_filename;
431
                                    $videoConvert->type = VideoConvert::TYPE_FEED;
432
 
433
                                    $videoConvertMapper = VideoConvertMapper::getInstance($this->adapter);
434
                                    $videoConvertMapper->insert($videoConvert);
435
                                } else {
436
                                    error_log('no se pudo mover o renombrar el documento : ' . $feed_tmp_filename . ' al directorio : ' . $full_filename );
437
                                }
438
                            } catch(\Throwable $e) {
439
                                error_log($e->getTraceAsString());
440
                            }
441
                        }
11714 eleazar 442
 
443
 
444
                        $response = [
445
                            'success'   => true,
446
                            'data'   => 'success'
447
                        ];
11336 eleazar 448
                } else {
11705 eleazar 449
                    $messages = [];
450
                    $form_messages = (array) $form->getMessages();
451
                    foreach($form_messages  as $fieldname => $field_messages)
452
                    {
453
                        $messages[$fieldname] = array_values($field_messages);
454
                    }
455
 
11336 eleazar 456
                }
457
 
458
            } else {
11705 eleazar 459
                $response = [
460
                    'success' => false,
461
                    'data' => 'ERROR_METHOD_NOT_ALLOWED'
462
                ];
11336 eleazar 463
            }
464
 
11714 eleazar 465
            return new JsonModel($response);
11336 eleazar 466
        }
467
 
468
    } catch (\Throwable $e) {
469
        $e->getMessage();
11984 eleazar 470
        return new JsonModel([
471
            'success' => false,
472
            'data' => $e
473
        ]);
11336 eleazar 474
    }
475
    }
11791 eleazar 476
 
11998 eleazar 477
     /**
478
     *
479
     * @param string $str
480
     * @return string
481
     */
482
    private function normalizeString ($str = ''){
483
        $basename  = substr($str, 0, strrpos($str, '.'));
484
        $basename  = str_replace('.', '-', $basename);
485
 
486
        $extension  = substr($str, strrpos($str, '.'));
487
 
488
        $str = $basename . $extension;
489
 
490
        $str = strip_tags($str);
491
        $str = preg_replace('/[\r\n\t ]+/', ' ', $str);
492
        $str = preg_replace('/[\"\*\/\:\<\>\?\'\|\,]+/', ' ', $str);
493
        $str = strtolower($str);
494
        $str = html_entity_decode( $str, ENT_QUOTES, "utf-8" );
495
        $str = htmlentities($str, ENT_QUOTES, "utf-8");
496
        $str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
497
        $str = str_replace(' ', '-', $str);
498
        $str = rawurlencode($str);
499
        $str = str_replace('%', '-', $str);
500
        return trim(strtolower($str));
501
    }
502
 
14740 efrain 503
    private function renderFeed($id , $now){
11791 eleazar 504
 
15351 efrain 505
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
506
        $network = $currentNetworkPlugin->getNetwork();
11791 eleazar 507
 
508
 
509
        $currentUserPlugin = $this->plugin('currentUserPlugin');
510
        $currentUser = $currentUserPlugin->getUser();
511
        $currentCompany = $currentUserPlugin->getCompany();
512
 
513
        $companyMapper = CompanyMapper::getInstance($this->adapter);
514
        $company = $companyMapper->fetchOne($currentCompany->id);
515
 
516
        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
11980 eleazar 517
        $owner = $companyUserMapper->fetchOwnerByCompanyId($currentCompany->id);
11791 eleazar 518
 
519
        $acl = $this->getEvent()->getViewModel()->getVariable('acl');
11976 eleazar 520
 
521
 
11995 eleazar 522
 
11791 eleazar 523
 
11977 eleazar 524
        $feedMapper = FeedMapper::getInstance($this->adapter);
525
        $feed = $feedMapper->fetchOne($id);
11995 eleazar 526
 
527
        $params = [
528
            'id' => $feed->uuid,
529
        ];
11791 eleazar 530
 
531
        $item = [
532
            'feed_unique' => uniqid(),
533
            'feed_uuid' => $feed->uuid,
11973 eleazar 534
            'feed_description' => $feed->description,
11994 eleazar 535
            'feed_delete_url' =>  $this->url()->fromRoute('my-trainer/question/answer/delete', $params),
11791 eleazar 536
            'feed_content_type' => $feed->file_type ? $feed->file_type : '',
537
            'feed_priority'=> $feed->priority,
538
        ];
539
 
540
        $userMapper = UserMapper::getInstance($this->adapter);
541
        $user = $userMapper->fetchOne($feed->user_id);
11994 eleazar 542
        $item['feed_delete_url'] = $this->url()->fromRoute('my-trainer/question/answer/delete',  $params);
15351 efrain 543
        $item['owner_url'] =  'https://'. $network->main_hostname . '/company/view/' .$company->uuid;
11791 eleazar 544
        $item['owner_image'] = $this->url()->fromRoute('storage', ['code' => $company->uuid, 'type' => 'user', 'filename' => $company->image]);
545
        $item['owner_name'] = $company->name;
546
 
14740 efrain 547
        $item['owner_time_elapse'] = Functions::timeAgo( $feed->added_on, $now);
11791 eleazar 548
 
549
        if($feed->file_type == Feed::FILE_TYPE_IMAGE) {
550
            $item['owner_file_image'] = $this->url()->fromRoute('storage', ['code' => $feed->uuid, 'type' => 'feed', 'filename' => $feed->file_name]);
551
 
552
        }
553
        if($feed->file_type == Feed::FILE_TYPE_DOCUMENT) {
554
            $item['owner_file_document'] = $this->url()->fromRoute('storage', ['code' => $feed->uuid, 'type' => 'feed', 'filename' => $feed->file_name]);
555
        }
556
        if($feed->file_type == Feed::FILE_TYPE_VIDEO) {
557
            $item['owner_file_image_preview'] = $this->url()->fromRoute('storage', ['code' => $feed->uuid, 'type' => 'feed', 'filename' => $feed->file_image_preview]);
558
            $item['owner_file_video'] = $this->url()->fromRoute('storage', ['code' => $feed->uuid, 'type' => 'feed', 'filename' => $feed->file_name]);
559
        }
560
        if($feed->file_type == Feed::FILE_TYPE_MEETING) {
561
            $dt = \DateTime::createFromFormat('Y-m-d', $feed->date);
562
            $dt2 = \DateTime::createFromFormat('H:i:s', $feed->time);
563
            $item['owner_meeting'] =  true;
564
            $item['owner_meeting_date'] =  $dt->format('d/m/Y');
565
            $item['owner_meeting_time'] =  $dt2->format('h:i a');
566
            $item['owner_meeting_link_type'] =  $feed->link_type;
567
            $item['owner_meeting_link_name'] =  $feed->link_name;
568
 
569
        }
570
 
571
        $commentMapper = CommentMapper::getInstance($this->adapter);
572
        $records = $commentMapper->fetchAllPublishedByFeedId($feed->id);
573
 
574
 
575
        $comments = [];
576
        $comment_count=0;
577
        foreach($records as $record)
578
        {
579
            $user = $userMapper->fetchOne($record->user_id);
580
 
14740 efrain 581
 
11791 eleazar 582
            $comment = [];
583
            $comment['unique'] = uniqid();
584
            $comment_count++;
585
            $comment['comment_index']=$comment_count;
586
            $user = $userMapper->fetchOne($record->user_id);
587
            if($user->id == $owner->user_id) {
588
                $comment['user_image'] = $this->url()->fromRoute('storage', ['type' => 'company',  'code' => $company->uuid, 'filename' =>  $company->image ]);
15351 efrain 589
                $comment['user_url'] =  'https://'. $network->main_hostname . '/company/view/' . $company->uuid;
11791 eleazar 590
                $comment['user_name'] = $company->name;
591
            } else {
592
                $comment['user_image'] = $this->url()->fromRoute('storage', ['type' => 'user',  'code' => $user->uuid, 'filename' =>  $user->image ]);
15351 efrain 593
                $comment['user_url'] = 'https://'. $network->main_hostname . '/profile/view/' . $user->uuid;
11791 eleazar 594
                $comment['user_name'] = $user->first_name . ' ' . $user->last_name;
595
            }
11854 eleazar 596
            $comment['link_delete'] = $this->url()->fromRoute('my-trainer/question/answer/comments/delete',['id' => $feed->uuid, 'comment' => $record->uuid ]);
11791 eleazar 597
 
598
 
11854 eleazar 599
            $comment['link_answer_add'] = $this->url()->fromRoute('my-trainer/question/answer/comments/answer',['id' => $feed->uuid, 'comment' => $record->uuid ]);
14740 efrain 600
            $comment['time_elapsed'] = Functions::timeAgo($record->added_on, $now);
11791 eleazar 601
            $comment['comment'] = $record->comment;
602
 
603
            $records2 = $commentMapper->fetchAllPublishedByCommentId($record->id);
604
            $answers = [];
605
            $contador=0;
606
            foreach($records2 as $record2)
607
            {
608
                $user = $userMapper->fetchOne($record2->user_id);
14740 efrain 609
 
11791 eleazar 610
 
611
                $answer = [];
612
                $answer['unique'] = uniqid();
613
 
614
 
615
                $user = $userMapper->fetchOne($record2->user_id);
616
                if($user->id == $owner->user_id) {
617
                    $answer['user_image'] = $this->url()->fromRoute('storage', ['type' => 'company',  'code' => $company->uuid, 'filename' =>  $company->image ]);
15351 efrain 618
                    $answer['user_url'] =  'https://'. $network->main_hostname . '/company/view/' . $company->uuid;
11791 eleazar 619
                    $answer['user_name'] = $company->name;
620
                } else {
621
                    $answer['user_image'] = $this->url()->fromRoute('storage', ['type' => 'user',  'code' => $user->uuid, 'filename' =>  $user->image ]);
15351 efrain 622
                    $answer['user_url'] = 'https://'. $network->main_hostname . '/profile/view/' .$user->uuid;
11791 eleazar 623
                    $answer['user_name'] = $user->first_name . ' ' . $user->last_name;
624
                }
625
 
11854 eleazar 626
                    $answer['link_delete'] = $this->url()->fromRoute('my-trainer/question/answer/comments/delete',['id' => $feed->uuid, 'comment' => $record2->uuid ]);
11791 eleazar 627
 
628
 
14740 efrain 629
                $answer['time_elapsed'] = Functions::timeAgo($record2->added_on, $now);
11791 eleazar 630
                $answer['comment'] = $record2->comment;
631
 
632
                $records2 = $commentMapper->fetchAllPublishedByCommentId($record2->id);
633
 
634
                $contador++;
635
                array_push($answers, $answer);
636
            }
637
            $comment['number_answers']=$contador;
638
            $comment['answers'] = $answers;
639
            array_push($comments, $comment);
640
        }
11854 eleazar 641
        $item['comment_add_url'] = $this->url()->fromRoute('my-trainer/question/answer/comments', ['id' => $feed->uuid]);
11791 eleazar 642
            $item['comments'] = $comments;
643
 
644
 
645
 
646
        return $item;
647
    }
11809 eleazar 648
 
649
    public function commentAction()
650
    {
651
 
652
 
653
        $currentUserPlugin = $this->plugin('currentUserPlugin');
654
        $currentUser = $currentUserPlugin->getUser();
655
        $currentCompany = $currentUserPlugin->getCompany();
656
 
657
 
658
        $id = $this->params()->fromRoute('id');
659
 
660
        $request = $this->getRequest();
661
        if($request->isPost()) {
662
            $feedMapper = FeedMapper::getInstance($this->adapter);
663
            $feed = $feedMapper->fetchOneByUuid($id);
664
            if(!$feed) {
665
                $response = [
666
                    'success' => false,
667
                    'data' => 'ERROR_POST_NOT_FOUND'
668
                ];
669
                return new JsonModel($response);
670
            }
671
 
672
            if($feed->company_id != $currentCompany->id) {
673
                $response = [
674
                    'success' => false,
675
                    'data' => 'ERROR_UNAUTHORIZED'
676
                ];
677
                return new JsonModel($response);
678
            }
679
 
680
            $dataPost = $request->getPost()->toArray();
681
            $form = new CommentForm();
682
            $form->setData($dataPost);
683
 
684
            if($form->isValid()) {
685
 
686
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
687
                $owner = $companyUserMapper->fetchOwnerByCompanyId($currentCompany->id);
688
 
689
                $dataPost = (array) $form->getData();
690
                $comment = new Comment();
691
                $comment->comment = $dataPost['comment'];
692
                $comment->feed_id = $feed->id;
693
                $comment->user_id = $currentCompany->id;
694
 
695
                $commentMapper = CommentMapper::getInstance($this->adapter);
696
                if($commentMapper->insert($comment)) {
14740 efrain 697
                    $utilMapper = UtilMapper::getInstance($this->adapter);
698
                    $now = $utilMapper->getDatebaseNow();
11809 eleazar 699
 
700
                    $total_comments = $commentMapper->fetchCountCommentByFeedId($comment->feed_id);
701
 
702
                    $feed->total_comments = $total_comments;
703
                    $feedMapper->update($feed);
704
 
705
                    $response = [
706
                        'success'   => true,
14740 efrain 707
                        'data'   => $this->renderComment($comment->id, $now),
11809 eleazar 708
                        'total_comments' => $total_comments
709
                    ];
710
 
711
                    return new JsonModel($response);
712
 
713
                } else {
714
 
715
                    $response = [
716
                        'success'   => false,
717
                        'data'   => $commentMapper->getError()
718
                    ];
719
 
720
                    return new JsonModel($response);
721
                }
722
 
723
            } else {
724
                $message = '';;
725
                $form_messages = (array) $form->getMessages();
726
                foreach($form_messages  as $fieldname => $field_messages)
727
                {
728
                    foreach( $field_messages as $key => $value)
729
                    {
730
                        $message = $value;
731
                    }
732
                }
733
 
734
                $response = [
735
                    'success'   => false,
736
                    'data'   => $message
737
                ];
738
 
739
                return new JsonModel($response);
740
            }
741
 
742
 
743
        } else {
744
            $response = [
745
                'success' => false,
746
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
747
            ];
748
 
749
            return new JsonModel($response);
750
        }
751
 
752
 
753
    }
11317 eleazar 754
 
11837 eleazar 755
    public function answerAction()
11809 eleazar 756
    {
11317 eleazar 757
 
11809 eleazar 758
 
759
        $currentUserPlugin = $this->plugin('currentUserPlugin');
760
        $currentUser = $currentUserPlugin->getUser();
761
        $currentCompany = $currentUserPlugin->getCompany();
762
 
763
 
764
        $id = $this->params()->fromRoute('id');
765
        $comment_uuid = $this->params()->fromRoute('comment');
766
 
767
        $request = $this->getRequest();
768
        if($request->isPost()) {
769
            $feedMapper = FeedMapper::getInstance($this->adapter);
770
            $feed = $feedMapper->fetchOneByUuid($id);
771
            if(!$feed) {
772
                $response = [
773
                    'success' => false,
774
                    'data' => 'ERROR_POST_NOT_FOUND'
775
                ];
776
                return new JsonModel($response);
777
            }
778
 
779
            if($feed->company_id != $currentCompany->id) {
780
                $response = [
781
                    'success' => false,
782
                    'data' => 'ERROR_UNAUTHORIZED'
783
                ];
784
                return new JsonModel($response);
785
            }
786
 
787
            $dataPost = $request->getPost()->toArray();
788
            $form = new CommentAnswerForm();
789
            $form->setData($dataPost);
790
 
791
            if($form->isValid()) {
792
 
793
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
794
                $owner = $companyUserMapper->fetchOwnerByCompanyId($currentCompany->id);
795
 
796
                $dataPost = (array) $form->getData();
797
                $answer = new Comment();
798
                $answer->comment = $dataPost['answer'];
799
                $answer->feed_id = $feed->id;
800
 
801
                $answer->user_id = $owner->user_id;
802
 
803
                $commentMapper = CommentMapper::getInstance($this->adapter);
804
                $comment=$commentMapper->fetchOneByUuid($comment_uuid);
805
                $answer->parent_id = $comment->id;
806
 
807
                if($commentMapper->insert($answer)) {
14740 efrain 808
                    $utilMapper = UtilMapper::getInstance($this->adapter);
809
                    $now = $utilMapper->getDatebaseNow();
11809 eleazar 810
 
811
                    $total_comments = $commentMapper->fetchCountCommentByFeedId($comment->feed_id);
812
 
813
                    $feed->total_comments = $total_comments;
814
                    $feedMapper->update($feed);
815
 
816
                    $response = [
817
                        'success'   => true,
14740 efrain 818
                        'data'   => $this->renderComment($answer->id, $now),
11809 eleazar 819
                        'total_comments' => $total_comments
820
                    ];
821
 
822
                    return new JsonModel($response);
823
 
824
                } else {
825
 
826
                    $response = [
827
                        'success'   => false,
828
                        'data'   => $commentMapper->getError()
829
                    ];
830
 
831
                    return new JsonModel($response);
832
                }
833
 
834
            } else {
835
                $message = '';;
836
                $form_messages = (array) $form->getMessages();
837
                foreach($form_messages  as $fieldname => $field_messages)
838
                {
839
                    foreach( $field_messages as $key => $value)
840
                    {
841
                        $message = $value;
842
                    }
843
                }
844
 
845
                $response = [
846
                    'success'   => false,
847
                    'data'   => $message
848
                ];
849
 
850
                return new JsonModel($response);
851
            }
852
 
853
 
854
        } else {
855
            $response = [
856
                'success' => false,
857
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
858
            ];
859
 
860
            return new JsonModel($response);
861
        }
862
 
863
 
864
    }
865
 
866
    public function commentDeleteAction()
867
    {
868
        $currentUserPlugin = $this->plugin('currentUserPlugin');
869
        $currentUser = $currentUserPlugin->getUser();
870
        $currentCompany = $currentUserPlugin->getCompany();
871
 
872
        $request = $this->getRequest();
873
        if($request->isPost()) {
874
            $currentUserPlugin = $this->plugin('currentUserPlugin');
875
            $currentUser = $currentUserPlugin->getUser();
876
 
877
            $id = $this->params()->fromRoute('id');
878
            $comment = $this->params()->fromRoute('comment');
879
 
880
            $feedMapper = FeedMapper::getInstance($this->adapter);
881
            $feed = $feedMapper->fetchOneByUuid($id);
882
            if(!$feed) {
883
                $response = [
884
                    'success' => false,
885
                    'data' => 'ERROR_POST_NOT_FOUND'
886
                ];
887
                return new JsonModel($response);
888
            }
889
 
890
            if($feed->company_id != $currentCompany->id) {
891
                $response = [
892
                    'success' => false,
893
                    'data' => 'ERROR_UNAUTHORIZED'
894
                ];
895
                return new JsonModel($response);
896
            }
897
 
898
            $commentMapper = CommentMapper::getInstance($this->adapter);
899
            $comment = $commentMapper->fetchOneByUuid($comment);
900
 
901
            if($comment && $comment->feed_id == $feed->id) {
902
                $comment->status = Comment::STATUS_DELETED;
903
                if($commentMapper->update($comment)) {
904
                    $total_comments = $commentMapper->fetchCountCommentByFeedId($comment->feed_id);
905
 
906
                    $feed = $feedMapper->fetchOne($comment->feed_id);
907
                    $feed->total_comments = $total_comments;
908
                    $feedMapper->update($feed);
909
 
910
 
911
 
912
 
913
 
914
                    $response = [
915
                        'success' => true,
916
                        'data' => [
917
                            'message' => 'LABEL_COMMENT_WAS_DELETED',
918
                            'total_comments' => $total_comments
919
                        ]
920
                   ];
921
                } else {
922
                    $response = [
923
                        'success' => false,
924
                        'data' => $commentMapper->getError()
925
                    ];
926
                }
927
 
928
            } else {
929
                $response = [
930
                    'success' => false,
931
                    'data' => 'ERROR_COMMENT_NOT_FOUND'
932
                ];
933
            }
934
 
935
        } else {
936
            $response = [
937
                'success' => false,
938
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
939
            ];
940
        }
941
 
942
        return new JsonModel($response);
943
    }
944
 
14740 efrain 945
    private function renderComment($comment_id, $now)
11809 eleazar 946
    {
947
        $currentUserPlugin = $this->plugin('currentUserPlugin');
948
        $currentUser = $currentUserPlugin->getUser();
949
        $currentCompany = $currentUserPlugin->getCompany();
950
 
951
        $companyMapper = CompanyMapper::getInstance($this->adapter);
952
        $company = $companyMapper->fetchOne($currentCompany->id);
953
 
954
        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
955
        $owner = $companyUserMapper->fetchOwnerByCompanyId($currentCompany->id);
956
 
957
 
15351 efrain 958
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
959
        $network = $currentNetworkPlugin->getNetwork();
11809 eleazar 960
 
961
        $item = [];
962
 
963
        $commentMapper = CommentMapper::getInstance($this->adapter);
964
        $record = $commentMapper->fetchOne($comment_id);
965
 
966
        $feedMapper = FeedMapper::getInstance($this->adapter);
967
        $feed = $feedMapper->fetchOne($record->feed_id);
968
 
969
        if($record) {
970
            $userMapper = UserMapper::getInstance($this->adapter);
971
 
14740 efrain 972
 
11809 eleazar 973
 
974
 
975
            $item = [];
976
            $item['unique'] = uniqid();
977
 
978
 
979
            $user = $userMapper->fetchOne($record->user_id);
980
            if($user->id == $owner->user_id) {
981
                $item['user_image'] = $this->url()->fromRoute('storage', ['type' => 'company',  'code' => $company->uuid, 'filename' =>  $company->image ]);
15351 efrain 982
                $item['user_url'] =  'https://'. $network->main_hostname . '/company/view/' . $company->uuid;
11809 eleazar 983
                $item['user_name'] = $company->name;
984
            } else {
985
                $item['user_image'] = $this->url()->fromRoute('storage', ['type' => 'user',  'code' => $user->uuid, 'filename' =>  $user->image ]);
15351 efrain 986
                $item['user_url'] = 'https://'. $network->main_hostname . '/profile/view/' . $user->uuid;
11809 eleazar 987
                $item['user_name'] = $user->first_name . ' ' . $user->last_name;
988
            }
989
 
990
 
991
 
11854 eleazar 992
            $item['link_answer_add'] = $this->url()->fromRoute('my-trainer/question/answer/comments/answer',['id' => $feed->uuid, 'comment' => $record->uuid ]);
993
            $item['link_delete'] = $this->url()->fromRoute('my-trainer/question/answer/comments/delete',['id' => $feed->uuid, 'comment' => $record->uuid ]);
14740 efrain 994
            $item['time_elapsed'] = Functions::timeAgo($record->added_on, $now);
11809 eleazar 995
            $item['comment'] = $record->comment;
996
 
997
        }
998
        return $item;
999
    }
11990 eleazar 1000
 
1001
    public function deleteAction()
1002
    {
1003
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1004
        $currentUser = $currentUserPlugin->getUser();
1005
        $currentCompany = $currentUserPlugin->getCompany();
1006
 
1007
        $request = $this->getRequest();
1008
        if($request->isPost()) {
1009
 
1010
 
1011
            $id =  $this->params()->fromRoute('id');
1012
 
1013
            $feedMapper = FeedMapper::getInstance($this->adapter);
1014
            $feed = $feedMapper->fetchOneByUuid($id);
1015
            if(!$feed) {
1016
                $response = [
1017
                    'success' => false,
1018
                    'data' => 'ERROR_POST_NOT_FOUND'
1019
                ];
1020
                return new JsonModel($response);
1021
            }
1022
 
1023
            if($feed->company_id != $currentCompany->id) {
1024
                $response = [
1025
                    'success' => false,
1026
                    'data' => 'ERROR_UNAUTHORIZED'
1027
                ];
1028
                return new JsonModel($response);
1029
            }
1030
 
1031
            $feedMapper = FeedMapper::getInstance($this->adapter);
1032
            $feed->status = Feed::STATUS_DELETED;
1033
            if($feedMapper->update($feed)) {
1034
                $response = [
1035
                    'success' => true,
1036
                    'data' => 'LABEL_FEED_WAS_DELETED'
1037
                ];
1038
 
1039
            } else {
1040
                $response = [
1041
                    'success' => false,
1042
                    'data' => $feedMapper->getError()
1043
                ];
1044
            }
1045
 
1046
 
1047
            return new JsonModel($response);
1048
 
1049
        } else {
1050
            $response = [
1051
                'success' => false,
1052
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1053
            ];
1054
        }
1055
 
1056
        return new JsonModel($response);
1057
    }
11809 eleazar 1058
 
11317 eleazar 1059
}