-
Notifications
You must be signed in to change notification settings - Fork 8
/
qa-chat.php
415 lines (347 loc) · 11.7 KB
/
qa-chat.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
<?php
/*
Question2Answer Chat Room plugin
License: http://www.gnu.org/licenses/gpl.html
*/
require_once QA_INCLUDE_DIR.'app/users.php';
class qa_chat
{
private $directory;
private $urltoroot;
private $user;
private $dates;
private $optactive = 'chat_active';
private $optkick = 'chat_kick_level';
private $optcss = 'chat_hide_css';
// TODO: get the proper language text, this is all a quick fix at the moment
private $userlevels = [
'editor' => QA_USER_LEVEL_EDITOR,
'mod' => QA_USER_LEVEL_MODERATOR,
'admin' => QA_USER_LEVEL_ADMIN,
];
private $userlevels_text = [
'editor' => 'Editor',
'mod' => 'Moderator',
'admin' => 'Administrator',
];
public function load_module($directory, $urltoroot)
{
$this->directory = $directory;
$this->urltoroot = $urltoroot;
}
public function option_default($option)
{
switch ($option) {
case $this->optactive:
return 0;
case $this->optkick:
return QA_USER_LEVEL_ADMIN;
case $this->optcss:
return 0;
default:
break;
}
}
// set admin options
function admin_form(&$qa_content)
{
$saved_msg = null;
if (qa_clicked('chat_save')) {
// kick level option
$kicklevel = qa_post_text('ch_kicklevel');
if (!in_array($kicklevel, array_keys($this->userlevels))) {
$kicklevel = 'admin';
}
qa_opt($this->optkick, $this->userlevels[$kicklevel]);
// css option
$hidecss = qa_post_text('ch_hidecss') ? '1' : '0';
qa_opt($this->optcss, $hidecss);
$saved_msg = 'Options saved.';
}
$kl_id = qa_opt($this->optkick);
$kl_alias = array_search($kl_id, $this->userlevels);
$kl_value = $this->userlevels_text[$kl_alias];
return [
'ok' => $saved_msg,
'style' => 'wide',
'note' => array_search(qa_opt($this->optkick), $this->userlevels),
'fields' => [
'kicklevel' => [
'type' => 'select',
'label' => 'Kick level',
'tags' => 'NAME="ch_kicklevel"',
'options' => $this->userlevels_text,
'value' => $kl_value,
'note' => 'Which user level is able to kick other users.',
],
'css' => [
'type' => 'checkbox',
'label' => 'Don\'t add CSS inline',
'tags' => 'NAME="ch_hidecss"',
'value' => qa_opt($this->optcss) === '1',
'note' => 'Tick if you added the CSS to your own stylesheet (more efficient).',
],
],
'buttons' => [
'save' => [
'tags' => 'NAME="chat_save"',
'label' => 'Save options',
'value' => '1',
],
],
];
}
public function suggest_requests() // for display in admin interface
{
return [
[
'title' => 'Chat Room',
'request' => 'chat',
'nav' => 'M', // 'M'=main, 'F'=footer, 'B'=before main, 'O'=opposite main, null=none
],
];
}
public function match_request($request)
{
return $request == 'chat';
}
function init_queries($tableslc)
{
$tbl1 = qa_db_add_table_prefix('chat_posts');
$tbl2 = qa_db_add_table_prefix('chat_users');
if (in_array($tbl1, $tableslc) && in_array($tbl2, $tableslc)) {
qa_opt($this->optactive, '1');
return null;
}
return [
'CREATE TABLE IF NOT EXISTS ^chat_posts (
`postid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`userid` int(10) unsigned NOT NULL,
`posted` datetime NOT NULL,
`message` varchar(800) NOT NULL,
PRIMARY KEY (`postid`),
KEY `posted` (`posted`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8',
'CREATE TABLE IF NOT EXISTS ^chat_users (
`userid` int(10) unsigned NOT NULL,
`lastposted` datetime NOT NULL,
`lastpolled` datetime NOT NULL,
`kickeduntil` datetime NOT NULL DEFAULT "2012-01-01 00:00:00",
PRIMARY KEY (`userid`),
KEY `active` (`lastpolled`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8',
'CREATE TABLE IF NOT EXISTS ^chat_kicks (
`userid` int(10) unsigned NOT NULL,
`kickedby` int(10) unsigned NOT NULL,
`whenkicked` datetime NOT NULL,
PRIMARY KEY (`userid`,`kickedby`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8',
];
}
/*
MAIN function: display the chat room, or run an AJAX request
*/
public function process_request($request)
{
// set up user
$this->user = [
'id' => qa_get_logged_in_userid(),
'handle' => qa_get_logged_in_handle(),
'flags' => qa_get_logged_in_flags(),
'level' => qa_get_logged_in_level(),
];
// check if user is banned (kicked)
$sql = 'SELECT kickeduntil, (kickeduntil-NOW() > 0) AS iskicked FROM ^chat_users WHERE userid=#';
$result = qa_db_query_sub($sql, $this->user['id']);
$row = qa_db_read_one_assoc($result, true);
$this->user['iskicked'] = @$row['iskicked'];
$this->user['kickeduntil'] = @$row['kickeduntil'];
// create dates for database
$now = time();
$this->dates = [
'posted' => gmdate('Y-m-d H:i:s', $now),
'posted_utc' => gmdate('Y-m-d\TH:i:s\Z', $now),
];
$opt_kicklevel = qa_opt($this->optkick);
// AJAX: someone posted a message
$message = qa_post_text('ajax_add_message');
if ($message !== null) {
if (!$this->user_perms_post()) {
echo "QA_AJAX_RESPONSE\n0\nYou are not allowed to post currently, sorry.";
return;
}
// prevent just spaces
$message = trim($message);
if (strlen($message) == 0) {
echo "QA_AJAX_RESPONSE\n0\nThe message you post must actually be something.";
return;
}
$data = [
'userid' => $this->user['id'],
'username' => $this->user['handle'],
'posted' => $this->dates['posted'],
'posted_utc' => $this->dates['posted_utc'],
'message' => $message,
];
// save to database
$data['postid'] = $this->post_message($data);
$this->update_activity(true);
$data['username'] = qa_html($data['username']);
$data['message'] = $this->format_message($data['message']);
header('Content-Type: text/plain; charset=utf-8');
echo "QA_AJAX_RESPONSE\n" . $this->user['id'] . "\n" . json_encode($data);
return;
}
// AJAX: polling check; $lastid=0 on initial page load
$lastid = qa_post_text('ajax_get_messages');
if ($lastid !== null) {
if (!$this->user_perms_view()) {
echo "QA_AJAX_RESPONSE\n0\nYou don't appear to be logged in. Please reload the page.";
return;
}
if ($this->user_perms_kicked()) {
echo "QA_AJAX_RESPONSE\n0\nYou have been kicked. Please reload the page.";
return;
}
$this->update_activity($lastid == 0);
$messages = $this->get_messages($lastid);
$users = $this->users_online();
header('Content-Type: text/plain; charset=utf-8');
echo "QA_AJAX_RESPONSE\n" . $this->user['id'] . "\n" . json_encode($messages) . "\n" . json_encode($users);
return;
}
// AJAX: request to kick user
$kickuserid = qa_post_text('ajax_kick_userid');
$kickhandle = qa_post_text('ajax_kick_username');
if ($kickuserid !== null) {
// make sure user is correct level as set in options
if ($this->user['level'] < $opt_kicklevel) {
echo "QA_AJAX_RESPONSE\n0\nYou are not allowed to do that currently, sorry.";
return;
}
$this->kick_user($kickuserid, $kickhandle);
header('Content-Type: text/plain; charset=utf-8');
echo "QA_AJAX_RESPONSE\n" . $this->user['id'] . "\nGave 'em a right kickin'!";
return;
}
// regular page request
$qa_content = qa_content_prepare();
$qa_content['title'] = 'Chat Room';
$qa_content['script_rel'][] = $this->urltoroot.'qa-chat.js?v=1.7';
if ($this->user_perms_post()) {
$qa_content['custom_form'] =
'<form method="post" id="qa-chat-form">' .
' <input id="message" class="qa-chat-post" type="text" name="ajax_add_message" autocomplete="off" maxlength="800">' .
' <input type="submit" class="qa-chat-post-btn" value="Post">' .
'</form>' .
'<ul id="qa-chat-list"></ul>';
} else if ($this->user_perms_kicked()) {
$ktil_utc = gmdate('Y-m-d\TH:i:s\Z', strtotime($this->user['kickeduntil']));
$qa_content['error'] =
'Sorry, you have been kicked from chat temporarily. Take a few moments to chill.<br>' .
'The ban expires <span id="qa_chat_kickeduntil" data-utc="' . $ktil_utc . '" title="' . $ktil_utc . '">soon</span>' .
'<script>$("#qa_chat_kickeduntil").timeago();</script>';
} else if ($this->user_perms_view()) {
$qa_content['error'] = 'Sorry, you are currently unable to post in chat. If you are new, you must confirm your email address.';
} else {
$qa_content['error'] = qa_insert_login_links('Please ^1log in^2 or ^3register^4 to use the chat room.', $request);
}
return $qa_content;
}
// fetch all messages after given id
private function get_messages($lastid)
{
$sql =
'SELECT p.postid, p.userid, u.handle AS username, p.message AS message,
p.posted, DATE_FORMAT(p.posted, "%Y-%m-%dT%H:%i:%sZ") AS posted_utc
FROM ^chat_posts p LEFT JOIN ^users u ON u.userid=p.userid
WHERE p.postid > #
ORDER BY p.posted DESC LIMIT 80';
$result = qa_db_query_sub($sql, $lastid);
$messages = qa_db_read_all_assoc($result);
foreach ($messages as &$m) {
$m['message'] = $this->format_message($m['message']);
$m['username'] = qa_html($m['username']);
}
return $messages;
}
// save message to database
private function post_message($data)
{
$sql = 'INSERT INTO ^chat_posts (postid, userid, posted, message) VALUES (0, #, $, $)';
qa_db_query_sub($sql, $data['userid'], $data['posted'], $data['message']);
return qa_db_last_insert_id();
}
// update user activity
private function update_activity($posted = false)
{
if ($posted) {
$sql = 'INSERT INTO ^chat_users (userid, lastposted, lastpolled) VALUES (#, NOW(), NOW()) ON DUPLICATE KEY UPDATE lastposted=NOW(), lastpolled=NOW()';
} else {
$sql = 'INSERT INTO ^chat_users (userid, lastpolled) VALUES (#, NOW()) ON DUPLICATE KEY UPDATE lastpolled=NOW()';
}
qa_db_query_sub($sql, $this->user['id']);
}
// get recently active users
private function users_online()
{
$sql =
'SELECT u.userid, u.handle AS username, u.level, (c.lastposted < DATE_SUB(NOW(), INTERVAL 8 MINUTE)) AS idle, (c.kickeduntil > NOW()) AS kicked
FROM ^users u, ^chat_users c
WHERE u.userid=c.userid AND c.lastpolled > DATE_SUB(NOW(), INTERVAL 1 MINUTE)
ORDER BY u.handle';
$result = qa_db_query_sub($sql);
$users = qa_db_read_all_assoc($result);
$opt_kicklevel = qa_opt($this->optkick);
foreach ($users as &$u) {
$u['username'] = qa_html($u['username']);
$kickable = $u['level'] < $opt_kicklevel && $this->user['level'] >= $opt_kicklevel;
$u['kickable'] = $kickable ? '1' : '0';
}
return $users;
}
// votes to kick a user; mods/admins can kick users straight away
private function kick_user($kickuserid, $kickhandle)
{
$sql = 'INSERT INTO ^chat_kicks (userid, kickedby, whenkicked) VALUES (#, #, NOW()) ON DUPLICATE KEY UPDATE whenkicked=NOW()';
qa_db_query_sub($sql, $kickuserid, $this->user['id']);
$sql = 'UPDATE ^chat_users SET kickeduntil = DATE_ADD(NOW(), INTERVAL 10 MINUTE) WHERE userid=#';
$result = qa_db_query_sub($sql, $kickuserid);
if ($result) {
$message = [
'userid' => '0',
'posted' => $this->dates['posted'],
'message' => qa_html($kickhandle) . ' has been kicked off chat for 10 minutes.',
];
$this->post_message($message);
}
}
// check user permissions for viewing page
private function user_perms_view()
{
return $this->user['id'] > 0;
}
// check if user was kicked
private function user_perms_kicked()
{
return $this->user['iskicked'] > 0;
}
// check user permissions for posting messages
private function user_perms_post()
{
return qa_user_permit_error() === false && !$this->user['iskicked'] && (
($this->user['level'] >= QA_USER_LEVEL_EXPERT) ||
($this->user['flags'] & QA_USER_FLAGS_EMAIL_CONFIRMED)
);
}
// format message
private function format_message($msg)
{
// censor bad words
require_once QA_INCLUDE_DIR.'util/string.php';
$blockwordspreg = qa_get_block_words_preg();
$msg = qa_block_words_replace($msg, $blockwordspreg);
$msg = qa_html($msg);
return qa_html_convert_urls($msg);
}
}