Proyectos de Subversion LeadersLinked - Backend

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
13675 nelberth 1
<?php
2
/**
3
 *
4
 * Controlador: Mis Perfiles
5
 *
6
 */
7
declare(strict_types=1);
8
 
9
namespace LeadersLinked\Controller;
10
 
11
use Laminas\Db\Adapter\AdapterInterface;
16768 efrain 12
 
13675 nelberth 13
use Laminas\Mvc\Controller\AbstractActionController;
14
use Laminas\Log\LoggerInterface;
15
use Laminas\View\Model\ViewModel;
16
 
17
use LeadersLinked\Library\Functions;
18
use LeadersLinked\Mapper\UserMapper;
19
 
20
use LeadersLinked\Model\User;
21
 
22
use LeadersLinked\Mapper\UserBlockedMapper;
23
 
24
use LeadersLinked\Mapper\CompanyMapper;
25
use LeadersLinked\Mapper\CompanyUserMapper;
26
use LeadersLinked\Mapper\ConversationMapper;
27
use LeadersLinked\Mapper\MessageMapper;
28
use LeadersLinked\Model\Conversation;
29
use LeadersLinked\Model\UserType;
30
use LeadersLinked\Library\Image;
31
use Laminas\View\Model\JsonModel;
13723 nelberth 32
use LeadersLinked\Form\CommunicationInMailSendAllForm;
13675 nelberth 33
use LeadersLinked\Model\Message;
34
use LeadersLinked\Model\VideoConvert;
35
use LeadersLinked\Mapper\VideoConvertMapper;
36
 
37
 
38
 
39
class CommunicationInboxController extends AbstractActionController
40
{
41
    /**
42
     *
16769 efrain 43
     * @var \Laminas\Db\Adapter\AdapterInterface
13675 nelberth 44
     */
45
    private $adapter;
46
 
47
    /**
48
     *
16769 efrain 49
     * @var \LeadersLinked\Cache\CacheInterface
13675 nelberth 50
     */
16769 efrain 51
    private $cache;
52
 
53
 
54
    /**
55
     *
56
     * @var \Laminas\Log\LoggerInterface
57
     */
13675 nelberth 58
    private $logger;
59
 
60
    /**
61
     *
62
     * @var array
63
     */
64
    private $config;
65
 
16769 efrain 66
 
13675 nelberth 67
    /**
68
     *
16769 efrain 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
13675 nelberth 79
     * @param array $config
16769 efrain 80
     * @param \Laminas\Mvc\I18n\Translator $translator
13675 nelberth 81
     */
16769 efrain 82
    public function __construct($adapter, $cache, $logger, $config, $translator)
13675 nelberth 83
    {
16769 efrain 84
        $this->adapter      = $adapter;
85
        $this->cache        = $cache;
86
        $this->logger       = $logger;
87
        $this->config       = $config;
88
        $this->translator   = $translator;
13675 nelberth 89
    }
90
 
91
    /**
92
     *
93
     * Generación del listado de conversationes
94
     *
95
     * [
96
     *  success: true,
97
     *  data:[
98
     *    [
99
     *       uuid: uuid con quien se tiene la conversación,
100
     *       name: nombre de con quien se tiene la conversacion,
101
     *       image: imagen de con quien se tiene la conversación,
102
     *       profile: url del profile con quien se tiene la conversación,
103
     *       last_message: fecha del ultimo mensaje,
104
     *       count_unread: cantidad de mensajes sin leer,
105
     *       messages_link: url para recuperar los mensajes,
106
     *       send_link: url para enviar el mensaje,
107
     *       selected: 0 = no seleccionado, 1 = seleccionado
108
     *     ]
109
     *  ]
110
     *
111
     *
112
     * @return \Laminas\View\Model\JsonModel
113
     */
114
    public function indexAction()
115
    {
116
        $request = $this->getRequest();
117
        if($request->isGet()) {
118
 
13723 nelberth 119
            $formSendAll = new CommunicationInMailSendAllForm();
13675 nelberth 120
            $this->layout()->setTemplate('layout/layout-backend');
121
            $viewModel = new ViewModel();
13677 nelberth 122
            $viewModel->setTemplate('leaders-linked/communication-inbox/index.phtml');
13675 nelberth 123
            $viewModel->setVariables([
13723 nelberth 124
                'formSendAll' => $formSendAll,
13675 nelberth 125
            ]);
126
            return $viewModel ;
127
 
128
        } else {
129
            return new JsonModel([
130
                'success' => false,
131
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
132
            ]);
133
        }
134
    }
135
 
136
 
137
 
138
 
139
 
140
    /**
141
     * Esta función remueve el usuario del grupo
142
     * Es una petición GET el url recuperado en /inmail
143
     * [ruta del servidor]/inmail/[uuid]/message
144
     * retorna un json en caso de ser  positivo
145
     * [
146
     *   success: true,
147
     *      data: [
148
     *          [
149
     *              sender_name: nombre de quien que envia el mensaje,
150
     *              sender_image: imagen de quien que recibe el mensaje,
151
     *              sender_profile: url de profile de quien que envia el mensaje,
152
     *              receiver_name: nombre de quien que recibe el mensaje,
153
     *              receiver_image: url de la imagen de quien  que recibe el mensaje,
154
     *              receiver_profile: url del profile de quien recibe el mensaje,
155
     *              side: left/righ de que lado de la pantalla se mostrara,
156
     *              message: texto del mensaje,
157
     *              type: text|image|video|document,
158
     *              filename: url del archivo enviado,
159
     *              date: cadena que describe hace cuanto se recibio el mensaje
160
     *          ]
161
     *      ]
162
     *   ]
163
     * En caso de ser negativo puede haber 2 formatos
164
     * [
165
     *  'success' : false,
166
     *  'data' : mensaje de error
167
     * ]
168
     * @return \Laminas\View\Model\JsonModel
169
     */
170
 
171
 
172
    /**
173
     * Esta función envia un mensaje
174
     * Es una petición POST el url recuperado en /inmail
175
     * [ruta del servidor]/inmail/[uidd del usuario]/message/send
176
     * Lo párametros son
177
     * message: text plain requerido
178
     * file: no requerido puede jpg, png, jpeg, mp3, mp4, webm o pdf
179
     * o
180
     * [ruta del servidor]/inmail/[uidd del usuario]/message/send/encoding/base64 para el caso de react-native
181
     * Los párametros son
182
     * message: text plain requerido
183
     * fileBase64Name: nombre del archivo  que se envia en base64 solo requerido si se envia un archivo
184
     * fileBase64Content: contenido en base 64 del archivo
185
     *
186
     * retorna un json en caso de ser  positivo
187
     * [
188
     *   success: true,
189
     *      data:{
190
     *          sender_name: nombre de quien que envia el mensaje,
191
     *          sender_image: imagen de quien que recibe el mensaje,
192
     *          sender_profile: url de profile de quien que envia el mensaje,
193
     *          receiver_name: nombre de quien que recibe el mensaje,
194
     *          receiver_image: url de la imagen de quien  que recibe el mensaje,
195
     *          receiver_profile: url del profile de quien recibe el mensaje,
196
     *          side: left/righ de que lado de la pantalla se mostrara,
197
     *          message: texto del mensaje,
198
     *          type: text|image|video|document,
199
     *          filename: url del archivo enviado,
200
     *          date: cadena que describe hace cuanto se recibio el mensaje
201
     *      ]
202
     *   ]
203
     * En caso de ser negativo puede haber 2 formatos
204
     * [
205
     *  'success' : false,
206
     *  'data' : mensaje de error
207
     * ]
208
     * @return \Laminas\View\Model\JsonModel
209
     */
210
 
211
 
13735 nelberth 212
    public function sendAllAction()
213
    {
13738 nelberth 214
 
13735 nelberth 215
        $request = $this->getRequest();
14119 nelberth 216
 
13735 nelberth 217
        if($request->isPost()) {
218
 
13980 nelberth 219
 
13735 nelberth 220
            $currentUserPlugin = $this->plugin('currentUserPlugin');
221
            $currentUser = $currentUserPlugin->getUser();
13746 nelberth 222
            $currentCompany = $currentUserPlugin->getCompany();
13735 nelberth 223
 
224
            $data = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
225
 
226
            $form = new CommunicationInMailSendAllForm();
227
            $form->setData($data);
13740 nelberth 228
 
13735 nelberth 229
            if($form->isValid()) {
14119 nelberth 230
                return new JsonModel([
231
                    'success'  => false,
14123 nelberth 232
                    'data' => $data
14119 nelberth 233
                ]);
14109 nelberth 234
                $sendTypeFilter=$form->get('type_send_filter')->getValue();
13746 nelberth 235
                $users=[];
14109 nelberth 236
                if($sendTypeFilter=='company_all'){
13746 nelberth 237
                    $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
238
                    $userMapper = UserMapper::getInstance($this->adapter);
13752 nelberth 239
                    $datosCompanyUser = $companyUserMapper->fetchAllByCompanyIdAndNotUserId($currentCompany->id, $currentUser->id);
13746 nelberth 240
                    foreach($datosCompanyUser as $record){
241
                        $datosUser = $userMapper->fetchOne($record->user_id);
242
                        array_push($users,  $datosUser);
243
                    }
14109 nelberth 244
                }else if($sendTypeFilter=='studens_all'){
13753 nelberth 245
                    $userMapper = UserMapper::getInstance($this->adapter);
246
                    $datosCompanyUser = $userMapper->fetchAllStudensByCompanyId($currentCompany->id);
247
                    foreach($datosCompanyUser as $record){
248
                        $datosUser = $userMapper->fetchOne($record->id);
249
                        array_push($users,  $datosUser);
250
                    }
13735 nelberth 251
                }else{
252
                    return new JsonModel([
253
                        'success'  => false,
254
                        'data' => 'te falta amor, hermano'
255
                    ]);
256
                }
14110 nelberth 257
                $files = $this->getRequest()->getFiles()->toArray();
13747 nelberth 258
                foreach($users as $user){
13735 nelberth 259
 
260
 
13747 nelberth 261
                    $conversationMapper = ConversationMapper::getInstance($this->adapter);
262
                    $conversation = $conversationMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
13735 nelberth 263
 
13747 nelberth 264
                    if($conversation) {
265
                        $conversation->receiver_status = Conversation::STATUS_NORMAL;
266
                        $conversation->sender_status = Conversation::STATUS_NORMAL;
267
                        if(!$conversationMapper->update($conversation)) {
268
                            return new JsonModel([
269
                                'success'  => false,
270
                                'data' => $conversationMapper->getError()
271
                            ]);
272
                        }
273
                    } else {
274
                        $conversation = new Conversation();
275
                        $conversation->sender_id = $currentUser->id;
276
                        $conversation->sender_status = Conversation::STATUS_NORMAL;
277
                        $conversation->receiver_id = $user->id;
278
                        $conversation->receiver_status = Conversation::STATUS_NORMAL;
13735 nelberth 279
 
13747 nelberth 280
                        if(!$conversationMapper->insert($conversation)) {
281
                            return new JsonModel([
282
                                'success'  => false,
283
                                'data' => $conversationMapper->getError()
284
                            ]);
285
                        }
286
 
287
                    }
14110 nelberth 288
 
13747 nelberth 289
                    $type = Message::TYPE_TEXT;
13735 nelberth 290
 
13747 nelberth 291
                    $encoding = $this->params()->fromRoute('encoding');
292
                    if($encoding == 'base64') {
13735 nelberth 293
 
13747 nelberth 294
 
295
                        $fileBase64Name = $this->params()->fromPost('file_base64_name');
296
                        $fileBase64Content = $this->params()->fromPost('file_base64_content');
297
 
298
 
299
                        if($fileBase64Name && $fileBase64Content) {
13735 nelberth 300
 
13747 nelberth 301
                            try {
302
 
303
                                $fileBase64Content = base64_decode($fileBase64Content);
304
                                if($fileBase64Content) {
13735 nelberth 305
 
13747 nelberth 306
                                    $message_filename      = $this->normalizeString($fileBase64Name);
307
                                    $message_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp';
308
                                    if(!file_exists($message_tmp_filename)) {
309
                                        mkdir($message_tmp_filename, 0755, true);
310
                                    }
13735 nelberth 311
 
13747 nelberth 312
                                    $message_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $message_filename;
313
                                    file_put_contents($message_tmp_filename, $fileBase64Content);
314
 
315
 
316
 
317
                                    $mime_type = mime_content_type($message_tmp_filename);
318
                                    //echo '$mime_type = '. $mime_type; exit;
319
 
320
 
321
                                    if($mime_type == 'image/jpg' || $mime_type == 'image/jpeg' || $mime_type == 'image/png') {
322
                                        $type = Message::TYPE_IMAGE;
323
                                    } else if($mime_type == 'video/webm' || $mime_type == 'video/mpeg' || $mime_type == 'video/mpg' || $mime_type == 'video/mp4') {
324
                                        $type = Message::FILE_TYPE_VIDEO;
325
                                    } else if($mime_type == 'application/pdf') {
326
                                        $type = Message::FILE_TYPE_DOCUMENT;
327
                                    }
328
 
13735 nelberth 329
                                }
13747 nelberth 330
                            } catch(\Exception $e) {
13735 nelberth 331
 
332
                            }
13747 nelberth 333
                        }
334
 
335
                    } else {
336
 
337
                        if(isset($files['file']) && empty($files['file']['error'])) {
338
                            $message_tmp_filename  = $files['file']['tmp_name'];
339
                            $message_filename      = $this->normalizeString($files['file']['name']);
13735 nelberth 340
 
13747 nelberth 341
                            $mime_type = mime_content_type($message_tmp_filename);
342
 
343
 
344
                            if($mime_type == 'image/jpg' || $mime_type == 'image/jpeg' || $mime_type == 'image/png') {
345
                                $type = Message::TYPE_IMAGE;
346
                            } else if($mime_type == 'video/webm' || $mime_type == 'video/mpeg' || $mime_type == 'video/mpg' || $mime_type == 'video/mp4') {
347
                                $type = Message::TYPE_VIDEO;
348
                            } else if($mime_type == 'application/pdf') {
349
                                $type = Message::TYPE_DOCUMENT;
350
                            }
13735 nelberth 351
                        }
352
                    }
353
 
354
 
13747 nelberth 355
 
356
                    $message = new Message();
357
                    $message->conversation_id = $conversation->id;
358
                    $message->read = Message::NO;
359
                    $message->message = $form->get('message')->getValue();
360
                    $message->receiver_id = $user->id;
361
                    $message->receiver_status = Message::STATUS_NORMAL;
362
                    $message->sender_id = $currentUser->id;
363
                    $message->sender_status = Message::STATUS_NORMAL;
364
                    $message->type = $type;
365
 
366
 
367
 
368
                    $messageMapper = MessageMapper::getInstance($this->adapter);
369
                    if($messageMapper->insert($message)) {
13735 nelberth 370
 
13747 nelberth 371
                        $message = $messageMapper->fetchOne($message->id);
13735 nelberth 372
 
373
 
13747 nelberth 374
                        if( $type == Message::TYPE_DOCUMENT) {
375
                            try {
376
                                $target_path = $this->config['leaderslinked.fullpath.message'] . $message->uuid;
377
                                if(!file_exists($target_path)) {
378
                                    mkdir($target_path, 0755);
379
                                }
13735 nelberth 380
 
13747 nelberth 381
                                $full_filename = $target_path  . DIRECTORY_SEPARATOR .$message_filename;
382
 
383
                                if($encoding == 'base64') {
384
                                    $resultMoveOrRename = rename($message_tmp_filename , $full_filename);
385
                                } else {
386
                                    $resultMoveOrRename = move_uploaded_file($message_tmp_filename , $full_filename);
387
                                }
388
 
389
                                if($resultMoveOrRename) {
390
 
391
                                    $message->type = $type;
392
                                    $message->filename = basename($message_filename);
393
                                    $messageMapper->update($message);
394
                                } else {
395
                                    error_log('no se pudo mover o renombrar el documento : ' . $message_tmp_filename . ' al directorio : ' . $full_filename );
396
                                }
397
                            } catch(\Throwable $e) {
398
                                error_log($e->getTraceAsString());
13735 nelberth 399
                            }
400
                        }
13747 nelberth 401
                        if( $type == Message::TYPE_IMAGE) {
402
                            try {
403
                                $target_path = $this->config['leaderslinked.fullpath.message'] . $message->uuid;
404
                                if(!file_exists($target_path)) {
405
                                    mkdir($target_path, 0755);
406
                                }
407
 
408
                                list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.message_image_size']);
409
 
410
                                $message_filename = substr($message_filename, 0, strrpos($message_filename, '.'))  . '.png';
411
                                $crop_to_dimensions = false;
412
                                if(Image::uploadImage($message_tmp_filename, $target_path, $message_filename, $target_width, $target_height, $crop_to_dimensions )) {
413
                                    $message->type = $type;
414
                                    $message->filename = basename($message_filename);
415
                                    $messageMapper->update($message);
416
                                }
417
                            } catch(\Throwable $e) {
418
                                error_log($e->getTraceAsString());
13735 nelberth 419
                            }
420
                        }
13747 nelberth 421
                        if( $type == Message::TYPE_VIDEO) {
422
                            try {
423
                                $target_path = $this->config['leaderslinked.fullpath.message'] . $message->uuid;
424
                                if(!file_exists($target_path)) {
425
                                    mkdir($target_path, 0755);
426
                                }
13735 nelberth 427
 
13747 nelberth 428
                                $full_filename = $target_path  . DIRECTORY_SEPARATOR . $message_filename;
13735 nelberth 429
 
13747 nelberth 430
                                if($encoding == 'base64') {
431
                                    $resultMoveOrRename = rename($message_tmp_filename , $full_filename);
432
                                } else {
433
                                    $resultMoveOrRename = move_uploaded_file($message_tmp_filename , $full_filename);
434
                                }
13735 nelberth 435
 
13747 nelberth 436
                                if($resultMoveOrRename) {
437
 
438
                                    $size = $this->config['leaderslinked.image_sizes.message_image_size'];
439
                                    $getFromSecound = 2;
440
 
441
                                    //extracción del cover
442
                                    $generateFileName = substr($message_filename, 0, strrpos($message_filename, '.'));
443
                                    $generateFile =  $target_path  . DIRECTORY_SEPARATOR . $generateFileName .  '.png';
444
                                    $cmd            = "/usr/bin/ffmpeg -i $full_filename -an -ss $getFromSecound -s $size $generateFile";
445
                                    exec($cmd);
446
 
447
 
448
                                    $message->type = $type;
449
                                    $message->filename = basename($message_filename);
450
                                    $message->image_preview = basename($generateFile);
451
                                    $messageMapper->update($message);
452
 
453
                                    $videoConvert = new VideoConvert();
454
                                    $videoConvert->filename = $full_filename;
455
                                    $videoConvert->type = VideoConvert::TYPE_FEED;
456
 
457
                                    $videoConvertMapper = VideoConvertMapper::getInstance($this->adapter);
458
                                    $videoConvertMapper->insert($videoConvert);
459
                                } else {
460
                                    error_log('no se pudo mover o renombrar el documento : ' . $message_tmp_filename . ' al directorio : ' . $full_filename );
461
                                }
462
                            } catch(\Throwable $e) {
463
                                error_log($e->getTraceAsString());
13735 nelberth 464
                            }
13747 nelberth 465
                        }
466
 
13735 nelberth 467
 
468
                    } else {
13747 nelberth 469
                        return new JsonModel([
470
                            'success'   => false,
471
                            'data'   => $messageMapper->getError()
472
                        ]);
13735 nelberth 473
                    }
13747 nelberth 474
                }
475
 
476
 
477
                $message = $messageMapper->fetchOne($message->id);
478
 
479
                if($message->filename) {
13735 nelberth 480
 
13747 nelberth 481
 
482
                    $filename = $this->url()->fromRoute('storage', ['type' => 'message', 'filename' => $message->filename, 'code' => $message->uuid]);
13735 nelberth 483
 
484
                } else {
13747 nelberth 485
                    $filename = '';
13735 nelberth 486
                }
487
 
13747 nelberth 488
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $message->added_on);
489
 
13735 nelberth 490
 
13747 nelberth 491
                return new JsonModel([
492
                    'success'   => true,
13980 nelberth 493
                    'data'   => 'Mensajes enviados con exito'
13747 nelberth 494
                ]);
13735 nelberth 495
 
496
 
497
            } else {
498
 
499
 
500
                $messages = [];
501
                $form_messages = (array) $form->getMessages();
502
                foreach($form_messages  as $fieldname => $field_messages)
503
                {
504
                    $messages[$fieldname] = array_values($field_messages);
505
                }
506
 
507
                return new JsonModel([
508
                    'success'   => false,
509
                    'data'   => $messages
510
                ]);
511
            }
512
 
513
 
514
 
515
        } else {
516
            return new JsonModel([
517
                'success' => false,
518
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
519
            ]);
520
        }
521
 
522
    }
13675 nelberth 523
 
524
    private function normalizeString ($str = '')
525
    {
526
        $basename  = substr($str, 0, strrpos($str, '.'));
527
        $basename  = str_replace('.', '-', $basename);
528
 
529
        $extension  = substr($str, strrpos($str, '.'));
530
 
531
        $str = $basename . $extension;
532
 
533
        $str = strip_tags($str);
534
        $str = preg_replace('/[\r\n\t ]+/', ' ', $str);
535
        $str = preg_replace('/[\"\*\/\:\<\>\?\'\|\,]+/', ' ', $str);
536
        $str = strtolower($str);
537
        $str = html_entity_decode( $str, ENT_QUOTES, "utf-8" );
538
        $str = htmlentities($str, ENT_QUOTES, "utf-8");
539
        $str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
540
        $str = str_replace(' ', '-', $str);
541
        $str = rawurlencode($str);
542
        $str = str_replace('%', '-', $str);
543
        return trim(strtolower($str));
544
    }
545
 
546
}