Jul 12 10

How to fetch, parse, cache, and display your external RSS and Atom feeds and mediaRSS on your website using SimplePie

by Ali

If you ever faced a scenario where you had to parse the rss feed with image thumbnails placed inside “enclosure” tags, SimplePie is the perfect solution. In fact SimplePie can parse mediaRSS. There are several other php classes such as Magpie which can do the job as well. Magpie can parse rss2.0 enclosure but not mediaRSS and I had hard time getting enclosure parsed with Magpie. After spending hours, I tried Simple Pie and it worked like a charm.

SimplePie is a fast and feature rich PHP class that is very simple to use.

In few steps, you can use SimplePie to retrieve and parse any RSS or Atom feeds and display them on any PHP website. SimplePie also allows you to incorporate any type of data from any number of feeds. Here’s how you can setup SimplePie in three steps:

  • Download SimplePie and uncompress it
  • Place the “simplepie.inc” into a your “includes” folder under root directory of your website and include it into your calling script
  • Create a directory named “cache” (also in the web-accessible root directory) and make sure that it’s writable by the server (i.e., CHMOD to 755, 775, or 777)

Here’s the sample code to fetch, parse, cache, and display your external RSS and Atom feeds and mediaRSS on your website using SimplePie:

define('SIMPLEPIE', '/path/to/simplepie.inc');
 
 require_once(SIMPLEPIE); //include the simplepie class
  $url = 'http://www.parorrey.com/blog/feed/';
  $feed = new SimplePie(); // bake a new pie
  $feed->set_feed_url($url);  // provide feed url
  $feed->set_cache_duration (3600); // specify cache duration in seconds
  $feed->handle_content_type(); // text/html utf-8 character encoding
  $check = $feed->init(); // script initialization check
 
  if ($check){
 
  foreach ($feed->get_items() as $item) {
 
  if ($enclosure = $item->get_enclosure()) 
   $thumb = '<img src="'.$enclosure->get_link().'" 
       alt="'.$item->get_title().'"/>';
  else $thumb = '';
 
  $rss_feed .= '<div class="rssItem">
  <span class="date">
 '.$item->get_date('j F Y @ g:i a').'</span>
  <h3><a href="'.$item->get_permalink().'" 
       title="'.$item->get_title().'"
      target="_blank" rel="no-follow">'.$item->get_title().'
       <br/>'.$thumb.'</a></h3>		
<p>'.$item->get_description().'</p></div>
<div class="spacer dash"></div>';      
 
 }
}
 
echo '<div id="rssNews">'. $rss_feed .'</div>';

SimplePie also allows you to merge different rss feeds into one single stream.

$feed = new SimplePie();
$feed->set_feed_url(array(
	'http://your-domain1.com/your-feed1/', 
	'http://your-domain2.com/your-feed2/', 
	'http://your-domain3.com/your-feed3/'
	));

Here is where the cache directory should exist if you are using the default cache location:

/path/to/your/feed_page.php
/path/to/your/cache/
/path/to/simplepie/way/deep/in/directory/simplepie.inc

Please note that using ./cache (dot-slash-cache) means that the cache directory will be relative to the page that’s calling SimplePie, not SimplePie itself.

Hope that helps.

Cheers!

Jul 1 10

Facebook requires every developer to verify his Facebook account to create new applications

by Ali

While attempting to add another developer to my Facebook Application Settings panel after I tried to save his name, I got the following error:

“Validation failed.

Only verified developers can be added as listed developers of this application.”

A Google search brings this blog post which says here http://developers.facebook.com/blog/post/386 that

“Starting this week, we are requiring every developer to verify his or her Facebook account to create new applications. This is the same quick process that users go through when they want to do things like upload large videos.”

“You can verify your account by either confirming your mobile phone or adding a credit card to your account. Facebook will not charge your credit card if you add it to your account.”

Verifying mobile number did not resolve it and I suggested him to first add the application where I was adding him as developer and that worked for me. After he joined that Facebook app as a user, I could add him in the developers list.

Cheers!

Jun 25 10

Facebook applications will automatically upgrade to new data permissions on June 30

by Ali

Starting June 30, 2010, your Facebook application will only be able to read the publically available information of a user’s profile by default, the way data read permissions are granted in the platform. While the changes are broad in scope, none of them impact backwards compatibility: all of your existing code will continue to work.

The most important changes are:

  • Graph API
  • Data Permissions
  • OAuth 2.0
  • New SDKs
  • Facebook Connect Branding

To get access to user’s profile information, your facebook application must explicitly request all of the data it needs to function. For instance, if you want to incorporate a user’s events into your application, you would request the user_events extended permission.During the authentication process, the user is presented with a UI in which the user can authorize your application to access that specific part of her profile.

Following is the complete list of extended permissions for Graph API:

publish_stream, create_event, rsvp_event, sms, offline_access, manage_pages, email, read_insights, read_stream, read_mailbox, ads_management, xmpp_login, user_about_me, user_activities, user_birthday, user_education_history, user_events, user_groups, user_hometown, user_interests, user_likes, user_location, user_notes, user_online_presence, user_photo_video_tags, user_photos, user_relationships, user_religion_politics, user_status, user_videos, user_website, user_work_history, read_friendlists, read_requests.

To upgrade your require_login() authentication to Graph API authorization, please check my earlier post for how to authenticate using Facebook Graph API and simply add any extended permission that you may need in your app. Go the function “RequestforPermission” in that post and add your permissions in the

  'req_perms'=>'email,publish_stream'

Cheers.

Jun 22 10

Facebook Graph API authentication OAuth 2.0 replacing Require Login

by Ali

Facebook has recently introduced Graph API and simplified many things. The new Graph API attempts to drastically simplify the way developers read and write data to Facebook.The Graph API uses OAuth 2.0 for authorization. OAuth 2.0 is a simpler version of OAuth that developers used earlier for authorization as $facebook->require_login(). (by the way, old token still works)

In the previous version, RequireLogin was a one line simple way of getting authorization for user. When I upgraded to OAuth 2.0, I had a hard time getting my user authenticated which looked like very simple thing in pre Graph API days.

Here is how I finally manage to put together for my latest facebook app.

To authenticate user in Graph API, first of all, download the Facebook PHP SDK facebook.php and put it inside includes folder. After that, get the Application Id, API key, application secret and canvas url of your facebook app and put it inside following $fbconfig array.

$fbconfig['appid']  = "Application id here";
  $fbconfig['api']  = "API Key here";
  $fbconfig['secret']  = "App Secret here";
  $fbconfig['canvas_url']  = "http://apps.facebook.com/your_app_name/";
 
 
  try{
  include_once 'includes/facebook.php';
  }
  catch(Exception $o){
 print_r($o);				
	}
 
// Create our Application instance.
$facebook = new Facebook(array(
 'appId'  => $fbconfig['appid'],
 'secret' => $fbconfig['secret'],
 'cookie' => true,
 'domain' => "Your Canvas Callback URL domain here"
  ));
 $session = $facebook->getSession();
 if (!$session) {
echo RequestforPermission();
	}
else {	//got session
	try {
	$me = $facebook->api('/me');
 
	if(!IsApplicationUser($me['id'])) {
	//InsertApplicationUser($me);
            //create a function and insert the user info
             //into App DB for later use
	}
          }
 catch (FacebookApiException $e) {
RequestforPermission($fbconfig['canvas_url'] );
	}
    }

Please add this function “RequestforPermission” as well in this file.

function RequestforPermission($next_url) { 
	global $facebook;
	$loginUrl=$facebook->getLoginUrl(array(
	'canvas'=>1,
	'fbconnect'=>0,
	'display'=>'page',
	'next'=>$next_url,
	'cancel_url'=>'http://www.facebook.com/',
	'req_perms'=>'email,publish_stream',
	));
	return '<fb:redirect url="'.$loginUrl.'" />';
	  } // end redirect function

Put all this code into a file named “fb-authentication.php” and simply include “fb-authentication.php” in those files in your application where you want Facebook user authentication.

Hope that helps.

Cheers.

Jun 10 10

How to show/hide divs based on radio button selection using jQuery

by Ali

If you want a radio button selection to show certain Div contents and hide some other Div on the web page, and on another radio button selection, you need a different Div associated with that radio button hiding the unwanted one, read on.

This can be achieved very efficiently using jQuery. We can put the code inside “click” or “change” event of radio button group,

$("input[name$='group_name']").click(function(){
  }

and after getting the value of selected radio button by this:

var radio_value = $(this).val();

We can simply hide or show our required Divs using following:

 if(radio_value=='Yes') {
  $("#yes_box").show("slow");
  $("#no_box").hide();
  }

Here’s putting every together, simply put this code in your page inside script tags and it will work.

$(document).ready(function(){
 
  $("input[name$='group_name']").click(function(){
 
  var radio_value = $(this).val();
 
  if(radio_value=='Yes') {
    $("#yes_box").show("slow");
     $("#no_box").hide();
  }
  else if(radio_value=='No') {
   $("#no_box").show("slow");
    $("#yes_box").hide();
   }
  });
 
  $("#yes_box").hide();
  $("#no_box").hide();
 
});

Hope that helps.

Cheers.

May 24 10

how to unzip files on remote server using PHP script

by Ali

Uploading files to server is a daily chore every webmaster has to do and if you do it using some ftp client where each and every file and image, no matter how small it might be, is uploaded separately, it’s a real pain. Sometimes, It takes hours to get these files uploaded and even then some files are skipped somehow.

A very easy solution to this tedious task is to upload a compressed zip or tar file and uncompress it on server. If you have SSH access or your hosting control panel provide you extracting your compressed file, it’s very helpful. For instance, CPanel and HSphere provide both zipping and unzipping of files and folders on server. But not all hosting environments allow you to unzip files on server without SSH access.

An easy way to unzip file on server is to use following php script.

Just provide the zip file name and destination folder to extract files in the script and it will extract your files for you saving you hours of uploading headache.

  $destination = '/destination'; //blank for root folder
 
  $zip = new ZipArchive;
 
  $zip_file = $zip->open('www.zip');
 
  if ( $zip_file ) {
 
  $zip->extractTo(dirname(__FILE__).$destination);
 
  $zip->close();
 
  echo 'files successfully extracted to
      <strong>'.dirname(__FILE__).$destination.'
     </strong> directory.';
  }
  else {
  echo 'No donuts for you. :(';
  }

Hope it helps.

Cheers!

Apr 15 10

PHP/MySQL datetime formatting bypassing UNIX_TIMESTAMP

by Ali

PHP/MySQL datetime formatting bypassing UNIX_TIMESTAMP

Formatting MySQL date to something useful has been a pain for PHP developers for a long time.

Usually you would make your query return the datetime using UNIX_TTIMESTAMP and then using PHP date function, format it to your heart’s content like this:

  echo date("F jS, Y h:i:s A", $row->date);

But this method has a downside, you can’t use the * and have to put all the fields in the query to use UNIX_TIMESTAMP for datetime field and have it returned as timestamp.

A better way of doing this is, especially in the scenario when you have to use * in the query, by using PHP5 DateTime Object. This way you can avoid UNIX_TIMESTAMP.

$myDate = new DateTime($row->date); 
$date = $oDate->format("F jS, Y h:i:s A ");

Hope it helps.

Cheers!

Apr 12 10

Apple goes to war with Adobe by banishing Flash

by Ali

As Apple previewed the new version of its iPhone OS, it also has updated the agreement that developers must adhere to if they want to create applications for Apple devices.

Since the iPhone went on sale in 2007, Apple has not allowed Flash onto the device, essentially shutting Adobe out of the creative process behind building applications for the iPhone OS.

When asked, during his preview of iPhone OS 4.0, Steven Jobs, if there had been any change in Apple’s position on Flash. He simple replied, “No.”

Although it is not official why Apple would want to cause trouble for Adobe in this way, but most probably Apple wants to make it harder for developers to create an application for one platform, like Flash,and then pop out versions for other platforms, like the iPhone or Google’s Android.

Some speculate that it is because most online ads use Flash and Apple wants to replace them with their own ad solution, now called iAd.

And explain is that Adobe turned its back on Apple when the company was deeply troubled, and that Jobs never forgave them, and waited for an opportunity to get back.

Whatever the reason, Apple has gone to war with an old ally Adobe after having gone sore with another ally Google.

Mar 18 10

Ten Step Guide to Install Redmine project management application

by Ali

Having tried several open source project management and bug tracking tools, such as dotProject, mantis  etc, Ruby based Redmine is a good solution.

Redmine is a flexible project management web application written using Ruby on Rails framework. It should run on most Unix, Linux, Mac and Windows systems as long as Ruby & Ruby on Rails and RubyGems are available on that platform.

Step 1

For setting up Redmine on your server, you need SSH access. Log into your shell using putty or any other tool, and create a folder for rails application inside your user account but outside your public root, for instance if you are using CPanel to manage your hosting account, create a folder “rails_apps” inside your “/home” folder beside “/public_html “ folder.

First of all, change your directory to “rails_apps” by typing:

cd /home/your-user-account/rails_apps/

Step 2

Once inside folder “rails_apps”, download and extract the Redmine archive. First get the Redmine files by typing following command at shell:

wget http://rubyforge.org/frs/download.php/69449/redmine-0.9.3.tar.gz

Please make sure that you get the latest version of Redmine. You can get the latest version file path from here http://rubyforge.org/frs/?group_id=1850

Type following command to uncompress the Redmine file:

tar zxvf redmine-0.9.3.tar.gz

It will uncompress and create the directory redmine-0.9.3.

Step 3

Now set up your MySQL Database/user for Redmine installation. After setting up your mysql db and db user, rename “config/database.yml.example” to “config/database.yml” and edit this file in order to configure your database settings for “production” environment. Add your DB information here.

Sample DB information for MySQL

production:
  adapter: mysql
  database: redmine
  host: localhost
  port: 3307
  username: redmine
  password: my_password

Step 4

Change your directory to Redmine by typing following command:

cd  /redmine-0.9.3

Step 5

Redmine stores session data in cookies by default, which requires a secret to be generated. This can be done by running following command but make sure you are under the application root directory:

RAILS_ENV=production rake config/initializers/session_store.rb

Step 6

Create the database structure, by running the following command to create tables and an administrator account under the application root directory:

RAILS_ENV=production rake db:migrate

Step 7

Insert default configuration data in database, by running the following command:

RAILS_ENV=production rake  redmine:load_default_data

This step is optional but highly recommended, as you can define your own configuration from scratch. It will load default roles, trackers, statuses, workflows and enumerations.

Step 8

Test the installation by running WEBrick web server:

ruby script/server webrick -e production -d

Once WEBrick has started, point your browser to http://yourdomain.com:3000/. You should now see the application welcome page. Take special care to run above WEBrick command with –d to detach otherwise when you close the shell window, application will also shut down.

Step 9

Use default administrator account to log in:

login: admin
password: admin

Step 10

To get email notifications, set up SMTP server configuration.

Rename “config/email.yml.example” to “config/email.yml “ and edit this file to adjust your SMTP or pop email settings.

#Outgoing email settings
production:
  delivery_method: :smtp
  smtp_settings:
  address: mail.yourdomain.com
  port: 25
  domain: yourdomain.com
  authentication: :login
  user_name: redmine@yourdomain.com
  password: redmine

Don’t forget to restart the application after any change.

Cheers!

Mar 4 10

FBJS Quick Jump Menu for a FBML Facebook Platform App

by Ali

In a FBML Facebook App, your quick jump menu will require a little tweak to work in FBJS properly.
Just change your standard js jump menu from:

<select onchange="goto(this.options[this.selectedIndex].value)">
    <option value="page.php?id=1">Page1</option>
    <option value="page.php?id=2">Page2</option>
    <option value="page.php?id=3">Page3</option>
</select>

To this:

<select onchange="document.setLocation(this.getValue());">
   <option value="page.php?id=1">Page1</option>
   <option value="page.php?id=2">Page2</option>
   <option value="page.php?id=3">Page3</option>
</select>

Cheers.