Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

Rev Autor Línea Nro. Línea
1 www 1
<?php
5595 stevensc 2
 
1 www 3
declare(strict_types=1);
4
 
5
namespace LeadersLinked\Controller;
6
 
7
use Laminas\Db\Adapter\AdapterInterface;
6849 efrain 8
 
1 www 9
use Laminas\Mvc\Controller\AbstractActionController;
10
use Laminas\Log\LoggerInterface;
11
use Laminas\View\Model\ViewModel;
12
 
13
use LeadersLinked\Library\Functions;
14
use LeadersLinked\Mapper\UserMapper;
15
 
16
use LeadersLinked\Model\User;
17
 
18
use LeadersLinked\Mapper\UserBlockedMapper;
19
 
20
use LeadersLinked\Mapper\CompanyMapper;
21
use LeadersLinked\Mapper\CompanyUserMapper;
22
use LeadersLinked\Mapper\ConversationMapper;
23
use LeadersLinked\Mapper\MessageMapper;
24
use LeadersLinked\Model\Conversation;
25
use LeadersLinked\Library\Image;
26
use Laminas\View\Model\JsonModel;
27
use LeadersLinked\Form\InMail\SendForm;
28
use LeadersLinked\Model\Message;
29
use LeadersLinked\Model\VideoConvert;
30
use LeadersLinked\Mapper\VideoConvertMapper;
6749 efrain 31
use Laminas\Mvc\I18n\Translator;
1 www 32
 
33
class InMailController extends AbstractActionController
34
{
35
    /**
36
     *
37
     * @var AdapterInterface
38
     */
39
    private $adapter;
6849 efrain 40
 
6749 efrain 41
 
1 www 42
    /**
43
     *
44
     * @var  LoggerInterface
45
     */
46
    private $logger;
6749 efrain 47
 
48
 
1 www 49
    /**
50
     *
51
     * @var array
52
     */
53
    private $config;
6749 efrain 54
 
1 www 55
    /**
56
     *
6749 efrain 57
     * @var Translator
58
     */
59
    private $translator;
60
 
61
    /**
62
     *
1 www 63
     * @param AdapterInterface $adapter
64
     * @param LoggerInterface $logger
6749 efrain 65
     * @param Translator $translator
1 www 66
     * @param array $config
67
     */
6849 efrain 68
    public function __construct($adapter, $logger,  $config, $translator)
1 www 69
    {
70
        $this->adapter      = $adapter;
71
        $this->logger       = $logger;
72
        $this->config       = $config;
6749 efrain 73
        $this->translator = $translator;
5595 stevensc 74
    }
1 www 75
 
76
    /**
77
     *
78
     * Generación del listado de conversationes
79
     *
80
     * [
81
     *  success: true,
82
     *  data:[
83
     *    [
84
     *       uuid: uuid con quien se tiene la conversación,
85
     *       name: nombre de con quien se tiene la conversacion,
86
     *       image: imagen de con quien se tiene la conversación,
87
     *       profile: url del profile con quien se tiene la conversación,
88
     *       last_message: fecha del ultimo mensaje,
89
     *       count_unread: cantidad de mensajes sin leer,
90
     *       messages_link: url para recuperar los mensajes,
91
     *       send_link: url para enviar el mensaje,
92
     *       selected: 0 = no seleccionado, 1 = seleccionado
93
     *     ]
94
     *  ]
95
     *
96
     *
97
     * @return \Laminas\View\Model\JsonModel
98
     */
99
    public function indexAction()
100
    {
101
        $request = $this->getRequest();
5595 stevensc 102
        if ($request->isGet()) {
1 www 103
            $currentUserPlugin = $this->plugin('currentUserPlugin');
104
            $currentUser = $currentUserPlugin->getUser();
5595 stevensc 105
 
1 www 106
            $id = $this->params()->fromRoute('id');
5595 stevensc 107
 
1 www 108
            $headers  = $request->getHeaders();
5595 stevensc 109
 
1 www 110
            $isJson = false;
5595 stevensc 111
            if ($headers->has('Accept')) {
1 www 112
                $accept = $headers->get('Accept');
5595 stevensc 113
 
1 www 114
                $prioritized = $accept->getPrioritized();
5595 stevensc 115
 
116
                foreach ($prioritized as $key => $value) {
1 www 117
                    $raw = trim($value->getRaw());
5595 stevensc 118
 
119
                    if (!$isJson) {
1 www 120
                        $isJson = strpos($raw, 'json');
121
                    }
122
                }
123
            }
124
 
5595 stevensc 125
            if ($isJson) {
1 www 126
                $currentUserPlugin = $this->plugin('currentUserPlugin');
127
                $currentUser = $currentUserPlugin->getUser();
5595 stevensc 128
 
1 www 129
                $userMapper = UserMapper::getInstance($this->adapter);
6388 efrain 130
                $now = $userMapper->getDatebaseNow();
131
 
1 www 132
                $conversationMapper = ConversationMapper::getInstance($this->adapter);
133
                $messageMapper = MessageMapper::getInstance($this->adapter);
134
                $conversations = [];
5595 stevensc 135
 
1 www 136
                $selected_user_id = 0;
5595 stevensc 137
 
1 www 138
                $id = $this->params()->fromRoute('id');
5595 stevensc 139
                if ($id) {
140
 
1 www 141
                    $companyMapper = CompanyMapper::getInstance($this->adapter);
142
                    $company = $companyMapper->fetchOneByUuid($id);
5595 stevensc 143
                    if ($company) {
144
 
1 www 145
                        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
146
                        $companyUser = $companyUserMapper->fetchOwnerByCompanyId($company->id);
5595 stevensc 147
 
1 www 148
                        $user  = $userMapper->fetchOne($companyUser->user_id);
5595 stevensc 149
 
150
 
2731 efrain 151
                        $selected_user_id = $user->id;
1 www 152
                        $conversation = $conversationMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
5595 stevensc 153
 
154
 
1 www 155
                        $timeElapsedString = '';
5595 stevensc 156
                        if ($conversation) {
1 www 157
                            $unread = $messageMapper->fetchCountUnreadMessagesByConversationIdAndReceiverId($conversation->id, $currentUser->id);
158
                            $lastMessage = $messageMapper->fetchLastUnreadMessagesByConversationIdAndReceiverId($conversation->id, $currentUser->id);
5595 stevensc 159
 
160
                            if ($lastMessage) {
3099 efrain 161
                                $timeElapsedString =  $this->timeAgo($lastMessage, $now);
5595 stevensc 162
                            }
1 www 163
                        } else {
164
                            $unread = 0;
165
                        }
5595 stevensc 166
 
167
 
1 www 168
                        array_push($conversations, [
169
                            'uuid' => $company->uuid,
170
                            'name' => $company->name,
2194 efrain 171
                            'image' => $this->url()->fromRoute('storage', ['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image]),
5595 stevensc 172
                            'profile' => $this->url()->fromRoute('company/view', ['id' => $company->uuid]),
173
                            'last_message' => $timeElapsedString,
1 www 174
                            'count_unread' => $unread,
175
                            'messages_link' => $this->url()->fromRoute('inmail/message', ['id' => $user->uuid]),
176
                            'send_link' => $this->url()->fromRoute('inmail/message/send', ['id' => $user->uuid]),
177
                            'selected' => 1,
5611 anderson 178
                            'delete_link' => $this->url()->fromRoute('inmail/delete',  ['id' => $user->uuid]),
5595 stevensc 179
                        ]);
1 www 180
                    } else {
181
                        $user = $userMapper->fetchOneByUuid($id);
5595 stevensc 182
                        if ($user) {
183
 
184
                            $timeElapsedString = '';
185
 
1 www 186
                            $selected_user_id = $user->id;
187
                            $conversation = $conversationMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
5595 stevensc 188
                            if ($conversation) {
1 www 189
                                $unread = $messageMapper->fetchCountUnreadMessagesByConversationIdAndReceiverId($conversation->id, $currentUser->id);
190
                                $lastMessage = $messageMapper->fetchLastUnreadMessagesByConversationIdAndReceiverId($conversation->id, $currentUser->id);
5595 stevensc 191
                                if ($lastMessage) {
3099 efrain 192
                                    $timeElapsedString =  $this->timeAgo($lastMessage, $now);
5595 stevensc 193
                                }
1 www 194
                            } else {
195
                                $unread = 0;
196
                            }
5595 stevensc 197
 
198
 
1 www 199
                            array_push($conversations, [
200
                                'uuid' => $user->uuid,
201
                                'name' => trim($user->first_name . ' ' . $user->last_name),
2194 efrain 202
                                'image' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $user->uuid, 'filename' => $user->image]),
1 www 203
                                'profile' => $this->url()->fromRoute('profile/view', ['id' => $user->uuid]),
204
                                'last_message' => $timeElapsedString,
205
                                'count_unread' => $unread,
206
                                'messages_link' => $this->url()->fromRoute('inmail/message', ['id' => $user->uuid]),
207
                                'send_link' => $this->url()->fromRoute('inmail/message/send', ['id' => $user->uuid]),
208
                                'selected' => 1,
5611 anderson 209
                                'delete_link' => $this->url()->fromRoute('inmail/delete',  ['id' => $user->uuid]),
1 www 210
                            ]);
211
                        }
212
                    }
213
                }
5595 stevensc 214
 
215
 
1 www 216
                $records = $conversationMapper->fetchAllByUserId($currentUser->id);
5595 stevensc 217
                foreach ($records as $record) {
218
                    if ($selected_user_id) {
219
                        if ($record->sender_id == $currentUser->id && $record->receiver_id == $selected_user_id) {
1 www 220
                            continue;
221
                        }
5595 stevensc 222
                        if ($record->receiver_id == $currentUser->id && $record->sender_id == $selected_user_id) {
1 www 223
                            continue;
224
                        }
225
                    }
5595 stevensc 226
 
227
                    if ($record->sender_id == $currentUser->id) {
1 www 228
                        $user = $userMapper->fetchOne($record->receiver_id);
229
                    }
5595 stevensc 230
                    if ($record->receiver_id == $currentUser->id) {
1 www 231
                        $user = $userMapper->fetchOne($record->sender_id);
232
                    }
5595 stevensc 233
 
1 www 234
                    $timeElapsedString = '';
235
                    $unread = $messageMapper->fetchCountUnreadMessagesByConversationIdAndReceiverId($record->id, $currentUser->id);
236
                    $lastMessage = $messageMapper->fetchLastMessagesByConversationIdAndReceiverId($record->id, $currentUser->id);
5595 stevensc 237
 
238
 
239
                    if ($lastMessage) {
3099 efrain 240
                        $timeElapsedString =  $this->timeAgo($lastMessage, $now);
5595 stevensc 241
                    }
242
 
1 www 243
                    array_push($conversations, [
244
                        'uuid' => $user->uuid,
245
                        'name' => trim($user->first_name . ' ' . $user->last_name),
2194 efrain 246
                        'image' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $user->uuid, 'filename' => $user->image]),
1 www 247
                        'profile' => $this->url()->fromRoute('profile/view', ['id' => $user->uuid]),
248
                        'last_message' => $timeElapsedString,
249
                        'count_unread' => $unread,
250
                        'messages_link' => $this->url()->fromRoute('inmail/message', ['id' => $user->uuid]),
251
                        'send_link' => $this->url()->fromRoute('inmail/message/send', ['id' => $user->uuid]),
252
                        'selected' => 0,
5611 anderson 253
                        'delete_link' => $this->url()->fromRoute('inmail/delete',  ['id' => $user->uuid]),
1 www 254
                    ]);
255
                }
5595 stevensc 256
 
257
 
258
                usort($conversations, function ($a, $b) {
1 www 259
                    if ($a['selected'] == $b['selected']) {
5595 stevensc 260
                        if ($a['last_message'] == $b['last_message']) {
1 www 261
                            return 0;
262
                        } else {
263
                            return $a['last_message'] < $b['last_message'] ? -1 : 1;
264
                        }
265
                    } else {
266
                        return $a['selected'] < $b['selected'] ? -1 : 1;
267
                    }
268
                });
5595 stevensc 269
 
270
 
1 www 271
                return new JsonModel([
272
                    'success' => true,
273
                    'data' => $conversations
274
                ]);
275
            } else {
276
                $this->layout()->setTemplate('layout/layout.phtml');
277
                $viewModel = new ViewModel();
278
                $viewModel->setTemplate('leaders-linked/inmail/index.phtml');
5595 stevensc 279
                return $viewModel;
1 www 280
            }
281
        } else {
282
            return new JsonModel([
283
                'success' => false,
284
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
285
            ]);
286
        }
287
    }
5595 stevensc 288
 
289
 
1 www 290
    /**
291
     * Esta función remueve el usuario del grupo
292
     * Es una petición GET el url recuperado en /inmail
293
     * [ruta del servidor]/inmail/[uuid]/message
294
     * retorna un json en caso de ser  positivo
295
     * [
296
     *   success: true,
297
     *      data: [
298
     *          [
299
     *              sender_name: nombre de quien que envia el mensaje,
300
     *              sender_image: imagen de quien que recibe el mensaje,
301
     *              sender_profile: url de profile de quien que envia el mensaje,
302
     *              receiver_name: nombre de quien que recibe el mensaje,
303
     *              receiver_image: url de la imagen de quien  que recibe el mensaje,
304
     *              receiver_profile: url del profile de quien recibe el mensaje,
305
     *              side: left/righ de que lado de la pantalla se mostrara,
306
     *              message: texto del mensaje,
307
     *              type: text|image|video|document,
308
     *              filename: url del archivo enviado,
309
     *              date: cadena que describe hace cuanto se recibio el mensaje
310
     *          ]
311
     *      ]
312
     *   ]
313
     * En caso de ser negativo puede haber 2 formatos
314
     * [
315
     *  'success' : false,
316
     *  'data' : mensaje de error
317
     * ]
318
     * @return \Laminas\View\Model\JsonModel
319
     */
320
    public function messageAction()
321
    {
322
        $request = $this->getRequest();
5595 stevensc 323
        if ($request->isGet()) {
1 www 324
            $page = intval($this->params()->fromQuery('page', 0), 10);
5595 stevensc 325
 
1 www 326
            $currentUserPlugin = $this->plugin('currentUserPlugin');
327
            $currentUser = $currentUserPlugin->getUser();
5595 stevensc 328
 
1 www 329
            $userMapper = UserMapper::getInstance($this->adapter);
6388 efrain 330
            $now = $userMapper->getDatebaseNow();
331
 
1 www 332
            $conversationMapper = ConversationMapper::getInstance($this->adapter);
5595 stevensc 333
 
1 www 334
            $messageMapper = MessageMapper::getInstance($this->adapter);
335
 
336
            $id = $this->params()->fromRoute('id');
5595 stevensc 337
            if (!$id) {
1 www 338
                return new JsonModel([
339
                    'success' => false,
340
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
341
                ]);
342
            }
5595 stevensc 343
 
1 www 344
            $user = $userMapper->fetchOneByUuid($id);
5595 stevensc 345
            if (!$user) {
1 www 346
                return new JsonModel([
347
                    'success' => false,
348
                    'data' => 'ERROR_REQUEST_IS_INVALID'
349
                ]);
350
            }
5595 stevensc 351
 
1 www 352
            $conversationMapper = ConversationMapper::getInstance($this->adapter);
353
            $conversation = $conversationMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
5595 stevensc 354
 
355
            $messages = [];
356
            if ($conversation) {
1 www 357
                $records = $messageMapper->getAllMessagesPaginatorByConversationId($conversation->id, $page);
5595 stevensc 358
 
359
 
360
                foreach ($records as $record) {
3262 efrain 361
                    /*
362
                    echo '<pre>';
363
                    print_r($record);
364
                    echo '</pre>'; */
5595 stevensc 365
 
3099 efrain 366
                    $timeElapsedString = $this->timeAgo($record->added_on, $now);
367
 
5595 stevensc 368
 
369
                    if ($record->sender_id == $currentUser->id) {
1 www 370
                        array_push($messages, [
6749 efrain 371
                            'uuid' => $record->uuid,
1 www 372
                            'sender_name' => trim($currentUser->first_name . ' ' . $currentUser->last_name),
2194 efrain 373
                            'sender_image' => $this->url()->fromRoute('storage', ['type' => 'user', 'filename' => $currentUser->image, 'code' => $currentUser->uuid]),
1 www 374
                            'sender_profile' => $this->url()->fromRoute('profile/view', ['id' => $currentUser->uuid]),
375
                            'receiver_name' => trim($user->first_name . ' ' . $user->last_name),
2194 efrain 376
                            'receiver_image' => $this->url()->fromRoute('storage', ['type' => 'user', 'filename' => $user->image, 'code' => $user->uuid]),
1 www 377
                            'receiver_profile' => $this->url()->fromRoute('profile/view', ['id' => $user->uuid]),
378
                            'side' => 'left',
379
                            'message' => $record->message,
380
                            'type' => $record->type,
3025 efrain 381
                            'filename' => $record->filename ? $this->url()->fromRoute('storage', ['type' => 'message', 'filename' => $record->filename, 'code' => $record->uuid]) : '',
1 www 382
                            'date' => $timeElapsedString
383
                        ]);
384
                    } else {
5595 stevensc 385
 
386
 
387
 
1 www 388
                        array_push($messages, [
6749 efrain 389
                            'uuid' => $record->uuid,
1 www 390
                            'sender_name' => trim($user->first_name . ' ' . $user->last_name),
3009 efrain 391
                            'sender_image' => $this->url()->fromRoute('storage', ['type' => 'user', 'filename' => $user->image, 'code' => $user->uuid]),
1 www 392
                            'sender_profile' => $this->url()->fromRoute('profile/view', ['id' => $user->uuid]),
393
                            'receiver_name' => trim($currentUser->first_name . ' ' . $currentUser->last_name),
2194 efrain 394
                            'receiver_image' => $this->url()->fromRoute('storage', ['type' => 'user', 'filename' => $currentUser->image, 'code' => $user->uuid]),
1 www 395
                            'receiver_profile' => $this->url()->fromRoute('profile/view', ['id' => $currentUser->uuid]),
396
                            'side' => 'right',
397
                            'message' => $record->message,
398
                            'type' => $record->type,
3025 efrain 399
                            'filename' => $record->filename ? $this->url()->fromRoute('storage', ['type' => 'message', 'filename' => $record->filename, 'code' => $record->uuid]) : '',
1 www 400
                            'date' => $timeElapsedString
401
                        ]);
5595 stevensc 402
 
1 www 403
                        $messageMapper->markAsRead($record->id);
404
                    }
405
                }
5595 stevensc 406
 
1 www 407
                return new JsonModel([
408
                    'success' => true,
409
                    'data' => $messages,
410
                    'pagination' => $records->getPages()
411
                ]);
412
            }
5595 stevensc 413
 
414
 
1 www 415
            return new JsonModel([
416
                'success' => false,
417
                'data' => $messages
418
            ]);
419
        } else {
420
            return new JsonModel([
421
                'success' => false,
422
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
423
            ]);
424
        }
425
    }
426
 
427
    /**
428
     * Esta función envia un mensaje
429
     * Es una petición POST el url recuperado en /inmail
430
     * [ruta del servidor]/inmail/[uidd del usuario]/message/send
431
     * Lo párametros son
432
     * message: text plain requerido
433
     * file: no requerido puede jpg, png, jpeg, mp3, mp4, webm o pdf
434
     * o
435
     * [ruta del servidor]/inmail/[uidd del usuario]/message/send/encoding/base64 para el caso de react-native
436
     * Los párametros son
437
     * message: text plain requerido
438
     * fileBase64Name: nombre del archivo  que se envia en base64 solo requerido si se envia un archivo
439
     * fileBase64Content: contenido en base 64 del archivo
440
     *
441
     * retorna un json en caso de ser  positivo
442
     * [
443
     *   success: true,
444
     *      data:{
445
     *          sender_name: nombre de quien que envia el mensaje,
446
     *          sender_image: imagen de quien que recibe el mensaje,
447
     *          sender_profile: url de profile de quien que envia el mensaje,
448
     *          receiver_name: nombre de quien que recibe el mensaje,
449
     *          receiver_image: url de la imagen de quien  que recibe el mensaje,
450
     *          receiver_profile: url del profile de quien recibe el mensaje,
451
     *          side: left/righ de que lado de la pantalla se mostrara,
452
     *          message: texto del mensaje,
453
     *          type: text|image|video|document,
454
     *          filename: url del archivo enviado,
455
     *          date: cadena que describe hace cuanto se recibio el mensaje
456
     *      ]
457
     *   ]
458
     * En caso de ser negativo puede haber 2 formatos
459
     * [
460
     *  'success' : false,
461
     *  'data' : mensaje de error
462
     * ]
463
     * @return \Laminas\View\Model\JsonModel
464
     */
465
    public function sendMessageAction()
466
    {
467
        $request = $this->getRequest();
5595 stevensc 468
        if ($request->isPost()) {
1 www 469
            $currentUserPlugin = $this->plugin('currentUserPlugin');
470
            $currentUser = $currentUserPlugin->getUser();
5595 stevensc 471
 
1 www 472
            $userMapper = UserMapper::getInstance($this->adapter);
6388 efrain 473
            $now = $userMapper->getDatebaseNow();
474
 
5595 stevensc 475
 
1 www 476
            $id = $this->params()->fromRoute('id');
5595 stevensc 477
            if (!$id) {
1 www 478
                return new JsonModel([
479
                    'success' => false,
480
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
481
                ]);
482
            }
5595 stevensc 483
 
484
 
3648 efrain 485
            $user = $userMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
5595 stevensc 486
            if (!$user) {
1 www 487
                return new JsonModel([
488
                    'success' => false,
489
                    'data' => 'ERROR_REQUEST_IS_INVALID'
490
                ]);
491
            }
5595 stevensc 492
 
493
 
1 www 494
            $data = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
5595 stevensc 495
 
1 www 496
            $form = new SendForm();
497
            $form->setData($data);
5595 stevensc 498
 
499
            if ($form->isValid()) {
500
 
3017 efrain 501
                $dataPost = (array) $form->getData();
5595 stevensc 502
 
1 www 503
                $conversationMapper = ConversationMapper::getInstance($this->adapter);
504
                $conversation = $conversationMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
5595 stevensc 505
 
506
                if ($conversation) {
1 www 507
                    $conversation->receiver_status = Conversation::STATUS_NORMAL;
508
                    $conversation->sender_status = Conversation::STATUS_NORMAL;
5595 stevensc 509
 
510
                    if (!$conversationMapper->update($conversation)) {
1 www 511
                        return new JsonModel([
512
                            'success'  => false,
513
                            'data' => $conversationMapper->getError()
514
                        ]);
515
                    }
516
                } else {
517
                    $conversation = new Conversation();
518
                    $conversation->sender_id = $currentUser->id;
519
                    $conversation->sender_status = Conversation::STATUS_NORMAL;
520
                    $conversation->receiver_id = $user->id;
521
                    $conversation->receiver_status = Conversation::STATUS_NORMAL;
5595 stevensc 522
 
523
                    if (!$conversationMapper->insert($conversation)) {
1 www 524
                        return new JsonModel([
525
                            'success'  => false,
526
                            'data' => $conversationMapper->getError()
527
                        ]);
528
                    }
529
                }
530
                $files = $this->getRequest()->getFiles()->toArray();
531
                $type = Message::TYPE_TEXT;
5595 stevensc 532
 
533
 
3017 efrain 534
                /*
1 www 535
                $encoding = $this->params()->fromRoute('encoding');
536
                if($encoding == 'base64') {
537
 
538
 
539
                    $fileBase64Name = $this->params()->fromPost('file_base64_name');
540
                    $fileBase64Content = $this->params()->fromPost('file_base64_content');
541
 
542
 
543
                    if($fileBase64Name && $fileBase64Content) {
544
 
545
                        try {
546
 
547
                            $fileBase64Content = base64_decode($fileBase64Content);
548
                            if($fileBase64Content) {
549
 
550
                                $message_filename      = $this->normalizeString($fileBase64Name);
551
                                $message_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp';
552
                                if(!file_exists($message_tmp_filename)) {
553
                                    mkdir($message_tmp_filename, 0755, true);
554
                                }
555
 
556
                                $message_tmp_filename = 'data' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $message_filename;
557
                                file_put_contents($message_tmp_filename, $fileBase64Content);
558
 
559
 
560
 
561
                                $mime_type = mime_content_type($message_tmp_filename);
562
                                //echo '$mime_type = '. $mime_type; exit;
563
 
564
 
565
                                if($mime_type == 'image/jpg' || $mime_type == 'image/jpeg' || $mime_type == 'image/png') {
566
                                    $type = Message::TYPE_IMAGE;
567
                                } else if($mime_type == 'video/webm' || $mime_type == 'video/mpeg' || $mime_type == 'video/mpg' || $mime_type == 'video/mp4') {
568
                                    $type = Message::FILE_TYPE_VIDEO;
569
                                } else if($mime_type == 'application/pdf') {
570
                                    $type = Message::FILE_TYPE_DOCUMENT;
571
                                }
572
 
573
                            }
574
                        } catch(\Exception $e) {
575
 
576
                        }
577
                    }
578
 
579
                } else {
580
 
3017 efrain 581
 
582
                }*/
5595 stevensc 583
 
584
                if (isset($files['filename']) && empty($files['filename']['error'])) {
3017 efrain 585
                    $message_tmp_filename  = $files['filename']['tmp_name'];
586
                    $message_filename      = $this->normalizeString($files['filename']['name']);
5595 stevensc 587
 
3017 efrain 588
                    $mime_type = mime_content_type($message_tmp_filename);
5595 stevensc 589
 
590
 
591
                    if ($mime_type == 'image/jpg' || $mime_type == 'image/jpeg' || $mime_type == 'image/png') {
3017 efrain 592
                        $type = Message::TYPE_IMAGE;
5595 stevensc 593
                    } else if ($mime_type == 'video/webm' || $mime_type == 'video/mpeg' || $mime_type == 'video/mpg' || $mime_type == 'video/mp4') {
3017 efrain 594
                        $type = Message::TYPE_VIDEO;
5595 stevensc 595
                    } else if ($mime_type == 'application/pdf') {
3017 efrain 596
                        $type = Message::TYPE_DOCUMENT;
1 www 597
                    }
598
                }
3015 efrain 599
 
5595 stevensc 600
 
601
 
602
 
1 www 603
                $message = new Message();
604
                $message->conversation_id = $conversation->id;
605
                $message->read = Message::NO;
3017 efrain 606
                $message->message = $type == Message::TYPE_TEXT ? $dataPost['message'] : '';
1 www 607
                $message->receiver_id = $user->id;
608
                $message->receiver_status = Message::STATUS_NORMAL;
609
                $message->sender_id = $currentUser->id;
610
                $message->sender_status = Message::STATUS_NORMAL;
611
                $message->type = $type;
612
 
3019 efrain 613
 
5595 stevensc 614
 
615
 
616
 
1 www 617
                $messageMapper = MessageMapper::getInstance($this->adapter);
5595 stevensc 618
                if ($messageMapper->insert($message)) {
619
 
3024 efrain 620
                    $message = $messageMapper->fetchOne($message->id);
5595 stevensc 621
 
622
 
623
                    if ($type == Message::TYPE_DOCUMENT) {
1 www 624
                        try {
625
                            $target_path = $this->config['leaderslinked.fullpath.message'] . $message->uuid;
5595 stevensc 626
                            if (!file_exists($target_path)) {
1 www 627
                                mkdir($target_path, 0755);
628
                            }
5595 stevensc 629
 
630
                            $full_filename = $target_path  . DIRECTORY_SEPARATOR . $message_filename;
3019 efrain 631
                            /*
1 www 632
                            if($encoding == 'base64') {
633
                                $resultMoveOrRename = rename($message_tmp_filename , $full_filename);
634
                            } else {
635
                                $resultMoveOrRename = move_uploaded_file($message_tmp_filename , $full_filename);
636
                            }
3019 efrain 637
                            */
5595 stevensc 638
 
639
                            $resultMoveOrRename = move_uploaded_file($message_tmp_filename, $full_filename);
640
                            if ($resultMoveOrRename) {
641
 
1 www 642
                                $message->type = $type;
643
                                $message->filename = basename($message_filename);
644
                                $messageMapper->update($message);
645
                            } else {
5595 stevensc 646
                                error_log('no se pudo mover o renombrar el documento : ' . $message_tmp_filename . ' al directorio : ' . $full_filename);
1 www 647
                            }
5595 stevensc 648
                        } catch (\Throwable $e) {
1 www 649
                            error_log($e->getTraceAsString());
650
                        }
651
                    }
5595 stevensc 652
                    if ($type == Message::TYPE_IMAGE) {
1 www 653
                        try {
654
                            $target_path = $this->config['leaderslinked.fullpath.message'] . $message->uuid;
5595 stevensc 655
                            if (!file_exists($target_path)) {
1 www 656
                                mkdir($target_path, 0755);
657
                            }
5595 stevensc 658
 
1 www 659
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.message_image_size']);
5595 stevensc 660
 
1 www 661
                            $message_filename = substr($message_filename, 0, strrpos($message_filename, '.'))  . '.png';
5595 stevensc 662
 
3024 efrain 663
                            //echo "target_path = $target_path message_tmp_filename = $message_tmp_filename message_filename = $message_filename"; exit;
5595 stevensc 664
 
1 www 665
                            $crop_to_dimensions = false;
5595 stevensc 666
                            if (Image::uploadImage($message_tmp_filename, $target_path, $message_filename, $target_width, $target_height, $crop_to_dimensions)) {
1 www 667
                                $message->type = $type;
668
                                $message->filename = basename($message_filename);
669
                                $messageMapper->update($message);
670
                            }
5595 stevensc 671
                        } catch (\Throwable $e) {
1 www 672
                            error_log($e->getTraceAsString());
673
                        }
674
                    }
5595 stevensc 675
                    if ($type == Message::TYPE_VIDEO) {
1 www 676
                        try {
677
                            $target_path = $this->config['leaderslinked.fullpath.message'] . $message->uuid;
5595 stevensc 678
                            if (!file_exists($target_path)) {
1 www 679
                                mkdir($target_path, 0755);
680
                            }
5595 stevensc 681
 
1 www 682
                            $full_filename = $target_path  . DIRECTORY_SEPARATOR . $message_filename;
5595 stevensc 683
 
3019 efrain 684
                            /*
1 www 685
                            if($encoding == 'base64') {
686
                                $resultMoveOrRename = rename($message_tmp_filename , $full_filename);
687
                            } else {
688
                                $resultMoveOrRename = move_uploaded_file($message_tmp_filename , $full_filename);
3019 efrain 689
                            }*/
5595 stevensc 690
 
691
                            $resultMoveOrRename = move_uploaded_file($message_tmp_filename, $full_filename);
692
                            if ($resultMoveOrRename) {
693
 
1 www 694
                                $size = $this->config['leaderslinked.image_sizes.message_image_size'];
695
                                $getFromSecound = 2;
5595 stevensc 696
 
1 www 697
                                //extracción del cover
698
                                $generateFileName = substr($message_filename, 0, strrpos($message_filename, '.'));
699
                                $generateFile =  $target_path  . DIRECTORY_SEPARATOR . $generateFileName .  '.png';
700
                                $cmd            = "/usr/bin/ffmpeg -i $full_filename -an -ss $getFromSecound -s $size $generateFile";
701
                                exec($cmd);
5595 stevensc 702
 
703
 
1 www 704
                                $message->type = $type;
705
                                $message->filename = basename($message_filename);
706
                                $message->image_preview = basename($generateFile);
707
                                $messageMapper->update($message);
5595 stevensc 708
 
1 www 709
                                $videoConvert = new VideoConvert();
710
                                $videoConvert->filename = $full_filename;
711
                                $videoConvert->type = VideoConvert::TYPE_FEED;
5595 stevensc 712
 
1 www 713
                                $videoConvertMapper = VideoConvertMapper::getInstance($this->adapter);
714
                                $videoConvertMapper->insert($videoConvert);
715
                            } else {
5595 stevensc 716
                                error_log('no se pudo mover o renombrar el documento : ' . $message_tmp_filename . ' al directorio : ' . $full_filename);
1 www 717
                            }
5595 stevensc 718
                        } catch (\Throwable $e) {
1 www 719
                            error_log($e->getTraceAsString());
720
                        }
5595 stevensc 721
                    }
722
 
1 www 723
                    $message = $messageMapper->fetchOne($message->id);
5595 stevensc 724
 
725
                    if ($message->filename) {
2194 efrain 726
                        $filename = $this->url()->fromRoute('storage', ['type' => 'message', 'filename' => $message->filename, 'code' => $message->uuid]);
1 www 727
                    } else {
728
                        $filename = '';
729
                    }
5595 stevensc 730
 
1 www 731
                    $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $message->added_on);
732
 
3086 efrain 733
                    $userMapper->updateLastActivity($currentUser->id);
5595 stevensc 734
 
735
 
736
 
1 www 737
                    return new JsonModel([
738
                        'success'   => true,
739
                        'data'   => [
740
                            'sender_name' => trim($currentUser->first_name . ' ' . $currentUser->last_name),
2194 efrain 741
                            'sender_image' => $this->url()->fromRoute('storage', ['type' => 'user', 'filename' => $currentUser->image, 'code' => $currentUser->uuid]),
1 www 742
                            'sender_profile' => $this->url()->fromRoute('profile/view', ['id' => $currentUser->uuid]),
743
                            'receiver_name' => trim($user->first_name . ' ' . $user->last_name),
2194 efrain 744
                            'receiver_image' => $this->url()->fromRoute('storage', ['type' => 'user', 'filename' => $user->image, 'code' => $user->uuid]),
1 www 745
                            'receiver_profile' => $this->url()->fromRoute('profile/view', ['id' => $user->uuid]),
746
                            'side' => 'left',
747
                            'message' => $message->message,
748
                            'type' => $message->type,
749
                            'filename' => $filename,
3100 efrain 750
                            'date' => $this->timeAgo($now, $now),
1 www 751
                        ]
752
                    ]);
753
                } else {
754
                    return new JsonModel([
755
                        'success'   => false,
756
                        'data'   => $messageMapper->getError()
757
                    ]);
758
                }
759
            } else {
760
 
5595 stevensc 761
 
1 www 762
                $messages = [];
763
                $form_messages = (array) $form->getMessages();
5595 stevensc 764
                foreach ($form_messages  as $fieldname => $field_messages) {
1 www 765
                    $messages[$fieldname] = array_values($field_messages);
766
                }
5595 stevensc 767
 
1 www 768
                return new JsonModel([
769
                    'success'   => false,
770
                    'data'   => $messages
771
                ]);
772
            }
773
        } else {
774
            return new JsonModel([
775
                'success' => false,
776
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
777
            ]);
778
        }
5595 stevensc 779
    }
1 www 780
 
5595 stevensc 781
 
782
 
783
    private function normalizeString($str = '')
1 www 784
    {
785
        $basename  = substr($str, 0, strrpos($str, '.'));
786
        $basename  = str_replace('.', '-', $basename);
5595 stevensc 787
 
1 www 788
        $extension  = substr($str, strrpos($str, '.'));
5595 stevensc 789
 
1 www 790
        $str = $basename . $extension;
5595 stevensc 791
 
1 www 792
        $str = strip_tags($str);
793
        $str = preg_replace('/[\r\n\t ]+/', ' ', $str);
794
        $str = preg_replace('/[\"\*\/\:\<\>\?\'\|\,]+/', ' ', $str);
795
        $str = strtolower($str);
5595 stevensc 796
        $str = html_entity_decode($str, ENT_QUOTES, "utf-8");
1 www 797
        $str = htmlentities($str, ENT_QUOTES, "utf-8");
798
        $str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
799
        $str = str_replace(' ', '-', $str);
800
        $str = rawurlencode($str);
801
        $str = str_replace('%', '-', $str);
802
        return trim(strtolower($str));
803
    }
5595 stevensc 804
 
3099 efrain 805
    /**
806
     *
807
     * @param string $timestamp
808
     * @param string $now
809
     * @return string
810
     */
811
    private function timeAgo($timestamp, $now = '')
812
    {
6749 efrain 813
 
5595 stevensc 814
        if ($now) {
3099 efrain 815
            $datetime1 = \DateTime::createFromFormat('Y-m-d H:i:s', $now);
816
        } else {
817
            $now = date('Y-m-d H:i:s');
818
            $datetime1 = date_create($now);
819
        }
820
        $datetime2 = date_create($timestamp);
6749 efrain 821
 
3099 efrain 822
        $diff = date_diff($datetime1, $datetime2);
823
        $timemsg = '';
824
        if ($diff->y > 0) {
6749 efrain 825
            $timemsg = $diff->y . ' ' .($diff->y > 1 ? $this->translator->translate('LABEL_YEARS_SMALL')  : $this->translator->translate('LABEL_YEAR_SMALL') );
3099 efrain 826
        } else if ($diff->m > 0) {
6749 efrain 827
            $timemsg = $diff->m  . ' ' .($diff->m > 1 ? $this->translator->translate('LABEL_MONTHS_SMALL')  : $this->translator->translate('LABEL_MONTH_SMALL') );
3099 efrain 828
        } else if ($diff->d > 0) {
6749 efrain 829
            $timemsg = $diff->d . ' ' .($diff->d > 1 ? $this->translator->translate('LABEL_DAYS_SMALL')  : $this->translator->translate('LABEL_DAY_SMALL') );
3099 efrain 830
        } else if ($diff->h > 0) {
6749 efrain 831
            $timemsg = $diff->h  . ' ' .($diff->h > 1 ? $this->translator->translate('LABEL_HOURS_SMALL')  : $this->translator->translate('LABEL_HOUR_SMALL') );
3099 efrain 832
        } else if ($diff->i > 0) {
6749 efrain 833
            $timemsg = $diff->i  . ' ' .($diff->i > 1 ? $this->translator->translate('LABEL_MINUTES_SMALL')  : $this->translator->translate('LABEL_MINUTE_SMALL') );
3099 efrain 834
        } else if ($diff->s > 0) {
6749 efrain 835
            $timemsg = $diff->s  . ' ' . ($diff->s > 1 ? $this->translator->translate('LABEL_SECONDS_SMALL')  : $this->translator->translate('LABEL_SECOND_SMALL') );
3099 efrain 836
        }
837
        if (!$timemsg) {
6749 efrain 838
            $timemsg = $this->translator->translate('LABEL_NOW') ;
3099 efrain 839
        } else {
6749 efrain 840
            $timemsg = $this->translator->translate('LABEL_AGO_SMALL') . ' '. $timemsg . '';
3099 efrain 841
        }
842
        return $timemsg;
6749 efrain 843
 
3099 efrain 844
    }
5605 anderson 845
 
846
 
847
    public function deleteAction()
848
    {
849
        $request = $this->getRequest();
850
        if ($request->isPost()) {
851
            $currentUserPlugin = $this->plugin('currentUserPlugin');
852
            $currentUser = $currentUserPlugin->getUser();
6749 efrain 853
 
854
            $id = $this->params()->fromRoute('id');
855
            if (!$id) {
856
                return new JsonModel([
857
                    'success' => false,
858
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
859
                ]);
860
            }
861
 
862
            $userMapper = UserMapper::getInstance($this->adapter);
863
            $user = $userMapper->fetchOneByUuid($id);
864
            if (!$user) {
865
                return new JsonModel([
866
                    'success' => false,
867
                    'data' => 'ERROR_REQUEST_IS_INVALID'
868
                ]);
869
            }
870
 
5610 anderson 871
            $conversationMapper = ConversationMapper::getInstance($this->adapter);
6749 efrain 872
            $conversation = $conversationMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
873
 
874
 
5655 anderson 875
            if ($conversation) {
6749 efrain 876
 
877
                if ($conversation->sender_id == $currentUser->id && $conversation->receiver_id == $user->id) {
878
                    $conversation->sender_status = Conversation::STATUS_DELETED;
879
                    if ($conversationMapper->update($conversation)) {
880
                        $response = [
881
                            'success' => true,
882
                            'data' => 'LABEL_CONVERSATION_WAS_DELETED'
883
                        ];
884
                    } else {
885
 
886
 
887
                        $response = [
888
                            'success' => false,
889
                            'data' => $conversationMapper->getError()
890
                        ];
891
                    }
5642 anderson 892
                }
6749 efrain 893
 
894
                if ($conversation->receiver_id == $currentUser->id && $conversation->sender_id == $user->id) {
895
                    $conversation->receiver_status = Conversation::STATUS_DELETED;
896
                    if ($conversationMapper->update($conversation)) {
897
                        $response = [
898
                            'success' => true,
899
                            'data' => 'LABEL_CONVERSATION_WAS_DELETED'
900
                        ];
901
                    } else {
902
 
903
 
904
                        $response = [
905
                            'success' => false,
906
                            'data' => $conversationMapper->getError()
907
                        ];
908
                    }
909
                }
910
 
911
                return new JsonModel($response);
912
 
5642 anderson 913
            } else {
914
                $response = [
915
                    'success' => false,
6749 efrain 916
                    'data' => 'ERROR_CONVERSATION_NOT_FOUND'
5642 anderson 917
                ];
918
            }
6749 efrain 919
 
5605 anderson 920
            return new JsonModel($response);
921
        } else {
922
            $response = [
923
                'success' => false,
924
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
925
            ];
926
        }
6749 efrain 927
 
5605 anderson 928
        return new JsonModel($response);
929
    }
2731 efrain 930
}