Charl van Niekerk » Blog

Main

Latest

Archives

Powered by Blogger

Zend Framework Google Login Example

Here is an example of how you can use Zend Framework to allow your users to log into your site using their Google Account access details.

<?php
 session_start();

 $email = isset($_REQUEST['email']) ? $_REQUEST['email'] : null;
 $password = isset($_REQUEST['password']) ? $_REQUEST['password'] : null;
 $captchaToken = isset($_REQUEST['captchatoken']) ? $_REQUEST['captchatoken'] : null;
 $captchaText = isset($_REQUEST['captchatext']) ? $_REQUEST['captchatext'] : null;

 if ($email && $password) {
  require_once 'Zend/Loader.php';
  Zend_Loader::registerAutoload();
  try {
   $client = Zend_Gdata_ClientLogin::getHttpClient($email, $password, 'xapi', null, 'Zend-ZendFramework', $captchaToken, $captchaText);
   $_SESSION['email'] = $email;
  } catch (Zend_Gdata_App_CaptchaRequiredException $e) {
   $captchaToken = $e->getCaptchaToken();
   $captchaUrl = $e->getCaptchaUrl();
  } catch (Zend_Gdata_App_AuthException $e) {
   $error = $e->getMessage();
  }
 }

 if (isset($_SESSION['email'])) {
  header('Location: profile');
  exit;
 }
?>
<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Zend Framework Google Login Example</title>
 </head>
 <body>
  <h1>Zend Framework Google Login Example</h1>
  <?php if (isset($error)): ?>
   <p><?php echo htmlspecialchars($error); ?></p>
  <?php endif; ?>
  <form method="post">
   <p><label for="email">Email:</label> <input id="email" name="email" type="text" value="<?php echo htmlspecialchars($email); ?>"></p>
   <p><label for="password">Password:</label> <input id="password" name="password" type="password"></p>
   <?php if (isset($captchaUrl)): ?>
    <div><input type="hidden" name="captchatoken" value="<?php echo htmlspecialchars($captchaToken); ?>"></div>
    <p><img src="<?php echo htmlspecialchars($captchaUrl); ?>" alt=""></p>
    <p><label for="captchatext">Text:</label> <input id="captchatext" name="captchatext" type="text"></p>
   <?php endif; ?>
   <p><button type="submit">Login</button></p>
  </form>
 </body>
</html>

I just don't want to have my password travel through somebody else's system. Surely there must be a better way? Can't we just do it like with Google App Engine?

Custom Muti Widgets

Here is some code, again making use of the Google AJAX Feed API, but this time you roll your own DOM so you have the world's flexibility of how you want the data to be displayed on your site.

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Google AJAX Feed API</title>

  <!-- Load the Google JavaScript library -->
  <script type="text/javascript" src="http://www.google.com/jsapi"></script>

  <!-- Add our own scripts -->
  <script type="text/javascript">
   // Decide which RSS feed you want to load
   var feedUri = "http://muti.co.za/by?name=charlvn&output=rss";

   // Load Google's feed engine
   google.load("feeds", "1");

   /**
    * Do the actual magic in this function. The content
    * gets dynamically loaded and pushed into the DOM.
    */
   function loadMuti() {
    // Disable the button before we start loading
    var button = document.getElementById("mutibutton");
    button.disabled = true;

    // Load the actual data via Google
    var feed = new google.feeds.Feed(feedUri);

    // Decide what happens after the feed has been loaded
    feed.load(function(result) {
     if (result.error) {
      // If the feed could not load, enable the button again
      button.disabled = false;
     } else {
      // Create and insert the necessary elements into the DOM
      var ul = document.getElementById("muti");
      for (var i = 0; i < result.feed.entries.length; i++) {
       var entry = result.feed.entries[i];

       // Create an anchor for the link
       var a = document.createElement("a");
       a.href = entry.link;
       a.appendChild(document.createTextNode(entry.title));

       // Create an item to insert into the unordered list
       var li = document.createElement("li");
       li.appendChild(a);
       ul.appendChild(li);
      }
     }
    });
   }

   /**
    * Ensure the button is enabled before refreshing,
    * otherwise some browsers might keep it disabled
    * even after the page has been reloaded.
    */
   function resetMuti() {
    document.getElementById("mutibutton").disabled = false;
   }
  </script>
  <style type="text/css">
   /**
    * This will apply to all elements in the DOM,
    * whether it is sourced from the original HTML
    * or dynamically generated via scripting.
    */
   #muti li a {
    color: white;
    background: green;
   }
  </style>
 </head>
 <body onunload="resetMuti()">
  <!-- This is the unordered list where the links will be populated -->
  <ul id="muti"></ul>

  <!-- Here is the button triggering the ajax action -->
  <button id="mutibutton" onclick="loadMuti()">Load My Muti Submissions</button>
 </body>
</html>

I tried to document it well so that you can see what's going on. Please comment if you have any questions though!

It's a real pity that we can't call google.load("feeds", "1") only after the user clicks the button. That would mean that if they do not click the button we can avoid loading the whole feed library. However this causes strange behaviour in many browsers, probably some document.write inside of the library or something of the sort, not sure.

This has been tested in Firefox 3.0.1 on Linux and seems to work fine. Not sure about other browsers. This is not something that should be used, it's just a demo, you build your own thing and use this as an example for learning. :)

We are still trying to support HTML 5 as far as possible, naturally.

Oh yes and as a last note. This should work with any public Atom or RSS feed, not just with muti.

I have a live demo of the code up if anybody wants it.

Google Social Graph API and PHP 5.2

This time I have been playing with consuming the Google Social Graph API in PHP 5.2 (using the JSON extension).

<?php
 $urls = array('http://charlvn.za.net/', 'http://blog.charlvn.za.net/');
 $q = urlencode(implode(',', $urls));
 $json = @file_get_contents("http://socialgraph.apis.google.com/lookup?q=$q&edi=1");
 $data = @json_decode($json, true);
 $me = array();
 $other = array();
 if ($data) {
  foreach ($data['nodes'] as $node) {
   foreach ($node['nodes_referenced_by'] as $domain => $ref) {
    if (in_array('me', $ref['types'])) {
     $me[] = $domain;
    } else {
     $other[$domain] = implode(', ', $ref['types']);
    }
   }
  }
 }
?>
<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Social Graph</title>
 </head>
 <body>
  <h1>Social Graph</h1>
  <?php if ($me): ?>
   <h2>Me</h2>
   <ul>
    <?php foreach ($me as $domain): ?>
     <li><a href="<?php echo htmlspecialchars($domain); ?>" rel="nofollow"><?php echo htmlspecialchars($domain); ?></a></li>
    <?php endforeach; ?>
   </ul>
  <?php endif; ?>
  <?php if ($other): ?>
   <h2>Other</h2>
   <ul>
    <?php foreach ($other as $domain => $relationship): ?>
     <li><a href="<?php echo htmlspecialchars($domain); ?>" rel="nofollow"><?php echo htmlspecialchars($domain); ?></a> <?php echo htmlspecialchars($relationship); ?></li>
    <?php endforeach; ?>
   </ul>
  <?php endif; ?>
 </body>
</html>

I have my social graph up as an example.

Sorry for the rel="nofollow" but I'm not going to encourage spammers.

Google AJAX Feed API Muti Example

Here is an example of how you can build a fancy Muti.co.za "widget" using the Google AJAX Feed API.

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Google AJAX Feed API Muti Example</title>
  <link rel="stylesheet" type="text/css" href="http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.css">
  <style type="text/css">
   body {
    margin: 40px;
    padding: 0;
    font: 0.8em verdana, arial, sans-serif;
   }
   h1 {
    margin: 20px;
    padding: 0;
    font: 2em verdana, arial, sans-serif;
    text-align: center;
   }
   #muti-feed {
    margin: 0 auto;
    max-width: 500px;
   }
   #muti-feed .loading {
    margin: 10px;
    padding: 4px;
    color: #676767;
   }
  </style>
  <script src="http://www.google.com/jsapi?key=notsupplied-wizard" type="text/javascript"></script>
  <script src="http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.js" type="text/javascript"></script>
  <script type="text/javascript">
   function LoadMutiFeed() {
    var feeds = [
     {title: "What's Hot", url: "http://muti.co.za/hot?output=rss"},
     {title: "Latest Submissions", url: "http://muti.co.za/new?output=rss"},
     {title: "Web Development", url: "http://muti.co.za/hot?tags=webdev&output=rss"},
     {title: "My Submissions", url: "http://muti.co.za/by?name=charlvn&output=rss"}
    ];
    var options = {
     stacked: true,
     horizontal: false,
     title: "Muti.co.za Social Bookmarks",
     numResults: 5,
     linkTarget: null
    };
    new GFdynamicFeedControl(feeds, "muti-feed", options);
   }
   google.load("feeds", "1");
   google.setOnLoadCallback(LoadMutiFeed);
  </script>
 </head>
 <body>
  <h1>Google AJAX Feed API Muti Example</h1>
  <div id="muti-feed"><span class="loading">Loading...</span></div>
 </body>
</html>

I have this up on a temporary URI. I say "temporary" not because I'm planning to remove it but because I can't guarantee its persistence. Yes, that is definitely not a cool URI. :)

This intends to support HTML 5.

Gnip API Changes

About three days ago, gnip decided to change their API, apparently without sending an e-mail to their (consumer) developers. The publisher.name attribute has been renamed to type and the twitter value has been changed to tweet. identica remains the same.

This broke the CLUG Micropark and I had to fix. Managed to come up with the following solution after some debugging. This has been checked into starstar with revision 5.

Index: update.php
===================================================================
--- update.php (revision 3)
+++ update.php (working copy)
@@ -33,7 +33,10 @@
 $data = file_get_contents('php://input');
 $xml = new SimpleXMLElement($data);
 foreach ($xml->activity as $activity) {
- $service = $activity['publisher.name'];
+ $service = $activity['type'];
+ if ($service == 'tweet') {
+  $service = 'twitter';
+ }
  $post_author_name = $activity['uid'];
  $post_author_uri = getAuthorUri($post_author_name);
  $post_date = date('Y-m-d H:i:s', strtotime($activity['at']));

But, why?

Google Maps and Geolocation

You can use the new google.loader.ClientLocation object to get the user's latitude and longitude and then display the user's location on an embedded map.

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Google Maps and Geolocation</title>
  <script type="application/javascript" src="http://www.google.com/jsapi?key=YOURKEYHERE"></script>
  <script type="application/javascript">
   google.load("maps", "2");
   function initialize() {
    var map = new google.maps.Map2(document.getElementById("map"));
    if (google.loader.ClientLocation && google.loader.ClientLocation.latitude && google.loader.ClientLocation.longitude) {
     document.getElementById("latitude").innerHTML = google.loader.ClientLocation.latitude;
     document.getElementById("longitude").innerHTML = google.loader.ClientLocation.longitude;
     map.setCenter(new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude), 10);
    } else {
     map.setCenter(new google.maps.LatLng(0, 0), 0);
    }
   }
   google.setOnLoadCallback(initialize);
  </script>
 </head>
 <body>
  <h1>Google Maps and Geolocation</h1>
  <div id="map" style="width:500px;height:500px"></div>
  <p>Latitude: <span id="latitude">Unknown</span></p>
  <p>Longitude: <span id="longitude">Unknown</span></p>
 </body>
</html>

This uses the user's source IP address; this didn't work directly from ISDSL but did work when I SSH piped through a server overseas.

I have this up on a temporary URI.

oEmbed, flickr and starstar

I have been playing with Flickr's oEmbed implementation just now and wrote the following script.

<?php
require_once 'db.php';
$rows = mysql_query('SELECT `post_content` FROM `post` WHERE `post_content` REGEXP "http://flickr.com/photos/[a-zA-Z0-9]+/[0-9]+"');
while ($row = mysql_fetch_assoc($rows)) {
  preg_match_all('#http://flickr.com/photos/[a-zA-Z0-9]+/[0-9]+#', $row['post_content'], $images);
  foreach ($images[0] as $image) {
    $data = @file_get_contents('http://flickr.com/services/oembed?url=' . urlencode($image));
    if ($data) {
      $xml = @new SimpleXMLElement($data);
      if ($xml && $xml->url) {
        $jpg = str_replace('.jpg', '_m.jpg', $xml->url);
        $alt = "$xml->title by $xml->author_name";
        echo "<a href='$image'><img src='$jpg' alt='$alt' title='$alt'></a>";
      }
    }
  }
}

This should work together with starstar. The API calls need to be cached though so will make a plan there before I commit it to subversion. Oh yes and the regular expression for the flickr usernames also probably needs checking. This is essentially WIP.

Copyright © 2004-2009 Charl van Niekerk. All articles are released under the Creative Commons Attribution 2.5 South Africa licence, unless where otherwise stated.