You are here

function drupalchat_poll in DrupalChat 6

Same name and namespace in other branches
  1. 6.2 drupalchat.module \drupalchat_poll()
  2. 7.2 drupalchat.module \drupalchat_poll()
  3. 7 drupalchat.module \drupalchat_poll()

Process and get messages

1 string reference to 'drupalchat_poll'
drupalchat_menu in ./drupalchat.module
Implementaiton of hook_menu()

File

./drupalchat.module, line 247
Module code for DrupalChat.

Code

function drupalchat_poll() {
  global $user;
  $initial_time = time();
  if ($_POST['drupalchat_last_timestamp'] > 0) {
    $last_timestamp = check_plain($_POST['drupalchat_last_timestamp']);
  }
  else {
    $last_timestamp = $initial_time;
  }
  $buddylist = _drupalchat_buddylist($user->uid);
  $buddylist_online_old = _drupalchat_buddylist_online($buddylist);
  $polling_method = variable_get('drupalchat_polling_method', DRUPALCHAT_LONGPOLL);
  if ($polling_method == DRUPALCHAT_AJAX) {
    $messages = db_query('SELECT u.name, m.uid1, m.uid2, m.message, m.timestamp FROM {drupalchat_msg} m INNER JOIN {users} u ON m.uid1 = u.uid WHERE m.uid2 = %d AND m.timestamp > %d ORDER BY m.timestamp ASC', $user->uid, $last_timestamp);
    _drupalchat_touch_user($user->uid);
    module_invoke_all('drupalchat_ajaxpoll');

    // AJAX poll hook
  }
  elseif ($polling_method == DRUPALCHAT_LONGPOLL) {
    do {
      sleep(3);
      $buddylist_online = _drupalchat_buddylist_online($buddylist);
      $message_count = db_result(db_query('SELECT COUNT(*) FROM {drupalchat_msg} m INNER JOIN {users} u ON m.uid1 = u.uid WHERE m.uid2 = %d AND m.timestamp > %d', $user->uid, $last_timestamp));
      _drupalchat_touch_user($user->uid);
      module_invoke_all('drupalchat_longpoll');

      // Long poll hook
    } while (time() - $initial_time < ini_get('max_execution_time') - 5 && $message_count == 0 && _drupalchat_buddylist_diff($buddylist_online_old, $buddylist_online));
  }
  $json['messages'] = array();
  if ($message_count > 0) {
    $messages = db_query('SELECT u.name, m.uid1, m.uid2, m.message, m.timestamp FROM {drupalchat_msg} m INNER JOIN {users} u ON m.uid1 = u.uid WHERE m.uid2 = %d AND m.timestamp > %d ORDER BY m.timestamp ASC', $user->uid, $last_timestamp);
    while ($message = db_fetch_object($messages)) {
      $json['messages'][] = array(
        'message' => $message->message,
        'timestamp' => date("H:i", $message->timestamp),
        'uid1' => $message->uid1,
        'name' => $message->name,
      );
      if ($message->timestamp > $last_timestamp) {
        $last_timestamp = $message->timestamp;
      }
    }
  }
  $json['total_messages'] = $message_count;
  $json['last_timestamp'] = $last_timestamp;
  $json['buddylist'] = $buddylist_online ? $buddylist_online : $buddylist_online_old;
  drupal_json($json);
}