Proyectos de Subversion LeadersLinked - Backend

Rev

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

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