-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat_ajax.php
565 lines (484 loc) · 28.8 KB
/
chat_ajax.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package block_tildeva
* @copyright 2023, Evita Korņējeva <[email protected]>
* @copyright 2023, SIA Tilde
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define('AJAX_SCRIPT', true);
require(__DIR__ . '/../../config.php');
require_once($CFG->dirroot . '/lib/setup.php');
$action = optional_param('action', '', PARAM_ALPHANUM);
$userid = optional_param('chat_usid', 0, PARAM_INT);
$courseid = optional_param('chat_couid', 0, PARAM_INT);
$conversationid = optional_param('chat_convid', '', PARAM_RAW);
$input = optional_param('chat_msg', '', PARAM_RAW);
if (!$chatsession = $DB->get_record('chat_sessions', array('userid' => $userid, 'courseid' => $courseid))) {
$chatsession = new stdClass();
$chatsession->conversationid = 0;
}
if (!isloggedin() && $conversationid != $chatsession->conversationid) {
throw new moodle_exception('notlogged', 'chat');
}
// Set up $PAGE so that format_text will work properly.
// $PAGE->set_cm($cm, $course, $chat);
$PAGE->set_url('/blocks/tildeva/chat_ajax.php', array('chat_usid' => $userid));
$courseContext = \context_course::instance($courseid);
// Create a new page instance
$PAGE->set_context($courseContext);
ob_start();
header('Expires: Sun, 28 Dec 1997 09:32:45 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-Type: text/html; charset=utf-8');
// Get the user's roles in the course
$userRoles = get_user_roles($courseContext, $userid, false);
// Check if the user has the 'teacher' or 'editingteacher' role
$hasTeacherRole = false;
foreach ($userRoles as $role) {
$roleShortname = $role->shortname;
if ($roleShortname === 'teacher') {
$hasTeacherRole = true;
} elseif ($roleShortname === 'editingteacher') {
$hasTeacherRole = true;
}
}
switch ($action) {
case 'init':
$response['firstname'] = $USER->firstname;
$response['lastname'] = $USER->lastname;
$response['email'] = $USER->email;
$response['conversationid'] = $chatsession->conversationid;
$response['userid'] = $userid;
$response['courseid'] = $courseid;
echo json_encode($response);
break;
case 'sid':
$chatsession->conversationid = $conversationid;
$chatsession->userid = $userid;
$chatsession->courseid = $courseid;
if ($chatsession->id) {
$DB->update_record('chat_sessions', $chatsession);
} else {
$DB->insert_record('chat_sessions', $chatsession);
}
echo json_encode($chatsession);
break;
case 'msg':
if ($input) {
$matches = array();
$matchCount = preg_match('/:(.+)$/', $input, $matches);
if ($matchCount > 0) {
// Match found
$command = $matches[1];
if (strncmp($command, "feedback", 8) === 0) {
$params = explode("|", $command);
if (count($params) == 3) {
// Load the feedback activity
$feedback = $DB->get_record('feedback', array('name' => $params[1], 'course' => $courseid));
if ($feedback) {
$feedbackItem = $DB->get_record('feedback_item', array('feedback' => $feedback->id));
$time = time();
// Insert new submission
$submissionData = array(
'feedback' => $feedback->id,
'anonymous_response' => 1,
'anonymous' => 1,
'course' => $feedback->course,
'timecompleted' => $time,
'timemodified' => $time,
'userid' => $userid
);
$submissionId = $DB->insert_record('feedback_completed', (object) $submissionData);
if ($submissionId) {
// Insert feedback response
$responseData = array(
'item' => $feedbackItem->id,
'completed' => $submissionId,
'course_id' => $feedback->course,
'anonymous_response' => 1,
'anonymous' => 1,
'timecreated' => $time,
'timemodified' => $time,
'value' => $params[2]
);
$responseId = $DB->insert_record('feedback_value', (object) $responseData);
if ($responseId) {
echo json_encode("Feedback posted successfully.");
} else {
echo json_encode("Error adding feedback response.");
}
} else {
echo json_encode("Error creating feedback submission.");
}
} else {
echo json_encode("Feedback activity not found.");
}
}
} else if (strncmp($command, "getpostbyname", 13) === 0) {
$params = explode("|", $command);
if (count($params) == 2) {
$sql = "SELECT p.message AS post_body, d.id AS discussion_id, p.id AS post_id
FROM {forum_discussions} d
LEFT JOIN {forum_posts} p ON d.id = p.discussion
WHERE (d.name = :dname OR p.subject = :pname) AND d.course = :course
LIMIT 1";
$params = array('dname' => $params[1], 'pname' => $params[1], 'course' => $courseid);
$result = $DB->get_records_sql($sql, $params);
if ($result) {
echo json_encode($result);
} else {
echo json_encode("Post not found.");
}
} else {
echo json_encode("Post not found.");
}
} else if (strncmp($command, "settimeclose", 12) === 0) {
if ($hasTeacherRole) {
$params = explode("|", $command);
if (count($params) == 4) {
$moduleid = $params[1];
$oldEndDate = strtotime($params[2]);
$newEndDate = strtotime($params[3]);
$quizid = $DB->get_field('course_modules', 'instance', array('id' => $moduleid), MUST_EXIST);
// Load the quiz
$quiz = $DB->get_record('quiz', array('id' => $quizid, 'course' => $courseid), '*', MUST_EXIST);
if ($quiz && $oldEndDate == $quiz->timeclose) {
// Update the end date
$quiz->timeclose = $newEndDate;
// Save the changes
$DB->update_record('quiz', $quiz);
}
$response['quiz']['id'] = $quiz->id;
$response['quiz']['name'] = $quiz->name;
$response['quiz']['timeclose'] = date('Y-m-d H:i:s', $quiz->timeclose);
$response['quiz']['timeopen'] = date('Y-m-d H:i:s', $quiz->timeopen);
echo json_encode($response);
}
} else {
header('HTTP/1.1 405 Method Not Allowed');
exit('Method Not Allowed');
}
} else if (strncmp($command, "settimeopen", 11) === 0) {
if ($hasTeacherRole) {
$params = explode("|", $command);
if (count($params) == 4) {
$moduleid = $params[1];
$oldStartDate = strtotime($params[2]);
$newSartDate = strtotime($params[3]);
$quizid = $DB->get_field('course_modules', 'instance', array('id' => $moduleid), MUST_EXIST);
// Load the quiz
$quiz = $DB->get_record('quiz', array('id' => $quizid, 'course' => $courseid), '*', MUST_EXIST);
if ($quiz && $oldStartDate == $quiz->timeopen) {
// Update the end date
$quiz->timeopen = $newSartDate;
// Save the changes
$DB->update_record('quiz', $quiz);
}
$response['quiz']['id'] = $quiz->id;
$response['quiz']['name'] = $quiz->name;
$response['quiz']['timeopen'] = date('Y-m-d H:i:s', $quiz->timeopen);
$response['quiz']['timeclose'] = date('Y-m-d H:i:s', $quiz->timeclose);
echo json_encode($response);
}
} else {
header('HTTP/1.1 405 Method Not Allowed');
exit('Method Not Allowed');
}
} else if (strncmp($command, "getquizzesstats", 15) === 0) {
$currentCourse = get_course($courseid);
// Assuming $command, $courseid, $userid, $hasTeacherRole are already defined
if ($hasTeacherRole) {
$params = explode("|", $command);
if (count($params) == 2) {
$gradetopass = $params[1];
$quizzes = get_all_instances_in_course('quiz', $currentCourse, $userid);
$studentRoleId = $DB->get_field('role', 'id', array('shortname' => 'student'));
$studentIds = $DB->get_records_sql("SELECT u.id FROM {user} u JOIN {role_assignments} ra ON u.id = ra.userid WHERE ra.contextid IN (SELECT id FROM {context} WHERE contextlevel = :courselevel AND instanceid = :courseid) AND ra.roleid = :studentrole", array('courselevel' => CONTEXT_COURSE, 'courseid' => $courseid, 'studentrole' => $studentRoleId));
foreach ($quizzes as $quizid => $quiz) {
$sectionInfo = $DB->get_record_sql(
"SELECT s.section AS section_id, s.name AS section_name
FROM {course_sections} s
INNER JOIN {course_modules} cm ON s.id = cm.section
WHERE cm.id = :quizid",
array('quizid' => $quiz->coursemodule)
);
$quizzes[$quizid]->section_name = $sectionInfo->section_name;
$quizzes[$quizid]->section_id = $sectionInfo->section_id;
$quizzes[$quizid]->passCount = 0;
$quizzes[$quizid]->failCount = 0;
$quizzes[$quizid]->passuserids = array();
$quizzes[$quizid]->failuserids = array();
foreach ($studentIds as $user) {
$maxAttempt = $DB->get_record_sql(
"SELECT MAX(qa.sumgrades) as maxsumgrades
FROM {quiz_attempts} qa
WHERE qa.quiz = :quizid AND qa.userid = :userid",
array('quizid' => $quiz->id, 'userid' => $user->id)
);
if (!empty($maxAttempt)) {
if ($quiz->sumgrades == 0) {
$finalgrade = 0;
} else {
$finalgrade = $quiz->grade / $quiz->sumgrades * $maxAttempt->maxsumgrades;
}
if ($finalgrade >= $gradetopass) {
$quizzes[$quizid]->passCount++;
$quizzes[$quizid]->passuserids[] = $user->id;
} else {
$quizzes[$quizid]->failCount++;
$quizzes[$quizid]->failuserids[] = $user->id;
}
} else {
$quizzes[$quizid]->failCount++;
$quizzes[$quizid]->failuserids[] = $user->id;
}
}
$quizzes[$quizid]->t_timeclose = date('Y-m-d H:i:s', $quiz->timeclose);
$quizzes[$quizid]->t_timeopen = date('Y-m-d H:i:s', $quiz->timeopen);
}
echo json_encode($quizzes);
} else {
header('HTTP/1.1 400 Bad Request');
exit('Invalid parameters');
}
} else {
header('HTTP/1.1 405 Method Not Allowed');
exit('Method Not Allowed');
}
} else if (strncmp($command, "sendmsg", 7) === 0) {
$params = explode("|", $command);
if (count($params) == 3) {
$userfrom = \core_user::get_user($userid);
$userto = \core_user::get_user($params[1]);
$message = $params[2];
$format = FORMAT_HTML;
$eventdata = new \core\message\message();
$eventdata->courseid = $courseid;
$eventdata->component = 'moodle';
$eventdata->name = 'instantmessage';
$eventdata->userfrom = $userfrom;
$eventdata->userto = $userto;
//using string manager directly so that strings in the message will be in the message recipients language rather than the senders
$eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
if ($format == FORMAT_HTML) {
$eventdata->fullmessagehtml = $message;
//some message processors may revert to sending plain text even if html is supplied
//so we keep both plain and html versions if we're intending to send html
$eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
} else {
$eventdata->fullmessage = $message;
$eventdata->fullmessagehtml = '';
}
$eventdata->fullmessageformat = $format;
$eventdata->smallmessage = $message; //store the message unfiltered. Clean up on output.
$eventdata->timecreated = time();
$eventdata->notification = 0;
// User image.
$userpicture = new user_picture($userfrom);
$userpicture->size = 1; // Use f1 size.
$userpicture->includetoken = $userto->id; // Generate an out-of-session token for the user receiving the message.
$eventdata->customdata = [
'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
'actionbuttons' => [
'send' => get_string_manager()->get_string('send', 'message', null, $eventdata->userto->lang),
],
'placeholders' => [
'send' => get_string_manager()->get_string('writeamessage', 'message', null, $eventdata->userto->lang),
],
];
$messageId = message_send($eventdata);
// // Check if the message was sent successfully
if ($messageId) {
echo json_encode('Notification sent');
} else {
echo json_encode('Failed to send the notification.');
}
} else {
echo json_encode($command);
}
} else {
switch ($command) {
case 'getuserinfo':
$response['userinfo']['firstname'] = $USER->firstname;
$response['userinfo']['lastname'] = $USER->lastname;
$response['userinfo']['email'] = $USER->email;
$response['userinfo']['username'] = $USER->username;
// Iterate through the roles and extract role names
$roleNames = array();
foreach ($userRoles as $role) {
$roleNames[] = $role->shortname;
}
$response['userinfo']['userroles'] = implode(", ", $roleNames);
echo json_encode($response);
break;
case 'getteacherinfo':
$teacherRoleId = $DB->get_field('role', 'id', array('shortname' => 'teacher'));
$editingTeacherRoleId = $DB->get_field('role', 'id', array('shortname' => 'editingteacher'));
// Get the list of users with both teacher and editingteacher roles in the current course
$teachers = array_merge(
get_role_users($teacherRoleId, $courseContext),
get_role_users($editingTeacherRoleId, $courseContext)
);
echo json_encode($teachers);
break;
case 'getcoursesections':
$params = array('course' => $courseid);
$sql = "SELECT name, section FROM {course_sections} WHERE course = :course ORDER BY id ASC";
$sections = $DB->get_records_sql($sql, $params);
echo json_encode($sections);
break;
case 'getquizzes':
$currentCourse = get_course($courseid);
$quizzes = get_all_instances_in_course('quiz', $currentCourse, $userid);
foreach ($quizzes as $quizid => $quiz) {
$sectionInfo = $DB->get_record_sql(
"SELECT s.section AS section_id, s.name AS section_name
FROM {course_sections} s
INNER JOIN {course_modules} cm ON s.id = cm.section
WHERE cm.id = :quizid",
array('quizid' => $quiz->coursemodule)
);
$maxAttempt = $DB->get_record_sql(
"SELECT MAX(qa.sumgrades) AS maxsumgrades, MAX(qa.timefinish) AS maxtimefinish
FROM {quiz_attempts} qa
WHERE qa.quiz = :quizid AND qa.userid = :userid",
array('quizid' => $quiz->id, 'userid' => $userid)
);
$quizzes[$quizid]->section_name = $sectionInfo->section_name;
$quizzes[$quizid]->section_id = $sectionInfo->section_id;
$quizzes[$quizid]->maxsumgrade = $maxAttempt->maxsumgrades;
$quizzes[$quizid]->maxtimefinish = date('Y-m-d H:i:s', $maxAttempt->maxtimefinish);
if ($quiz->sumgrades == 0) {
$quizzes[$quizid]->finalgrade = 0;
} else {
$quizzes[$quizid]->finalgrade = $quiz->grade / $quiz->sumgrades * $maxAttempt->maxsumgrades;
}
$quizzes[$quizid]->t_timeclose = date('Y-m-d H:i:s', $quiz->timeclose);
$quizzes[$quizid]->t_timeopen = date('Y-m-d H:i:s', $quiz->timeopen);
}
echo json_encode($quizzes);
break;
case 'getcourseinfo':
$currentCourse = get_course($courseid);
$response['courseinfo']['courseid'] = $courseid;
$response['courseinfo']['coursefullname'] = $currentCourse->fullname;
$response['courseinfo']['courseShortName'] = $currentCourse->shortname;
$response['courseinfo']['coursecategory'] = $currentCourse->category;
// Define the database tables and columns
$table = 'quiz';
$columns = 'q.id, q.name, q.intro, q.timeclose';
// Build the SQL query
$sql = "SELECT $columns
FROM {course_modules} cm
JOIN {quiz} q ON q.id = cm.instance
LEFT JOIN {quiz_attempts} qa ON qa.quiz = q.id
WHERE cm.course = :courseid
AND cm.module = (SELECT id FROM {modules} WHERE name = 'quiz')
GROUP BY q.id";
// Execute the query
$params = ['courseid' => $courseid];
$tests = $DB->get_records_sql($sql, $params);
// Display the test information
$i = 0;
foreach ($tests as $test) {
$testId = $test->id;
$testName = $test->name;
$testIntro = $test->intro;
$testDeadline = $test->timeclose;
$response['courseinfo']['tests'][$i]['attemptid'] = $attemptId;
$response['courseinfo']['tests'][$i]['testid'] = $testId;
$response['courseinfo']['tests'][$i]['testname'] = $testName;
$response['courseinfo']['tests'][$i]['testintro'] = $testIntro;
$response['courseinfo']['tests'][$i]['testdeadline'] = date('Y-m-d H:i:s', $testDeadline);
$i++;
}
echo json_encode($response);
break;
case 'getgroups':
if ($hasTeacherRole) {
$groups = groups_get_all_groups($courseid);
echo json_encode($groups);
} else {
header('HTTP/1.1 405 Method Not Allowed');
exit('Method Not Allowed');
}
break;
case 'gettestinfo':
// Define the database tables and columns
$table = 'quiz_attempts';
$columns = 'qa.id, qa.uniqueid, qa.timefinish, qa.sumgrades, q.name';
// Build the SQL query
$sql = "SELECT $columns
FROM {user} u
JOIN {user_enrolments} ue ON ue.userid = u.id
JOIN {enrol} e ON e.id = ue.enrolid
JOIN {course} c ON c.id = e.courseid
JOIN {quiz} q ON q.course = c.id
JOIN {quiz_attempts} qa ON qa.userid = u.id AND qa.quiz = q.id
WHERE u.id = :userid
ORDER BY qa.timefinish DESC";
// Execute the query
$params = ['userid' => $userid];
$testResults = $DB->get_records_sql($sql, $params);
$i = 0;
// Display the test results
foreach ($testResults as $testResult) {
$attemptId = $testResult->id;
$attemptUniqueId = $testResult->uniqueid;
$attemptTimeFinish = $testResult->timefinish;
$attemptSumGrades = $testResult->sumgrades;
$quizName = $testResult->name;
$response['testresults'][$i]['attemptid'] = $attemptId;
$response['testresults'][$i]['attemptuniqueid'] = $attemptUniqueId;
$response['testresults'][$i]['attempttimefinish'] = date('Y-m-d H:i:s', $attemptTimeFinish);
$response['testresults'][$i]['attemptsumgrades'] = $attemptSumGrades;
$response['testresults'][$i]['quizname'] = $quizName;
$i++;
}
echo json_encode($testResults);
break;
case 'getversion':
$response['moodleversion'] = $CFG->version;
$pluginConfig = get_config('block_tildeva');
if (!empty($pluginConfig) && isset($pluginConfig->release)) {
$response['pluginversion'] = $pluginConfig->release;
} else {
$response['pluginversion'] = 'v5';
}
echo json_encode($response);
break;
default:
echo json_encode($command);
break;
}
}
} else {
echo json_encode($input);
}
} else {
echo json_encode($input);
}
break;
case 'deleteconversation':
$DB->delete_records("chat_sessions", array('userid' => $userid, 'courseid' => $courseid));
echo json_encode(true);
break;
default:
break;
}