Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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