Skip to content

Commit c75b06a

Browse files
authored
Social: Security token for chat and social wall
1 parent 140f587 commit c75b06a

File tree

6 files changed

+114
-73
lines changed

6 files changed

+114
-73
lines changed

main/inc/lib/chat.lib.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ public function startSession()
142142
'me' => get_lang('Me'),
143143
'user_id' => api_get_user_id(),
144144
'items' => $chats,
145+
'sec_token' => Security::get_token('chat'),
145146
];
146147
echo json_encode($return);
147148

@@ -367,6 +368,13 @@ public function send(
367368
) {
368369
$relation = SocialManager::get_relation_between_contacts($fromUserId, $to_user_id);
369370

371+
if (!Security::check_token('post', null, 'chat')) {
372+
if ($printResult) {
373+
echo '0';
374+
exit;
375+
}
376+
}
377+
370378
if (USER_RELATION_TYPE_FRIEND == $relation) {
371379
$now = api_get_utc_datetime();
372380
$user_info = api_get_user_info($to_user_id, true);
@@ -405,8 +413,10 @@ public function send(
405413

406414
if (!empty($fromUserId) && !empty($to_user_id)) {
407415
$messageId = $this->save($params);
416+
408417
if ($printResult) {
409-
echo $messageId;
418+
header('Content-Type: application/json');
419+
echo json_encode(['id' => $messageId, 'sec_token' => Security::get_token('chat')]);
410420
exit;
411421
}
412422
}

main/inc/lib/javascript/chat/js/chat.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ var user_status = 0;
3939
var widthBox = 320; // see css class .chatbox
4040
//var ajax_url = 'chat.php'; // This variable is loaded in the template/layout/head.tpl file
4141
var doubleCheck = '<span class="chatbox_checked"><i class="fa fa-check"></i><i class="fa fa-check"></i></span>';
42+
var currentToken = '';
4243

4344
function set_user_status(status)
4445
{
@@ -134,6 +135,7 @@ function startChatSession()
134135
dataType: "json",
135136
success: function(data) {
136137
if (data) {
138+
currentToken = data.sec_token;
137139
username = data.me;
138140
currentUserId = data.user_id;
139141
user_status = data.user_status;
@@ -901,24 +903,26 @@ function checkChatBoxInputKey(event, chatboxtextarea, user_id)
901903
if (message != '') {
902904
$.post(ajax_url + "?action=sendchat", {
903905
to: user_id,
904-
message: message
906+
message: message,
907+
chat_sec_token: currentToken
905908
}, function (messageId) {
906-
if (messageId > 0) {
909+
if (messageId.id > 0) {
910+
currentToken = messageId.sec_token;
907911
message = message.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;");
908912
var item = {
909913
from_user_info : {id: currentUserId, complete_name: 'me'},
910914
username: username,
911915
date: moment().unix(),
912916
f: currentUserId,
913917
message: message,
914-
id: messageId
918+
id: messageId.id
915919
};
916920
createChatBubble(user_id, item);
917921
$("#chatbox_" + user_id + " .chatboxcontent").scrollTop(
918922
$("#chatbox_" + user_id + " .chatboxcontent")[0].scrollHeight
919923
);
920924

921-
intervals[messageId] = setInterval(checkMessageStatus, chatHeartbeatTime, messageId);
925+
intervals[messageId.id] = setInterval(checkMessageStatus, chatHeartbeatTime, messageId.id);
922926
} else {
923927
$("#chatbox_" + user_id + " .chatboxcontent").
924928
append('<i class="fa fa-exclamation-triangle" aria-hidden="true"></i><br />');

main/inc/lib/security.lib.php

Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -131,9 +131,11 @@ public static function filter_filename($filename)
131131
/**
132132
* @return string
133133
*/
134-
public static function getTokenFromSession()
134+
public static function getTokenFromSession(string $prefix = '')
135135
{
136-
return Session::read('sec_token');
136+
$secTokenVariable = self::generateSecTokenVariable($prefix);
137+
138+
return Session::read($secTokenVariable);
137139
}
138140

139141
/**
@@ -144,24 +146,25 @@ public static function getTokenFromSession()
144146
*
145147
* @return bool True if it's the right token, false otherwise
146148
*/
147-
public static function check_token($request_type = 'post', FormValidator $form = null)
149+
public static function check_token($request_type = 'post', FormValidator $form = null, string $prefix = '')
148150
{
149-
$sessionToken = Session::read('sec_token');
151+
$secTokenVariable = self::generateSecTokenVariable($prefix);
152+
$sessionToken = Session::read($secTokenVariable);
150153
switch ($request_type) {
151154
case 'request':
152-
if (!empty($sessionToken) && isset($_REQUEST['sec_token']) && $sessionToken === $_REQUEST['sec_token']) {
155+
if (!empty($sessionToken) && isset($_REQUEST[$secTokenVariable]) && $sessionToken === $_REQUEST[$secTokenVariable]) {
153156
return true;
154157
}
155158

156159
return false;
157160
case 'get':
158-
if (!empty($sessionToken) && isset($_GET['sec_token']) && $sessionToken === $_GET['sec_token']) {
161+
if (!empty($sessionToken) && isset($_GET[$secTokenVariable]) && $sessionToken === $_GET[$secTokenVariable]) {
159162
return true;
160163
}
161164

162165
return false;
163166
case 'post':
164-
if (!empty($sessionToken) && isset($_POST['sec_token']) && $sessionToken === $_POST['sec_token']) {
167+
if (!empty($sessionToken) && isset($_POST[$secTokenVariable]) && $sessionToken === $_POST[$secTokenVariable]) {
165168
return true;
166169
}
167170

@@ -206,9 +209,11 @@ public static function check_ua()
206209
/**
207210
* Clear the security token from the session.
208211
*/
209-
public static function clear_token()
212+
public static function clear_token(string $prefix = '')
210213
{
211-
Session::erase('sec_token');
214+
$secTokenVariable = self::generateSecTokenVariable($prefix);
215+
216+
Session::erase($secTokenVariable);
212217
}
213218

214219
/**
@@ -221,11 +226,12 @@ public static function clear_token()
221226
*
222227
* @return string Hidden-type input ready to insert into a form
223228
*/
224-
public static function get_HTML_token()
229+
public static function get_HTML_token(string $prefix = '')
225230
{
231+
$secTokenVariable = self::generateSecTokenVariable($prefix);
226232
$token = md5(uniqid(rand(), true));
227-
$string = '<input type="hidden" name="sec_token" value="'.$token.'" />';
228-
Session::write('sec_token', $token);
233+
$string = '<input type="hidden" name="'.$secTokenVariable.'" value="'.$token.'" />';
234+
Session::write($secTokenVariable, $token);
229235

230236
return $string;
231237
}
@@ -240,24 +246,26 @@ public static function get_HTML_token()
240246
*
241247
* @return string Token
242248
*/
243-
public static function get_token()
249+
public static function get_token($prefix = '')
244250
{
251+
$secTokenVariable = self::generateSecTokenVariable($prefix);
245252
$token = md5(uniqid(rand(), true));
246-
Session::write('sec_token', $token);
253+
Session::write($secTokenVariable, $token);
247254

248255
return $token;
249256
}
250257

251258
/**
252259
* @return string
253260
*/
254-
public static function get_existing_token()
261+
public static function get_existing_token(string $prefix = '')
255262
{
256-
$token = Session::read('sec_token');
263+
$secTokenVariable = self::generateSecTokenVariable($prefix);
264+
$token = Session::read($secTokenVariable);
257265
if (!empty($token)) {
258266
return $token;
259267
} else {
260-
return self::get_token();
268+
return self::get_token($prefix);
261269
}
262270
}
263271

@@ -584,4 +592,13 @@ public static function getPasswordRequirementsToString($passedConditions = [])
584592

585593
return $output;
586594
}
595+
596+
private static function generateSecTokenVariable(string $prefix = ''): string
597+
{
598+
if (empty($prefix)) {
599+
return 'sec_token';
600+
}
601+
602+
return $prefix.'_sec_token';
603+
}
587604
}

main/inc/lib/social.lib.php

Lines changed: 59 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -2404,53 +2404,10 @@ public static function getScriptToGetOpenGraph()
24042404
</script>';
24052405
}
24062406

2407-
/**
2408-
* @param string $urlForm
2409-
*
2410-
* @return string
2411-
*/
2412-
public static function getWallForm($urlForm)
2407+
public static function displayWallForm(string $urlForm): string
24132408
{
2414-
$userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
2415-
$form = new FormValidator(
2416-
'social_wall_main',
2417-
'post',
2418-
$urlForm.$userId,
2419-
null,
2420-
['enctype' => 'multipart/form-data'],
2421-
FormValidator::LAYOUT_HORIZONTAL
2422-
);
2423-
2424-
$socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang(
2425-
'SocialWallWhatAreYouThinkingAbout'
2426-
);
2427-
2428-
$form->addTextarea(
2429-
'social_wall_new_msg_main',
2430-
null,
2431-
[
2432-
'placeholder' => $socialWallPlaceholder,
2433-
'cols-size' => [1, 12, 1],
2434-
'aria-label' => $socialWallPlaceholder,
2435-
]
2436-
);
2437-
$form->addHtml('<div class="form-group">');
2438-
$form->addHtml('<div class="col-sm-6">');
2439-
$form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
2440-
$form->addHtml('</div>');
2441-
$form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
2442-
$form->addButtonSend(
2443-
get_lang('Post'),
2444-
'wall_post_button',
2445-
false,
2446-
[
2447-
'cols-size' => [1, 10, 1],
2448-
'custom' => true,
2449-
]
2450-
);
2451-
$form->addHtml('</div></div>');
2452-
$form->addHtml('</div>');
2453-
$form->addHidden('url_content', '');
2409+
$form = self::getWallForm($urlForm);
2410+
$form->protect();
24542411

24552412
return Display::panel($form->returnForm(), get_lang('SocialWall'));
24562413
}
@@ -2989,12 +2946,19 @@ public static function handlePosts($url)
29892946
{
29902947
$friendId = isset($_GET['u']) ? (int) $_GET['u'] : api_get_user_id();
29912948
$url = Security::remove_XSS($url);
2949+
$wallSocialAddPost = SocialManager::getWallForm(api_get_self());
2950+
2951+
if (!$wallSocialAddPost->validate()) {
2952+
return;
2953+
}
2954+
2955+
$values = $wallSocialAddPost->exportValues();
29922956

29932957
// Main post
2994-
if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp_name'])) {
2995-
$messageContent = $_POST['social_wall_new_msg_main'];
2958+
if (!empty($values['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp_name'])) {
2959+
$messageContent = $values['social_wall_new_msg_main'];
29962960
if (!empty($_POST['url_content'])) {
2997-
$messageContent = $_POST['social_wall_new_msg_main'].'<br /><br />'.$_POST['url_content'];
2961+
$messageContent = $values['social_wall_new_msg_main'].'<br /><br />'.$values['url_content'];
29982962
}
29992963

30002964
$messageId = self::sendWallMessage(
@@ -3407,6 +3371,52 @@ public static function getHomeProfileTabs($selected = 'home')
34073371
return $tabs;
34083372
}
34093373

3374+
private static function getWallForm(string $urlForm): FormValidator
3375+
{
3376+
$userId = isset($_GET['u']) ? '?u='.((int) $_GET['u']) : '';
3377+
$form = new FormValidator(
3378+
'social_wall_main',
3379+
'post',
3380+
$urlForm.$userId,
3381+
null,
3382+
['enctype' => 'multipart/form-data'],
3383+
FormValidator::LAYOUT_HORIZONTAL
3384+
);
3385+
3386+
$socialWallPlaceholder = isset($_GET['u'])
3387+
? get_lang('SocialWallWriteNewPostToFriend')
3388+
: get_lang('SocialWallWhatAreYouThinkingAbout');
3389+
3390+
$form->addTextarea(
3391+
'social_wall_new_msg_main',
3392+
null,
3393+
[
3394+
'placeholder' => $socialWallPlaceholder,
3395+
'cols-size' => [1, 12, 1],
3396+
'aria-label' => $socialWallPlaceholder,
3397+
]
3398+
);
3399+
$form->addHtml('<div class="form-group">');
3400+
$form->addHtml('<div class="col-sm-6">');
3401+
$form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
3402+
$form->addHtml('</div>');
3403+
$form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
3404+
$form->addButtonSend(
3405+
get_lang('Post'),
3406+
'wall_post_button',
3407+
false,
3408+
[
3409+
'cols-size' => [1, 10, 1],
3410+
'custom' => true,
3411+
]
3412+
);
3413+
$form->addHtml('</div></div>');
3414+
$form->addHtml('</div>');
3415+
$form->addHidden('url_content', '');
3416+
3417+
return $form;
3418+
}
3419+
34103420
/**
34113421
* Returns the formatted header message post.
34123422
*

main/social/home.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@
9999
$friend_html = SocialManager::listMyFriendsBlock($user_id);
100100

101101
// Block Social Sessions
102-
$wallSocialAddPost = SocialManager::getWallForm(api_get_self());
102+
$wallSocialAddPost = SocialManager::displayWallForm(api_get_self());
103103
$socialAutoExtendLink = SocialManager::getAutoExtendLink($user_id, $countPost);
104104

105105
$formSearch = new FormValidator(

main/social/profile.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@
141141

142142
// My friends
143143
$friend_html = SocialManager::listMyFriendsBlock($user_id, $link_shared);
144-
$addPostForm = SocialManager::getWallForm(api_get_self());
144+
$addPostForm = SocialManager::displayWallForm(api_get_self());
145145
$addPostFormPortfolio = SocialManager::getWallFormPortfolio(api_get_self());
146146

147147
$posts = SocialManager::getWallMessagesByUser($friendId);

0 commit comments

Comments
 (0)