<?php
# version 0.41
class UserRightsList extends UserrightsPage {

	function __construct(){
		SpecialPage::__construct('UserRightsList');
	#	SpecialPage::SpecialPage("UserRightsList", 'createaccount');
		self::loadMessages();
		$this->offset=0;
		$this->limit=50;
		list ($this->user_table,$this->user_groups_table) = wfGetDB(DB_MASTER)->tableNamesN('user','user_groups');
		return true;
	}

	public function userCanExecute( $user ) {
		global $egUserRightsListChGrp, $wgAddGroups, $wgRemoveGroups;
		if (!isset($egUserRightsListChGrp)) return true;
		foreach ($egUserRightsListChGrp as $group=>$chgrps){
			foreach ($chgrps as $grp)	$wgAddGroups[$group][] = $grp;
			foreach ($chgrps as $grp)	$wgRemoveGroups[$group][] = $grp;
		}
		return parent::userCanExecute( $user );
	}

	function execute( $par ) {
		global $wgRequest, $wgOut, $wgUser;
		$this->setHeaders();
		if( !$this->userCanExecute( $wgUser ) ) {
			// fixme... there may be intermediate groups we can mention.
			global $wgOut;
			$wgOut->showPermissionsErrorPage( array(
				$wgUser->isAnon()
					? 'userrights-nologin'
					: 'userrights-notallowed' ) );
			return true;
		}
		# Get request data from, e.g.
		$fields = array('yearfrom','yearto','monthfrom','monthto','username','offset','limit','group');
		foreach($fields as $field){
			if (!is_null($wgRequest->getVal($field))) $this->$field = $wgRequest->getVal($field);
		}
		if ($wgRequest->getText('act') == 'save') $this->save_rights();
		$output = $this->make_form($this->findMyUsers());
		$wgOut->addHTML( $output );
		return true;
	}
	
	function save_rights(){
		global $wgRequest;
		$users = $this->findMyUsers();
		foreach ($users as $user){
			$u = User::newFromId($user['user_id']);
			if(is_object($u)) {
				$oldGroups = $u->getGroups();
				$newGroups = $wgRequest->getArray('user_'.$user['user_id']);
				if(is_null($wgRequest->getArray('user_'.$user['user_id']))) $newGroups = array();;
				// remove then add groups
				$removegroup = array_diff($oldGroups, $newGroups); 			
				$addgroup = array_diff($newGroups, $oldGroups);
				if (count(array_merge($removegroup, $addgroup)) == 0) continue;
				# for 1.13
				$wgRequest->data['user'] = $u->getName();
				$wgRequest->data['wpEditToken'] = $u->editToken();	
				foreach ($newGroups as $group)	$wgRequest->data['wpGroup-'.$group] = 1;
				
				UserrightsPage::saveUserGroups( $u->getName(), $removegroup, $addgroup);
			}
		}
		return true;
	}
/*
# functions from Special::Userrights
	function fetchUser( $username ) {
		$user = UserrightsPage::fetchUser( $username );
		return $user;
	}
	function getAllGroups() {
		return User::getAllGroups();
	}

	function addLogEntry( $user, $oldGroups, $newGroups ) {
		return UserrightsPage::addLogEntry( $user, $oldGroups, $newGroups ) ;
	}

	function changeableByGroup( $group ) {
		global $wgAddGroups, $wgRemoveGroups;
		return UserrightsPage::changeableByGroup($group);
	}

	function changeableGroups( ) {
		return UserrightsPage::changeableGroups();
	}

	function makeGroupNameList( $ids ) {
		return implode( ', ', $ids );
	}
*/

	# takes an array of users where each user is a hash
	#	user_id, user_name, log_timestamp
	function make_form($users){
		global $wgUser;
		$form = $this->pageTop();
		if (count($users) == 0) return $form.wfMsg('nousersfound');
		$form .= $this->navLinks();
		$form .= "<br/><form method='post'><table>\n";
		$row = 1; $style = array('',"bgcolor = '#dddddd'");
		$changeable = UserrightsPage::changeableGroups();
		$changeable_groups = array_unique($changeable['add']+$changeable['remove']+$changeable['add-self']+$changeable['remove-self']);
		foreach ($users as $user){
			$mwUser = User::newFromId($user['user_id']);
			$mwUser->loadFromId();
			
			$form .= "<tr valign='bottom' ".$style[$row]."><td>".$user['user_name'].":</td>";
			foreach ($changeable_groups as $group){
				if (in_array($group, User::getAllGroups())){
					$checked = '';
					if (in_array($group, $mwUser->getGroups())) $checked = 'checked';
					$form .= "<td><input name='user.".$user['user_id']."[]' id='".$user['user_id']."' type='checkbox' value = '$group' $checked>$group</input></td>";
				}	
			}	
			$form .= "</tr>\n";	
			$row++;
			$row = $row%2;
		}
		$form .= "</table>";
		# Preserve params
		if( isset($this->offset) )
			$form .= wfElement( 'input', array( 'type' => 'hidden', 'name' => 'offset', 'value' => $this->offset ) );
		if( isset($this->limit) )
			$form .= wfElement( 'input', array( 'type' => 'hidden', 'name' => 'limit', 'value' => $this->limit ) );
		if( isset($this->yearfrom) )
			$form .= wfElement( 'input', array( 'type' => 'hidden', 'name' => 'yearfrom', 'value' => $this->yearfrom ) );
		if( isset($this->monthfrom) )
			$form .= wfElement( 'input', array( 'type' => 'hidden', 'name' => 'monthfrom', 'value' => $this->monthfrom ) );
		if( isset($this->yearto) )
			$form .= wfElement( 'input', array( 'type' => 'hidden', 'name' => 'yearto', 'value' => $this->yearto ) );
		if( isset($this->monthto) )
			$form .= wfElement( 'input', array( 'type' => 'hidden', 'name' => 'monthto', 'value' => $this->monthto ) );
		if( isset($this->username) )
			$form .= wfElement( 'input', array( 'type' => 'hidden', 'name' => 'username', 'value' => $this->username ) );
		if( isset($this->group) )
			$form .= wfElement( 'input', array( 'type' => 'hidden', 'name' => 'group', 'value' => $this->group ) );
		
		$form .="
		<input name='act' type='submit' value='save'>
		</form>\n";
		$form .= $this->navLinks();

		return $form;
		
	}

	function pageTop(){
		$self = $this->getTitle();
		$out = '<p>';
		# Form tag
		$out .= wfOpenElement( 'form', array( 'method' => 'post', 'action' => $self->getLocalUrl() ) );
		
		# Group drop-down list
		$out .= wfElement( 'label', array( 'for' => 'group' ), wfMsg( 'group' ) ) . ' ';
		$out .= wfOpenElement( 'select', array( 'name' => 'group' ) );
		$out .= wfElement( 'option', array( 'value' => '' ), wfMsg( 'group-all' ) ); # Item for "all groups"
		$groups = User::getAllGroups();
		foreach( $groups as $group ) {
			$attribs = array( 'value' => $group );
			if( isset($this->group) && $group == $this->group ) $attribs['selected'] = 'selected';
			$out .= wfElement( 'option', $attribs, User::getGroupName( $group ) );
		}
		$out .= wfCloseElement( 'select' ) . ' ';# . wfElement( 'br' );

		# Username field
		$out .= wfElement( 'label', array( 'for' => 'username' ), wfMsg( 'usernamelike' ) ) . '</td><td>';
		$out .= wfElement( 'input', array( 'type' => 'text', 'id' => 'username', 'name' => 'username',
							'value' => @$this->username ) ) . ' ';

		$out .= wfElement( 'label', array( 'for' => 'year' ), wfMsg( 'regafter' ) ) . ' ';
		$years = $this->getYears();
		$out .= $this->yearMenu($years, 'yearfrom');
		$out .= $this->monthMenu('monthfrom').' ';
		$out .= wfElement( 'label', array( 'for' => 'year' ), wfMsg( 'regbefore' ) ) . ' ';
		$out .= $this->yearMenu($years, 'yearto');
		$out .= $this->monthMenu('monthto');


		# Submit button and form bottom
		$out .= wfElement( 'input', array( 'type' => 'submit', 'value' => wfMsg( 'allpagessubmit' ) ) );
		$out .= wfCloseElement( 'form' );
		$out .= '</p>';
		$out .= "<hr>";
		return $out;
	}
	
	function getYears(){
		$dbr =& wfGetDB( DB_SLAVE );
		$years = array();
		$result = $dbr->selectRow(
			$this->user_table, 
			'user_registration', 
			'user_registration IS NOT NULL', 
			__METHOD__, 
			array('ORDER BY' => 'user_registration')
			); 
		$y = 2000; 
		$thisyear = date("Y");
		if (is_object($result))	$y = substr(wfTimeStamp(TS_MW, $result->user_registration),0,4);	
		for ($year = $y; $year <= $thisyear; $year++) $years[] = $year;
		return $years;
	}
	
	# Year drop-down list
	function yearMenu($years, $item = 'yearfrom'){
		$out = wfOpenElement( 'select', array( 'name' => $item ) );
		$out .= wfElement( 'option', array( 'value' => '' ), wfMsg( 'group-all' ) ); # Item for "all years"
		foreach( $years as $year ) {
			$attribs = array( 'value' => $year );
			if( isset ($this->$item) && $year == $this->$item )
				$attribs['selected'] = 'selected';
			$out .= wfElement( 'option', $attribs, $year );
		}
		$out .= wfCloseElement( 'select' ) . ' ';# . wfElement( 'br' );
		return $out;
	}

	function monthMenu($item){
		global $wgContLang;
		$out = wfOpenElement( 'select', array( 'name' => $item ) );
		$out .= wfElement( 'option', array( 'value' => '' ), wfMsg( 'group-all' ) ); # Item for "all months"
		for( $i = 1; $i <= 12; $i++ ) {
			$month = str_pad($i,2,'0',STR_PAD_LEFT);
			$monthName = $wgContLang->getMonthAbbreviation( $i );
			$attribs = array( 'value' => $month );
			if( isset ($this->$item) && $month == $this->$item )
				$attribs['selected'] = 'selected';
			$out .= wfElement( 'option', $attribs, $monthName );
		}
		$out .= wfCloseElement( 'select' ) . ' ';# . wfElement( 'br' );
		return $out;	
	}
	
	function navLinks(){
		global $wgContLang;
		$atend = $this->num < $this->limit;
		$params = array();
		if( isset($this->yearfrom) ) 	$params['yearfrom']	= $this->yearfrom;
		if( isset($this->monthfrom) ) 	$params['monthfrom']	= $this->monthfrom;
		if( isset($this->yearto) ) 		$params['yearto'] 	= $this->yearto;
		if( isset($this->monthto) ) 	$params['monthto'] 	= $this->monthto;
		if( isset($this->username) )	$params['username'] 	= $this->username;
		if( isset($this->group) )		$params['group'] 	= $this->group;
		
		return wfViewPrevNext( 
				$this->offset, 
				$this->limit ,
				$wgContLang->specialPage( $this->getName() ),
				wfArrayToCGI( $params ),
				$atend  );
	}

	function findMyUsers(){
		global $wgUser, $wgDBprefix;
		$dbr =& wfGetDB( DB_SLAVE );
		$vars = array('user_id', 'user_name', 'user_registration');
		if($wgUser->isAllowed('userrights')){
			$table = array($this->user_table);
			$conds = array();		
		}else{
			$table = array($this->user_table,'logging');
			$conds = array('log_title = user_name', 
				"log_type = 'newusers'",
				"log_user = '".$wgUser->getID()."'");
		}
		if (isset($this->group) && $this->group !=''){
			$table[] = $this->user_groups_table;
			$conds = array_merge($conds, array(" ug_user = user_id", "ug_group = '".$this->group."'"));
		}
		if (isset($this->username) && !is_null($this->username) && $this->username != ''){
			$conds = array_merge($conds, array("user_name LIKE'".mysql_real_escape_string($this->username)."' "));
		}
		if (isset($this->yearfrom) && !is_null($this->yearfrom) && $this->yearfrom != ''){
			$month = '00';
			if (!is_null($this->monthfrom )) $month = $this->monthfrom;
			$fromdate =  $dbr->timestamp(str_pad($this->yearfrom.$month, 14, '0', STR_PAD_RIGHT));
			$conds = array_merge($conds, array("user_registration >='$fromdate' "));
		}
		if (isset($this->yearto) && !is_null($this->yearto) && $this->yearto != ''){
			$year = $this->yearto;
			$month = '99';
			if (!is_null($this->monthto ) ) $month = $this->monthto;
			$todate = $dbr->timestamp(str_pad($year.$month, 14, '9', STR_PAD_RIGHT));
			$conds = array_merge($conds, array("user_registration <= '$todate'"));
		}
		$options["ORDER BY"] = "user_name"; 
		$options["LIMIT"] = $this->limit; 
		$options["OFFSET"] = $this->offset; 
		$results = $dbr->select($table, $vars, $conds, __METHOD__, $options);
		$this->num = $dbr->numRows($results);

		if (!$results) return array();
		while( $x = $dbr->fetchObject ( $results ) ) {
			$arr[] = get_object_vars($x);
		}
		#echo "<pre>";print_r($conds);print_r($dbr->lastQuery());echo "</pre>";
		return $arr;
	}

	function loadMessages() {
		static $messagesLoaded = false;
		global $wgMessageCache;
		if ( $messagesLoaded ) return true;
		$messagesLoaded = true;

		require( dirname( __FILE__ ) . '/SpecialUserRightsList.i18n.php' );
		foreach ( $allMessages as $lang => $langMessages ) {
//				$wgMessageCache->addMessages( $langMessages, $lang );
		}
		return true;
	}
}
?>
