Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17002 | | Comparar con el anterior | Ultima modificación | Ver Log |

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