Moodle  2.2.1
http://www.collinsharper.com
C:/xampp/htdocs/moodle/mod/chat/lib.php
Go to the documentation of this file.
00001 <?php
00002 
00003 // This file is part of Moodle - http://moodle.org/
00004 //
00005 // Moodle is free software: you can redistribute it and/or modify
00006 // it under the terms of the GNU General Public License as published by
00007 // the Free Software Foundation, either version 3 of the License, or
00008 // (at your option) any later version.
00009 //
00010 // Moodle is distributed in the hope that it will be useful,
00011 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013 // GNU General Public License for more details.
00014 //
00015 // You should have received a copy of the GNU General Public License
00016 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
00017 
00026 require_once($CFG->dirroot.'/calendar/lib.php');
00027 
00028 // The HTML head for the message window to start with (<!-- nix --> is used to get some browsers starting with output
00029 global $CHAT_HTMLHEAD;
00030 $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);
00031 
00032 // The HTML head for the message window to start with (with js scrolling)
00033 global $CHAT_HTMLHEAD_JS;
00034 $CHAT_HTMLHEAD_JS = <<<EOD
00035 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
00036 <html><head><script type="text/javascript">
00037 //<![CDATA[
00038 function move(){
00039     if (scroll_active)
00040         window.scroll(1,400000);
00041     window.setTimeout("move()",100);
00042 }
00043 var scroll_active = true;
00044 move();
00045 //]]>
00046 </script>
00047 </head>
00048 <body onBlur="scroll_active = true" onFocus="scroll_active = false">
00049 EOD;
00050 global $CHAT_HTMLHEAD_JS;
00051 $CHAT_HTMLHEAD_JS .= padding(200);
00052 
00053 // The HTML code for standard empty pages (e.g. if a user was kicked out)
00054 global $CHAT_HTMLHEAD_OUT;
00055 $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>";
00056 
00057 // The HTML head for the message input page
00058 global $CHAT_HTMLHEAD_MSGINPUT;
00059 $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>";
00060 
00061 // The HTML code for the message input page, with JavaScript
00062 global $CHAT_HTMLHEAD_MSGINPUT_JS;
00063 $CHAT_HTMLHEAD_MSGINPUT_JS = <<<EOD
00064 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
00065 <html>
00066     <head><title>Message Input</title>
00067     <script type="text/javascript">
00068     //<![CDATA[
00069     scroll_active = true;
00070     function empty_field_and_submit(){
00071         document.fdummy.arsc_message.value=document.f.arsc_message.value;
00072         document.fdummy.submit();
00073         document.f.arsc_message.focus();
00074         document.f.arsc_message.select();
00075         return false;
00076     }
00077     //]]>
00078     </script>
00079     </head><body OnLoad="document.f.arsc_message.focus();document.f.arsc_message.select();">;
00080 EOD;
00081 
00082 // Dummy data that gets output to the browser as needed, in order to make it show output
00083 global $CHAT_DUMMY_DATA;
00084 $CHAT_DUMMY_DATA = padding(200);
00085 
00090 function padding($n){
00091     $str = '';
00092     for($i=0; $i<$n; $i++){
00093         $str.="<!-- nix -->\n";
00094     }
00095     return $str;
00096 }
00097 
00108 function chat_add_instance($chat) {
00109     global $DB;
00110 
00111     $chat->timemodified = time();
00112 
00113     $returnid = $DB->insert_record("chat", $chat);
00114 
00115     $event = new stdClass();
00116     $event->name        = $chat->name;
00117     $event->description = format_module_intro('chat', $chat, $chat->coursemodule);
00118     $event->courseid    = $chat->course;
00119     $event->groupid     = 0;
00120     $event->userid      = 0;
00121     $event->modulename  = 'chat';
00122     $event->instance    = $returnid;
00123     $event->eventtype   = 'chattime';
00124     $event->timestart   = $chat->chattime;
00125     $event->timeduration = 0;
00126 
00127     calendar_event::create($event);
00128 
00129     return $returnid;
00130 }
00131 
00141 function chat_update_instance($chat) {
00142     global $DB;
00143 
00144     $chat->timemodified = time();
00145     $chat->id = $chat->instance;
00146 
00147 
00148     $DB->update_record("chat", $chat);
00149 
00150     $event = new stdClass();
00151 
00152     if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'chat', 'instance'=>$chat->id))) {
00153 
00154         $event->name        = $chat->name;
00155         $event->description = format_module_intro('chat', $chat, $chat->coursemodule);
00156         $event->timestart   = $chat->chattime;
00157 
00158         $calendarevent = calendar_event::load($event->id);
00159         $calendarevent->update($event);
00160     }
00161 
00162     return true;
00163 }
00164 
00174 function chat_delete_instance($id) {
00175     global $DB;
00176 
00177 
00178     if (! $chat = $DB->get_record('chat', array('id'=>$id))) {
00179         return false;
00180     }
00181 
00182     $result = true;
00183 
00184     // Delete any dependent records here
00185 
00186     if (! $DB->delete_records('chat', array('id'=>$chat->id))) {
00187         $result = false;
00188     }
00189     if (! $DB->delete_records('chat_messages', array('chatid'=>$chat->id))) {
00190         $result = false;
00191     }
00192     if (! $DB->delete_records('chat_messages_current', array('chatid'=>$chat->id))) {
00193         $result = false;
00194     }
00195     if (! $DB->delete_records('chat_users', array('chatid'=>$chat->id))) {
00196         $result = false;
00197     }
00198 
00199     if (! $DB->delete_records('event', array('modulename'=>'chat', 'instance'=>$chat->id))) {
00200         $result = false;
00201     }
00202 
00203     return $result;
00204 }
00205 
00221 function chat_user_outline($course, $user, $mod, $chat) {
00222     return NULL;
00223 }
00224 
00235 function chat_user_complete($course, $user, $mod, $chat) {
00236     return true;
00237 }
00238 
00251 function chat_print_recent_activity($course, $viewfullnames, $timestart) {
00252     global $CFG, $USER, $DB, $OUTPUT;
00253 
00254     // this is approximate only, but it is really fast ;-)
00255     $timeout = $CFG->chat_old_ping * 10;
00256 
00257     if (!$mcms = $DB->get_records_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
00258                                          FROM {course_modules} cm
00259                                          JOIN {modules} md        ON md.id = cm.module
00260                                          JOIN {chat} ch           ON ch.id = cm.instance
00261                                          JOIN {chat_messages} chm ON chm.chatid = ch.id
00262                                         WHERE chm.timestamp > ? AND ch.course = ? AND md.name = 'chat'
00263                                      GROUP BY cm.id
00264                                      ORDER BY lasttime ASC", array($timestart, $course->id))) {
00265          return false;
00266     }
00267 
00268     $past     = array();
00269     $current  = array();
00270     $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
00271 
00272     foreach ($mcms as $cmid=>$mcm) {
00273         if (!array_key_exists($cmid, $modinfo->cms)) {
00274             continue;
00275         }
00276         $cm = $modinfo->cms[$cmid];
00277         $cm->lasttime = $mcm->lasttime;
00278         if (!$modinfo->cms[$cm->id]->uservisible) {
00279             continue;
00280         }
00281 
00282         if (groups_get_activity_groupmode($cm) != SEPARATEGROUPS
00283          or has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
00284             if ($timeout > time() - $cm->lasttime) {
00285                 $current[] = $cm;
00286             } else {
00287                 $past[] = $cm;
00288             }
00289 
00290             continue;
00291         }
00292 
00293         if (is_null($modinfo->groups)) {
00294             $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
00295         }
00296 
00297         // verify groups in separate mode
00298         if (!$mygroupids = $modinfo->groups[$cm->groupingid]) {
00299             continue;
00300         }
00301 
00302         // ok, last post was not for my group - we have to query db to get last message from one of my groups
00303         // only minor problem is that the order will not be correct
00304         $mygroupids = implode(',', $mygroupids);
00305         $cm->mygroupids = $mygroupids;
00306 
00307         if (!$mcm = $DB->get_record_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
00308                                            FROM {course_modules} cm
00309                                            JOIN {chat} ch           ON ch.id = cm.instance
00310                                            JOIN {chat_messages_current} chm ON chm.chatid = ch.id
00311                                           WHERE chm.timestamp > ? AND cm.id = ? AND
00312                                                 (chm.groupid IN ($mygroupids) OR chm.groupid = 0)
00313                                        GROUP BY cm.id", array($timestart, $cm->id))) {
00314              continue;
00315         }
00316 
00317         $cm->lasttime = $mcm->lasttime;
00318         if ($timeout > time() - $cm->lasttime) {
00319             $current[] = $cm;
00320         } else {
00321             $past[] = $cm;
00322         }
00323     }
00324 
00325     if (!$past and !$current) {
00326         return false;
00327     }
00328 
00329     $strftimerecent = get_string('strftimerecent');
00330 
00331     if ($past) {
00332         echo $OUTPUT->heading(get_string("pastchats", 'chat').':');
00333 
00334         foreach ($past as $cm) {
00335             $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
00336             $date = userdate($cm->lasttime, $strftimerecent);
00337             echo '<div class="head"><div class="date">'.$date.'</div></div>';
00338             echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name,true).'</a></div>';
00339         }
00340     }
00341 
00342     if ($current) {
00343         echo $OUTPUT->heading(get_string("currentchats", 'chat').':');
00344 
00345         $oldest = floor((time()-$CFG->chat_old_ping)/10)*10;  // better db caching
00346 
00347         $timeold    = time() - $CFG->chat_old_ping;
00348         $timeold    = floor($timeold/10)*10;  // better db caching
00349         $timeoldext = time() - ($CFG->chat_old_ping*10); // JSless gui_basic needs much longer timeouts
00350         $timeoldext = floor($timeoldext/10)*10;  // better db caching
00351 
00352         $params = array('timeold'=>$timeold, 'timeoldext'=>$timeoldext, 'cmid'=>$cm->id);
00353 
00354         $timeout = "AND (chu.version<>'basic' AND chu.lastping>:timeold) OR (chu.version='basic' AND chu.lastping>:timeoldext)";
00355 
00356         foreach ($current as $cm) {
00357             //count users first
00358             if (isset($cm->mygroupids)) {
00359                 $groupselect = "AND (chu.groupid IN ({$cm->mygroupids}) OR chu.groupid = 0)";
00360             } else {
00361                 $groupselect = "";
00362             }
00363 
00364             if (!$users = $DB->get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email, u.picture
00365                                                   FROM {course_modules} cm
00366                                                   JOIN {chat} ch        ON ch.id = cm.instance
00367                                                   JOIN {chat_users} chu ON chu.chatid = ch.id
00368                                                   JOIN {user} u         ON u.id = chu.userid
00369                                                  WHERE cm.id = :cmid $timeout $groupselect
00370                                               GROUP BY u.id, u.firstname, u.lastname, u.email, u.picture", $params)) {
00371             }
00372 
00373             $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
00374             $date = userdate($cm->lasttime, $strftimerecent);
00375 
00376             echo '<div class="head"><div class="date">'.$date.'</div></div>';
00377             echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name,true).'</a></div>';
00378             echo '<div class="userlist">';
00379             if ($users) {
00380                 echo '<ul>';
00381                     foreach ($users as $user) {
00382                         echo '<li>'.fullname($user, $viewfullnames).'</li>';
00383                     }
00384                 echo '</ul>';
00385             }
00386             echo '</div>';
00387         }
00388     }
00389 
00390     return true;
00391 }
00392 
00401 function chat_cron () {
00402     global $DB;
00403 
00404     chat_update_chat_times();
00405 
00406     chat_delete_old_users();
00407 
00410     $subselect = "SELECT c.keepdays
00411                     FROM {chat} c
00412                    WHERE c.id = {chat_messages}.chatid";
00413 
00414     $sql = "DELETE
00415               FROM {chat_messages}
00416              WHERE ($subselect) > 0 AND timestamp < ( ".time()." -($subselect) * 24 * 3600)";
00417 
00418     $DB->execute($sql);
00419 
00420     $sql = "DELETE
00421               FROM {chat_messages_current}
00422              WHERE timestamp < ( ".time()." - 8 * 3600)";
00423 
00424     $DB->execute($sql);
00425 
00426     return true;
00427 }
00428 
00439 function chat_get_participants($chatid, $groupid=0) {
00440     global $DB;
00441 
00442     $params = array('groupid'=>$groupid, 'chatid'=>$chatid);
00443 
00444     if ($groupid) {
00445         $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
00446     } else {
00447         $groupselect = "";
00448     }
00449 
00450     //Get students
00451     $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
00452                                         FROM {user} u, {chat_messages} c
00453                                        WHERE c.chatid = :chatid $groupselect
00454                                              AND u.id = c.userid", $params);
00455 
00456     //Return students array (it contains an array of unique users)
00457     return ($students);
00458 }
00459 
00471 function chat_refresh_events($courseid = 0) {
00472     global $DB;
00473 
00474     if ($courseid) {
00475         if (! $chats = $DB->get_records("chat", array("course"=>$courseid))) {
00476             return true;
00477         }
00478     } else {
00479         if (! $chats = $DB->get_records("chat")) {
00480             return true;
00481         }
00482     }
00483     $moduleid = $DB->get_field('modules', 'id', array('name'=>'chat'));
00484 
00485     foreach ($chats as $chat) {
00486         $cm = get_coursemodule_from_id('chat', $chat->id);
00487         $event = new stdClass();
00488         $event->name        = $chat->name;
00489         $event->description = format_module_intro('chat', $chat, $cm->id);
00490         $event->timestart   = $chat->chattime;
00491 
00492         if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'chat', 'instance'=>$chat->id))) {
00493             $calendarevent = calendar_event::load($event->id);
00494             $calendarevent->update($event);
00495         } else {
00496             $event->courseid    = $chat->course;
00497             $event->groupid     = 0;
00498             $event->userid      = 0;
00499             $event->modulename  = 'chat';
00500             $event->instance    = $chat->id;
00501             $event->eventtype   = 'chattime';
00502             $event->timeduration = 0;
00503             $event->visible     = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$chat->id));
00504 
00505             calendar_event::create($event);
00506         }
00507     }
00508     return true;
00509 }
00510 
00511 
00514 
00522 function chat_get_users($chatid, $groupid=0, $groupingid=0) {
00523     global $DB;
00524 
00525     $params = array('chatid'=>$chatid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
00526 
00527     if ($groupid) {
00528         $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
00529     } else {
00530         $groupselect = "";
00531     }
00532 
00533     if (!empty($groupingid)) {
00534         $groupingjoin = "JOIN {groups_members} gm ON u.id = gm.userid
00535                          JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
00536 
00537     } else {
00538         $groupingjoin = '';
00539     }
00540 
00541     $ufields = user_picture::fields('u');
00542     return $DB->get_records_sql("SELECT DISTINCT $ufields, c.lastmessageping, c.firstping
00543                                    FROM {chat_users} c
00544                                    JOIN {user} u ON u.id = c.userid $groupingjoin
00545                                   WHERE c.chatid = :chatid $groupselect
00546                                ORDER BY c.firstping ASC", $params);
00547 }
00548 
00555 function chat_get_latest_message($chatid, $groupid=0) {
00556     global $DB;
00557 
00558     $params = array('chatid'=>$chatid, 'groupid'=>$groupid);
00559 
00560     if ($groupid) {
00561         $groupselect = "AND (groupid=:groupid OR groupid=0)";
00562     } else {
00563         $groupselect = "";
00564     }
00565 
00566     $sql = "SELECT *
00567         FROM {chat_messages_current} WHERE chatid = :chatid $groupselect
00568         ORDER BY timestamp DESC";
00569 
00570     // return the lastest one message
00571     return $DB->get_record_sql($sql, $params, true);
00572 }
00573 
00574 
00576 // login if not already logged in
00577 
00589 function chat_login_user($chatid, $version, $groupid, $course) {
00590     global $USER, $DB;
00591 
00592     if (($version != 'sockets') and $chatuser = $DB->get_record('chat_users', array('chatid'=>$chatid, 'userid'=>$USER->id, 'groupid'=>$groupid))) {
00593         // this will update logged user information
00594         $chatuser->version  = $version;
00595         $chatuser->ip       = $USER->lastip;
00596         $chatuser->lastping = time();
00597         $chatuser->lang     = current_language();
00598 
00599         // Sometimes $USER->lastip is not setup properly
00600         // during login. Update with current value if possible
00601         // or provide a dummy value for the db
00602         if (empty($chatuser->ip)) {
00603             $chatuser->ip = getremoteaddr();
00604         }
00605 
00606         if (($chatuser->course != $course->id) or ($chatuser->userid != $USER->id)) {
00607             return false;
00608         }
00609         $DB->update_record('chat_users', $chatuser);
00610 
00611     } else {
00612         $chatuser = new stdClass();
00613         $chatuser->chatid   = $chatid;
00614         $chatuser->userid   = $USER->id;
00615         $chatuser->groupid  = $groupid;
00616         $chatuser->version  = $version;
00617         $chatuser->ip       = $USER->lastip;
00618         $chatuser->lastping = $chatuser->firstping = $chatuser->lastmessageping = time();
00619         $chatuser->sid      = random_string(32);
00620         $chatuser->course   = $course->id; //caching - needed for current_language too
00621         $chatuser->lang     = current_language(); //caching - to resource intensive to find out later
00622 
00623         // Sometimes $USER->lastip is not setup properly
00624         // during login. Update with current value if possible
00625         // or provide a dummy value for the db
00626         if (empty($chatuser->ip)) {
00627             $chatuser->ip = getremoteaddr();
00628         }
00629 
00630 
00631         $DB->insert_record('chat_users', $chatuser);
00632 
00633         if ($version == 'sockets') {
00634             // do not send 'enter' message, chatd will do it
00635         } else {
00636             $message = new stdClass();
00637             $message->chatid    = $chatuser->chatid;
00638             $message->userid    = $chatuser->userid;
00639             $message->groupid   = $groupid;
00640             $message->message   = 'enter';
00641             $message->system    = 1;
00642             $message->timestamp = time();
00643 
00644             $DB->insert_record('chat_messages', $message);
00645             $DB->insert_record('chat_messages_current', $message);
00646         }
00647     }
00648 
00649     return $chatuser->sid;
00650 }
00651 
00658 function chat_delete_old_users() {
00659 // Delete the old and in the way
00660     global $CFG, $DB;
00661 
00662     $timeold = time() - $CFG->chat_old_ping;
00663     $timeoldext = time() - ($CFG->chat_old_ping*10); // JSless gui_basic needs much longer timeouts
00664 
00665     $query = "(version<>'basic' AND lastping<?) OR (version='basic' AND lastping<?)";
00666     $params = array($timeold, $timeoldext);
00667 
00668     if ($oldusers = $DB->get_records_select('chat_users', $query, $params) ) {
00669         $DB->delete_records_select('chat_users', $query, $params);
00670         foreach ($oldusers as $olduser) {
00671             $message = new stdClass();
00672             $message->chatid    = $olduser->chatid;
00673             $message->userid    = $olduser->userid;
00674             $message->groupid   = $olduser->groupid;
00675             $message->message   = 'exit';
00676             $message->system    = 1;
00677             $message->timestamp = time();
00678 
00679             $DB->insert_record('chat_messages', $message);
00680             $DB->insert_record('chat_messages_current', $message);
00681         }
00682     }
00683 }
00684 
00692 function chat_update_chat_times($chatid=0) {
00694     global $DB;
00695 
00696     $timenow = time();
00697 
00698     $params = array('timenow'=>$timenow, 'chatid'=>$chatid);
00699 
00700     if ($chatid) {
00701         if (!$chats[] = $DB->get_record_select("chat", "id = :chatid AND chattime <= :timenow AND schedule > 0", $params)) {
00702             return;
00703         }
00704     } else {
00705         if (!$chats = $DB->get_records_select("chat", "chattime <= :timenow AND schedule > 0", $params)) {
00706             return;
00707         }
00708     }
00709 
00710     foreach ($chats as $chat) {
00711         switch ($chat->schedule) {
00712             case 1: // Single event - turn off schedule and disable
00713                     $chat->chattime = 0;
00714                     $chat->schedule = 0;
00715                     break;
00716             case 2: // Repeat daily
00717                     while ($chat->chattime <= $timenow) {
00718                         $chat->chattime += 24 * 3600;
00719                     }
00720                     break;
00721             case 3: // Repeat weekly
00722                     while ($chat->chattime <= $timenow) {
00723                         $chat->chattime += 7 * 24 * 3600;
00724                     }
00725                     break;
00726         }
00727         $DB->update_record("chat", $chat);
00728 
00729         $event = new stdClass();           // Update calendar too
00730 
00731         $cond = "modulename='chat' AND instance = :chatid AND timestart <> :chattime";
00732         $params = array('chattime'=>$chat->chattime, 'chatid'=>$chatid);
00733 
00734         if ($event->id = $DB->get_field_select('event', 'id', $cond, $params)) {
00735             $event->timestart   = $chat->chattime;
00736             $calendarevent = calendar_event::load($event->id);
00737             $calendarevent->update($event, false);
00738         }
00739     }
00740 }
00741 
00752 function chat_format_message_manually($message, $courseid, $sender, $currentuser, $chat_lastrow=NULL) {
00753     global $CFG, $USER, $OUTPUT;
00754 
00755     $output = new stdClass();
00756     $output->beep = false;       // by default
00757     $output->refreshusers = false; // by default
00758 
00759     // Use get_user_timezone() to find the correct timezone for displaying this message:
00760     // It's either the current user's timezone or else decided by some Moodle config setting
00761     // First, "reset" $USER->timezone (which could have been set by a previous call to here)
00762     // because otherwise the value for the previous $currentuser will take precedence over $CFG->timezone
00763     $USER->timezone = 99;
00764     $tz = get_user_timezone($currentuser->timezone);
00765 
00766     // Before formatting the message time string, set $USER->timezone to the above.
00767     // This will allow dst_offset_on (called by userdate) to work correctly, otherwise the
00768     // message times appear off because DST is not taken into account when it should be.
00769     $USER->timezone = $tz;
00770     $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
00771 
00772     $message->picture = $OUTPUT->user_picture($sender, array('size'=>false, 'courseid'=>$courseid, 'link'=>false));
00773 
00774     if ($courseid) {
00775         $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>";
00776     }
00777 
00778     //Calculate the row class
00779     if ($chat_lastrow !== NULL) {
00780         $rowclass = ' class="r'.$chat_lastrow.'" ';
00781     } else {
00782         $rowclass = '';
00783     }
00784 
00785     // Start processing the message
00786 
00787     if(!empty($message->system)) {
00788         // System event
00789         $output->text = $message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender));
00790         $output->html  = '<table class="chat-event"><tr'.$rowclass.'><td class="picture">'.$message->picture.'</td><td class="text">';
00791         $output->html .= '<span class="event">'.$output->text.'</span></td></tr></table>';
00792         $output->basic = '<dl><dt class="event">'.$message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender)).'</dt></dl>';
00793 
00794         if($message->message == 'exit' or $message->message == 'enter') {
00795             $output->refreshusers = true; //force user panel refresh ASAP
00796         }
00797         return $output;
00798     }
00799 
00800     // It's not a system event
00801 
00802     $text = $message->message;
00803 
00805 
00806     $options = new stdClass();
00807     $options->para = false;
00808     $text = format_text($text, FORMAT_MOODLE, $options, $courseid);
00809 
00810     // And now check for special cases
00811     $special = false;
00812 
00813     if (substr($text, 0, 5) == 'beep ') {
00815         $special = true;
00816         $beepwho = trim(substr($text, 5));
00817 
00818         if ($beepwho == 'all') {   // everyone
00819             $outinfo = $message->strtime.': '.get_string('messagebeepseveryone', 'chat', fullname($sender));
00820             $outmain = '';
00821             $output->beep = true;  // (eventually this should be set to
00822                                    //  to a filename uploaded by the user)
00823 
00824         } else if ($beepwho == $currentuser->id) {  // current user
00825             $outinfo = $message->strtime.': '.get_string('messagebeepsyou', 'chat', fullname($sender));
00826             $outmain = '';
00827             $output->beep = true;
00828 
00829         } else {  //something is not caught?
00830             return false;
00831         }
00832     } else if (substr($text, 0, 1) == '/') {     
00833         // support some IRC commands
00834         $pattern = '#(^\/)(\w+).*#';
00835         preg_match($pattern, trim($text), $matches);
00836         $command = $matches[2];
00837         switch ($command){
00838         case 'me':
00839             $special = true;
00840             $outinfo = $message->strtime;
00841             $outmain = '*** <b>'.$sender->firstname.' '.substr($text, 4).'</b>';
00842             break;
00843         }
00844     } elseif (substr($text, 0, 2) == 'To') {
00845         $pattern = '#To[[:space:]](.*):(.*)#';
00846         preg_match($pattern, trim($text), $matches);
00847         $special = true;
00848         $outinfo = $message->strtime;
00849         $outmain = $sender->firstname.' '.get_string('saidto', 'chat').' <i>'.$matches[1].'</i>: '.$matches[2];
00850     }
00851 
00852     if(!$special) {
00853         $outinfo = $message->strtime.' '.$sender->firstname;
00854         $outmain = $text;
00855     }
00856 
00858 
00859     $output->text  = strip_tags($outinfo.': '.$outmain);
00860 
00861     $output->html  = "<table class=\"chat-message\"><tr$rowclass><td class=\"picture\" valign=\"top\">$message->picture</td><td class=\"text\">";
00862     $output->html .= "<span class=\"title\">$outinfo</span>";
00863     if ($outmain) {
00864         $output->html .= ": $outmain";
00865         $output->basic = '<dl><dt class="title">'.$outinfo.':</dt><dd class="text">'.$outmain.'</dd></dl>';
00866     } else {
00867         $output->basic = '<dl><dt class="title">'.$outinfo.'</dt></dl>';
00868     }
00869     $output->html .= "</td></tr></table>";
00870     return $output;
00871 }
00872 
00881 function chat_format_message($message, $courseid, $currentuser, $chat_lastrow=NULL) {
00885     global $DB;
00886 
00887     static $users;     // Cache user lookups
00888 
00889     if (isset($users[$message->userid])) {
00890         $user = $users[$message->userid];
00891     } else if ($user = $DB->get_record('user', array('id'=>$message->userid), user_picture::fields())) {
00892         $users[$message->userid] = $user;
00893     } else {
00894         return NULL;
00895     }
00896     return chat_format_message_manually($message, $courseid, $user, $currentuser, $chat_lastrow);
00897 }
00898 
00908 function chat_format_message_theme ($message, $chatuser, $currentuser, $groupingid, $theme = 'bubble') {
00909     global $CFG, $USER, $OUTPUT, $COURSE, $DB;
00910 
00911     static $users;     // Cache user lookups
00912 
00913     $result = new stdClass();
00914 
00915     if (file_exists($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php')) {
00916         include($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php');
00917     }
00918 
00919     if (isset($users[$message->userid])) {
00920         $sender = $users[$message->userid];
00921     } else if ($sender = $DB->get_record('user', array('id'=>$message->userid), user_picture::fields())) {
00922         $users[$message->userid] = $sender;
00923     } else {
00924         return NULL;
00925     }
00926 
00927     $USER->timezone = 99;
00928     $tz = get_user_timezone($currentuser->timezone);
00929     $USER->timezone = $tz;
00930 
00931     if (empty($chatuser->course)) {
00932         $courseid = $COURSE->id;
00933     } else {
00934         $courseid = $chatuser->course;
00935     }
00936 
00937     $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
00938     $message->picture = $OUTPUT->user_picture($sender, array('courseid'=>$courseid));
00939 
00940     $message->picture = "<a target='_blank' href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">$message->picture</a>";
00941 
00942     // Start processing the message
00943     if(!empty($message->system)) {
00944         $result->type = 'system';
00945 
00946         $userlink = new moodle_url('/user/view.php', array('id'=>$message->userid,'course'=>$courseid));
00947 
00948         $patterns = array();
00949         $replacements = array();
00950         $patterns[] = '___senderprofile___';
00951         $patterns[] = '___sender___';
00952         $patterns[] = '___time___';
00953         $patterns[] = '___event___';
00954         $replacements[] = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&amp;course='.$courseid;
00955         $replacements[] = fullname($sender);
00956         $replacements[] = $message->strtime;
00957         $replacements[] = get_string('message'.$message->message, 'chat', fullname($sender));
00958         $result->html = str_replace($patterns, $replacements, $chattheme_cfg->event_message);
00959         return $result;
00960     }
00961 
00962     // It's not a system event
00963     $text = $message->message;
00964 
00966     $options = new stdClass();
00967     $options->para = false;
00968     $text = format_text($text, FORMAT_MOODLE, $options, $courseid);
00969 
00970     // And now check for special cases
00971     $special = false;
00972     $outtime = $message->strtime;
00973 
00974     //Initilise output variable.
00975     $outmain = '';
00976 
00977     if (substr($text, 0, 5) == 'beep ') {
00978         $special = true;
00980         $result->type = 'beep';
00981         $beepwho = trim(substr($text, 5));
00982 
00983         if ($beepwho == 'all') {   // everyone
00984             $outmain =  get_string('messagebeepseveryone', 'chat', fullname($sender));
00985         } else if ($beepwho == $currentuser->id) {  // current user
00986             $outmain = get_string('messagebeepsyou', 'chat', fullname($sender));
00987         } else if ($sender->id == $currentuser->id) {  //something is not caught?
00988             //allow beep for a active chat user only, else user can beep anyone and get fullname
00989             if (!empty($chatuser) && is_numeric($beepwho)) {
00990                $chatusers = chat_get_users($chatuser->chatid, $chatuser->groupid, $groupingid);
00991                if (array_key_exists($beepwho, $chatusers)) {
00992                    $outmain = get_string('messageyoubeep', 'chat', fullname($chatusers[$beepwho]));
00993                } else {
00994                    $outmain = get_string('messageyoubeep', 'chat', $beepwho);
00995                }
00996             } else {
00997                 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
00998             }
00999         }
01000     } else if (substr($text, 0, 1) == '/') {     
01001         $special = true;
01002         $result->type = 'command';
01003         // support some IRC commands
01004         $pattern = '#(^\/)(\w+).*#';
01005         preg_match($pattern, trim($text), $matches);
01006         $command = $matches[2];
01007         $special = true;
01008         switch ($command){
01009         case 'me':
01010             $outmain = '*** <b>'.$sender->firstname.' '.substr($text, 4).'</b>';
01011             break;
01012         }
01013     } elseif (substr($text, 0, 2) == 'To') {
01014         $special = true;
01015         $result->type = 'dialogue';
01016         $pattern = '#To[[:space:]](.*):(.*)#';
01017         preg_match($pattern, trim($text), $matches);
01018         $special = true;
01019         $outmain = $sender->firstname.' <b>'.get_string('saidto', 'chat').'</b> <i>'.$matches[1].'</i>: '.$matches[2];
01020     }
01021 
01022     if(!$special) {
01023         $outmain = $text;
01024     }
01025 
01026     $result->text = strip_tags($outtime.': '.$outmain);
01027 
01028     $ismymessage = '';
01029     $rightalign = '';
01030     if ($sender->id == $USER->id) {
01031         $ismymessage = ' class="mymessage"';
01032         $rightalign = ' align="right"';
01033     }
01034     $patterns = array();
01035     $replacements = array();
01036     $patterns[] = '___avatar___';
01037     $patterns[] = '___sender___';
01038     $patterns[] = '___senderprofile___';
01039     $patterns[] = '___time___';
01040     $patterns[] = '___message___';
01041     $patterns[] = '___mymessageclass___';
01042     $patterns[] = '___tablealign___';
01043     $replacements[] = $message->picture;
01044     $replacements[] = fullname($sender);
01045     $replacements[] = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&amp;course='.$courseid;
01046     $replacements[] = $outtime;
01047     $replacements[] = $outmain;
01048     $replacements[] = $ismymessage;
01049     $replacements[] = $rightalign;
01050     if (!empty($chattheme_cfg->avatar) and !empty($chattheme_cfg->align)) {
01051         if (!empty($ismymessage)) {
01052             $result->html = str_replace($patterns, $replacements, $chattheme_cfg->user_message_right);
01053         } else {
01054             $result->html = str_replace($patterns, $replacements, $chattheme_cfg->user_message_left);
01055         }
01056     } else {
01057         $result->html = str_replace($patterns, $replacements, $chattheme_cfg->user_message);
01058     }
01059 
01060     //When user beeps other user, then don't show any timestamp to other users in chat.
01061     if (('' === $outmain) && $special) {
01062         return false;
01063     } else {
01064         return $result;
01065     }
01066 }
01067 
01068 
01078 function chat_format_userlist($users, $course) {
01079     global $CFG, $DB, $COURSE, $OUTPUT;
01080     $result = array();
01081     foreach($users as $user){
01082         $item = array();
01083         $item['name'] = fullname($user);
01084         $item['url'] = $CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id;
01085         $item['picture'] = $OUTPUT->user_picture($user);
01086         $item['id'] = $user->id;
01087         $result[] = $item;
01088     }
01089     return $result;
01090 }
01091 
01097 function chat_print_error($level, $msg) {
01098     header('Content-Length: ' . ob_get_length() );
01099     $error = new stdClass();
01100     $error->level = $level;
01101     $error->msg   = $msg;
01102     $response['error'] = $error;
01103     echo json_encode($response);
01104     ob_end_flush();
01105     exit;
01106 }
01107 
01111 function chat_get_view_actions() {
01112     return array('view','view all','report');
01113 }
01114 
01118 function chat_get_post_actions() {
01119     return array('talk');
01120 }
01121 
01128 function chat_print_overview($courses, &$htmlarray) {
01129     global $USER, $CFG;
01130 
01131     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
01132         return array();
01133     }
01134 
01135     if (!$chats = get_all_instances_in_courses('chat',$courses)) {
01136         return;
01137     }
01138 
01139     $strchat = get_string('modulename', 'chat');
01140     $strnextsession  = get_string('nextsession', 'chat');
01141 
01142     foreach ($chats as $chat) {
01143         if ($chat->chattime and $chat->schedule) {  // A chat is scheduled
01144             $str = '<div class="chat overview"><div class="name">'.
01145                    $strchat.': <a '.($chat->visible?'':' class="dimmed"').
01146                    ' href="'.$CFG->wwwroot.'/mod/chat/view.php?id='.$chat->coursemodule.'">'.
01147                    $chat->name.'</a></div>';
01148             $str .= '<div class="info">'.$strnextsession.': '.userdate($chat->chattime).'</div></div>';
01149 
01150             if (empty($htmlarray[$chat->course]['chat'])) {
01151                 $htmlarray[$chat->course]['chat'] = $str;
01152             } else {
01153                 $htmlarray[$chat->course]['chat'] .= $str;
01154             }
01155         }
01156     }
01157 }
01158 
01159 
01166 function chat_reset_course_form_definition(&$mform) {
01167     $mform->addElement('header', 'chatheader', get_string('modulenameplural', 'chat'));
01168     $mform->addElement('advcheckbox', 'reset_chat', get_string('removemessages','chat'));
01169 }
01170 
01177 function chat_reset_course_form_defaults($course) {
01178     return array('reset_chat'=>1);
01179 }
01180 
01190 function chat_reset_userdata($data) {
01191     global $CFG, $DB;
01192 
01193     $componentstr = get_string('modulenameplural', 'chat');
01194     $status = array();
01195 
01196     if (!empty($data->reset_chat)) {
01197         $chatessql = "SELECT ch.id
01198                         FROM {chat} ch
01199                        WHERE ch.course=?";
01200         $params = array($data->courseid);
01201 
01202         $DB->delete_records_select('chat_messages', "chatid IN ($chatessql)", $params);
01203         $DB->delete_records_select('chat_messages_current', "chatid IN ($chatessql)", $params);
01204         $DB->delete_records_select('chat_users', "chatid IN ($chatessql)", $params);
01205         $status[] = array('component'=>$componentstr, 'item'=>get_string('removemessages', 'chat'), 'error'=>false);
01206     }
01207 
01209     if ($data->timeshift) {
01210         shift_course_mod_dates('chat', array('chattime'), $data->timeshift, $data->courseid);
01211         $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
01212     }
01213 
01214     return $status;
01215 }
01216 
01222 function chat_get_extra_capabilities() {
01223     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
01224 }
01225 
01226 
01231 function chat_supports($feature) {
01232     switch($feature) {
01233         case FEATURE_GROUPS:                  return true;
01234         case FEATURE_GROUPINGS:               return true;
01235         case FEATURE_GROUPMEMBERSONLY:        return true;
01236         case FEATURE_MOD_INTRO:               return true;
01237         case FEATURE_BACKUP_MOODLE2:          return true;
01238         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
01239         case FEATURE_GRADE_HAS_GRADE:         return false;
01240         case FEATURE_GRADE_OUTCOMES:          return true;
01241         case FEATURE_SHOW_DESCRIPTION:        return true;
01242 
01243         default: return null;
01244     }
01245 }
01246 
01247 function chat_extend_navigation($navigation, $course, $module, $cm) {
01248     global $CFG, $USER, $PAGE, $OUTPUT;
01249 
01250     $currentgroup = groups_get_activity_group($cm, true);
01251 
01252     if (has_capability('mod/chat:chat', get_context_instance(CONTEXT_MODULE, $cm->id))) {
01253         $strenterchat    = get_string('enterchat', 'chat');
01254 
01255         $target = $CFG->wwwroot.'/mod/chat/';
01256         $params = array('id'=>$cm->instance);
01257 
01258         if ($currentgroup) {
01259             $params['groupid'] = $currentgroup;
01260         }
01261 
01262         $links = array();
01263 
01264         // If user is using screenreader, display gui_basic gui link only
01265         if (empty($USER->screenreader)) {
01266             $url = new moodle_url($target.'gui_'.$CFG->chat_method.'/index.php', $params);
01267             $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup, array('height' => 500, 'width' => 700));
01268             $links[] = new action_link($url, $strenterchat, $action);
01269         }
01270 
01271         $url = new moodle_url($target.'gui_basic/index.php', $params);
01272         $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup, array('height' => 500, 'width' => 700));
01273         $links[] = new action_link($url, get_string('noframesjs', 'message'), $action);
01274 
01275         foreach ($links as $link) {
01276             $navigation->add($link->text, $link, navigation_node::TYPE_SETTING, null ,null, new pix_icon('c/group' , ''));
01277         }
01278     }
01279 
01280     $chatusers = chat_get_users($cm->instance, $currentgroup, $cm->groupingid);
01281     if (is_array($chatusers) && count($chatusers)>0) {
01282         $users = $navigation->add(get_string('currentusers', 'chat'));
01283         foreach ($chatusers as $chatuser) {
01284             $userlink = new moodle_url('/user/view.php', array('id'=>$chatuser->id,'course'=>$course->id));
01285             $users->add(fullname($chatuser).' '.format_time(time() - $chatuser->lastmessageping), $userlink, navigation_node::TYPE_USER, null, null, new pix_icon('c/user', ''));
01286         }
01287     }
01288 }
01289 
01296 function chat_extend_settings_navigation(settings_navigation $settings, navigation_node $chatnode) {
01297     global $DB, $PAGE, $USER;
01298     $chat = $DB->get_record("chat", array("id" => $PAGE->cm->instance));
01299 
01300     if ($chat->chattime && $chat->schedule) {
01301         $nextsessionnode = $chatnode->add(get_string('nextsession', 'chat').': '.userdate($chat->chattime).' ('.usertimezone($USER->timezone));
01302         $nextsessionnode->add_class('note');
01303     }
01304 
01305     $currentgroup = groups_get_activity_group($PAGE->cm, true);
01306     if ($currentgroup) {
01307         $groupselect = " AND groupid = '$currentgroup'";
01308     } else {
01309         $groupselect = '';
01310     }
01311 
01312     if ($chat->studentlogs || has_capability('mod/chat:readlog',$PAGE->cm->context)) {
01313         if ($DB->get_records_select('chat_messages', "chatid = ? $groupselect", array($chat->id))) {
01314             $chatnode->add(get_string('viewreport', 'chat'), new moodle_url('/mod/chat/report.php', array('id'=>$PAGE->cm->id)));
01315         }
01316     }
01317 }
01318 
01324 function chat_user_logout($user) {
01325     global $DB;
01326     $DB->delete_records('chat_users', array('userid'=>$user->id));
01327 }
01328 
01335 function chat_page_type_list($pagetype, $parentcontext, $currentcontext) {
01336     $module_pagetype = array('mod-chat-*'=>get_string('page-mod-chat-x', 'chat'));
01337     return $module_pagetype;
01338 }
 All Data Structures Namespaces Files Functions Variables Enumerations