Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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