Merge branch 'MDL-61375_master' of git://github.com/markn86/moodle
[moodle.git] / mod / chat / lib.php
CommitLineData
848bb113 1<?php
848bb113 2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
1515a89e 16
848bb113 17/**
18 * Library of functions and constants for module chat
19 *
a6be3193 20 * @package mod_chat
848bb113 21 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
530d5535
SB
25defined('MOODLE_INTERNAL') || die();
26
89b8211e 27require_once($CFG->dirroot.'/calendar/lib.php');
c4d588cc 28
bea71d57
MN
29// Event types.
30define('CHAT_EVENT_TYPE_CHATTIME', 'chattime');
31
c52b4db5 32// The HTML head for the message window to start with (<!-- nix --> is used to get some browsers starting with output.
17da2e6f 33global $CHAT_HTMLHEAD;
1f8abb89 34$CHAT_HTMLHEAD = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"><html><head></head>\n<body>\n\n".padding(200);
1515a89e 35
c52b4db5 36// The HTML head for the message window to start with (with js scrolling).
17da2e6f 37global $CHAT_HTMLHEAD_JS;
1f8abb89 38$CHAT_HTMLHEAD_JS = <<<EOD
39<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
40<html><head><script type="text/javascript">
41//<![CDATA[
c52b4db5 42function move() {
1f8abb89 43 if (scroll_active)
44 window.scroll(1,400000);
45 window.setTimeout("move()",100);
46}
47var scroll_active = true;
48move();
49//]]>
50</script>
51</head>
52<body onBlur="scroll_active = true" onFocus="scroll_active = false">
53EOD;
17da2e6f 54global $CHAT_HTMLHEAD_JS;
1f8abb89 55$CHAT_HTMLHEAD_JS .= padding(200);
1515a89e 56
c52b4db5 57// The HTML code for standard empty pages (e.g. if a user was kicked out).
17da2e6f 58global $CHAT_HTMLHEAD_OUT;
1f8abb89 59$CHAT_HTMLHEAD_OUT = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"><html><head><title>You are out!</title></head><body></body></html>";
1515a89e 60
c52b4db5 61// The HTML head for the message input page.
17da2e6f 62global $CHAT_HTMLHEAD_MSGINPUT;
1f8abb89 63$CHAT_HTMLHEAD_MSGINPUT = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"><html><head><title>Message Input</title></head><body>";
1515a89e 64
c52b4db5 65// The HTML code for the message input page, with JavaScript.
17da2e6f 66global $CHAT_HTMLHEAD_MSGINPUT_JS;
1d507186 67$CHAT_HTMLHEAD_MSGINPUT_JS = <<<EOD
68<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
69<html>
70 <head><title>Message Input</title>
71 <script type="text/javascript">
72 //<![CDATA[
73 scroll_active = true;
c52b4db5 74 function empty_field_and_submit() {
1d507186 75 document.fdummy.arsc_message.value=document.f.arsc_message.value;
76 document.fdummy.submit();
77 document.f.arsc_message.focus();
78 document.f.arsc_message.select();
79 return false;
80 }
81 //]]>
82 </script>
83 </head><body OnLoad="document.f.arsc_message.focus();document.f.arsc_message.select();">;
84EOD;
1515a89e 85
c52b4db5 86// Dummy data that gets output to the browser as needed, in order to make it show output.
17da2e6f 87global $CHAT_DUMMY_DATA;
6e5f40ea 88$CHAT_DUMMY_DATA = padding(200);
5c2f6a7f 89
848bb113 90/**
91 * @param int $n
92 * @return string
93 */
c52b4db5 94function padding($n) {
5c2f6a7f 95 $str = '';
c52b4db5
AD
96 for ($i = 0; $i < $n; $i++) {
97 $str .= "<!-- nix -->\n";
5c2f6a7f 98 }
99 return $str;
100}
1515a89e 101
848bb113 102/**
103 * Given an object containing all the necessary data,
104 * (defined by the form in mod_form.php) this function
105 * will create a new instance and return the id number
106 * of the new instance.
107 *
108 * @global object
109 * @param object $chat
110 * @return int
111 */
1515a89e 112function chat_add_instance($chat) {
c18269c7 113 global $DB;
1515a89e 114
115 $chat->timemodified = time();
116
a9637e7d
PS
117 $returnid = $DB->insert_record("chat", $chat);
118
3a2f9a2e
SB
119 if ($chat->schedule > 0) {
120 $event = new stdClass();
bea71d57 121 $event->type = CALENDAR_EVENT_TYPE_ACTION;
3a2f9a2e
SB
122 $event->name = $chat->name;
123 $event->description = format_module_intro('chat', $chat, $chat->coursemodule);
124 $event->courseid = $chat->course;
125 $event->groupid = 0;
126 $event->userid = 0;
127 $event->modulename = 'chat';
128 $event->instance = $returnid;
bea71d57 129 $event->eventtype = CHAT_EVENT_TYPE_CHATTIME;
3a2f9a2e 130 $event->timestart = $chat->chattime;
bea71d57 131 $event->timesort = $chat->chattime;
3a2f9a2e 132 $event->timeduration = 0;
8496c4af 133
e1cd93ce 134 calendar_event::create($event);
3a2f9a2e 135 }
9ffbdafc
AG
136
137 if (!empty($chat->completionexpected)) {
138 \core_completion\api::update_completion_date_event($chat->coursemodule, 'chat', $returnid, $chat->completionexpected);
139 }
140
8496c4af 141 return $returnid;
1515a89e 142}
143
848bb113 144/**
145 * Given an object containing all the necessary data,
146 * (defined by the form in mod_form.php) this function
147 * will update an existing instance with new data.
148 *
149 * @global object
150 * @param object $chat
dd88de0e 151 * @return bool
848bb113 152 */
1515a89e 153function chat_update_instance($chat) {
c18269c7 154 global $DB;
1515a89e 155
156 $chat->timemodified = time();
157 $chat->id = $chat->instance;
158
dd88de0e 159 $DB->update_record("chat", $chat);
8496c4af 160
39790bd8 161 $event = new stdClass();
8496c4af 162
fb77b89f
MN
163 if ($event->id = $DB->get_field('event', 'id', array('modulename' => 'chat',
164 'instance' => $chat->id, 'eventtype' => CHAT_EVENT_TYPE_CHATTIME))) {
8496c4af 165
3a2f9a2e 166 if ($chat->schedule > 0) {
bea71d57 167 $event->type = CALENDAR_EVENT_TYPE_ACTION;
3a2f9a2e
SB
168 $event->name = $chat->name;
169 $event->description = format_module_intro('chat', $chat, $chat->coursemodule);
170 $event->timestart = $chat->chattime;
bea71d57 171 $event->timesort = $chat->chattime;
3a2f9a2e 172
e1cd93ce 173 $calendarevent = calendar_event::load($event->id);
3a2f9a2e
SB
174 $calendarevent->update($event);
175 } else {
176 // Do not publish this event, so delete it.
e1cd93ce 177 $calendarevent = calendar_event::load($event->id);
3a2f9a2e
SB
178 $calendarevent->delete();
179 }
180 } else {
181 // No event, do we need to create one?
182 if ($chat->schedule > 0) {
183 $event = new stdClass();
bea71d57 184 $event->type = CALENDAR_EVENT_TYPE_ACTION;
3a2f9a2e
SB
185 $event->name = $chat->name;
186 $event->description = format_module_intro('chat', $chat, $chat->coursemodule);
187 $event->courseid = $chat->course;
188 $event->groupid = 0;
189 $event->userid = 0;
190 $event->modulename = 'chat';
191 $event->instance = $chat->id;
bea71d57 192 $event->eventtype = CHAT_EVENT_TYPE_CHATTIME;
3a2f9a2e 193 $event->timestart = $chat->chattime;
bea71d57 194 $event->timesort = $chat->chattime;
3a2f9a2e
SB
195 $event->timeduration = 0;
196
e1cd93ce 197 calendar_event::create($event);
3a2f9a2e 198 }
8496c4af 199 }
200
9ffbdafc
AG
201 $completionexpected = (!empty($chat->completionexpected)) ? $chat->completionexpected : null;
202 \core_completion\api::update_completion_date_event($chat->coursemodule, 'chat', $chat->id, $completionexpected);
203
dd88de0e 204 return true;
1515a89e 205}
206
848bb113 207/**
208 * Given an ID of an instance of this module,
209 * this function will permanently delete the instance
210 * and any data that depends on it.
211 *
212 * @global object
213 * @param int $id
214 * @return bool
215 */
1515a89e 216function chat_delete_instance($id) {
c18269c7 217 global $DB;
848bb113 218
c52b4db5 219 if (! $chat = $DB->get_record('chat', array('id' => $id))) {
1515a89e 220 return false;
221 }
222
223 $result = true;
224
c52b4db5 225 // Delete any dependent records here.
1515a89e 226
c52b4db5 227 if (! $DB->delete_records('chat', array('id' => $chat->id))) {
a71efae3 228 $result = false;
229 }
c52b4db5 230 if (! $DB->delete_records('chat_messages', array('chatid' => $chat->id))) {
a71efae3 231 $result = false;
232 }
c52b4db5 233 if (! $DB->delete_records('chat_messages_current', array('chatid' => $chat->id))) {
6e5f40ea 234 $result = false;
235 }
c52b4db5 236 if (! $DB->delete_records('chat_users', array('chatid' => $chat->id))) {
1515a89e 237 $result = false;
238 }
239
c52b4db5 240 if (! $DB->delete_records('event', array('modulename' => 'chat', 'instance' => $chat->id))) {
36eb856f 241 $result = false;
242 }
243
1515a89e 244 return $result;
245}
246
848bb113 247/**
248 * Given a course and a date, prints a summary of all chat rooms past and present
a3f66bde 249 * This function is called from block_recent_activity
848bb113 250 *
251 * @global object
252 * @global object
253 * @global object
254 * @param object $course
0b21e588 255 * @param bool $viewfullnames
848bb113 256 * @param int|string $timestart Timestamp
257 * @return bool
258 */
dd97c328 259function chat_print_recent_activity($course, $viewfullnames, $timestart) {
e09fc68b 260 global $CFG, $USER, $DB, $OUTPUT;
dd97c328 261
c52b4db5 262 // This is approximate only, but it is really fast.
dd97c328 263 $timeout = $CFG->chat_old_ping * 10;
264
d3bf6f92 265 if (!$mcms = $DB->get_records_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
266 FROM {course_modules} cm
267 JOIN {modules} md ON md.id = cm.module
268 JOIN {chat} ch ON ch.id = cm.instance
269 JOIN {chat_messages} chm ON chm.chatid = ch.id
270 WHERE chm.timestamp > ? AND ch.course = ? AND md.name = 'chat'
271 GROUP BY cm.id
272 ORDER BY lasttime ASC", array($timestart, $course->id))) {
dd97c328 273 return false;
274 }
275
276 $past = array();
277 $current = array();
c52b4db5 278 $modinfo = get_fast_modinfo($course); // Reference needed because we might load the groups.
dd97c328 279
c52b4db5 280 foreach ($mcms as $cmid => $mcm) {
fd4d41c3 281 if (!array_key_exists($cmid, $modinfo->cms)) {
dd97c328 282 continue;
283 }
fd4d41c3 284 $cm = $modinfo->cms[$cmid];
dd97c328 285 if (!$modinfo->cms[$cm->id]->uservisible) {
286 continue;
287 }
b7602a11 288
dd97c328 289 if (groups_get_activity_groupmode($cm) != SEPARATEGROUPS
6536217c 290 or has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
55607eff 291 if ($timeout > time() - $mcm->lasttime) {
dd97c328 292 $current[] = $cm;
293 } else {
294 $past[] = $cm;
295 }
296
297 continue;
298 }
299
c52b4db5 300 // Verify groups in separate mode.
e19c086c 301 if (!$mygroupids = $modinfo->get_groups($cm->groupingid)) {
dd97c328 302 continue;
303 }
0469cccf 304
c52b4db5
AD
305 // Ok, last post was not for my group - we have to query db to get last message from one of my groups.
306 // The only minor problem is that the order will not be correct.
dd97c328 307 $mygroupids = implode(',', $mygroupids);
dd97c328 308
d3bf6f92 309 if (!$mcm = $DB->get_record_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
310 FROM {course_modules} cm
311 JOIN {chat} ch ON ch.id = cm.instance
6e5f40ea 312 JOIN {chat_messages_current} chm ON chm.chatid = ch.id
d3bf6f92 313 WHERE chm.timestamp > ? AND cm.id = ? AND
314 (chm.groupid IN ($mygroupids) OR chm.groupid = 0)
315 GROUP BY cm.id", array($timestart, $cm->id))) {
dd97c328 316 continue;
317 }
fd4d41c3 318
55607eff
MG
319 $mcms[$cmid]->lasttime = $mcm->lasttime;
320 if ($timeout > time() - $mcm->lasttime) {
dd97c328 321 $current[] = $cm;
322 } else {
323 $past[] = $cm;
324 }
325 }
326
327 if (!$past and !$current) {
b7602a11 328 return false;
329 }
1515a89e 330
dd97c328 331 $strftimerecent = get_string('strftimerecent');
332
333 if ($past) {
97b97b63 334 echo $OUTPUT->heading(get_string("pastchats", 'chat').':', 3);
dd97c328 335
336 foreach ($past as $cm) {
337 $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
55607eff 338 $date = userdate($mcms[$cm->id]->lasttime, $strftimerecent);
dd97c328 339 echo '<div class="head"><div class="date">'.$date.'</div></div>';
c52b4db5 340 echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name, true).'</a></div>';
b7602a11 341 }
8f7dc7f1 342 }
343
344 if ($current) {
97b97b63 345 echo $OUTPUT->heading(get_string("currentchats", 'chat').':', 3);
dd97c328 346
c52b4db5 347 $oldest = floor((time() - $CFG->chat_old_ping) / 10) * 10; // Better db caching.
dd97c328 348
349 $timeold = time() - $CFG->chat_old_ping;
c52b4db5
AD
350 $timeold = floor($timeold / 10) * 10; // Better db caching.
351 $timeoldext = time() - ($CFG->chat_old_ping * 10); // JSless gui_basic needs much longer timeouts.
352 $timeoldext = floor($timeoldext / 10) * 10; // Better db caching.
dd97c328 353
c52b4db5 354 $params = array('timeold' => $timeold, 'timeoldext' => $timeoldext, 'cmid' => $cm->id);
d3bf6f92 355
488bbfb7 356 $timeout = "AND ((chu.version<>'basic' AND chu.lastping>:timeold) OR (chu.version='basic' AND chu.lastping>:timeoldext))";
dd97c328 357
358 foreach ($current as $cm) {
c52b4db5 359 // Count users first.
0eadedea
MG
360 $mygroupids = $modinfo->groups[$cm->groupingid];
361 if (!empty($mygroupids)) {
362 list($subquery, $subparams) = $DB->get_in_or_equal($mygroupids, SQL_PARAMS_NAMED, 'gid');
363 $params += $subparams;
364 $groupselect = "AND (chu.groupid $subquery OR chu.groupid = 0)";
dd97c328 365 } else {
366 $groupselect = "";
367 }
fd4d41c3 368
2072af6c
MN
369 $userfields = user_picture::fields('u');
370 if (!$users = $DB->get_records_sql("SELECT $userfields
d3bf6f92 371 FROM {course_modules} cm
372 JOIN {chat} ch ON ch.id = cm.instance
373 JOIN {chat_users} chu ON chu.chatid = ch.id
374 JOIN {user} u ON u.id = chu.userid
375 WHERE cm.id = :cmid $timeout $groupselect
1f47813b 376 GROUP BY $userfields", $params)) {
dd97c328 377 }
378
379 $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
55607eff 380 $date = userdate($mcms[$cm->id]->lasttime, $strftimerecent);
dd97c328 381
382 echo '<div class="head"><div class="date">'.$date.'</div></div>';
c52b4db5 383 echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name, true).'</a></div>';
dd97c328 384 echo '<div class="userlist">';
385 if ($users) {
386 echo '<ul>';
c52b4db5
AD
387 foreach ($users as $user) {
388 echo '<li>'.fullname($user, $viewfullnames).'</li>';
389 }
dd97c328 390 echo '</ul>';
391 }
392 echo '</div>';
393 }
b7602a11 394 }
395
396 return true;
1515a89e 397}
398
848bb113 399/**
400 * Function to be run periodically according to the moodle cron
401 * This function searches for things that need to be done, such
402 * as sending out mail, toggling flags etc ...
403 *
404 * @global object
405 * @return bool
406 */
1515a89e 407function chat_cron () {
d3bf6f92 408 global $DB;
1515a89e 409
fcd3a1ee 410 chat_update_chat_times();
411
7d792369 412 chat_delete_old_users();
413
c52b4db5 414 // Delete old messages with a single SQL query.
319038c3 415 $subselect = "SELECT c.keepdays
d3bf6f92 416 FROM {chat} c
417 WHERE c.id = {chat_messages}.chatid";
4388027c 418
319038c3 419 $sql = "DELETE
d3bf6f92 420 FROM {chat_messages}
6e5f40ea 421 WHERE ($subselect) > 0 AND timestamp < ( ".time()." -($subselect) * 24 * 3600)";
422
423 $DB->execute($sql);
424
425 $sql = "DELETE
426 FROM {chat_messages_current}
427 WHERE timestamp < ( ".time()." - 8 * 3600)";
4388027c 428
d3bf6f92 429 $DB->execute($sql);
22a4491a 430
1515a89e 431 return true;
432}
433
848bb113 434/**
435 * This standard function will check all instances of this module
436 * and make sure there are up-to-date events created for each of them.
437 * If courseid = 0, then every chat event in the site is checked, else
438 * only chat events belonging to the course specified are checked.
439 * This function is used, in its new format, by restore_refresh_events()
440 *
441 * @global object
442 * @param int $courseid
9ffbdafc
AG
443 * @param int|stdClass $instance Chat module instance or ID.
444 * @param int|stdClass $cm Course module object or ID.
848bb113 445 * @return bool
446 */
9ffbdafc 447function chat_refresh_events($courseid = 0, $instance = null, $cm = null) {
d3bf6f92 448 global $DB;
8496c4af 449
9ffbdafc
AG
450 // If we have instance information then we can just update the one event instead of updating all events.
451 if (isset($instance)) {
452 if (!is_object($instance)) {
453 $instance = $DB->get_record('chat', array('id' => $instance), '*', MUST_EXIST);
454 }
455 if (isset($cm)) {
456 if (!is_object($cm)) {
457 chat_prepare_update_events($instance);
458 return true;
459 } else {
460 chat_prepare_update_events($instance, $cm);
461 return true;
462 }
463 }
464 }
465
8496c4af 466 if ($courseid) {
c52b4db5 467 if (! $chats = $DB->get_records("chat", array("course" => $courseid))) {
8496c4af 468 return true;
469 }
470 } else {
d3bf6f92 471 if (! $chats = $DB->get_records("chat")) {
8496c4af 472 return true;
473 }
474 }
8496c4af 475 foreach ($chats as $chat) {
9ffbdafc 476 chat_prepare_update_events($chat);
8496c4af 477 }
478 return true;
479}
480
9ffbdafc
AG
481/**
482 * Updates both the normal and completion calendar events for chat.
483 *
484 * @param stdClass $chat The chat object (from the DB)
485 * @param stdClass $cm The course module object.
486 */
487function chat_prepare_update_events($chat, $cm = null) {
488 global $DB;
489 if (!isset($cm)) {
490 $cm = get_coursemodule_from_instance('chat', $chat->id, $chat->course);
491 }
492 $event = new stdClass();
493 $event->name = $chat->name;
494 $event->type = CALENDAR_EVENT_TYPE_ACTION;
495 $event->description = format_module_intro('chat', $chat, $cm->id);
496 $event->timestart = $chat->chattime;
497 $event->timesort = $chat->chattime;
fb77b89f
MN
498 if ($event->id = $DB->get_field('event', 'id', array('modulename' => 'chat', 'instance' => $chat->id,
499 'eventtype' => CHAT_EVENT_TYPE_CHATTIME))) {
9ffbdafc
AG
500 $calendarevent = calendar_event::load($event->id);
501 $calendarevent->update($event);
502 } else if ($chat->schedule > 0) {
503 // The chat is scheduled and the event should be published.
504 $event->courseid = $chat->course;
505 $event->groupid = 0;
506 $event->userid = 0;
507 $event->modulename = 'chat';
508 $event->instance = $chat->id;
509 $event->eventtype = CHAT_EVENT_TYPE_CHATTIME;
510 $event->timeduration = 0;
511 $event->visible = $cm->visible;
512 calendar_event::create($event);
513 }
514}
515
c52b4db5 516// Functions that require some SQL.
1515a89e 517
848bb113 518/**
519 * @global object
520 * @param int $chatid
521 * @param int $groupid
522 * @param int $groupingid
523 * @return array
524 */
a12e11c1 525function chat_get_users($chatid, $groupid=0, $groupingid=0) {
d3bf6f92 526 global $DB;
1515a89e 527
c52b4db5 528 $params = array('chatid' => $chatid, 'groupid' => $groupid, 'groupingid' => $groupingid);
84a2fdd7 529
530 if ($groupid) {
d3bf6f92 531 $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
84a2fdd7 532 } else {
533 $groupselect = "";
534 }
6e5f40ea 535
98da6021 536 if (!empty($groupingid)) {
d3bf6f92 537 $groupingjoin = "JOIN {groups_members} gm ON u.id = gm.userid
538 JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
6e5f40ea 539
a12e11c1 540 } else {
541 $groupingjoin = '';
542 }
b5de723d 543
3a11c09f
PS
544 $ufields = user_picture::fields('u');
545 return $DB->get_records_sql("SELECT DISTINCT $ufields, c.lastmessageping, c.firstping
546 FROM {chat_users} c
547 JOIN {user} u ON u.id = c.userid $groupingjoin
548 WHERE c.chatid = :chatid $groupselect
549 ORDER BY c.firstping ASC", $params);
1515a89e 550}
551
848bb113 552/**
553 * @global object
554 * @param int $chatid
555 * @param int $groupid
556 * @return array
557 */
84a2fdd7 558function chat_get_latest_message($chatid, $groupid=0) {
f33e1ed4 559 global $DB;
1515a89e 560
c52b4db5 561 $params = array('chatid' => $chatid, 'groupid' => $groupid);
1515a89e 562
84a2fdd7 563 if ($groupid) {
d3bf6f92 564 $groupselect = "AND (groupid=:groupid OR groupid=0)";
84a2fdd7 565 } else {
566 $groupselect = "";
567 }
568
e7521559 569 $sql = "SELECT *
547ac664 570 FROM {chat_messages_current} WHERE chatid = :chatid $groupselect
38e7a952 571 ORDER BY timestamp DESC, id DESC";
03cedd62 572
c52b4db5 573 // Return the lastest one message.
f33e1ed4 574 return $DB->get_record_sql($sql, $params, true);
1515a89e 575}
576
848bb113 577/**
578 * login if not already logged in
579 *
580 * @global object
581 * @global object
582 * @param int $chatid
583 * @param string $version
584 * @param int $groupid
585 * @param object $course
586 * @return bool|int Returns the chat users sid or false
587 */
a32c7772 588function chat_login_user($chatid, $version, $groupid, $course) {
d3bf6f92 589 global $USER, $DB;
590
c52b4db5
AD
591 if (($version != 'sockets') and $chatuser = $DB->get_record('chat_users', array('chatid' => $chatid,
592 'userid' => $USER->id,
593 'groupid' => $groupid))) {
594 // This will update logged user information.
516121bd 595 $chatuser->version = $version;
d96466d2 596 $chatuser->ip = $USER->lastip;
516121bd 597 $chatuser->lastping = time();
598 $chatuser->lang = current_language();
1515a89e 599
c52b4db5
AD
600 // Sometimes $USER->lastip is not setup properly during login.
601 // Update with current value if possible or provide a dummy value for the db.
d13ef2fb 602 if (empty($chatuser->ip)) {
603 $chatuser->ip = getremoteaddr();
d13ef2fb 604 }
605
7f0483f6 606 if (($chatuser->course != $course->id) or ($chatuser->userid != $USER->id)) {
516121bd 607 return false;
608 }
a8c31db2 609 $DB->update_record('chat_users', $chatuser);
610
516121bd 611 } else {
39790bd8 612 $chatuser = new stdClass();
516121bd 613 $chatuser->chatid = $chatid;
614 $chatuser->userid = $USER->id;
615 $chatuser->groupid = $groupid;
616 $chatuser->version = $version;
d96466d2 617 $chatuser->ip = $USER->lastip;
516121bd 618 $chatuser->lastping = $chatuser->firstping = $chatuser->lastmessageping = time();
619 $chatuser->sid = random_string(32);
c52b4db5
AD
620 $chatuser->course = $course->id; // Caching - needed for current_language too.
621 $chatuser->lang = current_language(); // Caching - to resource intensive to find out later.
516121bd 622
c52b4db5
AD
623 // Sometimes $USER->lastip is not setup properly during login.
624 // Update with current value if possible or provide a dummy value for the db.
274f0091 625 if (empty($chatuser->ip)) {
626 $chatuser->ip = getremoteaddr();
274f0091 627 }
628
a8c31db2 629 $DB->insert_record('chat_users', $chatuser);
516121bd 630
a32c7772 631 if ($version == 'sockets') {
c52b4db5 632 // Do not send 'enter' message, chatd will do it.
a32c7772 633 } else {
f49d814a 634 chat_send_chatmessage($chatuser, 'enter', true);
516121bd 635 }
1515a89e 636 }
637
638 return $chatuser->sid;
639}
640
848bb113 641/**
642 * Delete the old and in the way
643 *
644 * @global object
645 * @global object
646 */
7d792369 647function chat_delete_old_users() {
c52b4db5 648 // Delete the old and in the way.
d3bf6f92 649 global $CFG, $DB;
b5012f3e 650
e7fbd0b3 651 $timeold = time() - $CFG->chat_old_ping;
c52b4db5 652 $timeoldext = time() - ($CFG->chat_old_ping * 10); // JSless gui_basic needs much longer timeouts.
a32c7772 653
d3bf6f92 654 $query = "(version<>'basic' AND lastping<?) OR (version='basic' AND lastping<?)";
655 $params = array($timeold, $timeoldext);
7d792369 656
d3bf6f92 657 if ($oldusers = $DB->get_records_select('chat_users', $query, $params) ) {
658 $DB->delete_records_select('chat_users', $query, $params);
7d792369 659 foreach ($oldusers as $olduser) {
f49d814a 660 chat_send_chatmessage($olduser, 'exit', true);
7d792369 661 }
662 }
663}
1515a89e 664
848bb113 665/**
666 * Updates chat records so that the next chat time is correct
667 *
668 * @global object
669 * @param int $chatid
670 * @return void
671 */
fcd3a1ee 672function chat_update_chat_times($chatid=0) {
c52b4db5 673 // Updates chat records so that the next chat time is correct.
d3bf6f92 674 global $DB;
fcd3a1ee 675
676 $timenow = time();
d3bf6f92 677
c52b4db5 678 $params = array('timenow' => $timenow, 'chatid' => $chatid);
d3bf6f92 679
fcd3a1ee 680 if ($chatid) {
d3bf6f92 681 if (!$chats[] = $DB->get_record_select("chat", "id = :chatid AND chattime <= :timenow AND schedule > 0", $params)) {
fcd3a1ee 682 return;
683 }
684 } else {
d3bf6f92 685 if (!$chats = $DB->get_records_select("chat", "chattime <= :timenow AND schedule > 0", $params)) {
fcd3a1ee 686 return;
687 }
688 }
689
690 foreach ($chats as $chat) {
691 switch ($chat->schedule) {
c52b4db5
AD
692 case 1: // Single event - turn off schedule and disable.
693 $chat->chattime = 0;
694 $chat->schedule = 0;
695 break;
696 case 2: // Repeat daily.
697 while ($chat->chattime <= $timenow) {
698 $chat->chattime += 24 * 3600;
699 }
700 break;
701 case 3: // Repeat weekly.
702 while ($chat->chattime <= $timenow) {
703 $chat->chattime += 7 * 24 * 3600;
704 }
705 break;
fcd3a1ee 706 }
d3bf6f92 707 $DB->update_record("chat", $chat);
708
c52b4db5 709 $event = new stdClass(); // Update calendar too.
8496c4af 710
d3bf6f92 711 $cond = "modulename='chat' AND instance = :chatid AND timestart <> :chattime";
600b8152 712 $params = array('chattime' => $chat->chattime, 'chatid' => $chat->id);
d3bf6f92 713
714 if ($event->id = $DB->get_field_select('event', 'id', $cond, $params)) {
ec4b1e61
CB
715 $event->timestart = $chat->chattime;
716 $event->timesort = $chat->chattime;
e1cd93ce 717 $calendarevent = calendar_event::load($event->id);
1d5bd3d2 718 $calendarevent->update($event, false);
8496c4af 719 }
fcd3a1ee 720 }
721}
722
f49d814a
FM
723/**
724 * Send a message on the chat.
725 *
726 * @param object $chatuser The chat user record.
727 * @param string $messagetext The message to be sent.
307dce6c 728 * @param bool $issystem False for non-system messages, true for system messages.
f49d814a
FM
729 * @param object $cm The course module object, pass it to save a database query when we trigger the event.
730 * @return int The message ID.
5bcfd504 731 * @since Moodle 2.6
f49d814a 732 */
307dce6c 733function chat_send_chatmessage($chatuser, $messagetext, $issystem = false, $cm = null) {
f49d814a
FM
734 global $DB;
735
736 $message = new stdClass();
737 $message->chatid = $chatuser->chatid;
738 $message->userid = $chatuser->userid;
739 $message->groupid = $chatuser->groupid;
740 $message->message = $messagetext;
307dce6c 741 $message->issystem = $issystem ? 1 : 0;
f49d814a
FM
742 $message->timestamp = time();
743
744 $messageid = $DB->insert_record('chat_messages', $message);
745 $DB->insert_record('chat_messages_current', $message);
746 $message->id = $messageid;
747
307dce6c 748 if (!$issystem) {
f49d814a
FM
749
750 if (empty($cm)) {
751 $cm = get_coursemodule_from_instance('chat', $chatuser->chatid, $chatuser->course);
752 }
753
754 $params = array(
755 'context' => context_module::instance($cm->id),
756 'objectid' => $message->id,
757 // We set relateduserid, because when triggered from the chat daemon, the event userid is null.
758 'relateduserid' => $chatuser->userid
759 );
760 $event = \mod_chat\event\message_sent::create($params);
761 $event->add_record_snapshot('chat_messages', $message);
762 $event->trigger();
763 }
764
765 return $message->id;
766}
767
848bb113 768/**
769 * @global object
770 * @global object
771 * @param object $message
772 * @param int $courseid
773 * @param object $sender
774 * @param object $currentuser
c52b4db5 775 * @param string $chatlastrow
848bb113 776 * @return bool|string Returns HTML or false
777 */
c52b4db5 778function chat_format_message_manually($message, $courseid, $sender, $currentuser, $chatlastrow = null) {
d3222955 779 global $CFG, $USER, $OUTPUT;
1515a89e 780
39790bd8 781 $output = new stdClass();
c52b4db5
AD
782 $output->beep = false; // By default.
783 $output->refreshusers = false; // By default.
7d792369 784
d6e7a63d
PS
785 // Find the correct timezone for displaying this message.
786 $tz = core_date::get_user_timezone($currentuser);
787
b5de723d 788 $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
789
c52b4db5 790 $message->picture = $OUTPUT->user_picture($sender, array('size' => false, 'courseid' => $courseid, 'link' => false));
d3222955 791
75d07096 792 if ($courseid) {
c52b4db5 793 $message->picture = "<a onclick=\"window.open('$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid')\"".
5eb1703c 794 " href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">$message->picture</a>";
582de679 795 }
1515a89e 796
c52b4db5
AD
797 // Calculate the row class.
798 if ($chatlastrow !== null) {
799 $rowclass = ' class="r'.$chatlastrow.'" ';
aa5c32fd 800 } else {
801 $rowclass = '';
802 }
803
c52b4db5 804 // Start processing the message.
75d07096 805
307dce6c 806 if (!empty($message->issystem)) {
c52b4db5 807 // System event.
75d07096 808 $output->text = $message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender));
c52b4db5
AD
809 $output->html = '<table class="chat-event"><tr'.$rowclass.'><td class="picture">'.$message->picture.'</td>';
810 $output->html .= '<td class="text"><span class="event">'.$output->text.'</span></td></tr></table>';
83f47164
JM
811 $output->basic = '<tr class="r1">
812 <th scope="row" class="cell c1 title"></th>
813 <td class="cell c2 text">' . get_string('message'.$message->message, 'chat', fullname($sender)) . '</td>
814 <td class="cell c3">' . $message->strtime . '</td>
815 </tr>';
c52b4db5
AD
816 if ($message->message == 'exit' or $message->message == 'enter') {
817 $output->refreshusers = true; // Force user panel refresh ASAP.
516121bd 818 }
75d07096 819 return $output;
1515a89e 820 }
821
c52b4db5 822 // It's not a system event.
376be6ae 823 $rawtext = trim($message->message);
82a524ef 824
376be6ae
NP
825 // Options for format_text, when we get to it...
826 // format_text call will parse the text to clean and filter it.
827 // It cannot be called here as HTML-isation interferes with special case
828 // recognition, but *must* be called on any user-sourced text to be inserted
829 // into $outmain.
39790bd8 830 $options = new stdClass();
82a524ef 831 $options->para = false;
cd29373c 832 $options->blanktarget = true;
927a7808 833
c52b4db5
AD
834 // And now check for special cases.
835 $patternto = '#^\s*To\s([^:]+):(.*)#';
927a7808 836 $special = false;
837
376be6ae 838 if (substr($rawtext, 0, 5) == 'beep ') {
c52b4db5 839 // It's a beep!
927a7808 840 $special = true;
376be6ae 841 $beepwho = trim(substr($rawtext, 5));
9f85bed4 842
c52b4db5 843 if ($beepwho == 'all') { // Everyone.
83f47164
JM
844 $outinfobasic = get_string('messagebeepseveryone', 'chat', fullname($sender));
845 $outinfo = $message->strtime . ': ' . $outinfobasic;
75d07096 846 $outmain = '';
83f47164 847
c52b4db5 848 $output->beep = true; // Eventually this should be set to a filename uploaded by the user.
7d792369 849
c52b4db5 850 } else if ($beepwho == $currentuser->id) { // Current user.
83f47164
JM
851 $outinfobasic = get_string('messagebeepsyou', 'chat', fullname($sender));
852 $outinfo = $message->strtime . ': ' . $outinfobasic;
75d07096 853 $outmain = '';
854 $output->beep = true;
264867fd 855
c52b4db5 856 } else { // Something is not caught?
7d792369 857 return false;
858 }
376be6ae 859 } else if (substr($rawtext, 0, 1) == '/') { // It's a user command.
6c6ed54a 860 $special = true;
1d507186 861 $pattern = '#(^\/)(\w+).*#';
376be6ae 862 preg_match($pattern, $rawtext, $matches);
6c6ed54a
FM
863 $command = isset($matches[2]) ? $matches[2] : false;
864 // Support some IRC commands.
c52b4db5 865 switch ($command) {
6c6ed54a
FM
866 case 'me':
867 $outinfo = $message->strtime;
376be6ae
NP
868 $text = '*** <b>'.$sender->firstname.' '.substr($rawtext, 4).'</b>';
869 $outmain = format_text($text, FORMAT_MOODLE, $options, $courseid);
6c6ed54a
FM
870 break;
871 default:
872 // Error, we set special back to false to use the classic message output.
873 $special = false;
874 break;
1515a89e 875 }
376be6ae 876 } else if (preg_match($patternto, $rawtext)) {
7f0483f6 877 $special = true;
6c6ed54a 878 $matches = array();
376be6ae 879 preg_match($patternto, $rawtext, $matches);
6c6ed54a 880 if (isset($matches[1]) && isset($matches[2])) {
376be6ae 881 $text = format_text($matches[2], FORMAT_MOODLE, $options, $courseid);
6c6ed54a 882 $outinfo = $message->strtime;
376be6ae 883 $outmain = $sender->firstname.' '.get_string('saidto', 'chat').' <i>'.$matches[1].'</i>: '.$text;
6c6ed54a
FM
884 } else {
885 // Error, we set special back to false to use the classic message output.
886 $special = false;
887 }
927a7808 888 }
9f85bed4 889
c52b4db5 890 if (!$special) {
376be6ae 891 $text = format_text($rawtext, FORMAT_MOODLE, $options, $courseid);
75d07096 892 $outinfo = $message->strtime.' '.$sender->firstname;
7d792369 893 $outmain = $text;
1515a89e 894 }
264867fd 895
c52b4db5 896 // Format the message as a small table.
1515a89e 897
75d07096 898 $output->text = strip_tags($outinfo.': '.$outmain);
7d792369 899
c52b4db5
AD
900 $output->html = "<table class=\"chat-message\"><tr$rowclass><td class=\"picture\" valign=\"top\">$message->picture</td>";
901 $output->html .= "<td class=\"text\"><span class=\"title\">$outinfo</span>";
75d07096 902 if ($outmain) {
903 $output->html .= ": $outmain";
83f47164
JM
904 $output->basic = '<tr class="r0">
905 <th scope="row" class="cell c1 title">' . $sender->firstname . '</th>
906 <td class="cell c2 text">' . $outmain . '</td>
907 <td class="cell c3">' . $message->strtime . '</td>
908 </tr>';
6ee78cee 909 } else {
83f47164
JM
910 $output->basic = '<tr class="r1">
911 <th scope="row" class="cell c1 title"></th>
912 <td class="cell c2 text">' . $outinfobasic . '</td>
913 <td class="cell c3">' . $message->strtime . '</td>
914 </tr>';
7d792369 915 }
75d07096 916 $output->html .= "</td></tr></table>";
917 return $output;
b5de723d 918}
919
848bb113 920/**
c52b4db5 921 * Given a message object this function formats it appropriately into text and html then returns the formatted data
848bb113 922 * @global object
923 * @param object $message
924 * @param int $courseid
925 * @param object $currentuser
c52b4db5 926 * @param string $chatlastrow
848bb113 927 * @return bool|string Returns HTML or false
928 */
c52b4db5 929function chat_format_message($message, $courseid, $currentuser, $chatlastrow=null) {
d3bf6f92 930 global $DB;
b5de723d 931
c52b4db5 932 static $users; // Cache user lookups.
78c98892 933
934 if (isset($users[$message->userid])) {
935 $user = $users[$message->userid];
c52b4db5 936 } else if ($user = $DB->get_record('user', array('id' => $message->userid), user_picture::fields())) {
78c98892 937 $users[$message->userid] = $user;
938 } else {
c52b4db5 939 return null;
b5de723d 940 }
c52b4db5 941 return chat_format_message_manually($message, $courseid, $user, $currentuser, $chatlastrow);
1515a89e 942}
943
75d07096 944/**
945 * @global object
d0157d82
RT
946 * @param object $message message to be displayed.
947 * @param mixed $chatuser user chat data
948 * @param object $currentuser current user for whom the message should be displayed.
949 * @param int $groupingid course module grouping id
950 * @param string $theme name of the chat theme.
75d07096 951 * @return bool|string Returns HTML or false
952 */
d0157d82 953function chat_format_message_theme ($message, $chatuser, $currentuser, $groupingid, $theme = 'bubble') {
a2592fec
AD
954 global $CFG, $USER, $OUTPUT, $COURSE, $DB, $PAGE;
955 require_once($CFG->dirroot.'/mod/chat/locallib.php');
75d07096 956
c52b4db5 957 static $users; // Cache user lookups.
75d07096 958
39790bd8 959 $result = new stdClass();
75d07096 960
961 if (file_exists($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php')) {
962 include($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php');
963 }
964
965 if (isset($users[$message->userid])) {
966 $sender = $users[$message->userid];
c52b4db5 967 } else if ($sender = $DB->get_record('user', array('id' => $message->userid), user_picture::fields())) {
75d07096 968 $users[$message->userid] = $sender;
969 } else {
c52b4db5 970 return null;
75d07096 971 }
972
d6e7a63d
PS
973 // Find the correct timezone for displaying this message.
974 $tz = core_date::get_user_timezone($currentuser);
75d07096 975
d0157d82 976 if (empty($chatuser->course)) {
75d07096 977 $courseid = $COURSE->id;
d0157d82
RT
978 } else {
979 $courseid = $chatuser->course;
75d07096 980 }
981
982 $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
c52b4db5 983 $message->picture = $OUTPUT->user_picture($sender, array('courseid' => $courseid));
75d07096 984
c52b4db5 985 $message->picture = "<a target='_blank'".
56302d48 986 " href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">$message->picture</a>";
75d07096 987
c52b4db5 988 // Start processing the message.
307dce6c 989 if (!empty($message->issystem)) {
75d07096 990 $result->type = 'system';
991
a2592fec
AD
992 $senderprofile = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&amp;course='.$courseid;
993 $event = get_string('message'.$message->message, 'chat', fullname($sender));
994 $eventmessage = new event_message($senderprofile, fullname($sender), $message->strtime, $event, $theme);
995
996 $output = $PAGE->get_renderer('mod_chat');
997 $result->html = $output->render($eventmessage);
998
75d07096 999 return $result;
1000 }
1001
c52b4db5 1002 // It's not a system event.
376be6ae 1003 $rawtext = trim($message->message);
75d07096 1004
376be6ae
NP
1005 // Options for format_text, when we get to it...
1006 // format_text call will parse the text to clean and filter it.
1007 // It cannot be called here as HTML-isation interferes with special case
1008 // recognition, but *must* be called on any user-sourced text to be inserted
1009 // into $outmain.
39790bd8 1010 $options = new stdClass();
75d07096 1011 $options->para = false;
cd29373c 1012 $options->blanktarget = true;
75d07096 1013
c52b4db5 1014 // And now check for special cases.
75d07096 1015 $special = false;
1016 $outtime = $message->strtime;
1017
6c6ed54a 1018 // Initialise variables.
d0157d82 1019 $outmain = '';
c52b4db5 1020 $patternto = '#^\s*To\s([^:]+):(.*)#';
d0157d82 1021
376be6ae 1022 if (substr($rawtext, 0, 5) == 'beep ') {
75d07096 1023 $special = true;
c52b4db5 1024 // It's a beep!
75d07096 1025 $result->type = 'beep';
376be6ae 1026 $beepwho = trim(substr($rawtext, 5));
75d07096 1027
c52b4db5
AD
1028 if ($beepwho == 'all') { // Everyone.
1029 $outmain = get_string('messagebeepseveryone', 'chat', fullname($sender));
1030 } else if ($beepwho == $currentuser->id) { // Current user.
75d07096 1031 $outmain = get_string('messagebeepsyou', 'chat', fullname($sender));
c52b4db5
AD
1032 } else if ($sender->id == $currentuser->id) { // Something is not caught?
1033 // Allow beep for a active chat user only, else user can beep anyone and get fullname.
d0157d82 1034 if (!empty($chatuser) && is_numeric($beepwho)) {
c52b4db5
AD
1035 $chatusers = chat_get_users($chatuser->chatid, $chatuser->groupid, $groupingid);
1036 if (array_key_exists($beepwho, $chatusers)) {
1037 $outmain = get_string('messageyoubeep', 'chat', fullname($chatusers[$beepwho]));
1038 } else {
1039 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
1040 }
d0157d82
RT
1041 } else {
1042 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
1043 }
75d07096 1044 }
376be6ae 1045 } else if (substr($rawtext, 0, 1) == '/') { // It's a user command.
75d07096 1046 $special = true;
1047 $result->type = 'command';
75d07096 1048 $pattern = '#(^\/)(\w+).*#';
376be6ae 1049 preg_match($pattern, $rawtext, $matches);
6c6ed54a
FM
1050 $command = isset($matches[2]) ? $matches[2] : false;
1051 // Support some IRC commands.
c52b4db5 1052 switch ($command) {
6c6ed54a 1053 case 'me':
376be6ae
NP
1054 $text = '*** <b>'.$sender->firstname.' '.substr($rawtext, 4).'</b>';
1055 $outmain = format_text($text, FORMAT_MOODLE, $options, $courseid);
6c6ed54a
FM
1056 break;
1057 default:
1058 // Error, we set special back to false to use the classic message output.
1059 $special = false;
1060 break;
75d07096 1061 }
376be6ae 1062 } else if (preg_match($patternto, $rawtext)) {
75d07096 1063 $special = true;
1064 $result->type = 'dialogue';
6c6ed54a 1065 $matches = array();
376be6ae 1066 preg_match($patternto, $rawtext, $matches);
6c6ed54a 1067 if (isset($matches[1]) && isset($matches[2])) {
376be6ae
NP
1068 $text = format_text($matches[2], FORMAT_MOODLE, $options, $courseid);
1069 $outmain = $sender->firstname.' <b>'.get_string('saidto', 'chat').'</b> <i>'.$matches[1].'</i>: '.$text;
6c6ed54a
FM
1070 } else {
1071 // Error, we set special back to false to use the classic message output.
1072 $special = false;
1073 }
75d07096 1074 }
1075
6c6ed54a 1076 if (!$special) {
376be6ae 1077 $text = format_text($rawtext, FORMAT_MOODLE, $options, $courseid);
75d07096 1078 $outmain = $text;
1079 }
1080
1081 $result->text = strip_tags($outtime.': '.$outmain);
1082
a2592fec 1083 $mymessageclass = '';
75d07096 1084 if ($sender->id == $USER->id) {
a2592fec 1085 $mymessageclass = 'chat-message-mymessage';
75d07096 1086 }
1087
a2592fec 1088 $senderprofile = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&amp;course='.$courseid;
c52b4db5
AD
1089 $usermessage = new user_message($senderprofile, fullname($sender), $message->picture,
1090 $mymessageclass, $outtime, $outmain, $theme);
a2592fec
AD
1091
1092 $output = $PAGE->get_renderer('mod_chat');
1093 $result->html = $output->render($usermessage);
1094
c52b4db5 1095 // When user beeps other user, then don't show any timestamp to other users in chat.
d0157d82
RT
1096 if (('' === $outmain) && $special) {
1097 return false;
1098 } else {
1099 return $result;
1100 }
75d07096 1101}
1102
83064f9c 1103/**
1104 * @global object $DB
1105 * @global object $CFG
1106 * @global object $COURSE
1107 * @global object $OUTPUT
1108 * @param object $users
1109 * @param object $course
1110 * @return array return formatted user list
1111 */
1112function chat_format_userlist($users, $course) {
1113 global $CFG, $DB, $COURSE, $OUTPUT;
1114 $result = array();
c52b4db5 1115 foreach ($users as $user) {
83064f9c 1116 $item = array();
1117 $item['name'] = fullname($user);
ff0e58c8 1118 $item['url'] = $CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id;
812dbaf7 1119 $item['picture'] = $OUTPUT->user_picture($user);
83064f9c 1120 $item['id'] = $user->id;
1121 $result[] = $item;
1122 }
1123 return $result;
1124}
1125
1126/**
1127 * Print json format error
1128 * @param string $level
1129 * @param string $msg
1130 */
1131function chat_print_error($level, $msg) {
1132 header('Content-Length: ' . ob_get_length() );
6bdfef5d 1133 $error = new stdClass();
83064f9c 1134 $error->level = $level;
1135 $error->msg = $msg;
1136 $response['error'] = $error;
1137 echo json_encode($response);
1138 ob_end_flush();
1139 exit;
1140}
1141
848bb113 1142/**
b2b4ec30
RT
1143 * List the actions that correspond to a view of this module.
1144 * This is used by the participation report.
1145 *
1146 * Note: This is not used by new logging system. Event with
1147 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1148 * be considered as view action.
1149 *
848bb113 1150 * @return array
1151 */
f3221af9 1152function chat_get_view_actions() {
c52b4db5 1153 return array('view', 'view all', 'report');
f3221af9 1154}
1155
848bb113 1156/**
b2b4ec30
RT
1157 * List the actions that correspond to a post of this module.
1158 * This is used by the participation report.
1159 *
1160 * Note: This is not used by new logging system. Event with
1161 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1162 * will be considered as post action.
1163 *
848bb113 1164 * @return array
1165 */
f3221af9 1166function chat_get_post_actions() {
1167 return array('talk');
1168}
1169
848bb113 1170/**
e9dfeec9 1171 * @deprecated since 3.3
063b7ee6 1172 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
848bb113 1173 * @global object
1174 * @global object
1175 * @param array $courses
1176 * @param array $htmlarray Passed by reference
1177 */
9ca0187e 1178function chat_print_overview($courses, &$htmlarray) {
1179 global $USER, $CFG;
1180
e9dfeec9
MN
1181 debugging('The function chat_print_overview() is now deprecated.', DEBUG_DEVELOPER);
1182
9ca0187e 1183 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1184 return array();
1185 }
1186
c52b4db5 1187 if (!$chats = get_all_instances_in_courses('chat', $courses)) {
9ca0187e 1188 return;
1189 }
1190
1191 $strchat = get_string('modulename', 'chat');
1192 $strnextsession = get_string('nextsession', 'chat');
9ca0187e 1193
1194 foreach ($chats as $chat) {
c52b4db5 1195 if ($chat->chattime and $chat->schedule) { // A chat is scheduled.
a2a37336 1196 $str = '<div class="chat overview"><div class="name">'.
c52b4db5 1197 $strchat.': <a '.($chat->visible ? '' : ' class="dimmed"').
a2a37336 1198 ' href="'.$CFG->wwwroot.'/mod/chat/view.php?id='.$chat->coursemodule.'">'.
1199 $chat->name.'</a></div>';
1200 $str .= '<div class="info">'.$strnextsession.': '.userdate($chat->chattime).'</div></div>';
1201
1202 if (empty($htmlarray[$chat->course]['chat'])) {
1203 $htmlarray[$chat->course]['chat'] = $str;
1204 } else {
1205 $htmlarray[$chat->course]['chat'] .= $str;
1206 }
9ca0187e 1207 }
9ca0187e 1208 }
1209}
1210
0b5a80a1 1211
1212/**
1213 * Implementation of the function for printing the form elements that control
1214 * whether the course reset functionality affects the chat.
848bb113 1215 *
1216 * @param object $mform form passed by reference
0b5a80a1 1217 */
1218function chat_reset_course_form_definition(&$mform) {
1219 $mform->addElement('header', 'chatheader', get_string('modulenameplural', 'chat'));
c52b4db5 1220 $mform->addElement('advcheckbox', 'reset_chat', get_string('removemessages', 'chat'));
0b5a80a1 1221}
1222
1223/**
1224 * Course reset form defaults.
848bb113 1225 *
1226 * @param object $course
1227 * @return array
0b5a80a1 1228 */
1229function chat_reset_course_form_defaults($course) {
c52b4db5 1230 return array('reset_chat' => 1);
0b5a80a1 1231}
1232
1233/**
72d2982e 1234 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 1235 * chat messages for course $data->courseid.
848bb113 1236 *
1237 * @global object
1238 * @global object
1239 * @param object $data the data submitted from the reset course.
0b5a80a1 1240 * @return array status array
1241 */
1242function chat_reset_userdata($data) {
d3bf6f92 1243 global $CFG, $DB;
0b5a80a1 1244
1245 $componentstr = get_string('modulenameplural', 'chat');
1246 $status = array();
1247
1248 if (!empty($data->reset_chat)) {
1249 $chatessql = "SELECT ch.id
d3bf6f92 1250 FROM {chat} ch
1251 WHERE ch.course=?";
1252 $params = array($data->courseid);
0b5a80a1 1253
d3bf6f92 1254 $DB->delete_records_select('chat_messages', "chatid IN ($chatessql)", $params);
6e5f40ea 1255 $DB->delete_records_select('chat_messages_current', "chatid IN ($chatessql)", $params);
d3bf6f92 1256 $DB->delete_records_select('chat_users', "chatid IN ($chatessql)", $params);
c52b4db5 1257 $status[] = array('component' => $componentstr, 'item' => get_string('removemessages', 'chat'), 'error' => false);
0b5a80a1 1258 }
1259
c52b4db5 1260 // Updating dates - shift may be negative too.
0b5a80a1 1261 if ($data->timeshift) {
0d14fcbc
AA
1262 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1263 // See MDL-9367.
0b5a80a1 1264 shift_course_mod_dates('chat', array('chattime'), $data->timeshift, $data->courseid);
c52b4db5 1265 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
0b5a80a1 1266 }
1267
1268 return $status;
1269}
1270
f432bebf 1271/**
1272 * Returns all other caps used in module
848bb113 1273 *
1274 * @return array
f432bebf 1275 */
1276function chat_get_extra_capabilities() {
1277 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
1278}
1279
47cfd331 1280
42f103be 1281/**
1282 * @param string $feature FEATURE_xx constant for requested feature
1283 * @return mixed True if module supports feature, null if doesn't know
1284 */
1285function chat_supports($feature) {
1286 switch($feature) {
c52b4db5
AD
1287 case FEATURE_GROUPS:
1288 return true;
1289 case FEATURE_GROUPINGS:
1290 return true;
c52b4db5
AD
1291 case FEATURE_MOD_INTRO:
1292 return true;
1293 case FEATURE_BACKUP_MOODLE2:
1294 return true;
1295 case FEATURE_COMPLETION_TRACKS_VIEWS:
1296 return true;
1297 case FEATURE_GRADE_HAS_GRADE:
1298 return false;
1299 case FEATURE_GRADE_OUTCOMES:
1300 return true;
1301 case FEATURE_SHOW_DESCRIPTION:
1302 return true;
1303 default:
1304 return null;
42f103be 1305 }
1306}
b14ae498 1307
1308function chat_extend_navigation($navigation, $course, $module, $cm) {
36ab2fed 1309 global $CFG;
0b29477b
SH
1310
1311 $currentgroup = groups_get_activity_group($cm, true);
4f0c2d00 1312
6536217c 1313 if (has_capability('mod/chat:chat', context_module::instance($cm->id))) {
b14ae498 1314 $strenterchat = get_string('enterchat', 'chat');
b14ae498 1315
1316 $target = $CFG->wwwroot.'/mod/chat/';
c52b4db5 1317 $params = array('id' => $cm->instance);
b14ae498 1318
1319 if ($currentgroup) {
1320 $params['groupid'] = $currentgroup;
1321 }
1322
1323 $links = array();
e7521559 1324
36ab2fed 1325 $url = new moodle_url($target.'gui_'.$CFG->chat_method.'/index.php', $params);
c52b4db5
AD
1326 $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup,
1327 array('height' => 500, 'width' => 700));
36ab2fed 1328 $links[] = new action_link($url, $strenterchat, $action);
b14ae498 1329
af140288 1330 $url = new moodle_url($target.'gui_basic/index.php', $params);
c52b4db5
AD
1331 $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup,
1332 array('height' => 500, 'width' => 700));
af140288 1333 $links[] = new action_link($url, get_string('noframesjs', 'message'), $action);
b14ae498 1334
1335 foreach ($links as $link) {
c52b4db5 1336 $navigation->add($link->text, $link, navigation_node::TYPE_SETTING, null , null, new pix_icon('i/group' , ''));
b14ae498 1337 }
1338 }
1339
1340 $chatusers = chat_get_users($cm->instance, $currentgroup, $cm->groupingid);
c52b4db5 1341 if (is_array($chatusers) && count($chatusers) > 0) {
3406acde 1342 $users = $navigation->add(get_string('currentusers', 'chat'));
b14ae498 1343 foreach ($chatusers as $chatuser) {
c52b4db5
AD
1344 $userlink = new moodle_url('/user/view.php', array('id' => $chatuser->id, 'course' => $course->id));
1345 $users->add(fullname($chatuser).' '.format_time(time() - $chatuser->lastmessageping),
1346 $userlink, navigation_node::TYPE_USER, null, null, new pix_icon('i/user', ''));
b14ae498 1347 }
1348 }
1349}
1350
0b29477b
SH
1351/**
1352 * Adds module specific settings to the settings block
1353 *
1354 * @param settings_navigation $settings The settings navigation object
1355 * @param navigation_node $chatnode The node to add module settings to
1356 */
1357function chat_extend_settings_navigation(settings_navigation $settings, navigation_node $chatnode) {
1358 global $DB, $PAGE, $USER;
b14ae498 1359 $chat = $DB->get_record("chat", array("id" => $PAGE->cm->instance));
0b29477b 1360
b14ae498 1361 if ($chat->chattime && $chat->schedule) {
c52b4db5
AD
1362 $nextsessionnode = $chatnode->add(get_string('nextsession', 'chat').
1363 ': '.userdate($chat->chattime).
1c2a11fc 1364 ' ('.usertimezone($USER->timezone).')');
3406acde 1365 $nextsessionnode->add_class('note');
b14ae498 1366 }
1367
1368 $currentgroup = groups_get_activity_group($PAGE->cm, true);
1369 if ($currentgroup) {
1370 $groupselect = " AND groupid = '$currentgroup'";
1371 } else {
1372 $groupselect = '';
1373 }
1374
c52b4db5 1375 if ($chat->studentlogs || has_capability('mod/chat:readlog', $PAGE->cm->context)) {
b14ae498 1376 if ($DB->get_records_select('chat_messages', "chatid = ? $groupselect", array($chat->id))) {
c52b4db5 1377 $chatnode->add(get_string('viewreport', 'chat'), new moodle_url('/mod/chat/report.php', array('id' => $PAGE->cm->id)));
b14ae498 1378 }
1379 }
50d76994 1380}
a8e3b008
DC
1381
1382/**
1383 * user logout event handler
1384 *
c8135e8b
FM
1385 * @param \core\event\user_loggedout $event The event.
1386 * @return void
a8e3b008 1387 */
c8135e8b 1388function chat_user_logout(\core\event\user_loggedout $event) {
a8e3b008 1389 global $DB;
c8135e8b 1390 $DB->delete_records('chat_users', array('userid' => $event->objectid));
a8e3b008 1391}
b1627a92
DC
1392
1393/**
1394 * Return a list of page types
1395 * @param string $pagetype current page type
1396 * @param stdClass $parentcontext Block's parent context
1397 * @param stdClass $currentcontext Current context of block
1398 */
b38e2e28 1399function chat_page_type_list($pagetype, $parentcontext, $currentcontext) {
c52b4db5
AD
1400 $modulepagetype = array('mod-chat-*' => get_string('page-mod-chat-x', 'chat'));
1401 return $modulepagetype;
b1627a92 1402}
8380bc7f
JL
1403
1404/**
1405 * Return a list of the latest messages in the given chat session.
1406 *
1407 * @param stdClass $chatuser chat user session data
1408 * @param int $chatlasttime last time messages were retrieved
1409 * @return array list of messages
1410 * @since Moodle 3.0
1411 */
1412function chat_get_latest_messages($chatuser, $chatlasttime) {
1413 global $DB;
1414
1415 $params = array('groupid' => $chatuser->groupid, 'chatid' => $chatuser->chatid, 'lasttime' => $chatlasttime);
1416
1417 $groupselect = $chatuser->groupid ? " AND (groupid=" . $chatuser->groupid . " OR groupid=0) " : "";
1418
1419 return $DB->get_records_select('chat_messages_current', 'chatid = :chatid AND timestamp > :lasttime ' . $groupselect,
1420 $params, 'timestamp ASC');
1421}
5841b9d5
JL
1422
1423/**
1424 * Mark the activity completed (if required) and trigger the course_module_viewed event.
1425 *
1426 * @param stdClass $chat chat object
1427 * @param stdClass $course course object
1428 * @param stdClass $cm course module object
1429 * @param stdClass $context context object
1430 * @since Moodle 3.0
1431 */
1432function chat_view($chat, $course, $cm, $context) {
1433
1434 // Trigger course_module_viewed event.
1435 $params = array(
1436 'context' => $context,
1437 'objectid' => $chat->id
1438 );
1439
1440 $event = \mod_chat\event\course_module_viewed::create($params);
1441 $event->add_record_snapshot('course_modules', $cm);
1442 $event->add_record_snapshot('course', $course);
1443 $event->add_record_snapshot('chat', $chat);
1444 $event->trigger();
1445
1446 // Completion.
1447 $completion = new completion_info($course);
1448 $completion->set_module_viewed($cm);
1449}
bea71d57 1450
bea71d57 1451/**
59391e80
MN
1452 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1453 *
1454 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1455 * is not displayed on the block.
bea71d57 1456 *
e1cd93ce 1457 * @param calendar_event $event
bea71d57 1458 * @param \core_calendar\action_factory $factory
01f96180 1459 * @return \core_calendar\local\event\entities\action_interface|null
bea71d57 1460 */
e1cd93ce 1461function mod_chat_core_calendar_provide_event_action(calendar_event $event,
bea71d57
MN
1462 \core_calendar\action_factory $factory) {
1463 global $DB;
1464
1465 $cm = get_fast_modinfo($event->courseid)->instances['chat'][$event->instance];
1466 $chattime = $DB->get_field('chat', 'chattime', array('id' => $event->instance));
3b2be06b
AN
1467 $chattimemidnight = usergetmidnight($chattime);
1468 $todaymidnight = usergetmidnight(time());
bea71d57 1469
3b2be06b
AN
1470 if ($chattime < $todaymidnight) {
1471 // The chat is before today. Do not show at all.
1472 return null;
1473 } else {
1474 // The chat is actionable if it is at some point today.
1475 $actionable = $chattimemidnight == $todaymidnight;
1476
1477 return $factory->create_instance(
1478 get_string('enterchat', 'chat'),
1479 new \moodle_url('/mod/chat/view.php', array('id' => $cm->id)),
1480 1,
1481 $actionable
1482 );
1483 }
bea71d57 1484}
9b82171b
JL
1485
1486/**
1487 * Given a set of messages for a chat, return the completed chat sessions (including optionally not completed ones).
1488 *
1489 * @param array $messages list of messages from a chat
26b4e858 1490 * @param bool $showall whether to include incomplete sessions or not
9b82171b
JL
1491 * @return array the list of sessions
1492 * @since Moodle 3.4
1493 */
1494function chat_get_sessions($messages, $showall = false) {
1495 $sessions = array();
1496 $sessiongap = 5 * 60; // 5 minutes silence means a new session.
1497 $sessionend = 0;
1498 $sessionstart = 0;
1499 $sessionusers = array();
1500 $lasttime = 0;
1501
1502 $messagesleft = count($messages);
1503
1504 foreach ($messages as $message) { // We are walking BACKWARDS through the messages.
1505
1506 $messagesleft --; // Countdown.
1507
1508 if (!$lasttime) {
1509 $lasttime = $message->timestamp;
1510 }
1511 if (!$sessionend) {
1512 $sessionend = $message->timestamp;
1513 }
1514 if ((($lasttime - $message->timestamp) < $sessiongap) and $messagesleft) { // Same session.
1515 if ($message->userid and !$message->issystem) { // Remember user and count messages.
1516 if (empty($sessionusers[$message->userid])) {
1517 $sessionusers[$message->userid] = 1;
1518 } else {
1519 $sessionusers[$message->userid] ++;
1520 }
1521 }
1522 } else {
1523 $sessionstart = $lasttime;
1524
1525 $iscomplete = ($sessionend - $sessionstart > 60 and count($sessionusers) > 1);
1526 if ($showall or $iscomplete) {
1527 $sessions[] = (object) array(
1528 'sessionstart' => $sessionstart,
1529 'sessionend' => $sessionend,
1530 'sessionusers' => $sessionusers,
1531 'iscomplete' => $iscomplete,
1532 );
1533 }
1534
1535 $sessionend = $message->timestamp;
1536 $sessionusers = array();
1537 $sessionusers[$message->userid] = 1;
1538 }
1539 $lasttime = $message->timestamp;
1540 }
1541 return $sessions;
2971d842
JL
1542}
1543
1544/**
1545 * Return the messages of the given chat session.
1546 *
1547 * @param int $chatid the chat id
1548 * @param mixed $group false if groups not used, int if groups used, 0 means all groups
1549 * @param int $start the session start timestamp (0 to not filter by time)
1550 * @param int $end the session end timestamp (0 to not filter by time)
1551 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter)
1552 * @return array session messages
1553 * @since Moodle 3.4
1554 */
1555function chat_get_session_messages($chatid, $group = false, $start = 0, $end = 0, $sort = '') {
1556 global $DB;
1557
1558 $params = array('chatid' => $chatid);
1559
1560 // If the user is allocated to a group, only show messages from people in the same group, or no group.
1561 if ($group) {
1562 $groupselect = " AND (groupid = :currentgroup OR groupid = 0)";
1563 $params['currentgroup'] = $group;
1564 } else {
1565 $groupselect = "";
1566 }
1567
1568 $select = "chatid = :chatid $groupselect";
1569 if (!empty($start)) {
1570 $select .= ' AND timestamp >= :start';
1571 $params['start'] = $start;
1572 }
1573 if (!empty($end)) {
1574 $select .= ' AND timestamp <= :end';
1575 $params['end'] = $end;
1576 }
1577
1578 return $DB->get_records_select('chat_messages', $select, $params, $sort);
1579}