Prevent post and term hierarchy loops. Props mdawaffe. fixes #14662

git-svn-id: https://develop.svn.wordpress.org/trunk@15806 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Ryan Boren
2010-10-14 15:09:04 +00:00
parent 3bd3ec6455
commit 8e1da911a2
4 changed files with 197 additions and 12 deletions
+60 -11
View File
@@ -2337,17 +2337,8 @@ function wp_insert_post($postarr, $wp_error = false) {
else
$post_parent = 0;
if ( !empty($post_ID) ) {
if ( $post_parent == $post_ID ) {
// Post can't be its own parent
$post_parent = 0;
} elseif ( !empty($post_parent) ) {
$parent_post = get_post($post_parent);
// Check for circular dependency
if ( isset( $parent_post->post_parent ) && $parent_post->post_parent == $post_ID )
$post_parent = 0;
}
}
// Check the post_parent to see if it will cause a hierarchy loop
$post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
if ( isset($menu_order) )
$menu_order = (int) $menu_order;
@@ -4804,6 +4795,64 @@ function _show_post_preview() {
}
}
/**
* Returns the post's parent's post_ID
*
* @since 3.1
*
* @param int $post_id
*
* @return int|bool false on error
*/
function wp_get_post_parent_id( $post_ID ) {
$post = get_post( $post_ID );
if ( !$post || is_wp_error( $post ) )
return false;
return (int) $post->post_parent;
}
/**
* Checks the given subset of the post hierarchy for hierarchy loops.
* Prevents loops from forming and breaks those that it finds.
*
* Attached to the wp_insert_post_parent filter.
*
* @since 3.1
* @uses wp_find_hierarchy_loop()
*
* @param int $post_parent ID of the parent for the post we're checking.
* @parem int $post_ID ID of the post we're checking.
*
* @return int The new post_parent for the post.
*/
function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
// Nothing fancy here - bail
if ( !$post_parent )
return 0;
// New post can't cause a loop
if ( empty( $post_ID ) )
return $post_parent;
// Can't be its own parent
if ( $post_parent == $post_ID )
return 0;
// Now look for larger loops
if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
return $post_parent; // No loop
// Setting $post_parent to the given value causes a loop
if ( isset( $loop[$post_ID] ) )
return 0;
// There's a loop, but it doesn't contain $post_ID. Break the loop.
foreach ( array_keys( $loop ) as $loop_member )
wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
return $post_parent;
}
/**
* Default post information to use when populating the "Write Post" form.