<?php

/* 
	Engine: Social Plus
	e-mail: dobriisasa@gmail.com
	Copyright: Алех Доброволский
	All rights reserved.
*/



// engine file
require_once('../../inc/_core.php');


try {
	// build engine
	$core = new _SOCIALPLUS;

} catch (Exception $e) {
	print $e->getMessage();
}


//define variables
$albid = '0';
$count   = 0;
$message = $CreatedImage = $fileSize = $injectPhotos = "";
// upload
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
 

  
    $max_file_size = 1048576 * $core->settings['MAX_FILE_UPLOAD'];
    $dir = __ROOT__.$core->settings['AT_OUTPUT_DIR'].$core->USER['id'].'/';



    // generate dir by user id
    if (!file_exists($dir))
    mkdir($dir, 0777, true);


    // Loop $_FILES to execute all files
    foreach ($_FILES['files']['name'] as $f => $name) {
        if ($_FILES['files']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }
        if ($_FILES['files']['error'][$f] == 0) {
            if ($_FILES['files']['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            } elseif (!in_array(pathinfo(strtolower($name), PATHINFO_EXTENSION), $core->settings['VALID_FORMATS'])) {
                $message[] = "$name is not a valid format, only " . $core->settings['VALID_FORMATS'][1];
                continue; // Skip invalid file formats
                
            } else {
                $fileN = $_FILES['files']['name'][$f];
                $temp    = explode('.', $fileN);
		$fileExt = end($temp);
                $newName = basename($core->USER['id'].'_'.rand(0, 999999999999999) . rand(0, 999999999999999) . rand(0, 999999999999999) . '.' . $fileExt);
		$mainImage = $dir . $newName;

                // No error found! Move uploaded files 
                if (move_uploaded_file($_FILES["files"]["tmp_name"][$f], $mainImage)) {
                    $count++; // Number of successfully uploaded files


        $fileSize = filesize($mainImage);
	//Let's check allowed $ImageType, we use PHP SWITCH statement here
	switch(strtolower($_FILES['files']['type'][$f]))
	{
		case 'image/png':
			//Create a new image from file 
			$CreatedImage = imagecreatefrompng($mainImage);
			break;
		case 'image/gif':
			$CreatedImage = imagecreatefromgif($mainImage);
			break;			
		case 'image/jpeg':
		case 'image/pjpeg':
		case 'image/jpg':
			$CreatedImage = imagecreatefromjpeg($mainImage);
			break;
		default:
			$core->dieErr(['response' => 'Unsupported File!']); //output error and exit
	}
			list($CurWidth,$CurHeight)=getimagesize($mainImage);

		    $toUser = isset($_POST['to']) && (int)$_POST['to'] > 0 ? $core->test_input($_POST['to']) : '0';
                    $userid = $core->USER['id'];
                    $name_m   = $_FILES["files"]["name"][$f];
		    $photoId = $core->query_insert("insert into ".tbl_attach." set `userid`='$userid',`filename` = '$newName', `added`='".time()."', `file_size`='$fileSize', `sended_to`='$toUser'");

                    if (!$photoId) {
                        @unlink($mainImage);
                        $message[] = "Error! [ Connect to database ], the file have been deleted, please try again.";
                    } 
                    
                    
                }
            }
        }
    }

if ($message) {
    
    ////foreach ($message as $msg)
        //echo $msg;
    echo json_encode($message);
} else
    echo json_encode(array("status" => "OK", "photoid" => $photoId, "filename" => $newName, "userid" => $userid, "added" => time(), "size" => $fileSize));


}


?>