Proyectos de Subversion LeadersLinked - Backend

Rev

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