<?php
    require_once('include/functions/image_upload.php');
    require_once('include/functions/image_directory.php');
    
    $_back = isset($_GET['b']) ? str_replace('@', '&', trim(strval($_GET['b']))) : 's=home';
    $_degrees = isset($_GET['degrees']) ? intval($_GET['degrees']) : 0;
    $_id = isset($_GET['i']) ? intval($_GET['i']) : 0;
    
    if ($_degrees != 90 && $_degrees != 180 && $_degrees != 270)
    {
        make_cookie('notice', 'Please stop playing with our scripts!');
        header('Location: ./?s=home');
        die;
    }
    
    $_degrees = 360 - $_degrees;
    
    if ($GLOBALS['auth']['rotate'])
    {
        $images = mysqli_query_logged("SELECT * FROM images WHERE id = " . sq($_id));
        if ($images_row = mysqli_fetch_assoc($images))
        {
            $binaries = mysqli_query_logged("SELECT * FROM z_" . binaries_path($images_row['id']) . " WHERE image_id = '" . $images_row['id'] . "'");
            if ($binaries_row = mysqli_fetch_assoc($binaries))
            {
                if ($images_row['height'] < 160 && ($_degrees == 90 || $_degrees == 270))
                {
                    make_cookie('notice', 'This image can\'t be rotated.');
                    header('Location: ./?' . $_back);
                    die;
                }
                if (!$convert = @imagecreatefromstring($binaries_row['full']))
                {
                    make_cookie('notice', 'This image can\'t be rotated.');
                    header('Location: ./?' . $_back);
                    die;
                }
                mysqli_query_logged("INSERT INTO z_rotate SET posted_on = NOW(), image_id = '" . $binaries_row['image_id'] . "', full = '" . addslashes($binaries_row['full']) . "', thumb = '" . addslashes($binaries_row['thumb']) . "', original = '" . addslashes($binaries_row['original']) . "'");
                $handle = imagecreatefromstring($binaries_row['full']);
                $handle = imagerotate($handle, $_degrees, 0);
                $shrink_size = shrink_image($handle, '', $images_row['file_type'], IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT, $images_row['id'], 1);
                $thumb_size = thumb_image($handle, $images_row['file_type'], THUMB_WIDTH, THUMB_HEIGHT, $images_row['id']);
                if ($_degrees == 90 || $_degrees == 270)
                {
                    mysqli_query_logged("UPDATE images SET height = '" . $images_row['width'] . "', width = '" . $images_row['height'] . "' WHERE id = '" . $images_row['id'] . "'");
                }
                make_cookie('notice', 'Rotated.');
            }
        }
    }
    
    header('Location: ./?' . $_back . '&rand=1');
    die;    
?>