<?php
// $Revision: 1.11.4.1.2.12 $
// ------------------------------------------------------------------------- //
//  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/AL.php';
include_once 'include/lib.php';

$myuid = is_object( $xoopsUser ) ? $xoopsUser->getVar( 'uid', 'n' ) : UID_GUEST;

$formdata =& xoonips_getutility( 'formdata' );
$uid = $formdata->getValue( 'get', 'uid', 'i', false );
$myxoopsConfigUser =& xoonips_get_xoops_configs( XOOPS_CONF_USER );

if ( is_null( $uid ) ) {
  if ( $myuid == UID_GUEST ) {
    redirect_header( XOOPS_URL.'/', 3, _US_SORRYNOTFOUND);
    exit();
  }
  $uid = $myuid;
}

// profile of 'not activated user' is not displayed.
$table = $xoopsDB->prefix("xoonips_users");
$sql = "select uid from $table where activate=1";
$result = $xoopsDB->query( $sql );
while( $uid_row = $xoopsDB->fetchArray($result)){
	$uids[] = intval( $uid_row['uid'] );
}
if( !in_array( $uid, $uids ) ){
	redirect_header( XOOPS_URL.'/', 3, _US_SELECTNG);
	exit();
}

// part of Self-introduction
$xmember_handler =& xoonips_gethandler( 'xoonips', 'member' );
$is_admin = $xmember_handler->isAdmin( $myuid );

$myts =& MyTextSanitizer::getInstance();
$textutil =& xoonips_getutility( 'text' );

if (is_object($xoopsUser)) {
	if ($uid == $xoopsUser->getVar('uid')) {
		$xoopsOption['template_main'] = 'xoonips_showusers.html';
		include XOOPS_ROOT_PATH.'/header.php';
		$xoopsTpl->assign('user_ownpage', true);
		$xoopsTpl->assign('lang_editprofile', _US_EDITPROFILE);
		$xoopsTpl->assign('lang_notifications', _MD_XOONIPS_ACCOUNT_NOTIFICATIONS);
		$xoopsTpl->assign('lang_avatar', _US_AVATAR);
		$xoopsTpl->assign('lang_inbox', _US_INBOX);
		$xoopsTpl->assign('lang_logout', _US_LOGOUT);
		if ($myxoopsConfigUser['self_delete'] == 1) {
			$xoopsTpl->assign('user_candelete', true);
			$xoopsTpl->assign('lang_deleteaccount', _US_DELACCOUNT);
		} else {
			$xoopsTpl->assign('user_candelete', false);
		}
		$thisUser =& $xoopsUser;
	} else {
		$member_handler =& xoops_gethandler('member');
		$thisUser =& $member_handler->getUser($uid);
		if (!is_object($thisUser) || !$thisUser->isActive() ) {
 			// this error will occured when user is not
                        // activated on XOOPS
			redirect_header( XOOPS_URL.'/',3,_US_SELECTNG);
			exit();
		}
		$xoopsOption['template_main'] = 'xoonips_showusers.html';
		include XOOPS_ROOT_PATH.'/header.php';
		$xoopsTpl->assign('user_ownpage', false);
	}
} else {
	$member_handler =& xoops_gethandler('member');
	$thisUser =& $member_handler->getUser($uid);
	if (!is_object($thisUser) || !$thisUser->isActive()) {
		redirect_header( XOOPS_URL.'/',3,_US_SELECTNG);
		exit();
	}
	$xoopsOption['template_main'] = 'xoonips_showusers.html';
	include(XOOPS_ROOT_PATH.'/header.php');
	$xoopsTpl->assign('user_ownpage', false);
}

if ( is_object($xoopsUser) && $is_admin ) {
	$xoopsTpl->assign('lang_editprofile', _US_EDITPROFILE);
	$xoopsTpl->assign('lang_deleteaccount', _US_DELACCOUNT);
	$xoopsTpl->assign('user_uid', $thisUser->getVar('uid'));
}
$xoopsTpl->assign('lang_allaboutuser', sprintf(_US_ALLABOUT,$thisUser->getVar('uname')));
$xoopsTpl->assign('lang_avatar', _US_AVATAR);
$xoopsTpl->assign('user_avatarurl', '../../uploads/'.$thisUser->getVar('user_avatar'));
$xoopsTpl->assign('user_username', $textutil->html_special_chars( $thisUser->getVar( 'uname', 'n') ) );
$xoopsTpl->assign('lang_realname', _US_REALNAME);
$xoopsTpl->assign('user_realname', $textutil->html_special_chars( $thisUser->getVar( 'name', 'n' ) ) );
$xoopsTpl->assign('lang_website', _US_WEBSITE);
$xoopsTpl->assign('user_websiteurl', '<a href="'.$thisUser->getVar('url', 'E').'" target="_blank">'.$thisUser->getVar('url').'</a>');
$xoopsTpl->assign('lang_email', _US_EMAIL);
$xoopsTpl->assign('lang_privmsg', _US_PM);
// $xoopsTpl->assign('lang_icq', _US_ICQ);
// $xoopsTpl->assign('user_icq', $thisUser->getVar('user_icq'));
// $xoopsTpl->assign('lang_aim', _US_AIM);
// $xoopsTpl->assign('user_aim', $thisUser->getVar('user_aim'));
// $xoopsTpl->assign('lang_yim', _US_YIM);
// $xoopsTpl->assign('user_yim', $thisUser->getVar('user_yim'));
// $xoopsTpl->assign('lang_msnm', _US_MSNM);
// $xoopsTpl->assign('user_msnm', $thisUser->getVar('user_msnm'));
// $xoopsTpl->assign('lang_location', _US_LOCATION);
// $xoopsTpl->assign('user_location', $thisUser->getVar('user_from'));
// $xoopsTpl->assign('lang_occupation', _US_OCCUPATION);
// $xoopsTpl->assign('user_occupation', $thisUser->getVar('user_occ'));
$xoopsTpl->assign('lang_interest', _US_INTEREST);
$xoopsTpl->assign('user_interest', $textutil->html_special_chars( $thisUser->getVar('user_intrest','n' ) ) );
// $xoopsTpl->assign('lang_extrainfo', _US_EXTRAINFO);
// $xoopsTpl->assign('user_extrainfo', $myts->makeTareaData4Show($thisUser->getVar('bio', 'N'),0,1,1));
$xoopsTpl->assign('lang_statistics', _US_STATISTICS);
$xoopsTpl->assign('lang_membersince', _US_MEMBERSINCE);
$xoopsTpl->assign('user_joindate', formatTimestamp($thisUser->getVar('user_regdate'),'s'));
$xoopsTpl->assign('lang_rank', _US_RANK);
// $xoopsTpl->assign('lang_posts', _US_GETS);
$xoopsTpl->assign('lang_basicInfo', _US_BASICINFO);
$xoopsTpl->assign('lang_more', _US_MOREABOUT);
$xoopsTpl->assign('lang_myinfo', _US_MYINFO);
$xoopsTpl->assign('user_posts', $thisUser->getVar('posts'));
$xoopsTpl->assign('lang_lastlogin', _US_LASTLOGIN);
$xoopsTpl->assign('lang_notregistered', _US_NOTREGISTERED);

$xoopsTpl->assign('lang_signature', _US_SIGNATURE);
$xoopsTpl->assign('user_signature', $textutil->html_special_chars( $thisUser->getVar('user_sig', 'n' ) ) );


// pm operation
if (is_object($xoopsUser) && $uid != $xoopsUser->getVar('uid')) {
//	$xoopsTpl->assign('user_pmlink', "<a href=\"javascript:openWithSelfMain('".XOOPS_URL."/pmlite.php?send2=1&amp;to_userid=".$thisUser->getVar('uid')."', 'pmlite', 450, 380);\"><img src=\"".XOOPS_URL."/images/icons/pm.gif\" alt=\"".sprintf(_SENDPMTO,$thisUser->getVar('uname'))."\" /></a>");
//	$xoopsTpl->assign('user_pmlink', "<a href=\"javascript:openWithSelfMain('".XOOPS_URL."/pmlite.php?send2=1&amp;to_userid=".$thisUser->getVar('uid')."', 'pmlite', 450, 380);\"><img src=\"".XOOPS_URL."/images/icons/pm_small.gif\" alt=\"".sprintf(_SENDPMTO,$thisUser->getVar('uname'))."\" /></a>");
	$xoopsTpl->assign('user_pmlink', "<input class=\"formButton\" type=\"button\" value='"._MD_XOONIPS_SEND_MESSAGE."' onclick=\"openWithSelfMain('".XOOPS_URL."/pmlite.php?send2=1&amp;to_userid=".$thisUser->getVar('uid')."', 'pmlite', 450, 380);\" />");
} else {
	$xoopsTpl->assign('user_pmlink', '');
}

// assign xoonips user information from uid.
{
	$ts =& MyTextSanitizer::getInstance();
	$table = $xoopsDB->prefix("xoonips_users");
	$sql = "select * from $table where uid=$uid";
	$result = $xoopsDB->query( $sql );
	if ( $result != FALSE && $xoopsDB->getRowsNum($result) != 0 ){
		$xoopsTpl->assign('xnp_user_ownpage', true);
		$row = $xoopsDB->fetchArray( $result );
		reset( $row );
		while ( list( $key, $val ) = each( $row ) ){
			if( $key == "posi" ){
				$posiid = intval( $val );
			}
			else if( $key == "appeal" ) {
				$sap = $textutil->html_special_chars( $val );
				$xoopsTpl->assign('xnp_user_appeal', $sap);
			}
			else {
				$xoopsTpl->assign( "xnp_user_$key", $textutil->html_special_chars( $val ) );
			}

		}
        $xoopsDB->freeRecordSet( $result );
	}
	else {
		$xoopsTpl->assign('xnp_user_ownpage', false);
	}
}

$potab = $xoopsDB->prefix( "xoonips_positions" );
$posql = "SELECT posi_title FROM $potab WHERE posi_id=$posiid";
$pores = $xoopsDB->query( $posql );
$porow = $xoopsDB->fetchArray( $pores );
$xoopsTpl->assign( 'user_posititle', $textutil->html_special_chars( $porow['posi_title'] ) );

// optimize page number
function page_optimize($page, $last){
	// empty string is page 1
	if(strlen($page) == 0){
		return 1;
	}
	// not numerical string is page 1
	if(!is_numeric($page)){
		return 1;
	}
	// convert decimal point to integer
	$w_page = floor($page);
	// limit minumum page
	if($page < 1){
		return 1;
	}
	// limit maximum page
	if($w_page > $last){
		$w_page = $last;
	}
	return $w_page;
}

// caclulate number of show items
// get 'item_show_optional' variable from xoonips_config table.
//  on  : count from own items (default)
//  off : count from all public items
$tab = $xoopsDB->prefix("xoonips_config");
$sql = "SELECT value FROM ".$tab." WHERE name='item_show_optional'";
$res = $xoopsDB->query($sql);
while($itop = $xoopsDB->fetchArray($res)){
	if($itop["value"] === "on"){
		$val = 1;
	} else {
		$val = 0;
	}
}


$sql = "SELECT index_id FROM ".$xoopsDB->prefix("xoonips_index")." WHERE uid IS NULL AND gid IS NULL";
$res = $xoopsDB->query($sql);
$inid = "";
$itid = "";
$num_of_data = "";
$sum_of_data = "";
$item_htmls = array();
while($row = $xoopsDB->fetchArray($res)){
	$inid = intval( $row["index_id"] );
	$sql2 = "SELECT item_id FROM ".$xoopsDB->prefix("xoonips_index_item_link")." WHERE index_id=".$inid." ";
	$res2 = $xoopsDB->query($sql2);
	while($row2 = $xoopsDB->fetchArray($res2)){
		$itid = intval( $row2["item_id"] );
			// var_dump($itid);
			switch( $val ) {
				case 0:
				$sql3 = "SELECT i2.item_id FROM ".$xoopsDB->prefix("xoonips_item_basic")." as i1, ".$xoopsDB->prefix("xoonips_item_show")." as i2 WHERE i1.item_id=".$itid." AND i1.uid=".$uid." AND i1.item_id=i2.item_id AND i1.uid=i2.uid";
				$res3 = $xoopsDB->query($sql3);
				$num_of_data = $xoopsDB->getRowsNum($res3);
				$sum_of_data = $sum_of_data + $num_of_data;
				break;
				
				case 1:
				$sql3 = "SELECT item_id FROM ".$xoopsDB->prefix("xoonips_item_show")." WHERE item_id=".$itid." AND uid=".$uid."";
				$res3 = $xoopsDB->query($sql3);
				$num_of_data = $xoopsDB->getRowsNum($res3);
				$sum_of_data = $sum_of_data + $num_of_data;
			}
	}
	if( !is_numeric( $sum_of_data ) ){
		$sum_of_data = 0;
	}
}


// calculate maximum number of pages and offset value
	$w_last = intval($sum_of_data / 20);
	if( $w_last < 1 ){
		$w_last = 1;
	}
	$page = $formdata->getValue( 'get', 'page', 'i', false, 0 );
        if ( $page <= 0 ) {
	  $w_page = page_optimize(1, $w_last);
        } else {
	  $w_page = page_optimize($page, $w_last);
	}
	$w_offset = intval( ($w_page - 1) * 20 );
	if( $w_offset < 0 ){
		$w_offset = 0;
	}
	$xoopsTpl->assign('sum_of_data', $sum_of_data);

// create page links
$xoopsTpl->assign('uid', $uid);

if ( $w_page > 1 ){
	$w_back = intval( $w_page - 1 );
	$xoopsTpl->assign('w_back', $w_back);
}

if(!isset($pages)){
	$pages = array( min( max( 0, $w_page - 4 ), max( 0, $w_last - 9 ) ) );
}

// decide number of iteration
foreach( $pages as $key => $value ){
	if( $value < 10 ){
		$times = $value;
	} else {
		$times = 10;
	}
}

$w_link = '';
for( $i = 0 ; $i < $times; $i++ ){
	$pag = intval( $pages[ $i ] ) + 1;
	switch ( $pag ) {
		case $w_page:
			if($w_last != 1){
				$link = "&nbsp;".$pages[ $i ]."&nbsp;";
			} else {
				$link = '';
			}
				break;
		default:
			$link ="&nbsp;<a href=\"showusers.php?uid=".$uid."&page=".$pag."\">".$pag."</a>&nbsp;";
		}
	$w_link[] = array('link'=>$link);
	}
$xoopsTpl->assign('w_link', $w_link);

if ( $w_page < $w_last ){
	$w_next = intval( $w_page + 1 );
	$xoopsTpl->assign('w_next', $w_next);
}

// show item using itemid2ListBlock
// get 'item_show_optional' variable from xoonips_config table.
//  on  : count from own items (default)
//  off : count from all public items
$tab = $xoopsDB->prefix("xoonips_config");
$sql = "SELECT value FROM ".$tab." WHERE name='item_show_optional'";
$res = $xoopsDB->query($sql);
while($itop = $xoopsDB->fetchArray($res)){
	if($itop["value"] === "on"){
		$val = 1;
	} else {
		$val = 0;
	}
}

$item_htmls = array();
	if( $sum_of_data !== 0 ){
		$tab_name1 = $xoopsDB->prefix('xoonips_item_show');
		$tab_name2 = $xoopsDB->prefix('xoonips_item_basic');
		$tab_name3 = $xoopsDB->prefix('xoonips_index_item_link');
		$tab_name4 = $xoopsDB->prefix('xoonips_index');
		$tab_name5 = $xoopsDB->prefix('xoonips_item_type');
		$tab_name6 = $xoopsDB->prefix('modules');
		switch( $val ) {
		case 0:
			$sql  = "SELECT DISTINCT i1.item_id, i2.item_type_id FROM ".$tab_name1." as i1, ".$tab_name2." as i2, ".$tab_name3." as i3, ".$tab_name4." as i4, ".$tab_name5." as i5, ".$tab_name6." as i6";
			$sql .= " WHERE i1.uid=".$uid." AND i1.item_id=i2.item_id AND i2.item_id=i3.item_id AND i3.index_id=i4.index_id AND i4.uid IS NULL AND i4.gid IS NULL";
			$sql .= " AND i3.certify_state=2 AND i2.item_type_id=i5.item_type_id AND i5.mid=i6.mid AND i2.uid=".$uid."";
			$sql .= " ORDER BY i6.weight ASC, i2.publication_year DESC, i2.publication_month DESC, i2.publication_mday DESC, i2.last_update_date DESC";
			$res = $xoopsDB->query($sql);
			break;
		case 1:
			$sql  = "SELECT DISTINCT i1.item_id, i2.item_type_id FROM ".$tab_name1." as i1, ".$tab_name2." as i2, ".$tab_name3." as i3, ".$tab_name4." as i4, ".$tab_name5." as i5, ".$tab_name6." as i6";
			$sql .= " WHERE i1.uid=".$uid." AND i1.item_id=i2.item_id AND i2.item_id=i3.item_id AND i3.index_id=i4.index_id AND i4.uid IS NULL AND i4.gid IS NULL";
			$sql .= " AND i3.certify_state=2 AND i2.item_type_id=i5.item_type_id AND i5.mid=i6.mid";
			$sql .= " ORDER BY i6.weight ASC, i2.publication_year DESC, i2.publication_month DESC, i2.publication_mday DESC, i2.last_update_date DESC";
			$res = $xoopsDB->query($sql);
		}
		$ch_a ='';
		while($row = $xoopsDB->fetchArray($res)){
			// show item_type's name
			$ch_b = intval( $row["item_type_id"] );
			if( empty($ch_a) || $ch_a !== $ch_b ){
				$tab_name = $xoopsDB->prefix('xoonips_item_type');
				$tsql = "SELECT display_name FROM ".$tab_name." WHERE item_type_id=".$ch_b."";
				$tres = $xoopsDB->query($tsql);
				$trow = $xoopsDB->fetchArray($tres);
					$item_type_title = $ts->htmlSpecialChars($trow['display_name']);
					$title_t = "<table><tr><td>&nbsp;&nbsp;".$item_type_title."</td></tr></table>";
					$item_htmls[] = array( 'html'=>$title_t, 'th'=>'on' );
			}
			// make item block
			$tmp = itemid2ListBlock( intval($row['item_id']) );
			foreach($tmp as $key =>$value ){
				$item_htmls[] = array( 'html'=>$value );
			}
			$ch_a = intval( $row["item_type_id"] );
		}
	}
	$xoopsTpl->assign('item_htmls', $item_htmls );

if( isset( $_SESSION['xoopsUserId'] ) ){
	if( intval( $_SESSION['xoopsUserId'] ) == $uid ){
		$piedit = 1;
		$xoopsTpl->assign('piedit', $piedit);
	}
	$aid = intval( $_SESSION['xoopsUserId'] );
	$xoopsTpl->assign('aid', $aid);
}


$tab_co = $xoopsDB->prefix("xoonips_config");
$cosql = "SELECT value FROM ".$tab_co." WHERE name='public_item_target_user'";
$cores = $xoopsDB->query($cosql);
$corow = $xoopsDB->fetchArray($cores);
$target = $corow["value"];
$target = $ts->htmlSpecialChars($target);
$xoopsTpl->assign('target', $target);

// Get date of Curriculum Vitae
$tab_cv = $xoopsDB->prefix("xoonips_cvitaes");
$besql_cv = "SELECT cvitae_id FROM ".$tab_cv." WHERE uid=".$uid."";
$beres_cv = $xoopsDB->query($besql_cv);
	if ( $beres_cv == FALSE ){
		echo "ERROR: SQL=$besql<br />\n error=" . $xoopsDB -> error() . "<br />\n";
	}
	$benum_cv = $xoopsDB->getRowsNum($beres_cv);
	if ( $benum_cv !== 0 ) {
		$sql_cv = "SELECT * FROM ".$tab_cv." WHERE uid=".$uid." ORDER BY cvitae_order ASC, from_year ASC, from_month ASC";
		$res_cv = $xoopsDB->query($sql_cv);
				if ( $res_cv == FALSE ){
					echo "ERROR: SQL=$sql_cv<br />\n error=" . $xoopsDB -> error() . "<br />\n";
				}
		while( $row_cv = $xoopsDB->fetchArray($res_cv) ){
			// $cvdata["cvitae_id"       ] = $myts->makeTboxData4Show($row["cvitae_id"]);
			$bedata["cvitae_from_month"] = $row_cv["from_month"] != 0 ? intval($row_cv["from_month"]) : 0;
			$bedata["cvitae_from_year" ] = $row_cv["from_year" ] != 0 ? intval($row_cv["from_year" ]) : 0;
			$bedata["cvitae_to_month"  ] = $row_cv["to_month"  ] != 0 ? intval($row_cv["to_month"  ]) : 0;
			$bedata["cvitae_to_year"   ] = $row_cv["to_year"   ] != 0 ? intval($row_cv["to_year"   ]) : 0;
			
			if( $bedata["cvitae_from_month"] !== 0 ){
				$cvdata["cvitae_from_month"] = date("M.", mktime(0, 0, 0, $bedata["cvitae_from_month"], 1, 0));
			} else {
				$cvdata["cvitae_from_month"] = '';
			}
			if( $bedata["cvitae_from_year"] !== 0 ){
				$cvdata["cvitae_from_year"] = date("Y", mktime(0, 0, 0, 1, 1, $bedata["cvitae_from_year"]));
			} else {
				$cvdata["cvitae_from_year"] = '';
			}
			if( $bedata["cvitae_to_month"] !== 0 ){
				$cvdata["cvitae_to_month"] = date("M.", mktime(0, 0, 0, $bedata["cvitae_to_month"], 1, 0));
			} else {
				$cvdata["cvitae_to_month"] = '';
			}
			if( $bedata["cvitae_to_year"] !== 0 ){
				$cvdata["cvitae_to_year"] = date("Y", mktime(0, 0, 0, 1, 1, $bedata["cvitae_to_year"]));
			} else {
				$cvdata["cvitae_to_year"] = '';
			}
			$cvdata["cvitae_title"] = $myts->makeTboxData4Show($row_cv["cvitae_title"]);
			
			$xoopsTpl->append("cv_array", $cvdata);
		}
	}


include XOOPS_ROOT_PATH.'/footer.php';

?>
