<?php
// $Revision: 1.10.4.1.2.16 $
// ------------------------------------------------------------------------- //
//  XooNIps - Neuroinformatics Base Platform System                          //
//  Copyright (C) 2005-2008 RIKEN, Japan All rights reserved.                //
//  http://xoonips.sourceforge.jp/                                           //
// ------------------------------------------------------------------------- //
//  This program is free software; you can redistribute it and/or modify     //
//  it under the terms of the GNU General Public License as published by     //
//  the Free Software Foundation; either version 2 of the License, or        //
//  (at your option) any later version.                                      //
//                                                                           //
//  You may not change or alter any portion of this comment or credits       //
//  of supporting developers from this source code or any supporting         //
//  source code which is considered copyrighted (c) material of the          //
//  original comment or credit authors.                                      //
//                                                                           //
//  This program is distributed in the hope that it will be useful,          //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
//  GNU General Public License for more details.                             //
//                                                                           //
//  You should have received a copy of the GNU General Public License        //
//  along with this program; if not, write to the Free Software              //
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
// ------------------------------------------------------------------------- //

$xoopsOption['pagetype'] = 'user';
include 'include/common.inc.php';
include_once 'include/lib.php';
include_once 'include/AL.php';

$xnpsid = $_SESSION['XNPSID'];

xoonips_deny_guest_access();

$uid = $xoopsUser->getVar('uid');

//User(Not Moderater) can't control(except XOOPS administrator).
if( !$xoopsUser->isAdmin( $xoopsModule->getVar( 'mid' ) )
	&& !xnp_is_moderator( $xnpsid, $uid ) ) {
	redirect_header( XOOPS_URL.'/', 3, _MD_XOONIPS_MODERATOR_SHULD_BE_MODERATOR );
	exit(  );
}


xnpEncodeMacSafariPost();
xnpEncodeMacSafariGet();

$request_vars = array(
  'item_number_limit' => array( 'i', 0 ), 
  'index_number_limit' => array( 'i', 0 ),
  'item_storage_limit' => array( 'i', 0 ),
  'gname' => array( 's', '' ),
  'gdesc' => array( 's', '' ),
  'gid' => array( 'i', 0 ), 
  'op' => array( 's', '' ),
);
$formdata =& xoonips_getutility( 'formdata' );
foreach ( $request_vars as $key => $meta ) {
  list( $type, $default ) = $meta;
  $$key = $formdata->getValue( 'both', $key, $type, false, $default );
}
$gadmins=$formdata->getValueArray('post', 'gadmins', 'i', false);

$item_number_limit = max( 0, $item_number_limit );
$index_number_limit = max( 0, $index_number_limit );
$item_storage_limit = max( 0, $item_storage_limit );

$textutil =& xoonips_getutility( 'text' );

/** output error message and redirect if $gid is bad or group root index is locked.
 */
function xoonips_show_error_if_group_locked( $gid, $message_base )
{
    //is group index locked?
    $groups_handler =& xoonips_getormhandler( 'xoonips', 'groups' );
    $group = $groups_handler->get( $gid );
    if ( $group === false ){
        redirect_header( 'editgroups.php', 3, 
            _MD_XOONIPS_MODERATOR_ERROR_SELECT_GROUP );
        exit();
    }
    $item_lock_handler =& xoonips_getormhandler( 'xoonips', 'item_lock' );
    if ( $item_lock_handler->isLocked( $group->get('group_index_id') ) ){
        redirect_header(XOOPS_URL.'/modules/xoonips/editgroups.php',
            5, sprintf( $message_base, 
                xoonips_get_lock_type_string(
                    $item_lock_handler->getLockType( $group->get('group_index_id') ))));
        exit();
    }
}


switch ( $op ) {
case 'register':
	//make a group and register administorators
	$gid = 0;
	
	if ( in_array( strtolower($gname), array( 'public', 'private', 'root' ) ) ){
		$xoopsTpl->assign( 'gname', $textutil->html_special_chars( $gname ) );
		$xoopsTpl->assign( 'gdesc', $textutil->html_specail_chars( $gdesc ) );
		$xoopsTpl->assign( 'item_number_limit', $item_number_limit );
		$xoopsTpl->assign( 'index_number_limit', $index_number_limit );
		$xoopsTpl->assign( 'item_storage_limit', $item_storage_limit );
		$xoopsTpl->assign( 'gname_forbidden', true );
		$gadmin_uids = $gadmins;
		break;
	}
	
	$result = xnp_insert_group( $xnpsid,
								array( 'gname' => $gname,
									   'gdesc' => $gdesc,
									   'item_number_limit' => $item_number_limit,
									   'index_number_limit' => $index_number_limit,
									   'item_storage_limit' => $item_storage_limit * 1000 * 1000 ),
								$gid );
	if( $result != RES_OK ) {
		if( $result == RES_GROUPNAME_ALREADY_EXISTS ){
			$xoopsTpl->assign( 'gname', $textutil->html_special_chars( $gname ) );
			$xoopsTpl->assign( 'gdesc', $textutil->html_special_chars( $gdesc ) );
			$xoopsTpl->assign( 'item_number_limit', $item_number_limit );
			$xoopsTpl->assign( 'index_number_limit', $index_number_limit );
			$xoopsTpl->assign( 'item_storage_limit', $item_storage_limit );
			$xoopsTpl->assign( 'gname_exists', true );
			$gadmin_uids = $gadmins;
			break;
		}else{
			redirect_header( 'editgroups.php', 3, _MD_XOONIPS_MODERATOR_ERROR_INSERT_GROUP );
			exit( );
		}
	}
	//set group's administrators
	//add members as group's administrators
	foreach( $gadmins as $i ) {
		xnp_delete_member( $xnpsid, $gid, $i );
		xnp_insert_member( $xnpsid, $gid, $i, 1 );
	}
	$op = '';
	
	// Record events(insert group)
        $eventlog_handler =& xoonips_getormhandler( 'xoonips', 'event_log' );
        $eventlog_handler->recordInsertGroupEvent( $gid );
	break;
case 'edit':
    xoonips_show_error_if_group_locked( $gid, _MD_XOONIPS_ERROR_CANNOT_EDIT_LOCKED_GROUP );
	$group = array(  );
	$result = xnp_get_group( $xnpsid, $gid, $group );
	if( $result != 0 ) {
		redirect_header( 'editgroups.php', 3, _MD_XOONIPS_MODERATOR_ERROR_SELECT_GROUP );
		exit(  );
	}
	$item_storage_limit = sprintf( "%d", $group['item_storage_limit'] / 1000 / 1000 );
	$xoopsTpl->assign( 'gid', $group['gid'] );
	$xoopsTpl->assign( 'gname', $textutil->html_special_chars( $group['gname'] ) );
	$xoopsTpl->assign( 'gdesc', $textutil->html_special_chars( $group['gdesc'] ) );
	$xoopsTpl->assign( 'item_number_limit', $group['item_number_limit'] );
	$xoopsTpl->assign( 'index_number_limit', $group['index_number_limit'] );
	$xoopsTpl->assign( 'item_storage_limit', $item_storage_limit );
	break;
case 'update':
    xoonips_show_error_if_group_locked( $gid, _MD_XOONIPS_ERROR_CANNOT_EDIT_LOCKED_GROUP );
	if ( in_array( strtolower($gname), array( 'public', 'private', 'root' ) ) ){
		$xoopsTpl->assign( 'gid', $gid );
		$xoopsTpl->assign( 'gname', $textutil->html_special_chars( $gname ) );
		$xoopsTpl->assign( 'gdesc', $textutil->html_special_chars( $gdesc ) );
		$xoopsTpl->assign( 'item_number_limit', $item_number_limit );
		$xoopsTpl->assign( 'index_number_limit', $index_number_limit );
		$xoopsTpl->assign( 'item_storage_limit', $item_storage_limit );
		$xoopsTpl->assign( 'gname_forbidden', true );
		$gadmin_uids = $gadmins;
		$op='edit';
		break;
	}
	
	$group = array( 'gid' => $gid,
			'gname' => $gname,
			'gdesc' => $gdesc,
			'item_number_limit' => $item_number_limit,
			'index_number_limit' => $index_number_limit,
			'item_storage_limit' => $item_storage_limit * 1000 * 1000 );
	$result = xnp_update_group( $xnpsid, $group );
	if( $result != RES_OK ) {
		if( $result == RES_GROUPNAME_ALREADY_EXISTS ){
			$xoopsTpl->assign( 'gid', $gid );
			$xoopsTpl->assign( 'gname', $textutil->html_special_chars( $gname ) );
			$xoopsTpl->assign( 'gdesc', $textutil->html_special_chars( $gdesc ) );
			$xoopsTpl->assign( 'item_number_limit', $item_number_limit );
			$xoopsTpl->assign( 'index_number_limit', $index_number_limit );
			$xoopsTpl->assign( 'item_storage_limit', $item_storage_limit );
			$xoopsTpl->assign( 'gname_exists', true );
			$gadmin_uids = $gadmins;
			$op='edit';
			break;
		}else{
			redirect_header( 'editgroups.php', 3, _MD_XOONIPS_MODERATOR_ERROR_INSERT_GROUP );
			exit(  );
		}
	}
	$adminuids = array(  );
	if( xnp_dump_group_admins( $xnpsid, $gid, array(  ), $adminuids ) == 0 ) {
		foreach( $adminuids as $i ) {
			xnp_delete_member( $xnpsid, $gid, $i );
			xnp_insert_member( $xnpsid, $gid, $i, 0 );
		}
	}
	foreach( $gadmins as $i ) {
		xnp_delete_member( $xnpsid, $gid, $i );
		xnp_insert_member( $xnpsid, $gid, $i, 1 );
	}
	$op = '';
	
	// Record events(update group)
        $eventlog_handler =& xoonips_getormhandler( 'xoonips', 'event_log' );
        $eventlog_handler->recordUpdateGroupEvent( $gid );
	break;
case 'delete':
    xoonips_show_error_if_group_locked( $gid, _MD_XOONIPS_ERROR_CANNOT_DELETE_LOCKED_GROUP );
	$result = xnp_delete_group( $xnpsid, $gid );
	if( $result != 0 ) {
		redirect_header( 'editgroups.php', 3, _MD_XOONIPS_MODERATOR_ERROR_DELETE_GROUP );
		exit(  );
	}
	$op = '';
	
	// Record events(delete group)
	$eventlog_handler =& xoonips_getormhandler( 'xoonips', 'event_log' );
	$eventlog_handler->recordDeleteGroupEvent( $gid );
	break;
default:
	$op = '';
	break;
}

$xoopsTpl->assign( 'op', $op );
$xoopsOption['template_main'] = 'xoonips_editgroups.html';

//set limitation value(initial value)
if( $op == '' ) {
	$value = '';
	xnp_get_config_value( 'group_item_number_limit', $value );
	$xoopsTpl->assign( 'item_number_limit', $value );

	$value = '';
	xnp_get_config_value( 'group_item_storage_limit', $value );
	$xoopsTpl->assign( 'item_storage_limit', sprintf( "%d", $value / 1000 / 1000 ) );

	$value = '';
	xnp_get_config_value( 'group_index_number_limit', $value );
	$xoopsTpl->assign( 'index_number_limit', $value );

}

$gids = array(  );
if( xnp_dump_gids( $xnpsid, array(  ), $gids ) != 0 ) {
	redirect_header( XOOPS_URL.'/', 3,
					 "ERROR");
	exit(  );
}

$groups = array(  );
if( xnp_get_groups( $xnpsid, $gids, array(  ), $groups ) != 0 ) {
	redirect_header( XOOPS_URL.'/', 3, "ERROR");
	exit(  );
}

//show warning if group index is locked
$item_lock_handler =& xoonips_getormhandler( 'xoonips', 'item_lock' );
foreach ( $groups as $key => $val ){
    $groups[$key]['gname'] = $textutil->html_special_chars( $groups[$key]['gname'] );
    $groups[$key]['gdesc'] = $textutil->html_special_chars( $groups[$key]['gdesc'] );
    $isLocked = $item_lock_handler->isLocked( $val['group_index_id'] );
    $groups[$key]['isLocked'] = $isLocked;
    if ( $isLocked ){
         $groups[$key]['lockTypeString'] = $textutil->html_special_chars(
             sprintf( _MD_XOONIPS_WARNING_CANNOT_EDIT_LOCKED_GROUP, 
                 xoonips_get_lock_type_string(
                     $item_lock_handler->getLockType( $val['group_index_id'] ))));
    }
}

$xoopsTpl->assign( 'groups', $groups );

$uids = array(  );
if( xnp_dump_uids( $xnpsid, array(  ), $uids ) != 0 ) {
	redirect_header( XOOPS_URL.'/', 3, "ERROR");
	exit(  );
}

$users = array(  );
if( xnp_get_accounts( $xnpsid, $uids, array(  ), $users ) != 0 ) {
	redirect_header( XOOPS_URL.'/', 3, "ERROR");
	exit(  );
}


$gadmins = array(  );
foreach( $users as $i )
{
	$admin_flag = 0;
	if( ( $op == 'register' || $op == 'edit' ) && isset( $gadmin_uids ) ){
		$admin_flag = in_array( $i['uid'], $gadmin_uids );
	}else if( $op == 'edit' && isset( $gid ) ) {
		//if user is group's administrator
		if( xnp_is_group_admin( $xnpsid, $gid, $i['uid'] ) ) {
			$admin_flag = 1;
		}
	}
	if( $i['activate'] == 1 ) {	//add to gadmins if activated.
		$gadmins[] = array( 'uid' => $i['uid'],
							'uname' => $textutil->html_special_chars( $i['uname'] ), 'isadmin' => $admin_flag );
	}
}

require( XOOPS_ROOT_PATH.'/header.php' );

$xoopsTpl->assign( 'gadmins', $gadmins );
$xoopsTpl->assign( 'accept_charset', xnpGetMacSafariAcceptCharset() );
$xoopsTpl->assign( 'xoonips_editprofile_url', XOOPS_URL . '/modules/xoonips/edituser.php?uid=' . $uid );

require( XOOPS_ROOT_PATH.'/footer.php' );
?>
