No public Twitter messages.

Zend, Twitter, and OAuth Made Easy

October 3rd, 2009 by Ray in Computer Related, PHP/MySQL | Tags: , , | 3 Comments

I have been working on a Twitter service as of late and ran into a problem that I am sure others have as well and ended up solving it in their own way. However, after searching high and low on the Internet for an elegant solution, I came up with nothing and found I was on my own. This post is for those of you who are, or will be, using Zend_Service_Twitter and need Twitter users to grant your application access to their account information in a secure way.

The project I am working on requires that users allow my Twitter service to access their account information. The only reason I require this is because this service makes several API requests over the course of time, and instead of having users use up all of my allotted API service requests, I use their’s instead, It’s a little more complicated than that, and a full explanation falls outside the scope of this post. All you need to keep in mind for this post is that I need to have access to their account so API calls are counted on their behalf and not my server’s.

Currently, Zend Framework 1.9 only supports basic authentication for the Twitter API, which works well, but leaves, or should leave, a bad taste in the end-user’s and developer’s mouth. I say this because a developer who wants access to a user’s account at a later time (e.g. if you are running scheduled API calls) will have to store the user’s credentials on the server. This means A) the user may be iffy about using your service since they may not trust your site and/or want their password stored on your server, and B) this creates more overhead for you because you now have to keep track of user information, keep it secure, etc. The way we get rid of this bad taste is to implement a system such as OAuth.

OAuth is an authentication protocol that allows secure API authorization for applications. What this means is that a user can grant you, the 3rd party developer, access to their information without providing you with their username and password. User login takes place at the source, in this case at Twitter.com. For more information about OAuth, please see the Twitter API Wiki / OAuth FAQ

If you are currently using the Twitter API, it is probably better to change over to using OAuth sooner than later since support for basic authentication will be going away in the future.

In order to get Zend_Service_Twitter working with OAuth, you will need to obtain OAuth via subversion since it is not in the currently released version of Zend Framework. It can be obtained here.

The code you are about the see takes place in my IndexController, meaning I am using Zend’s MVC setup. I have also put configuration information inline so you can see exactly what is passed into each object.

<?php

/**
 * Default Index Controller using Zend's MVC implementation.
 *
 * @author Raymond J. Kolbe <rkolbe@white-box.us>
 */
class IndexController extends Zend_Controller_Action
{
    /**
     * Login Action
     *
     * Performs user login through Twitter using OAuth.  If user's have not
     * granted our application access to their account, they will be sent to
     * Twitter to do so.  Once done, they will return to this page again so
     * that we can handle them (e.g. run our application for them).
     *
     * @param void
     * @return void
     */
    public function loginAction()
    {
        // Check to see if the user already has an OAuth access token
        if ($this->_session->access_token) {
            // You would redirect the user to the main part of your
            // application that they needed to be authenticated for.
        }

        // Configuration for OAuth. @see Zend_Oauth_Consumer
        $config = array(
            'signatureMethod' => 'HMAC-SHA1',
            'callbackUrl' => 'http://localhost/login',
            'requestTokenUrl' => 'http://twitter.com/oauth/request_token',
            'authorizeUrl' => 'http://twitter.com/oauth/authorize',
            'accessTokenUrl' => 'http://twitter.com/oauth/access_token',
            'consumerKey' => 'jDrJud90Jhg66whddj876',
            'consumerSecret' => 'UdjneHdyGsj90Bsg2UdjneHdyGsj90Bsg2'
        );

        $consumer = new Zend_Oauth_Consumer($config);

        // If we do not have a request token, generate one now
        if (!$this->_session->request_token) {
            $request_token = $consumer->getRequestToken();

            // Save the token for when the user returns to this page.
            // This will be used to get the user's access token.
            $this->_session->request_token = serialize($request_token);

            // Send the user off to Twitter to grant our application access
            $consumer->redirect();
            return;
        }

        // If we made it here, the user has been to Twitter to grant our
        // application access and now we must get an access token that
        // will allow us to make API calls on behalf of the user.
        $access_token = $consumer->getAccessToken($this->_request->getQuery(), unserialize($this->_session->request_token));

        // We no longer need the request token so remove it
        unset($this->_session->request_token);

        // Save to session so that reloading of this page will send the user
        // to your application main page or wherever you want them to go.
        $this->_session->access_token = serialize($access_token);

        // This line is very important. Since Zend_Service_Twitter does
        // not have support for OAuth (yet), this is how we get it to work.
        // All we are doing is making Zend_Service_Twitter use OAuth's
        // HTTP Client instance, which will automatically append the proper
        // OAuth query info to any Twitter service call we make from here
        // on out.
        Zend_Service_Twitter::setHttpClient($access_token->getHttpClient($config));

        // Username and password are passed in as null because we will not be
        // authenticating using a user/pass combo (which uses basic
        // authentication).
        $twitter = new Zend_Service_Twitter(null, null);

        // This is not required but shows you as an example that OAuth did
        // in fact work.
        $response = $twitter->account->verifyCredentials();

        // Your code goes here.  This would be the point you want to save
        // the access token to the database for later use and/or save a cookie
        // on the user's system.
    }
}

Solar e-mail helper that stops spammers

August 19th, 2009 by Ray in Cookbook, PHP/MySQL, Solar | Tags: , , | No Comments

Tonight I created a helper for Solar that encodes mailto href addresses so SPAMers that scrape HTML pages will never get your addresses.

To use this helper, just do the following in your views/layouts:

echo $this->email('someuser@somehost.com', 'Ray');

Here is the helper code:

<?php

/**
 * Generates an encoded mailto href to stop spammers from scrapping email
 * addresses from your web pages.  This code is based on the PHP example
 * from http://rumkin.com/tools/mailto_encoder/
 *
 * @category Whitebox
 * @package Whitebox_View
 * @author Raymond J. Kolbe <rkolbe@gmail.com>
 */
class Whitebox_View_Helper_Email extends Solar_View_Helper {
    /**
     * The encoded email address.
     *
     * @var string
     */
    protected $_encoded_string = '';

    /**
     * The encoded index used to decode $_encoded_string/
     *
     * @var string
     */
    protected $_encoded_indexes = '';

    /**
     * Generates an encoded mailto href to stop spammers from
     * scrapping email addresses off your web pages.  Returns
     * an inline javascript code block that allows web browser
     * to read the mailto href.
     *
     * If javascript is disabled in the web browser, only the
     * link text is shown to the user.
     *
     * @param string $spec The email address (e.g. rkolbe@gmail.com)
     * @param string $text Href
     * @param array $attribs An array of href attributes
     * @return string An inline string of javascript to handle the
     * encoded mailto href
     */
    public function email($spec, $text = null, $attribs = null) {
        // escape the email address
        $spec = $this->_view->escape($spec);

        // build attribs, after dropping any 'href' attrib
        $attribs = (array) $attribs;
        unset($attribs['href']);
        $attribs = $this->_view->attribs($attribs);

        $this->_obfuscate("<a href=\"mailto:$spec\"$attribs>$text</a>");

        $script = $this->_getScript();
        $script .= '<noscript>'.$text.'</noscript>';

        return $script;
    }

    /**
     * Takes a given href and obfuscates it.
     *
     * @param string $link A full mailto href
     * @return void
     */
    protected function _obfuscate($link) {
        $scrambled_chars = str_shuffle($link);
        $this->_encoded_string = $this->_escapeString($scrambled_chars);

        $string_indexes = '';
        for ($i = 0; $i < strlen($link); $i++) {
            $index = strpos($scrambled_chars, substr($link, $i, 1)) + 48;
            $string_indexes .= chr($index);
        }

        $this->_encoded_indexes = $this->_escapeString($string_indexes);
    }

    /**
     * Returns a block of javascript used to decode the mailto href.
     * This only allows web browsers to see the mailto address.
     *
     * @param void
     * @return string An inline block of javascript
     */
    protected function _getScript() {
        return $this->_view->scriptInline('<!--
            chars = "'.$this->_encoded_string.'";
            indexes = "'.$this->_encoded_indexes.'";
            href = "";

            for(j = 0; j < indexes.length; j++){
                href += chars.charAt(indexes.charCodeAt(j) - 48);
            }

            document.write(href);
            // -->');
    }

    /**
     * Prepares (escapes) a string for javascript.
     *
     * @param string $string The string to escape
     * @return string The escaped string
     */
    protected function _escapeString($string) {
        $string = str_replace("\\", "\\\\", $string);
        $string = str_replace("\"", "\\\"", $string);

        return $string;
    }
}

Table view helper it out!

July 25th, 2009 by Ray in Cookbook, PHP/MySQL | Tags: , , | No Comments

Table view helper has been released! Since my last post about writing a helper such as this, a lot has changed. I hope to have API docs up soon. In the meantime you can download the code and check out the examples at its new project page.


Table helper

July 9th, 2009 by Ray in PHP/MySQL, Solar | Tags: , | No Comments

Thought I would give you all a sneak peek at the table helper class I am working on. I’m not a big fan of table helper classes but I kind of found a use for a helper such as this for one of my projects–plus it’s neat.

$table = new Table();

$table->setCssId('my_table');
$table->addCssClasses('default big_text');

$thead = $table->addGroup('thead')->addCssClass('thead_tag_css_class');

$row1 = $thead->addRow()->addCssClass('sample_css_heading');
$row1->addHeadingCell('Name');
$row1->addHeadingCell('Sex');
$row1->addHeadingCell('Position');
$row1->addHeadingCell('Top 2 favorite colors')->colSpan(2);

// rows that are not instantiated from addGroup() are added to tbody
$row2 = $table->addRow();
$row2->addDataCell('Adam Smith');
$row2->addDataCell('Male');
$row2->addDataCell('Economist');
$row2->addDataCell('Black');
$row2->addDataCell('White');

$tfoot = $table->addGroup('tfoot');

// empty data cells make sure we are compliant
// empty cells default to &nbsp;
$row3 = $tfoot->addRow();
$row3->addDataCell('example footer data');
$row3->addDataCell();
$row3->addDataCell();
$row3->addDataCell();
$row3->addDataCell();

// we can also just call print $table;
print $table->display()

Produces…

<table id="my_table" class="default big_text">
    <thead class="thead_tag_css_class">
            <tr class="sample_css_heading">
        <th>
            Name
        </th>
        <th>
            Sex
        </th>
        <th>
            Position
        </th>
        <th colspan="2">
            Top 2 favorite colors
        </th>
    </tr>
    </thead>
    <tfoot>
            <tr>
        <td>
            example footer data
        </td>
        <td>
            &nbsp;
        </td>
        <td>
            &nbsp;
        </td>
        <td>
            &nbsp;
        </td>
        <td>
            &nbsp;
        </td>
    </tr>
    </tfoot>
    <tbody>
            <tr>
        <td>
            Adam Smith
        </td>
        <td>
            Male
        </td>
        <td>
            Economist
        </td>
        <td>
            Black
        </td>
        <td>
            White
        </td>
    </tr>
    </tbody>
</table>

I still have some refactoring/testing/fixing to do but I hope to release this package soon under the GPLv3. I have also been throwing the idea around of being able to have this class generate CSS tables–e.g. fetchCssTable() and displayCssTable() (something like that) that would return both a CSS stylesheet and the proper div tags for the table itself.

Once I’m happy with this package I will also convert it over to Solar since it lacks this type of helper.


Maillog Logger 0.2.0alpha1 released

July 4th, 2009 by Ray in Maillog Logger | Tags: | No Comments

It’s out!  Maillog Logger 0.2.0alpha1 was released overnight and is a great improvement over 0.1.0.  We now have new CSS styles, MySQL vs. SQLite for security, and an easier install procedure.

Get it now!


Savant3 URI Plugin

June 14th, 2009 by Ray in PHP/MySQL, Solar | Tags: , , | No Comments

I started working on a small project last weekend for a [H]ard|Forum member that would allow viewing maillog log info from a web site. I wanted to make an app that would have a small footprint and would be easy to manage (code base wise as well as UI). My first instinct was to use a MVC framework like Solar or Zend but those two have more features than what I needed for this project. Remember, I wanted a small footprint.

I decided to give Savant3 a shot. This at least allows me to separate my controller logic from my view logic. I only had one controller and one template so code overhead wasn’t an issue.

One of the things missing from this system was a way to easily handle URIs/URLs. Since Savant3 is a template engine, I wouldn’t necessarily expect a URI handler. However, I felt that having a plugin that handles URIs was worth the effort, even with a project of this size.

Since the plugin code is still a bit messy (missing inline docs, needs a little bit of refactoring, etc) I can only show you usage examples for now. I plan on cleaning up the code and releasing the plugin on this site shortly.

Here is how one might use this URI plugin in a Savant3 template:

// builds the URI based off of the current URL
$uri = $this->uri()->fromCurrentUrl();

// allows setting query info
$uri->query = 'order=name_asc';

// this adds to the query, it does not overwrite it
$uri->query = 'page=2';

// returns only the query portion: '?order=name&page=2'
$uri->get();

// this will update page to 'page=3'
$uri->query = 'page=3';

// again we only return the query portion: '?order=name&page=3'
$uri->get();

// we can also set a full query as well and we can provide keys without values
$uri->query = 'order=name_desc&page=3&submitted'

// currently there is not a way to remove a single piece of the query
// we have to reset the whole query and rebuild it
unset($uri->query);

// passing 'true' to get() gives us the whole URI
// for example: http://white-box.us/somedir/index.php
$uri->get(true);

The rest of the functionality works much like Solar_Uri (currently w/the exception of path and query behavior), being able to set each piece of the URI before returning a newly built URI.


Dropbox API

May 29th, 2009 by Ray in Computer Related, PHP/MySQL | Tags: , , | No Comments

http://code.google.com/p/dropbox-api/

A while back (3 or 4 months) I emailed the guys over at Dropbox asking them about a public API. The response I got was basically that in the near future they will have something. I want it now!! Guess I will have to keep tabs on that Google Group (link above).


Modifying Solar_View_Helper_Form

May 23rd, 2009 by Ray in Cookbook, PHP/MySQL, Solar | Tags: , | No Comments

Solar comes packed with many different view helpers that will make your life easier, such as inserting images, creating links, and generating forms. However, sometimes a generic helper doesn’t cut it for custom behavior in a project. For example, I wanted to change the way form field hints (field descriptions) and error messages were displayed for the registration form at http://fahwebmon.white-box.us. Note that I am using Solar_View_Helper_Form::auto() to generate my form automagically. The only downside to this is that you do not have control over where errors are displayed on a page.

Read the rest of this entry »


BBCode PHP Syntax Highlighting For Lazy People

April 26th, 2009 by Ray in Cookbook, PHP/MySQL | Tags: , | No Comments

While working on one of my little side projects, I came across a problem where I wanted to highlight bbcode syle php tags in my text (e.g. [PHP] echo “code goes here”; [/PHP]).

Being lazy and using regex (I love it!), I came up with the following solution:

// test text w/embedded code
$text = "This is a sample text string with PHP style tags. [PHP] echo 'Hello'; [/PHP]

// and I made sure to make this case insensitive.
$pattern = "/\[PHP\](.*)\[\/PHP\]/Uis";

// the magic!
$matchCount = preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);
if ($matchCount !== false && $matchCount > 0) {
    foreach ($matches as $match) {
        // highlight_string forces us to start with at least the php opening tag
        $highlightedCode = highlight_string('<?php'.$match[1].'?>', true);

        // finally, replace the original non-highlighted text with the highlighted text
        $text = preg_replace($pattern, $highlightedCode, $text, 1);
    }
}

echo $text;

Just FYI, this was a quick one-off and wasn’t intended to scale with other bbcode style tags. Also, in my real code, the [PHP] tags are lowercase. The only reason they are uppercase is because the syntax highlighter in Wordpress isn’t smart enough to distinguish the tags in my code and tags to signify syntax highlighting.


Zend PHP5 Certification Study Guide Annoyance

April 18th, 2009 by Ray in Computer Related, PHP/MySQL, The Bin | Tags: , | 3 Comments

Zend PHP5 Certification Study Guide by Davey Shafik annoys me in many ways which include grammatical errors and erroneous coding examples.

Today’s rant will be on coding examples:

Page 133.

function __autoload($class)
{
//Require PEAR-compatible classes
require_once str_replace("_", "/", $class);
}

$obj = new Some_Class();

At first glance this looks OK but the author goes on to state that the file, Some/Class.php will be included automagically. WRONG! Autoload passes in the name of the class, not the name of the class plus .php at the end (which is what he is thinking). $class is really Some_Class, so the code above should read:

function __autoload($class)
{
//Require PEAR-compatible classes
require_once str_replace("_", "/", $class) . '.php';
}

$obj = new Some_Class();

I’m annoyed not just because the code is wrong, but because he says “When instantiating Some_Class, __autoload() is called and passed “Some_Class.php” as its argument.” If Mr. Shafik took just a couple of minutes to read the documentation, he would have realized he was wrong, and I could avoid some frustration this book has (and still is) caused me.