Browsing the archives for the Code category.

Zend Framework Twitter and oAuth in 1.10.7

Code, oauth, php, twitter, Zend Framework

Today I wanted need to switch out some implementations I have in twitter. I was using HTTP Basic for authentication as were most. I went through the Zend Oauth docs, and combined with their examples and those of Pádraic Brady I got this working fine.

I’m not going to give a step by step, as I’m assuming you’ve already read various docs.

I broke my files out like Pádraic, so if you’ve read his than you’ll understand mine.

First, my config file which is included within each subsequent file.

$config = array(
        'callbackUrl'    => 'http://www.example.com/callback.php',
        'siteUrl'        => 'http://twitter.com/oauth',
        'consumerKey'    => 'XXXXXXXXXXXXXXXXXXXXX',
        'consumerSecret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
);

My index page is the starting point of the authentication process. Our persistent storage for this example is in session, though in production I’m using a database.

include_once './config.php';

if (!$_SESSION['TWITTER_REQUEST_TOKEN']) {
    // $config is from our include!
    $consumer = new Zend_Oauth_Consumer($config);

    // fetch a request token
    $token = $consumer->getRequestToken();

    // persist the token to storage
    $_SESSION['TWITTER_REQUEST_TOKEN'] = serialize($token);

    // redirect the user
    $consumer->redirect();
}

The callback url specified will now be triggered

include_once './config.php';

// Check if _GET is set and that the request token is being returned
if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {

    $consumer = new Zend_Oauth_Consumer($config);
    $token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));

    $_SESSION['TWITTER_ACCESS_TOKEN'] = serialize($token);

    // Now that we have an Access Token, we can discard the Request Token
    $_SESSION['TWITTER_REQUEST_TOKEN'] = null;
} else {
    // Mistaken request? Some malfeasant trying something?
    exit('Invalid callback request. Oops. Sorry.');
}

// Lets just pass on to a test posting page
redirect_url('post.php');

Finally, if all went to plan and the user authorized our application, we can pull in their access token and do as we need on their behalf.

include_once './config.php';

// Verify we're good to go
if (isset($_SESSION['TWITTER_ACCESS_TOKEN'])) {

    // Unserialize and add the token to the config
    $token = unserialize($_SESSION['TWITTER_ACCESS_TOKEN']);
    $config['accessToken'] = $token;

    // Pass the config into Twitter, and act upon the users account
    $twitter = new Zend_Service_Twitter($config);

    $twitter->status->update('I am so posting from your account. Rock!');
}

That’s all really. I do wish the Zend Service Twitter docs would be updated to reflect some examples. I saw in SVN Pádraic has already changed some of the docs, they’ve just not been updated on site yet.

Thanks to the documentation authors and those I borrowed from to get my working example going and so I could more easily move forward with this project.

-Casey

No Comments

Zend Form Element Radio and Default value

Code, Zend Framework

I setup a Zend Form object and needed radio buttons, but also needed a default value. Took me a few minutes to find, but here’s an example of use.

/**
 * Setting some values for our radio buttons.
 */
$options = array(
    '1' => 'Option 1',
    '2' => 'Option 2',
    '3' => 'Option 3'
);

/**
 * The array('value' => 2) below sets our default value.
 */
$radio = new Zend_Form_Element_Radio('elementName', array('value' => '2'));
$radio->addMultiOptions($options);
$this->addElement($radio);
No Comments

Old code.

Code, php

I love coming across old code *cough* garbage *cough*

The purpose of this was to take a title, and create something url safe and in the fashion a client was wanting. The first function was old code, so don’t blame me.

function cleanUrl($url)
{
  $find =        array('/--/', '/ - /','/ /', '/!/', '/"/', "/'/", '/--/');
  $replace =    array('-', '-', '-', '', '', '', '-');

  $result = strtr($url, "`~@#$%^&*()_=+|[]{};:,./<>?", "---------------------------");

  return strtolower(preg_replace($find, $replace, strip_tags(stripslashes(trim($result)))));
}

Isn’t it horrible?

I rewrote the function to…

function cleanUrl($url)
{
  $url = strtolower($url);

  $url = preg_replace("/[^a-z0-9\s+]/", '', $url);
  $url = preg_replace("/[\s]{1,}/", '-', $url);

  return $url;
}

That makes me happier.

No Comments

Ewerl Function

Code

Ewerl is a new URL rewritting site with cool features.

Here’s a simple function to return the Ewerl url. It’s only being used for the main url, but could easily be adjusted to return an array. I just didn’t have a need for it in my case at this time.

/**
 * Returns an Ewerl url if available.
 * Otherwise the original that was passed in.
 * Returns false if..
 * 1. JSON extension isn't installed.
 * 2. No url was entered.
 * 3. No response from server.
 *
 * @todo Add URL validation.
 *
 * @param string $url
 * @return string URL, or false.
 * @author Casey Wilson 
 */
function getEwerl($url) {
	/**
	 * Verify JSON extension is loaded.
	 */
	if (!extension_loaded('JSON')) return false;

	/**
	 * Url wasn't passed
	 */
	if (!$url) return false;

	/**
	 * Assign / Prep vars.
	 */
	$postUrl = 'http://ewerl.com/api/v1/make/url=';
	$urlEncoded = base64_encode($url);

	$response = file_get_contents($postUrl . $urlEncoded);

	if (!$response) {
		return $url;
	}

	/**
	 * Should have returned a JSON object.
	 */
	$jsonObj = json_decode($response);

	/**
	 * If either Status not set, or status is false, return original url.
	 */
	if (!isset($jsonObj->status) || $jsonObj->status == 'FALSE') {
		return $url;
	}

	return $jsonObj->url_main;
}
No Comments

Url to TinyUrl Function

Code

I needed to transform some long urls into tiny ones :p

Figured I’d post something up here that may be useful to someone else.

Code was updated.

/**
 * Get TinyUrl for $url
 *
 * @param string $url Must be a valid url
 */
function getTinyUrl($url) {
	if (! $url) {
		return false;
	}

	if (strlen ( $url ) < 30) {
		return $url;
	}

	$response = file_get_contents ( 'http://tinyurl.com/api-create.php?url=' . $url );

	return ($response) ? $response : $url;
}
No Comments