Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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