<?php
include("includes/site_info.php");
session_cache_limiter('private, must-revalidate');
session_start();
error_reporting(0);
include_once __INCLUDE_CLASS_PATH."/class.ItemManager.php";
$option_manager = new OptionManager();
$email_confirm=$option_manager->GetValue('email_confirm');
$CONST_MAIL = $option_manager->GetValue('mail'); 
$CONST_SUPPMAIL = $option_manager->GetValue('suppmail'); 

include_once __INCLUDE_CLASS_PATH."/class.DB.php";
$db = new DB();

include('functions.php');
include('lib/lib.Functions.php');

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;
}
$_SESSION["reg_post1"]["error"] = '';
$_SESSION["reg_post2"] = $_POST;

$error_msg = "";
if ($_SESSION["reg_post1"]) {
	foreach($_SESSION["reg_post1"] as $field=>$data)
	{ 
		if (($field=="WUsername") || ($field=="WRPassword") || ($field=="WAuthEmail") || ($field=="WMyMobileCode2") || ($field=="WMyMobile")) {
		if (isset($data) && !empty($data)) {
			if($field=="WUsername") {
				$count = mysql_num_rows(mysql_query("SELECT * FROM `members` WHERE `mem_username`='".$data."'"));
				if($count > 0) {
					$error_msg .= "This username already exists, please try another one.<br>";
					$continue = "false";
				}
				if(!preg_match("/^[a-zA-Z0-9]+$/", $data)) {
					$error_msg .= "Limit to Alphanumeric character set only.<br>";
					$continue = "false";
				}
			}
			
			if($field=="WAuthEmail") {
				$count = mysql_num_rows(mysql_query("SELECT * FROM `members` WHERE `mem_email`='".$data."'"));
				if(!ereg( "^[-a-zA-Z0-9_\\.]+\\@([0-9A-Za-z][0-9A-Za-z-]+\\.)+[A-Za-z]{2,5}\$", $data)) {
					$error_msg .= "Invalid  Authorize Email!<br>";
					$continue = "false";
				}
				if($count > 0) {
					$error_msg .= "This Email already exists, please try another one.<br>";
					$continue = "false";
				}
			}
		} //end of if $data validate
		else {
			$error_msg .= "Please fill in $field.<br>";
			$continue = "false";
		}
		} //end of if $field validate
	}//end of foreach
}//end of if $_SESSION["reg_post1"]
else {
			$error_msg .= "Please fill in all field.<br>";
			$continue = "false";
}//end of if $_SESSION["reg_post1"]

if ($continue=="false") {
	$_SESSION["reg_post1"]["error"] = $error_msg;
	print "<script>location.href='$CONST_LINK_ROOT/register1.php?error_msg=error'</script>";
			die;
}

 $WVCode=$_REQUEST['WVCode'];
 if (md5($WVCode) != $_SESSION['image_random_value']) {
			print "<script>location.href='$CONST_LINK_ROOT/register2.php?error_msg=Invalid_Verification_Code'</script>";
			die;
	}


$client_ip = $_SERVER["REMOTE_ADDR"]." ".$_SERVER["HTTP_X_FORWARDED_FOR"];

if($_SESSION['lang_id']=='') $lang_id= $CONST_DEFAULT_LANGUAGE;
if($_SESSION['lang_id']!='') $lang_id= $_SESSION['lang_id'];

$WUsername=$_SESSION['reg_post1']['WUsername'];
$WPassword=md5($_SESSION['reg_post1']['WRPassword']);
$WAuthEmail=$_SESSION['reg_post1']['WAuthEmail'];
$WMyMobile=$_SESSION['reg_post1']['WMyMobileCode2'].$_SESSION['reg_post1']['WMyMobile'];
$WNickname=$_SESSION['reg_post1']['WNickname'];

$facebook_uid=$_REQUEST['facebook_uid'];
$WFullname=form_get('WFullname');
$WDay=form_get('WDay');
$WMonth=form_get('WMonth');
$WYear=form_get('WYear');
$WGender=form_get('WGender');
$WCountry=$_REQUEST['WCountry'];
$WState=$_REQUEST['WState'];
$WCity=$_REQUEST['WCity'];
//$WTown=$_REQUEST['WTown'];
$WPostcode=$_REQUEST['WPostcode'];
$WIntroducer=form_get('WMobileCode2').form_get('WIntroducer');

if (isset($WIntroducer) && !empty($WIntroducer)) {
    $q_refer = $db->get_row("SELECT * FROM members WHERE mem_mobile = '$WIntroducer'");
	$referrer = $q_refer->mem_userid;
}

$expdate=mktime (date("H"),date("i"),date("s"),date("m") ,date("d")-1,date("Y")+1);
$expiredate=date("Y-m-d H:i:s", $expdate);

if (checkdate($WMonth, $WDay, $WYear))
{
$new_timestamp = mktime(0,0,0, $WMonth, $WDay, $WYear);
$dob = date("Y-m-d", $new_timestamp);
}

$tempDate=date("Y-m-d H:i:s");
 
//$txtLocation=$_REQUEST['WTown'] .", ". $_REQUEST['WCity'] .", ". $_REQUEST['WState'];
$txtLocation=$_REQUEST['WCity'] .", ". $_REQUEST['WState'];

$q_country = $db->get_row("select CountryId from Geo_Countries where Country ='$WCountry'");
$WCountryId = $q_country->CountryId;

$mem_referCode = md5("wauhaha".$WUsername.date(c));

//$query1="INSERT INTO members(mem_referCode, mem_username, mem_fullname, mem_password, mem_expiredate, mem_email, mem_joindate, mem_sex, mem_dob, mem_mobile, mem_lastvisit, mem_update, mem_type, mem_referrer, mem_town, mem_city, mem_state, mem_country, mem_ip, lang_id, mem_confirm) VALUES ('$mem_referCode', '$WUsername', '$WFullname', '$WPassword', '$expiredate', '$WAuthEmail', '$tempDate', '$WGender', '$dob', '$WMyMobile', '$tempDate', 0, 'U', '$referrer', '$WTown', '$WCity', '$WState', '$WCountryId', '$client_ip', '$lang_id', ".($email_confirm == 'Y' ? 0 : 1).")";
$query1="INSERT INTO members(mem_referCode, mem_username, mem_nickname, mem_fullname, mem_password, mem_expiredate, mem_email, mem_joindate, mem_sex, mem_dob, mem_mobile, mem_lastvisit, mem_update, mem_type, mem_referrer, mem_city, mem_state, mem_country, mem_ip, lang_id, mem_confirm) VALUES ('$mem_referCode', '$WUsername', '$WNickname', '$WFullname', '$WPassword', '$expiredate', '$WAuthEmail', '$tempDate', '$WGender', '$dob', '$WMyMobile', '$tempDate', 0, 'U', '$referrer', '$WCity', '$WState', '$WCountryId', '$client_ip', '$lang_id', ".($email_confirm == 'Y' ? 0 : 1).")";

//===========================================================//
        if (!mysql_query($query1))
		   {

			print "<script>location.href='$CONST_LINK_ROOT/register1.php?error_msg=Database_Error'</script>";

           } 
	    else
		 {
                $mem_id=mysql_insert_id();
                $_SESSION['Sess_JustRegistered']=true;

                $_SESSION['Sess_UserType']="U";

                $_SESSION['Sess_UserName']=$WUsername;

                $_SESSION['Sess_UserId']=$mem_id;

                $Sess_UserId=$mem_id;
								
				$time=time();
				$q = "REPLACE INTO active_users VALUES ('$Sess_UserId','$WUsername', '$time')";
				mysql_query($q);
				
        if (isset($referrer) && !empty($referrer)) {
		   $network = $db->get_row("SELECT stat FROM networkinvite WHERE Email='$WAuthEmail' and inv_id='".$_SESSION["inv_id"]."'");
			if ($network->stat =='p') {
        $db->query("UPDATE networkinvite set stat='f' where Email='$WAuthEmail' and inv_id='".$_SESSION["inv_id"]."'");
			}
			
			$row = $db->get_row("SELECT A.uid,B.friend_uid FROM my_friends A LEFT JOIN my_friends B ON (A.uid=B.friend_uid AND B.uid=A.friend_uid) WHERE (A.uid = '$referrer' AND A.friend_uid = '$Sess_UserId') OR (A.friend_uid = '$referrer' AND A.uid = '$Sess_UserId')");
        if (!$row->uid && !$row->friend_uid) {
        $db->query("INSERT INTO my_friends SET
                             uid = '$referrer',
                             friend_uid = '$Sess_UserId',
                              approved  = '1'
                    ");
            $db->query("INSERT INTO my_friends SET
                                 uid = '$Sess_UserId',
                                 friend_uid = '$referrer',
                              approved  = '1'
                         ");

         $oTo = $db->get_row("SELECT * FROM members WHERE mem_userid = '$referrer'");
$data['ReceiverName'] = $oTo->mem_username;
        $data['Member']   = $WUsername;
        $data['Url'] = $CONST_URL;
        $data['SupportEmail'] = $CONST_SUPPMAIL;
        list($type,$message) = getTemplateByName("myReferrer",$data,getDefaultLanguage($referrer));
        send_mail ($oTo->mem_email, $CONST_MAIL, "$CONST_COMPANY ".PRGAUTHREF_APR, $message ,$type,"ON");
     }
	 }
				   
                $query="SELECT mem_userid, mem_dob, mem_username, mem_sex, mem_expiredate FROM members WHERE mem_userid = '$Sess_UserId'";
				$result=mysql_query($query);

                        $sql_array=mysql_fetch_object($result);

                        $tempdob=$sql_array->mem_dob;

                        $tempusername=$sql_array->mem_username;

                        $tempid=$sql_array->mem_userid;

                        $tempexpire=$sql_array->mem_expiredate;
		   
                                if ($WGender=='M') {$pictureS='images/hahaper_ms.jpg'; $pictureB='images/hahaper_m.jpg';}

                                if ($WGender=='F') {$pictureS='images/hahaper_fs.jpg';$pictureB='images/hahaper_f.jpg';}

                                if ($WGender=='C') {$pictureS='images/hahaper_cs.jpg';$pictureB='images/hahaper_c.jpg';}
						
//                $query="INSERT INTO adverts (adv_zipcode, adv_userid, adv_username, adv_dob, adv_countryid, adv_location, adv_picture, adv_pic_full, adv_imageappr, adv_createdate, adv_approved, adv_expiredate, adv_ip) VALUES ('$WPostcode', '$tempid', '$tempusername', '$tempdob', '$WCountryId','$txtLocation', '$pictureS', '$pictureB',  '1', '$tempDate', '1', '$tempexpire','$client_ip')";
                $query="INSERT INTO adverts (adv_zipcode, adv_userid, adv_username, adv_dob, adv_countryid, adv_location, adv_picture, adv_pic_full, adv_imageappr, adv_createdate, adv_approved, adv_expiredate, adv_ip) VALUES ('$WPostcode', '$tempid', '$tempusername', '$tempdob', '$WCountryId','$txtLocation', '$pictureS', '$pictureB',  '1', '$tempDate', '1', '$tempexpire','$client_ip')";
			
				
$memCount=mysql_query("SELECT * from member_stats where statDate=CURDATE()");
		if(mysql_num_rows($memCount) > 0){
mysql_query("UPDATE member_stats set counter_sign=counter_sign+1 where statDate=CURDATE()");	
		}else{
mysql_query("INSERT into member_stats set counter_sign=counter_sign+1, statDate=CURDATE()");	
		}
	
 			 	mysql_query($query) or die(mysql_error());
				
				if (isset($facebook_uid) && !empty($facebook_uid)) {
						$main_dir = "/home/wauhaha/public_html/members";
						$member_dir = "/home/wauhaha/public_html/members/".$sql_array->mem_username;
						$picture_dir = "/home/wauhaha/public_html/members/".$sql_array->mem_username."/picture/"; // Directory for file storing
						
						checkfolder($member_dir);
						checkfolder($picture_dir);
						checkindex($main_dir,$member_dir);
						checkindex($main_dir,$picture_dir);
						
						$newname = md5('wauhaha'.$sql_array->mem_username);
						$ext = "jpg";
						
						$contents= file_get_contents("http://graph.facebook.com/$facebook_uid/picture?type=large");
						$im = imagecreatefromstring($contents);
						$fullpath = $picture_dir.$newname."_ori.jpg";
						if ($im !== false) {
							if(file_exists($fullpath)){
								unlink($fullpath);
							}
    						imagejpeg($im, $fullpath, 100);
    						imagedestroy($im);
						}else {
    						echo 'An error occurred.';
						}

						$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($fullpath, $params, $ext) == false)
        die("Error processing uploaded file {$filename}");

			unlink ($fullpath);

		$sql="Insert into pictures set pic_userid='$tempid', pic_picture='$newname', ext='$ext', pic_private='N', pic_default='Y', pic_date=NOW(), approved='1'";
		$squery=mysql_query($sql);
						}


            unset($_SESSION["reg_post1"]);
            unset($_SESSION["reg_post2"]);
				unset($_SESSION["referid"]);
				unset($_SESSION["inv_id"]);
				unset($_SESSION["ref_id"]);
			

		print "<script>location.href='$CONST_LINK_ROOT/register_complete.php'</script>";
                exit;

}
?>
