Proyectos de Subversion LeadersLinked - Backend

Rev

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