<?php

// site includes
require_once('../../../../core/includes/master.inc.php');

// csaKey1 & csaKey2 keys (cross site security)
$data = crossSiteAction::getData($_REQUEST['csaKey1'], $_REQUEST['csaKey2']);
if(!$data)
{
	// exit
    coreFunctions::output404();
}

// clear the csaKey data since we don't need it after here
crossSiteAction::deleteData($_REQUEST['csaKey1'], $_REQUEST['csaKey2']);

// load the user id of the cross site request
$_logged_in_user_id = (int)$data['_logged_in_user_id'];

//setup database
$db = Database::getDatabase();

// load files and check ownership
$fileId = (int)$_REQUEST['fileId'];
$dir    = trim($_REQUEST['dir']);
if(!in_array($dir, array('r', 'l')))
{
	// exit
    coreFunctions::output404();
}

// make sure the logged in user owns the files
$file = file::loadById($fileId);
if ($file->userId != $_logged_in_user_id)
{
    // exit
    coreFunctions::output404();
}

if (_CONFIG_DEMO_MODE == true)
{
    notification::setError(t("no_changes_in_demo_mode"));
}

// no errors
if (!notification::isErrors())
{
	// get image viewer object
	$imageViewerObj = pluginHelper::getInstance('imageviewer');

    // rotate image
	$imageViewerObj->rotateImage($file, $dir);
	
	// remove image cache
	$imageViewerObj->deleteImageCache($file->id, true);
}

// prepare result
$returnJson            = array();
$returnJson['success'] = false;
$returnJson['msg']     = t("problem_updating_item", "There was a problem updating the item, please try again later.");
if (notification::isErrors())
{
    // error
    $returnJson['success'] = false;
    $returnJson['msg']     = implode('<br/>', notification::getErrors());
}
else
{
    // success
    $returnJson['success'] = true;
    $returnJson['msg']     = implode('<br/>', notification::getSuccess());
}

echo json_encode($returnJson);