<?php

function wpseo_set_option() {
	update_option($_POST['option'], $_POST['newval']);
	return 1;
	die();
}
add_action('wp_ajax_wpseo_set_option', 'wpseo_set_option');

function wpseo_set_ignore() {
	$options = get_option('wpseo');
	$options['ignore_'.$_POST['option']] = 'ignore';
	update_option('wpseo', $options);
	return 1;
	die();
}
add_action('wp_ajax_wpseo_set_ignore', 'wpseo_set_ignore');

function wpseo_autogen_title_callback() {
	$options = get_wpseo_options();
	$p = get_post( $_POST['postid'] );
	$p->post_title = trim( stripslashes($_POST['curtitle']) );
	if ( empty($p->post_title) )
		die();
	if ( isset($options['title-'.$_POST['post_type']]) && $options['title-'.$_POST['post_type']] != '' )
		$title = wpseo_replace_vars($options['title-'.$_POST['post_type']], $p );
	else
		$title = $p->post_title . ' - ' .get_bloginfo('name'); 
	echo trim( preg_replace( '/\s+/', ' ', $title ) );
	die();
}
add_action('wp_ajax_wpseo_autogen_title', 'wpseo_autogen_title_callback');

// TODO: make this actually work and used in post editor.
function wpseo_autogen_metadesc_callback() {
	$options = get_wpseo_options();
	$p = get_post( $_POST['postid'] );

	if ( isset( $_POST['post_content'] ) )
		$p->post_content = trim( stripslashes( $_POST['post_content'] ) );
	if ( isset( $_POST['post_excerpt'] ) )
		$p->post_excerpt = trim( stripslashes( $_POST['post_excerpt'] ) );
	
	if ( isset($options['metadesc-'.$_POST['post_type']]) && $options['metadesc-'.$_POST['post_type']] != '' )
		echo wpseo_replace_vars($options['metadesc-'.$_POST['post_type']], $p );
	die();
}
add_action('wp_ajax_wpseo_autogen_metadesc', 'wpseo_autogen_metadesc_callback');

function wpseo_ajax_generate_sitemap_callback() {
	$options = get_option('wpseo');
	$type = (isset($_POST['type'])) ? $_POST['type'] : '';
	
	if ($type == '') {
		global $wpseo_generate, $wpseo_echo;
		$wpseo_generate = true;
		$wpseo_echo = true;
		
		$mem_before = function_exists('memory_get_peak_usage') ? memory_get_peak_usage() : memory_get_usage();
		require_once WPSEO_PATH.'/sitemaps/xml-sitemap-class.php';
		$mem_after = function_exists('memory_get_peak_usage') ? memory_get_peak_usage() : memory_get_usage();
		echo number_format( ($mem_after - $mem_before) / 1024 ).'KB of memory used.';

	} else {
		global $wpseo_generate, $wpseo_echo;
		$wpseo_generate = true;
		$module_name = $type;
		if($type == 'kml' || $type == 'geo') {
			$module_name = 'local';
			$type = 'geo';
		}
		require_once WP_PLUGIN_DIR.'/wordpress-seo-modules/wpseo-' . $module_name . '/xml-' . $type . '-sitemap-class.php';
	}	
	die();
}
add_action('wp_ajax_wpseo_generate_sitemap', 'wpseo_ajax_generate_sitemap_callback');