Proyectos de Subversion LeadersLinked - Backend

Rev

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

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