Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

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