How to make a new avatar with html/CSS

I just made a new avatar, but I only used Photoshop to shave off the grey background to save it as a png with transparent background. A quick post to show you how ...

Here is the How

  • 1. I made a screenshot of part of the background image of Exploring the web
  • 2. I wanted to have BB (Bob Belderbos) on top of that so I set up a h1 element with a span wrapped inside (for the matter of this exercise any elements would do because I am about to style them with CSS)
  • 3. I gave h1 the background of the towers and all styles (span could inherit).
  • 4. I used the span (child) tag for some specific styles:

    a. BB to be transparent => opacity: .7; 

    b. tweak a bit the positioning => position: relative; top: 0px; right: 15px;

Why this exercise?

Usually this goes as quick with Photoshop but I wanted to use the Limelight Google font (font of the headers on this blog) and I was too lazy to import it into Photoshop.

I think the conclusion is: CSS(3) is very versatile to quickly apply styles to your designs. It's one of the easiest languages to learn, and I use it for mockups often (much more than Photoshop) due to its flexibility

Images




Finally here: The google+ API

We had to wait a bit but the google+ API was officially launched yesterday. Only public data and posts can be accessed, but it is a start to get familiar with the API.

Simple Facebook API like start

Building an app is similar to the Facebook API. You start registering an app. When you put the obtained keys/secret in your code, you can use oauth2 to authorize and obtain a token. Then you can access the data (JSON response)

Examples

A. You can load your profile data in an array referring to me:

$me = $plus->people->get('me');

* note the similarity to Facebook: $me = $facebook->api('/me');

Response:


B. Your public activities:

  $optParams = array('maxResults' => 100);
  $activities = $plus->activities->listActivities('me', 'public', $optParams);

There are a bunch of more advanced examples in the API libraries

Links

See the API reference. Some issues you might run into (for example, I had a missing .crt file, see this post)

Progress

As said, only public data can be gathered. However the fact that you can authorize with Oauth2  is much better then another method I tried some weeks ago. I am eager to learn what other functionalities will be available next ...

My Reading List: load Google book preview in overlay

Google books API is cool, it gets you quite some info and it is easy to use. I used it in My Reading List ( you can read more here ) .

Book preview

Last week, apart from creating a widget, I tried to improve the code a bit for the book preview button. I programmed the book preview button to open an iframe overlay (fancybox) and tries to load the book's preview. If not found, it redirects to google's book page. 

Update

How does it work?

Below the script. After loading Google's jsapi library, google.setOnLoadCallback(previewTitle), is called. previewTitle is a function that tries to create a view of the book (googleID) you pass in (php get variable in this case). If it can't find it, alertNotFound is called which puts a message and redirects to google's book page. A wrapper div "viewerCanvas" is defined to load in the content. All this happens in the preview.php page that gets loaded in an overlay iframe upon clicking the google preview button (first printscreen)

Result:



More info

At the developers guide. Check this script out here

Nice Jquery plugin: Jeditable

With the increased use of My Reading List I added some scaffolding to edit and update the books a user added. This was requested by several users as well.

Effective and beatiful

This CMS kind of things are quite labor intensive, and you usually want it to be user friendly. A great plugin that answers both is jeditable which allows you to edit in place after clicking the element. It works in a wide variety of cases, especially the select box popping out is neat.

How does it work

The technique is rather simple: you point to a server side script that gets the variables POST-ed in id/value pairs. It's best to check out the plugin's page and start playing with the demo page

Video Demo

My Reading List Widget

As you can see at the right side, I created a widget with recent books I have read/ am reading/ want to read. This data is fetched from My Reading List, a Facebook App I created to integrate your reading into Facebook

Why a widget?

My first take was the complete app page in an iframe but it is cluttered (images below). Instead I wrote a widget page to get the last 4 to 6 titles from the My Reading List database dynamically. It's much cleaner now. Below it you can click to see all titles or to join the App. I always loved how you could integrate your Amazon reading list into Linkedin but wanted to have it on my blog + with Facebook integration  :)

Want your own?

You can! Just join My Reading List and start adding books. You then put an iframe on your site and point to http://fbreadinglist.com/widget.php?id=<your_fb_id>

Update

As you can see the original widget was black because I published it on Exploring the web which has a dark theme. I just made a white version which you see used on this blog:
http://fbreadinglist.com/widget_white.php?id=<your_fb_id>

Examples

First approach = cluttered:

Now: widget = better

When you hover over the book thumbs, you see the title, review, date. Clicking the thumb gets you to the My Reading List book page with Facebook comment box. I might wrap this in a Wordpress plugin one day.


Google+ API still due? You can already do stuff ...

After playing with some APIs, especially the Facebook one, I cannot wait till Google+ releases its API. However there are ways you can already import your profile and posts!

featured image

In this post I will show you how this is done with Rudimentary GooglePlus API, a very cool Python script that returns the dataset based on the "type" variable you give it (profile or posts). Then I will show you how you can process the obtained output with PHP. I will do the profile data, as it is a bit trickier to find the pieces as it not an associative array.

After experimenting a bit with it, the data seems to be at fixed positions which I tested with some Google+ IDs (by the way, click on your avatar in Google+ : your Google+ ID appears in the URL)

Getting profile

Here are two examples. See Rudimentary GooglePlus API for more details. For both examples, replace the id= number for your own or somebody else.

Process data

Here is my script that filters most of the profile information. I did not play much with the posts, but the "prettyposts" array is better structured, so with below code it should be fairly easy to get.

As said, the challenge was to find where the bits were. You can see from the array offsets, that some pieces are quite deep down in this multidimensional array that is obtained with json_decode (one of my favorite functions when dealing with API data processing!).

Funny enough the structure seems persistent testing 10 to 20 Google+ profile IDs. So this is something useful we can do already today. However I guess the Google+ API will blow us away ;)

   <html>
   <head>
   	<title>Google+ importer</title>
   	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   	<meta name="description" content="This page imports your google+ profile" />
   </head>
   <body>
   <?php
   // thanks!! to: 
   // http://point7.wordpress.com/2011/07/10/rudimentary-googleplus-api/ <--
   // more php https://github.com/jmstriegel/php.googleplusapi
   
   $user = $_GET['u'];
   
   $query = "http://my.syyn.cc/gpapi?id={$user}&type=profile";
   
   $out = file_get_contents($query);
   $response = json_decode($out, true);
   
   $g = array();
   $g['usr'] = ($response[2])? $response[2]: '';
   $g['avatar'] = ($response[3])? $response[3].'?sz=90': '';
   $g['name'] = ($response[4][3])? $response[4][3]: '';
   $g['title'] = ($response[6][1])? $response[6][1]: '';
   $g['location'] = ($response[9][1])? $response[9][1]: '';
   
   echo '<h1><a href="'.$g['usr'].'">'.$g['name'].'</a></h1>';
   
   echo '<h2>Personal Data</h2>
   	<ul>
   		<li>Avatar: <img src="'.$g['avatar'].'"></li>
   		<li>Title: ' .$g['title'] . '</li>
   		<li>Location: ' .$g['location'] . '</li>		
    	</ul>';
   
   
   if(!empty($response[14][1])) {
   	echo '<h2>About me</h2>
   			<p>'.$response[14][1].'</p>';
   }
   
   if(!empty($response[7][1])) {
   	echo '<h2>Work</h2>
   	<table><th>Company</th><th>Function</th>';
   	foreach($response[7][1] as $r) {
   		echo '<tr>';
   		echo '<td>'.$r[0].'</td>';
   		echo '<td>'.$r[1].'</td>';
   		echo '</tr>';
   	}
   	echo '</table>';	
   }
   
   if(!empty($response[8][1])) {
   	echo '<h2>Education</h2>
   	<table><th>Institute</th><th>Studies</th>';
   	foreach($response[8][1] as $r) {
   		echo '<tr>';
   		echo '<td>'.$r[0].'</td>';
   		echo '<td>'.$r[1].'</td>';
   		echo '</tr>';
   	}
   	echo '</table>';	
   }
   
   
   if(!empty($response[11][0])) {
   	echo '<h2>Links</h2>
   	<table><th>Name</th><th>URL</th>';
   	foreach($response[11][0] as $r) {
   		echo '<tr>';
   		echo '<td>'.$r[3].'</td>';
   		echo '<td><a href="'.$r[1].'" target="_blank" 
   			style="padding-left: 20px; background:url('http:'.$r[2].'') top left
   			no-repeat">'.$r[1].'</a></td>';
   		echo '</tr>';
   	}
   	echo '</table>';	
   }
   ?>
   </body>
   </html>

Two remarks

You can resize the avatar appending ?sz=size to it:

   $g['avatar'] = ($response[3])? $response[3].'?sz=90': '';

You can even put the corresponding social media icons for the link:

   	foreach($response[11][0] as $r) {
.. ..
   			style="padding-left: 20px; background:url('http:'.$r[2].'') top left

Result

My Google+ profile imported (no CSS applied):

google+ profile exported

Share

You can comment on this post and/or follow me

Facebook API: post with Perl from CLI

In the last post I explained how to post to a FB wall (yours or a friend) via a simple FB App, and with the FB PHP SDK 3. In this post I like to show the same but from the Command Line (CLI) and with Perl.

featured image

Purpose: find within your friends and liked pages, the fbID. This ID can then be entered to wallpost a URL and/or message. The webinterface makes this easy but from command line you can script (cron) it and easily extend it to send multiple updates at once. A first script (draft) is here

Requirements

As in the last post you need to have a valid FB APP. See next section where to go to get all preconfigured (= get a valid $access_token to input in your script)

Secondly your App needs to have the following extended permissions

  • publish_stream -> this allows the app to post to walls on your behalf
  • user_likes -> this allows the app to access your liked pages
  • offline_access -> I am still testing this but I believe this prevents the access token to expire in the standard 2 hours (FB permissions page: "Enables your app to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.")

Thanks to...

The harness for the script I made, comes from qscript.blogspot.com - this great post explains how Perl can talk with the Facebook API. Very cool and credits to this article! Of course there is more advanced stuff for accesing the API, but this article is a quick and easy way to get the job done.

Get access token

The only manual preparation is to get the access token in your script, then you are good to go. The only inconvenience is that the token expires if you use the normal permissions. It seems though that the offline_access permission prevents the timeout (and thus saves you from amending the script!)

Script logic

The script follows these steps:

  • you want to get the fbID of a 'friend' or a 'liked' page? If you know this info you can put in 'skip' to break out the first loop;
  • as you can have multiple results per query, you should still enter the fbID after breaking out of the first loop (alternatively make the script to get the fbID from the command line = shift @ARGV ; that was my initial approach but I wanted to have this lookup feature);
  • from this point we know where to post, but what? -> next you are asked to provide an URL and/or message to post to the wall of the fbID
  • Perl calls graph.facebook.com with method 'post'

Full code example

Again, you can download the code here . It is merely a draft, validation should be build in etc. Another RFE is to do the oauth process automatically.

   #!/usr/bin/perl -w
   #copyright (c) 2011 bob belderbos
   #created: August 2011 
   #site: http://bobbelderbos.com/2011/08/facebook-api-post-with-perl-from-cli/
   #special thanks: http://qscripts.blogspot.com/2011/02/post-to-your-own-facebook-account-from.html
   
   use strict;
   use URI;
   use LWP::Simple;
   use JSON; # imports encode_json, decode_json, to_json and from_json.
   
   my $access_token = '-----'; 
   # see http://qscripts.blogspot.com/2011/02/post-to-your-own-facebook-account-from.html
   
   sub build_query {
     my $uri = URI->new(shift);
     $uri->query_form(@_);
     return $uri->as_string;
   }
   
   while(1) { # infinite loop until you get the right fbID to post your link/message to
   	print "Enter 'friends' to find his/her ID, 'likes' to find the page ID, 
  		or enter 'skip' if you know this info: ";
   	chomp(my $cat = );
   	next unless $cat eq 'friends' || $cat eq 'likes' || $cat eq 'skip';
   	last if ($cat =~ /skip/i );
   	
   	print "Enter part of your friend's name or title of the liked page: ";
   	chomp(my $friend = );
   
   	my $response = get(build_query('https://graph.facebook.com/me/' .$cat,
   	  access_token => $access_token
   	));
   	my $deserialized = from_json( $response );
   
   	foreach my $e(@{$deserialized->{data}}){
   		print $e->{id} . ' - ' . $e->{name} . "\n" if $e->{name} =~ /$friend/i;
   	}
   	
   	print "Found ID of friend/ page you want to post to? ";
   	chomp(my $answer = );
   
   	last if ($answer =~ /y(es)?/i );	
   }
   
   
   # here you broke the 'lookup' loop so you know which ID to pick.
   # as there might be various candidates, you still have to enter the exact fbID
   print "Enter the ID of the page / friend you want to post to: ";
   chomp(my $fbID = );
   
   print "Enter the URL you want to send (if only a message, press Enter): ";
   chomp(my $link = );
   
   print "Enter a message (if you defined an URL, you can leave this blank by pressing Enter: ";
   chomp(my $message = );
   
   my $response = get(build_query('https://graph.facebook.com/'.$fbID.'/feed',
     access_token => $access_token,
     message      => $message,
     link         => $link,
     method       => 'post'
   ));
   
   print "Feedback post method: $response\n == END == \n";
   
   exit 0;

Demo

Here you can see the script in action -> 1. command line / 2. result on Facebook :

demo printscreen 1
demo printscreen 2

Also thanks

... to PRAEDO for changing the /me/friends into /me/likes to post to pages instead of friends, and his mention of fbcmd which is a command line interface (CLI) for facebook.

From here on ...

You can subscribe at the top of this page to receive each post in your Inbox. You can also keep up with my blog and discuss Web technology and programming at BobsBlog Facebook group And you can find me on Twitter @bbelderbos

Example Facebook PHP SDK: Post to Friend's wall

I got a question from one of my readers how to automatically post to the Wall of a friend. I started to code a quick example, but I realized it might be valuable to more people, so here is the code and a short howto.

featured image

This example is in PHP. You first create an app at the Facebook developer page, then you get the Facebook PHP SDK 3.0 and download it to the defined folder (localhost/whatever/). The complete code example is here

Here you can see how this looks :

Creating an app
Copy in the app codes

The SDK comes with an example php page, copy it over to the root of your project

Project structure
Login link
Login wrapper

For this exercise you need the extended permission publish_stream, which you append here:

Extended permission

Now when you login to the App you are asked for the normal and this extended permission:

Permission request

Now that your user is logged in you can get the friends with this bit of code:

Get friends

I embedded this in a form to choose the friend I want to message:

Design Form
Complete Form

The user selects his/her friend, writes a message / and/or puts in a link, and clicks submit. Index.php receives these 3 post variables and embeds them in the $facebook->api 'post' call.

Post to wall code

And that's it. It seems much work, but by adding the SDK you can make it a much more powerful application. Needless to say, you need to validate the ouputs obtained through this form. This is beyond the scope of this example. I zipped the code here to play with it yourself. Don't forget to first create your own App and put the App ID and Secret in the index.php page!

Demo

Here you see the form in action and the result on Roberto's wall:

Post to wall demo 1
Post to wall demo 2

7 cool Wordpress plugins (the sequel)

November last year I wrote a post about 10 great Wordpress plugins - since then I kept blogging and installing plugins from time to time to leverage the power of this platform. Today a short post with 7 more useful plugins.

UPDATE 30.08.11:

If you like widgets read on. I actually came to the conclusion I had way to much clutter on my blog I did a big cleanup. My site feels faster now, and I kept the essential stuff, but much more compact. I will write a post soon, what I could declutter


Feedburner Email Widget

featured image

I really like this Google service so I put the subscribe box as the first option for readers in the sidebar. When you put your email in it, the Feedburner Email Widget pops up a Feedburner dialog guiding the user through the signup process.

MailChimp Widget

I played a bit with MailChimp a few months ago to set up a weekly newsletter (to be fired off weekly if there are new posts). It is a great piece of software behind an awesome interface. The MailChimp Widget gives you quite some flexibility in adding a subscription input field to your site (sidebar)

the first two plugins combined

googleCards

I mentioned this one some weeks ago - more info on the plugin site

Twitter Facebook Social Share

I got various readers asking how I got the share buttons floating box at the left. I discovered this recently on Fluent in 3 months (an interesting language learning site) and other sites. There are various plugins available. I started with Twitter Facebook Social Share which gives a pretty neat floating box! However the left floated box overlaps my content depending of the width of my browser app. That is why I prefer to use Sharebar

This plugin shows a float of buttons if the browser window is at least 1000px, if you resize your window, the float disappears and the buttons appear at the top of the post. This is very nice!

Moreover, the plugin creates a table in your WP database and you can edit / delete the social buttons. You can even edit the corresponding table and add buttons that were not there previously (google+ and linkedin). I also like the Sharethis button, so that users can share to other services as well (there are too many social networks!). In the next printscreens you see the overlap of the first plugin, and the resizing of the website of the plugin to see the effect. You can also try it with this page, because I just implemented this solution!

overlap of 1st plugin
 share plugin
social share plugin

KC Related Posts by Category

From the same author as "Twitter Facebook Social Share" comes this related posts plugin : I used another plugin in the past but it would mess up the thumbnails and the algorithm was long not that smart as this plugin. Now the reader is invited to read (potentially) related articles of the end of my posts.

related posts of facebook fql post

Snazzy Archives

With Snazzy Archives you can make a very cool archive of your blog posts in time. I think I had to tweak the CSS to fit it into my site, but it played out nice

snazzy archives

EZPZ One Click Backup

There is a lot possible with EZPZ, but so far I only used the one-click-backup-all feature which is quite convenient. I need to check how I can incremental backups to Dropbox - I am sure it will be very easy

From here on ...

You can subscribe at the top of this page to receive each post in your Inbox. You can also keep up with my blog and discuss Web technology and programming at BobsBlog Facebook group And you can find me on Twitter @bbelderbos

My first week of Perl

... has been quite effective. I already solved some easy to intermediate problems with less code. I am far from mastering the language, but it is one of the few times I saw results this quickly

Learning path

featured image

I need to do some data mining and I was tired to have some sed, awk/ Unix utilities and some PHP. I wanted one solution. And although I have Python on my list to learn (as well as Ruby) by coincidence I stumbled upon this old Perl 4 tutorial from the early 1990's! It really wetted my appetite as it had some good exercises to get a hang of the basics. After finishing this short tutorial, I wanted something more detailed, so I went to the book shop and bought Learning Perl, 6th Edition (the 6th edition just came out in June 2011, this book is also called "the LLama"). This title is absolutely fantastic, quite thorough. It also has some good exercises that you really should do to rehash what you have read. I really understand most concepts now. After this one you can continue with Intermediate Perl and Mastering Perl of the same authors.

What I like about this language

Perl is very robust, there are few to no things you cannot do with it. It has strong support for Regular Expressions - this is particularly of interest for what I am going to use the language: text parsing (but I think Python is as powerful, I can probably tell in some months, because it is next on my agenda).

The shortcuts in syntax take a bit of time to get used to. There are special variables to save code. In a loop $_ automatically takes the iterator value and you don't need to mention it. See the next code example:

   #!/usr/bin/perl
   	use strict; 
   	open POST, '<', 'blogpost.txt';
   	while(< POST >){   #leave spaces out here! WP does not display this right
   		chomp; # take new line char off
   		print; # perl knows you want to print $_, the internal loop variable  
   	}
   	close POST;

Another example is when matching a regular expression:

   instead of
   	if ($sentence =~ /under/){
   	
   	} 
   you can write
   	if (/under/){
   	
   	} 

Compact syntax

I like the distinction in variable names: $ for a scalar, @ for a list (array) and % for a hash. You can assign a list to a @list and you get the complete list, but if you assign it to a $scalar you get the number of list items. There are many examples where you save typing. The language is well designed (thanks Larry)

Counting words in a text

An example how easy it is to get a hash of words found with their frequencies in this post (top 10):

   	#!/usr/bin/perl
   
   	use strict; 
   
   	my %words = (); # declares the hash in which we are going to store the words
   
   	open OUTPUT, '<', '2011.08.13_first_week_perl.txt'; #this post in txt file
   
   	while(< OUTPUT >){   #leave spaces out here! WP does not display this right
   		chomp; # get \n new line character off
   	
   		# break each line down in separate words
   		#split uses per default a space and works on $_
   		foreach my $word (split) {    
   			# store the word as key, and add +1 for each occurrence 
   	     	$words{$word}++;  
   	  	}
   	}
   
   	close OUTPUT;
   
   	# Output hash values in descending order 
   	foreach my $w ( sort { $words{$b} <=> $words{$a} } keys %words) {
   	    printf "%-10s %5d\n", $w, $words{$w} if $words{$w} > 10;
   	}

Outputs:

   	to            24
   	I             20
   	the           20
   	a             19
   	you           17
   	in            16
   	is            16
   	and           13
   	of            12
   	this          11

Another example I gave in my previous blogpost where I converted text into html (based upon some easy rules). I use it now as I write this post. It is an example of the many things you can use Perl to get things done and save time.

I didn't even experiment with Perl Modules and I haven't mentioned a lot of cool stuff. Read Learning Perl! More in another blog post I guess...

Conclusion:

  • Perl is a powerful and versatile language. You can use it for almost anything.
  • If you want to parse text (using Regex) Perl is a very good candidate.
  • It has a compact syntax which you need to get used to a bit but is not hard to learn. You will write less code eventually.
  • I enjoy more writing code in Perl than in PHP (might also be the "wow this is new/cool" effect, call it love at first sight)
  • There are great resources - the mentioned O'Reilly books are highly recommended. When you start googling for solutions you find a very active community.
  • For Regex Mastering Regular Expressions is a great title to learn in parallel.