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