Recent Topics

1 Sep 07, 2005 02:00    

What is that?
As requested in [url=http://forums.b2evolution.net/viewtopic.php?t=5326]Posts which redirect to other posts[/url], here is a PostRedirectHack hack for [url=http://b2evolution.net]b2evolution[/url] 0.9.0.1x to redirect users from a post to another one (using a post ID or title) or any URL (relative or absolute path) using standard HTTP header commands.

What does it do?
PostRedirectHack hack redirects visitors who come on a given single post page (permalink URL) to another post or URL. The destination post can be either a post ID, a post_title (the often used as URL suffix) or a relative or absolute URL (including external URLs). In order to help you checking if a given redirection post is used or not, the hit log is updated.

When to use it?
If you publish a post with a given URL, ping some sites, trackback some others, other webmasters add a link to your post. Then, you discover you misspelled the URL and want to fix it. If you do so, all the external links are going to lead visitors to a blank page. The PostRedirectHack hack helps you to redirect people from this old URL to the new one.

How to use it?
In order to use the PostRedirectHack hack is used as following:
[list]

  • If you haven't done it yet, change your "bad" post's URL and notice its date.

  • Create a new post.

  • Change the new post's date to the previously "bad" post's one (in order to get the "bad" URL identical, since the date is used by [url=http://b2evolution.net]b2evolution[/url] in posts' URLs).

  • Change the new post's status to Draft (in order to avoid displaying it in your blog).

  • If any, remove all the display filters for that blog. (The Auto Links filter plug-in corrupts the display of the list of posts in the [url=http://b2evolution.net]b2evolution[/url] backoffice Edition tab when one of the displayed posts is a redirection post with a URL as parameter. Instead of skipping HTML comments -- this hack's tags are HTML comments and should be ignored! -- the Auto Links filter modify the hack's appareance leading to some corrupted displays including some posts dissapearing from the [url=http://b2evolution.net]b2evolution[/url]backoffice Edition tab.)

  • Write the following redirection tag to the new post:
    <!--redirect 123-->
    to redirect visitors from the current post to post ID #123 (or use another destination post ID). For your convenience, you can also use other forms of this redirection tag:
    <!--redirect post_title-->
    <!--redirect /a_file_on_my_blog_server.html-->
    <!--redirect http://blog.lesperlesduchat.com/dev.php-->

    or even:

  • <!--PostRedirectHack 456-->
    <!--Location: http://blog.lesperlesduchat.com/dev.php-->

    as well as other forms (see code).[/list:u]An error URL can be used to redirect visitors on it when you've done errors on your redirection (like redirecting to a missing post or to the redirection post itself).

    How quick is it?
    The PostRedirectHack executes code for every single post page displayed so it has incidence on your server performance. However, the code is small enough to make it quick enough to be unnoticable on global server performance. (This hack does almost nothing when compared to what is done when a page is displayed.)

    If you care about performance, use an [url=http://www.apache.org]Apache[/url] .htaccess configuration file to redirect visitors from a given URL to another one. (However, not everybody has access to a .htaccess and not everybody has the technical skills to modify it.) You can also read the [url=http://forums.b2evolution.net/viewtopic.php?t=5245]CPU Usage Reduction Hack: Auto pruning of old stats[/url] and recommanded threads about improving your [url=http://b2evolution.net]b2evolution[/url] system performance.

    Known Bugs
    The only known bug (at the moment) is an incompatibility in the [url=http://b2evolution.net]b2evolution[/url] backoffice Edition tab display when the Auto Links filter plug-in is activated on a redirection post using a URL as parameter. The display of the Edition tab may appear corrupted: you click on an Edit button and instead of editing the expected post, you edit another one!

    Always deactivate all the display filters plug-ins in order to avoid unexpected results. When you forget to do so, edit a post, then change the current URL appearing on your browser's address tab to find and edit the redirection post using a URL as parameter and deactivate all its display filters.

    Implementation
    If you haven't created a conf/hacks.php file before, create a dummy (empty) conf/hacks.php file with:

    <?php
    
    /* PHP code to be inserted here */
    
    ?>


    All the incoming PHP code should be inserted between the beginning:

    <?php


    and the finishing:

    ?>


    lines. Make sure all the code you add is exactly the same as the one written here, especially ponctuation and case (PHP is a case-sensitive language).

    Edit your conf/hacks.php file to add the following lines at the end of the file:

    /**
     * Redirect the visitor from the current single post (only) to another one
     * (using its post ID or title) or to any URL (using relative or absolute
     * paths).
     * 
     * This PostRedirectHack for b2evolution 0.9.0.1x is intended to help people
     * redirecting visitors from a previously used, but modified URL. This is
     * usefull when you fix a misspelled URL referrenced by external sites
     * (blogrolls, trackbacks, etc.) Using that hack avoids people coming to the
     * obsolete URL with a blank page: they are redirected to the right place to
     * be!
     * 
     * Here are some examples of tags you can use to redirect users. Insert a
     * redirection tag at the top of your post that needs redirect users:
     *   <!--redirect 123-->
     *   <!--redirect post_title-->
     *   <!--redirect http://www.example.com/page.html-->
     * You can also use other forms, including:
     *   <!--PostRedirectHack 123-->
     *   <!--Location: post_title-->
     * Since the post is not intended to be displayed (it redirects people using
     * HTTP header commands, before any display), it should not contain any other
     * information and should be published as 'draft' tag in order to prevent it
     * from being publicly available. In the case this tag is displayed, it appears
     * as a standard HTML comment and does not cause any trouble.
     * 
     * @param $disp			Must be 'single' in order to enable redirection check,
     *						anything else makes this function doing nothing.
     * @param $SourceItem	A post item (@see Item) containing the item information
     *						to be displayed (or not).
     * @param $ErrorUrl		Error URL to be used when an error occurs.
     * 
     * @copyright (c)2005 by kwa {@link http://blog.lesperlesduchat.com/dev.php}
    */
    function PostRedirectHack( $disp, $SourceItem, $ErrorUrl )
    {
    	// Do we try to display a single item?
    	if( ( $SourceItem !== false ) && $disp === 'single' )
    	{
    		// Find the redirect pseudo-tag
    		if( preg_match( "/<!--((post[_]?)?(redirect)([_]?to)?([_]?hack)?|(http[_]?)?location):?[\s]*([^\s]*)[\s]*-->/siU",
    						$SourceItem->content,
    						$Matches ) )
    		{
    			// The redirection tag 
    			$Redirection = $Matches[ 7 ];
    			if( preg_match( "/^[0-9]{1,6}$/i", $Redirection, $Matches ) )
    			{
    				// Redirect to post ID
    				$RedirectionItem = Item_get_by_ID( $Matches[ 0 ] );
    				if( $RedirectionItem !== false && $RedirectionItem->ID != $SourceItem->ID  )
    					$RedirectionUrl = $RedirectionItem->gen_permalink( '', '', false, '&' );
    				else
    					$RedirectionUrl = $ErrorUrl;
    			}
    			elseif( preg_match( "/^[0-9a-z\-_]{1,64}$/i", $Redirection, $Matches ) )
    			{
    				// Redirect to post title
    				$RedirectionItem = Item_get_by_title( $Matches[ 0 ] );
    				if( $RedirectionItem !== false && $RedirectionItem->ID != $SourceItem->ID  )
    					$RedirectionUrl = $RedirectionItem->gen_permalink( '', '', false, '&' );
    				else
    					$RedirectionUrl = $ErrorUrl;
    			}
    			elseif( preg_match( "/^((ht|f)tps?\:\/\/[^\?\/](:[0-9]{1,5})?\/?|\/)([a-z0-9\-\.\?\,\'\/\\\+&%\$#_=]*?)$/i",
    					$Redirection,
    					$Matches ) )
    			{
    				// Redirect to relative or full URL
    				$RedirectionUrl = $Matches[ 0 ];
    			}
    			else
    			{
    				// Error, cannot retrieve the redirection URL
    				$RedirectionUrl = $ErrorUrl;
    			}
    
    			if( !empty( $RedirectionUrl ) )
    			{
    				// Redirect visitor and search engine robots
    				header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' 301 Moved Permanently' );
    				header( 'Location: ' . $RedirectionUrl );
    				log_hit();
    				die();
    			}
    		}
    	}
    } // PostRedirectHack()

    The previous code makes the PostRedirectHack feature available, but does not use it yet.

    Edit the conf/_blog_main.php file and find the following lines (about lines 117-121):

    # If a particular post is requested (by id or title) but on the wrong blog,
    # do you want to automatically redirect to the right blog?
    # This is overly usefull if you move posts or categories from one blog to another
    # If this is disabled, the post will be displayed in the wrong blog template.
    $redirect_to_postblog = false;

    and change:

    $redirect_to_postblog = false;

    to:

    $redirect_to_postblog = true;

    in order to authorize redirects on all the blogs. This is not specific to the PostRedirectHack, but is needed by it.

    Edit the b2evocore/_blog_main.php file and find the following lines (about lines 165-180):

    	// On single post requests, check if we're on the right blog!
    	if( $redirect_to_postblog && ( $disp == 'single' ) )
    	{	// Yes we need to check.
    		if( !empty($p) )
    			$Item = Item_get_by_ID( $p );	// TODO: use cache
    		else
    			$Item = Item_get_by_title( $title );	// TODO: use cache
    			
    		if( ($Item !== false) && ($Item->blog_ID != $blog) )
    		{	// We're on the wrong blog (probably an old permalink) let's redirect
    			$new_permalink = $Item->gen_permalink( '', '', false, '&' );
          # echo $new_permalink;
    			header ("Location: $new_permalink");
    			exit();
    		}
    	}

    and change the following four last lines:

    			header ("Location: $new_permalink");
    			exit();
    		}
    	}

    to:

    			header ("Location: $new_permalink");
    			exit();
    		}
    
    		///>>> PostRedirectHack START
    		// In order to deactivate the PostRedirectHack, add a double-slash at
    		// the beginning of the following line (as on the current line!)
    		PostRedirectHack( $disp, $Item, $Blog->gen_blogurl() );
    		///<<< PostRedirectHack END
    	}

    The previous code calls the PostRedirectHack and makes it available to all your blogs. If you want to deactivate the hack, edit the previously added:

    		PostRedirectHack( $disp, $Item, $Blog->gen_blogurl() );

    and comment out it like so:

    		//PostRedirectHack( $disp, $Item, $Blog->gen_blogurl() );

    You don't have to remove anything else.

    Final words
    [list]

  • Thanks to [url=http://forums.b2evolution.net/profile.php?mode=viewprofile&u=3508]fallstorm[/url] for requesting this hack in the [url=http://forums.b2evolution.net/viewtopic.php?t=5326]Posts which redirect to other posts[/url] thread. I thought writing one before, but never had the motivation to do so. Thanks, man!

  • You can visit the "official" Post Redirect Hack page on my own blog: [url=http://blog.lesperlesduchat.com/dev.php/2005/09/07/b2evolution_post_redirect_hack]b2evolution: Post Redirect Hack[/url].

  • [*]Any feedback is appreciated![/list:u]

    2 Sep 07, 2005 04:17

    Quality Assurance / Testing
    Since redirection doesn't display anything, I had to use some [url=http://forums.b2evolution.net/viewtopic.php?t=5328]Web Browsers Emulators/Simulators[/url] to debug the Post Redirect Hack. That helped a lot, especially on circular redirections making a page display appearing as the server has freezed (then, I added a check to redirect the visitor to the "error URL")...

    I created the following posts on [url=http://blog.lesperlesduchat.com/dev.php]My Own Little Development Blog[/url] as drafts posts [u]with all display filter plug-ins disabled[/u]:


    Form is loading...