/**
  * Returns rendered message content.
  *
  * @param WiseChatMessage $message
  *
  * @return string HTML source
  */
 private function getRenderedMessageContent($message)
 {
     $formattedMessage = htmlspecialchars($message->getText(), ENT_QUOTES, 'UTF-8');
     /** @var WiseChatLinksPostFilter $linksFilter */
     $linksFilter = WiseChatContainer::get('rendering/filters/post/WiseChatLinksPostFilter');
     $formattedMessage = $linksFilter->filter($formattedMessage, $this->options->isOptionEnabled('allow_post_links'));
     /** @var WiseChatAttachmentsPostFilter $attachmentsFilter */
     $attachmentsFilter = WiseChatContainer::get('rendering/filters/post/WiseChatAttachmentsPostFilter');
     $formattedMessage = $attachmentsFilter->filter($formattedMessage, $this->options->isOptionEnabled('enable_attachments_uploader'), $this->options->isOptionEnabled('allow_post_links'));
     /** @var WiseChatImagesPostFilter $imagesFilter */
     $imagesFilter = WiseChatContainer::get('rendering/filters/post/WiseChatImagesPostFilter');
     $formattedMessage = $imagesFilter->filter($formattedMessage, $this->options->isOptionEnabled('allow_post_images'), $this->options->isOptionEnabled('allow_post_links'));
     /** @var WiseChatYouTubePostFilter $youTubeFilter */
     $youTubeFilter = WiseChatContainer::get('rendering/filters/post/WiseChatYouTubePostFilter');
     $formattedMessage = $youTubeFilter->filter($formattedMessage, $this->options->isOptionEnabled('enable_youtube'), $this->options->isOptionEnabled('allow_post_links'), $this->options->getIntegerOption('youtube_width', 186), $this->options->getIntegerOption('youtube_height', 105));
     if ($this->options->isOptionEnabled('enable_twitter_hashtags')) {
         /** @var WiseChatHashtagsPostFilter $hashTagsFilter */
         $hashTagsFilter = WiseChatContainer::get('rendering/filters/post/WiseChatHashtagsPostFilter');
         $formattedMessage = $hashTagsFilter->filter($formattedMessage);
     }
     if ($this->options->isOptionEnabled('emoticons_enabled', true)) {
         /** @var WiseChatEmoticonsFilter $emoticonsFilter */
         $emoticonsFilter = WiseChatContainer::get('rendering/filters/post/WiseChatEmoticonsFilter');
         $formattedMessage = $emoticonsFilter->filter($formattedMessage);
     }
     if ($this->options->isOptionEnabled('multiline_support')) {
         $formattedMessage = str_replace("\n", '<br />', $formattedMessage);
     }
     return $formattedMessage;
 }
 /**
  * Endpoint for banning users by message ID.
  */
 public function userBanEndpoint()
 {
     $this->verifyCheckSum();
     $response = array();
     try {
         $this->checkChatOpen();
         $this->checkUserAuthentication();
         $this->checkUserRight('ban_user');
         $this->checkPostParams(array('channelId', 'messageId'));
         $channelId = trim($this->getPostParam('channelId'));
         $messageId = trim($this->getPostParam('messageId'));
         $channel = $this->channelsDAO->get($channelId);
         $this->checkChannel($channel);
         $this->checkChannelAuthorization($channel);
         $duration = $this->options->getIntegerOption('moderation_ban_duration', 1440);
         $this->bansService->banByMessageId($messageId, $channel, $duration . 'm');
         $this->messagesService->addMessage($this->authentication->getSystemUser(), $channel, "User has been banned for {$duration} minutes", true);
         $response['result'] = 'OK';
     } catch (WiseChatUnauthorizedAccessException $exception) {
         $response['error'] = $exception->getMessage();
         $this->sendUnauthorizedStatus();
     } catch (Exception $exception) {
         $response['error'] = $exception->getMessage();
         $this->sendBadRequestStatus();
     }
     echo json_encode($response);
     die;
 }
 private function addUsersListWidthDefinition()
 {
     if ($this->options->isOptionNotEmpty('users_list_width')) {
         $width = $this->options->getIntegerOption('users_list_width');
         if ($width > 1 && $width < 99) {
             $this->addRawDefinition('.wcUsersList', 'width', $width . '%');
             $this->addRawDefinition('.wcMessages', 'width', 100 - $width - 1 . '%');
         }
     }
 }
 /**
  * Generates thumbnail image for given attachment and returns URL of the thumbnail.
  *
  * @param string $attachmentId
  *
  * @return null|string
  * @throws Exception
  */
 private function generateThumbnail($attachmentId)
 {
     $imagePath = get_attached_file($attachmentId);
     $imageThPath = preg_replace('/\\.([a-zA-Z]+)$/', '-th.$1', $imagePath);
     $image = wp_get_image_editor($imagePath);
     if (!is_wp_error($image)) {
         $image->resize($this->options->getIntegerOption('images_thumbnail_width_limit', 60), $this->options->getIntegerOption('images_thumbnail_height_limit', 60), true);
         $image->save($imageThPath);
     } else {
         $this->logError('Error creating thumbnail: ' . $image->get_error_message());
         throw new Exception('The thumbnail of the image could not be generated');
     }
     $imageUrl = wp_get_attachment_url($attachmentId);
     $imageThUrl = preg_replace('/\\.([a-zA-Z]+)$/', '-th.$1', $imageUrl);
     return $imageThUrl;
 }
 /**
  * Determines if the number of channels that current user participates has been reached.
  *
  * @param WiseChatChannel $channel
  *
  * @return boolean
  */
 public function isChatChannelsLimitReached($channel)
 {
     $limit = $this->options->getIntegerOption('channels_limit', 0);
     if ($limit > 0) {
         $this->userService->refreshChannelUsersData();
         $amountOfChannels = $this->channelUsersDAO->getAmountOfActiveBySessionId(session_id());
         $user = $this->authentication->getUser();
         if ($user === null || $channel === null || $this->channelUsersDAO->getActiveByUserIdAndChannelId($user->getId(), $channel->getId()) === null) {
             $amountOfChannels++;
         }
         if ($amountOfChannels > $limit) {
             return true;
         }
     }
     return false;
 }
 /**
  * Returns information about the temporary file but only if it is an image file.
  *
  * @param string $fileName Name of the file
  *
  * @return null|array
  */
 private function getTempFileImageInfo($fileName)
 {
     if (file_exists($this->tempFileName)) {
         $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
         $allowedFormats = $this->getAllowedFormats();
         if (!in_array($extension, $allowedFormats)) {
             $this->logError('Unsupported file type: ' . $extension);
             return null;
         }
         $fileSize = filesize($this->tempFileName);
         if ($fileSize > $this->options->getIntegerOption('attachments_size_limit', 3145728)) {
             $this->logError('Attachment is to big: ' . $fileSize . ' bytes');
             return null;
         }
         $fileName = date('Ymd-His') . '-' . uniqid(rand()) . '.' . $extension;
         return $_FILES[self::UPLOAD_FILE_NAME] = array('name' => $fileName, 'type' => 'application/octet-stream', 'tmp_name' => $this->tempFileName, 'error' => 0, 'size' => $fileSize);
     }
     $this->logError('The file does not exist');
     return null;
 }
 /**
  * Deletes old messages according to the plugin's settings.
  * Images connected to the messages (WordPress Media Library attachments) are also deleted.
  *
  * @param WiseChatChannel $channel
  *
  * @throws Exception
  */
 private function deleteOldMessages($channel)
 {
     $minutesThreshold = $this->options->getIntegerOption('auto_clean_after', 0);
     if ($minutesThreshold > 0) {
         $criteria = new WiseChatMessagesCriteria();
         $criteria->setChannelName($channel->getName());
         $criteria->setIncludeAdminMessages(true);
         $criteria->setMaximumTime(time() - $minutesThreshold * 60);
         $messages = $this->messagesDAO->getAllByCriteria($criteria);
         $messagesIds = array();
         foreach ($messages as $message) {
             $messagesIds[] = $message->getId();
         }
         if (count($messagesIds) > 0) {
             $this->attachmentsService->deleteAttachmentsByMessageIds($messagesIds);
             $this->actions->publishAction('deleteMessages', array('ids' => $messagesIds));
             $this->messagesDAO->deleteAllByCriteria($criteria);
         }
     }
 }
Exemple #8
0
 /**
  * Returns chat HTML for given channel.
  *
  * @param string|null $channelName
  *
  * @return string
  * @throws Exception
  */
 public function getRenderedChat($channelName = null)
 {
     $channel = $this->service->createAndGetChannel($this->service->getValidChatChannelName($channelName));
     if ($this->service->isChatRestrictedForAnonymousUsers()) {
         return $this->renderer->getRenderedAccessDenied($this->options->getOption('message_error_4', 'Only logged in users are allowed to enter the chat'), 'wcAccessDenied');
     }
     if (!$this->service->isChatOpen()) {
         return $this->renderer->getRenderedAccessDenied($this->options->getOption('message_error_5', 'The chat is closed now'), 'wcChatClosed');
     }
     if ($this->service->isChatChannelFull($channel)) {
         return $this->renderer->getRenderedAccessDenied($this->options->getOption('message_error_6', 'The chat is full now. Try again later.'), 'wcChatFull');
     }
     if ($this->service->isChatChannelsLimitReached($channel)) {
         return $this->renderer->getRenderedAccessDenied($this->options->getOption('message_error_10', 'You cannot enter the chat due to the limit of channels you can participate simultaneously.'), 'wcChatChannelLimitFull');
     }
     if ($this->service->hasUserToBeForcedToEnterName()) {
         if ($this->getPostParam('wcUserNameSelection') !== null) {
             try {
                 $this->authentication->authenticate($this->getPostParam('wcUserName'));
             } catch (Exception $e) {
                 return $this->renderer->getRenderedUserNameForm($e->getMessage());
             }
         } else {
             return $this->renderer->getRenderedUserNameForm();
         }
     }
     if ($this->service->hasUserToBeAuthorizedInChannel($channel)) {
         if ($this->getPostParam('wcChannelAuthorization') !== null) {
             if (!$this->service->authorize($channel, $this->getPostParam('wcChannelPassword'))) {
                 return $this->renderer->getRenderedPasswordAuthorization($this->options->getOption('message_error_9', 'Invalid password.'));
             }
         } else {
             return $this->renderer->getRenderedPasswordAuthorization();
         }
     }
     $chatId = $this->service->getChatID();
     $this->userService->startUpMaintenance($channel);
     $this->bansService->startUpMaintenance();
     $this->messagesService->startUpMaintenance($channel);
     $messages = $this->messagesService->getAllByChannelNameAndOffset($channel->getName());
     $renderedMessages = '';
     $lastId = 0;
     foreach ($messages as $message) {
         // omit non-admin messages:
         if ($message->isAdmin() && !$this->usersDAO->isWpUserAdminLogged()) {
             continue;
         }
         $renderedMessages .= $this->renderer->getRenderedMessage($message);
         if ($lastId < $message->getId()) {
             $lastId = $message->getId();
         }
     }
     $lastAction = $this->actionsDAO->getLast();
     $jsOptions = array('chatId' => $chatId, 'channelId' => $channel->getId(), 'nowTime' => gmdate('c', time()), 'lastId' => $lastId, 'checksum' => $this->getCheckSum(), 'lastActionId' => $lastAction !== null ? $lastAction->getId() : 0, 'baseDir' => $this->options->getBaseDir(), 'emoticonsBaseURL' => $this->options->getEmoticonsBaseURL(), 'apiEndpointBase' => $this->getEndpointBase(), 'messagesRefreshTime' => intval($this->options->getEncodedOption('messages_refresh_time', 3000)), 'messagesOrder' => $this->options->getEncodedOption('messages_order', '') == 'descending' ? 'descending' : 'ascending', 'enableTitleNotifications' => $this->options->isOptionEnabled('enable_title_notifications'), 'soundNotification' => $this->options->getEncodedOption('sound_notification'), 'messagesTimeMode' => $this->options->getEncodedOption('messages_time_mode'), 'channelUsersLimit' => $this->options->getIntegerOption('channel_users_limit', 0), 'messages' => array('message_sending' => $this->options->getEncodedOption('message_sending', 'Sending ...'), 'hint_message' => $this->options->getEncodedOption('hint_message'), 'messageSecAgo' => $this->options->getEncodedOption('message_sec_ago', 'sec. ago'), 'messageMinAgo' => $this->options->getEncodedOption('message_min_ago', 'min. ago'), 'messageYesterday' => $this->options->getEncodedOption('message_yesterday', 'yesterday'), 'messageUnsupportedTypeOfFile' => $this->options->getEncodedOption('message_error_7', 'Unsupported type of file.'), 'messageSizeLimitError' => $this->options->getEncodedOption('message_error_8', 'The size of the file exceeds allowed limit.')), 'userSettings' => $this->userSettingsDAO->getAll(), 'attachmentsValidFileFormats' => $this->attachmentsService->getAllowedFormats(), 'attachmentsSizeLimit' => $this->attachmentsService->getSizeLimit(), 'imagesSizeLimit' => $this->options->getIntegerOption('images_size_limit', 3145728));
     $templater = new WiseChatTemplater($this->options->getPluginBaseDir());
     $templater->setTemplateFile(WiseChatThemes::getInstance()->getMainTemplate());
     $data = array('chatId' => $chatId, 'baseDir' => $this->options->getBaseDir(), 'messages' => $renderedMessages, 'themeStyles' => $this->options->getBaseDir() . WiseChatThemes::getInstance()->getCss(), 'showMessageSubmitButton' => $this->options->isOptionEnabled('show_message_submit_button'), 'showEmoticonInsertButton' => $this->options->isOptionEnabled('show_emoticon_insert_button', true), 'messageSubmitButtonCaption' => $this->options->getEncodedOption('message_submit_button_caption', 'Send'), 'showUsersList' => $this->options->isOptionEnabled('show_users'), 'usersList' => $this->options->isOptionEnabled('show_users') ? $this->renderer->getRenderedUsersList($channel) : '', 'showUsersCounter' => $this->options->isOptionEnabled('show_users_counter'), 'channelUsersLimit' => $this->options->getIntegerOption('channel_users_limit', 0), 'totalUsers' => $this->channelUsersDAO->getAmountOfUsersInChannel($channel->getId()), 'showUserName' => $this->options->isOptionEnabled('show_user_name'), 'currentUserName' => htmlentities($this->authentication->getUserNameOrEmptyString(), ENT_QUOTES, 'UTF-8'), 'isCurrentUserNameNotEmpty' => $this->authentication->isAuthenticated(), 'inputControlsTopLocation' => $this->options->getEncodedOption('input_controls_location') == 'top', 'inputControlsBottomLocation' => $this->options->getEncodedOption('input_controls_location') == '', 'showCustomizationsPanel' => $this->options->isOptionEnabled('allow_change_user_name') && !$this->usersDAO->isWpUserLogged() || $this->options->isOptionEnabled('allow_mute_sound') && strlen($this->options->getEncodedOption('sound_notification')) > 0 || $this->options->isOptionEnabled('allow_change_text_color'), 'allowChangeUserName' => $this->options->isOptionEnabled('allow_change_user_name') && !$this->usersDAO->isWpUserLogged(), 'allowMuteSound' => $this->options->isOptionEnabled('allow_mute_sound') && strlen($this->options->getEncodedOption('sound_notification')) > 0, 'allowChangeTextColor' => $this->options->isOptionEnabled('allow_change_text_color'), 'allowToSendMessages' => !$this->options->isOptionEnabled('read_only_for_anonymous', false) || $this->usersDAO->isWpUserLogged(), 'messageCustomize' => $this->options->getEncodedOption('message_customize', 'Customize'), 'messageName' => $this->options->getEncodedOption('message_name', 'Name'), 'messageSave' => $this->options->getEncodedOption('message_save', 'Save'), 'messageReset' => $this->options->getEncodedOption('message_reset', 'Reset'), 'messageMuteSounds' => $this->options->getEncodedOption('message_mute_sounds', 'Mute sounds'), 'messageTextColor' => $this->options->getEncodedOption('message_text_color', 'Text color'), 'messageTotalUsers' => $this->options->getEncodedOption('message_total_users', 'Total users'), 'messagePictureUploadHint' => $this->options->getEncodedOption('message_picture_upload_hint', 'Upload a picture'), 'messageAttachFileHint' => $this->options->getEncodedOption('message_attach_file_hint', 'Attach a file'), 'messageInsertEmoticon' => $this->options->getEncodedOption('message_insert_emoticon', 'Insert an emoticon'), 'windowTitle' => $this->options->getEncodedOption('window_title', ''), 'enableAttachmentsPanel' => $this->options->isOptionEnabled('enable_images_uploader') || $this->options->isOptionEnabled('enable_attachments_uploader'), 'enableImagesUploader' => $this->options->isOptionEnabled('enable_images_uploader'), 'enableAttachmentsUploader' => $this->options->isOptionEnabled('enable_attachments_uploader'), 'attachmentsExtensionsList' => $this->attachmentsService->getAllowedExtensionsList(), 'multilineSupport' => $this->options->isOptionEnabled('multiline_support'), 'hintMessage' => $this->options->getEncodedOption('hint_message'), 'messageMaxLength' => $this->options->getIntegerOption('message_max_length', 100), 'jsOptions' => json_encode($jsOptions), 'messagesOrder' => $this->options->getEncodedOption('messages_order', '') == 'descending' ? 'descending' : 'ascending', 'cssDefinitions' => $this->cssRenderer->getCssDefinition($chatId), 'customCssDefinitions' => $this->cssRenderer->getCustomCssDefinition());
     $data = array_merge($data, $this->userSettingsDAO->getAll());
     if ($this->authentication->isAuthenticated()) {
         $data = array_merge($data, $this->authentication->getUser()->getData());
     }
     return $templater->render($data);
 }