0) { while ($usr = mysql_fetch_assoc($result)) { $users[] = $usr; } } return $users; } public static function getUserChatSettings($userId = 0) { if (!$userId) { $userId = $_SESSION['id']; } $sql = "SELECT * FROM `chat_settings_user` WHERE user_id = $userId"; $res = mysql_query($sql); if (mysql_num_rows($res) > 0) { return mysql_fetch_assoc($res); } else { return 0; } } public static function getAgencyChatSettings($agencyId) { $sql = "SELECT * FROM `chat_settings_agency` WHERE agency_id = $agencyId"; $res = mysql_query($sql); if (mysql_num_rows($res) > 0) { return mysql_fetch_assoc($res); } else { return 0; } } public static function createUserChannel($userOwnerId, $name, $userIds) { $url = RocketChat::getRocketChatUrl(); //логиним пользователя, если он не залогинен $loginData = RocketChat::loginUser($userOwnerId); $userChatUsernames = []; foreach ($userIds as $id) { $result = RocketChat::getUserChatSettings($id); $userChatUsernames[] = $result['chat_login']; } return RocketChat::createChannel($name, $userChatUsernames, $url, $loginData['user']['chat_token'], $loginData['user']['chat_user_id']); } public static function getGroupUsers($groupId) { $url = RocketChat::getRocketChatUrl(); //логиним пользователя, если он не залогинен $loginData = RocketChat::loginUser($_SESSION['id']); return RocketChat::getChannelMembers($groupId, $url, $loginData['user']['chat_token'], $loginData['user']['chat_user_id']); } public static function clearGroup($groupId) { return RocketChat::clearRoomHistory($groupId); } public static function removeUserFromChannel($groupId, $userId) { $url = RocketChat::getRocketChatUrl(); //логиним пользователя, если он не залогинен $loginData = RocketChat::loginUser($_SESSION['id']); return RocketChat::removeUserFromGroup($groupId, $userId, $url, $loginData['user']['chat_token'], $loginData['user']['chat_user_id']); } public static function createAgencyChannel($agencyId, $name) { $url = RocketChat::getRocketChatUrl(); $adminToken = RocketChat::getAdminToken(); $adminUserId = RocketChat::getAdminUserId(); $agency = new User; $agency->get($agencyId); $managers = User::getAllManagers($agencyId, true); $agents = User::getAllAgents($agencyId, true); $userChatUsernames = []; //создаем аккаунт для руководителя $result = RocketChat::createChatUser($agency, $url, $adminToken, $adminUserId); if ($result['success']) { //создаем аккаунты для менеджеров if ($managers) { foreach ($managers as $mngr) { $manager = new User; $manager->get($mngr['id']); $result = RocketChat::createChatUser($manager, $url, $adminToken, $adminUserId); if ($result['success']) { $userChatUsernames[] = $result['user']['chat_login']; } } } //создаем аккаунты для агентов if ($agents) { foreach ($agents as $agnt) { $agent = new User; $agent->get($agnt['id']); $result = RocketChat::createChatUser($agent, $url, $adminToken, $adminUserId); if ($result['success']) { $userChatUsernames[] = $result['user']['chat_login']; } } } //логиним руководителя $loginData = RocketChat::loginUser($agency->id); //создаем канал $channelSettings = RocketChat::getAgencyChatSettings($agency->id); if ($channelSettings && $channelSettings['general_channel_id']) { return ["success" => true, "settings" => $channelSettings, "error" => null]; } else { $result = RocketChat::createChannel($name, $userChatUsernames, $url, $loginData['user']['chat_token'], $loginData['user']['chat_user_id']); if ($result['success']) { $id = $result['channelId']; if ($channelSettings) { $sql = "UPDATE `chat_settings_agency` SET general_channel_id = '$id' WHERE agency_id = $agency->id"; mysql_query($sql); } else { $sql = "INSERT INTO `chat_settings_agency`(agency_id, general_channel_id) VALUES($agency->id, '$id')"; mysql_query($sql); } $channelSettings = RocketChat::getAgencyChatSettings($agency->id); return ["success" => true, "settings" => $channelSettings, "error" => null]; } else { if ($channelSettings) { $sql = "UPDATE `chat_settings_agency` SET error = '$result[error]' WHERE agency_id = $agency->id"; mysql_query($sql); } else { $sql = "INSERT INTO `chat_settings_agency`(agency_id, error) VALUES($agency->id, '$result[error]')"; mysql_query($sql); } return ["success" => false, "settings" => null, "error" => $result['error']]; } } } else { return ["success" => false, "settings" => null, "error" => $result['error']]; } } public static function createChannel($name, $users, $baseUrl = '', $adminToken = '', $adminUserId = '') { if (!$baseUrl) { $baseUrl = RocketChat::getRocketChatUrl(); $adminToken = RocketChat::getAdminToken(); $adminUserId = RocketChat::getAdminUserId(); } $url = $baseUrl . 'api/v1/channels.create'; $post = array( 'name' => $name, 'members' => $users ); $header = array('Content-type:application/json', 'X-Auth-Token: ' . $adminToken, 'X-User-Id: ' . $adminUserId); $resp = RocketChat::sendCurl($url, json_encode($post), $header); $json = json_decode($resp, true); if ($json['status'] === 'error') { return ["success" => false, "channelId" => null, "error" => $json['message']]; } if ($json['success']) { return ["success" => true, "channelId" => $json['channel']['_id'], "error" => null]; } else { return ["success" => false, "channelId" => null, "error" => $json['error']]; } } public static function loginUser($userId, $baseUrl = '') { $settings = RocketChat::getUserChatSettings($userId); if ($settings) { if ($settings['chat_token'] && $settings['chat_user_id']) { return ["success" => true, "user" => $settings, "error" => null]; } else { if (!$baseUrl) { $baseUrl = RocketChat::getRocketChatUrl(); } $url = $baseUrl . 'api/v1/login'; $post = array( 'user' => $settings['chat_login'], 'password' => $settings['chat_password'] ); $header = array('Content-type:application/json'); $resp = RocketChat::sendCurl($url, json_encode($post), $header); $json = json_decode($resp, true); if ($json['status'] === 'success') { $token = $json['data']['authToken']; $chatUserId = $json['data']['userId']; $sql = "UPDATE `chat_settings_user` SET chat_token = '$token', chat_user_id = '$chatUserId' WHERE user_id = $userId"; mysql_query($sql); return ["success" => true, "user" => RocketChat::getUserChatSettings($userId), "error" => null]; } else { $sql = "UPDATE `chat_settings_user` SET error = '$resp' WHERE user_id = $userId"; mysql_query($sql); return ["success" => false, "user" => null, "error" => $json['error']]; } } } else { return ["success" => false, "user" => null, "error" => "Не найден логин и пароль для авторизации"]; } } public static function deleteChatUser($userId, $baseUrl = '', $adminToken = '', $adminUserId = '') { $settings = RocketChat::getUserChatSettings($userId); if ($settings) { if (!$baseUrl) { $baseUrl = RocketChat::getRocketChatUrl(); $adminToken = RocketChat::getAdminToken(); $adminUserId = RocketChat::getAdminUserId(); } $url = $baseUrl . 'api/v1/users.delete'; $post = array( 'username' => $settings['chat_login'] ); $header = array('Content-type:application/json', 'X-Auth-Token: ' . $adminToken, 'X-User-Id: ' . $adminUserId); RocketChat::sendCurl($url, json_encode($post), $header); } } public static function checkUserInChannel($user, $roomId, $baseUrl = '', $adminToken = '', $adminUserId = '') { $settings = RocketChat::getUserChatSettings($user->id); if ($settings && $settings['chat_user_id']) { if (!$baseUrl) { $baseUrl = RocketChat::getRocketChatUrl(); $adminToken = RocketChat::getAdminToken(); $adminUserId = RocketChat::getAdminUserId(); } $url = $baseUrl . 'api/v1/users.info?userId=' . $settings['chat_user_id'] . '&fields={%22userRooms%22:%201}'; $header = array('Content-type:application/json', 'X-Auth-Token: ' . $adminToken, 'X-User-Id: ' . $adminUserId); $resp = RocketChat::sendCurl($url, false, $header); $json = json_decode($resp, true); if ($json && $json['success'] == true) { $rooms = $json['user']['rooms']; if ($rooms) { foreach ($rooms as $room) { if ($room['rid'] === $roomId) { return true; } } } } } return false; } public static function addUserToChannel($user, $roomId, $baseUrl = '', $adminToken = '', $adminUserId = '') { $settings = RocketChat::getUserChatSettings($user->id); if ($settings && $settings['chat_user_id']) { if (!$baseUrl) { $baseUrl = RocketChat::getRocketChatUrl(); $adminToken = RocketChat::getAdminToken(); $adminUserId = RocketChat::getAdminUserId(); } $url = $baseUrl . 'api/v1/channels.invite'; $post = array( 'roomId' => $roomId, 'userId' => $settings['chat_user_id'] ); $header = array('Content-type:application/json', 'X-Auth-Token: ' . $adminToken, 'X-User-Id: ' . $adminUserId); return RocketChat::sendCurl($url, json_encode($post), $header); } return 0; } public static function getChannelMembers($roomId, $baseUrl = '', $adminToken = '', $adminUserId = '') { if (!$baseUrl) { $baseUrl = RocketChat::getRocketChatUrl(); $adminToken = RocketChat::getAdminToken(); $adminUserId = RocketChat::getAdminUserId(); } $url = $baseUrl . 'api/v1/channels.members?roomId='. $roomId; $header = array('Content-type:application/json', 'X-Auth-Token: ' . $adminToken, 'X-User-Id: ' . $adminUserId); return RocketChat::sendCurl($url, false, $header); } public static function clearRoomHistory($roomId, $baseUrl = '', $adminToken = '', $adminUserId = '') { if (!$baseUrl) { $baseUrl = RocketChat::getRocketChatUrl(); $adminToken = RocketChat::getAdminToken(); $adminUserId = RocketChat::getAdminUserId(); } $url = $baseUrl . 'api/v1/rooms.cleanHistory'; $post = array( 'roomId' => $roomId, 'oldest' => '2010-09-30T13:42:25.304Z', 'latest' => '2050-09-30T13:42:25.304Z' ); $header = array('Content-type:application/json', 'X-Auth-Token: ' . $adminToken, 'X-User-Id: ' . $adminUserId); return RocketChat::sendCurl($url, json_encode($post), $header); } public static function removeUserFromGroup($roomId, $userId, $baseUrl = '', $adminToken = '', $adminUserId = '') { if (!$baseUrl) { $baseUrl = RocketChat::getRocketChatUrl(); $adminToken = RocketChat::getAdminToken(); $adminUserId = RocketChat::getAdminUserId(); } $url = $baseUrl . 'api/v1/channels.kick'; $post = array( 'roomId' => $roomId, 'userId' => $userId ); $header = array('Content-type:application/json', 'X-Auth-Token: ' . $adminToken, 'X-User-Id: ' . $adminUserId); return RocketChat::sendCurl($url, json_encode($post), $header); } public static function createChatUser($user, $baseUrl = '', $adminToken = '', $adminUserId = '') { $settings = RocketChat::getUserChatSettings($user->id); if (!$settings || !$settings['chat_login']) { if (!$baseUrl) { $baseUrl = RocketChat::getRocketChatUrl(); $adminToken = RocketChat::getAdminToken(); $adminUserId = RocketChat::getAdminUserId(); } $url = $baseUrl . 'api/v1/users.create'; $pass = generatePass(); $username = slugify($user->last_name) . '_' . slugify($user->first_name) . '_' . rand(1, 9); $username = str_replace("ʹ", '', $username); $post = array( 'email' => $user->email, 'name' => $user->last_name . ' ' . $user->first_name, 'password' => $pass, 'username' => $username, 'active' => true, 'roles' => ['user'], 'joinDefaultChannels' => false, 'requirePasswordChange' => false, 'sendWelcomeEmail' => false, 'verified' => false ); $header = array('Content-type:application/json', 'X-Auth-Token: ' . $adminToken, 'X-User-Id: ' . $adminUserId); $resp = RocketChat::sendCurl($url, json_encode($post), $header); $json = json_decode($resp, true); if ($json['success']) { if ($settings) { $sql = "UPDATE `chat_settings_user` SET chat_login = '$username', chat_password = '$pass' WHERE user_id = $user->id"; mysql_query($sql); } else { $sql = "INSERT INTO `chat_settings_user`(user_id, chat_login, chat_password) VALUES($user->id, '$username','$pass')"; mysql_query($sql); } return ["success" => true, "user" => RocketChat::getUserChatSettings($user->id), "error" => null]; } else { if ($settings) { $sql = "UPDATE `chat_settings_user` SET error = '$resp' WHERE user_id = $user->id"; mysql_query($sql); } else { $sql = "INSERT INTO `chat_settings_user`(user_id, error) VALUES($user->id, '$resp')"; mysql_query($sql); } return ["success" => false, "user" => null, "error" => $json['error']]; } } else { return ["success" => true, "user" => $settings, "error" => null]; } } public static function getAdminToken() { $sql = "SELECT value FROM `params` WHERE code = 'rocket_chat_admin_token'"; $res = mysql_query($sql); return mysql_fetch_assoc($res)['value']; } public static function getAdminUserId() { $sql = "SELECT value FROM `params` WHERE code = 'rocket_chat_admin_user_id'"; $res = mysql_query($sql); return mysql_fetch_assoc($res)['value']; } public static function getRocketChatUrl() { $sql = "SELECT value FROM `params` WHERE code = 'rocket_chat_url'"; $res = mysql_query($sql); return mysql_fetch_assoc($res)['value']; } private static function sendCurl($url, $post = false, $header = false){ $ch = curl_init($url); //debug curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_STDERR, fopen($_SERVER['DOCUMENT_ROOT'] . '/curl.txt', 'a+')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if ($header) { curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_HEADER,0); } if ($post) { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); } $response = curl_exec($ch); //if(curl_error($ch)) { //echo 'curl error is -' . curl_error($ch); //} curl_close($ch); return $response; } }