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