<?php
include $_SERVER['DOCUMENT_ROOT'].'/inc/login.php';
include $_SERVER['DOCUMENT_ROOT'].'/inc/config.php';
if ($my_id) {
    $uploadDir = '/uploads/';
    $saveDir = '/photo/';
    $fileTypes = array('jpg', 'jpeg');

    if ($_POST['token'] == md5($my_id.'_messages_'.$secret)) {
        $tempFile   = $_FILES['Filedata']['tmp_name'];
        $uploadDir  = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
        $saveDir  = $_SERVER['DOCUMENT_ROOT'] . $saveDir;

        $fileParts = pathinfo($_FILES['Filedata']['name']);
        if (in_array(strtolower($fileParts['extension']), $fileTypes)) {
            $rand = rand(1000000, 9999999);
            $targetFile = $uploadDir . $rand . '.jpg';
            move_uploaded_file($tempFile, $targetFile);
            include $_SERVER['DOCUMENT_ROOT'].'/inc/sql_social.php';
            $saveFile = $saveDir . $rand . '.jpg';
            $saveFileMini = $saveDir . 'm_' . $rand . '.jpg';
            
            $im = imagecreatefromjpeg($targetFile);
            list($w,$h) = getimagesize($targetFile);
            $koe=$w/600;
            $new_h=ceil($h/$koe);
            $im1 = imagecreatetruecolor(600, $new_h); 
            imagecopyresampled($im1,$im,0,0,0,0,600,$new_h,imagesx($im),imagesy($im));  
            imagejpeg($im1, $saveFile, 100);
            imagedestroy($im); 
            imagedestroy($im1);
            
            $save_h = $new_h;
            
            if ($h>$w) {
                $im = imagecreatefromjpeg($targetFile);
                list($w,$h) = getimagesize($targetFile);
                $koe=$w/200;
                $new_h=ceil($h/$koe);
                $im1 = imagecreatetruecolor(200, $new_h); 
                imagecopyresampled($im1,$im,0,0,0,0,200,$new_h,imagesx($im),imagesy($im));  
                imagejpeg($im1, $saveFileMini, 200);
                imagedestroy($im); 
                imagedestroy($im1);
            } else {
                $im = imagecreatefromjpeg($targetFile);
                list($w,$h) = getimagesize($targetFile);
                $koe=$h/200;
                $new_w=ceil($w/$koe);
                $im1 = imagecreatetruecolor($new_w, 200); 
                imagecopyresampled($im1,$im,0,0,0,0,$new_w,200,imagesx($im),imagesy($im));  
                imagejpeg($im1, $saveFileMini, 200);
                imagedestroy($im); 
                imagedestroy($im1);
            }
            
            unlink($targetFile);
            
            $date = date('U');
            mysql_query("INSERT photo_to_users SET user_id='$my_id', photo_name='$rand', width='600', height='$save_h', date='$date', photo_type='3'");
            mysql_close($msconnect);
            echo $rand;
        } else {
            echo 'Invalid file type.';
        }
    } else {
        echo 0;
    }
}
?>