Articles

Categories

Automatically Tweet New Articles

Introduction

Some time back I wrote an article on using a short URL to redirect to your website articles. Rather than use one of the many existing services I suggested it would be better to create your own short url site. The obvious advantage is, unlike some services, you are not going to shut it down.

At that time I mentioned I would write an article on automating the procedure - at least for the Modx CMS. It has taken a while but I finally sat down and wrote the code. Nothing fancy, but it does seem to work. It was meant to meet a specific need - to post a tweet each time I wrote a new article on my website.

It is not a simple process - there are four separate sections to setting up the process. Since you are changing the .htaccess I would strongly recommend you test it first on a development server. Getting the .htaccess wrong is one sure way to bring down your website.

  • The first is the .htaccess file. Because my URL is relatively short, www.timr.ca, I use the one on my main site. However, it you have a longer URL you will want to register a shorter one. There is a host of two letter TLD's that allow foreigners to register names if the .us name is not available. All you need it for is the redirect.
  • Copy the redirect code to its location. I put under 'assets/snippets/redirect', but you can put it where ever you want. Just change the .htaccess rewrite rule
  • Create the table in the database
  • Copy and configure the plugin

 

I have a separate directory, with sub directories, for articles posted on my website. This plugin was designed to post tweets every time an article was published in any of the sub directories. It is setup to monitor multiple sub directories or even the top level. Feel free to modify as necessary

.htaccess

If you are using your main url, like I am, you will need to select a leading character to trigger the redirect. I chose the underscore, '_', since I would not normally use that to start a file name. Then add the following to the .htaccess:

# Short urls for twitter
RewriteRule ^_(.*)$ http://www.your.url/index-ajax.php?q=assets/snippets/redirect/redirect.php&redirect=$1 [L,R=301]

If you have a separate site just for redirects the .htaccess will look something like this:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /


# Short urls for twitter
RewriteRule ^(.*)$ http://www.your.url/index-ajax.php?q=assets/snippets/redirect/redirect.php&redirect=$1 [L,R=301]

Note: Each .htaccess statement is on its own line.

The Redirect Code

The "assets/snippets/redirect/" is where I put the redirect code, you can put it anywhere you want - just change the redirect. Run it through index-ajax.php first - it checks the code against a host of nastiness.

The code is a simple look-up using the Modx database for your site. There is only one Config item:

// Config
define("REDIRECT_TO","http://www.your.domain"); // Edit default redirect location

Which simply defines where you want to redirect the request if there is an error.

The rest of the code is fairly straight forward. It will generate a 301 redirect either to the error page or to the requested page.

if(isset($_REQUEST['redirect'])) {
    // Get access to $modx
    include_once MODX_BASE_PATH . '/manager/' .
      includes/document.parser.class.inc.php';
    $modx = new DocumentParser();
    $modx->getSettings();
    $redirect = trim($_REQUEST['redirect']);
    $pattern = "'[^A-Za-z0-9]'";
    if (!preg_match($pattern, $redirect, $matches)) {
        $sql = "SELECT `long_url` FROM " .           $modx->getFullTableName('redirect_twitter')
          " WHERE `short_url` = '$redirect'";
        if($rs = $modx->db->query($sql)) {
            if($modx->db->getRecordCount($rs) == '1') {
                $row = $modx->db->getRow($rs, 'assoc');
                $location = "Location: " . trim($row['long_url']);
                header($location, TRUE, 301);
                exit;
            }
        }
    }
}
$location = "Location: " . REDIRECT_TO;
header($location, TRUE, 301);
exit;

The first line tests to that there is a redirect. If there is, it grabs the Modx parser. If not, it falls through to the error redirect.

The next test is to do a validate of the redirect string. It should be alpha numeric, if not, fall through to the end and redirect to the location set for errors.

Finally - check the database for the new location. Again, if there is an error, or the redirect is not in the database, it will fall through to the error redirect. Download redirect and put it in the directory /assets/snippets/redirect/'. Rename the file redirect.php.

Create Table in Database

It doesn't matter which tool you use for accessing your database, I use phpMyAdmin, but the code to setup the table is the same no matter what you are using:

CREATE TABLE IF NOT EXISTS `modx_redirect_twitter` (
    `short_url` varchar(19) NOT NULL,
    `long_url` mediumtext NOT NULL,
    KEY `short_url` (`short_url`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

If you are not using 'modx' as your table prefix, you will have to change that. Otherwise it is pretty straight forward.

The Plugin

Create a new plugin go to Elements > Manage Elements > Plugins > New Plugin - copy and paste the following text into the 'Plugin code (php)' textarea. Note - Plugins don't use the <php and ?> opening and closing tags.

// Configuration
// Comma separated list of directories to trigger a Twitter post. All sub directories will be tweeted as well.
$twitterThese = '';
// Twitter account username
$username = 'your name';
// Twitter password
$password = 'your password';
// Text to appears at the start of each post - always end with a space.
$msgPrefix = '';
// The character that will trigger a .htaccess redirect - the default is an underscore.
// Can be left empty
$htaccessTrigger = '_';
// Set to deepest path - the default, 6 levels of sub directories is usually enough
$limit = '6';
// You can get 3 extra characters by removing the spaces between the dots
$ellipses = ' . . . ';

include_once( $modx->config['base_path'] .
        'assets/plugins/twitterNotify/dbUpdate.php');

Plugins can be linked to an event. In this case we want to run the plugin each time the page is saved. Select 'OnDocFormSave' from the 'System Events' tab.

The rest of the plugin code is too large to show here. You can download a copy of dbUpdate and put it in the directory 'assets/plugins/twitterNotify/'. Rename the file dbUpdate.php.

The first section of the code just does a check to see that there is an alias, longtitle and some content. If not just, resume the normal operation. The second section checks to make sure the page is published. This is a little more complex, if the page was published previously it will be in the database table and we need to remove it before returning to the normal operation.

The final section builds the mesage to be sent to Twitter. The final message consists of the message prefix, the Page Title (longtitle) and the URL. If the Page Title is too long - it is chopped and an ellipses is added.

The message is sent to Twitter using code found at http://kosso.co.uk/twitter/twitterCurl.phps. The code did not run properly right out of the box. I wasn't getting the correct error codes. A post by Chad Etzel suggested adding "curl_setopt($ch, CURLOPT_POSTFIELDS, "");", that fixed the problem.

I haven't been able to test the error code against a Twitter system busy message, which I get every now and then. If the authorization fails a 403 error is returned. And a warning is placed in the System Log.

Leave a Comment






"));