<?php

/*
+--------------------------------------------------------------------------
|   Invision Power Board v1.1
|   ========================================
|   by Matthew Mecham
|   (c) 2001,2002 Invision Power Services
|   http://www.ibforums.com
|   ========================================
|   Web: http://www.ibforums.com
|   Email: phpboards@ibforums.com
|   Licence Info: phpib-licence@ibforums.com
+---------------------------------------------------------------------------
|
|   > Admin Forum functions
|   > Module written by Matt Mecham
|   > Date started: 17th March 2002
|
|	> Module Version Number: 1.0.0
+--------------------------------------------------------------------------
*/




$idx = new ad_groups();


class ad_groups {

	var $base_url;

	function ad_groups() {
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		//---------------------------------------
		// Kill globals - globals bad, Homer good.
		//---------------------------------------
		
		$tmp_in = array_merge( $_GET, $_POST, $_COOKIE );
		
		foreach ( $tmp_in as $k => $v )
		{
			unset($$k);
		}

		switch($IN['code'])
		{
			case 'doadd':
				$this->save_group('add');
				break;
				
			case 'add':
				$this->group_form('add');
				break;
				
			case 'edit':
				$this->group_form('edit');
				break;
			
			case 'doedit':
				$this->save_group('edit');
				break;
			
			case 'delete':
				$this->delete_form();
				break;
			
			case 'dodelete':
				$this->do_delete();
				break;
				
			case 'fedit':
				$this->forum_perms();
				break;
				
			case 'dofedit':
				$this->do_forum_perms();
				break;
						
			default:
				$this->main_screen();
				break;
		}
		
	}
	
	
	//+---------------------------------------------------------------------------------
	//
	// Delete a group
	//
	//+---------------------------------------------------------------------------------
	
	function forum_perms()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		if ($IN['id'] == "")
		{
			$ADMIN->error("无法找到用户团队ID，请检查后重试！");
		}
		
		//+----------------------------------
		
		$ADMIN->page_title = "用户团队论坛栏目权限设置";
		
		$ADMIN->page_detail = "你可以在下面快速的设置用户团队在论坛栏目的权限，如果你需要修改用户团队，请返回[用户团队管理]选项。<br><br>你只需要在下面的选择表框中选择或取消相关权限设置。<br><b>全局设置</b> 指所有的用户团队都拥有此权限。你可以在[用户团队管理]中进行设置和修改。";
		
		//+----------------------------------
		
		$DB->query("SELECT g_title, g_id FROM ibf_groups WHERE g_id='".$IN['id']."'");
		$group = $DB->fetch_row();
		
		$gid = $group['g_id'];
		
		//+-------------------------------
		
		$cats     = array();
		$forums   = array();
		$children = array();
		
		$DB->query("SELECT * from ibf_categories WHERE id > 0 ORDER BY position ASC");
		while ($r = $DB->fetch_row())
		{
			$cats[$r['id']] = $r;
		}
		
		$DB->query("SELECT * from ibf_forums ORDER BY position ASC");
		while ($r = $DB->fetch_row())
		{
			
			if ($r['parent_id'] > 0)
			{
				$children[ $r['parent_id'] ][] = $r;
			}
			else
			{
				$forums[] = $r;
			}
			
		}
		
		//+----------------------------------
		
		$ADMIN->html .= $SKIN->start_form( array( 1 => array( 'code'  , 'dofedit' ),
												  2 => array( 'act'   , 'group'   ),
												  3 => array( 'id'    , $gid      ),
									     )      );
		
		$SKIN->td_header[] = array( "论坛栏目名称"   , "20%" );
		$SKIN->td_header[] = array( "回复"        , "10%" );
		$SKIN->td_header[] = array( "主题"       , "10%" );
		$SKIN->td_header[] = array( "发表主题"        , "15%" );
		$SKIN->td_header[] = array( "回复主题"        , "15%" );
		$SKIN->td_header[] = array( "查看主题"         , "15%" );
		$SKIN->td_header[] = array( "上传文件"       , "15%" );
		
		$ADMIN->html .= $SKIN->start_table( "论坛栏目权限设置：".$group['g_title'] );
		
		$last_cat_id = -1;
		
		foreach ($cats as $c)
		{
			
			$ADMIN->html .= $SKIN->add_td_basic( $c['name'], 'center', 'catrow' );
													   
			$last_cat_id = $c['id'];
			
			
			foreach($forums as $r)
			{	
			
				if ($r['category'] == $last_cat_id)
				{
				
					$read   = "";
					$start  = "";
					$reply  = "";
					$upload = "";
					$global = '<center>全局设置</center>';
					
					if ($r['read_perms'] == '*')
					{
						$read = $global;
					}
					else if ( preg_match( "/(^|,)".$gid."(,|$)/", $r['read_perms'] ) )
					{
						$read = "<center><input type='checkbox' name='read_".$r['id']."' value='1' checked></center>";
					}
					else
					{
						$read = "<center><input type='checkbox' name='read_".$r['id']."' value='1'></center>";
					}
					
					//---------------------------
					
					if ($r['start_perms'] == '*')
					{
						$start = $global;
					}
					else if ( preg_match( "/(^|,)".$gid."(,|$)/", $r['start_perms'] ) )
					{
						$start = "<center><input type='checkbox' name='start_".$r['id']."' value='1' checked></center>";
					}
					else
					{
						$start = "<center><input type='checkbox' name='start_".$r['id']."' value='1'></center>";
					}
					
					//---------------------------
					
					if ($r['reply_perms'] == '*')
					{
						$reply = $global;
					}
					else if ( preg_match( "/(^|,)".$gid."(,|$)/", $r['reply_perms'] ) )
					{
						$reply = "<center><input type='checkbox' name='reply_".$r['id']."' value='1' checked></center>";
					}
					else
					{
						$reply = "<center><input type='checkbox' name='reply_".$r['id']."' value='1'></center>";
					}
					
					//---------------------------
					
					if ($r['upload_perms'] == '*')
					{
						$upload = $global;
					}
					else if ( preg_match( "/(^|,)".$gid."(,|$)/", $r['upload_perms'] ) )
					{
						$upload = "<center><input type='checkbox' name='upload_".$r['id']."' value='1' checked></center>";
					}
					else
					{
						$upload = "<center><input type='checkbox' name='upload_".$r['id']."' value='1'></center>";
					}
					
					//---------------------------
					
					if ($r['subwrap'] == 1 and $r['sub_can_post'] != 1)
					{
						$ADMIN->html .= $SKIN->add_td_basic( "&gt; ".$r['name'], 'left', 'catrow2' );
					}
					else
					{
						$css = $r['subwrap'] == 1 ? 'catrow2' : '';
						
						$ADMIN->html .= $SKIN->add_td_row( array(
															   "<b>".$r['name']."</b><br>".$r['description'],
															   "<center>".$r['posts']."</center>",
															   "<center>".$r['topics']."</center>",
															   $start,
															   $reply,
															   $read,
															   $upload
													 )   , $css   );
					}
													 
					if ( ( isset($children[ $r['id'] ]) ) and ( count ($children[ $r['id'] ]) > 0 ) )
					{
						foreach($children[ $r['id'] ] as $idx => $rd)
						{
							$read   = "";
							$start  = "";
							$reply  = "";
							$upload = "";
							$global = '<center>全局设置</center>';
							
							if ($rd['read_perms'] == '*')
							{
								$read = $global;
							}
							else if ( preg_match( "/(^|,)".$gid."(,|$)/", $rd['read_perms'] ) )
							{
								$read = "<center><input type='checkbox' name='read_".$rd['id']."' value='1' checked></center>";
							}
							else
							{
								$read = "<center><input type='checkbox' name='read_".$rd['id']."' value='1'></center>";
							}
							
							//---------------------------
							
							if ($rd['start_perms'] == '*')
							{
								$start = $global;
							}
							else if ( preg_match( "/(^|,)".$gid."(,|$)/", $rd['start_perms'] ) )
							{
								$start = "<center><input type='checkbox' name='start_".$rd['id']."' value='1' checked></center>";
							}
							else
							{
								$start = "<center><input type='checkbox' name='start_".$rd['id']."' value='1'></center>";
							}
							
							//---------------------------
							
							if ($rd['reply_perms'] == '*')
							{
								$reply = $global;
							}
							else if ( preg_match( "/(^|,)".$gid."(,|$)/", $rd['reply_perms'] ) )
							{
								$reply = "<center><input type='checkbox' name='reply_".$rd['id']."' value='1' checked></center>";
							}
							else
							{
								$reply = "<center><input type='checkbox' name='reply_".$rd['id']."' value='1'></center>";
							}
							
							//---------------------------
							
							if ($rd['upload_perms'] == '*')
							{
								$upload = $global;
							}
							else if ( preg_match( "/(^|,)".$gid."(,|$)/", $rd['upload_perms'] ) )
							{
								$upload = "<center><input type='checkbox' name='upload_".$rd['id']."' value='1' checked></center>";
							}
							else
							{
								$upload = "<center><input type='checkbox' name='upload_".$rd['id']."' value='1'></center>";
							}
							
							//---------------------------
					
							$ADMIN->html .= $SKIN->add_td_row( array(
															   "<b>".$rd['name']."</b><br>".$rd['description'],
															   "<center>".$rd['posts']."</center>",
															   "<center>".$rd['topics']."</center>",
															   $start,
															   $reply,
															   $read,
															   $upload
													 ) , 'subforum'     );
						}
					}					 
				}
			}
		}
		
		$ADMIN->html .= $SKIN->end_form("更新论坛栏目权限设置");
		
		$ADMIN->html .= $SKIN->end_table();
		
		$ADMIN->output();
		
	}
	
	function do_forum_perms()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		//---------------------------
		// Check for legal ID
		//---------------------------
		
		if ($IN['id'] == "")
		{
			$ADMIN->error("无法找到用户团队ID，请检查后重试！");
		}
		
		$gid = $IN['id'];
		
		//---------------------------
		
		$DB->query("SELECT g_id, g_title FROM ibf_groups WHERE g_id='".$IN['id']."'");
		
		if ( ! $gr = $DB->fetch_row() )
		{
			$ADMIN->error("不是有效的用户团队ID");
		}
		
		//---------------------------
		// Pull the forum data..
		//---------------------------
		
		$forum_q = $DB->query("SELECT id, read_perms, start_perms, reply_perms, upload_perms FROM ibf_forums ORDER BY position ASC");
		
		while ( $row = $DB->fetch_row( $forum_q ) )
		{
		
			$read  = "";
			$reply = "";
			$start = "";
			$upload = "";
			//---------------------------
			// Is this global?
			//---------------------------
			
			if ($row['read_perms'] == '*')
			{
				$read = '*';
				
			}
			else
			{
				//---------------------------
				// Split the set IDs
				//---------------------------
				
				$read_ids = explode( ",", $row['read_perms'] );
				
				if ( is_array($read_ids) )
				{
				   foreach ($read_ids as $i)
				   {
					   //---------------------------
					   // If it's the current ID, skip
					   //---------------------------
					   
					   if ($gid == $i)
					   {
						   continue;
					   }
					   else
					   {
						   $read .= $i.",";
					   }
				   }
				}
				//---------------------------
				// Was the box checked?
				//---------------------------
				
				if ($IN[ 'read_'.$row['id'] ] == 1)
				{
					// Add our group ID...
					
					$read .= $gid.",";
				}
				
				// Tidy..
				
				$read = preg_replace( "/,$/", "", $read );
				$read = preg_replace( "/^,/", "", $read );
				
			}
			
			//---------------------------
			// Reply topics..
			//---------------------------
				
			if ($row['reply_perms'] == '*')
			{
				$reply = '*';
			}
			else
			{
				$reply_ids = explode( ",", $row['reply_perms'] );
				
				if ( is_array($reply_ids) )
				{
				
					foreach ($reply_ids as $i)
					{
						if ($gid == $i)
						{
							continue;
						}
						else
						{
							$reply .= $i.",";
						}
					}
				
				}
				
				if ($IN[ 'reply_'.$row['id'] ] == 1)
				{
					$reply .= $gid.",";
				}
				
				$reply = preg_replace( "/,$/", "", $reply );
				$reply = preg_replace( "/^,/", "", $reply );
			}
			
			//---------------------------
			// Start topics..
			//---------------------------
				
			if ($row['start_perms'] == '*')
			{
				$start = '*';
			}
			else
			{
				$start_ids = explode( ",", $row['start_perms'] );
				
				if ( is_array($start_ids) )
				{
				
					foreach ($start_ids as $i)
					{
						if ($gid == $i)
						{
							continue;
						}
						else
						{
							$start .= $i.",";
						}
					}
				
				}
				
				if ($IN[ 'start_'.$row['id'] ] == 1)
				{
					$start .= $gid.",";
				}
				
				$start = preg_replace( "/,$/", "", $start );
				$start = preg_replace( "/^,/", "", $start );
			}
			
			//---------------------------
			// Upload topics..
			//---------------------------
				
			if ($row['upload_perms'] == '*')
			{
				$upload = '*';
			}
			else
			{
				$upload_ids = explode( ",", $row['upload_perms'] );
				
				if ( is_array($upload_ids) )
				{
				
					foreach ($upload_ids as $i)
					{
						if ($gid == $i)
						{
							continue;
						}
						else
						{
							$upload .= $i.",";
						}
					}
				
				}
				
				if ($IN[ 'upload_'.$row['id'] ] == 1)
				{
					$upload .= $gid.",";
				}
				
				$upload = preg_replace( "/,$/", "", $upload );
				$upload = preg_replace( "/^,/", "", $upload );
			}
			
			//---------------------------
			// Update the DB...
			//---------------------------
			
			if (! $new_q = $DB->query("UPDATE ibf_forums SET read_perms='$read', reply_perms='$reply', start_perms='$start', upload_perms='$upload' WHERE id='".$row['id']."'") )
			{
				die ("更新数据失败，论坛栏目：".$row['id']);
			}
			
		}
		
		$ADMIN->save_log("论坛栏目访问权限设置：'{$gr['g_title']}'");
		
		$ADMIN->done_screen("论坛栏目访问权限已经更新", "用户团队管理", "act=group" );
		
	}
	
	//+---------------------------------------------------------------------------------
	//
	// Delete a group
	//
	//+---------------------------------------------------------------------------------
	
	function delete_form()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		if ($IN['id'] == "")
		{
			$ADMIN->error("无法找到用户团队ID，请检查后重试！");
		}
		
		if ($IN['id'] < 5)
		{
			$ADMIN->error("无法移动用户团队，你可以对用户团队重新命名或编辑用户团队参数设置。");
		}
		
		$ADMIN->page_title = "删除用户团队";
		
		$ADMIN->page_detail = "在删除用户团队前，请仔细检查确认是否选择了正确的用户团队。";
		
		
		//+-------------------------------
		
		$DB->query("SELECT COUNT(id) as users FROM ibf_members WHERE mgroup='".$IN['id']."'");
		$black_adder = $DB->fetch_row();
		
		if ($black_adder['users'] < 1)
		{
			$black_adder['users'] = 0;
		}
		
		$DB->query("SELECT g_title FROM ibf_groups WHERE g_id='".$IN['id']."'");
		$group = $DB->fetch_row();
		
		//+-------------------------------
		
		$DB->query("SELECT g_id, g_title FROM ibf_groups WHERE g_id <> '".$IN['id']."'");
		
		$mem_groups = array();
		
		while ( $r = $DB->fetch_row() )
		{
			$mem_groups[] = array( $r['g_id'], $r['g_title'] );
		}
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_form( array( 1 => array( 'code'  , 'dodelete'  ),
												  2 => array( 'act'   , 'group'     ),
												  3 => array( 'id'    , $IN['id']   ),
												  4 => array( 'name'  , $group['g_title'] ),
									     )      );
									     
		
		
		//+-------------------------------
		
		$SKIN->td_header[] = array( "&nbsp;"  , "40%" );
		$SKIN->td_header[] = array( "&nbsp;"  , "60%" );
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_table( "删除确认：".$group['g_title'] );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>当前用户团队的用户数量：</b>" ,
												  "<b>".$black_adder['users']."</b>",
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>移动这个用户团队中的所有用户到 ...</b>" ,
												  $SKIN->form_dropdown("to_id", $mem_groups )
									     )      );
		
		$ADMIN->html .= $SKIN->end_form("删除用户团队");
										 
		$ADMIN->html .= $SKIN->end_table();
		
		$ADMIN->output();
			
			
	}
	
	function do_delete()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		if ($IN['id'] == "")
		{
			$ADMIN->error("无法找到用户团队ID，请检查后重试！");
		}
		
		if ($IN['to_id'] == "")
		{
			$ADMIN->error("无法找到需要移动的用户团队ID，请检查后再试！");
		}
		
		// Check to make sure that the relevant groups exist.
		
		$DB->query("SELECT g_id FROM ibf_groups WHERE g_id IN(".$IN['id'].",".$IN['to_id'].")");
		
		if ( $DB->get_num_rows() != 2 )
		{
			$ADMIN->error("无法找到需要删除的用户团队ID，请检查后再试！");
		}
		
		$DB->query("UPDATE ibf_members SET mgroup='".$IN['to_id']."' WHERE mgroup='".$IN['id']."'");
		
		$DB->query("DELETE FROM ibf_groups WHERE g_id='".$IN['id']."'");
		
		// Look for promotions in case we have members to be promoted to this group...
		
		$prq = $DB->query("SELECT g_id FROM ibf_groups WHERE g_promotion LIKE '{$IN['id']}&%'");
		
		while ( $row = $DB->fetch_row($prq) )
		{
			$nq = $DB->query("UPDATE ibf_groups SET g_promotion='-1&-1' WHERE g_id='".$row['g_id']."'");
		}
		
		// Remove from moderators table
		
		$DB->query("DELETE FROM ibf_moderators WHERE is_group=1 AND group_id=".$IN['id']);
		
		$ADMIN->save_log("删除用户团队：'{$IN['name']}' removed");
		
		$ADMIN->done_screen("用户团队已经删除", "用户团队管理", "act=group" );
		
	}
	
	
	//+---------------------------------------------------------------------------------
	//
	// Save changes to DB
	//
	//+---------------------------------------------------------------------------------
	
	function save_group($type='edit')
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP, $HTTP_POST_VARS;
		
		if ($IN['g_title'] == "")
		{
			$ADMIN->error("你必须输入用户团队名称。");
		}
		
		if ($type == 'edit')
		{
			if ($IN['id'] == "")
			{
				$ADMIN->error("无法找到用户团队ID，请检查后再试！");
			}
			
			if ($IN['id'] == $INFO['admin_group'] and $IN['g_access_cp'] != 1)
			{
				$ADMIN->error("你不能删除论坛管理员团队，否则你将无法登录论坛管理中心。");
			}
		}
		
		// Build up the hashy washy for the database ..er.. wase.
		
		$prefix = preg_replace( "/&#39;/", "'" , stripslashes($HTTP_POST_VARS['prefix']) );
		$prefix = preg_replace( "/&lt;/" , "<" , $prefix          );
		$suffix = preg_replace( "/&#39;/", "'" , stripslashes($HTTP_POST_VARS['suffix']) );
		$suffix = preg_replace( "/&lt;/" , "<" , $suffix          );
		
		$promotion_a = '-1'; //id
		$promotion_b = '-1'; // posts
		
		if ($IN['g_promotion_id'] > 0)
		{
			$promotion_a = $IN['g_promotion_id'];
			$promotion_b = $IN['g_promotion_posts'];
		}
		
		//if ($IN['g_max_messages'] == 0)
		//{
			//$IN['g_max_messages'] = -1;
		//}
		
		$db_string = array(
							 'g_view_board'         => $IN['g_view_board'],
							 'g_mem_info'           => $IN['g_mem_info'],
							 'g_other_topics'       => $IN['g_other_topics'],
							 'g_use_search'         => $IN['g_use_search'],
							 'g_email_friend'       => $IN['g_email_friend'],
							 'g_invite_friend'      => $IN['g_invite_friend'],
							 'g_edit_profile'       => $IN['g_edit_profile'],
							 'g_post_new_topics'    => $IN['g_post_new_topics'],
							 'g_reply_own_topics'   => $IN['g_reply_own_topics'],
							 'g_reply_other_topics' => $IN['g_reply_other_topics'],
							 'g_edit_posts'         => $IN['g_edit_posts'],
							 'g_edit_cutoff'        => $IN['g_edit_cutoff'],
							 'g_delete_own_posts'   => $IN['g_delete_own_posts'],
							 'g_open_close_posts'   => $IN['g_open_close_posts'],
							 'g_delete_own_topics'  => $IN['g_delete_own_topics'],
							 'g_post_polls'         => $IN['g_post_polls'],
							 'g_vote_polls'         => $IN['g_vote_polls'],
							 'g_use_pm'             => $IN['g_use_pm'],
							 'g_is_supmod'          => $IN['g_is_supmod'],
							 'g_access_cp'          => $IN['g_access_cp'],
							 'g_title'              => trim($IN['g_title']),
							 'g_can_remove'         => $IN['g_can_remove'],
							 'g_append_edit'        => $IN['g_append_edit'],
							 'g_access_offline'     => $IN['g_access_offline'],
							 'g_avoid_q'            => $IN['g_avoid_q'],
							 'g_avoid_flood'        => $IN['g_avoid_flood'],
							 'g_icon'               => trim($IN['g_icon']),
							 'g_attach_max'         => $IN['g_attach_max'],
							 'g_avatar_upload'      => $IN['g_avatar_upload'],
							 'g_calendar_post'      => $IN['g_calendar_post'],
							 'g_max_messages'       => $IN['g_max_messages'],
							 'g_max_mass_pm'        => $IN['g_max_mass_pm'],
							 'g_search_flood'       => $IN['g_search_flood'],
							 'prefix'               => $prefix,
							 'suffix'               => $suffix,
							 'g_promotion'          => $promotion_a.'&'.$promotion_b,
							 'g_hide_from_list'     => $IN['g_hide_from_list'],
							 'g_post_closed'        => $IN['g_post_closed'],
							 
						  );
						  
		if ($type == 'edit')
		{
			$rstring = $DB->compile_db_update_string( $db_string );
			
			$DB->query("UPDATE ibf_groups SET $rstring WHERE g_id='".$IN['id']."'");
			
			// Update the title of the group held in the mod table incase it changed.
			
			$DB->query("UPDATE ibf_moderators SET group_name='".trim($IN['g_title'])."' WHERE group_id='".$IN['id']."'");
			
			$ADMIN->save_log("编辑用户团队：'{$IN['g_title']}'");
			
			$ADMIN->done_screen("用户团队编辑完成", "用户团队管理", "act=group" );
			
		}
		else
		{
			$rstring = $DB->compile_db_insert_string( $db_string );
			
			$DB->query("INSERT INTO ibf_groups (" .$rstring['FIELD_NAMES']. ") VALUES (". $rstring['FIELD_VALUES'] .")");
			
			//---------------------------------------
			//
			// Inherit forum permissions
			//
			//---------------------------------------
			
			if ($IN['inherit'] == 1)
			{
				// Get last insert ID
				
				$new_id = $DB->get_insert_id();
				$old_id = intval($IN['id']);
				
				if ( ($new_id > 0) and ($old_id > 0) )
				{
					$get = $DB->query("SELECT id, read_perms, reply_perms, start_perms, upload_perms FROM ibf_forums");
					
					while( $f = $DB->fetch_row($get) )
					{
						$d_str = "";
						$d_arr = array();
						
						foreach( array( 'read_perms', 'reply_perms', 'start_perms', 'upload_perms' ) as $perm_bit )
						{
							if ($f[ $perm_bit ] != '*')
							{
								if ( preg_match( "/(^|,)".$old_id."(,|$)/", $f[ $perm_bit ]) )
								{
									$d_arr[ $perm_bit ] = $this->clean_perms( $f[ $perm_bit ] ) . ",".$new_id;
								}
							}
						}
						
						// Do we have anything to save?
							
						if ( count($d_arr) > 0 )
						{
							$d_str = $DB->compile_db_update_string( $d_arr );
							
							// Sure?..
							
							if ( strlen($d_str) > 5)
							{
								$save = $DB->query("UPDATE ibf_forums SET $d_str WHERE id={$f['id']}");
							}
						}
					}
				}
			}
			
			$ADMIN->save_log("添加用户团队：'{$IN['g_title']}'");
			
			$ADMIN->done_screen("用户团队已经添加", "用户团队管理", "act=group" );
		}
	}
	
	function clean_perms($str)
	{
		$str = preg_replace( "/,$/", "", $str );
		$str = str_replace(  ",,", ",", $str );
		
		return $str;
	}
	
	//+---------------------------------------------------------------------------------
	//
	// Add / edit group
	//
	//+---------------------------------------------------------------------------------
	
	function group_form($type='edit')
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		$all_groups = array( 0 => array ('none', '暂不提升') );
		
		if ($type == 'edit')
		{
			if ($IN['id'] == "")
			{
				$ADMIN->error("无法从数据库中找到相关的用户团队ID，请检查后再试！");
			}
			
			$form_code = 'doedit';
			$button    = '完成编辑';
				
		}
		else
		{
			$form_code = 'doadd';
			$button    = '添加团队';
		}
		
		if ($IN['id'] != "")
		{
			$DB->query("SELECT * FROM ibf_groups WHERE g_id='".$IN['id']."'");
			$group = $DB->fetch_row();
			
			$query = "SELECT g_id, g_title FROM ibf_groups WHERE g_id <> {$IN['id']} ORDER BY g_title";
		}
		else
		{
			$group = array();
			
			$query = "SELECT g_id, g_title FROM ibf_groups ORDER BY g_title";
		}
		
		//-------------------------------------------
		// sort out the promotion stuff
		//-------------------------------------------
		
		list($group['g_promotion_id'], $group['g_promotion_posts']) = explode( '&', $group['g_promotion'] );
		
		if ($group['g_promotion_posts'] < 1)
		{
			$group['g_promotion_posts'] = '';
		}
		
		$DB->query($query);
		
		while ( $r = $DB->fetch_row() )
		{
			$all_groups[] = array( $r['g_id'], $r['g_title'] );
		}
		
		//-------------------------------------------
		
		if ($type == 'edit')
		{
			$ADMIN->page_title = "编辑用户团队：".$group['g_title'];
		}
		else
		{
			$ADMIN->page_title = '添加新用户团队';
			$group['g_title'] = '新用户团队';
		}
		
		$guest_legend = "";
		
		if ($group['g_id'] == $INFO['guest_group'])
		{
			$guest_legend = "</b><br>论坛游客不适用";
		}
		
		$ADMIN->page_detail = "在提交表单数据前，请双击相关信息选项。";
		
		
		//+-------------------------------
		
		$ADMIN->html .= "<script language='javascript'>
						 <!--
						  function checkform() {
						  
						  	isAdmin = document.forms[0].g_access_cp;
						  	isMod   = document.forms[0].g_is_supmod;
						  	
						  	msg = '';
						  	
						  	if (isAdmin[0].checked == true)
						  	{
						  		msg += '在此用户团队里的所有用户都可以登录论坛管理中心！\\n\\n';
						  	}
						  	
						  	if (isMod[0].checked == true)
						  	{
						  		msg += '在此用户团队里的所有用户都是论坛总版主！\\n\\n';
						  	}
						  	
						  	if (msg != '')
						  	{
						  		msg = '安全检测\\n--------------\\nn用户团队名称：' + document.forms[0].g_title.value + '\\n--------------\\n\\n' + msg + '是否设置正确？';
						  		
						  		formCheck = confirm(msg);
						  		
						  		if (formCheck == true)
						  		{
						  			return true;
						  		}
						  		else
						  		{
						  			return false;
						  		}
						  	}
						  }
						 //-->
						 </script>\n";
		
		$ADMIN->html .= $SKIN->start_form( array( 1 => array( 'code'  , $form_code  ),
												  2 => array( 'act'   , 'group'     ),
												  3 => array( 'id'    , $IN['id']   ),
									     ) , 'adform', "onSubmit='return checkform()'" );
									     
		
		
		//+-------------------------------
		
		$SKIN->td_header[] = array( "&nbsp;"  , "40%" );
		$SKIN->td_header[] = array( "&nbsp;"  , "60%" );
		
		//+-------------------------------
		
		$prefix = preg_replace( "/'/", "&#39;", $group['prefix'] );
		$prefix = preg_replace( "/</", "&lt;" , $prefix          );
		$suffix = preg_replace( "/'/", "&#39;", $group['suffix'] );
		$suffix = preg_replace( "/</", "&lt;" , $suffix          );
		
		$ADMIN->html .= $SKIN->start_table( "用户团队参数设置" );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>用户团队名称：</b>" ,
												  $SKIN->form_input("g_title", $group['g_title'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>用户团队图标：</b><br>(可以省略)" ,
												  $SKIN->form_input("g_icon", $group['g_icon'] )
									     )      );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>最大文件上传尺寸：(KB)</b>".$SKIN->js_help_link('mg_upload')."<br>(不填表示不允许上传)" ,
												  $SKIN->form_input("g_attach_max", $group['g_attach_max'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>用户在线显示格式：[前缀]</b><br>(可以不填，例如：&lt;span style='color:red'&gt;)" ,
												  $SKIN->form_input("prefix", $prefix )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>用户在线显示格式：[后缀]</b><br>(可以不填，例如：&lt;/span&gt;)" ,
												  $SKIN->form_input("suffix", $suffix )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否在用户列表中隐藏这个用户团队？</b>" ,
												  $SKIN->form_yes_no("g_hide_from_list", $group['g_hide_from_list'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->end_table();
		
		//+-------------------------------
		
		$SKIN->td_header[] = array( "&nbsp;"  , "40%" );
		$SKIN->td_header[] = array( "&nbsp;"  , "60%" );
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_table( "用户团对权限设置" );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许访问论坛？</b>" ,
												  $SKIN->form_yes_no("g_view_board", $group['g_view_board'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许访问关闭的论坛？</b>" ,
												  $SKIN->form_yes_no("g_access_offline", $group['g_access_offline'] )
									     )      );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许查看用户信息和用户列表？</b>" ,
												  $SKIN->form_yes_no("g_mem_info", $group['g_mem_info'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许查看其他用户发表的主题？</b>" ,
												  $SKIN->form_yes_no("g_other_topics", $group['g_other_topics'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许使用论坛搜索功能？</b>" ,
												  $SKIN->form_yes_no("g_use_search", $group['g_use_search'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>使用搜索功能的执行时间控制：（秒）</b><br>多少时间后，搜索自动停止，输入0或留空表示不使用搜索控制功能。" ,
												  $SKIN->form_input("g_search_flood", $group['g_search_flood'] )
									     )      );							     
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许在论坛发送电子邮件给其他用户?$guest_legend</b>" ,
												  $SKIN->form_yes_no("g_email_friend", $group['g_email_friend'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许编辑自己的用户信息内容?$guest_legend" ,
												  $SKIN->form_yes_no("g_edit_profile", $group['g_edit_profile'] )
									     )      );							     
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许使用私人短信功能?$guest_legend" ,
												  $SKIN->form_yes_no("g_use_pm", $group['g_use_pm'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>批量发送私人短信的最大用户数量?$guest_legend<br>(输入0或留空表示禁止批量发送短信功能。)" ,
												  $SKIN->form_input("g_max_mass_pm", $group['g_max_mass_pm'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>私人短信的最大保存数量?$guest_legend" ,
												  $SKIN->form_input("g_max_messages", $group['g_max_messages'] )
									     )      );
									     						     							     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许用户上传头像文件?$guest_legend" ,
												  $SKIN->form_yes_no("g_avatar_upload", $group['g_avatar_upload'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->end_table();
		
		//+-------------------------------
		
		$SKIN->td_header[] = array( "&nbsp;"  , "40%" );
		$SKIN->td_header[] = array( "&nbsp;"  , "60%" );
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_table( "用户发表帖子权限设置" );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许发表主题？</b>" ,
												  $SKIN->form_yes_no("g_post_new_topics", $group['g_post_new_topics'] )
									     )      );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许回复自己发表的主题？</b>" ,
												  $SKIN->form_yes_no("g_reply_own_topics", $group['g_reply_own_topics'] )
									     )      );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许回复其他用户发表的主题？</b>" ,
												  $SKIN->form_yes_no("g_reply_other_topics", $group['g_reply_other_topics'] )
									     )      );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许编辑自己发表的主题和回复?$guest_legend" ,
												  $SKIN->form_yes_no("g_edit_posts", $group['g_edit_posts'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>编辑主题和回复时的时间限制(分钟)?$guest_legend<br>超过设定的时间后，用户不能编辑主题和回复，输入0或留空表示不进行控制。" ,
												  $SKIN->form_input("g_edit_cutoff", $group['g_edit_cutoff'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许用户删除 '帖子编辑作者' 标签?$guest_legend</b>" ,
												  $SKIN->form_yes_no("g_append_edit", $group['g_append_edit'] )
									     )      );							     
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许删除自己发表的回复?$guest_legend" ,
												  $SKIN->form_yes_no("g_delete_own_posts", $group['g_delete_own_posts'] )
									     )      );
									     						     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许 打开/关闭 自己发表的主题?$guest_legend" ,
												  $SKIN->form_yes_no("g_open_close_posts", $group['g_open_close_posts'] )
									     )      );							     
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许删除自己发表的主题?$guest_legend" ,
												  $SKIN->form_yes_no("g_delete_own_topics", $group['g_delete_own_topics'] )
									     )      );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许发表投票主题?$guest_legend</b>" ,
												  $SKIN->form_yes_no("g_post_polls", $group['g_post_polls'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许在投票主题中参与投票?$guest_legend" ,
												  $SKIN->form_yes_no("g_vote_polls", $group['g_vote_polls'] )
									     )      );							     
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否可以取消灌水控制功能？</b>" ,
												  $SKIN->form_yes_no("g_avoid_flood", $group['g_avoid_flood'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否可以取消等待版主审批功能？</b>" ,
												  $SKIN->form_yes_no("g_avoid_q", $group['g_avoid_q'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许在事件日历中添加事件内容?$guest_legend</b>" ,
												  $SKIN->form_yes_no("g_calendar_post", $group['g_calendar_post'] )
									     )      );
									     					     							     
		$ADMIN->html .= $SKIN->end_table();
		
		//+-------------------------------
		
		$SKIN->td_header[] = array( "&nbsp;"  , "40%" );
		$SKIN->td_header[] = array( "&nbsp;"  , "60%" );
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_table( "论坛版主权限设置" );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否作为论坛总版主(可以在所有论坛栏目进行管理)?$guest_legend" ,
												  $SKIN->form_yes_no("g_is_supmod", $group['g_is_supmod'] )
									     )      );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许登录论坛管理中心?$guest_legend" ,
												  $SKIN->form_yes_no("g_access_cp", $group['g_access_cp'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许在 '关闭的主题' 中发表回复？" ,
												  $SKIN->form_yes_no("g_post_closed", $group['g_post_closed'] )
									     )      );
									     
		$ADMIN->html .= $SKIN->end_table();
		
		//+-------------------------------
		
		$SKIN->td_header[] = array( "&nbsp;"  , "40%" );
		$SKIN->td_header[] = array( "&nbsp;"  , "60%" );
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_table( "用户团队提升设置" );
		
		if ($group['g_id'] == $INFO['admin_group'])
		{
			$ADMIN->html .= $SKIN->add_td_row( array( "<b>请选择 '暂不提升' 禁止此功能</b><br>".$SKIN->js_help_link('mg_promote') ,
													  "注意：用户团队提升功能不适用于管理员团队，因为管理员团队已经是论坛级别最高的用户团队。"
											 )      );
		}
		else
		{
			$ADMIN->html .= $SKIN->add_td_row( array( "<b>请选择 '暂不提升' 禁止此功能</b>$guest_legend<br>".$SKIN->js_help_link('mg_promote') ,
													  '当用户在论坛发表的帖子数量超过： '.$SKIN->form_simple_input('g_promotion_posts', $group['g_promotion_posts'] )
													 .'<br>提升该用户到下面的用户团队： '.$SKIN->form_dropdown("g_promotion_id", $all_groups, $group['g_promotion_id'] ).''
											 )      );
		}
		
		
		if ($type != 'edit')
		{
			$ADMIN->html .= $SKIN->end_table();
			
			//+-------------------------------
		
			$SKIN->td_header[] = array( "&nbsp;"  , "40%" );
			$SKIN->td_header[] = array( "&nbsp;"  , "60%" );
			
			//+-------------------------------
			
			$ADMIN->html .= $SKIN->start_table( "论坛权限管理" );
			
			$ADMIN->html .= $SKIN->add_td_row( array( "<b>是否允许新用户团队继承论坛权限设置？</b><br>如果选择是，那么该用户团队将拥有团队成员相同的论坛权限设置。<br>如果选择否，那么将重新进行论坛权限设置操作。" ,
												 	  $SKIN->form_yes_no("inherit", 1 )
									     	 )      );
									     
		}
									     
		$ADMIN->html .= $SKIN->end_form($button);
										 
		$ADMIN->html .= $SKIN->end_table();
		
		$ADMIN->output();
			
			
	}

	//+---------------------------------------------------------------------------------
	//
	// Show "Management Screen
	//
	//+---------------------------------------------------------------------------------
	
	function main_screen()
	{
		global $IN, $INFO, $DB, $SKIN, $ADMIN, $std, $MEMBER, $GROUP;
		
		$ADMIN->page_title = "用户团队管理";
		
		$ADMIN->page_detail = "用户团队是一个快速管理论坛用户的强大功能，在你安装论坛后，系统将会默认为你建立4个用户团队(审核用户、论坛游客，注册用户、管理员)，你可以根据你的需要添加更多的用户团队。例如：你可以添加一个 '版主' 用户团队，这样你就可以快速、轻松的管理所有论坛版主。<br>论坛栏目权限允许你对用户团队进行论坛栏目权限管理。例如：设置用户团队是否允许 查看/回复/发表 论坛主题等权限。";
		
		$g_array = array();
		
		$SKIN->td_header[] = array( "用户团队名称"    , "20%" );
		$SKIN->td_header[] = array( "管理面板"            , "10%" );
		$SKIN->td_header[] = array( "版主面板"           , "10%" );
		$SKIN->td_header[] = array( "用户数量"        , "10%" );
		$SKIN->td_header[] = array( "编辑团队"     , "20%" );
		$SKIN->td_header[] = array( "编辑权限"   , "20%" );
		$SKIN->td_header[] = array( "删除团队"         , "10%" );
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_table( "用户团队管理" );
		
		$DB->query("SELECT ibf_groups.g_id, ibf_groups.g_access_cp, ibf_groups.g_is_supmod, ibf_groups.g_title,ibf_groups.prefix, ibf_groups.suffix, COUNT(ibf_members.id) as count FROM ibf_groups "
		          ."LEFT JOIN ibf_members ON (ibf_members.mgroup = ibf_groups.g_id) "
		          ."GROUP BY ibf_groups.g_id ORDER BY ibf_groups.g_title");
		
		while ( $r = $DB->fetch_row() )
		{
		
			$del  = "";
			$mod  = '&nbsp;';
			$adm  = '&nbsp;';
			
			if ($r['g_id'] > 4)
			{
				$del = "<center><a href='{$ADMIN->base_url}&act=group&code=delete&id=".$r['g_id']."'>删除</a></center>";
			}
			//-----------------------------------
			if ($r['g_access_cp'] == 1)
			{
				$adm = '<center><span style="color:red">是</span></center>';
			}
			//-----------------------------------
			if ($r['g_is_supmod'] == 1)
			{
				$mod = '<center><span style="color:red">是</span></center>';
			}
			
			if ($r['g_id'] != 1 and $r['g_id'] != 2)
			{
				$total_linkage = "<a href='{$INFO['board_url']}/index.{$INFO['php_ext']}?act=Members&max_results=30&filter={$r['g_id']}&sort_order=asc&sort_key=name&st=0' target='_blank' title='用户列表'>".$r['prefix'].$r['g_title'].$r['suffix']."</a>";
			}
			else
			{
				$total_linkage = $r['prefix'].$r['g_title'].$r['suffix'];
			}
			
			$ADMIN->html .= $SKIN->add_td_row( array( "<b>$total_linkage</b>" ,
												      $adm,
												      $mod,
												      "<center>".$r['count']."</center>",
												      "<center><a href='{$ADMIN->base_url}&act=group&code=edit&id=".$r['g_id']."'>编辑团队</a></center>",
												      "<center><a href='{$ADMIN->base_url}&act=group&code=fedit&id=".$r['g_id']."'>编辑权限</a></center>",
												      $del
												      
									     )      );
									     
			$g_array[] = array( $r['g_id'], $r['g_title'] );
		}
		
		$ADMIN->html .= $SKIN->add_td_basic("&nbsp;", "center", "title");

		$ADMIN->html .= $SKIN->end_table();
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_form( array( 1 => array( 'code'  , 'add' ),
												  2 => array( 'act'   , 'group'     ),
									     )      );
									     
		//+-------------------------------
		
		$SKIN->td_header[] = array( "&nbsp;"  , "40%" );
		$SKIN->td_header[] = array( "&nbsp;"  , "60%" );
		
		//+-------------------------------
		
		$ADMIN->html .= $SKIN->start_table( "添加新用户团队" );
		
		$ADMIN->html .= $SKIN->add_td_row( array( "<b>新用户团队基于 ...</b>" ,
												  $SKIN->form_dropdown("id", $g_array, 3 )
									     )      );
									     
		$ADMIN->html .= $SKIN->end_form("设置新用户团队");
										 
		$ADMIN->html .= $SKIN->end_table();
		
		$ADMIN->output();
		
		
	}
	
		
}


?>