adding missing portfolio string
[moodle.git] / mod / chat / lib.php
CommitLineData
1c61c8d6 1<?php // $Id$
1515a89e 2
3/// Library of functions and constants for module chat
c4d588cc 4require_once($CFG->libdir.'/pagelib.php');
5
1515a89e 6// The HTML head for the message window to start with (<!-- nix --> is used to get some browsers starting with output
6e5f40ea 7$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 bgcolor=\"#FFFFFF\">\n\n".padding(200);
1515a89e 8
9// The HTML head for the message window to start with (with js scrolling)
6e5f40ea 10$CHAT_HTMLHEAD_JS = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"><html><head><script type=\"text/javascript\">\n//<![CDATA[\nfunction move()\n{\nif (scroll_active) window.scroll(1,400000);\nwindow.setTimeout(\"move()\",100);\n}\nscroll_active = true;\nmove();\n//]]>\n</script>\n</head>\n<body bgcolor=\"#FFFFFF\" onBlur=\"scroll_active = true\" onFocus=\"scroll_active = false\">\n\n".padding(200);
1515a89e 11
12// The HTML code for standard empty pages (e.g. if a user was kicked out)
89f688b6 13$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 bgcolor=\"#FFFFFF\"></body></html>";
1515a89e 14
15// The HTML head for the message input page
89f688b6 16$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 bgcolor=\"#FFFFFF\">";
1515a89e 17
18// The HTML code for the message input page, with JavaScript
32f0b38a 19$CHAT_HTMLHEAD_MSGINPUT_JS = "<!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>\n<script type=\"text/javascript\">\n//<![CDATA[\nscroll_active = true;\nfunction empty_field_and_submit()\n{\ndocument.fdummy.arsc_message.value=document.f.arsc_message.value;\ndocument.fdummy.submit();\ndocument.f.arsc_message.focus();\ndocument.f.arsc_message.select();\nreturn false;\n}\n//]]>\n</script>\n</head><body bgcolor=\"#FFFFFF\" OnLoad=\"document.f.arsc_message.focus();document.f.arsc_message.select();\">";
1515a89e 20
fbabbd23 21// Dummy data that gets output to the browser as needed, in order to make it show output
6e5f40ea 22$CHAT_DUMMY_DATA = padding(200);
5c2f6a7f 23
6e5f40ea 24function padding($n){
5c2f6a7f 25 $str = '';
633c3341 26 for($i=0; $i<$n; $i++){
5c2f6a7f 27 $str.='<!-- nix -->\n';
28 }
29 return $str;
30}
1515a89e 31
32function chat_add_instance($chat) {
c18269c7 33 global $DB;
b5de723d 34/// Given an object containing all the necessary data,
7cac0c4b 35/// (defined by the form in mod_form.php) this function
b5de723d 36/// will create a new instance and return the id number
1515a89e 37/// of the new instance.
38
39 $chat->timemodified = time();
40
c18269c7 41 if ($returnid = $DB->insert_record("chat", $chat)) {
8496c4af 42
43 $event = NULL;
44 $event->name = $chat->name;
45 $event->description = $chat->intro;
46 $event->courseid = $chat->course;
47 $event->groupid = 0;
48 $event->userid = 0;
49 $event->modulename = 'chat';
50 $event->instance = $returnid;
51 $event->eventtype = $chat->schedule;
52 $event->timestart = $chat->chattime;
53 $event->timeduration = 0;
54
55 add_event($event);
56 }
57
58 return $returnid;
1515a89e 59}
60
61
62function chat_update_instance($chat) {
c18269c7 63 global $DB;
b5de723d 64/// Given an object containing all the necessary data,
7cac0c4b 65/// (defined by the form in mod_form.php) this function
1515a89e 66/// will update an existing instance with new data.
67
68 $chat->timemodified = time();
69 $chat->id = $chat->instance;
70
1515a89e 71
c18269c7 72 if ($returnid = $DB->update_record("chat", $chat)) {
8496c4af 73
264867fd 74 $event = new object();
8496c4af 75
c18269c7 76 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'chat', 'instance'=>$chat->id))) {
8496c4af 77
78 $event->name = $chat->name;
79 $event->description = $chat->intro;
80 $event->timestart = $chat->chattime;
81
82 update_event($event);
83 }
84 }
85
86 return $returnid;
1515a89e 87}
88
89
90function chat_delete_instance($id) {
c18269c7 91 global $DB;
b5de723d 92/// Given an ID of an instance of this module,
93/// this function will permanently delete the instance
94/// and any data that depends on it.
1515a89e 95
c18269c7 96 if (! $chat = $DB->get_record('chat', array('id'=>$id))) {
1515a89e 97 return false;
98 }
99
100 $result = true;
101
102 # Delete any dependent records here #
103
c18269c7 104 if (! $DB->delete_records('chat', array('id'=>$chat->id))) {
a71efae3 105 $result = false;
106 }
c18269c7 107 if (! $DB->delete_records('chat_messages', array('chatid'=>$chat->id))) {
a71efae3 108 $result = false;
109 }
6e5f40ea 110 if (! $DB->delete_records('chat_messages_current', array('chatid'=>$chat->id))) {
111 $result = false;
112 }
c18269c7 113 if (! $DB->delete_records('chat_users', array('chatid'=>$chat->id))) {
1515a89e 114 $result = false;
115 }
116
880d8675 117 $pagetypes = page_import_types('mod/chat/');
118 foreach($pagetypes as $pagetype) {
c18269c7 119 if (!$DB->delete_records('block_instance', array('pageid'=>$chat->id, 'pagetype'=>$pagetype))) {
880d8675 120 $result = false;
121 }
122 }
123
c18269c7 124 if (! $DB->delete_records('event', array('modulename'=>'chat', 'instance'=>$chat->id))) {
36eb856f 125 $result = false;
126 }
127
1515a89e 128 return $result;
129}
130
131function chat_user_outline($course, $user, $mod, $chat) {
b5de723d 132/// Return a small object with summary information about what a
1515a89e 133/// user has done with a given particular instance of this module
134/// Used for user activity reports.
135/// $return->time = the time they did it
136/// $return->info = a short text description
d3bf6f92 137 return NULL;
1515a89e 138}
139
140function chat_user_complete($course, $user, $mod, $chat) {
b5de723d 141/// Print a detailed representation of what a user has done with
1515a89e 142/// a given particular instance of this module, for user activity reports.
1515a89e 143 return true;
144}
145
dd97c328 146function chat_print_recent_activity($course, $viewfullnames, $timestart) {
147/// Given a course and a date, prints a summary of all chat rooms past and present
1515a89e 148/// This function is called from course/lib.php: print_recent_activity()
d3bf6f92 149 global $CFG, $USER, $DB;
dd97c328 150
151 // this is approximate only, but it is really fast ;-)
152 $timeout = $CFG->chat_old_ping * 10;
153
d3bf6f92 154 if (!$mcms = $DB->get_records_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
155 FROM {course_modules} cm
156 JOIN {modules} md ON md.id = cm.module
157 JOIN {chat} ch ON ch.id = cm.instance
158 JOIN {chat_messages} chm ON chm.chatid = ch.id
159 WHERE chm.timestamp > ? AND ch.course = ? AND md.name = 'chat'
160 GROUP BY cm.id
161 ORDER BY lasttime ASC", array($timestart, $course->id))) {
dd97c328 162 return false;
163 }
164
165 $past = array();
166 $current = array();
167 $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
168
fd4d41c3 169 foreach ($mcms as $cmid=>$mcm) {
170 if (!array_key_exists($cmid, $modinfo->cms)) {
dd97c328 171 continue;
172 }
fd4d41c3 173 $cm = $modinfo->cms[$cmid];
174 $cm->lasttime = $mcm->lasttime;
dd97c328 175 if (!$modinfo->cms[$cm->id]->uservisible) {
176 continue;
177 }
b7602a11 178
dd97c328 179 if (groups_get_activity_groupmode($cm) != SEPARATEGROUPS
180 or has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
181 if ($timeout > time() - $cm->lasttime) {
182 $current[] = $cm;
183 } else {
184 $past[] = $cm;
185 }
186
187 continue;
188 }
189
190 if (is_null($modinfo->groups)) {
191 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
192 }
c5a05b95 193
dd97c328 194 // verify groups in separate mode
195 if (!$mygroupids = $modinfo->groups[$cm->groupingid]) {
196 continue;
197 }
0469cccf 198
dd97c328 199 // ok, last post was not for my group - we have to query db to get last message from one of my groups
200 // only minor problem is that the order will not be correct
201 $mygroupids = implode(',', $mygroupids);
202 $cm->mygroupids = $mygroupids;
203
d3bf6f92 204 if (!$mcm = $DB->get_record_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
205 FROM {course_modules} cm
206 JOIN {chat} ch ON ch.id = cm.instance
6e5f40ea 207 JOIN {chat_messages_current} chm ON chm.chatid = ch.id
d3bf6f92 208 WHERE chm.timestamp > ? AND cm.id = ? AND
209 (chm.groupid IN ($mygroupids) OR chm.groupid = 0)
210 GROUP BY cm.id", array($timestart, $cm->id))) {
dd97c328 211 continue;
212 }
fd4d41c3 213
214 $cm->lasttime = $mcm->lasttime;
dd97c328 215 if ($timeout > time() - $cm->lasttime) {
216 $current[] = $cm;
217 } else {
218 $past[] = $cm;
219 }
220 }
221
222 if (!$past and !$current) {
b7602a11 223 return false;
224 }
1515a89e 225
dd97c328 226 $strftimerecent = get_string('strftimerecent');
227
228 if ($past) {
229 print_headline(get_string('pastchats', 'chat').':');
230
231 foreach ($past as $cm) {
232 $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
233 $date = userdate($cm->lasttime, $strftimerecent);
234 echo '<div class="head"><div class="date">'.$date.'</div></div>';
235 echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name,true).'</a></div>';
b7602a11 236 }
8f7dc7f1 237 }
238
239 if ($current) {
dd97c328 240 print_headline(get_string('currentchats', 'chat').':');
241
242 $oldest = floor((time()-$CFG->chat_old_ping)/10)*10; // better db caching
243
244 $timeold = time() - $CFG->chat_old_ping;
245 $timeold = floor($timeold/10)*10; // better db caching
246 $timeoldext = time() - ($CFG->chat_old_ping*10); // JSless gui_basic needs much longer timeouts
247 $timeoldext = floor($timeoldext/10)*10; // better db caching
248
d3bf6f92 249 $params = array('timeold'=>$timeold, 'timeoldext'=>$timeoldext, 'cmid'=>$cm->id);
250
251 $timeout = "AND (chu.version<>'basic' AND chu.lastping>:timeold) OR (chu.version='basic' AND chu.lastping>:timeoldext)";
dd97c328 252
253 foreach ($current as $cm) {
254 //count users first
255 if (isset($cm->mygroupids)) {
256 $groupselect = "AND (chu.groupid IN ({$cm->mygroupids}) OR chu.groupid = 0)";
257 } else {
258 $groupselect = "";
259 }
fd4d41c3 260
d3bf6f92 261 if (!$users = $DB->get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email, u.picture
262 FROM {course_modules} cm
263 JOIN {chat} ch ON ch.id = cm.instance
264 JOIN {chat_users} chu ON chu.chatid = ch.id
265 JOIN {user} u ON u.id = chu.userid
266 WHERE cm.id = :cmid $timeout $groupselect
267 GROUP BY u.id, u.firstname, u.lastname, u.email, u.picture", $params)) {
dd97c328 268 }
269
270 $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
271 $date = userdate($cm->lasttime, $strftimerecent);
272
273 echo '<div class="head"><div class="date">'.$date.'</div></div>';
274 echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name,true).'</a></div>';
275 echo '<div class="userlist">';
276 if ($users) {
277 echo '<ul>';
278 foreach ($users as $user) {
279 echo '<li>'.fullname($user, $viewfullnames).'</li>';
280 }
281 echo '</ul>';
282 }
283 echo '</div>';
284 }
b7602a11 285 }
286
287 return true;
1515a89e 288}
289
8f7dc7f1 290
1515a89e 291function chat_cron () {
292/// Function to be run periodically according to the moodle cron
b5de723d 293/// This function searches for things that need to be done, such
294/// as sending out mail, toggling flags etc ...
d3bf6f92 295 global $DB;
1515a89e 296
fcd3a1ee 297 chat_update_chat_times();
298
7d792369 299 chat_delete_old_users();
300
319038c3 301 /// Delete old messages with a
302 /// single SQL query.
303 $subselect = "SELECT c.keepdays
d3bf6f92 304 FROM {chat} c
305 WHERE c.id = {chat_messages}.chatid";
4388027c 306
319038c3 307 $sql = "DELETE
d3bf6f92 308 FROM {chat_messages}
6e5f40ea 309 WHERE ($subselect) > 0 AND timestamp < ( ".time()." -($subselect) * 24 * 3600)";
310
311 $DB->execute($sql);
312
313 $sql = "DELETE
314 FROM {chat_messages_current}
315 WHERE timestamp < ( ".time()." - 8 * 3600)";
4388027c 316
d3bf6f92 317 $DB->execute($sql);
22a4491a 318
1515a89e 319 return true;
320}
321
84a2fdd7 322function chat_get_participants($chatid, $groupid=0) {
05855091 323//Returns the users with data in one chat
324//(users with records in chat_messages, students)
d3bf6f92 325 global $DB;
05855091 326
d3bf6f92 327 $params = array('groupid'=>$groupid, 'chatid'=>$chatid);
05855091 328
84a2fdd7 329 if ($groupid) {
d3bf6f92 330 $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
84a2fdd7 331 } else {
332 $groupselect = "";
333 }
334
05855091 335 //Get students
d3bf6f92 336 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
337 FROM {user} u, {chat_messages} c
338 WHERE c.chatid = :chatid $groupselect
339 AND u.id = c.userid", $params);
1515a89e 340
05855091 341 //Return students array (it contains an array of unique users)
342 return ($students);
343}
1515a89e 344
8496c4af 345function chat_refresh_events($courseid = 0) {
346// This standard function will check all instances of this module
347// and make sure there are up-to-date events created for each of them.
348// If courseid = 0, then every chat event in the site is checked, else
349// only chat events belonging to the course specified are checked.
350// This function is used, in its new format, by restore_refresh_events()
d3bf6f92 351 global $DB;
8496c4af 352
353 if ($courseid) {
d3bf6f92 354 if (! $chats = $DB->get_records("chat", array("course"=>$courseid))) {
8496c4af 355 return true;
356 }
357 } else {
d3bf6f92 358 if (! $chats = $DB->get_records("chat")) {
8496c4af 359 return true;
360 }
361 }
d3bf6f92 362 $moduleid = $DB->get_field('modules', 'id', array('name'=>'chat'));
8496c4af 363
364 foreach ($chats as $chat) {
365 $event = NULL;
d3bf6f92 366 $event->name = $chat->name;
367 $event->description = $chat->intro;
8496c4af 368 $event->timestart = $chat->chattime;
369
d3bf6f92 370 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'chat', 'instance'=>$chat->id))) {
8496c4af 371 update_event($event);
372
373 } else {
374 $event->courseid = $chat->course;
375 $event->groupid = 0;
376 $event->userid = 0;
377 $event->modulename = 'chat';
378 $event->instance = $chat->id;
379 $event->eventtype = $chat->schedule;
380 $event->timeduration = 0;
d3bf6f92 381 $event->visible = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$chat->id));
b5de723d 382
8496c4af 383 add_event($event);
384 }
385 }
386 return true;
387}
388
516121bd 389
1515a89e 390//////////////////////////////////////////////////////////////////////
391/// Functions that require some SQL
392
a12e11c1 393function chat_get_users($chatid, $groupid=0, $groupingid=0) {
d3bf6f92 394 global $DB;
1515a89e 395
d3bf6f92 396 $params = array('chatid'=>$chatid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
84a2fdd7 397
398 if ($groupid) {
d3bf6f92 399 $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
84a2fdd7 400 } else {
401 $groupselect = "";
402 }
6e5f40ea 403
a12e11c1 404 if (!empty($CFG->enablegroupings) && !(empty($groupingid))) {
d3bf6f92 405 $groupingjoin = "JOIN {groups_members} gm ON u.id = gm.userid
406 JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
6e5f40ea 407
a12e11c1 408 } else {
409 $groupingjoin = '';
410 }
b5de723d 411
d3bf6f92 412 return $DB->get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, c.lastmessageping, c.firstping, u.imagealt
413 FROM {chat_users} c
414 JOIN {user} u ON u.id = c.userid
415 $groupingjoin
416 WHERE c.chatid = :chatid
417 $groupselect
418 ORDER BY c.firstping ASC", $params);
1515a89e 419}
420
84a2fdd7 421function chat_get_latest_message($chatid, $groupid=0) {
f33e1ed4 422 global $DB;
1515a89e 423
d3bf6f92 424 $params = array('chatid'=>$chatid, 'groupid'=>$groupid);
1515a89e 425
84a2fdd7 426 if ($groupid) {
d3bf6f92 427 $groupselect = "AND (groupid=:groupid OR groupid=0)";
84a2fdd7 428 } else {
429 $groupselect = "";
430 }
431
f33e1ed4 432 $sql = "SELECT *
6e5f40ea 433 FROM {chat_messages_current}
d3bf6f92 434 WHERE chatid = :chatid
f33e1ed4 435 $groupselect
436 ORDER BY timestamp DESC";
03cedd62 437
f33e1ed4 438 return $DB->get_record_sql($sql, $params, true);
1515a89e 439}
440
5a8625e4 441
1515a89e 442//////////////////////////////////////////////////////////////////////
516121bd 443// login if not already logged in
1515a89e 444
a32c7772 445function chat_login_user($chatid, $version, $groupid, $course) {
d3bf6f92 446 global $USER, $DB;
447
448 if (($version != 'sockets') and $chatuser = $DB->get_record('chat_users', array('chatid'=>$chatid, 'userid'=>$USER->id, 'groupid'=>$groupid))) {
516121bd 449 $chatuser->version = $version;
d96466d2 450 $chatuser->ip = $USER->lastip;
516121bd 451 $chatuser->lastping = time();
452 $chatuser->lang = current_language();
1515a89e 453
d96466d2 454 // Sometimes $USER->lastip is not setup properly
d13ef2fb 455 // during login. Update with current value if possible
f83edcb1 456 // or provide a dummy value for the db
d13ef2fb 457 if (empty($chatuser->ip)) {
458 $chatuser->ip = getremoteaddr();
459 if (empty($chatuser->ip)) {
f83edcb1 460 $chatuser->ip = '';
d13ef2fb 461 }
462 }
463
516121bd 464 if (($chatuser->course != $course->id)
465 or ($chatuser->userid != $USER->id)) {
466 return false;
467 }
d3bf6f92 468 if (!$DB->update_record('chat_users', $chatuser)) {
516121bd 469 return false;
470 }
516121bd 471 } else {
6ee78cee 472 $chatuser = new object();
516121bd 473 $chatuser->chatid = $chatid;
474 $chatuser->userid = $USER->id;
475 $chatuser->groupid = $groupid;
476 $chatuser->version = $version;
d96466d2 477 $chatuser->ip = $USER->lastip;
516121bd 478 $chatuser->lastping = $chatuser->firstping = $chatuser->lastmessageping = time();
479 $chatuser->sid = random_string(32);
3dfd307f 480 $chatuser->course = $course->id; //caching - needed for current_language too
481 $chatuser->lang = current_language(); //caching - to resource intensive to find out later
516121bd 482
d96466d2 483 // Sometimes $USER->lastip is not setup properly
274f0091 484 // during login. Update with current value if possible
485 // or provide a dummy value for the db
486 if (empty($chatuser->ip)) {
487 $chatuser->ip = getremoteaddr();
488 if (empty($chatuser->ip)) {
489 $chatuser->ip = '';
490 }
491 }
492
493
d3bf6f92 494 if (!$DB->insert_record('chat_users', $chatuser)) {
516121bd 495 return false;
496 }
497
a32c7772 498 if ($version == 'sockets') {
499 // do not send 'enter' message, chatd will do it
500 } else {
6ee78cee 501 $message = new object();
2ac0d13b 502 $message->chatid = $chatuser->chatid;
503 $message->userid = $chatuser->userid;
504 $message->groupid = $groupid;
505 $message->message = 'enter';
506 $message->system = 1;
507 $message->timestamp = time();
508
6e5f40ea 509 if (!$DB->insert_record('chat_messages', $message) || !$DB->insert_record('chat_messages_current', $message)) {
2f52a088 510 print_error('cantinsert', 'chat');
2ac0d13b 511 }
516121bd 512 }
1515a89e 513 }
514
515 return $chatuser->sid;
516}
517
7d792369 518function chat_delete_old_users() {
519// Delete the old and in the way
d3bf6f92 520 global $CFG, $DB;
b5012f3e 521
e7fbd0b3 522 $timeold = time() - $CFG->chat_old_ping;
953eb6f3 523 $timeoldext = time() - ($CFG->chat_old_ping*10); // JSless gui_basic needs much longer timeouts
a32c7772 524
d3bf6f92 525 $query = "(version<>'basic' AND lastping<?) OR (version='basic' AND lastping<?)";
526 $params = array($timeold, $timeoldext);
7d792369 527
d3bf6f92 528 if ($oldusers = $DB->get_records_select('chat_users', $query, $params) ) {
529 $DB->delete_records_select('chat_users', $query, $params);
7d792369 530 foreach ($oldusers as $olduser) {
6ee78cee 531 $message = new object();
516121bd 532 $message->chatid = $olduser->chatid;
533 $message->userid = $olduser->userid;
534 $message->groupid = $olduser->groupid;
535 $message->message = 'exit';
536 $message->system = 1;
7d792369 537 $message->timestamp = time();
b5de723d 538
6e5f40ea 539 if (!$DB->insert_record('chat_messages', $message) || !$DB->insert_record('chat_messages_current', $message) ) {
2f52a088 540 print_error('cantinsert', 'chat');
7d792369 541 }
542 }
543 }
544}
1515a89e 545
22a4491a 546
fcd3a1ee 547function chat_update_chat_times($chatid=0) {
548/// Updates chat records so that the next chat time is correct
d3bf6f92 549 global $DB;
fcd3a1ee 550
551 $timenow = time();
d3bf6f92 552
553 $params = array('timenow'=>$timenow, 'chatid'=>$chatid);
554
fcd3a1ee 555 if ($chatid) {
d3bf6f92 556 if (!$chats[] = $DB->get_record_select("chat", "id = :chatid AND chattime <= :timenow AND schedule > 0", $params)) {
fcd3a1ee 557 return;
558 }
559 } else {
d3bf6f92 560 if (!$chats = $DB->get_records_select("chat", "chattime <= :timenow AND schedule > 0", $params)) {
fcd3a1ee 561 return;
562 }
563 }
564
565 foreach ($chats as $chat) {
7626969c 566 unset($chat->name);
567 unset($chat->intro);
fcd3a1ee 568 switch ($chat->schedule) {
569 case 1: // Single event - turn off schedule and disable
570 $chat->chattime = 0;
571 $chat->schedule = 0;
572 break;
573 case 2: // Repeat daily
f0d3bb9e 574 while ($chat->chattime <= $timenow) {
575 $chat->chattime += 24 * 3600;
576 }
fcd3a1ee 577 break;
578 case 3: // Repeat weekly
f0d3bb9e 579 while ($chat->chattime <= $timenow) {
580 $chat->chattime += 7 * 24 * 3600;
581 }
fcd3a1ee 582 break;
583 }
d3bf6f92 584 $DB->update_record("chat", $chat);
585
586 $event = new object(); // Update calendar too
8496c4af 587
d3bf6f92 588 $cond = "modulename='chat' AND instance = :chatid AND timestart <> :chattime";
589 $params = array('chattime'=>$chat->chattime, 'chatid'=>$chatid);
590
591 if ($event->id = $DB->get_field_select('event', 'id', $cond, $params)) {
8496c4af 592 $event->timestart = $chat->chattime;
593 update_event($event);
594 }
fcd3a1ee 595 }
596}
597
598
aa5c32fd 599function chat_format_message_manually($message, $courseid, $sender, $currentuser, $chat_lastrow=NULL) {
72989350 600 global $CFG, $USER;
1515a89e 601
6ee78cee 602 $output = new object();
516121bd 603 $output->beep = false; // by default
604 $output->refreshusers = false; // by default
7d792369 605
72989350 606 // Use get_user_timezone() to find the correct timezone for displaying this message:
607 // It's either the current user's timezone or else decided by some Moodle config setting
970f144e 608 // First, "reset" $USER->timezone (which could have been set by a previous call to here)
609 // because otherwise the value for the previous $currentuser will take precedence over $CFG->timezone
610 $USER->timezone = 99;
72989350 611 $tz = get_user_timezone($currentuser->timezone);
b5de723d 612
72989350 613 // Before formatting the message time string, set $USER->timezone to the above.
614 // This will allow dst_offset_on (called by userdate) to work correctly, otherwise the
615 // message times appear off because DST is not taken into account when it should be.
616 $USER->timezone = $tz;
b5de723d 617 $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
618
619 $message->picture = print_user_picture($sender->id, 0, $sender->picture, false, true, false);
582de679 620 if ($courseid) {
d3981e38 621 $message->picture = "<a onclick=\"window.open('$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid')\" href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">$message->picture</a>";
582de679 622 }
1515a89e 623
aa5c32fd 624 //Calculate the row class
625 if ($chat_lastrow !== NULL) {
626 $rowclass = ' class="r'.$chat_lastrow.'" ';
627 } else {
628 $rowclass = '';
629 }
630
b5de723d 631 // Start processing the message
1515a89e 632
b5de723d 633 if(!empty($message->system)) {
634 // System event
635 $output->text = $message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender));
aa5c32fd 636 $output->html = '<table class="chat-event"><tr'.$rowclass.'><td class="picture">'.$message->picture.'</td><td class="text">';
637 $output->html .= '<span class="event">'.$output->text.'</span></td></tr></table>';
6e5f40ea 638 $output->basic = '<dl><dt class="event">'.$message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender)).'</dt></dl>';
7d792369 639
516121bd 640 if($message->message == 'exit' or $message->message == 'enter') {
641 $output->refreshusers = true; //force user panel refresh ASAP
642 }
1515a89e 643 return $output;
644 }
645
82a524ef 646 // It's not a system event
b5de723d 647
648 $text = $message->message;
82a524ef 649
650 /// Parse the text to clean and filter it
651
6ee78cee 652 $options = new object();
82a524ef 653 $options->para = false;
654 $text = format_text($text, FORMAT_MOODLE, $options, $courseid);
927a7808 655
b5de723d 656 // And now check for special cases
927a7808 657 $special = false;
658
b5de723d 659 if (substr($text, 0, 5) == 'beep ') {
6e5f40ea 660 /// It's a beep!
927a7808 661 $special = true;
7d792369 662 $beepwho = trim(substr($text, 5));
9f85bed4 663
b5de723d 664 if ($beepwho == 'all') { // everyone
665 $outinfo = $message->strtime.': '.get_string('messagebeepseveryone', 'chat', fullname($sender));
666 $outmain = '';
667 $output->beep = true; // (eventually this should be set to
7d792369 668 // to a filename uploaded by the user)
669
82a524ef 670 } else if ($beepwho == $currentuser->id) { // current user
b5de723d 671 $outinfo = $message->strtime.': '.get_string('messagebeepsyou', 'chat', fullname($sender));
672 $outmain = '';
7d792369 673 $output->beep = true;
264867fd 674
0eda0a46 675 } else { //something is not caught?
7d792369 676 return false;
677 }
b5de723d 678 } else if (substr($text, 0, 1) == '/') { /// It's a user command
927a7808 679 if (trim(substr($text, 0, 4)) == '/me') {
680 $special = true;
b5de723d 681 $outinfo = $message->strtime;
682 $outmain = $sender->firstname.' '.substr($text, 4);
1515a89e 683 }
927a7808 684 }
9f85bed4 685
927a7808 686 if(!$special) {
b5de723d 687 $outinfo = $message->strtime.' '.$sender->firstname;
7d792369 688 $outmain = $text;
1515a89e 689 }
264867fd 690
9f85bed4 691 /// Format the message as a small table
1515a89e 692
b5de723d 693 $output->text = strip_tags($outinfo.': '.$outmain);
7d792369 694
5379d249 695 $output->html = "<table class=\"chat-message\"><tr$rowclass><td class=\"picture\" valign=\"top\">$message->picture</td><td class=\"text\">";
aa5c32fd 696 $output->html .= "<span class=\"title\">$outinfo</span>";
7d792369 697 if ($outmain) {
698 $output->html .= ": $outmain";
6e5f40ea 699 $output->basic = '<dl><dt class="title">'.$outinfo.':</dt><dd class="text">'.$outmain.'</dd></dl>';
6ee78cee 700 } else {
6e5f40ea 701 $output->basic = '<dl><dt class="title">'.$outinfo.'</dt></dl>';
7d792369 702 }
aa5c32fd 703 $output->html .= "</td></tr></table>";
7d792369 704 return $output;
b5de723d 705}
706
aa5c32fd 707function chat_format_message($message, $courseid, $currentuser, $chat_lastrow=NULL) {
b5de723d 708/// Given a message object full of information, this function
709/// formats it appropriately into text and html, then
710/// returns the formatted data.
d3bf6f92 711 global $DB;
b5de723d 712
78c98892 713 static $users; // Cache user lookups
714
715 if (isset($users[$message->userid])) {
716 $user = $users[$message->userid];
d3bf6f92 717 } else if ($user = $DB->get_record('user', array('id'=>$message->userid), 'id,picture,firstname,lastname')) {
78c98892 718 $users[$message->userid] = $user;
719 } else {
720 return NULL;
b5de723d 721 }
aa5c32fd 722 return chat_format_message_manually($message, $courseid, $user, $currentuser, $chat_lastrow);
1515a89e 723}
724
f3221af9 725function chat_get_view_actions() {
726 return array('view','view all','report');
727}
728
729function chat_get_post_actions() {
730 return array('talk');
731}
732
9ca0187e 733function chat_print_overview($courses, &$htmlarray) {
734 global $USER, $CFG;
735
736 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
737 return array();
738 }
739
740 if (!$chats = get_all_instances_in_courses('chat',$courses)) {
741 return;
742 }
743
744 $strchat = get_string('modulename', 'chat');
745 $strnextsession = get_string('nextsession', 'chat');
9ca0187e 746
747 foreach ($chats as $chat) {
9ca0187e 748 if ($chat->chattime and $chat->schedule) { // A chat is scheduled
a2a37336 749 $str = '<div class="chat overview"><div class="name">'.
750 $strchat.': <a '.($chat->visible?'':' class="dimmed"').
751 ' href="'.$CFG->wwwroot.'/mod/chat/view.php?id='.$chat->coursemodule.'">'.
752 $chat->name.'</a></div>';
753 $str .= '<div class="info">'.$strnextsession.': '.userdate($chat->chattime).'</div></div>';
754
755 if (empty($htmlarray[$chat->course]['chat'])) {
756 $htmlarray[$chat->course]['chat'] = $str;
757 } else {
758 $htmlarray[$chat->course]['chat'] .= $str;
759 }
9ca0187e 760 }
9ca0187e 761 }
762}
763
0b5a80a1 764
765/**
766 * Implementation of the function for printing the form elements that control
767 * whether the course reset functionality affects the chat.
768 * @param $mform form passed by reference
769 */
770function chat_reset_course_form_definition(&$mform) {
771 $mform->addElement('header', 'chatheader', get_string('modulenameplural', 'chat'));
772 $mform->addElement('advcheckbox', 'reset_chat', get_string('removemessages','chat'));
773}
774
775/**
776 * Course reset form defaults.
777 */
778function chat_reset_course_form_defaults($course) {
779 return array('reset_chat'=>1);
780}
781
782/**
783 * Actual implementation of the rest coures functionality, delete all the
784 * chat messages for course $data->courseid.
785 * @param $data the data submitted from the reset course.
786 * @return array status array
787 */
788function chat_reset_userdata($data) {
d3bf6f92 789 global $CFG, $DB;
0b5a80a1 790
791 $componentstr = get_string('modulenameplural', 'chat');
792 $status = array();
793
794 if (!empty($data->reset_chat)) {
795 $chatessql = "SELECT ch.id
d3bf6f92 796 FROM {chat} ch
797 WHERE ch.course=?";
798 $params = array($data->courseid);
0b5a80a1 799
d3bf6f92 800 $DB->delete_records_select('chat_messages', "chatid IN ($chatessql)", $params);
6e5f40ea 801 $DB->delete_records_select('chat_messages_current', "chatid IN ($chatessql)", $params);
d3bf6f92 802 $DB->delete_records_select('chat_users', "chatid IN ($chatessql)", $params);
0b5a80a1 803 $status[] = array('component'=>$componentstr, 'item'=>get_string('removemessages', 'chat'), 'error'=>false);
804 }
805
806 /// updating dates - shift may be negative too
807 if ($data->timeshift) {
808 shift_course_mod_dates('chat', array('chattime'), $data->timeshift, $data->courseid);
809 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
810 }
811
812 return $status;
813}
814
f432bebf 815/**
816 * Returns all other caps used in module
817 */
818function chat_get_extra_capabilities() {
819 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
820}
821
1515a89e 822?>