I am creating a front end editor that uses AJAX to update the page content.
It updates by using JS to take chunks of HTML components and save to the page content, wrapped in <!-- wp:html --> tags.
The function is only available if user is logged in and front-end editor option (custom theme option) is selected.
The AJAX code is:
function scedPage(post_id) {
var pageComs = ["<!-- wp:html -->"];
jQuery('section component').each(function () {
$this0 = jQuery(this)[0].outerHTML;
pageComs.push($this0);
});
pageComs.push("<!-- /wp:html -->");
pageHtml = pageComs.join(' ');
console.log(pageHtml);
jQuery.ajax({
type: "POST",
url: ajax_object.ajaxurl,
async: true,
data: {
action: 'sced_page',
post_content: pageHtml,
postId: post_id
},
success: function (data) {
location.reload();
},
error: function (error) {
console.log(error)
}
});
};
The PHP is:
function sced_page() {
$dev_sced = get_option('scale_opt_field2');
if (current_user_can('editor') || current_user_can('administrator')) {
if ($dev_sced !== "1") {
} else if ($dev_sced == "1") {
$post_id = $_POST['postId'];
$post_content = $_POST['post_content'];
$the_post = array();
$the_post['ID'] = $post_id;
$the_post['post_content'] = $post_content;
$post_id = wp_update_post($the_post);
wp_die();
add_action( 'wp_ajax_sced_page', 'sced_page' );
}
}
};
Does posting large blocks of unescaped/unfiltered HTML pose a problem? I realise I'll need to add nonce in there.
Thank you for your help.
Does posting large blocks of unescaped/unfiltered HTML pose a problem?
TLDR;
Yes, there's a chance that your code could be exploited by malicious users so I'd sanitize the user's input using wp_kses_posts() before saving it to the database (or before rendering the content on the website).
Since you're checking for user capabilities and expect that they're either an editor or an administrator, which are roles you usually assign to people you trust, in theory it might sound OK to just save whatever they submit into the database.
Experience though has taught me -and many others out there will surely say the same thing- that you should never trust user's input. Sanitize/escape data whenever possible. Make this your personal mantra as a developer and save your Future Self some trouble.
$post_content = wp_kses_post($_POST['post_content']);
Not related to your original question but wanted to point out a couple of things about your code if that's OK:
if condition isn't doing anything. Is that incomplete code or ...?add_action( 'wp_ajax_sced_page', 'sced_page' ); is never going to be executed: nothing after wp_die(); is going to be run by the server.$_POST['postId'] and $_POST['post_content'] are set using isset() before attempting to access them.