<?php
include("includes/site_info.php");
include('session_handler.inc');
	
	switch ($_REQUEST["Submit"]) {
	case "edit_delete"; 
		edit_delete();
		break;
	case "edit_note"; 
		edit_note();
		break;
	case "add_note"; 
		add_note();
		break;
	default; 
		echo "";
		break;
	}
function delete_image ($url, $filename, $ext) {
	if (file_exists($url.$filename.".".$ext)) {
    	unlink ($url.$filename.".".$ext);
	} 
	if (file_exists($url.$filename."_med.".$ext)) {
    	unlink ($url.$filename."_med.".$ext);
	}
	if (file_exists($url.$filename."_small.".$ext)) {
    	unlink ($url.$filename."_small.".$ext);
	}
		return;
}

function edit_delete() {
	$WUserID = $_REQUEST['userid'];
	$articleid = $_REQUEST['articleid'];

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

	$WUsername = mysql_fetch_object(mysql_query("SELECT mem_username FROM members WHERE mem_userid=$WUserID"));
	$article_dir = "/home/wauhaha/public_html/members/".$WUsername->mem_username."/article/"; // Directory for file storing

	$article_query=mysql_query("SELECT * FROM articles WHERE art_userid = '$WUserID' AND art_id='$articleid'") or die(mysql_error());
	$article_TOTAL = mysql_num_rows($article_query);

	if ($article_TOTAL < 1) {
		$error  = "Database error!";
		$return = array_merge_recursive($return,  array( 'error' => $error));
		echo json_encode($return);
		die;
	}
	
	$article= mysql_fetch_object($article_query);
	if ($article->art_picture) delete_image($article_dir,$article->art_picture ,$article->art_ext);

	$query="DELETE FROM articles WHERE art_userid = '$WUserID' AND art_id='$articleid'";
	$result=mysql_query($query) or die(mysql_error());

	if (!$result) {
		$return['status'] ='0';
		$error  = "Database error!";
		$return = array_merge_recursive($return,  array( 'error' => $error));
		echo json_encode($return);
		die;
	}

	$return['status'] ='1';
	$return = array_merge_recursive($return,  array( 'success' => 'Your note was successfully deleted!'));
	
	echo json_encode($return);
}

function edit_note() {
	$WUserID = $_REQUEST['userid'];
	$articleid = $_REQUEST['articleid'];
	$title = htmlspecialchars($_REQUEST['title'], ENT_QUOTES);
	$txtArticle = htmlspecialchars($_REQUEST['txtArticle'], ENT_QUOTES);
	$tags = $_REQUEST['tags'];
	$private = $_REQUEST['privacy'];
	$delete = $_REQUEST['delete'];

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

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

	$main_dir = "/home/wauhaha/public_html/members";
	$member_dir = "/home/wauhaha/public_html/members/".$WUsername->mem_username;
	$article_dir = "/home/wauhaha/public_html/members/".$WUsername->mem_username."/article/"; // Directory for file storing

	checkfolder($member_dir);
	checkfolder($article_dir);
	checkindex($main_dir,$member_dir);
	checkindex($main_dir,$article_dir);
	
	$article_query=mysql_query("SELECT * FROM articles WHERE art_userid = '$WUserID' AND art_id='$articleid'") or die(mysql_error());
	$article_TOTAL = mysql_num_rows($article_query);

	if ($article_TOTAL < 1) {
		$error  = "Database error!";
		$return = array_merge_recursive($return,  array( 'error' => $error));
		echo json_encode($return);
		die;
	}
	
	if (isset($delete) && ($delete==1)) {
		$article= mysql_fetch_object($article_query);
		if ($article->art_picture) delete_image($article_dir,$article->art_picture ,$article->art_ext);
		$query="DELETE FROM articles WHERE art_userid = '$WUserID' AND art_id='$articleid'";
		$result=mysql_query($query) or die(mysql_error());
		$return['status'] ='2';
		$return = array_merge_recursive($return,  array( 'success' => 'Your note was successfully deleted!'));
		echo json_encode($return);
		die;
	} 

	$sql="UPDATE articles SET art_title='$title', art_message='$txtArticle', art_tags='$tags', art_private='$private', art_approved='Y' WHERE  art_userid='$WUserID' AND art_id='$articleid'";
	$squery=mysql_query($sql) or die(mysql_error());

	if (!$squery) {
		$return['status'] ='0';
		$error  = "Database error!";
		$return = array_merge_recursive($return,  array( 'error' => $error));
		echo json_encode($return);
		die;
	}

	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']);

		$article= mysql_fetch_object($article_query);
		if ($article->art_picture) delete_image($article_dir,$article->art_picture ,$article->art_ext);

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

		$a_filename = preg_split("/\./",$filename);
		$ext = end($a_filename);
		$newname = md5('wauhaha'.$articleid);
		
		$query="UPDATE articles SET art_picture='$newname', art_ext='$ext'  WHERE art_userid='$WUserID' AND art_id='$articleid'";
		$result=mysql_query($query) or die(mysql_error());

		if (!$result) {
			$return['status'] ='0';
			$error  = "Database error!";
			$return = array_merge_recursive($return,  array( 'error' => $error));
			echo json_encode($return);
			die;
		}

		// Setting params array for thumbnail_generator 
		$params = array(array('size' => 604,
                          'file' => $article_dir.$newname.".".$ext),
						  array('size' => 130,
                          'file' => $article_dir.$newname.'_med'.".".$ext),
						  array('size' => 50,
                          'file' => $article_dir.$newname.'_small'.".".$ext));

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

			unlink ($article_dir.$filename);

			$success= $name['name'] . ' was uploaded to the folder!';
			$return = array_merge_recursive($return,  array( 'success' => $success));
		}
	}
	
	$return['status'] ='1';
	$return = array_merge_recursive($return,  array( 'success' => 'Your note was submitted to the system!'));
	echo json_encode($return);

}

function add_note() {
	$WUserID = $_REQUEST['userid'];
	$title = htmlspecialchars($_REQUEST['title'], ENT_QUOTES);
	$txtArticle = htmlentities($_REQUEST['txtArticle'], ENT_QUOTES);
	$tags = $_REQUEST['tags'];
	$private = $_REQUEST['privacy'];

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

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

	$main_dir = "/home/wauhaha/public_html/members";
	$member_dir = "/home/wauhaha/public_html/members/".$WUsername->mem_username;
	$article_dir = "/home/wauhaha/public_html/members/".$WUsername->mem_username."/article/"; // Directory for file storing

	checkfolder($member_dir);
	checkfolder($article_dir);
	checkindex($main_dir,$member_dir);
	checkindex($main_dir,$article_dir);

	$sql="Insert into articles set art_userid='$WUserID', art_title='$title', art_message='$txtArticle', art_tags='$tags', art_private='$private', art_approved='Y'";
	$squery=mysql_query($sql);
	$aid=mysql_insert_id();

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

	$activityText = "added a note with title <a href=\"$CONST_LINK_ROOT/home.php#mshownote?tab=thought&aid=$aid&uID=$WUserID\" >".ucwords($title)."</a>.";
	$query2="INSERT INTO activities_user (userID, activityID, activityText) values ('$WUserID', '9', '$activityText')";
	$result2=mysql_query($query2) or die(mysql_error());

	$return['url'] = $aid;

	if (!$squery) {
		$return['status'] = '0';
		$error  = "Database error!";
		$return = array_merge_recursive($return,  array( 'error' => $error));
		echo json_encode($return);
		die;
	}
	
	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'], $article_dir.$filename))
		{
			$return['status'] = '0';
			$error  = "Could not upload file " .$name['tmp_name'];
			$return = array_merge_recursive($return,  array( 'error' => $error));
			echo json_encode($return);
			die;
		}

		$a_filename = preg_split("/\./",$filename);
		$ext = end($a_filename);
		$newname = md5('wauhaha'.$aid);
		
		$query="UPDATE articles SET art_picture='$newname', art_ext='$ext'  WHERE art_userid='$WUserID' AND art_id='$aid'";
		$result=mysql_query($query) or die(mysql_error());

		if (!$result) {
			$return['status'] = '0';
			$error  = "Database error!";
			$return = array_merge_recursive($return,  array( 'error' => $error));
			echo json_encode($return);
			die;
		}

		// Setting params array for thumbnail_generator 
		$params = array(array('size' => 604,
                          'file' => $article_dir.$newname.".".$ext),
						  array('size' => 130,
                          'file' => $article_dir.$newname.'_med'.".".$ext),
						  array('size' => 50,
                          'file' => $article_dir.$newname.'_small'.".".$ext));

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

			unlink ($article_dir.$filename);

			$success= $name['name'] . ' was uploaded to the folder!';
			$return = array_merge_recursive($return,  array( 'success' => $success));
		}
	}
	
	$return['status'] = '1';
	$return = array_merge_recursive($return,  array( 'success' => 'Your note was submitted to the system!'));
	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')) {
		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;
}
?>
