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