Proyectos de Subversion LeadersLinked - Backend

Rev

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

Rev Autor Línea Nro. Línea
11339 nelberth 1
<?php
16181 anderson 2
 
3
declare(strict_types=1);
4
 
11339 nelberth 5
namespace LeadersLinked\Controller;
6
 
16292 anderson 7
use LeadersLinked\Model\User;
8
use LeadersLinked\Library\Zoom;
11339 nelberth 9
use Laminas\Log\LoggerInterface;
16292 anderson 10
use LeadersLinked\Model\Network;
11339 nelberth 11
use Laminas\View\Model\JsonModel;
12
use Laminas\View\Model\ViewModel;
16292 anderson 13
use LeadersLinked\Model\ChatUser;
14
use LeadersLinked\Model\ChatGroup;
15
use LeadersLinked\Model\Connection;
11339 nelberth 16
use LeadersLinked\Library\Functions;
17
use LeadersLinked\Mapper\UserMapper;
16292 anderson 18
use LeadersLinked\Mapper\UtilMapper;
19
use LeadersLinked\Model\ChatMessage;
20
use LeadersLinked\Model\ZoomMeeting;
21
use LeadersLinked\Model\ChatGroupUser;
22
use Laminas\Db\Adapter\AdapterInterface;
23
use LeadersLinked\Form\Chat\ZoomAddForm;
24
use LeadersLinked\Mapper\ChatUserMapper;
25
use LeadersLinked\Model\ZoomMeetingUser;
26
use LeadersLinked\Mapper\ChatGroupMapper;
27
use LeadersLinked\Model\ChatGroupMessage;
16283 stevensc 28
use LeadersLinked\Mapper\ConnectionMapper;
16292 anderson 29
use LeadersLinked\Form\CreateChatGroupForm;
16283 stevensc 30
use LeadersLinked\Mapper\ChatMessageMapper;
16292 anderson 31
use LeadersLinked\Mapper\ZoomMeetingMapper;
32
use LeadersLinked\Mapper\ChatGroupUserMapper;
33
use LeadersLinked\Model\ChatGroupUserMessage;
34
use LeadersLinked\Mapper\ZoomMeetingUserMapper;
16283 stevensc 35
use LeadersLinked\Mapper\ChatGroupMessageMapper;
16292 anderson 36
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
37
use Laminas\Mvc\Controller\AbstractActionController;
16283 stevensc 38
use LeadersLinked\Mapper\ChatGroupUserMessageMapper;
11339 nelberth 39
 
40
 
41
class ChatController extends AbstractActionController
16181 anderson 42
{
11339 nelberth 43
    /**
44
     *
45
     * @var AdapterInterface
46
     */
47
    private $adapter;
48
 
49
    /**
50
     *
51
     * @var AbstractAdapter
52
     */
53
    private $cache;
54
 
55
    /**
56
     *
57
     * @var LoggerInterface
58
     */
59
    private $logger;
60
 
61
    /**
62
     *
63
     * @var array
64
     */
65
    private $config;
66
 
67
    /**
68
     *
69
     * @param AdapterInterface $adapter
70
     * @param AbstractAdapter $cache
71
     * @param LoggerInterface $logger
72
     * @param array $config
73
     */
74
    public function __construct($adapter, $cache, $logger, $config)
75
    {
76
        $this->adapter  = $adapter;
77
        $this->cache    = $cache;
78
        $this->logger   = $logger;
79
        $this->config   = $config;
16181 anderson 80
    }
11339 nelberth 81
 
82
    /**
83
     *
84
     * Ruta usada para mostrar el chat en pantalla completa usada en los moviles
85
     *
86
     */
87
    public function indexAction()
88
    {
89
        $currentUserPlugin = $this->plugin('currentUserPlugin');
90
        $currentUser = $currentUserPlugin->getUser();
16181 anderson 91
 
92
        $connectionMapper = ConnectionMapper::getInstance($this->adapter);
93
        $connectionIds = $connectionMapper->fetchAllConnectionsByUserReturnIds($currentUser->id);
94
 
11339 nelberth 95
        $contacts = [];
16181 anderson 96
        if ($connectionIds) {
11339 nelberth 97
            $userMapper = UserMapper::getInstance($this->adapter);
98
            $users = $userMapper->fetchAllByIds($connectionIds);
16181 anderson 99
 
100
            foreach ($users as $user) {
11339 nelberth 101
                $username = trim($user->first_name . ' ' . $user->last_name);
14590 efrain 102
                $status = $user->online ? 'Online' : 'Offline';
11339 nelberth 103
                $user_image = $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $user->uuid, 'filename' => $user->image]);
16181 anderson 104
 
105
                array_push($contacts, ['id' => $user->uuid, 'status' => $status, 'name' => $username, 'image' => $user_image]);
11339 nelberth 106
            }
107
        }
16181 anderson 108
 
11339 nelberth 109
        $groups = [];
110
        $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
111
        $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
16181 anderson 112
 
11339 nelberth 113
        $results = $chatGroupUserMapper->fetchAllByUserId($currentUser->id);
16181 anderson 114
        if (is_array($results)) {
115
            foreach ($results as $r) {
116
 
11339 nelberth 117
                $chatOwner = $chatGroupUserMapper->fetchOwnerByGroupId($r->group_id);
16181 anderson 118
                $userOwner = $userMapper->fetchOne($chatOwner->user_id);
11339 nelberth 119
                $chatGroup = $chatGroupMapper->fetchOne($r->group_id);
16181 anderson 120
 
121
                array_push($groups, ['id' => $chatGroup->uuid, 'name' => $chatGroup->name, 'owner_id' => $userOwner->uuid]);
11339 nelberth 122
            }
123
        }
16181 anderson 124
 
11339 nelberth 125
        /*
126
        $this->layout()->setTemplate('layout/layout-chat.phtml');
127
        $this->layout()->setVariables([
128
            'is_chat' => true
129
        ]);*/
11428 nelberth 130
        $this->layout()->setTemplate('layout/layout-backend');
11339 nelberth 131
        $viewModel = new ViewModel();
132
        $viewModel->setTemplate('leaders-linked/chat/chat.phtml');
133
        $viewModel->setVariables([
16181 anderson 134
            'contacts' => $contacts,
135
            'groups' => $groups,
11339 nelberth 136
            'user_id' => $currentUser->id,
137
            'is_chat' => true
138
        ]);
16181 anderson 139
        return $viewModel;
11339 nelberth 140
    }
16181 anderson 141
 
11339 nelberth 142
    /**
143
     * Recuperamos los contactos y grupos
144
     * tiene que enviarse un petición GET a la siguiente url: /chat/heart-beat
145
     * retorna un json en caso de ser  positivo
146
     * [
147
     *  'success' : true,
148
     *  'data' : [
149
     *     [
150
     *       'url_leave'                                => 'url para abandonar el grupo en caso de no ser el propietario',
151
     *       'url_delete'                               => 'url para borrar el grupo si es el propietario',
152
     *       'url_add_user_to_group'                    => 'url para agregar un usuario al grupo si es el propietario',
153
     *       'url_get_contacts_availables_for_group'    => 'url para obtener los usuarios disponibles para agregarlos al grupo',
154
     *       'url_get_contact_group_list'               => 'url para obtener los usuarios del grupo si es el propietario',
155
     *       'url_clear'                                => 'url para limpiar los mensajes del grupo',
14692 efrain 156
     *       'url_close'                                => 'url para marcar como cerrado el chat',
157
     *       'url_open'                                 => 'url para marcar como abierto el chat',
11339 nelberth 158
     *       'url_send'                                 => 'url para enviar un mensaje',
159
     *       'url_upload'                               => 'url para subir un archivo, imagen o video',
160
     *       'url_get_all_messages'                     => 'url para para obtener los mensajes',
161
     *       'url_mark_seen'                            => 'url para marcar los mensajes como vistos'
162
     *       'url_mark_received'                        => 'url para marcar los mensajes como recibios'
163
     *       'id'                                       => 'id del grupo encriptado',
164
     *       'name'                                     => 'nombre del grupo',
165
     *       'type'                                     => 'group', //fixed
166
     *       'is_open'                                  => 'true/false',
167
     *       'unsee_messages'                           => 'true/false',
168
     *       'unread_messages'                          => 'true/false'
169
     *      ],
170
     *      [
171
     *        'url_clear'               => 'url para limpiar los mensajes del grupo',
14692 efrain 172
     *        'url_close'               => 'url para marcar como cerrado el chat',
173
     *        'url_open'                => 'url para marcar como abierto el chat',
11339 nelberth 174
     *        'url_send'                => 'url para enviar un mensaje',
175
     *        'url_upload'              => 'url para subir un archivo, imagen o video',
176
     *        'url_get_all_messages'    => 'url para para obtener los mensajes',
14692 efrain 177
     *        'url_mark_seen'           => 'url para marcar los mensajes como vistos'
178
     *        'url_mark_received'       => 'url para marcar los mensajes como recibios'
11339 nelberth 179
     *        'id'                      => 'id del usuario encriptado',
180
     *        'name'                    => 'nombre del usuario',
181
     *        'image'                   => 'imagen del usuario',
182
     *        'type'                    => 'user' //fixed,
183
     *        'profile'                 => 'url del profile',
184
     *        'online'                  => 'true/false',
185
     *        'is_open'                 => 'true/false',
186
     *        'unsee_messages'          => 'true/false'
187
     *        'unread_messages'         => 'true/false'
188
     *     ]
189
     * ]
190
     * En caso de ser negativo puede haber 2 formatos
191
     * [
192
     *  'success' : false,
193
     *  'data' : mensaje de error
194
     * ]
195
     * o
196
     * [
197
     *  'success' : false,
198
     *  'data' : [
199
     *      'fieldname' : [
200
     *          'mensaje de error'
201
     *      ]
202
     *  ]
203
     * ]
204
     * @return \Laminas\View\Model\JsonModel
205
     */
206
    public function heartBeatAction()
207
    {
16181 anderson 208
 
11339 nelberth 209
        $request    = $this->getRequest();
16181 anderson 210
        if ($request->isGet()) {
16301 efrain 211
 
212
            $utilMapper = UtilMapper::getInstance($this->adapter);
213
            $now = $utilMapper->getDatebaseNow();
16181 anderson 214
 
215
 
11339 nelberth 216
            $currentUserPlugin = $this->plugin('currentUserPlugin');
217
            $currentUser = $currentUserPlugin->getUser();
16301 efrain 218
 
219
            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
220
            $currentNetwork = $currentNetworkPlugin->getNetwork();
11339 nelberth 221
 
222
            $userMapper = UserMapper::getInstance($this->adapter);
223
            $userMapper->updateChatOnlineStatus($currentUser->id);
224
 
225
            $chats      = [];
16181 anderson 226
 
11339 nelberth 227
            $chatGroupMapper            = ChatGroupMapper::getInstance($this->adapter);
228
            $chatGroupUserMapper        = ChatGroupUserMapper::getInstance($this->adapter);
229
            $chatGroupUserMessageMapper = ChatGroupUserMessageMapper::getInstance($this->adapter);
16181 anderson 230
 
231
 
11339 nelberth 232
            $results = $chatGroupUserMapper->fetchAllByUserId($currentUser->id);
16181 anderson 233
 
11339 nelberth 234
            if (is_array($results)) {
16181 anderson 235
                foreach ($results as $r) {
236
 
237
                    $chatGroup = $chatGroupMapper->fetchOne($r->group_id);
11339 nelberth 238
                    $chatUserOwner = $chatGroupUserMapper->fetchOwnerByGroupId($chatGroup->id);
14627 efrain 239
                    $chatUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 240
 
241
 
14627 efrain 242
                    $is_open = $chatUser->open == ChatUser::OPEN_YES;
11339 nelberth 243
                    $not_seen_messages     = $chatGroupUserMessageMapper->existNotSeenMessages($chatGroup->id, $currentUser->id);
244
                    $not_received_messages = $chatGroupUserMessageMapper->existNotReceivedMessages($chatGroup->id, $currentUser->id);
16181 anderson 245
                    if ($chatGroup->high_performance_team_group_id != NULL) {
11339 nelberth 246
                        $chat = [
247
                            'url_leave'                             => '',
11711 nelberth 248
                            'url_delete'                            => '',
249
                            'url_add_user_to_group'                 => '',
11716 nelberth 250
                            'url_get_contact_group_list'            => '',
11715 nelberth 251
                            'url_get_contacts_availables_for_group' => '',
11339 nelberth 252
                            'url_clear'                             => $this->url()->fromRoute('chat/clear', ['id' => $chatGroup->uuid]),
253
                            'url_close'                             => $this->url()->fromRoute('chat/close', ['id' => $chatGroup->uuid]),
14692 efrain 254
                            'url_open'                              => $this->url()->fromRoute('chat/open', ['id' => $chatGroup->uuid]),
11339 nelberth 255
                            'url_send'                              => $this->url()->fromRoute('chat/send', ['id' => $chatGroup->uuid]),
256
                            'url_upload'                            => $this->url()->fromRoute('chat/upload', ['id' => $chatGroup->uuid]),
257
                            'url_get_all_messages'                  => $this->url()->fromRoute('chat/get-all-messages', ['id' => $chatGroup->uuid]),
258
                            'url_mark_seen'                         => $this->url()->fromRoute('chat/mark-seen', ['id' => $chatGroup->uuid]),
259
                            'url_mark_received'                     => $this->url()->fromRoute('chat/mark-received', ['id' => $chatGroup->uuid]),
260
                            'id'                                    => $chatGroup->uuid,
261
                            'name'                                  => $chatGroup->name,
262
                            'type'                                  => 'group',
263
                            'is_open'                               => $is_open ? 1 : 0,
264
                            'not_seen_messages'                     => $not_seen_messages,
265
                            'not_received_messages'                 => $not_received_messages,
16181 anderson 266
 
11339 nelberth 267
                        ];
16181 anderson 268
                    } else {
269
                        if ($chatUserOwner->user_id == $currentUser->id) {
270
 
11711 nelberth 271
                            $chat = [
272
                                'url_leave'                             => '',
273
                                'url_delete'                            => $this->url()->fromRoute('chat/delete-group', ['group_id' => $chatGroup->uuid]),
274
                                'url_add_user_to_group'                 => $this->url()->fromRoute('chat/add-user-to-group', ['group_id' => $chatGroup->uuid]),
275
                                'url_get_contact_group_list'            => $this->url()->fromRoute('chat/get-contact-group-list', ['group_id' => $chatGroup->uuid]),
276
                                'url_get_contacts_availables_for_group' => $this->url()->fromRoute('chat/get-contacts-availables-for-group', ['group_id' => $chatGroup->uuid]),
277
                                'url_clear'                             => $this->url()->fromRoute('chat/clear', ['id' => $chatGroup->uuid]),
278
                                'url_close'                             => $this->url()->fromRoute('chat/close', ['id' => $chatGroup->uuid]),
14692 efrain 279
                                'url_open'                              => $this->url()->fromRoute('chat/open', ['id' => $chatGroup->uuid]),
11711 nelberth 280
                                'url_send'                              => $this->url()->fromRoute('chat/send', ['id' => $chatGroup->uuid]),
281
                                'url_upload'                            => $this->url()->fromRoute('chat/upload', ['id' => $chatGroup->uuid]),
282
                                'url_get_all_messages'                  => $this->url()->fromRoute('chat/get-all-messages', ['id' => $chatGroup->uuid]),
283
                                'url_mark_seen'                         => $this->url()->fromRoute('chat/mark-seen', ['id' => $chatGroup->uuid]),
284
                                'url_mark_received'                     => $this->url()->fromRoute('chat/mark-received', ['id' => $chatGroup->uuid]),
285
                                'id'                                    => $chatGroup->uuid,
286
                                'name'                                  => $chatGroup->name,
287
                                'type'                                  => 'group',
288
                                'is_open'                               => $is_open ? 1 : 0,
289
                                'not_seen_messages'                     => $not_seen_messages,
290
                                'not_received_messages'                 => $not_received_messages,
16181 anderson 291
 
11711 nelberth 292
                            ];
293
                        } else {
16181 anderson 294
 
11711 nelberth 295
                            $chat = [
296
                                'url_delete'                    => '',
297
                                'url_add_user_to_group'         => '',
298
                                'url_get_contact_group_list'    => $this->url()->fromRoute('chat/get-contact-group-list', ['group_id' => $chatGroup->uuid]),
299
                                'url_leave'                     => $this->url()->fromRoute('chat/leave-group', ['group_id' => $chatGroup->uuid]),
300
                                'url_clear'                     => $this->url()->fromRoute('chat/clear', ['id' => $chatGroup->uuid]),
301
                                'url_close'                     => $this->url()->fromRoute('chat/close', ['id' => $chatGroup->uuid]),
14692 efrain 302
                                'url_open'                      => $this->url()->fromRoute('chat/open', ['id' => $chatGroup->uuid]),
11711 nelberth 303
                                'url_send'                      => $this->url()->fromRoute('chat/send', ['id' => $chatGroup->uuid]),
304
                                'url_upload'                    => $this->url()->fromRoute('chat/upload', ['id' => $chatGroup->uuid]),
305
                                'url_get_all_messages'          => $this->url()->fromRoute('chat/get-all-messages', ['id' => $chatGroup->uuid]),
306
                                'url_mark_seen'                 => $this->url()->fromRoute('chat/mark-seen', ['id' => $chatGroup->uuid]),
307
                                'url_mark_received'             => $this->url()->fromRoute('chat/mark-received', ['id' => $chatGroup->uuid]),
308
                                'id'                            => $chatGroup->uuid,
309
                                'name'                          => $chatGroup->name,
310
                                'type'                          => 'group',
311
                                'is_open'                       => $is_open ? 1 : 0,
312
                                'not_seen_messages'             => $not_seen_messages,
313
                                'not_received_messages'         => $not_received_messages,
314
                            ];
315
                        }
11339 nelberth 316
                    }
317
 
16181 anderson 318
 
319
                    array_push($chats, $chat);
11339 nelberth 320
                }
321
            }
16181 anderson 322
 
11339 nelberth 323
            $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
324
            $chatMessageMapper = ChatMessageMapper::getInstance($this->adapter);
16301 efrain 325
 
326
 
327
 
328
            if($currentNetwork->relationship_user_mode == Network::RELATIONSHIP_USER_MODE_USER_2_USER)  {
329
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
330
                $userConnectionIds = $connectionMapper->fetchAllConnectionsByUserReturnIds($currentUser->id);
331
            } else {
332
                $userConnectionIds = [];
333
            }
334
 
335
 
336
            $userIds = [];
337
            $records = $chatUserMapper->fetchAllByUserId($currentUser->id);
338
            foreach ($records as $record) {
339
                if($currentNetwork->relationship_user_mode == Network::RELATIONSHIP_USER_MODE_USER_2_USER)  {
340
 
341
                    if ($record->user_id1 == $currentUser->id) {
342
                        $connection_user_id = $record->user_id2;
343
                    } else {
344
                        $connection_user_id = $record->user_id1;
345
                    }
346
 
347
                    if(in_array($connection_user_id, $userConnectionIds)) {
348
                        array_push($userIds, $connection_user_id);
349
                    }
350
 
351
                } else {
352
 
353
 
354
                    if ($record->user_id1 == $currentUser->id) {
355
                        array_push($userIds, $record->user_id2);
356
                    } else {
357
                        array_push($userIds, $record->user_id1);
358
                    }
359
                }
360
            }
361
 
362
            /*
363
             if($currentNetwork->relationship_user_mode == Network::RELATIONSHIP_USER_MODE_USER_2_USER)  {
364
 
365
             $connectionMapper = ConnectionMapper::getInstance($this->adapter);
366
             $userIds = $connectionMapper->fetchAllConnectionsByUserReturnIds($currentUser->id);
367
 
368
             } else {
369
 
370
             $records = $chatUserMapper->fetchAllByUserId($currentUser->id);
371
             foreach($records as $record)
372
             {
373
             if($record->user_id1 == $currentUser->id) {
374
             array_push($userIds, $record->user_id2);
375
             } else {
376
             array_push($userIds, $record->user_id1);
377
             }
378
             }
379
 
380
             }
381
             */
382
 
383
 
384
 
385
            if ($userIds) {
386
 
11339 nelberth 387
                $userMapper = UserMapper::getInstance($this->adapter);
16301 efrain 388
                $users = $userMapper->fetchAllByIds($userIds);
389
 
16181 anderson 390
                foreach ($users as $user) {
11339 nelberth 391
                    $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 392
                    if ($chatUser) {
16301 efrain 393
                        $count_not_received_messages = $chatMessageMapper->countNotReceivedMessagesByChatIdAndToId($chatUser->id, $currentUser->id);
394
                        $count_not_seen_messages = $chatMessageMapper->countNotSeenMessagesByChatIdAndToId($chatUser->id, $currentUser->id);
395
                        $lastMessage = $chatMessageMapper->fetchLastMessage($chatUser->id, $currentUser->id);
396
 
397
                        if ($lastMessage) {
398
                            $lastMessage = Functions::timeAgo($lastMessage->added_on, $now);
399
                        } else {
400
                            $lastMessage = '';
401
                        }
402
 
16181 anderson 403
                        if ($currentUser->id == $chatUser->user_id1) {
14627 efrain 404
                            $is_open = $chatUser->user_open1 == ChatUser::OPEN_YES;
405
                        } else {
406
                            $is_open = $chatUser->user_open2 == ChatUser::OPEN_YES;
407
                        }
16301 efrain 408
 
409
 
410
                        $not_received_messages = $count_not_received_messages > 0;
411
                        $not_seen_messages = $count_not_seen_messages > 0;
11339 nelberth 412
                    } else {
413
                        $is_open = false;
16301 efrain 414
                        $count_not_received_messages = 0;
415
                        $count_not_seen_messages =  0;
11339 nelberth 416
                        $not_seen_messages = false;
417
                        $not_received_messages = false;
16301 efrain 418
                        $lastMessage = '';
11339 nelberth 419
                    }
16301 efrain 420
 
421
 
11339 nelberth 422
                    $chat = [
423
                        'url_clear'                 => $this->url()->fromRoute('chat/clear', ['id' => $user->uuid]),
424
                        'url_close'                 => $this->url()->fromRoute('chat/close', ['id' => $user->uuid]),
14692 efrain 425
                        'url_open'                  => $this->url()->fromRoute('chat/open', ['id' => $user->uuid]),
11339 nelberth 426
                        'url_send'                  => $this->url()->fromRoute('chat/send', ['id' => $user->uuid]),
427
                        'url_upload'                => $this->url()->fromRoute('chat/upload', ['id' => $user->uuid]),
428
                        'url_mark_seen'             => $this->url()->fromRoute('chat/mark-seen', ['id' => $user->uuid]),
429
                        'url_mark_received'         => $this->url()->fromRoute('chat/mark-received', ['id' => $user->uuid]),
430
                        'url_get_all_messages'      => $this->url()->fromRoute('chat/get-all-messages', ['id' => $user->uuid]),
16292 anderson 431
                        'url_zoom'                  => $this->url()->fromRoute('chat/zoom', ['id' => $user->uuid, 'type' => 'chat']),
11339 nelberth 432
                        'id'                        => $user->uuid,
433
                        'name'                      => trim($user->first_name . ' ' . $user->last_name),
434
                        'image'                     => $this->url()->fromRoute('storage', ['code' => $user->uuid, 'type' => 'user', 'filename' => $user->image]),
16301 efrain 435
                       // 'profile'                   => $this->url()->fromRoute('profile/view', ['id' => $user->uuid]),
11366 nelberth 436
                        'type'                      => 'user',
14590 efrain 437
                        'online'                    => $user->online ? 1 : 0,
11365 nelberth 438
                        'is_open'                   => $is_open ? 1 : 0,
439
                        'not_seen_messages'         => $not_seen_messages,
440
                        'not_received_messages'     => $not_received_messages,
16301 efrain 441
                        'count_not_seen_messages'       => $count_not_seen_messages,
442
                        'count_not_received_messages'   => $count_not_received_messages,
443
                        'last_message'                  => $lastMessage
444
 
11339 nelberth 445
                    ];
16301 efrain 446
 
11339 nelberth 447
                    array_push($chats, $chat);
448
                }
449
            }
16181 anderson 450
 
11339 nelberth 451
            $userMapper->updateLastHeartBeat($currentUser->id);
452
 
453
            $response = [
454
                'success' => true,
455
                'data' => $chats
456
            ];
457
        } else {
458
            $response = [
459
                'success' => false,
460
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
461
            ];
462
        }
16181 anderson 463
 
11339 nelberth 464
        return new JsonModel($response);
465
    }
466
 
16181 anderson 467
 
468
 
11339 nelberth 469
    /**
470
     * Esta función crea un grupo y asigna al usuario actual como el owner del mismo,
471
     * tiene que enviarse un petición POST a la siguiente url: /chat/create-group
472
     * con el siguiente parámetro
473
     * name = un string con un máximo de 50 carácteres
474
     * retorna un json en caso de ser  positivo
475
     * [
476
     *  'success' : true,
477
     *  'data' : ID del grupo encriptado
478
     * ]
479
     * En caso de ser negativo puede haber 2 formatos
480
     * [
481
     *  'success' : false,
482
     *  'data' : mensaje de error
483
     * ]
484
     * o
485
     * [
486
     *  'success' : false,
487
     *  'data' : [
488
     *      'fieldname' : [
489
     *          'mensaje de error'
490
     *      ]
491
     *  ]
492
     * ]
493
     * @return \Laminas\View\Model\JsonModel
494
     */
495
    public function createGroupAction()
496
    {
497
        $request    = $this->getRequest();
16181 anderson 498
        if ($request->isPost()) {
11589 nelberth 499
            $form = new  CreateChatGroupForm();
11339 nelberth 500
            $form->setData($request->getPost()->toArray());
16181 anderson 501
 
502
            if ($form->isValid()) {
11339 nelberth 503
                $dataPost = (array) $form->getData();
504
                $name = $dataPost['name'];
16181 anderson 505
 
506
 
11339 nelberth 507
                $currentUserPlugin = $this->plugin('currentUserPlugin');
508
                $currentUser = $currentUserPlugin->getUser();
16181 anderson 509
 
11339 nelberth 510
                $chatGroup = new ChatGroup();
511
                $chatGroup->name = $name;
512
 
513
 
514
                $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
515
                $result = $chatGroupMapper->insert($chatGroup);
516
                if ($result) {
517
                    $chatGroup = $chatGroupMapper->fetchOne($chatGroup->id);
16181 anderson 518
 
519
 
520
 
11339 nelberth 521
                    $chatGroupUser = new ChatGroupUser();
522
                    $chatGroupUser->group_id = $chatGroup->id;
523
                    $chatGroupUser->user_id = $currentUser->id;
524
                    $chatGroupUser->owner = ChatGroupUser::OWNER_YES;
16181 anderson 525
 
11339 nelberth 526
                    $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
527
                    $result = $chatGroupUserMapper->insert($chatGroupUser);
16181 anderson 528
 
529
                    if ($result) {
11339 nelberth 530
                        $fullpath_chat = $this->config['leaderslinked.fullpath.chat'];
531
                        $dirpath = $fullpath_chat . $chatGroup->uuid;
16181 anderson 532
                        if (!file_exists($dirpath)) {
11339 nelberth 533
                            mkdir($dirpath, 0777, true);
534
                            chmod($dirpath, 0777);
535
                        }
16181 anderson 536
 
11339 nelberth 537
                        $response = [
538
                            'success' => true,
539
                            'data' => $chatGroup->uuid,
540
                        ];
541
                    } else {
542
                        $response = [
543
                            'success' => false,
544
                            'data' => $chatGroupUserMapper->getError(),
545
                        ];
546
                    }
547
                } else {
548
                    $response = [
549
                        'success' => false,
550
                        'data' => $chatGroupMapper->getError(),
551
                    ];
552
                }
553
            } else {
554
                $messages = [];
555
                $form_messages = (array) $form->getMessages();
16181 anderson 556
                foreach ($form_messages  as $fieldname => $field_messages) {
557
 
11339 nelberth 558
                    $messages[$fieldname] = array_values($field_messages);
559
                }
16181 anderson 560
 
11339 nelberth 561
                return new JsonModel([
562
                    'success'   => false,
563
                    'data'   => $messages
564
                ]);
565
            }
566
        } else {
567
            $response = [
568
                'success' => false,
569
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
570
            ];
571
        }
572
 
573
        return new JsonModel($response);
574
    }
575
 
576
    /**
577
     * Esta función crea un grupo y asigna al usuario al mismo, solo el owner puede hacerlo
578
     * Es una petición POST el url que contiene el ID encriptado del chat (/chat/add-user-to-group/:group_id)
579
     * Parámetros del route
580
     * :group_id = id del grupo encriptado
581
     * Parámetro post
582
     * uid = id encriptado del usuario
583
     * retorna un json en caso de ser  positivo
584
     * [
585
     *  'success' : true,
586
     *  'data' : [
587
     *     [
588
     *       'url_remove_from_group' => 'url para remover el usuario del grupo',
589
     *       'id'                    => 'id del usuario encriptado',
590
     *       'name'                  => 'nombre del usuario',
591
     *       'image'                 => 'imagen del usuario',
592
     *       'type'                  => 'user' //fixed,
593
     *       'online'                => $online,
594
     *     ]
595
     * ]
596
     * En caso de ser negativo puede haber 2 formatos
597
     * [
598
     *  'success' : false,
599
     *  'data' : mensaje de error
600
     * ]
601
     * o
602
     * [
603
     *  'success' : false,
604
     *  'data' : [
605
     *      'fieldname' : [
606
     *          'mensaje de error'
607
     *      ]
608
     *  ]
609
     * ]
610
     * @return \Laminas\View\Model\JsonModel
611
     */
612
    public function addUserToGroupAction()
613
    {
614
        $request    = $this->getRequest();
16181 anderson 615
        if ($request->isPost()) {
11339 nelberth 616
            $currentUserPlugin = $this->plugin('currentUserPlugin');
617
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 618
 
11339 nelberth 619
            $group_id   = $this->params()->fromRoute('group_id');
620
            $user_id    = $this->params()->fromPost('uid');
16181 anderson 621
 
622
            if (empty($group_id) || empty($user_id)) {
11339 nelberth 623
                return new JsonModel([
624
                    'success' => false,
625
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
626
                ]);
627
            }
16181 anderson 628
 
11339 nelberth 629
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
630
            $chatGroup = $chatGroupMapper->fetchOneByUuid($group_id);
16181 anderson 631
            if (!$chatGroup) {
11339 nelberth 632
                return new JsonModel([
633
                    'success' => false,
634
                    'data' => 'ERROR_CHAT_GROUP_NOT_FOUND'
635
                ]);
636
            }
16181 anderson 637
            if ($chatGroup->high_performance_team_group_id != NULL) {
11722 nelberth 638
                return new JsonModel([
639
                    'success' => false,
640
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS'
641
                ]);
642
            }
11339 nelberth 643
            $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
644
            $chatGroupOwner = $chatGroupUserMapper->fetchOwnerByGroupId($chatGroup->id);
16181 anderson 645
 
646
            if ($chatGroupOwner->user_id != $currentUser->id) {
11339 nelberth 647
                return new JsonModel([
648
                    'success' => false,
649
                    'data' => 'ERROR_CHAT_GROUP_YOU_ARE_NOT_OWNER'
650
                ]);
651
            }
16181 anderson 652
 
11339 nelberth 653
            $userMapper = UserMapper::getInstance($this->adapter);
654
            $user = $userMapper->fetchOneByUuid($user_id);
16181 anderson 655
 
656
            if (!$user) {
11339 nelberth 657
                return new JsonModel([
658
                    'success' => false,
659
                    'data' => 'ERROR_USER_NOT_FOUND'
660
                ]);
661
            }
16181 anderson 662
 
663
            if ($chatGroupOwner->user_id == $user->id) {
11339 nelberth 664
                return new JsonModel([
665
                    'success' => false,
666
                    'data' => 'ERROR_CHAT_I_CAN_NOT_ADD_HIMSELF'
667
                ]);
668
            }
16181 anderson 669
 
670
 
11339 nelberth 671
            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
672
            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 673
            if (!$connection) {
11339 nelberth 674
                return new JsonModel([
675
                    'success' => false,
676
                    'data' => 'ERROR_THIS_USER_IS_NOT_A_CONNECTION'
677
                ]);
678
            }
16181 anderson 679
 
11339 nelberth 680
            $chatGroupUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $user->id);
16181 anderson 681
            if ($chatGroupUser) {
11339 nelberth 682
                return new JsonModel([
683
                    'success' => false,
684
                    'data' => 'ERROR_THIS_USER_ALREADY_EXISTS_IN_THIS_GROUP'
685
                ]);
686
            }
687
 
16181 anderson 688
 
11339 nelberth 689
            $chatGroupUser = new ChatGroupUser();
690
            $chatGroupUser->group_id    = $chatGroup->id;
691
            $chatGroupUser->user_id     = $user->id;
692
            $chatGroupUser->owner       = ChatGroupUser::OWNER_NO;
16181 anderson 693
 
11339 nelberth 694
            $result = $chatGroupUserMapper->insert($chatGroupUser);
16181 anderson 695
            if (!$result) {
11339 nelberth 696
                return new JsonModel([
697
                    'success' => false,
698
                    'data' => $chatGroupUserMapper->getError()
699
                ]);
700
            }
16181 anderson 701
 
702
 
703
 
704
 
11339 nelberth 705
            return new JsonModel([
706
                'success' => true,
707
                'data' => [
708
                    'url_remove_from_group' => $this->url()->fromRoute('chat/remove-user-from-group', ['group_id' => $chatGroup->uuid, 'user_id' => $user->uuid]),
709
                    'id'        => $user->uuid,
710
                    'name'      => trim($user->first_name . ' ' . $user->last_name),
711
                    'image'     => $this->url()->fromRoute('storage', ['code' => $user->uuid, 'type' => 'user', 'filename' => $user->image]),
712
                    'type'      => 'user',
14590 efrain 713
                    'online'    => $user->online,
11339 nelberth 714
                ]
16181 anderson 715
            ]);
11339 nelberth 716
        } else {
717
            return new JsonModel([
718
                'success' => false,
719
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
720
            ]);
721
        }
722
    }
723
 
724
    /**
725
     * Esta función remueve el usuario del grupo
726
     * Es una petición POST el url que contiene el ID encriptado del chat (/chat/remove-user-from-group/:group_id/:user_id)
727
     * y la cuál se recibe en la función heartBeat.
728
     * Parámetros del route
729
     * group_id= id encriptado del grupo
730
     * user_id = id encriptado del usuario
731
     * retorna un json en caso de ser  positivo
732
     * [
733
     *  'success' : true,
734
     * ]
735
     * En caso de ser negativo puede haber 2 formatos
736
     * [
737
     *  'success' : false,
738
     *  'data' : mensaje de error
739
     * ]
740
     * @return \Laminas\View\Model\JsonModel
741
     */
742
    public function removeUserFromGroupAction()
743
    {
744
        $request    = $this->getRequest();
16181 anderson 745
        if ($request->isPost()) {
746
 
11339 nelberth 747
            $currentUserPlugin = $this->plugin('currentUserPlugin');
748
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 749
 
11339 nelberth 750
            $user_id = $this->params()->fromRoute('user_id');
751
            $group_id = $this->params()->fromRoute('group_id');
16181 anderson 752
 
753
            if (empty($group_id) || empty($user_id)) {
11339 nelberth 754
                return new JsonModel([
755
                    'success' => false,
756
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
757
                ]);
758
            }
16181 anderson 759
 
11339 nelberth 760
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
761
            $chatGroup = $chatGroupMapper->fetchOneByUuid($group_id);
16181 anderson 762
            if (!$chatGroup) {
11339 nelberth 763
                return new JsonModel([
764
                    'success' => false,
765
                    'data' => 'ERROR_CHAT_GROUP_NOT_FOUND'
766
                ]);
767
            }
16181 anderson 768
            if ($chatGroup->high_performance_team_group_id != NULL) {
11722 nelberth 769
                return new JsonModel([
770
                    'success' => false,
771
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS'
772
                ]);
773
            }
11339 nelberth 774
            $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
775
            $chatGroupOwner = $chatGroupUserMapper->fetchOwnerByGroupId($chatGroup->id);
16181 anderson 776
 
777
            if ($chatGroupOwner->user_id != $currentUser->id) {
11339 nelberth 778
                return new JsonModel([
779
                    'success' => false,
780
                    'data' => 'ERROR_CHAT_GROUP_YOU_ARE_NOT_OWNER'
781
                ]);
782
            }
16181 anderson 783
 
11339 nelberth 784
            $userMapper = UserMapper::getInstance($this->adapter);
785
            $user = $userMapper->fetchOneByUuid($user_id);
16181 anderson 786
 
787
            if (!$user) {
11339 nelberth 788
                return new JsonModel([
789
                    'success' => false,
790
                    'data' => 'ERROR_USER_NOT_FOUND'
791
                ]);
792
            }
16181 anderson 793
 
794
            if ($chatGroupOwner->user_id == $user->id) {
11339 nelberth 795
                return new JsonModel([
796
                    'success' => false,
797
                    'data' => 'ERROR_CHAT_I_CAN_NOT_REMOVE_MYSELF'
798
                ]);
799
            }
800
 
16181 anderson 801
 
802
 
803
 
11339 nelberth 804
            $chatGroupUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $user->id);
16181 anderson 805
            if (!$chatGroupUser) {
11339 nelberth 806
                return new JsonModel([
807
                    'success' => false,
808
                    'data' => 'ERROR_CHAT_GROUP_YOU_NOT_MEMBER'
809
                ]);
810
            }
811
 
16181 anderson 812
 
11339 nelberth 813
            $response = $chatGroupUserMapper->deleteByGroupIdAndUserId($chatGroup->id, $user->id);
16181 anderson 814
            if ($response) {
11339 nelberth 815
                return new JsonModel([
816
                    'success' => true
817
                ]);
818
            } else {
819
                return new JsonModel([
820
                    'success' => false,
821
                    'data' => $chatGroupMapper->getError()
822
                ]);
823
            }
824
        } else {
825
            return new JsonModel([
826
                'success' => false,
827
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
828
            ]);
829
        }
830
    }
831
 
16181 anderson 832
 
11339 nelberth 833
    /**
834
     * Abandonar un grupo
835
     * Es una petición POST el url que contiene el ID encriptado del chat (/chat/leave-group/:group_id) y la cuál se recibe en la función heartBeat.
836
     * Parámetros del route
837
     * :group_id = id del grupo encriptado
838
     * En caso de una respuesta positiva
839
     * [
840
     *      'success' => true,
841
     * ]
842
     * En caso de un respuesta negativa
843
     * [
844
     *      'success' => false,
845
     *      'data' => (string) 'mensaje_de_error'
846
     * ]
847
     * @return \Laminas\View\Model\JsonModel
848
     */
849
    public function leaveGroupAction()
850
    {
851
        $request    = $this->getRequest();
16181 anderson 852
        if ($request->isPost()) {
11339 nelberth 853
            $currentUserPlugin = $this->plugin('currentUserPlugin');
854
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 855
 
11339 nelberth 856
            $result = false;
857
            $group_id = $this->params()->fromRoute('group_id');
16181 anderson 858
 
859
 
860
            if (empty($group_id)) {
11339 nelberth 861
                return new JsonModel([
862
                    'success' => false,
863
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
864
                ]);
865
            }
16181 anderson 866
 
867
 
11339 nelberth 868
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
869
            $chatGroup = $chatGroupMapper->fetchOneByUuid($group_id);
16181 anderson 870
            if (!$chatGroup) {
11339 nelberth 871
                return new JsonModel([
872
                    'success' => false,
873
                    'data' => 'ERROR_GROUP_NOT_FOUND'
874
                ]);
875
            }
16181 anderson 876
            if ($chatGroup->high_performance_team_group_id != NULL) {
11722 nelberth 877
                return new JsonModel([
878
                    'success' => false,
879
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS'
880
                ]);
881
            }
11339 nelberth 882
            $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
883
            $chatGroupUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 884
            if (!$chatGroupUser) {
11339 nelberth 885
                return new JsonModel([
886
                    'success' => false,
887
                    'data' => 'ERROR_CHAT_GROUP_YOU_NOT_MEMBER'
888
                ]);
889
            }
16181 anderson 890
 
891
            if ($chatGroupUser->owner == ChatGroupUser::OWNER_YES) {
11339 nelberth 892
                return new JsonModel([
893
                    'success' => false,
894
                    'data' => 'ERROR_CHAT_GROUP_YOU_ARE_OWNER'
895
                ]);
896
            }
16181 anderson 897
 
898
 
11339 nelberth 899
            $result = $chatGroupUserMapper->deleteByGroupIdAndUserId($chatGroupUser->group_id, $chatGroupUser->user_id);
16181 anderson 900
            if ($result) {
11339 nelberth 901
                return new JsonModel([
902
                    'success' => true
903
                ]);
904
            } else {
905
                return new JsonModel([
906
                    'success' => false,
907
                    'data' => $chatGroupMapper->getError()
908
                ]);
909
            }
910
        } else {
911
            return new JsonModel([
912
                'success' => false,
913
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
914
            ]);
915
        }
16181 anderson 916
    }
11339 nelberth 917
 
918
    /**
919
     *
920
     * @param ChatGroup $chatGroup
921
     * @param int $page
922
     * @return array
923
     */
924
    private function getAllMessagesForChatGroup($chatGroup, $page = 0)
925
    {
926
        $currentUserPlugin = $this->plugin('currentUserPlugin');
927
        $currentUser = $currentUserPlugin->getUser();
16181 anderson 928
 
11339 nelberth 929
        $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
930
        $chatGroupUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 931
 
932
        if (!$chatGroupUser) {
11339 nelberth 933
            return [
934
                'success' => false,
935
                'data' => 'ERROR_CHAT_GROUP_YOU_NOT_MEMBER'
936
            ];
937
        }
14692 efrain 938
 
11339 nelberth 939
        $chatGroupMessageMapper = ChatGroupMessageMapper::getInstance($this->adapter);
940
        $paginator = $chatGroupMessageMapper->getPaginatorByGroupId($chatGroup->id, $page);
16181 anderson 941
 
11339 nelberth 942
        $pages = $paginator->count();
943
        $page  = $paginator->getCurrentPageNumber();
16181 anderson 944
 
11339 nelberth 945
        $items = [];
946
        $users = [];
947
        $userMapper = UserMapper::getInstance($this->adapter);
16181 anderson 948
 
14590 efrain 949
        $utilMapper = UtilMapper::getInstance($this->adapter);
950
        $now = $utilMapper->getDatebaseNow();
11339 nelberth 951
 
16181 anderson 952
        foreach ($paginator as $m) {
953
 
11339 nelberth 954
            if (isset($users[$m->sender_id])) {
955
                $userdata_from = $users[$m->sender_id];
956
            } else {
957
                $userdata_from = $userMapper->fetchOne($m->sender_id);
16181 anderson 958
                $users[$m->sender_id] = $userdata_from;
11339 nelberth 959
            }
16181 anderson 960
 
11339 nelberth 961
            $pic_from = $this->url()->fromRoute('storage', [
962
                'code' => $userdata_from->uuid,
963
                'type' => 'user',
964
                'filename' => $userdata_from->image
965
            ]);
966
            $u =  $userdata_from->id == $currentUser->id ? 1 : 2;
16181 anderson 967
            if ($m->type == ChatGroupMessage::TYPE_TEXT) {
11339 nelberth 968
                $content = $this->sanitize($m->content);
969
            } else {
970
                $content = $this->url()->fromRoute('storage', ['code' => $chatGroup->uuid, 'type' => 'chat', 'filename' => $m->content]);
971
            }
16181 anderson 972
 
14590 efrain 973
            $msgtime = $this->timeAgo($m->added_on, $now);
11339 nelberth 974
            array_push($items, [
16181 anderson 975
                'user_name' => trim($userdata_from->first_name . ' ' . $userdata_from->last_name),
11339 nelberth 976
                'user_id' => $userdata_from->uuid,
977
                'user_image' => $pic_from,
978
                'u' => $u,
979
                'mtype' => $m->type,
980
                'm' => $content,
981
                'time' => $msgtime,
982
                'id' => $m->uuid
983
            ]);
984
        }
16181 anderson 985
 
11339 nelberth 986
        return [
987
            'success' => true,
988
            'data' => [
989
                'page' => $page,
990
                'pages' => $pages,
991
                'items' => $items
992
            ]
993
        ];
994
    }
16181 anderson 995
 
11339 nelberth 996
    /**
997
     *
998
     * @param ChatUser $chatUser
999
     * @param int $page
1000
     * @return array
1001
     */
1002
    private function getAllMessagesForChatUser($chatUser, $page = 0)
1003
    {
1004
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1005
        $currentUser = $currentUserPlugin->getUser();
14692 efrain 1006
 
1007
 
11339 nelberth 1008
        $chatMessageMapper = ChatMessageMapper::getInstance($this->adapter);
1009
        $paginator = $chatMessageMapper->getAllMessagesPaginatorByChatId($chatUser->id, $page);
1010
        $pages = $paginator->count();
1011
        $page = $paginator->getCurrentPageNumber();
16181 anderson 1012
 
11339 nelberth 1013
        $items = [];
1014
        $users = [];
1015
        $userMapper = UserMapper::getInstance($this->adapter);
16181 anderson 1016
 
14590 efrain 1017
        $utilMapper = UtilMapper::getInstance($this->adapter);
1018
        $now = $utilMapper->getDatebaseNow();
16181 anderson 1019
 
1020
 
11339 nelberth 1021
        $messages = $paginator->getCurrentItems();
1022
        foreach ($messages as $m) {
1023
            $from_id = (int) $m->from_id;
1024
            $to_id = (int) $m->to_id;
16181 anderson 1025
 
11339 nelberth 1026
            if (isset($users[$from_id])) {
1027
                $userdata_from = $users[$from_id];
1028
            } else {
1029
                $userdata_from = $userMapper->fetchOne($from_id);
1030
                $users[$from_id] = $userdata_from;
1031
            }
16181 anderson 1032
 
11339 nelberth 1033
            $pic_from = $this->url()->fromRoute('storage', [
1034
                'code' => $userdata_from->uuid,
1035
                'type' => 'user',
1036
                'filename' => $userdata_from->image
1037
            ]);
16181 anderson 1038
 
11339 nelberth 1039
            if (isset($users[$to_id])) {
1040
                $userdata_to = $users[$to_id];
1041
            } else {
1042
                $userdata_to = $userMapper->fetchOne($to_id);
16181 anderson 1043
                $users[$to_id] = $userdata_to;
11339 nelberth 1044
            }
16181 anderson 1045
 
11339 nelberth 1046
            $u = $m->from_id == $currentUser->id ? 1 : 2;
16181 anderson 1047
 
1048
 
1049
            if ($m->type == ChatMessage::TYPE_TEXT) {
11339 nelberth 1050
                $content = $this->sanitize($m->content);
1051
            } else {
1052
                $content = $this->url()->fromRoute('storage', ['code' => $chatUser->uuid, 'type' => 'chat', 'filename' => $m->content]);
1053
            }
16181 anderson 1054
 
1055
 
1056
 
14590 efrain 1057
            $msgtime = $this->timeAgo($m->added_on, $now);
11339 nelberth 1058
            array_push($items, [
1059
                'user_name' => ($userdata_from->first_name . ' ' . $userdata_from->last_name),
1060
                'user_id' => $userdata_from->uuid,
1061
                'user_image' => $pic_from,
1062
                'u' => $u,
1063
                'mtype' => $m->type,
1064
                'm' => $content,
1065
                'time' => $msgtime,
1066
                'id' => $m->uuid,
1067
            ]);
1068
        }
14590 efrain 1069
 
16181 anderson 1070
 
1071
 
1072
 
11339 nelberth 1073
        return [
1074
            'success' => true,
1075
            'data' => [
1076
                'page' => $page,
1077
                'pages' => $pages,
1078
                'items' => $items,
14590 efrain 1079
                'online' => 1
11339 nelberth 1080
            ]
1081
        ];
1082
    }
1083
 
1084
    /**
1085
     * Recupera los mensajes de un chat individual o grupal
1086
     * Es una petición GET el url que contiene el ID encriptado del chat (/chat/get-all-messages/:id) y la cuál se recibe en la función heartBeat.
1087
     * En caso de una respuesta positiva
1088
     * [
1089
     *      'success' => true,
1090
     *      'data' => [
1091
     *          'page' => 'entero número de página actúal',
1092
     *          'pages' => 'entero número total de páginaS',
1093
     *              'items' => [
1094
     *              'user_name' => 'nombre del usuario que envia',
1095
     *              'user_id_encript' => 'id encriptado del usuario que envia',
1096
     *              'user_image' => 'ruta de la imagén del usuario que envia',
1097
     *              'u' => '1 = si el usuario que envia es el usuario actual , 2 si no lo es',
1098
     *              'mtype' => 'text | file',
1099
     *              'm' => 'texto del mensaje o url del archivo',
1100
     *              'time' => 'cadena que da el tiempo del mensaje ejemplo 1seg',
1101
     *          ],
1102
     *          'online' => 'true/false'
1103
     *      ]
1104
     * ]
1105
     * En caso de un respuesta negativa
1106
     * [
1107
     *      'success' => false,
1108
     *      'data' => (string) 'mensaje_de_error'
1109
     * ]
1110
     * @return \Laminas\View\Model\JsonModel
1111
     */
1112
    public function getAllMessagesAction()
1113
    {
16181 anderson 1114
 
11339 nelberth 1115
        $request    = $this->getRequest();
16181 anderson 1116
        if ($request->isGet()) {
11339 nelberth 1117
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1118
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 1119
 
1120
 
11339 nelberth 1121
            $id     = $this->params()->fromRoute('id');
1122
            $page   = filter_var($this->params()->fromQuery('page', 0), FILTER_SANITIZE_NUMBER_INT);
16181 anderson 1123
 
1124
            if (!$id) {
11339 nelberth 1125
                return new JsonModel([
1126
                    'success' => false,
1127
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1128
                ]);
1129
            }
16181 anderson 1130
 
11339 nelberth 1131
            /**** Mensajes de un chat grupal ****/
1132
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
1133
            $chatGroup = $chatGroupMapper->fetchOneByUuid($id);
1134
            if ($chatGroup) {
1135
                $response = $this->getAllMessagesForChatGroup($chatGroup, $page);
1136
                return new JsonModel($response);
1137
            } else {
16181 anderson 1138
 
11339 nelberth 1139
                $userMapper = UserMapper::getInstance($this->adapter);
1140
                $user = $userMapper->fetchOneByUuid($id);
16181 anderson 1141
                if (!$user) {
11339 nelberth 1142
                    return new JsonModel([
1143
                        'success' => false,
1144
                        'data' => 'ERROR_USER_NOT_FOUND'
1145
                    ]);
1146
                }
1147
 
16181 anderson 1148
 
1149
 
1150
 
1151
 
1152
 
11339 nelberth 1153
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1154
                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 1155
                if (!$connection || $connection->status != Connection::STATUS_ACCEPTED) {
1156
 
11339 nelberth 1157
                    return new JsonModel([
1158
                        'success' => false,
1159
                        'data' => 'ERROR_THIS_USER_IS_NOT_A_CONNECTION'
1160
                    ]);
1161
                }
1162
                $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
1163
                $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 1164
                if (!$chatUser) {
11339 nelberth 1165
                    $chatUser = new ChatUser();
1166
                    $chatUser->user_id1 = $currentUser->id;
1167
                    $chatUser->user_id2 = $user->id;
16181 anderson 1168
 
11339 nelberth 1169
                    $response = $chatUserMapper->insert($chatUser);
16181 anderson 1170
 
1171
 
1172
                    if (!$response) {
11339 nelberth 1173
                        return new JsonModel([
1174
                            'success' => false,
1175
                            'data' => $chatUserMapper->getError()
1176
                        ]);
1177
                    }
16181 anderson 1178
 
11339 nelberth 1179
                    $chatUser = $chatUserMapper->fetchOne($chatUser->id);
1180
                    $fullpath_chat = $this->config['leaderslinked.fullpath.chat'];
1181
                    $dirpath = $fullpath_chat . $chatUser->uuid;
16181 anderson 1182
                    if (!file_exists($dirpath)) {
11339 nelberth 1183
                        mkdir($dirpath, 0777, true);
1184
                        chmod($dirpath, 0777);
1185
                    }
1186
                }
16181 anderson 1187
 
1188
 
1189
 
11339 nelberth 1190
                $response = $this->getAllMessagesForChatUser($chatUser, $page);
1191
                return new JsonModel($response);
1192
            }
1193
        } else {
1194
            return new JsonModel([
1195
                'success' => false,
1196
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1197
            ]);
1198
        }
1199
    }
1200
 
1201
    /**
1202
     * Envia un mensaje a un chat individual o grupal
1203
     * Es una petición POST el url que contiene el ID encriptado del chat (/chat/send/:id) y la cuál se recibe en la función heartBeat.
1204
     * Parámetros del route
1205
     * :id = id del chat encriptado
1206
     * Como parámentro solo se espera un campo
1207
     * message: string
1208
     * En caso de una respuesta positiva
1209
     * [
1210
     *      'success' => true,
1211
     *      'user_name' => 'nombre del usuario que envia',
1212
     *      'user_id_encripted' => 'id encriptado del usuario que envia',
1213
     *      'user_image' => 'ruta de la imagén del usuario que envia',
1214
     *      'u' => '1 = si el usuario que envia es el usuario actual , 2 si no lo es',
1215
     *      'mtype' => 'text | file',
1216
     *      'm' => 'texto del mensaje o url del archivo',
1217
     *      'time' => 'cadena que da el tiempo del mensaje ejemplo 1seg',
16181 anderson 1218
     * ]
11339 nelberth 1219
     * En caso de un respuesta negativa
1220
     * [
1221
     *      'success' => false,
1222
     *      'data' => (string) 'mensaje_de_error'
1223
     * ]
1224
     * @return \Laminas\View\Model\JsonModel
1225
     */
1226
    public function sendAction()
1227
    {
16181 anderson 1228
 
11339 nelberth 1229
        $request    = $this->getRequest();
16181 anderson 1230
        if ($request->isPost()) {
11339 nelberth 1231
            $id         = $this->params()->fromRoute('id');
1232
            $message    = trim(filter_var($this->params()->fromPost('message', ''), FILTER_SANITIZE_STRING));
16181 anderson 1233
 
1234
            if (!$id || empty($message)) {
11339 nelberth 1235
                return new JsonModel([
1236
                    'success' => false,
1237
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1238
                ]);
16181 anderson 1239
            }
1240
 
14590 efrain 1241
            $utilMapper = UtilMapper::getInstance($this->adapter);
1242
            $now = $utilMapper->getDatebaseNow();
16181 anderson 1243
 
11339 nelberth 1244
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1245
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 1246
 
11339 nelberth 1247
            $userMapper = UserMapper::getInstance($this->adapter);
1248
            $sender_result = $userMapper->fetchOne($currentUser->id);
1249
            $sender_name = trim($sender_result->first_name . ' ' . $sender_result->last_name);
1250
            $sender_pic = $this->url()->fromRoute('storage', [
1251
                'code' => $sender_result->uuid,
1252
                'type' => 'user',
1253
                'filename' => $sender_result->image
1254
            ]);
16181 anderson 1255
 
11339 nelberth 1256
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
1257
            $chatGroup = $chatGroupMapper->fetchOneByUuid($id);
16181 anderson 1258
            if ($chatGroup) {
1259
 
11339 nelberth 1260
                $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
1261
                $chatGroupUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 1262
 
1263
                if (!$chatGroupUser) {
11339 nelberth 1264
                    return new JsonModel([
1265
                        'success' => false,
1266
                        'data' => 'ERROR_CHAT_GROUP_YOU_NOT_MEMBER'
1267
                    ]);
1268
                }
16181 anderson 1269
 
11339 nelberth 1270
                $chatGroupMessage = new ChatGroupMessage();
1271
                $chatGroupMessage->sender_id = $currentUser->id;
1272
                $chatGroupMessage->group_id = $chatGroup->id;
1273
                $chatGroupMessage->content = $message;
1274
                $chatGroupMessage->type = ChatGroupMessage::TYPE_TEXT;
16181 anderson 1275
 
11339 nelberth 1276
                $chatGroupMessageMapper = ChatGroupMessageMapper::getInstance($this->adapter);
1277
                $result = $chatGroupMessageMapper->insert($chatGroupMessage);
16181 anderson 1278
                if (!$result) {
11339 nelberth 1279
                    return new JsonModel([
1280
                        'success' => false,
1281
                        'data' => $chatGroupMessageMapper->getError()
1282
                    ]);
1283
                }
1284
                $chatGroupMessage = $chatGroupMessageMapper->fetchOne($chatGroupMessage->id);
1285
 
16181 anderson 1286
 
11339 nelberth 1287
                $chatGroupUserMessage = new ChatGroupUserMessage();
1288
                $chatGroupUserMessage->group_id = $chatGroupMessage->group_id;
1289
                $chatGroupUserMessage->message_id = $chatGroupMessage->id;
1290
                $chatGroupUserMessage->receiver_id = $currentUser->id;
1291
                $chatGroupUserMessage->recd = ChatGroupUserMessage::RECD_YES;
1292
                $chatGroupUserMessage->seen = ChatGroupUserMessage::SEEN_NO;
16181 anderson 1293
 
11339 nelberth 1294
                $chatGroupUserMessageMapper = ChatGroupUserMessageMapper::getInstance($this->adapter);
1295
                $result = $chatGroupUserMessageMapper->insert($chatGroupUserMessage);
16181 anderson 1296
                if (!$result) {
11339 nelberth 1297
                    return new JsonModel([
1298
                        'success' => false,
1299
                        'data' => $chatGroupUserMessageMapper->getError()
1300
                    ]);
1301
                }
16181 anderson 1302
 
1303
 
11339 nelberth 1304
                $results = $chatGroupUserMapper->fetchAllByGroupId($chatGroup->id);
16181 anderson 1305
                foreach ($results as $r) {
11339 nelberth 1306
                    if ($r->user_id != $currentUser->id) {
1307
                        $chatGroupUserMessage               = new ChatGroupUserMessage();
1308
                        $chatGroupUserMessage->group_id     = $chatGroupMessage->group_id;
1309
                        $chatGroupUserMessage->message_id   = $chatGroupMessage->id;
1310
                        $chatGroupUserMessage->receiver_id  = $r->user_id;
1311
                        $chatGroupUserMessage->recd         = ChatGroupUserMessage::RECD_NO;
1312
                        $chatGroupUserMessage->seen         = ChatGroupUserMessage::SEEN_NO;
16181 anderson 1313
 
11339 nelberth 1314
                        $result = $chatGroupUserMessageMapper->insert($chatGroupUserMessage);
16181 anderson 1315
                        if (!$result) {
11339 nelberth 1316
                            return new JsonModel([
1317
                                'success' => false,
1318
                                'data' => $chatGroupUserMessageMapper->getError()
1319
                            ]);
1320
                        }
1321
                    }
1322
                }
16181 anderson 1323
 
14627 efrain 1324
                $userMapper->updateLastActivity($currentUser->id);
16181 anderson 1325
 
14590 efrain 1326
                $msgtime = $this->timeAgo($now, $now);
11339 nelberth 1327
                return new JsonModel([
1328
                    'success' => true,
1329
                    'data' => [
1330
                        'user_name'         => $sender_name,
1331
                        'user_id_encripted' => $sender_result->uuid,
1332
                        'user_image'        => $sender_pic,
1333
                        'u'                 => 1,
1334
                        'mtype'             => 'text',
1335
                        'm'                 => $message,
1336
                        'time'              => $msgtime,
1337
                        'id'                => $chatGroupMessage->uuid,
1338
                    ]
1339
                ]);
1340
            } else {
1341
                $userMapper = UserMapper::getInstance($this->adapter);
1342
                $user = $userMapper->fetchOneByUuid($id);
16181 anderson 1343
                if (!$user) {
11339 nelberth 1344
                    return new JsonModel([
1345
                        'success' => false,
1346
                        'data' => 'ERROR_USER_NOT_FOUND'
1347
                    ]);
1348
                }
16181 anderson 1349
 
1350
 
11339 nelberth 1351
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1352
                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 1353
                if (!$connection || $connection->status != Connection::STATUS_ACCEPTED) {
1354
 
11339 nelberth 1355
                    return new JsonModel([
1356
                        'success' => false,
1357
                        'data' => 'ERROR_THIS_USER_IS_NOT_A_CONNECTION'
1358
                    ]);
1359
                }
1360
                $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
1361
                $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 1362
                if (!$chatUser) {
11339 nelberth 1363
                    $chatUser = new ChatUser();
1364
                    $chatUser->user_id1 = $currentUser->id;
1365
                    $chatUser->user_id2 = $user->id;
16181 anderson 1366
 
11339 nelberth 1367
                    $response = $chatUserMapper->insert($chatUser);
16181 anderson 1368
                    if (!$response) {
11339 nelberth 1369
                        return new JsonModel([
1370
                            'success' => false,
1371
                            'data' => $chatUserMapper->getError()
1372
                        ]);
1373
                    }
16181 anderson 1374
 
11339 nelberth 1375
                    $chatUser = $chatUserMapper->fetchOne($chatUser->id);
1376
                    $fullpath_chat = $this->config['leaderslinked.fullpath.chat'];
1377
                    $dirpath = $fullpath_chat . $chatUser->uuid;
16181 anderson 1378
                    if (!file_exists($dirpath)) {
11339 nelberth 1379
                        mkdir($dirpath, 0777, true);
1380
                        chmod($dirpath, 0777);
1381
                    }
1382
                }
16181 anderson 1383
 
1384
 
1385
 
11339 nelberth 1386
                $chatMessage = new ChatMessage();
1387
                $chatMessage->chat_id   = $chatUser->id;
1388
                $chatMessage->from_id   = $currentUser->id;
1389
                $chatMessage->to_id     = $user->id;
1390
                $chatMessage->content   = $message;
1391
                $chatMessage->type      = ChatMessage::TYPE_TEXT;
1392
                $chatMessage->recd      = ChatMessage::RECD_NO;
1393
                $chatMessage->seen      = ChatMessage::SEEN_NO;
16181 anderson 1394
 
11339 nelberth 1395
                $chatMessageMapper = ChatMessageMapper::getInstance($this->adapter);
1396
                $result = $chatMessageMapper->insert($chatMessage);
16181 anderson 1397
                if (!$result) {
11339 nelberth 1398
                    return new JsonModel([
1399
                        'success' => false,
1400
                        'data' => $chatMessageMapper->getError()
1401
                    ]);
1402
                }
16181 anderson 1403
 
11339 nelberth 1404
                $chatMessage = $chatMessageMapper->fetchOne($chatMessage->id);
16181 anderson 1405
 
14590 efrain 1406
                $msgtime = $this->timeAgo($chatMessage->added_on, $now);
14627 efrain 1407
                $userMapper->updateLastActivity($currentUser->id);
16181 anderson 1408
 
1409
                if ($currentUser->id == $chatUser->user_id1) {
14688 efrain 1410
                    $chatUserMapper->markIsOpen2($chatUser->id);
14687 efrain 1411
                } else {
14688 efrain 1412
                    $chatUserMapper->markIsOpen1($chatUser->id);
14687 efrain 1413
                }
16181 anderson 1414
 
11339 nelberth 1415
                return new JsonModel([
1416
                    'success' => true,
1417
                    'data' => [
1418
                        'user_name'     => $sender_name,
1419
                        'user_id'       => $sender_result->uuid,
1420
                        'user_image'    => $sender_pic,
1421
                        'u'             => 1,
1422
                        'mtype'         => ChatMessage::TYPE_TEXT,
1423
                        'm'             => $message,
1424
                        'time'          => $msgtime,
1425
                        'id'            => $chatMessage->uuid,
1426
                    ]
16181 anderson 1427
                ]);
11339 nelberth 1428
            }
1429
            return new JsonModel($response);
1430
        } else {
1431
            return new JsonModel([
1432
                'success' => false,
1433
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1434
            ]);
1435
        }
16181 anderson 1436
    }
11339 nelberth 1437
 
1438
    /**
1439
     * Esta función recuperar los contactos disponibles para agregarlos a un grupo
1440
     * Es una petición GET el url que contiene el ID encriptado del chat (/chat/get-contacts-availables-for-group/:group_id) y la cuál se recibe en la función heartBeat.
1441
     * con el siguiente parámetro
1442
     * uid = id encriptado del usuario
1443
     * retorna un json en caso de ser  positivo
1444
     * [
1445
     *  'success' : true,
1446
     *  'data' : [
1447
     *     [
1448
     *       'id'                    => 'id del usuario encriptado',
1449
     *       'name'                  => 'nombre del usuario',
1450
     *       'image'                 => 'imagen del usuario',
1451
     *       'type'                  => 'user' //fixed,
1452
     *       'online'                => $online,
1453
     *     ]
1454
     * ]
1455
     * En caso de ser negativo puede haber 2 formatos
1456
     * [
1457
     *  'success' : false,
1458
     *  'data' : mensaje de error
1459
     * ]
1460
     * @return \Laminas\View\Model\JsonModel
1461
     */
1462
    public function contactAvailableGroupListAction()
1463
    {
1464
        $request    = $this->getRequest();
16181 anderson 1465
        if ($request->isGet()) {
11339 nelberth 1466
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1467
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 1468
 
11339 nelberth 1469
            $id = $this->params()->fromRoute('group_id');
16181 anderson 1470
            if (!$id) {
11339 nelberth 1471
                return new JsonModel([
1472
                    'success' => false,
1473
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1474
                ]);
16181 anderson 1475
            }
1476
 
11339 nelberth 1477
            $userMapper = UserMapper::getInstance($this->adapter);
1478
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
1479
            $chatGroup = $chatGroupMapper->fetchOneByUuid($id);
16181 anderson 1480
 
1481
            if (!$chatGroup) {
11339 nelberth 1482
                return new JsonModel([
1483
                    'success' => false,
1484
                    'data' => 'ERROR_GROUP_NOT_FOUND'
1485
                ]);
1486
            }
16181 anderson 1487
 
11339 nelberth 1488
            $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
1489
            $chatGroupOwner = $chatGroupUserMapper->fetchOwnerByGroupId($chatGroup->id);
16181 anderson 1490
 
1491
            if ($chatGroupOwner->user_id != $currentUser->id) {
11339 nelberth 1492
                return new JsonModel([
1493
                    'success' => false,
1494
                    'data' => 'ERROR_CHAT_GROUP_YOU_ARE_NOT_OWNER'
1495
                ]);
1496
            }
16181 anderson 1497
 
1498
 
1499
 
11339 nelberth 1500
            $contact_ids = [];
1501
            $contacts = $chatGroupUserMapper->fetchAllByGroupId($chatGroup->id);
16181 anderson 1502
            foreach ($contacts as $contact) {
11339 nelberth 1503
                array_push($contact_ids, $contact->user_id);
1504
            }
16181 anderson 1505
 
11339 nelberth 1506
            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1507
            $connection_ids = $connectionMapper->fetchAllConnectionsByUserReturnIds($currentUser->id);
16181 anderson 1508
            $connection_ids = array_filter($connection_ids, function ($var) use ($contact_ids) {
1509
                return !in_array($var, $contact_ids);
11339 nelberth 1510
            });
16181 anderson 1511
 
1512
 
11339 nelberth 1513
            $items = [];
16181 anderson 1514
            foreach ($connection_ids as $connection_id) {
11339 nelberth 1515
                $user = $userMapper->fetchOne($connection_id);
16181 anderson 1516
                if (!$user) {
11339 nelberth 1517
                    continue;
1518
                }
16181 anderson 1519
 
11339 nelberth 1520
                $name   = trim($user->first_name . ' ' . $user->last_name);
1521
                $image  = $this->url()->fromRoute('storage', [
1522
                    'code' => $user->uuid,
1523
                    'type' => 'user',
1524
                    'filename' => $user->image
1525
                ]);
1526
 
14590 efrain 1527
 
11339 nelberth 1528
 
16181 anderson 1529
 
11339 nelberth 1530
                array_push($items, [
1531
                    'id'        => $user->uuid,
1532
                    'name'      => $name,
1533
                    'image'     => $image,
14590 efrain 1534
                    'online'    => $user->online,
11339 nelberth 1535
                ]);
16181 anderson 1536
            }
1537
 
14627 efrain 1538
            $userMapper->updateLastActivity($currentUser->id);
16181 anderson 1539
 
11339 nelberth 1540
            return new JsonModel([
1541
                'success' => true,
1542
                'data' => $items,
1543
            ]);
1544
        } else {
1545
            return new JsonModel([
1546
                'success' => false,
1547
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1548
            ]);
1549
        }
1550
    }
1551
 
1552
    /**
1553
     * Esta función recuperar los contactos de un grupo
1554
     * Es una petición GET el url que contiene el ID encriptado del chat (/chat/get-contact-group-list/:group_id) y la cuál se recibe en la función heartBeat.
1555
     * con el siguiente parámetro
1556
     * uid = id encriptado del usuario
1557
     * retorna un json en caso de ser  positivo
1558
     * [
1559
     *  'success' : true,
1560
     *  'data' : [
1561
     *     [
1562
     *       'url_remove_from_group' => 'url para remover el usuario del grupo',
1563
     *       'id'                    => 'id del usuario encriptado',
1564
     *       'name'                  => 'nombre del usuario',
1565
     *       'image'                 => 'imagen del usuario',
1566
     *       'type'                  => 'user' //fixed,
1567
     *       'online'                => $online,
1568
     *     ]
1569
     * ]
1570
     * En caso de ser negativo puede haber 2 formatos
1571
     * [
1572
     *  'success' : false,
1573
     *  'data' : mensaje de error
1574
     * ]
1575
     * o
1576
     * [
1577
     *  'success' : false,
1578
     *  'data' : [
1579
     *      'fieldname' : [
1580
     *          'mensaje de error'
1581
     *      ]
1582
     *  ]
1583
     * ]
1584
     * @return \Laminas\View\Model\JsonModel
1585
     */
1586
 
1587
    public function contactGroupListAction()
1588
    {
16181 anderson 1589
 
11339 nelberth 1590
        $request    = $this->getRequest();
16181 anderson 1591
        if ($request->isGet()) {
11339 nelberth 1592
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1593
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 1594
 
11339 nelberth 1595
            $id = $this->params()->fromRoute('group_id');
16181 anderson 1596
            if (!$id) {
11339 nelberth 1597
                return new JsonModel([
1598
                    'success' => false,
1599
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1600
                ]);
16181 anderson 1601
            }
1602
 
11339 nelberth 1603
            $userMapper = UserMapper::getInstance($this->adapter);
1604
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
1605
            $chatGroup = $chatGroupMapper->fetchOneByUuid($id);
16181 anderson 1606
 
1607
            if (!$chatGroup) {
11339 nelberth 1608
                return new JsonModel([
1609
                    'success' => false,
1610
                    'data' => 'ERROR_GROUP_NOT_FOUND'
1611
                ]);
1612
            }
16181 anderson 1613
 
11339 nelberth 1614
            $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
16181 anderson 1615
 
11339 nelberth 1616
            $chatGroupUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 1617
 
1618
            if (!$chatGroupUser) {
11339 nelberth 1619
                return new JsonModel([
1620
                    'success' => false,
1621
                    'data' => 'ERROR_CHAT_GROUP_USER_NOT_FOUND'
1622
                ]);
1623
            }
1624
 
1625
            $items = [];
1626
            $chatGroupUsers = $chatGroupUserMapper->fetchAllByGroupId($chatGroup->id);
16181 anderson 1627
            foreach ($chatGroupUsers as $chatGroupUser) {
11339 nelberth 1628
                $user = $userMapper->fetchOne((int) $chatGroupUser->user_id);
16181 anderson 1629
                if (!$user) {
11339 nelberth 1630
                    continue;
1631
                }
16181 anderson 1632
 
11339 nelberth 1633
                $name   = trim($user->first_name . ' ' . $user->last_name);
1634
                $image  = $this->url()->fromRoute('storage', [
1635
                    'code' => $user->uuid,
1636
                    'type' => 'user',
1637
                    'filename' => $user->image
1638
                ]);
16181 anderson 1639
 
1640
 
1641
                if ($chatGroupUser->owner == ChatGroupUser::OWNER_YES) {
11339 nelberth 1642
                    $url_remove_from_group = '';
1643
                } else {
16181 anderson 1644
                    $url_remove_from_group = $this->url()->fromRoute('chat/remove-user-from-group', ['group_id' => $chatGroup->uuid, 'user_id' => $user->uuid]);
11339 nelberth 1645
                }
1646
 
14590 efrain 1647
 
16181 anderson 1648
 
1649
 
11339 nelberth 1650
                array_push($items, [
1651
                    'url_remove_from_group' => $url_remove_from_group,
1652
                    'id'                    => $user->uuid,
1653
                    'name'                  => $name,
1654
                    'image'                 => $image,
14590 efrain 1655
                    'online'                => $user->online,
11339 nelberth 1656
                ]);
1657
            }
16181 anderson 1658
 
14627 efrain 1659
            $userMapper->updateLastActivity($currentUser->id);
16181 anderson 1660
 
11339 nelberth 1661
            return new JsonModel([
16181 anderson 1662
                'success' => true,
11339 nelberth 1663
                'data' => $items,
1664
            ]);
1665
        } else {
1666
            return new JsonModel([
1667
                'success' => false,
1668
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1669
            ]);
1670
        }
1671
    }
16181 anderson 1672
 
11339 nelberth 1673
    /**
1674
     * Elimina un grupo de chat, solo el owner puede realizarla
1675
     * Es una petición POST el url que contiene el ID encriptado del chat (/chat/delete-group/:group_id) y la cuál se recibe en la función heartBeat.
1676
     * Parámetros del route
1677
     * :group_id = id del grupo encriptado
1678
     * En caso de una respuesta positiva
1679
     * [
1680
     *      'success' => true,
1681
     *      'data'=> (int) registros_borrados
1682
     * ]
1683
     * En caso de un respuesta negativa
1684
     * [
1685
     *      'success' => false,
1686
     *      'data' => (string) 'mensaje_de_error'
1687
     * ]
1688
     * @return \Laminas\View\Model\JsonModel
1689
     */
1690
    public function deleteGroupAction()
1691
    {
16181 anderson 1692
 
11339 nelberth 1693
        $request    = $this->getRequest();
16181 anderson 1694
        if ($request->isPost()) {
11339 nelberth 1695
 
1696
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1697
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 1698
 
11339 nelberth 1699
            $id = trim(filter_var($this->params()->fromRoute('group_id'), FILTER_SANITIZE_STRING));
16181 anderson 1700
            if (!$id) {
11339 nelberth 1701
                return new JsonModel([
1702
                    'success' => false,
1703
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1704
                ]);
16181 anderson 1705
            }
11339 nelberth 1706
 
16181 anderson 1707
 
1708
 
11339 nelberth 1709
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
1710
            $chatGroup = $chatGroupMapper->fetchOneByUuid($id);
16181 anderson 1711
 
1712
            if (!$chatGroup) {
11339 nelberth 1713
                return new JsonModel([
1714
                    'success' => false,
1715
                    'data' => 'ERROR_GROUP_NOT_FOUND'
1716
                ]);
1717
            }
16181 anderson 1718
 
11339 nelberth 1719
            $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
1720
            $chatGroupOwner = $chatGroupUserMapper->fetchOwnerByGroupId($chatGroup->id);
16181 anderson 1721
 
1722
            if ($chatGroupOwner->user_id != $currentUser->id) {
11339 nelberth 1723
                return new JsonModel([
1724
                    'success' => false,
1725
                    'data' => 'ERROR_CHAT_GROUP_YOU_ARE_NOT_OWNER'
1726
                ]);
1727
            }
1728
 
1729
 
1730
            $chatGroupUserMessageMapper = ChatGroupUserMessageMapper::getInstance($this->adapter);
1731
            $result = $chatGroupUserMessageMapper->deleteAllByGroupId($chatGroup->id);
16181 anderson 1732
            if (!$result) {
11339 nelberth 1733
                return new JsonModel([
1734
                    'success' => false,
1735
                    'data' => $chatGroupUserMessageMapper->getError()
1736
                ]);
1737
            }
16181 anderson 1738
 
11339 nelberth 1739
            $chatGroupMessageMapper = ChatGroupMessageMapper::getInstance($this->adapter);
1740
            $result = $chatGroupMessageMapper->deleteAllByGroupId($chatGroup->id);
16181 anderson 1741
            if (!$result) {
11339 nelberth 1742
                return new JsonModel([
1743
                    'success' => false,
1744
                    'data' => $chatGroupMessageMapper->getError()
1745
                ]);
1746
            }
16181 anderson 1747
 
11339 nelberth 1748
            $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
1749
            $result = $chatGroupUserMapper->deleteAllByGroupId($chatGroup->id);
16181 anderson 1750
            if (!$result) {
11339 nelberth 1751
                return new JsonModel([
1752
                    'success' => false,
1753
                    'data' => $chatGroupUserMapper->getError()
1754
                ]);
1755
            }
16181 anderson 1756
 
11339 nelberth 1757
            $chatGroupMapper->deleteByGroupId($chatGroup->id);
16181 anderson 1758
            if (!$result) {
11339 nelberth 1759
                return new JsonModel([
1760
                    'success' => false,
1761
                    'data' => $chatGroupMapper->getError()
1762
                ]);
1763
            }
16181 anderson 1764
 
1765
 
11339 nelberth 1766
            $fullpath_chat = $this->config['leaderslinked.fullpath.chat'];
1767
            $dirpath = $fullpath_chat . $chatGroup->uuid;
16181 anderson 1768
 
11339 nelberth 1769
            Functions::rmDirRecursive($dirpath);
16181 anderson 1770
 
14627 efrain 1771
            $userMapper = UserMapper::getInstance($this->adapter);
1772
            $userMapper->updateLastActivity($currentUser->id);
16181 anderson 1773
 
11339 nelberth 1774
            return new JsonModel([
1775
                'success' => true
1776
            ]);
1777
        } else {
1778
            return new JsonModel([
1779
                'success' => false,
1780
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1781
            ]);
1782
        }
1783
    }
1784
 
1785
    /**
1786
     * Cerrar el chat, consiste en borrar de la variable de sessión para que el mismo no se presente la siguiente vez abierto ,
1787
     * al menos que tenga mensajes sin leer
1788
     * Es una petición POST el url que contiene el ID encriptado del chat (/chat/close/:id)  y la cuál se recibe en la función heartBeat.
1789
     * Parámetros del route
1790
     * :id = id del chat encriptado
1791
     * En caso de una respuesta positiva
1792
     * [
1793
     *  'success' => true
1794
     * ]
1795
     * En caso de un respuesta negativa
1796
     * [
1797
     *  'success' => false,
1798
     *  'data'  => mensaje_de_error
1799
     * ]
1800
     * @return \Laminas\View\Model\JsonModel
1801
     */
1802
    public function closeAction()
1803
    {
1804
        $request    = $this->getRequest();
16181 anderson 1805
        if ($request->isPost()) {
11339 nelberth 1806
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1807
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 1808
 
11339 nelberth 1809
            $id = filter_var($this->params()->fromRoute('id'), FILTER_SANITIZE_STRING);
16181 anderson 1810
 
11339 nelberth 1811
            if (!$id) {
1812
                return new JsonModel([
1813
                    'success' => false,
1814
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1815
                ]);
1816
            }
16181 anderson 1817
 
1818
 
11339 nelberth 1819
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
1820
            $chatGroup = $chatGroupMapper->fetchOneByUuid($id);
1821
            if ($chatGroup) {
14627 efrain 1822
                $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
14692 efrain 1823
                $chatGroupUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 1824
 
1825
                if (!$chatGroupUser) {
14692 efrain 1826
                    return new JsonModel([
1827
                        'success' => false,
1828
                        'data' =>  'ERROR_CHAT_GROUP_YOU_NOT_MEMBER'
1829
                    ]);
1830
                }
16181 anderson 1831
 
14627 efrain 1832
                $chatGroupUserMapper->markIsClose($chatGroup->id, $currentUser->id);
11339 nelberth 1833
            } else {
16181 anderson 1834
 
11339 nelberth 1835
                $userMapper = UserMapper::getInstance($this->adapter);
1836
                $user = $userMapper->fetchOneByUuid($id);
16181 anderson 1837
                if (!$user) {
11339 nelberth 1838
                    return new JsonModel([
1839
                        'success' => false,
1840
                        'data' => 'ERROR_USER_NOT_FOUND'
1841
                    ]);
1842
                }
16181 anderson 1843
 
1844
 
11339 nelberth 1845
                $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
1846
                $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 1847
                if ($chatUser) {
1848
                    if ($currentUser->id == $chatUser->user_id1) {
14686 efrain 1849
                        $chatUserMapper->markIsClose1($currentUser->id);
14685 efrain 1850
                    } else {
16181 anderson 1851
 
14686 efrain 1852
                        $chatUserMapper->markIsClose2($currentUser->id);
14627 efrain 1853
                    }
11339 nelberth 1854
                }
1855
            }
16181 anderson 1856
 
14627 efrain 1857
            $userMapper->updateLastActivity($currentUser->id);
1858
 
16181 anderson 1859
 
1860
 
11339 nelberth 1861
            return new JsonModel([
1862
                'success' => true
1863
            ]);
1864
        } else {
1865
            return new JsonModel([
1866
                'success' => false,
1867
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1868
            ]);
1869
        }
1870
    }
1871
 
1872
    /**
1873
     * Clear como su nombre lo indica es borrar los mensajes entre el usuario actual y otro usuario con quien sostiene el chat
1874
     * Es una petición POST el url que contiene el ID encriptado del chat (/chat/clear/:id) y la cuál se recibe en la función heartBeat.
1875
     * Parámetros del route
1876
     * :id = id del usuario encriptado
1877
     * En caso de una respuesta positiva
1878
     * [
1879
     *      'success' => true,
1880
     *      'data'=> (int) registros_borrados
1881
     * ]
1882
     * En caso de un respuesta negativa
1883
     * [
1884
     *      'success' => false,
1885
     *      'data' => (string) 'mensaje_de_error'
1886
     * ]
1887
     * @return \Laminas\View\Model\JsonModel
1888
     */
1889
    public function clearAction()
1890
    {
1891
        $request    = $this->getRequest();
16181 anderson 1892
        if ($request->isPost()) {
11339 nelberth 1893
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1894
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 1895
 
11339 nelberth 1896
            $id = filter_var($this->params()->fromRoute('id'), FILTER_SANITIZE_STRING);
16181 anderson 1897
 
11339 nelberth 1898
            if (!$id) {
1899
                return new JsonModel([
1900
                    'success' => false,
1901
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1902
                ]);
1903
            }
14627 efrain 1904
 
16181 anderson 1905
 
1906
 
11339 nelberth 1907
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
1908
            $chatGroup = $chatGroupMapper->fetchOneByUuid($id);
1909
            if ($chatGroup) {
14627 efrain 1910
                $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
14692 efrain 1911
                $chatGroupUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 1912
 
1913
                if (!$chatGroupUser) {
14692 efrain 1914
                    return new JsonModel([
1915
                        'success' => false,
1916
                        'data' =>  'ERROR_CHAT_GROUP_YOU_NOT_MEMBER'
1917
                    ]);
1918
                }
16181 anderson 1919
 
14627 efrain 1920
                $chatGroupUserMapper->markIsClose($chatGroup->id, $currentUser->id);
11339 nelberth 1921
            } else {
16181 anderson 1922
 
11339 nelberth 1923
                $userMapper = UserMapper::getInstance($this->adapter);
1924
                $user = $userMapper->fetchOneByUuid($id);
16181 anderson 1925
                if (!$user) {
11339 nelberth 1926
                    return new JsonModel([
1927
                        'success' => false,
1928
                        'data' => 'ERROR_USER_NOT_FOUND'
1929
                    ]);
1930
                }
16181 anderson 1931
 
1932
 
11339 nelberth 1933
                $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
1934
                $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 1935
                if ($chatUser) {
1936
                    if ($currentUser->id == $chatUser->user_id1) {
14686 efrain 1937
                        $chatUserMapper->markIsClose1($currentUser->id);
1938
                    } else {
14685 efrain 1939
                        $chatUserMapper->markIsClose2($currentUser->id);
14627 efrain 1940
                    }
11339 nelberth 1941
                }
1942
            }
16181 anderson 1943
 
14627 efrain 1944
            $userMapper->updateLastActivity($currentUser->id);
1945
 
16181 anderson 1946
 
11339 nelberth 1947
            return new JsonModel([
1948
                'success' => true
1949
            ]);
1950
        } else {
1951
            return new JsonModel([
1952
                'success' => false,
1953
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1954
            ]);
1955
        }
1956
    }
16181 anderson 1957
 
14692 efrain 1958
    /**
1959
     * Marca como abierto el caht
1960
     * Es una petición POST el url que contiene el ID encriptado del chat (/chat/open/:id) y la cuál se recibe en la función heartBeat.
1961
     * Parámetros del route
1962
     * :id = id del usuario encriptado
1963
     * En caso de una respuesta positiva
1964
     * [
1965
     *      'success' => true,
1966
     *      'data'=> (int) registros_borrados
1967
     * ]
1968
     * En caso de un respuesta negativa
1969
     * [
1970
     *      'success' => false,
1971
     *      'data' => (string) 'mensaje_de_error'
1972
     * ]
1973
     * @return \Laminas\View\Model\JsonModel
1974
     */
1975
    public function openAction()
1976
    {
1977
        $request    = $this->getRequest();
16181 anderson 1978
        if ($request->isPost()) {
14692 efrain 1979
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1980
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 1981
 
14692 efrain 1982
            $id = filter_var($this->params()->fromRoute('id'), FILTER_SANITIZE_STRING);
16181 anderson 1983
 
14692 efrain 1984
            if (!$id) {
1985
                return new JsonModel([
1986
                    'success' => false,
1987
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1988
                ]);
1989
            }
16181 anderson 1990
 
1991
 
14692 efrain 1992
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
1993
            $chatGroup = $chatGroupMapper->fetchOneByUuid($id);
1994
            if ($chatGroup) {
1995
                $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
1996
                $chatGroupUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 1997
 
1998
                if (!$chatGroupUser) {
14692 efrain 1999
                    return new JsonModel([
2000
                        'success' => false,
2001
                        'data' =>  'ERROR_CHAT_GROUP_YOU_NOT_MEMBER'
2002
                    ]);
2003
                }
16181 anderson 2004
 
14692 efrain 2005
                $chatGroupUserMapper->markIsOpen($chatGroup->id, $currentUser->id);
2006
            } else {
16181 anderson 2007
 
14692 efrain 2008
                $userMapper = UserMapper::getInstance($this->adapter);
2009
                $user = $userMapper->fetchOneByUuid($id);
16181 anderson 2010
                if (!$user) {
14692 efrain 2011
                    return new JsonModel([
2012
                        'success' => false,
2013
                        'data' => 'ERROR_USER_NOT_FOUND'
2014
                    ]);
2015
                }
16181 anderson 2016
 
2017
 
14692 efrain 2018
                $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
2019
                $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 2020
                if ($chatUser) {
2021
                    if ($currentUser->id == $chatUser->user_id1) {
14692 efrain 2022
                        $chatUserMapper->markIsOpen1($chatUser->id);
2023
                    } else {
2024
                        $chatUserMapper->markIsOpen2($chatUser->id);
2025
                    }
2026
                }
2027
            }
16181 anderson 2028
 
2029
 
14692 efrain 2030
            $userMapper->updateLastActivity($currentUser->id);
16181 anderson 2031
 
14692 efrain 2032
            return new JsonModel([
2033
                'success' => true
2034
            ]);
2035
        } else {
2036
            return new JsonModel([
2037
                'success' => false,
2038
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2039
            ]);
2040
        }
2041
    }
16181 anderson 2042
 
11339 nelberth 2043
    public function uploadAction()
2044
    {
2045
        $request    = $this->getRequest();
16181 anderson 2046
        if ($request->isPost()) {
11339 nelberth 2047
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2048
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 2049
 
11339 nelberth 2050
            $id = filter_var($this->params()->fromRoute('id'), FILTER_SANITIZE_STRING);
2051
            if (!$id) {
2052
                return new JsonModel([
2053
                    'success' => false,
2054
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
2055
                ]);
2056
            }
16181 anderson 2057
 
11339 nelberth 2058
            $files = $this->getRequest()->getFiles()->toArray();
16181 anderson 2059
            if (!isset($files['file']) || !empty($files['file']['error'])) {
11339 nelberth 2060
                return new JsonModel([
2061
                    'success' => false,
2062
                    'data' => 'ERROR_FILE_NOT_UPLOAD'
2063
                ]);
2064
            }
16181 anderson 2065
 
11339 nelberth 2066
            $tmp_filename   = $files['file']['tmp_name'];
16181 anderson 2067
            if (!$this->validMimeType($tmp_filename)) {
11339 nelberth 2068
                return new JsonModel([
2069
                    'success' => false,
2070
                    'data' => 'ERROR_FILE_UPLODED_IS_NOT_VALID'
2071
                ]);
2072
            }
2073
 
16181 anderson 2074
 
11339 nelberth 2075
            $extensions     = explode('.', $files['file']['name']);
2076
            $extension      = strtolower(trim($extensions[count($extensions) - 1]));
2077
            $filename       = uniqid() . '.' . $extension;
2078
 
16181 anderson 2079
 
11339 nelberth 2080
            $mime_type = mime_content_type($tmp_filename);
16181 anderson 2081
            if ($mime_type == 'image/jpg' || $mime_type == 'image/jpeg' || $mime_type == 'image/png') {
11339 nelberth 2082
                $file_type = 'image';
16181 anderson 2083
            } else if ($mime_type == 'video/webm' || $mime_type == 'video/mpeg' || $mime_type == 'video/mpg' || $mime_type == 'video/mp4') {
11339 nelberth 2084
                $file_type = 'video';
16181 anderson 2085
            } else if ($mime_type == 'application/pdf') {
11339 nelberth 2086
                $file_type = 'document';
2087
            }
16181 anderson 2088
 
2089
 
11339 nelberth 2090
            $userMapper = UserMapper::getInstance($this->adapter);
2091
            $sender_result = $userMapper->fetchOne($currentUser->id);
2092
            $sender_from = trim($sender_result->first_name . ' ' . $sender_result->last_name);
2093
            $sender_pic = $this->url()->fromRoute('storage', [
2094
                'code' => $sender_result->uuid,
2095
                'type' => 'user',
2096
                'filename' => $sender_result->image
2097
            ]);
16181 anderson 2098
 
11339 nelberth 2099
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
2100
            $chatGroup = $chatGroupMapper->fetchOneByUuid($id);
16181 anderson 2101
            if ($chatGroup) {
2102
 
11339 nelberth 2103
                $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
2104
                $chatGroupUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 2105
 
2106
                if (!$chatGroupUser) {
11339 nelberth 2107
                    return new JsonModel([
2108
                        'success' => false,
2109
                        'data' => 'ERROR_CHAT_GROUP_YOU_NOT_MEMBER'
2110
                    ]);
2111
                }
2112
 
16181 anderson 2113
 
11339 nelberth 2114
                $fullpath_chat = $this->config['leaderslinked.fullpath.chat'];
2115
                $dirpath = $fullpath_chat . $chatGroup->uuid;
16181 anderson 2116
                if (!file_exists($dirpath)) {
11339 nelberth 2117
                    mkdir($dirpath, 0777, true);
2118
                    chmod($dirpath, 0777);
2119
                }
16181 anderson 2120
 
11339 nelberth 2121
                $full_filename = $dirpath . DIRECTORY_SEPARATOR . $filename;
16181 anderson 2122
                if (!move_uploaded_file($tmp_filename, $full_filename)) {
11339 nelberth 2123
                    return new JsonModel([
2124
                        'success' => false,
2125
                        'data' => 'ERROR_FILE_UPLOADED_NOT_MOVE'
2126
                    ]);
2127
                }
16181 anderson 2128
 
11339 nelberth 2129
                $chatGroupMessage = new ChatGroupMessage();
2130
                $chatGroupMessage->sender_id    = $currentUser->id;
2131
                $chatGroupMessage->group_id     = $chatGroup->id;
2132
                $chatGroupMessage->content      = $filename;
2133
                $chatGroupMessage->type         = $file_type;
16181 anderson 2134
 
11339 nelberth 2135
                $chatGroupMessageMapper = ChatGroupMessageMapper::getInstance($this->adapter);
2136
                $result = $chatGroupMessageMapper->insert($chatGroupMessage);
16181 anderson 2137
                if (!$result) {
11339 nelberth 2138
                    return new JsonModel([
2139
                        'success' => false,
2140
                        'data' => $chatGroupMessageMapper->getError()
2141
                    ]);
2142
                }
16181 anderson 2143
 
11339 nelberth 2144
                $chatGroupMessage = $chatGroupMessageMapper->fetchOne($chatGroupMessage->id);
16181 anderson 2145
 
2146
 
11339 nelberth 2147
                $chatGroupUserMessage = new ChatGroupUserMessage();
2148
                $chatGroupUserMessage->group_id = $chatGroupMessage->group_id;
2149
                $chatGroupUserMessage->message_id = $chatGroupMessage->id;
2150
                $chatGroupUserMessage->receiver_id = $currentUser->id;
2151
                $chatGroupUserMessage->recd = ChatGroupUserMessage::RECD_YES;
2152
                $chatGroupUserMessage->seen = ChatGroupUserMessage::SEEN_YES;
16181 anderson 2153
 
2154
 
11339 nelberth 2155
                $chatGroupUserMessageMapper = ChatGroupUserMessageMapper::getInstance($this->adapter);
2156
                $result = $chatGroupUserMessageMapper->insert($chatGroupUserMessage);
16181 anderson 2157
                if (!$result) {
11339 nelberth 2158
                    return new JsonModel([
2159
                        'success' => false,
2160
                        'data' => $chatGroupUserMessageMapper->getError()
2161
                    ]);
2162
                }
16181 anderson 2163
 
2164
 
2165
 
11339 nelberth 2166
                $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
16181 anderson 2167
 
11339 nelberth 2168
                $results = $chatGroupUserMapper->fetchAllByGroupId($chatGroup->id);
16181 anderson 2169
                foreach ($results as $r) {
11339 nelberth 2170
                    if ($r->user_id != $currentUser->id) {
2171
                        $chatGroupUserMessage = new ChatGroupUserMessage();
2172
                        $chatGroupUserMessage->group_id = $chatGroupMessage->group_id;
2173
                        $chatGroupUserMessage->message_id = $chatGroupMessage->id;
16181 anderson 2174
                        $chatGroupUserMessage->receiver_id = $r->user_id;
11339 nelberth 2175
                        $chatGroupUserMessage->recd = ChatGroupUserMessage::RECD_NO;
2176
                        $chatGroupUserMessage->seen = ChatGroupUserMessage::SEEN_NO;
16181 anderson 2177
 
11339 nelberth 2178
                        $result = $chatGroupUserMessageMapper->insert($chatGroupUserMessage);
16181 anderson 2179
                        if (!$result) {
11339 nelberth 2180
                            return new JsonModel([
2181
                                'success' => false,
2182
                                'data' => $chatGroupUserMessageMapper->getError()
2183
                            ]);
2184
                        }
2185
                    }
2186
                }
16181 anderson 2187
 
14627 efrain 2188
                $userMapper->updateLastActivity($currentUser->id);
16181 anderson 2189
 
14590 efrain 2190
                $utilMapper = UtilMapper::getInstance($this->adapter);
2191
                $now = $utilMapper->getDatebaseNow();
16181 anderson 2192
 
14590 efrain 2193
                $msgtime = $this->timeAgo($now, $now);
11339 nelberth 2194
                return new JsonModel([
2195
                    'success' => true,
2196
                    'data' => [
2197
                        'user_name'     => $sender_from,
2198
                        'user_id'       => $currentUser->uuid,
2199
                        'user_image'    => $sender_pic,
2200
                        'u'             => 1,
2201
                        'mtype'         => $file_type,
2202
                        'm'             => $this->url()->fromRoute('storage', ['code' => $chatGroup->uuid, 'type' => 'chat', 'filename' => $filename]),
2203
                        'time'          => $msgtime,
2204
                        'id'            => $chatGroupMessage->uuid
2205
                    ]
2206
                ]);
16181 anderson 2207
            } else {
11339 nelberth 2208
 
2209
                $user = $userMapper->fetchOneByUuid($id);
16181 anderson 2210
                if (!$user) {
11339 nelberth 2211
                    return new JsonModel([
2212
                        'success' => false,
2213
                        'data' => 'ERROR_USER_NOT_FOUND'
2214
                    ]);
2215
                }
16181 anderson 2216
 
11339 nelberth 2217
                $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
2218
                $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 2219
                if (!$chatUser) {
11339 nelberth 2220
                    return new JsonModel([
2221
                        'success' => false,
2222
                        'data' => 'ERROR_CHAT_NOT_FOUND'
2223
                    ]);
2224
                }
16181 anderson 2225
 
11339 nelberth 2226
                $fullpath_chat = $this->config['leaderslinked.fullpath.chat'];
2227
                $dirpath = $fullpath_chat . $chatUser->uuid;
16181 anderson 2228
 
2229
                if (!file_exists($dirpath)) {
11339 nelberth 2230
                    mkdir($dirpath, 0777, true);
2231
                    chmod($dirpath, 0777);
2232
                }
16181 anderson 2233
 
11339 nelberth 2234
                $full_filename = $dirpath . DIRECTORY_SEPARATOR . $filename;
16181 anderson 2235
                if (!move_uploaded_file($tmp_filename, $full_filename)) {
11339 nelberth 2236
                    return new JsonModel([
2237
                        'success' => false,
2238
                        'data' => 'ERROR_FILE_UPLOADED_NOT_MOVE'
2239
                    ]);
2240
                }
2241
 
2242
                $chatMessage = new ChatMessage();
2243
                $chatMessage->chat_id = $chatUser->id;
2244
                $chatMessage->from_id = $currentUser->id;
2245
                $chatMessage->to_id = $user->id;
2246
                $chatMessage->content = $filename;
2247
                $chatMessage->type = $file_type;
2248
                $chatMessage->recd = ChatMessage::RECD_NO;
2249
                $chatMessage->seen = ChatMessage::SEEN_NO;
16181 anderson 2250
 
2251
 
11339 nelberth 2252
                $chatMessageMapper = ChatMessageMapper::getInstance($this->adapter);
2253
                $result = $chatMessageMapper->insert($chatMessage);
16181 anderson 2254
                if (!$result) {
11339 nelberth 2255
                    return new JsonModel([
2256
                        'success' => false,
2257
                        'data' =>  $chatMessageMapper->getError()
2258
                    ]);
2259
                }
16181 anderson 2260
 
2261
 
14627 efrain 2262
                $userMapper->updateLastActivity($currentUser->id);
16181 anderson 2263
 
11339 nelberth 2264
                $chatMessage = $chatMessageMapper->fetchOne($chatMessage->id);
16181 anderson 2265
 
14590 efrain 2266
                $utilMapper = UtilMapper::getInstance($this->adapter);
2267
                $now = $utilMapper->getDatebaseNow();
16181 anderson 2268
 
14590 efrain 2269
                $msgtime = $this->timeAgo($chatMessage->added_on, $now);
11339 nelberth 2270
                return new JsonModel([
2271
                    'success' => true,
2272
                    'data' => [
2273
                        'user_name' => $sender_from,
2274
                        'user_id' => $currentUser->uuid,
2275
                        'user_image' => $sender_pic,
2276
                        'u' => 1,
2277
                        'mtype' => $file_type,
2278
                        'm' => $this->url()->fromRoute('storage', ['code' => $currentUser->uuid, 'type' => 'chat', 'filename' => $filename]),
2279
                        'time' => $msgtime,
2280
                        'id' => $chatMessage->uuid
2281
                    ]
2282
                ]);
2283
            }
2284
        } else {
2285
            return new JsonModel([
2286
                'success' => false,
2287
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2288
            ]);
2289
        }
2290
    }
2291
 
2292
    public function markSeenAction()
2293
    {
2294
        $request = $this->getRequest();
16181 anderson 2295
        if ($request->isPost()) {
11339 nelberth 2296
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2297
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 2298
 
11339 nelberth 2299
            $id = $this->params()->fromRoute('id');
2300
            if (!$id) {
2301
                return new JsonModel([
2302
                    'success' => false,
2303
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
2304
                ]);
2305
            }
16181 anderson 2306
 
11339 nelberth 2307
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
2308
            $chatGroup =  $chatGroupMapper->fetchOneByUuid($id);
16181 anderson 2309
 
2310
            if ($chatGroup) {
2311
 
11339 nelberth 2312
                $charGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
2313
                $chatGroupUser = $charGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 2314
 
2315
                if (!$chatGroupUser) {
11339 nelberth 2316
                    return new JsonModel([
2317
                        'success' => false,
2318
                        'data' =>  'ERROR_CHAT_GROUP_YOU_NOT_MEMBER'
2319
                    ]);
2320
                }
16181 anderson 2321
 
11339 nelberth 2322
                $charGroupUserMessage = ChatGroupUserMessageMapper::getInstance($this->adapter);
2323
                $result = $charGroupUserMessage->markAsSeenByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 2324
                if ($result) {
11339 nelberth 2325
                    return new JsonModel([
2326
                        'success' => true,
2327
                    ]);
2328
                } else {
2329
                    return new JsonModel([
2330
                        'success' => false,
2331
                        'data' =>  $charGroupUserMessage->getError()
2332
                    ]);
2333
                }
2334
            } else {
2335
                $userMapper = UserMapper::getInstance($this->adapter);
2336
                $user = $userMapper->fetchOneByUuid($id);
16181 anderson 2337
 
2338
                if (!$user) {
11339 nelberth 2339
                    return new JsonModel([
2340
                        'success' => false,
2341
                        'data' => 'ERROR_USER_NOT_FOUND'
2342
                    ]);
2343
                }
16181 anderson 2344
 
11339 nelberth 2345
                $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
2346
                $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 2347
                if (!$chatUser) {
11339 nelberth 2348
                    return new JsonModel([
2349
                        'success' => false,
2350
                        'data' => 'ERROR_CHAT_NOT_FOUND'
2351
                    ]);
2352
                }
16181 anderson 2353
 
11339 nelberth 2354
                $chatMessageMapper = ChatMessageMapper::getInstance($this->adapter);
2355
                $result = $chatMessageMapper->markAsSeenByChatIdAndToId($chatUser->id, $currentUser->id);
16181 anderson 2356
                if ($result) {
11339 nelberth 2357
                    return new JsonModel([
2358
                        'success' => true,
2359
                    ]);
2360
                } else {
2361
                    return new JsonModel([
2362
                        'success' => false,
2363
                        'data' =>  $charGroupUserMessage->getError()
2364
                    ]);
2365
                }
2366
            }
2367
        } else {
2368
            $response = [
2369
                'success' => false,
2370
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2371
            ];
2372
        }
2373
 
2374
        return new JsonModel($response);
2375
    }
16181 anderson 2376
 
2377
 
11339 nelberth 2378
    public function markReceivedAction()
2379
    {
2380
        $request = $this->getRequest();
16181 anderson 2381
        if ($request->isPost()) {
11339 nelberth 2382
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2383
            $currentUser = $currentUserPlugin->getUser();
16181 anderson 2384
 
11339 nelberth 2385
            $id = $this->params()->fromRoute('id');
2386
            if (!$id) {
2387
                return new JsonModel([
2388
                    'success' => false,
2389
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
2390
                ]);
2391
            }
16181 anderson 2392
 
11339 nelberth 2393
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
2394
            $chatGroup =  $chatGroupMapper->fetchOneByUuid($id);
16181 anderson 2395
 
2396
            if ($chatGroup) {
2397
 
11339 nelberth 2398
                $charGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
2399
                $chatGroupUser = $charGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 2400
 
2401
                if (!$chatGroupUser) {
11339 nelberth 2402
                    return new JsonModel([
2403
                        'success' => false,
2404
                        'data' =>  'ERROR_CHAT_GROUP_YOU_NOT_MEMBER'
2405
                    ]);
2406
                }
16181 anderson 2407
 
11339 nelberth 2408
                $charGroupUserMessage = ChatGroupUserMessageMapper::getInstance($this->adapter);
2409
                $result = $charGroupUserMessage->markAsReceivedByGroupIdAndUserId($chatGroup->id, $currentUser->id);
16181 anderson 2410
                if ($result) {
11339 nelberth 2411
                    return new JsonModel([
2412
                        'success' => true,
2413
                    ]);
2414
                } else {
2415
                    return new JsonModel([
2416
                        'success' => false,
2417
                        'data' =>  $charGroupUserMessage->getError()
2418
                    ]);
2419
                }
2420
            } else {
2421
                $userMapper = UserMapper::getInstance($this->adapter);
2422
                $user = $userMapper->fetchOneByUuid($id);
16181 anderson 2423
 
2424
                if (!$user) {
11339 nelberth 2425
                    return new JsonModel([
2426
                        'success' => false,
2427
                        'data' => 'ERROR_USER_NOT_FOUND'
2428
                    ]);
2429
                }
16181 anderson 2430
 
11339 nelberth 2431
                $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
2432
                $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
16181 anderson 2433
                if (!$chatUser) {
11339 nelberth 2434
                    return new JsonModel([
2435
                        'success' => false,
2436
                        'data' => 'ERROR_CHAT_NOT_FOUND'
2437
                    ]);
2438
                }
16181 anderson 2439
 
11339 nelberth 2440
                $chatMessageMapper = ChatMessageMapper::getInstance($this->adapter);
2441
                $result = $chatMessageMapper->markAsReceivedByChatIdAndToId($chatUser->id, $currentUser->id);
16181 anderson 2442
                if ($result) {
11339 nelberth 2443
                    return new JsonModel([
2444
                        'success' => true,
2445
                    ]);
2446
                } else {
2447
                    return new JsonModel([
2448
                        'success' => false,
2449
                        'data' =>  $charGroupUserMessage->getError()
2450
                    ]);
2451
                }
2452
            }
2453
        } else {
2454
            $response = [
2455
                'success' => false,
2456
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2457
            ];
2458
        }
16181 anderson 2459
 
11339 nelberth 2460
        return new JsonModel($response);
2461
    }
2462
 
2463
 
16181 anderson 2464
 
11339 nelberth 2465
    /**
2466
     *
2467
     * @param string $file
2468
     * @return boolean
2469
     */
2470
    private function validMimeType($file)
2471
    {
2472
        /*
2473
         * image/jpeg jpeg jpg jpe
2474
         * image/gif gif
2475
         * image/png png
2476
         * video/mp4
2477
         * audio/mpeg mpga mp2 mp2a mp3 m2a m3a
2478
         * video/x-flv flv
2479
         * application/msword doc dot
2480
         * application/vnd.openxmlformats-officedocument.wordprocessingml.document docx
2481
         * application/vnd.ms-excel xls xlm xla xlc xlt xlw
2482
         * application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx
2483
         * application/vnd.ms-powerpoint ppt pps pot
2484
         * application/vnd.openxmlformats-officedocument.presentationml.presentation pptx
2485
         * application/pdf pdf
2486
         */
2487
        $mime = mime_content_type($file);
2488
        $valid = false;
2489
        $types = [
2490
            'image/jpeg',
2491
            'image/gif',
2492
            'image/png',
2493
            'video/mp4',
2494
            'audio/mpeg',
2495
            'video/x-flv',
2496
            'application/msword',
2497
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
2498
            'application/vnd.ms-excel',
2499
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
2500
            'application/vnd.ms-powerpoint',
2501
            'application/vnd.openxmlformats-officedocument.presentationml.presentation',
2502
            'application/pdf'
2503
        ];
2504
        foreach ($types as $t) {
2505
            if (strpos($mime, $t) !== false) {
2506
                $valid = true;
2507
                break;
2508
            }
2509
        }
2510
        return $valid;
2511
    }
2512
 
2513
    /**
2514
     *
2515
     * @param string $text
2516
     * @return string
2517
     */
2518
    private function sanitize($text)
2519
    {
2520
        $text = htmlspecialchars($text, ENT_QUOTES);
2521
        $text = str_replace("\n\r", "\n", $text);
2522
        $text = str_replace("\r\n", "\n", $text);
2523
        $text = str_replace("\n", "<br>", $text);
2524
        return $text;
2525
    }
2526
 
2527
    /**
14590 efrain 2528
     *
11339 nelberth 2529
     * @param string $timestamp
14590 efrain 2530
     * @param string $now
11339 nelberth 2531
     * @return string
2532
     */
14590 efrain 2533
    private function timeAgo($timestamp, $now = '')
11339 nelberth 2534
    {
16181 anderson 2535
 
2536
        if ($now) {
14590 efrain 2537
            $datetime1 = \DateTime::createFromFormat('Y-m-d H:i:s', $now);
2538
        } else {
2539
            $now = date('Y-m-d H:i:s');
2540
            $datetime1 = date_create($now);
2541
        }
11339 nelberth 2542
        $datetime2 = date_create($timestamp);
16181 anderson 2543
 
11339 nelberth 2544
        $diff = date_diff($datetime1, $datetime2);
2545
        $timemsg = '';
2546
        if ($diff->y > 0) {
14590 efrain 2547
            $timemsg = $diff->y . ' año' . ($diff->y > 1 ? "s" : '');
11339 nelberth 2548
        } else if ($diff->m > 0) {
14590 efrain 2549
            $timemsg = $diff->m . ' mes' . ($diff->m > 1 ? "es" : '');
11339 nelberth 2550
        } else if ($diff->d > 0) {
2551
            $timemsg = $diff->d . ' dia' . ($diff->d > 1 ? "s" : '');
2552
        } else if ($diff->h > 0) {
2553
            $timemsg = $diff->h . ' hora' . ($diff->h > 1 ? "s" : '');
2554
        } else if ($diff->i > 0) {
2555
            $timemsg = $diff->i . ' minuto' . ($diff->i > 1 ? "s" : '');
2556
        } else if ($diff->s > 0) {
2557
            $timemsg = $diff->s . ' segundo' . ($diff->s > 1 ? "s" : '');
2558
        }
2559
        if (!$timemsg) {
2560
            $timemsg = "Ahora";
2561
        } else {
2562
            $timemsg = $timemsg . '';
2563
        }
2564
        return $timemsg;
2565
    }
2566
 
2567
    /**
2568
     *
2569
     * @param string $timestamp
2570
     * @return boolean
2571
     */
2572
    private function isInactiveConnection($timestamp)
2573
    {
2574
        if (empty($timestamp)) {
2575
            return true;
2576
        }
2577
 
2578
        $now = date('Y-m-d H:i:s');
2579
        $datetime1 = date_create($now);
2580
        $datetime2 = date_create($timestamp);
2581
        $diff = date_diff($datetime1, $datetime2);
2582
 
2583
        if ($diff->y > 0 || $diff->m > 0 || $diff->d > 0 || $diff->h > 0 || $diff->i > 0) {
2584
            return true;
2585
        }
2586
 
2587
        return ($diff->s) > 15 ? true : false;
2588
    }
16292 anderson 2589
 
2590
    public function zoomAction()
2591
    {
2592
        $request = $this->getRequest();
2593
        if ($request->isPost()) {
2594
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2595
            $currentUser = $currentUserPlugin->getUser();
2596
            $id = $this->params()->fromRoute('id');
2597
 
2598
            if (!$id) {
2599
                return new JsonModel([
2600
                    'success' => false,
2601
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
2602
                ]);
2603
            }
2604
 
2605
            $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
2606
            $chatGroupMapper = ChatGroupMapper::getInstance($this->adapter);
2607
            $chatUser = null;
2608
            $chatGroup = $chatGroupMapper->fetchOneByUuid($id);
2609
 
2610
            if ($chatGroup) {
2611
                $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
2612
                $chatGroupUser = $chatGroupUserMapper->fetchOneByGroupIdAndUserId($chatGroup->id, $currentUser->id);
2613
 
2614
                if (!$chatGroupUser) {
2615
                    $data = [
2616
                        'success' => false,
2617
                        'data' =>  'ERROR_ZOOM_CHAT_UNAUTHORIZE'
2618
                    ];
2619
                    return new JsonModel($data);
2620
                }
2621
            } else {
2622
                $userMapper = UserMapper::getInstance($this->adapter);
2623
                $user = $userMapper->fetchOneByUuid($id);
2624
 
2625
                if (!$user) {
2626
                    return new JsonModel([
2627
                        'success' => false,
2628
                        'data' => 'ERROR_USER_NOT_FOUND'
2629
                    ]);
2630
                }
2631
 
2632
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
2633
                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
2634
 
2635
                if (!$connection || $connection->status != Connection::STATUS_ACCEPTED) {
2636
 
2637
                    return new JsonModel([
2638
                        'success' => false,
2639
                        'data' => 'ERROR_THIS_USER_IS_NOT_A_CONNECTION'
2640
                    ]);
2641
                }
2642
 
2643
                $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
2644
                $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
2645
 
2646
                if (!$chatUser) {
2647
                    $chatUser = new ChatUser();
2648
                    $chatUser->user_id1 = $currentUser->id;
2649
                    $chatUser->user_id2 = $user->id;
2650
                    $response = $chatUserMapper->insert($chatUser);
2651
 
2652
                    if (!$response) {
2653
                        return new JsonModel([
2654
                            'success' => false,
2655
                            'data' => $chatUserMapper->getError()
2656
                        ]);
2657
                    }
2658
 
2659
                    $chatUser = $chatUserMapper->fetchOne($chatUser->id);
2660
                    $fullpath_chat = $this->config['leaderslinked.fullpath.chat'];
2661
                    $dirpath = $fullpath_chat . $chatUser->uuid;
2662
 
2663
                    if (!file_exists($dirpath)) {
2664
                        mkdir($dirpath, 0777, true);
2665
                        chmod($dirpath, 0777);
2666
                    }
2667
                }
2668
            }
2669
 
2670
            if (!$chatUser && !$chatGroup) {
2671
                $data = [
2672
                    'success' => false,
2673
                    'data' => 'ERROR_ZOOM_CHAT_NOT_FOUND'
2674
                ];
2675
                return new JsonModel($data);
2676
            }
2677
 
2678
            $dataPost = $request->getPost()->toArray();
2679
            $form = new ZoomAddForm();
16293 anderson 2680
            //Anderson
16292 anderson 2681
            $form->setData($dataPost);
2682
 
2683
            if ($form->isValid()) {
2684
                $dataPost = (array) $form->getData();
2685
                $dtStart = \DateTime::createFromFormat('Y-m-d H:i:s', $dataPost['date'] . ' ' . $dataPost['time']);
2686
                if (!$dtStart) {
2687
                    return new JsonModel([
2688
                        'success' => false,
2689
                        'data' => 'ERROR_PARAMETERS_ARE_INVALID'
2690
                    ]);
2691
                }
2692
 
2693
                $dtEnd = \DateTime::createFromFormat('Y-m-d H:i:s', $dataPost['date'] . ' ' . $dataPost['time']);
2694
                $dtEnd->add(new \DateInterval('PT' . $dataPost['duration'] . 'M'));
2695
                $start_time = $dtStart->format('Y-m-d\TH:i:s');
2696
                $zoom = new Zoom($this->adapter, $this->config, $this->cache);
2697
                $response =  $zoom->getOAuthAccessToken();
2698
 
2699
                if ($response['success']) {
2700
                    $access_token = $response['data'];
2701
                    $result = $zoom->addMeeting($access_token, $dataPost['title'], $dataPost['description'], $dataPost['type'], $start_time, $dataPost['duration'], $dataPost['timezone'], $dataPost['password']);
2702
                } else {
2703
                    return new JsonModel([
2704
                        'success' => false,
2705
                        'data' => 'ERROR_ZOOM_CREATING_NEW_MEETING'
2706
                    ]);
2707
                }
2708
 
2709
                if ($result['success']) {
2710
                    $zoomMeetingMapper = ZoomMeetingMapper::getInstance($this->adapter);
2711
                    $zoomMeeting = $zoomMeetingMapper->fetchOne($result['data']['id']);
2712
 
2713
                    if (!$zoomMeeting) {
2714
                        $zoomMeeting = new ZoomMeeting();
2715
                        $zoomMeeting->id = $result['data']['id'];
2716
                        $zoomMeeting->topic = $dataPost['title'];
2717
                        $zoomMeeting->agenda = $dataPost['description'];
2718
                        $zoomMeeting->duration = $dataPost['duration'];
2719
                        $zoomMeeting->join_url = $result['data']['join_url'];
2720
                        $zoomMeeting->start_time = $dtStart->format('Y-m-d H:i:s');
2721
                        $zoomMeeting->end_time = $dtEnd->format('Y-m-d H:i:s');
2722
                        $zoomMeeting->timezone = $dataPost['timezone'];
2723
                        $zoomMeeting->type = $dataPost['type'];
2724
                        $zoomMeeting->uuid = $result['data']['uuid'];
2725
                        $zoomMeeting->password = $dataPost['password'];
2726
 
2727
                        if (!$zoomMeetingMapper->insert($zoomMeeting)) {
2728
                            return new JsonModel([
2729
                                'success' => false,
2730
                                'data' => $zoomMeetingMapper->getError()
2731
                            ]);
2732
                        }
2733
                    }
2734
 
2735
                    $chatMessageContent = "LABEL_ZOOM_MEETING \r\n" .
2736
                        " LABEL_ZOOM_MEETING_START_DATE : " . $dtStart->format('Y-m-d') . "\r\n" .
2737
                        " LABEL_ZOOM_MEETING_START_TIME : " . $dtStart->format('H:i a') . "\r\n" .
2738
                        " LABEL_ZOOM_MEETING_TIMEZONE : " . $zoomMeeting->timezone . "\r\n" .
2739
                        " LABEL_ZOOM_MEETING_TITLE :  " . $zoomMeeting->topic  . "\r\n" .
2740
                        " LABEL_ZOOM_MEETING_URL : " . $zoomMeeting->join_url . "\r\n" .
2741
                        " LABEL_ZOOM_MEETING_PASSWORD : " . $zoomMeeting->password . "\r\n";
2742
                    $zoomMeetingUserMapper = ZoomMeetingUserMapper::getInstance($this->adapter);
2743
                    $zoomMeetingUser = $zoomMeetingUserMapper->fetchOneByZoomMeetingIdAndUserId($zoomMeeting->id, $currentUser->id);
2744
 
2745
                    if (!$zoomMeetingUser) {
2746
                        $zoomMeetingUser = new ZoomMeetingUser();
2747
                        $zoomMeetingUser->zoom_meeting_id = $zoomMeeting->id;
2748
                        $zoomMeetingUser->user_id = $currentUser->id;
2749
                        $zoomMeetingUser->type = ZoomMeetingUser::TYPE_CREATOR;
2750
                        $zoomMeetingUserMapper->insert($zoomMeetingUser);
2751
                    }
2752
 
2753
                    if ($chatUser) {
2754
                        if ($chatUser->user_id1 == $currentUser->id) {
2755
                            $zoomMeetingUser = $zoomMeetingUserMapper->fetchOneByZoomMeetingIdAndUserId($zoomMeeting->id, $chatUser->user_id2);
2756
 
2757
                            if (!$zoomMeetingUser) {
2758
                                $zoomMeetingUser = new ZoomMeetingUser();
2759
                                $zoomMeetingUser->zoom_meeting_id = $zoomMeeting->id;
2760
                                $zoomMeetingUser->user_id = $chatUser->user_id2;
2761
                                $zoomMeetingUser->type = ZoomMeetingUser::TYPE_CREATOR;
2762
                                $zoomMeetingUserMapper->insert($zoomMeetingUser);
2763
                            }
2764
                        } else {
2765
                            $zoomMeetingUser = $zoomMeetingUserMapper->fetchOneByZoomMeetingIdAndUserId($zoomMeeting->id, $chatUser->user_id1);
2766
 
2767
                            if (!$zoomMeetingUser) {
2768
                                $zoomMeetingUser = new ZoomMeetingUser();
2769
                                $zoomMeetingUser->zoom_meeting_id = $zoomMeeting->id;
2770
                                $zoomMeetingUser->user_id = $chatUser->user_id1;
2771
                                $zoomMeetingUser->type = ZoomMeetingUser::TYPE_CREATOR;
2772
                                $zoomMeetingUserMapper->insert($zoomMeetingUser);
2773
                            }
2774
                        }
2775
 
2776
                        $chatMessage = new ChatMessage();
2777
                        $chatMessage->recd = ChatMessage::RECD_NO;
2778
                        $chatMessage->seen = ChatMessage::SEEN_NO;
2779
                        $chatMessage->type = ChatMessage::TYPE_TEXT;
2780
                        $chatMessage->content = $chatMessageContent;
2781
                        $chatMessage->from_id = $currentUser->id;
2782
                        $chatMessage->to_id = $chatUser->user_id1 == $currentUser->id ? $chatUser->user_id2 : $chatUser->user_id1;
2783
                        $chatMessage->chat_id = $chatUser->id;
2784
                        $chatMessageMapper = ChatMessageMapper::getInstance($this->adapter);
2785
                        $chatMessageMapper->insert($chatMessage);
2786
                        $chatUserMapper->markIsOpen1($chatUser->id);
2787
                        $chatUserMapper->markIsOpen2($chatUser->id);
2788
                    } else if ($chatGroup) {
2789
 
2790
                        $chatGroupMessage = new ChatGroupMessage();
2791
                        $chatGroupMessage->group_id = $chatGroup->id;
2792
                        $chatGroupMessage->content = $chatMessageContent;
2793
                        $chatGroupMessage->sender_id = $currentUser->id;
2794
                        $chatGroupMessage->type = ChatGroupMessage::TYPE_TEXT;
2795
                        $chatGroupMessageMapper = ChatGroupMessageMapper::getInstance($this->adapter);
2796
 
2797
                        if ($chatGroupMessageMapper->insert($chatGroupMessage)) {
2798
                            $chatGroupUserMapper = ChatGroupUserMapper::getInstance($this->adapter);
2799
                            $groupUsers =   $chatGroupUserMapper->fetchAllByGroupId($chatGroup->id);
2800
                            $chatGroupUserMessageMapper = ChatGroupUserMessageMapper::getInstance($this->adapter);
2801
                            foreach ($groupUsers as $groupUser) {
2802
                                if ($groupUser->user_id != $currentUser->id) {
2803
                                    $zoomMeetingUser = $zoomMeetingUserMapper->fetchOneByZoomMeetingIdAndUserId($zoomMeeting->id, $groupUser->user_id);
2804
 
2805
                                    if (!$zoomMeetingUser) {
2806
                                        $zoomMeetingUser = new ZoomMeetingUser();
2807
                                        $zoomMeetingUser->zoom_meeting_id = $zoomMeeting->id;
2808
                                        $zoomMeetingUser->user_id = $groupUser->user_id;
2809
                                        $zoomMeetingUser->type = ZoomMeetingUser::TYPE_CREATOR;
2810
                                        $zoomMeetingUserMapper->insert($zoomMeetingUser);
2811
                                    }
2812
                                }
2813
 
2814
                                $chatGroupUserMessage = new ChatGroupUserMessage();
2815
                                $chatGroupUserMessage->group_id = $chatGroup->id;
2816
                                $chatGroupUserMessage->message_id = $chatGroupMessage->id;
2817
                                $chatGroupUserMessage->receiver_id = $groupUser->user_id;
2818
                                $chatGroupUserMessage->recd = ChatGroupUserMessage::RECD_NO;
2819
                                $chatGroupUserMessage->seen = ChatGroupUserMessage::SEEN_NO;
2820
                                $chatGroupUserMessageMapper->insert($chatGroupUserMessage);
2821
                                $chatGroupUserMapper->markIsOpen($groupUser->group_id, $groupUser->user_id);
2822
                            }
2823
                        }
2824
                    }
2825
 
2826
                    return new JsonModel([
2827
                        'success' => true,
2828
                        'data' => 'LABEL_ZOOM_NEW_MEETING_SUCCESSFULLY'
2829
                    ]);
2830
                } else {
2831
                    return new JsonModel([
2832
                        'success' => false,
2833
                        'data' => 'ERROR_ZOOM_CREATING_NEW_MEETING'
2834
                    ]);
2835
                }
2836
            } else {
2837
                $messages = [];
2838
                $form_messages = (array) $form->getMessages();
2839
                foreach ($form_messages  as $fieldname => $field_messages) {
2840
                    $messages[$fieldname] = array_values($field_messages);
2841
                }
2842
 
2843
                return new JsonModel([
2844
                    'success'   => false,
2845
                    'data'   => $messages
2846
                ]);
2847
 
2848
                return new JsonModel($response);
2849
            }
2850
        } else {
2851
            $response = [
2852
                'success' => false,
2853
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2854
            ];
2855
        }
2856
 
2857
        return new JsonModel($response);
2858
    }
2859
 
2860
 
2861
    public function usersAction()
2862
    {
2863
        $currentUserPlugin = $this->plugin('currentUserPlugin');
2864
        $currentUser = $currentUserPlugin->getUser();
2865
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
2866
        $currentNetwork = $currentNetworkPlugin->getNetwork();
2867
        $request = $this->getRequest();
2868
 
2869
        if ($request->isGet()) {
2870
            $items = [];
2871
            $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
2872
            $search = trim(filter_var($this->params()->fromQuery('search', ''), FILTER_SANITIZE_STRING));
2873
 
2874
            if (strlen($search) >= 3) {
2875
                $user_ids = [];
2876
                $userMapper = UserMapper::getInstance($this->adapter);
2877
 
2878
                if ($currentNetwork->relationship_user_mode == Network::RELATIONSHIP_USER_MODE_USER_2_USER) {
2879
 
2880
                    $connectionMapper = ConnectionMapper::getInstance($this->adapter);
2881
                    $user_ids = $connectionMapper->fetchAllConnectionsByUserReturnIds($currentUser->id);
2882
                } else {
2883
                    if ($currentNetwork->default == Network::DEFAULT_YES) {
2884
                        $user_ids = $userMapper->fetchAllIdsByDefaultNetworkId($currentNetwork->id, $currentUser->id);
2885
                    } else {
2886
                        $user_ids = $userMapper->fetchAllIdsByNonDefaultNetworkId($currentNetwork->id, $currentUser->id);
2887
                    }
2888
                }
2889
 
2890
                $items = [];
16303 efrain 2891
                $records = $userMapper->fetchAllByIdsAndSearch($user_ids, $search, $currentUser->id);
16292 anderson 2892
 
2893
                foreach ($records as $record) {
2894
                    $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $record->id);
2895
                    if ($chatUser) {
2896
                        $link_send = $this->url()->fromRoute('chat/send', ['id' => $record->uuid]);
2897
                    } else {
2898
                        $link_send = '';
2899
                    }
2900
 
2901
                    $link_open_or_create = $this->url()->fromRoute('chat/open-or-create', ['id' => $record->uuid]);
2902
                    array_push($items, [
2903
                        'name'  => trim($record->first_name .  '  ' . $record->last_name) . ' (' . $record->email . ')',
2904
                        'image' => $this->url()->fromRoute('storage', ['code' => $record->uuid, 'type' => 'user', 'filename' => $record->image]),
2905
                        'link_send' => $link_send,
2906
                        'link_open_or_create' => $link_open_or_create,
2907
                    ]);
2908
                }
2909
            }
2910
 
2911
            $response = [
2912
                'success' => true,
2913
                'data' => $items
2914
            ];
2915
        } else {
2916
            $response = [
2917
                'success' => false,
2918
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2919
            ];
2920
        }
2921
 
2922
        return new JsonModel($response);
2923
    }
2924
 
2925
    public function openOrCreateAction()
2926
    {
2927
        $request    = $this->getRequest();
2928
        if ($request->isPost()) {
2929
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2930
            $currentUser = $currentUserPlugin->getUser();
2931
 
2932
            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
2933
            $currentNetwork = $currentNetworkPlugin->getNetwork();
2934
 
2935
 
2936
            $id = filter_var($this->params()->fromRoute('id'), FILTER_SANITIZE_STRING);
2937
 
2938
            if (!$id) {
2939
                return new JsonModel([
2940
                    'success' => false,
2941
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
2942
                ]);
2943
            }
2944
 
2945
            $userMapper = UserMapper::getInstance($this->adapter);
2946
            $user = $userMapper->fetchOneByUuid($id);
2947
 
2948
            if (!$user) {
2949
                return new JsonModel([
2950
                    'success' => false,
2951
                    'data' => 'ERROR_USER_NOT_FOUND'
2952
                ]);
2953
            }
2954
 
2955
            if ($user->email_verified == User::EMAIL_VERIFIED_NO || $user->status != User::STATUS_ACTIVE) {
2956
                return new JsonModel([
2957
                    'success' => false,
2958
                    'data' => 'ERROR_USER_IS_INACTIVE'
2959
                ]);
2960
            }
2961
 
2962
            if ($user->network_id != $currentUser->network_id) {
2963
                return new JsonModel([
2964
                    'success' => false,
2965
                    'data' => 'ERROR_USER_IS_INACTIVE'
2966
                ]);
2967
            }
2968
 
2969
            if ($currentNetwork->relationship_user_mode == Network::RELATIONSHIP_USER_MODE_USER_2_USER) {
2970
 
2971
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
2972
                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
2973
 
2974
                if (!$connection) {
2975
                    return new JsonModel([
2976
                        'success' => false,
2977
                        'data' =>  'ERROR_CONNECTION_NOT_ACTIVE'
2978
                    ]);
2979
                }
2980
            }
2981
 
2982
            $chatUserMapper = ChatUserMapper::getInstance($this->adapter);
2983
            $chatUser = $chatUserMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
2984
            if ($chatUser) {
2985
                if ($currentUser->id == $chatUser->user_id1) {
2986
                    $chatUserMapper->markIsOpen1($chatUser->id);
2987
                } else {
2988
                    $chatUserMapper->markIsOpen2($chatUser->id);
2989
                }
2990
            } else {
2991
                $chatUser = new ChatUser();
2992
                $chatUser->user_id1 = $currentUser->id;
2993
                $chatUser->user_id2 = $user->id;
2994
                $chatUser->user_open1 = ChatUser::OPEN_YES;
2995
                $chatUser->user_open2 = ChatUser::OPEN_NO;
2996
 
2997
 
2998
                if (!$chatUserMapper->insert($chatUser)) {
2999
                    return new JsonModel([
3000
                        'success' => false,
3001
                        'data' =>  $chatUserMapper->getError()
3002
                    ]);
3003
                }
3004
            }
3005
 
3006
            $utilMapper = UtilMapper::getInstance($this->adapter);
3007
            $now = $utilMapper->getDatebaseNow();
3008
 
3009
            $chatMessageMapper = ChatMessageMapper::getInstance($this->adapter);
3010
            $count_not_received_messages = $chatMessageMapper->countNotReceivedMessagesByChatIdAndToId($chatUser->id, $currentUser->id);
3011
            $count_not_seen_messages = $chatMessageMapper->countNotSeenMessagesByChatIdAndToId($chatUser->id, $currentUser->id);
3012
            $lastMessage = $chatMessageMapper->fetchLastMessage($chatUser->id, $currentUser->id);
3013
 
3014
            if ($lastMessage) {
3015
                $lastMessage = Functions::timeAgo($lastMessage->added_on, $now);
3016
            } else {
3017
                $lastMessage = '';
3018
            }
3019
 
3020
            if ($currentUser->id == $chatUser->user_id1) {
3021
                $is_open = $chatUser->user_open1 == ChatUser::OPEN_YES;
3022
            } else {
3023
                $is_open = $chatUser->user_open2 == ChatUser::OPEN_YES;
3024
            }
3025
 
3026
 
3027
            $not_received_messages = $count_not_received_messages > 0;
3028
            $not_seen_messages = $count_not_seen_messages > 0;
3029
 
3030
            $data = [
3031
                'url_clear'                 => $this->url()->fromRoute('chat/clear', ['id' => $user->uuid]),
3032
                'url_close'                 => $this->url()->fromRoute('chat/close', ['id' => $user->uuid]),
3033
                'url_open'                  => $this->url()->fromRoute('chat/open', ['id' => $user->uuid]),
3034
                'url_send'                  => $this->url()->fromRoute('chat/send', ['id' => $user->uuid]),
3035
                'url_upload'                => $this->url()->fromRoute('chat/upload', ['id' => $user->uuid]),
3036
                'url_mark_seen'             => $this->url()->fromRoute('chat/mark-seen', ['id' => $user->uuid]),
3037
                'url_mark_received'         => $this->url()->fromRoute('chat/mark-received', ['id' => $user->uuid]),
3038
                'url_get_all_messages'      => $this->url()->fromRoute('chat/get-all-messages', ['id' => $user->uuid]),
3039
                'url_zoom'                  => $this->url()->fromRoute('chat/zoom', ['id' => $user->uuid, 'type' => 'chat']),
3040
                'id'                        => $user->uuid,
3041
                'name'                      => trim($user->first_name . ' ' . $user->last_name),
3042
                'image'                     => $this->url()->fromRoute('storage', ['code' => $user->uuid, 'type' => 'user', 'filename' => $user->image]),
3043
                'profile'                   => $this->url()->fromRoute('profile/view', ['id' => $user->uuid]),
3044
                'type'                      => 'user',
3045
                'online'                    => $user->online ? 1 : 0,
3046
                'is_open'                   => $is_open ? 1 : 0,
3047
                'not_seen_messages'         => $not_seen_messages,
3048
                'not_received_messages'     => $not_received_messages,
3049
                'count_not_seen_messages'       => $count_not_seen_messages,
3050
                'count_not_received_messages'   => $count_not_received_messages,
3051
                'last_message'                  => $lastMessage
3052
            ];
3053
 
3054
 
3055
 
3056
            $userMapper->updateLastActivity($currentUser->id);
3057
 
3058
            return new JsonModel([
3059
                'success' => true,
3060
                'data' => $data,
3061
            ]);
3062
        } else {
3063
            return new JsonModel([
3064
                'success' => false,
3065
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
3066
            ]);
3067
        }
3068
    }
11339 nelberth 3069
}