eZ Community » Learn » eZ Publish » Creating a simple custom workflow event

Creating a simple custom workflow event

Thursday 09 December 2010 5:01:18 pm

  • Currently 5 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Step 8 – Authorize eZ Publish via Twitter OAuth

Since August 2010 Twitter doesn’t allow access to the service via the basic authentication method. This is affecting all scripts and bots that automatically update a Twitter account. The pain is mainly because of the way the new authentication method (OAuth) is dealing with hand shakes, it requires a human interaction in order to generate an Access Token and Access Token Secrets that will authenticate the user later one. Fortunately this is only needed once.

The Arc90 with OAuth support you have downloaded above allows a PHP script to use OAuth and update a Twitter feed. But you need to modify few lines and create a new script allowing you to authenticate a user and generate keys and tokens for future authentication.

In Step 4 above, we have created an INI file to hold some of our variables and credentials for Twitter OAuth. It’s now time to see how to retrieve them. We will need to do some small modifications to the OAuth library we downloaded earlier and create a little PHP script to help us with the Twitter authentication. This is a bit tedious because of how OAuth is working, but fortunately you only have to do it once.

 

Modifying OAuth library to support PIN validation:

Twitter OAuth supports two methods to validate the authorization of an app to update a user account. It can either redirect to a callback URL or generate a PIN code. For this tutorial, I’ve setup a Twitter customer key and customer secret string that will identify this app as ‘eztweeter’. I strongly recommend you register for a Twitter API and get your own key and secret strings, this also good for your own branding as this will show your app name on the tweets. This demo Twitter API profile has been registered and configured to provide a PIN code for validation. But in order to use this PIN we need to modify the OAuth’s library file ‘oauth/twitterOAuth.php, edit that file and look for the function getAccessToken and modify it to look like this:

function getAccessToken( $token = NULL, $pin = NULL )
{
    if ( $pin )
    {
        $r = $this->oAuthRequest( $this->accessTokenURL(),
                                  array( "oauth_verifier" => $pin ) );
    }
    else
    {
        $r = $this->oAuthRequest( $this->accessTokenURL() );
    }
 
    $token = $this->oAuthParseResponse( $r );
    $this->token = new OauthConsumer( $token['oauth_token'],
                                      $token['oauth_token_secret'] );
    return $token;
}
 

You now also need to create a little PHP script that will handle the authorization and validation via command line:

<?php
error_reporting( E_ALL | E_NOTICE );
 
// Go back to eZ root folder
require 'autoload.php';
//require_once( 'extension/mytwitter/lib/oauth/twitterOAuth.php' );
 
$cli = eZCLI::instance();
 
$script = eZScript::instance( array( 'description' => ( "Twitter credentials registration / validation\n" .
                                                        "Script to register and validate OAuth credentials for Twitter\n" .
                                                        "\n" .
                                                        "extension/mytwitter/lib/setup.php" ),
                                     'use-session'    => false,
                                     'use-modules'    => false,
                                     'use-extensions' => true ) );
 
$script->startup();
 
// CLI parameters
$options = $script->getOptions( "[register][validate:]",
                                "",
                                array( 'register'                 => 'generate a registration URL',
                                       'validate'                 => 'validate the PIN returned by the registration URL' ) );
 
$script->initialize();
 
$myTwitterINI = eZINI::instance( 'mytwitter.ini' );
$consumerKey = $myTwitterINI->variable( 'TwitterSettings', 'ConsumerKey' );
$consumerSecret = $myTwitterINI->variable( 'TwitterSettings', 'ConsumerSecret' );
$accessToken = $myTwitterINI->variable( 'TwitterSettings', 'AccessToken' );
 
$varDir = eZSys::varDirectory();
$myTwitterTmpDir = $varDir . '/mytwitter';
if ( !file_exists( $myTwitterTmpDir ) )
{
     eZDir::mkdir( $myTwitterTmpDir, eZDir::directoryPermission(), true);
}
 
$noAction = true;
$register = isset( $options['register'] );
$noAction = !$register;
 
$pin = false;
if ( $options['validate'] )
{
    $noAction = false;
    $pin = $options['validate'];
}
 
 
if ( $register )
{
    // instantiate a TwitterOAuth object and request a token
    $oauth = new TwitterOAuth( $consumerKey, $consumerSecret );
    $request = $oauth->getRequestToken();
 
    $request_token = $request["oauth_token"];
    $request_token_secret = $request["oauth_token_secret"];
 
    // Saving the token in files for the validation process to use
    // Make sure to delete this after validation.
    file_put_contents( "{$myTwitterTmpDir}/request_token", $request_token );
    file_put_contents( "{$myTwitterTmpDir}/request_token_secret", $request_token_secret );
 
    // Generate an authorisation URL
    $request_link = $oauth->getAuthorizeURL( $request );
    $cli->warning( "Request here: " . $request_link );
}
elseif ( $pin )
{
 
    // read the request token from the registration process
    $request_token = file_get_contents( $myTwitterTmpDir ."/request_token" );
    $request_token_secret = file_get_contents( $myTwitterTmpDir ."/request_token_secret" );
 
    // Instantiate a TwitterOath object and provide it with the loaded token
    $oauth = new TwitterOAuth( $consumerKey, $consumerSecret,
                   $request_token, $request_token_secret );
 
    // request an access token from Twitter
    $request = $oauth->getAccessToken( FALSE, $pin );
 
    $cli->output( "Twitter user: {$request['screen_name']}" );
 
    $access_token = $request['oauth_token'];
    $access_token_secret = $request['oauth_token_secret'];
 
    // Display INI file settings
    $cli->output( "mytwitter.ini.append.php variables:" );
    $cli->warning( "AccessToken={$access_token}" );
    $cli->warning( "AccessSecret={$access_token_secret}\n" );
 
    //require_once( "extension/mytwitter/lib/Arc90/Service/Twitter.php" );
 
    // Lets see if everything is working
    $twitter = new Arc90_Service_Twitter();
    // Authenticate 
    $twitter->useOAuth( $consumerKey, $consumerSecret, $access_token, $access_token_secret );
 
    // Retreive our account's timeline
    $cli->output( 'Trying to retreive our Twitter timeline' );
    $response = $twitter->getFriendsTimeline( 'json', array( 'count' => 200, 'page' => 0 ) );
    $cli->output( 'HTTP code: '.$response->getHttpCode() );
 
    if (!$response->isError())
    {
        $messages = $response->getJsonData();
        $cli->output( "Found ".count($messages). "new tweets" );
    }
    else
    {
        $cli->output( 'Error description: '.$response->getData() );
    }
 
    // Deleting the token request files
    unlink( $myTwitterTmpDir ."/request_token" );
    unlink( $myTwitterTmpDir ."/request_token_secret" );
 
}
 
if ( $noAction )
{
    $cli->warning( "Please use one of the following options --register --validate. Use --help option for more details." );
}
$script->shutdown();
?>
 

Now lets proceed with the authorization to modify your Twitter feed, change to the directory ~/extension/mytwitter/lib/ and run:

php setup.php --register

This will give you a URL that you need to open in a browser. Login into Twitter and allow eztweeter to access your feed, then copy the PIN code and run the following command:

php setup.php --validate=[PIN]

Replace [PIN] with the PIN code you copied earlier. This command will give you the INI string you need to setup in mytwitter.ini in the settings folder of the extension or mytwitter.ini.append.php of your siteaccess settings folder.

That’s it.

 

Printable

Printer Friendly version of the full article on one page with plain styles

Author(s)

Proudly Developed with from