<?php

class SBBUsers {

  var $count = 0;
  var $error;
  var $success;
  var $p = 1;
  var $users = array();
  var $userposts = array();
     
  function SBBUsers() {
    global $SBBAuth, $board_config;
    $this->auth = $SBBAuth;
    $this->board_config = $board_config;
    $this->uper_page = $board_config->users_per_page;
    if (intval($_REQUEST["p"])) $this->p = intval($_REQUEST["p"]);
    $this->orderbyusers = $_SESSION["orderbyusers"];
    $this->orderbydir = $_SESSION["orderbydir"];
    if (!$this->orderbydir) $this->orderbydir = "asc";
    if (!$this->orderbyusers) $this->orderbyusers = "joined";
    if ($_REQUEST["orderby"]) {
      if ($this->orderbyusers == $_REQUEST["orderby"]) $this->orderbydir = $_SESSION["orderbydir"] = ($this->orderbydir == "asc" ? "desc" : "asc");
      else $this->orderbydir = $_SESSION["orderbydir"] = "asc";
      $this->orderbyusers = $_SESSION["orderbyusers"] = trim($_REQUEST["orderby"]);
    }
  }
  
  function UserList() {
    $orderby = "id";
    if ($this->orderbyusers == "nickname") $orderby = "user"; 
    elseif ($this->orderbyusers == "lastlogin") $orderby = "last_login";  
    else unset ($this->orderbyusers);
    
    //get totals
    $sql = "select * from `" . $this->board_config->prefix . "users` " . (!$this->auth->is_mod ?  "where status = '1'" : "");
    $res = dbquery($sql);
    $total = mysql_num_rows($res);
    
    //some pagecalculations
    if ($this->uper_page) {
      if (($this->p * $this->uper_page) >= ($total+$this->uper_page)) $this->p = 1;       //if you are redirecting to page without ..., the page will be set to 1
      $offset = ($this->p * $this->uper_page) - $this->uper_page;
      $this->pages = ceil($total/$this->uper_page);
      $limitsql = " limit $offset, " . $this->uper_page;
    }
    
    //get postcounts
    $this->UserPosts();
        
    //the users  
    $sql = "select * from `" . $this->board_config->prefix . "users` " . (!$this->auth->is_mod ?  "where status = '1'" : "") . " order by $orderby " . $this->orderbydir . " $limitsql";
    $res = dbquery($sql);
    while ($row = mysql_fetch_object($res)) {
      $row->userposts = $this->userposts[$row->id];
      $this->users[] = $row;
    }
    $this->count = mysql_num_rows($res);
  }
  
  function UserPosts() {
    //count userposts
    $sql = "select count(a_id) as counted, a_uid from `" . $this->board_config->prefix . "answer` group by a_uid;";
    $res = dbquery($sql);
    while ($row = mysql_fetch_object($res)) {
      $this->userposts[$row->a_uid] = $row->counted;
    }
    $sql = "select count(id) as counted, uid from `" . $this->board_config->prefix . "question` group by uid;";
    $res = dbquery($sql);
    while ($row = mysql_fetch_object($res)) {
      $this->userposts[$row->uid] += $row->counted;
    }
    return $userposts;
  }
  
}

?>