<?php
include("includes/site_info.php");
include('session_handler.inc');
include('functions.php');
	
	switch ($_REQUEST["Submit"]) {
	case "account"; 
		account();
		break;
	case "profile_basic"; 
		profile_basic();
		break;
	case "profile_personal"; 
		profile_personal();
		break;
	case "profile_picture"; 
		add_photos();
		break;
	default; 
		echo "";
		break;
	}

function account() {
$mem_fullname=form_get('fullname');
$mem_nickname=form_get('nickname');
$mem_profileid=form_get('profileid');
$mem_email=form_get('email');
$mem_mobile=form_get('WMyMobile');
$current_pass=form_get('current_pass');
$mem_password=form_get('new_pass');
$lang_id=form_get('WLang');
$mem_newsletter=form_get('newsletter');
$mem_purpose=form_get('purpose');

$result=mysql_query("SELECT * FROM members WHERE mem_userid = '".$_REQUEST['user_id']."'");
$sql_array=mysql_fetch_object($result);

if ((md5($current_pass) != $sql_array->mem_password) && ($mem_password!=""))  {
	print "<font color=\"red\">Ops! Your current password was wrong! Please try again!</font>";
	die;
}

$count = mysql_num_rows(mysql_query("SELECT * FROM members WHERE mem_email='".$mem_email."' and mem_email!='".$sql_array->mem_email."'")); 
if($count > 0) { 
   echo "<font color=\"red\">This Email already exists, please choose another one.</font>"; 
   die;
}
if (!empty($mem_profileid)) {
$count2 = mysql_num_rows(mysql_query("SELECT * FROM members WHERE mem_profileid='".$mem_profileid."' and mem_profileid!='".$sql_array->mem_profileid."'")); 
$invalid_string = "admin support join help test testing tester wau wauhaha wauhh administrator";
if($count2 > 0) { 
   echo "<font color=\"red\">This Display Name already exists, please choose another one.</font>"; 
   die;
}
if(stristr($invalid_string, $mem_profileid) == true){
   echo "<font color=\"red\">This Display Name was not available, please choose another one.</font>";
   die;
}
}

if ((md5($current_pass) == $sql_array->mem_password) && ($mem_password!="")) {
$query1=mysql_query("UPDATE members set mem_password='".md5($mem_password)."', mem_fullname='$mem_fullname', mem_nickname='$mem_nickname',  mem_profileid='$mem_profileid', mem_email='$mem_email', mem_mobile='$mem_mobile', lang_id='$lang_id', mem_newsletter='$mem_newsletter', mem_purpose='$mem_purpose' where mem_userid='".$_REQUEST['user_id']."'");
} else {
$query1=mysql_query("UPDATE members set mem_fullname='$mem_fullname', mem_nickname='$mem_nickname',  mem_profileid='$mem_profileid', mem_email='$mem_email', mem_mobile='$mem_mobile', lang_id='$lang_id', mem_newsletter='$mem_newsletter', mem_purpose='$mem_purpose' where mem_userid='".$_REQUEST['user_id']."'");
}
//===========================================================//
        if (!$query1)
		   {
		print "<font color=\"red\">Ops! Database Error, please try again!</font> ";
        die;
           } 
	    else
		 {
		print "<font color=\"green\">Wow, Your request was done!</font>";
        die;
}
}

function profile_basic() {
global $CONST_LINK_ROOT;

$adv_title=htmlentities(form_get('title'), ENT_QUOTES);
$mem_sex=form_get('sex');
$dob_day=form_get('dob_day');
$dob_month=form_get('dob_month');
$dob_year=form_get('dob_year');
$mem_city=htmlentities(form_get('city'), ENT_QUOTES);
$mem_state=htmlentities(form_get('state'), ENT_QUOTES);
$mem_country=form_get('country');
$mem_zipcode=form_get('zipcode');
$adv_marital=form_get('marital');
$seeking=$_REQUEST['seeking'];
$adv_religious=form_get('religious');
$adv_politicalview=htmlentities(form_get('politicalview'), ENT_QUOTES);

if (checkdate($dob_month, $dob_day, $dob_year))
{
$new_timestamp = mktime(0,0,0, $dob_month, $dob_day, $dob_year);
$dob = date("Y-m-d", $new_timestamp);
}

$adv_location=$mem_city .", ".$mem_state;

if ($seeking!='') {
$adv_seeking .= implode("|", $seeking);
}
		
		
$query1=mysql_query("UPDATE members, adverts set mem_sex='$mem_sex', mem_dob='$dob', mem_city='$mem_city', mem_state='$mem_state', mem_country='$mem_country', mem_zipcode='$mem_zipcode', adv_location='$adv_location', adv_countryid='$mem_country', adv_marital='$adv_marital', adv_religious='$adv_religious', adv_politicalview='$adv_politicalview', adv_seeking='$adv_seeking', adv_dob='$dob', adv_zipcode='$mem_zipcode', adv_title='$adv_title' where mem_userid=adv_userid and mem_userid='".$_REQUEST['user_id']."'");

//===========================================================//
        if (!$query1)
		   {
		print "<font color=\"red\">Ops! Database Error, please try again!</font> ";
        die;
           } 
	    else
		 {
		$RUser = mysql_fetch_object(mysql_query("SELECT mem_username, mem_profileid, mem_sex FROM members WHERE mem_userid='".$_REQUEST['user_id']."'"));
		if ($RUser->mem_profileid != null) { $male1_name1= $RUser->mem_profileid; }
		else { $male1_name1= $RUser->mem_username; }
		if($RUser->mem_sex=="F") $sex = "her"; else $sex = "his";
		$activityText ="edited ".$sex." <a href=\"".$CONST_LINK_ROOT."/".$male1_name1."\">Basic Information</a>.";
		$query2="INSERT INTO activities_user (userID, activityID, activityText) values ('".$_REQUEST['user_id']."', '1', '$activityText')";
		$result2=mysql_query($query2) or die(mysql_error());
		print "<font color=\"green\">Wow, Your request was done!</font>";
        die;
}

}

function profile_personal() {
global $CONST_LINK_ROOT;

$adv_children=form_get('children');
$adv_bodytype=form_get('bodytype');
$adv_height=form_get('height');
$adv_weight=form_get('weight');
$adv_eyecolor=form_get('eyecolor');
$adv_haircolor=form_get('haircolor');
$adv_smoker=form_get('smoker');
$adv_drink=form_get('drink');
$adv_interests=htmlentities(form_get('interests'), ENT_QUOTES);
$adv_favoritefood=htmlentities(form_get('favoritefood'), ENT_QUOTES);
$adv_sports=htmlentities(form_get('sports'), ENT_QUOTES);
$adv_movies=htmlentities(form_get('movies'), ENT_QUOTES);
$adv_music=htmlentities(form_get('music'), ENT_QUOTES);
$adv_books=htmlentities(form_get('books'), ENT_QUOTES);
$adv_tvshows=htmlentities(form_get('tvshows'), ENT_QUOTES);
$adv_games=htmlentities(form_get('games'), ENT_QUOTES);
$adv_comment=htmlentities(form_get('comment'), ENT_QUOTES);

$query1=mysql_query("UPDATE adverts set adv_children='$adv_children', adv_bodytype='$adv_bodytype', adv_height='$adv_height', adv_weight='$adv_weight', adv_eyecolor='$adv_eyecolor', adv_haircolor='$adv_haircolor', adv_smoker='$adv_smoker', adv_drink='$adv_drink', adv_interests='$adv_interests', adv_favoritefood='$adv_favoritefood', adv_sports='$adv_sports', adv_movies='$adv_movies', adv_music='$adv_music', adv_books='$adv_books', adv_tvshows='$adv_tvshows', adv_games='$adv_games', adv_comment='$adv_comment' where adv_userid='".$_REQUEST['user_id']."'");

//===========================================================//
        if (!$query1)
		   {
		print "<font color=\"red\">Ops! Database Error, please try again!</font> ";
        die;
           } 
	    else
		 {
		$RUser = mysql_fetch_object(mysql_query("SELECT mem_username, mem_profileid, mem_sex FROM members WHERE mem_userid='".$_REQUEST['user_id']."'"));
		if ($RUser->mem_profileid != null) { $male1_name1= $RUser->mem_profileid; }
		else { $male1_name1= $RUser->mem_username; }
		if($RUser->mem_sex=="F") $sex = "her"; else $sex = "his";
		$activityText ="edited ".$sex." <a href=\"".$CONST_LINK_ROOT."/".$male1_name1."\">Physical Information / Interests / Favorites</a>.";
		$query2="INSERT INTO activities_user (userID, activityID, activityText) values ('".$_REQUEST['user_id']."', '2', '$activityText')";
		$result2=mysql_query($query2) or die(mysql_error());
		print "<font color=\"green\">Wow, Your request was done!</font>";
        die;
}

}


function set_default ($pid, $WUserID){
		$picture=mysql_fetch_object(mysql_query("SELECT *, count(pic_id) as counter FROM pictures WHERE pic_userid='$WUserID' AND pic_default='Y'")) or die(mysql_error());
		if ($picture->counter=='0') {
			$query1="UPDATE pictures SET pic_default='Y', mod_date=NOW() WHERE pic_id='$pid' AND pic_userid='$WUserID'";
			$result1=mysql_query($query1) or die(mysql_error());
		} elseif ($picture->counter=='1') {
			if ($picture->pic_id <> $pid) {
			$query2="UPDATE pictures SET pic_default='N', mod_date=NOW() WHERE pic_userid = '$WUserID'";
			$result2=mysql_query($query2) or die(mysql_error());
			$query1="UPDATE pictures SET pic_default='Y', mod_date=NOW() WHERE pic_id='$pid' AND pic_userid='$WUserID'";
			$result1=mysql_query($query1) or die(mysql_error());
			}
		} else {
		$query2="UPDATE pictures SET pic_default='N', mod_date=NOW() WHERE pic_userid = '$WUserID'";
		$result2=mysql_query($query2) or die(mysql_error());
		$query1="UPDATE pictures SET pic_default='Y', mod_date=NOW() WHERE pic_id='$pid' AND pic_userid='$WUserID'";
		$result1=mysql_query($query1) or die(mysql_error());
		}
			
		return $result1;
}


function add_photos() {

	$WUserID = $_REQUEST['user_id'];

	$return = array('status' => '0');

	$WUsername = mysql_fetch_object(mysql_query("SELECT mem_username, mem_sex FROM members WHERE mem_userid=$WUserID"));

	$main_dir = "/home/wowdoyou/public_html/members";
	$member_dir = "/home/wowdoyou/public_html/members/".$WUsername->mem_username;
	$picture_dir = "/home/wowdoyou/public_html/members/".$WUsername->mem_username."/picture/"; // Directory for file storing

	checkfolder($member_dir);
	checkfolder($picture_dir);
	checkindex($main_dir,$member_dir);
	checkindex($main_dir,$picture_dir);
	
	foreach($_FILES as $k=>$name){
 		if (!$name['name']) continue;
		$return['file'][$k]['name'] = $name['name'];
		$return['file'][$k]['tmp_name'] = $name['tmp_name'];
		$return['file'][$k]['size'] = $name['size'];
		$return['file'][$k]['type'] = $name['type'];
		$return['file'][$k]['error'] = $name['error'];

		if (!isset($k) || !is_uploaded_file($name['tmp_name'])) {
			$error='Invalid Upload';
			$return = array_merge_recursive($return,  array( 'error' => $error));
		}
		if ( $name['size'] > 4 * 1024 * 1024)
		{
			$error= $name['name'] . ' is too large. Please upload only files smaller than 4Mb!';
			$return = array_merge_recursive($return,  array( 'error' => $error));
		}
		if (!($size = @getimagesize($name['tmp_name']) ) )
		{
			$error='Please upload only images, no other files are supported.';
			$return = array_merge_recursive($return,  array( 'error' => $error));
		}
		if (!in_array($size[2], array(1, 2, 3) ) )
		{
			$error='Please upload only images of type JPEG, GIF or PNG.';
			$return = array_merge_recursive($return,  array( 'error' => $error));
		}

		if ($error) {
			$return['status'] = '0';
			echo json_encode($return);
			die;
		} else {
			$return['status'] ='1';
			$filename = basename($name['name']);

        // Upload file or return error message information
        if(!move_uploaded_file($name['tmp_name'], $picture_dir.$filename))
		{
			$error  = "Could not upload file " .$name['tmp_name'];
			$return = array_merge_recursive($return,  array( 'error' => $error));
		}

		$a_filename = preg_split("/\./",$filename);
		$ext = end($a_filename);
		$newname = md5('wauhaha'.array_shift($a_filename));
		
		// Setting params array for thumbnail_generator 
		$params = array(array('size' => 604,
                          'file' => $picture_dir.$newname.".".$ext),
						  array('size' => 180,
                          'file' => $picture_dir.$newname.'_medium'.".".$ext),
						  array('size' => 170,
                          'file' => $picture_dir.$newname.'_pb'.".".$ext),
						  array('size' => 130,
                          'file' => $picture_dir.$newname.'_small'.".".$ext),
						  array('size' => 50,
                          'file' => $picture_dir.$newname.'_ps'.".".$ext));

    	if (thumbnail_generator($picture_dir.$filename, $params, $ext) == false)
        die("Error processing uploaded file {$filename}");

			unlink ($picture_dir.$filename);
		
		$pictures_query=mysql_query("SELECT * FROM pictures WHERE pic_userid='$WUserID' AND pic_picture='$newname'") or die(mysql_error());
		$pictures_TOTAL = mysql_num_rows($pictures_query);

		if($WUsername->mem_sex=="F") $sex = "her"; else $sex = "his";

		if ($pictures_TOTAL > 0) {
		$query="UPDATE pictures set mod_date=NOW() WHERE pic_userid='$WUserID' AND pic_picture='$newname'";
		$result=mysql_query($query) or die(mysql_error());
		$pid=mysql_insert_id();
		
		$activityText = "changed ".$sex." profile picture.";
		$query2="INSERT INTO activities_user (userID, activityID, activityText) values ('$WUserID', '3', '$activityText')";
		$result2=mysql_query($query2) or die(mysql_error());

		} else {
		$sql="Insert into pictures set pic_userid='$WUserID', pic_picture='$newname', ext='$ext', pic_private='N', pic_default='Y', pic_date=NOW(), approved='1'";
		$squery=mysql_query($sql);
		$pid=mysql_insert_id();
		
		$activityText = "changed  ".$sex." profile picture.";
		$query2="INSERT INTO activities_user (userID, activityID, activityText) values ('$WUserID', '3', '$activityText')";
		$result2=mysql_query($query2) or die(mysql_error());

		set_default($pid,$WUserID);
		}
		
			$success= $name['name'] . ' was uploaded to the folder!';
			$return = array_merge_recursive($return,  array( 'success' => $success));
			$return["src"] = $newname.'_pb'.".".$ext;
		}
	}

	
	echo json_encode($return);

}
function checkfolder($member_dir) {
	$return = array();
	clearstatcache();

	if (!is_dir($member_dir)) {
		$create_f1 = mkdir($member_dir, 0777, true);
		$chmod_f1 = chmod($member_dir, 0777);
	}

	$fileperms = substr(decoct( fileperms($member_dir) ), 1);
	if ($fileperms != "0777") {
		recursiveDelete($member_dir);
		$create_f2 = mkdir($member_dir, 0777, true);
		$chmod_f2 = chmod($member_dir, 0777);
	}

	if (!$create_f1 || !$create_f2) {
		$return = array_merge_recursive($return,  array( 'error' => 'Failed to create folder'));
	}
	if (!$chmod_f1 || !$chmod_f2) {
		$return = array_merge_recursive($return,  array( 'error' => 'Failed to chmod'));
	}
	return true;
}

function checkindex($source, $destination) {
	$return = array();
	$file = "index.php";

	if(!is_dir("$source/$file")) {
		if (!file_exists("$destination/$file")) {
		$copy_f1 = copy("$source/$file","$destination/$file");
		}
	} else {
		$return = array_merge_recursive($return,  array( 'error' => 'Is a directory, not a file.'));
	}
	if (!$copy_f1) {
		$return = array_merge_recursive($return,  array( 'error' => 'Failed to copy file'));
	}
	return true;
}

function recursiveDelete($str){
        if(is_file($str)){
            return @unlink($str);
        }
        elseif(is_dir($str)){
            $scan = glob(rtrim($str,'/').'/*');
            foreach($scan as $index=>$path){
                recursiveDelete($path);
            }
            return @rmdir($str);
        }
    }

function thumbnail_calcsize($w, $h, $square)
{
    if ($square < max($w, $h)) {
	$k = $square / max($w, $h);
	} else {
	$k = 1;
	}
    return array($w*$k, $h*$k);
}                            

function thumbnail_generator($srcfile, &$params, $ext)
{
    // getting source image size
    @list($w, $h) = getimagesize($srcfile);
    if ($w == false)
        return false;

    // checking params array 
    if (!(is_array($params)&&is_array($params[0])))
        return false;

     // Load
    $ext = strtolower($ext);
   
    if($ext=='jpg' || $ext=='jpeg')
       $src = imagecreatefromjpeg($srcfile);
    if($ext=='gif')
        $src = imagecreatefromgif($srcfile);
    if($ext=='png')
        $src = imagecreatefrompng($srcfile); 
		
		
    list($s1_w, $s1_h) = thumbnail_calcsize($w, $h, $params[0]['size']);

    // Create first thumbnail
    // Remember, first thumbnail should be largest thumbnail
    $img_s1 = imagecreatetruecolor($s1_w, $s1_h);
    if($ext=="png") {
            imagealphablending($img_s1, false);
            $colorTransparent = imagecolorallocatealpha($img_s1, 0, 0, 0, 127);
            imagefill($img_s1, 0, 0, $colorTransparent);
            imagesavealpha($img_s1, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($src);
            if ($trnprt_indx >= 0 && $trnprt_indx < 255) {
                //its transparent
                $trnprt_color = imagecolorsforindex($src, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($img_s1, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($img_s1, 0, 0, $trnprt_indx);
                imagecolortransparent($img_s1, $trnprt_indx);
            }
        }
	imagecopyresampled($img_s1, $src, 0, 0, 0, 0, $s1_w, $s1_h, $w, $h);
    imagedestroy($src); // Destroy source image 

    // Other thumbnails are just downscaled copies of the first one
    for($i=1; $i<sizeof($params); $i++)
    {
		if (($params[$i]['size'] == '50') || ($params[$i]['size'] == '170')) {
		if ($params[$i]['size'] < $w) {
		$thumbnail_width = $params[$i]['size'];
		} else {
			$thumbnail_width = $w;
		}
		
		if ($params[$i]['size'] < $h) {
		$thumbnail_height = $params[$i]['size'];
		} else {
			$thumbnail_height = $h;
		}

		$ratio_orig = $s1_w/$s1_h;
   
    	if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
       		$new_height = $thumbnail_width/$ratio_orig;
       		$new_width = $thumbnail_width;
		} else {
       		$new_width = $thumbnail_height*$ratio_orig;
			   $new_height = $thumbnail_height;
    	}
		$x_mid = $new_width/2;  //horizontal middle
    	$y_mid = $new_height/2; //vertical middle
   
		$process = imagecreatetruecolor(round($new_width), round($new_height));
	    imagecopyresampled($process, $img_s1, 0, 0, 0, 0, $new_width, $new_height, $s1_w, $s1_h);
        $img_cur = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
        if($ext=="png") {
            imagealphablending($img_cur, false);
            $colorTransparent = imagecolorallocatealpha($img_cur, 0, 0, 0, 127);
            imagefill($img_cur, 0, 0, $colorTransparent);
            imagesavealpha($img_cur, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($img_s1);
            if ($trnprt_indx >= 0) {
                //its transparent
                $trnprt_color = imagecolorsforindex($img_s1, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($img_cur, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($img_cur, 0, 0, $trnprt_indx);
                imagecolortransparent($img_cur, $trnprt_indx);
            }
        }
   
		imagecopyresampled($img_cur, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
		imagedestroy($process);
		} else {
        list($cur_w, $cur_h) = thumbnail_calcsize($w, $h, $params[$i]['size']);
        $img_cur = imagecreatetruecolor($cur_w, $cur_h);
        if($ext=="png") {
            imagealphablending($img_cur, false);
            $colorTransparent = imagecolorallocatealpha($img_cur, 0, 0, 0, 127);
            imagefill($img_cur, 0, 0, $colorTransparent);
            imagesavealpha($img_cur, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($img_s1);
            if ($trnprt_indx >= 0) {
                //its transparent
                $trnprt_color = imagecolorsforindex($img_s1, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($img_cur, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($img_cur, 0, 0, $trnprt_indx);
                imagecolortransparent($img_cur, $trnprt_indx);
            }
        }
			imagecopyresampled($img_cur, $img_s1, 0, 0, 0, 0, $cur_w, $cur_h, $s1_w, $s1_h);
		}
        
		if($ext=='jpg' || $ext=='jpeg')
		imagejpeg($img_cur, $params[$i]['file'], 90);
		if($ext=='gif')
		imagegif($img_cur, $params[$i]['file']);
		if($ext=='png')
		imagepng($img_cur, $params[$i]['file'], 9);

        imagedestroy($img_cur);
    }

    // Saving first thumbnail 
    if($ext=='jpg' || $ext=='jpeg')
	imagejpeg($img_s1, $params[0]['file'], 90);
	if($ext=='gif')
	imagegif($img_s1, $params[0]['file']);
	if($ext=='png')
	imagepng($img_s1, $params[0]['file'], 9);
		
    imagedestroy($img_s1);
    return true;
}

?>
