[ Index ]

PHP Cross Reference of Moodle 1.9.3 [Build 15-Oct-2008]

title

Body

[close]

/mod/chat/ -> lib.php (source)

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


Generated: Wed Jan 14 11:33:29 2009 Cross-referenced by PHPXref 0.7