<?php
/**
* This plugin depends on XThreads.
* Most method used here uses XThreads method.
*
* XThreads official release thread:
*
*		http://mybbhacks.zingaburga.com/showthread.php?tid=288
*		Coded by: Yumi/ZiNgA BuRgA
*		@ http://mybbhacks.zingaburga.com
*/

if(!defined('IN_MYBB')) die();
function xt_ucp_main_info(){
	return array(
		'name'			=> 'UCP Main Page',
		'description'	=> '<strong style="color: red"><em><a href="http://mybbhacks.zingaburga.com/showthread.php?tid=288">XThreads</a> is required for this plugin.</em></strong><br />Load Custom Profile Fields input into User CP main page.',
		'website'		=> 'http://mybbhacks.zingaburga.com',
		'author'		=> 'XThreads Mania',
		'authorsite'	=> 'http://mybbhacks.zingaburga.com',
		'version'		=> '1.0',
		'compatibility' => '*',
		'guid'        	=> ''
	);
}

function xt_ucp_main_activate(){}
function xt_ucp_main_deactivate(){}

$plugins->add_hook('global_start','xt_ucp_main_tcache');
function xt_ucp_main_tcache(){
	if(THIS_SCRIPT == 'usercp.php'){
		global $templatelist;
		if(isset($templatelist)) $templatelist .= ',smilieinsert,codebuttons,usercp_editsig,usercp_editsig_suspended, usercp_editsig_current,usercp_avatar';
	}
}

$plugins->add_hook('usercp_start','xt_ucp_main_usercp_start');
function xt_ucp_main_usercp_start(){
	if($GLOBALS['mybb']->settings['xt_proffields_ucp'] != 0){
		global $xtpfc;
		if(!$xtpfc) $xtpfc = $GLOBALS['cache']->read('xt_proffields');
		if($xtpfc){
			global $db,$theme,$mybb,$xtpfc,$errors,$lang,$templates,$user,$xtpf_minp,$xtpf_data,$birth_day,$userwebsite,$showsig,$showavatar,$bdprivacy,$allownotices,$receivepms,$pmnotice,$pmnotify,$tzselect,$editsig,$parser,$signature,$avatarupload;
			if(!is_object($parser)){
				require_once MYBB_ROOT.'inc/class_parser.php';
				$parser = new postParser;
			}
			$sig_parser = array(
				'allow_html' => $mybb->settings['sightml'],
				'allow_mycode' => $mybb->settings['sigmycode'],
				'allow_smilies' => $mybb->settings['sigsmilies'],
				'allow_imgcode' => $mybb->settings['sigimgcode'],
				'me_username' => $mybb->user['username'],
				'filter_badwords' => 1
			);
			if($mybb->input['action'] == 'do_update_xt_proffields' && $mybb->request_method == 'post'){
				verify_post_check($mybb->input['my_post_key']);
				require_once MYBB_ROOT.'inc/datahandlers/user.php';
				$userhandler = new UserDataHandler('update');
				$error = array();
				if($mybb->input['updatesig'] == 1){
					if($mybb->usergroup['canusesig'] != 1 || ($mybb->user['suspendsignature'] && ($mybb->user['suspendsigtime'] == 0 || $mybb->user['suspendsigtime'] > 0 && $mybb->user['suspendsigtime'] > TIME_NOW)) || ($mybb->usergroup['canusesig'] == 1 && $mybb->usergroup['canusesigxposts'] > 0 && $mybb->user['postnum'] < $mybb->usergroup['canusesigxposts'])){
						$error[] = $lang->sig_suspended;
					}else{
						$parsed_sig = $parser->parse_message($mybb->input['signature'],$sig_parser);
						if((($mybb->settings['sigimgcode'] == 0 && $mybb->settings['sigsmilies'] != 1) && substr_count($parsed_sig,'<img') > 0) || (($mybb->settings['sigimgcode'] == 1 || $mybb->settings['sigsmilies'] == 1) && substr_count($parsed_sig,'<img') > $mybb->settings['maxsigimages'])){
							if($mybb->settings['sigimgcode'] == 1){
								$imgsallowed = $mybb->settings['maxsigimages'];
							}else{
								$imgsallowed = 0;
							}
							$lang->too_many_sig_images2 = $lang->sprintf($lang->too_many_sig_images2, $imgsallowed);
							$error[] = $lang->too_many_sig_images.' '.$lang->too_many_sig_images2;
						}elseif($mybb->settings['siglength'] > 0){
							if($mybb->settings['sigcountmycode'] == 0){
								$parsed_sig = $parser->text_parse_message($mybb->input['signature']);
							}else{
								$parsed_sig = $mybb->input['signature'];
							}
							$parsed_sig = preg_replace('#\s#','',$parsed_sig);
							$sig_length = my_strlen($parsed_sig);
							if($sig_length > $mybb->settings['siglength']){
								$lang->sig_too_long = $lang->sprintf($lang->sig_too_long, $mybb->settings['siglength']);
								if($sig_length - $mybb->settings['siglength'] > 1){
									$lang->sig_too_long .= $lang->sprintf($lang->sig_remove_chars_plural,$sig_length-$mybb->settings['siglength']);
								}else{
									$lang->sig_too_long .= $lang->sig_remove_chars_singular;
								}
								$error[] = $lang->sig_too_long;
							}
						}
					}
				}
				$userxtpf = array(
					'uid'=>$mybb->user['uid'],
					'birthday'=>array('day'=>(int)$mybb->input['bday1'],'month'=>(int)$mybb->input['bday2'],'year'=>(int)$mybb->input['bday3']),
					'website'=>$mybb->input['website'],
					'timezone'=>$mybb->input['timezone'],
					'birthdayprivacy'=>$mybb->input['birthdayprivacy'],
					'options'=>array(
						'showsigs'=>(int)$mybb->input['showsigs'],
						'showavatars'=>(int)$mybb->input['showavatars'],
						'allownotices'=>(int)$mybb->input['allownotices'],
						'receivepms'=>(int)$mybb->input['receivepms'],
						'pmnotice'=>(int)$mybb->input['pmnotice'],
						'pmnotify'=>(int)$mybb->input['pmnotify']
					)
				);
				foreach($xtpfc as $pfields => &$pfval){
					if(xthreads_user_in_groups($pfval['xt_proffields_editable']) && !$pfval['xt_proffields_cinp'] && !$mybb->input['profile_fields']['fid'.$pfval['fid']]){
						$mybb->input['profile_fields']['fid'.$pfval['fid']] = $mybb->user['fid'.$pfval['fid']];
					}
				}
				$userxtpf['profile_fields'] = $mybb->input['profile_fields'];
				if($mybb->settings['usertppoptions']) $userxtpf['options']['tpp'] = (int)$mybb->input['tpp'];
				if($mybb->settings['userpppoptions']) $userxtpf['options']['ppp'] = (int)$mybb->input['ppp'];
				if($mybb->input['updatesig']) $userxtpf['signature'] = $mybb->input['signature'];
				$userhandler->set_data($userxtpf);
				if(!$userhandler->validate_user()){
					$uherrors = $userhandler->get_friendly_errors();
					if($uherrors){
						foreach($uherrors as $uherror){
							$error[] = $uherror;
						}
					}
				}
				if(count($error) > 0){
					$errors = inline_error($error);
					$mybb->input['action'] = '';
				}else{
					if($mybb->input['update_remove_avatar']){
						require_once MYBB_ROOT.'inc/functions_upload.php';
						$update_avatar = $avatar_error = ''; $avatar_remove = 1;
						switch($mybb->input['update_remove_avatar']){
							case 1:
								$update_avatar = 1;
								$avatar_dimensions = $user_avatar = $avatar_type = '';
							break;
							case 2:
								if($_FILES['avatarupload']['name']){
									if($mybb->usergroup['canuploadavatars'] == 0){
										$error[] = 'You do not have permission to upload avatar.';
									}else{
										$upload_avatar = upload_avatar();
										if($upload_avatar['error']){
											$error[] = $upload_avatar['error'];
										}else{
											if($upload_avatar['width'] > 0 && $upload_avatar['height'] > 0){
												$avatar_dimensions = $upload_avatar['width'].'|'.$upload_avatar['height'];
											}
											$user_avatar = $upload_avatar['avatar'].'?dateline='.TIME_NOW;
											$avatar_type = 'upload';
											$avatar_remove = 0;
											$update_avatar = 1;
										}
									}
								}elseif($mybb->input['avatarurl']){
									$mybb->input['avatarurl'] = preg_replace('#script:#i','',$mybb->input['avatarurl']);
									$ext = get_extension($mybb->input['avatarurl']);
									$file = fetch_remote_file($mybb->input['avatarurl']);
									if(!$file){
										$error[] = $lang->error_invalidavatarurl;
									}else{
										$tmp_name = $mybb->settings['avataruploadpath'].'/remote_'.md5(random_str());
										$fp = @fopen($tmp_name,'wb');
										if(!$fp){
											$avatar_error = 1;
											$error[] = $lang->error_invalidavatarurl;
										}else{
											fwrite($fp, $file);
											fclose($fp);
											list($width,$height,$type) = @getimagesize($tmp_name);
											@unlink($tmp_name);
											if(!$type){
												$avatar_error = 1;
												$error[] = $lang->error_invalidavatarurl;
											}
										}
										if(!$avatar_error){
											if($width && $height && $mybb->settings['maxavatardims'] != ''){
												list($maxwidth, $maxheight) = explode('x',my_strtolower($mybb->settings['maxavatardims']));
												if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){
													$lang->error_avatartoobig = $lang->sprintf($lang->error_avatartoobig,$maxwidth,$maxheight);
													$avatar_error = 1;
													$error[] = $lang->error_avatartoobig;
												}
											}
										}
										if(!$avatar_error){
											if($width > 0 && $height > 0){
												$avatar_dimensions = intval($width).'|'.intval($height);
											}
											$user_avatar = $db->escape_string($mybb->input['avatarurl'].'?dateline='.TIME_NOW);
											$avatar_type = 'remote';
											$update_avatar = 1;
										}
									}
								}
							break;
						}
					}
				}
				if(count($error) > 0){
					$errors = inline_error($error);
					$mybb->input['action'] = '';
				}else{
					$userhandler->update_user();
					if($mybb->input['updateposts'] == 'enable' || $mybb->input['updateposts'] == 'disable'){
						switch($mybb->input['updateposts']){
							case 'enable': $includesig = 1; break;
							case 'disable': $includesig = 0; break;
						}
						$db->update_query('posts',array('includesig'=>(int)$includesig),'uid='.(int)$mybb->user['uid']);
					}
					if($update_avatar){
						$updated_avatar = array(
							'avatar' => $user_avatar,
							'avatardimensions' => $avatar_dimensions,
							'avatartype' => $avatartype
						);
						$db->update_query('users',$updated_avatar,'uid='.(int)$mybb->user['uid']);
						if($avatar_remove) remove_avatars($mybb->user['uid']);
					}
					if(!$lang->xt_proffields_updated) $lang->load('xt_proffields');
					redirect('usercp.php',$lang->xt_proffields_updated);
				}
			}
			$lang->load('global');
			$xtpf_minp = array();
			if(!$user) $user = $mybb->user;
			foreach($xtpfc as $uf => &$xtpf){
				if($xtpf['editable'] == 1){
					$code = '';
					if($xtpf['postnum'] && $xtpf['postnum'] > $user['postnum']){
						continue;
					}
					if(xthreads_user_in_groups($xtpf['xt_proffields_editable'])){
						$code = xt_proffields_inp($xtpf,$user,$errors,$vars);
						$xtpf_minp['fid'.$xtpf['fid']] = xt_proffields_cinp($xtpf,$vars);
					}
				}
			}
			if($errors){
				$user = $mybb->input;
				$bday = array();
				$bday[0] = $mybb->input['bday1'];
				$bday[1] = $mybb->input['bday2'];
				$bday[2] = intval($mybb->input['bday3']);
			}else{
				$user = $mybb->user;
				$bday = explode('-',$user['birthday']);
			}
			$bdaydaysel = $bdaymonthsel = $bdayprivacysel = '';
			for($i = 1; $i <= 31; ++$i){
				if($bday[0] == $i) $daysel[$i] = ' selected="selected"';
				$bdaydaysel .= '<option value="'.$i.'"'.$daysel[$i].'>'.$i.'</option>'."\n";
			}
			for($i = 1; $i <= 12; ++$i){
				$lang_month = 'month_'.$i;
				if($bday[1] == $i) $monthsel[$i] = ' selected="selected"';
				$bdaymonthsel .= '<option value="'.$i.'"'.$monthsel[$i].'>'.$lang->$lang_month.'</option>'."\n";
			}
			$bd_day = '<select name="bday1"><option value="">&nbsp;</option>'.$bdaydaysel.'</select>';
			$bd_month = '<select name="bday2"><option value="">&nbsp;</option>'.$bdaymonthsel.'</select>';
			$bd_year = '<input type="text" class="textbox" size="4" maxlength="4" name="bday3" value="'.$bday['2'].'" />';
			$birth_day = $bd_day.' '.$bd_month.' '.$bd_year;
			if($user['birthdayprivacy'] == 'all' || !$user['birthdayprivacy']){
				$allselected = ' selected="selected"';
			}else if($user['birthdayprivacy'] == 'none'){
				$noneselected = ' selected="selected"';
			}else if($user['birthdayprivacy'] == 'age'){
				$ageselected = ' selected="selected"';
			}
			$bdayprivacysel .= '<option value="all"'.$allselected.'>'.$lang->birthdayprivacyall.'</option>'."\n";
			$bdayprivacysel .= '<option value="none"'.$noneselected.'>'.$lang->birthdayprivacynone.'</option>'."\n";
			$bdayprivacysel .= '<option value="age"'.$ageselected.'>'.$lang->birthdayprivacyage.'</option>';
			$bdprivacy = '<select name="birthdayprivacy">'.$bdayprivacysel.'</select>';
			if($user['website'] == '' || $user['website'] == 'http://'){
				$user['website'] = 'http://';
			}else{
				$user['website'] = htmlspecialchars_uni($user['website']);
			}
			$userwebsite = '<input type="text" class="textbox" name="website" size="25" maxlength="75" value="'.$user['website'].'" />';
			if($mybb->settings['usertppoptions']){
				global $threadperpage;
				$explodedtpp = explode(',',$mybb->settings['usertppoptions']);
				$tppoptions = '';
				if(is_array($explodedtpp)){
					foreach($explodedtpp as $key => $val){
						$val = trim($val);
						$selected = '';
						if($user['tpp'] == $val) $selected = ' selected="selected"';
						$tppoptions .= '<option value="'.$val.'"'.$selected.'>'.$lang->sprintf($lang->tpp_option,$val).'</option>'."\n";
					}
				}
				$threadperpage = '<select name="tpp"><option value="">'.$lang->use_default.'</option>'.$tppoptions.'</select>';
				//eval('$tppselect = "'.$templates->get('usercp_options_tppselect').'";');
			}
			if($mybb->settings['userpppoptions']){
				global $postperpage;
				$explodedppp = explode(',',$mybb->settings['userpppoptions']);
				$pppoptions = '';
				if(is_array($explodedppp)){
					foreach($explodedppp as $key => $val){
						$val = trim($val);
						$selected = '';
						if($user['ppp'] == $val) $selected = ' selected="selected"';
						$pppoptions .= '<option value="'.$val.'"'.$selected.'>'.$lang->sprintf($lang->ppp_option, $val).'</option>'."\n";
					}
				}
				$postperpage = '<select name="ppp"><option value="">'.$lang->use_default.'</option>'.$pppoptions.'</select>';
				//eval('$pppselect = "'.$templates->get('usercp_options_pppselect').'";');
			}
			if($user['showsigs'] == 1) $showsigscheck = ' checked="checked"';
			if($user['showavatars'] == 1) $showavatarscheck = ' checked="checked"';
			$showsig = '<table border="0" style="width:100%"><tr><td style="width:1px"><input type="checkbox" class="checkbox" name="showsigs" id="showsigs" value="1"'.$showsigscheck.' /></td><td><label for="showsigs">'.$lang->show_sigs.'</label></td></tr></table>';
			$showavatar = '<table border="0" style="width:100%"><tr><td style="width:1px"><input type="checkbox" class="checkbox" name="showavatars" id="showavatars" value="1"'.$showavatarscheck.' /></td><td><label for="showavatars">'.$lang->show_avatars.'</label></td></tr></table>';
			if($user['allownotices'] == 1){
				$allownoticescheck = ' checked="checked"';
			}else{
				$allownoticescheck = '';
			}
			$allownotices = '<table border="0" style="width:100%"><tr><td style="width:1px"><input type="checkbox" class="checkbox" name="allownotices" id="allownotices" value="1"'.$allownoticescheck.' /></td><td><label for="allownotices">'.$lang->allow_notices.'</label></td></tr></table>';
			if($user['receivepms'] == 1){
				$receivepmscheck = ' checked="checked"';
			}else{
				$receivepmscheck = '';
			}
			$receivepms = '<table border="0" style="width:100%"><tr><td style="width:1px"><input type="checkbox" class="checkbox" name="receivepms" id="receivepms" value="1"'.$receivepmscheck.' /></td><td><label for="receivepms">'.$lang->receive_pms.'</label></td></tr></table>';
			if($user['pmnotice'] == 1 || $user['pmnotice'] == 2){
				$pmnoticecheck = ' checked="checked"';
			}else{
				$pmnoticecheck = '';
			}
			$pmnotice = '<table border="0" style="width:100%"><tr><td style="width:1px"><input type="checkbox" class="checkbox" name="pmnotice" id="pmnotice" value="1"'.$pmnoticecheck.' /></td><td><label for="pmnotice">'.$lang->pm_notice.'</label></td></tr></table>';
			if($user['pmnotify'] == 1){
				$pmnotifycheck = ' checked="checked"';
			}else{
				$pmnotifycheck = '';
			}
			$pmnotify = '<table border="0" style="width:100%"><tr><td style="width:1px"><input type="checkbox" class="checkbox" name="pmnotify" id="pmnotify" value="1"'.$pmnotifycheck.' /></td><td><label for="pmnotify">'.$lang->pm_notify.'</label></td></tr></table>';
			$tzselect = build_timezone_select('timezoneoffset',$mybb->user['timezone'],true);
			$sig = htmlspecialchars_uni($user['signature']);
			if($mybb->usergroup['canusesig'] != 1 || ($mybb->user['suspendsignature'] && ($mybb->user['suspendsigtime'] == 0 || $mybb->user['suspendsigtime'] > 0 && $mybb->user['suspendsigtime'] > TIME_NOW)) || ($mybb->usergroup['canusesig'] == 1 && $mybb->usergroup['canusesigxposts'] > 0 && $mybb->user['postnum'] < $mybb->usergroup['canusesigxposts'])){
				eval('$editsig = "'.$templates->get('usercp_editsig_suspended').'";');
			}else{
				if($mybb->settings['sigsmilies'] == 1){
					$sigsmilies = $lang->on;
					$smilieinserter = build_clickable_smilies();
				}else{
					$sigsmilies = $lang->off;
				}
				if($mybb->settings['sigmycode'] == 1){
					$sigmycode = $lang->on;
				}else{
					$sigmycode = $lang->off;
				}
				if($mybb->settings['sightml'] == 1){
					$sightml = $lang->on;
				}else{
					$sightml = $lang->off;
				}
				if($mybb->settings['sigimgcode'] == 1){
					$sigimgcode = $lang->on;
				}else{
					$sigimgcode = $lang->off;
				}
				$lang->edit_sig_note2 = $lang->sprintf($lang->edit_sig_note2,$sigsmilies,$sigmycode,$sigimgcode,$sightml,$mybb->settings['siglength']);
		
				if($mybb->settings['bbcodeinserter'] != 0 || $mybb->user['showcodebuttons'] != 0){
					$codebuttons = build_mycode_inserter('signature');
				}
				if($mybb->input['updatesig']) $updatesigcheck = ' checked="checked"';
				eval('$editsig = "'.$templates->get('usercp_editsig').'";');
			}
			if($sig){		
				$sigpreview = $parser->parse_message($sig,$sig_parser);
				eval('$signature = "'.$templates->get('usercp_editsig_current').'";');
			}
			if($mybb->user['avatartype'] == 'upload' || stristr($mybb->user['avatar'],$mybb->settings['avataruploadpath'])){
				$avatarmsg = '<br /><strong>'.$lang->already_uploaded_avatar.'</strong>';
			}elseif($mybb->user['avatartype'] == 'gallery' || stristr($mybb->user['avatar'],$mybb->settings['avatardir'])){
				$avatarmsg = '<br /><strong>'.$lang->using_gallery_avatar.'</strong>';
			}elseif($mybb->user['avatartype'] == 'remote' || my_strpos(my_strtolower($mybb->user['avatar']),'http://') !== false){
				$avatarmsg = '<br /><strong>'.$lang->using_remote_avatar.'</strong>';
				$avatarurl = htmlspecialchars_uni($mybb->user['avatar']);
			}
			if($mybb->settings['maxavatardims'] != ''){
				list($maxwidth, $maxheight) = explode('x',my_strtolower($mybb->settings['maxavatardims']));
				$lang->avatar_note .= '<br />'.$lang->sprintf($lang->avatar_note_dimensions,$maxwidth,$maxheight);
			}
			if($mybb->settings['avatarsize']){
				$maxsize = get_friendly_size($mybb->settings['avatarsize']*1024);
				$lang->avatar_note .= '<br />'.$lang->sprintf($lang->avatar_note_size,$maxsize);
			}
			if($mybb->settings['avatarresizing'] == 'auto'){
				$auto_resize = '<br /><span class="smalltext">'.$lang->avatar_auto_resize_note.'</span>'."\n";
			}else if($mybb->settings['avatarresizing'] == 'user'){
				$auto_resize = '<br /><span class="smalltext"><input type="checkbox" name="auto_resize" value="1" checked="checked" id="auto_resize" /> <label for="auto_resize">'.$lang->avatar_auto_resize_option.'</label></span>';
			}
			$urac = array();
			$urac[(int)$mybb->input['update_remove_avatar']] = ' checked="checked"';
			eval('$avatarupload = "'.$templates->get('usercp_avatar').'";');
		}
	}
}
?>