<?php

// We need the ABSPATH
if (!defined('ABSPATH')) exit;

// Handle AJAX functions

// Is the nonce there ?
if(empty($_REQUEST['sitepad_nonce'])){
	return;
}

// Switch Language
add_action( 'wp_ajax_change_lang', 'change_lang' );
//add_action( 'wp_ajax_nopriv_change_lang', 'change_lang' );
function change_lang() {
	
	// Some AJAX security
	check_ajax_referer('sitepad_ajax', 'sitepad_nonce');
	
	if(!is_super_admin()){
		die();
	}
	
	$lang = optGET('sitepad_lang');
	update_option('WPLANG', $lang );
	// Switch translation in case WPLANG was changed.
	$language = get_option( 'WPLANG' );
	if ( $language ) {
		load_default_textdomain( $language );
	} else {
		unload_textdomain( 'default' );
	}
	
	// Update the language preference for SitePad editor
	die('done'); // this is required to terminate immediately as this is just an ajax call

}

// The ajax handler
add_action('wp_ajax_sitepad_save_screenshot', 'sitepad_save_screenshot');
function sitepad_save_screenshot(){

	global $sitepad;

	// Some AJAX security
	check_ajax_referer('sitepad_ajax', 'sitepad_nonce');
	
	$postID = optREQ('postID');
	$post_name = $_POST['post_name'];
	$data = $_POST['image'];
	$data = substr($data, strpos($data, ',') + 1);
	$data = base64_decode($data);
	
	// Make sure the dir exists
	mkdir($sitepad['screenshots_path'], 0755, true);
	
	// Save an upload
	file_put_contents($sitepad['screenshots_path'].'/'.$post_name.'.jpg', $data);
	
	echo '{done:'.$postID.'}';
	die();
	
}

add_action( 'wp_ajax_sitepad_reset_site', 'sitepad_reset_site' );
function sitepad_reset_site(){
	
	global $wpdb, $wp_rewrite, $pagelayer;

	// Some AJAX security
	check_ajax_referer('sitepad_ajax', 'sitepad_nonce');
	
	if(!current_user_can( 'manage_options' )){
		wp_send_json(array('error' => 'You do not have permission to reset site !'));
	}

	$reset_todo = optGET('reset_todo');
	
	if(empty($reset_todo) || !in_array($reset_todo, array('pages', 'posts', 'all'))){
		wp_send_json(array('error' => 'Invalid reset action'));
	}
	
	// Reset the site
	$ret = sitepad_reset_site_fn($reset_todo);
	
	if($ret){
		wp_send_json(array('done' => 1));
	}else{
		wp_send_json(array('error' => 'An unexpected error occured'));
	}	
	
}