Proyectos de Subversion LeadersLinked - Backend

Rev

| Ultima modificación | Ver Log |

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