Wednesday, November 24, 2010

Creating an RSS feed with PHP and MySQL

What is RSS feed ?

RSS (most commonly expanded as Really Simple Syndication) is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format. An RSS document (which is called a "feed", "web feed", or "channel") includes full or summarized text, plus metadata such as publishing dates and authorship. Web feeds benefit publishers by letting them syndicate content automatically. They benefit readers who want to subscribe to timely updates from favored websites or to aggregate feeds from many sites into one place. RSS feeds can be read using software called an "RSS reader", "feed reader", or "aggregator", which can be web-based, desktop-based, or mobile-device-based.
http://en.wikipedia.org/wiki/RSS_feed

RSS is a technology that is being used by millions of web users around the world to keep track of their favorite websites.
Using RSS feed we can share our website content with the rest of the Internet.

The RSS format is based on XML that is built using standardised tags. Following is an example of RSS document.
<rss version="2.0">
<channel>
<title>RSS Feed</title>
<description>RSS Feed</description>
<link>http://mywebsite.com</link>
<lastBuildDate>Wed, 24 Nov 2010 09:47:31 +0100</lastBuildDate>
<language>en-us</language>
<copyright>Copyright (C) 2010 mywebsite.com</copyright>

<item>
<title>Sample title one</title>
<link>http://mywebsite.com/news1.html</link>
<description>This is the description of the smaple title one</description>
<pubDate>Wed, 10 Nov 2010 11:04:12 +0100</pubDate>
</item>
<item>
<title>Sample title two</title>
<link>http://mywebsite.com/news2.html</link>
<description>This is the description of the smaple title two</description>
<pubDate>Wed, 10 Nov 2010 11:03:24 +0100</pubDate>
</item>
<item>
<title>Sample title three</title>
<link>http://mywebsite.com/news3.html</link>
<description>This is the description of the smaple title three</description>
<pubDate>Wed, 10 Nov 2010 11:01:53 +0100</pubDate>
</item>
</channel>
</rss>

We can generate an RSS feed similar as the above sample using PHP and MySQL.

In this example we are listing the latest articles from the database are feed. For that we need a database table . If not not created, we can create a table using the following code..

CREATE TABLE `articles` (
`id` int(11) unsigned NOT NULL auto_increment,
`title` varchar(255) NOT NULL default '',
`link` varchar(255) NOT NULL default '',
`introtext` mediumtext NOT NULL,
`created` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

RSS feeds are using XML tags. So we are going to generate the XML tags using PHP.

Step 1 : Creating the header

header("Content-Type: application/rss+xml; charset=ISO-8859-1");

The first step is that , we need to tell PHP that what type of data we would like to output. In the header function we are specify that the content type is " application/rss+xml ". This will output a XML formated data into the browser.

Step 2 : Setup a Database connecction

Create a database connection to fetch the datas from the database.

DEFINE ('DB_USER', 'dbusername');
DEFINE ('DB_PASSWORD', 'dbpassword');
DEFINE ('DB_HOST', 'dbroot');
DEFINE ('DB_NAME', 'dbname');

$connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect to database');
mysql_select_db(DB_NAME) or die ('Error.. Could not connecct to database');
$query = "SELECT * FROM articles ORDER BY id DESC";
$result = mysql_query($query) or die ("Error.. Could not execute query");

Step 3 : Add RSS Feed Information

Next add the information about our RSS feed such as the title of it, the description, and a link to the the site.
Also add the xml version, rss version etc.

$rssfeed = '<?xml version="1.0" encoding="UTF-8"?>';
$rssfeed .= '<rss version="2.0">';
$rssfeed .= '<channel>';
$rssfeed .= '<title>RSS Feed</title>';
$rssfeed .= '<description>RSS Feed</description>';
$rssfeed .= '<link>http://mywebsite.com</link>';
$rssfeed .= '<lastBuildDate>Wed, 24 Nov 2010 09:47:31 +0100</lastBuildDate>';
$rssfeed .= '<language>en-us</language>';
$rssfeed .= '<copyright>Copyright (C) 2010 mywebsite.com</copyright>';
Step 4 : Adding RSS Items

Next, we need to extract our data by looping through our MySQL database to create the <item> tags.

while($row = mysql_fetch_array($result))
{
extract($row);
$rssfeed .= '<item>';
$rssfeed .= '<title>' . $title . '</title>';
$rssfeed .= '<link>http://mywebsite.com/news'.$id.'.html</link>';
$rssfeed .= '<description>[CDATA[' .$introtext . ']]</description>';
$rssfeed .= '<pubDate>' . $created . '</pubDate>';
$rssfeed .= '</item>';
}

Make sure you escape any characters that might cause your XML to invalidate, these characters include <, >, & - I like to enclose any content that may contain HTML inside a CDATA section.

Step 5: Close Channel, RSS tags and output the rssfeed.

$rssfeed .= '</channel>';
$rssfeed .= '</rss>';

echo $rssfeed;


Step 6: Validate your feed

Validate your feed using FeedValidator.org.


Full Source Code:
<?php
header("Content-Type: application/rss+xml; charset=ISO-8859-1");
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'fourjmktg9908_iapc');
$connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect to database');
mysql_select_db(DB_NAME) or die ('Error.. Could not connecct to database');
$query = "SELECT * FROM jos_content ORDER BY id DESC";
$result = mysql_query($query) or die ("Error.. Could not execute query");

$rssfeed = '<?xml version="1.0" encoding="UTF-8"?>';
$rssfeed .= '<rss version="2.0">';
$rssfeed .= '<channel>';
$rssfeed .= '<title>RSS Feed</title>';
$rssfeed .= '<description>RSS Feed</description>';
$rssfeed .= '<link>http://mywebsite.com</link>';
$rssfeed .= '<lastBuildDate>Wed, 24 Nov 2010 09:47:31 +0100</lastBuildDate>';
$rssfeed .= '<language>en-us</language>';
$rssfeed .= '<copyright>Copyright (C) 2010 mywebsite.com</copyright>';
while($row = mysql_fetch_array($result)) {
extract($row);
$rssfeed .= '<item>';
$rssfeed .= '<title>' . $title . '</title>';
$rssfeed .= '<link>http://mywebsite.com/news'.$id.'.html</link>';
$rssfeed .= '<description>[CDATA[' .$introtext . ']]</description>';
$rssfeed .= '<pubDate>' . $created . '</pubDate>';
$rssfeed .= '</item>';
}
$rssfeed .= '</channel>';
$rssfeed .= '</rss>';
echo $rssfeed;
?>

Save this file as index.php and save it in the folder named 'feed'. Now we can directly access the rss feeds from the browser using the link ' http://mywebsite.com/feed '

Monday, November 22, 2010

How to resize youtube embed video using regular expression ?

When we are creating a web application that let the user insert video embeds coming from YouTube or from Vimeo, or what ever else, there is the problem of the embed size. Most probably they will directly insert the embed code, that they are copied from youtube. This size of object tag (iframe, embed, object) may affect our design. If we are creating a video gallery we need to resize the embed code video into our size. In PHP we can use regular expression to resize the embed code.

Sample Code
<?php
//eg :
$video = "<object width="640" height="385">

<param value="http://www.youtube.com/v/bIx5vDn28eE?fs=1&amp;hl=en_US" name="movie" />

<param value="true" name="allowFullScreen" />

<param value="always" name="allowscriptaccess" /><embed width="640" height="385" allowfullscreen="true" allowscriptaccess="always" type="application/x-shockwave-flash" src="http://www.youtube.com/v/bIx5vDn28eE?fs=1&amp;hl=en_US"></embed></object>";


// our prefered size : width="208" height="103"
// regular exression to change the height and width
$pattern = "/height=\"[0-9]*\"/";
$video = preg_replace($pattern, "height='103'", $video);
$pattern = "/width=\"[0-9]*\"/";
$video = preg_replace($pattern, "width='208'", $video);
echo $video;

?>
The above code will resize the embed video into the size we are given.

If we want to add the 'wmode' in the video we can assign that value along with the width parameter.

eg :
$video = preg_replace($pattern, "width='208' wmode='transparent'", $video);

Thursday, November 18, 2010

How to check a radio button list is checked or not using javascript?

How to check a radio button list is checked or not using javascript ?


Radio Buttons are work in groups .If we have a set of radio buttons on a form , they are unchecked by default. We want an alert message if the radio buttons are not checked on submit.

Radio buttons are stored as an array, so we have to loop the array elements to see if one is checked or not.

To determine whether a particular button is pressed the syntax required is:
test = document.formName.radioGroupName[indexNumber].checked;

This will result a TRUE or False value . If the radio button is checked it will result a TRUE value, otherwise FALSE.

Sample Code

<script language="javascript">

function validate()

{

var flag = false;

for(var i =0 ;i<document.frmgraph.cond1.length; i++)

{

if(document.frmgraph.cond1[i].checked)

flag = true;

}

if(flag == false)

{

alert("Please select the group");

return false;

}

return true;

}

</script>

<form id="frmgraph" name="frmgraph" method="post" onsubmit="return validate();">

Male <input type="radio" name="cond1" id="cond1" value="male" />

Female <input type="radio" name="cond1" id="cond1" value="female" />

<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />

</form>



In this function the javascript will alert a message if the radio button is not checked.

Wednesday, November 17, 2010

New PHP V6 features

PHP is already popular, used in millions of domains (according to Netcraft), supported by most ISPs and used by household-name Web companies like Yahoo! The upcoming versions of PHP aim to add to this success by introducing new features that make PHP more usable in some cases and more secure in others. Are you ready for PHP V6? If you were upgrading tomorrow, would your scripts execute just fine or would you have work to do? This article focuses on the changes for PHP V6 — some of them back-ported to versions PHP V5.x — that could require some tweaks to your current scripts.

If you're not using PHP yet and have been thinking about it, take a look at its latest features. These features, from Unicode to core support for XML, make it even easier for you to write feature-filled PHP applications.

New PHP V6 features

PHP V6 is currently available as a developer snapshot, so you can download and try out many of the features and changes listed in this article.

Improved Unicode support
Much improved for PHP V6 is support for Unicode strings in many of the core functions. This new feature has a big impact because it will allow PHP to support a broader set of characters for international support. So, if you're a developer or architect using a different language, such as the Java™ programming language, because it has better internationalization (i18n) support than PHP, it'll be time to take another look at PHP when the support improves.

Unicode support at present can be set on a per request basis. This equates to PHP having to store both Unicode and non-Unicode variants of class, method and function names in the symbol tables. In short - it uses up more resources. Their decision is to make the Unicode setting server wide, not request wide. Turning Unicode off where not required can help performance and they quote some string functions as being up to 300% slower and whole applications 25% slower as a result. The decision to move it to the php.ini in my mind does take the control away from the user, and puts it into the hands of the Web Host.

If you compile PHP yourself or are responsible for this on your servers then you may be interested to know that PHP 6 will require the ICU libs (regardless if Unicode is turned on or off). The build system will bail out if the required ICU libs cannot be found. In a nutshell, you'll have another thing to install if you want to compile PHP.

Namespaces
Namespaces are a way of avoiding name collisions between functions and classes without using prefixes in naming conventions that make the names of your methods and classes unreadable. So by using namespaces, you can have class names that someone else might use, but now you don't have to worry about running into any problems. Listing 1 provides an example of a namespace in PHP.
You won't have to update or change anything in your code because any PHP code you write that doesn't include namespaces will run just fine. Because the namespaces feature appears to be back-ported to V5.3 of PHP, when it becomes available, you can start to introduce namespaces into your own PHP applications.


Listing 1. Example of a namespace

<?php
// I'm not sure why I would implement my own XMLWriter, but at least
// the name of this one won't collide with the one built in to PHP
namespace NathanAGood;
class XMLWriter
{
// Implementation here...
}

$writer = new NathanAGood::XMLWriter();

?>

Web 2.0 features

Depending on how you use PHP and what your scripts look like now, the language and syntax differences in PHP V6 may or may not affect you as much as the next features, which are those that directly allow you to introduce Web 2.0 features into your PHP application.

SOAP

SOAP is one of the protocols that Web services "speak" and is supported in quite a few other languages, such as the Java programming language and Microsoft® .NET. Although there are other ways to consume and expose Web services, such as Representational State Transfer (REST), SOAP remains a common way of allowing different platforms to have interoperability. In addition to SOAP modules in the PHP Extension and Application Repository (PEAR) library, a SOAP extension to PHP was introduced in V5. This extension wasn't enabled by default, so you have to enable the extension or hope your ISP did. In addition, PEAR packages are available that allow you to build SOAP clients and servers, such as the SOAP package.

Unless you change the default, the SOAP extension will be enabled for you in V6. These extensions provide an easy way to implement SOAP clients and SOAP servers, allowing you to build PHP applications that consume and provide Web services.

If SOAP extensions are on by default, that means you won't have to configure them in PHP. If you develop PHP applications and publish them to an ISP, you may need to check with your ISP to verify that SOAP extensions will be enabled for you when they upgrade.

XML

As of PHP V5.1, XMLReader and XMLWriter have been part of the core of PHP, which makes it easier for you to work with XML in your PHP applications. Like the SOAP extensions, this can be good news if you use SOAP or XML because PHP V6 will be a better fit for you than V4 out of the box.

The XMLWriter and XMLReader are stream-based object-oriented classes that allow you to read and write XML without having to worry about the XML details.

Things removed

In addition to having new features, PHP V6 will not have some other functions and features that have been in previous versions. Most of these things, such as register_globals and safe_mode, are widely considered "broken" in current PHP, as they may expose security risks. In an effort to clean up PHP, the functions and features listed in the next section will be removed, or deprecated, from PHP. Opponents of this removal will most likely cite issues with existing scripts breaking after ISPs or enterprises upgrade to PHP V6, but proponents of this cleanup effort will be happy that the PHP team is sewing up some holes and providing a cleaner, safer implementation.

Features that will be removed from the PHP version include:

* magic_quotes
* register_globals
* register_long_arrays
* safe_mode
* ereg removed from the core
* long variables (i.e. $HTTP_*_VARS)
* <?


magic_quotes

Citing portability, performance, and inconvenience, the PHP documentation discourages the use of magic_quotes. It's so discouraged that it's being removed from PHP V6 altogether, so before upgrading to PHP V6, make sure that all your code avoids using magic_quotes. If you're using magic_quotes to escape strings for database calls, use your database implementation's parameterized queries, if they're supported. If not, use your database implementation's escape function, such as mysql_escape_string for MySQL or pg_escape_string for PostgreSQL. Listing 2 shows an example of magic_quotes use.

Using magic_quotes (discouraged)
<?php
// Assuming magic_quotes is on...
$sql = "INSERT INTO USERS (USERNAME) VALUES $_GET['username']";
?>



After preparing your PHP code for the new versions of PHP, your code should look like that in Listing 3.

Using parameterized queries (recommended)

<?php
// Using the proper parameterized query method for MySQL, as an example
$statement = $dbh->prepare("INSERT INTO USERS (USERNAME) VALUES ?");
$statement->execute(array($_GET['username']));
?>


Now that support for magic_quotes will be completely removed, the get_magic_quotes_gpc() function will no longer be available. This may affect some of the older PHP scripts, so before updating, make sure you fix any locations in which this functions exists.

register_globals

The register_globals configuration key was already defaulted to off in PHP V4.2, which was controversial at the time. When register_globals is turned on, it was easy to use variables that could be injected with values from HTML forms. These variables don't really require initialization in your scripts, so it's easy to write scripts with gaping security holes. The register_globals documentation (see Resources) provides much more information about register_globals. See Listing 4 for an example of using register_globals.

Using register_globals (discouraged)

<?php
// A security hole, because if register_globals is on, the value for user_authorized
// can be set by a user sending them on the query string
// (i.e., http://www.example.com/myscript.php?user_authorized=true)
if ($user_authorized) {
// Show them everyone's sensitive data...
}
?>

If your PHP code uses global variables, you should update it. If you don't update your code to get prepared for newer versions of PHP, consider updating it for security reasons. When you're finished, your code should look like Listing 5.

Being specific instead (recommended)

<?php
function is_authorized() {
if (isset($_SESSION['user'])) {
return true;
} else {
return false;
}
}

$user_authorized = is_authorized();
?>

register_long_arrays

The register_long_arrays setting, when turned on, registers the $HTTP_*_VARS predefined variables. If you're using the longer variables, update now to use the shorter variables. This setting was introduced in PHP V5 — presumably for backward-compatibility — and the PHP folks recommend turning it off for performance reasons. Listing 6 shows an example of register_long-arrays use.

Using deprecated registered arrays (discouraged)

<?php
// Echo's the name of the user value given on the query string, like
// http://www.example.com/myscript.php?username=ngood
echo "Welcome, $HTTP_GET_VARS['username']!";
?>


If your PHP code looks like that shown in Listing 6, update it to look like that in Listing 7. Shut off the register_long_arrays setting if it's on and test your scripts again.

Using $_GET (recommended)


<?php
// Using the supported $_GET array instead.
echo "Welcome, $_GET['username']!";
?>

safe_mode

The safe_mode configuration key, when turned on, ensures that the owner of a file being operated on matches the owner of the script that is executing. It was originally a way to attempt to handle security when operating in a shared server environment, like many ISPs would have. (For a link to a list of the functions affected by this safe_mode change, see Resources.) Your PHP code will be unaffected by this change, but it's good to be aware of it in case you're setting up PHP in the future or counting on safe_mode in your scripts.

PHP tags

Microsoft Active Server Pages (ASP)-style tags — the shorter version of the PHP tags — are no longer supported. To make sure this is not an issue for your scripts, verify that you aren't using the <% or %> tags in your PHP files. Replace them with .

FreeType 1 and GD 1

The PHP team is removing support for both FreeType 1 and GD 1, citing the age and lack of ongoing developments of both libraries as the reason. Newer versions of both of these libraries are available that provide better functionality. For more information about FreeType and GD, see Resources.

ereg

The ereg extension, which supports Portable Operating System Interface (POSIX) regular expressions, is being removed from core PHP support. If you are using any of the POSIX regex functions, this change will affect you unless you include the ereg functionality. If you're using POSIX regex today, consider taking the time to update your regex functions to use the Perl-Compatible Regular Expression (PCRE) functions because they give you more features and perform better. Table 1 provides a list of the POSIX regex functions that will not be available after ereg is removed. Their PCRE replacements are also shown.

'var' to alias 'public'

PHP4 used 'var' within classes. PHP5 (in its OO move) caused this to raise a warning under E_STRICT. This warning will be removed in PHP6 and instead 'var' will mean the same thing as 'public'. This is a nice move but I if anyone has updated their scripts to work under E_STRICT in PHP5 it will be a redundant one for them.




PHP Engine Additions

64 bit integers
A new 64 bit integer will be added (int64). There will be no int32 (it is assumed unless you specify int64)

breaking to a label
No 'goto' command will be added, but the break keyword will be extended with a static label - so you could do 'break foo' and it'll jump to the label foo: in your code. We can jump the execution into a labeled point.

<?php
for ($i = 0; $i < 9; $i++) { if (true) { break blah; } echo "not shown"; blah: echo "iteration $i\n"; } ?>



ifsetor()

It looks like we won't be seeing this one, which is a shame. But instead the ?: operator will have the 'middle parameter' requirement dropped, which means you'd be able to do something like this: "$foo = $_GET['foo'] ?: 42;" (i.e. if foo is true, $foo will equal 42). This should save some code, but I personally don't think it is as 'readable' as ifsetor would have been.

foreach multi-dim arrays
syntactic sugar
This is a nice change - you'll be able to foreach through array lists, i.e. "foreach( $a as $k => list($a, $b))".


<?php
$a = array(
array(1, 2),
array(3, 4)
);
foreach( $a as $k => list($a, $b)) {
// blah
}
?>

{} vs []
You can currently use both {} and [] to access string indexes. But the {} notation will raise an E_STRICT in PHP5.1 and will be gone totally in PHP6. Also the [] version will gain substr and array_slice functionality directly - so you could do "[2,]" to access characters 2 to the end, etc. Very handy.

improvements to []

For both strings and arrays, the [] operator will support substr()/array_slice() functionality.
• [2,3] is elements (or characters) 2, 3, 4
• [2,] is elements (or characters) 2 to the end
• [,2] is elements (or characters) 0, 1, 2
• [,-2] is from the start until the last two elements in the array/string
• [-3,2] this is the same as substr and array_slice()
• [,] doesn't work on the left side of an equation (but does on the right side)




Resources
http://www.ibm.com/developerworks/opensource/library/os-php-future/
http://www.corephp.co.uk/archives/19-Prepare-for-PHP-6.html
http://www.php.net/~derick/meeting-notes.html

Monday, November 15, 2010

How to send email from your joomla component

Many times you will have the need to send emails from your joomla component. Users want to be notified immediately of changes on their sites, when a new article has been submitted, or a blog comment has been posted. Joomla provides email notifications to site administrator when a user has registered on their site.If you want to create a component and that component needs an email functionality, you dont need to create a custom email function for the component. Joomla provides a very helpful class for this.Thats JMail.


# Set the variables for the email message
$subject = "Subject for the email message";
$body = "Body of the email message";
$to = "user@domainname.com";
$from = array("admin@domainname.com", "Administrator");


# Invoke JMail Class

$mailSender = JFactory::getMailer();

# Set the sender array
$mailSender->setSender($from);

# Add the recipient - We can assign a single email address or an array of addresses

$mailSender->addRecipient($to);
$mailSender->setSubject($subject);
$mailSender->setBody($body);

# If you would like to send as HTML, include this line.
$mailSender->isHTML();
# Send the mail
if (!$mailSender ->Send())
{
echo "there is an error with the mail";
}


That's all for sending a simple email.If you would like to add carbon copy recipients, include the following before sending the email.



$mailSender->addCC("carboncopy@domainname.com");

# Add a blind carbon copy

$mailSender->addBCC("blindcopy@domainname.com");


It also has the option to add attachments.


If the file is in the server we can give the path.


$file = JPATH_SITE."/path/filename.doc";


$mailSender->addAttachment($file);


If we want to send an user uploaded file, then we have to give the option to upload the file.

The code is as follows.



Change the enctype of the form.


<form action="index.php" enctype="multipart/form-data" method="post" name="adminForm">

Add a file field within the form.



<input class="text_area" id="attachment" maxlength="250" name="attachment" size="32" type="file">









get the attached file.




$attachment = JRequest::getVar('attachment', null, 'files', 'array' );



$name_of_uploaded_file = $attachment['name'];
$config =& JFactory::getConfig();
$upload_folder = $config->getValue('config.tmp_path').DS;
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $attachment ['tmp_name'];

jimport('joomla.filesystem.file');
$uploaded = JFile::upload($tmp_path, $path_of_uploaded_file);
$mailSender->addAttachment($path_of_uploaded_file);






There are several more methods available in JMail.

You should also check out JMailHelper.

It provides several functions to help you secure input from users before passing it along in an email.

Adding sortable columns to a joomla component

Most of the joomla components have listing of data. And some of them dont have a sorting option in the listing. This tutorial explains that how to add a sortable column in a joomla component. To explain this we are taking the component 'com_profiler'.


The joomla the component 'com_profiler' is very helpful in profile making. It has a user listing in the administrator side. It lists the users list with name, username, groups, email etc. But this section doesnt have a sorting field. Usually you cant sort any fields in 'com_profiler' user list. This section explains how to add a sorting field in the admin section of comprofiler. Now we are going to change the username field in to a 'sorting' field.


Usually the user listing is generated by the comprofiler html page and comprofiler controller page. Path for these pages are as follows.


administrator/components/com_comprofiler/admin.comprofiler.html.php

administrator/components/com_comprofiler/admin.comprofiler.controller.php


Step 1 : Modify the admin.comprofiler.html.php


In admin.comprofiler.html.php there is a function named 'showUsers'. This function generates the list of users. In the showuser function we will add the 'ordering' code



global $mainframe;

$filter_order = $mainframe->getUserStateFromRequest( $option.'filter_order', 'filter_order', 'u.username', 'cmd' );

$filter_order_Dir = $mainframe->getUserStateFromRequest( $option.'filter_order_Dir', 'filter_order_Dir', 'asc','word' );
$lists1['order_Dir'] = $filter_order_Dir;

$lists1['order'] = $filter_order;


So the page will look like as

function showUsers( &$rows, &$pageNav, $search, $option, &$lists, &$pluginColumns ) {

HTML_comprofiler::secureAboveForm('showUsers');

// table ordering

global $mainframe;

$filter_order = $mainframe->getUserStateFromRequest( $option.'filter_order', 'filter_order', 'u.username', 'cmd' );

$filter_order_Dir = $mainframe->getUserStateFromRequest( $option.'filter_order_Dir', 'filter_order_Dir', 'u.username','word' );
$lists1['order_Dir'] = $filter_order_Dir;

$lists1['order'] = $filter_order;

outputCbTemplate( 2 );

outputCbJs( 2 );


Step 2 : Setting the Order Link

After that we can set the sorting link to the username field. Place the following code instead of the 'Usernmae' Title.


<?php echo JHTML::_( 'grid.sort', 'UserName', 'u.username', $lists1['order_Dir'], $lists1['order']); ?>

So the code will look like as follows.


<th width="15%" class="title"><?php echo CBTxt::T('Name'); ?></th>

<th width="10%" class="title">

<?php echo JHTML::_( 'grid.sort', 'UserName', 'u.username', $lists1['order_Dir'], $lists1['order']); ?></th>

<th width="5%" class="title" nowrap="nowrap"><?php echo CBTxt::T('Logged In'); ?></th>

Step 3 : Add the Hidden Fields


Also add the hidden fields to post the sorting field and sorting direction to the controller page. Add the following code before the end of the form


<input type="hidden" name="filter_order" value="<?php echo $lists1['order']; ?>" />

<input type="hidden" name="filter_order_Dir" value="<?php echo $lists1['order_Dir']; ?>" />

now the code will look like as follows.


<input type="hidden" name="option" value="<?php echo $option;?>" />

<input type="hidden" name="task" value="showusers" />

<input type="hidden" name="boxchecked" value="0" />

<input type="hidden" name="filter_order" value="<?php echo $lists1['order']; ?>" />

<input type="hidden" name="filter_order_Dir" value="<?php echo $lists1['order_Dir']; ?>" />
<?php

echo cbGetSpoofInputTag( 'user' );

?>

</form>

Step 4 : Modify the controller code (admin.comprofiler.controller.php)


The controller grabs the data from the database.


So we need to modify the function to list based on the order.


The controller contains a function named 'showUsers'.Edit the function to get the post values submitted from the listng page. Use the post method to assign the values. After placing the code the function will look like as


function showUsers( $option ) {

global $_CB_database, $_CB_framework, $_POST, $_PLUGINS, $_CB_TxtIntStore;

if(isset($_POST['filter_order']))

     $filter_order = $_POST['filter_order'];

else

     $filter_order = "u.username";



if(isset($_POST['filter_order_Dir']))

      $filter_order_Dir = $_POST['filter_order_Dir'];

else

     $filter_order_Dir = "asc";

Also modify the search query to get the ordered data.Add the ' ORDER BY' clause in the search query. After adding the ' ORDER BY ' clause the code will look like as the follow.


$query = "SELECT DISTINCT u.*, g.name AS groupname, ue.approved, ue.confirmed"

. $queryFrom

. " ORDER BY $filter_order $filter_order_Dir "

. "\n LIMIT " . (int) $pageNav->limitstart . ", " . (int) $pageNav->limit

;

That's all. Now in the user listing of the admin panel we have the 'user name ' filed as link. Now we can list the data's either in ascending order or by descending order.

Wednesday, November 10, 2010

Twitter Application development


What is twitter


Twitter is a status-updating or microblogging social networking website. It is a breakthrough in social networking because it takes communication into another level. Before, a person can only update his status (e.g. what he's doing, where he is) at a certain time. But with Twitter and its mobile integration, he can update his status almost all throughout the day and get in touch with people that matters to him the most.



But the functions of Twitter do not stop there. It is now used by various fields. Business, for example, has used Twitter to get in touch with customers on a personal level. It is also a nice place to meet people from different parts of the world that shares the same interests. Furthermore, its possibilities to promote new technology, news and products can't be denied.

Twitter have been used by companies, bloggers and agencies to promote their brand


Advantages and disadvantages of using Twitter for Internet Marketing


Advantages of twitter


Your Internet marketing can be done free of cost if you use Twitter wisely. Your target market is out there for you to seek and understand. Understand from their tweets, their passion and interests. Do your research on your target market by following the tweets of your target market for better understanding. Identify the strategies used by your competitors by following their tweets as well.

Twitter allows you to network efficiently and with large groups of people. Twitter and its third party applications allow you to segregate and interact with your target markets effectively. You can direct your Internet marketing campaigns at relevant groups efficiently by using Twitter

Twitter allows you to communicate directly with your target market instantly. Normally, the process of communication takes time. For example, if you have a Website, the communication would be via polls, which are not personal or though contact forms which are time consuming and impersonal as well. With twitter, you can expect instant communication with your target market. You may have just posted a tweet, but a reply from your target market could come in an instant as well. Twitter helps you to gather real time intelligence from your very own target market as well as obtain valuable feedback. The speed of communication is just fantastic with Twitter. Moreover, your near approach helps to builds lasting relationship as you will come cross as a company that cares for its consumers instead of just hard selling.


Disadvantages of twitter


Twitter is the number one site for spammers. You will have to filter and weed out spammers from your lists from time to time, if you want to have a good gauge of your target market. Otherwise, the followers total will be an inflated number which will not help in your Internet marketing campaigns. Filtering spam tweets is a lot of hard work. Other means of Internet marketing may seem feasible in the long run.



Twitter has no applications rather than other sites like Facebook, Friendster and MySpace. It also has no groups, videos, blogs, classified ads, forums, marketplace and other unique and popular social networking menus. You can only upload one picture, which is your avatar and must be small, compare to other social networks which you can upload pictures as many as you want. You also cannot upload music files here on Twitter, but you can upload on the other social networks.


What does twitter do for businesses?


Twitter is a communication platform that helps businesses stay connected to their customers. As a business, you can use it to quickly share information with people interested in your company, gather real-time market intelligence and feedback, and build relationships with customers, partners and other people who care about your company. As an individual user, you can use Twitter to tell a company (or anyone else) that you've had a great—or disappointing—experience with their business, offer product ideas, and learn about great offers.

How does it work?


Twitter lets you write and read messages of up to 140 characters, or the very length of this sentence, including all punctuation and spaces. The messages are public and you decide what sort of messages you want to receive—Twitter being a recipient driven information network. In addition, you can send and receive Twitter messages, or tweets, equally well from your desktop or your mobile phone.

When you combine messages that are quick to write, easy to read, public, controlled by the recipient and exchangeable anywhere, you’ve got a powerful, real-time way to communicate. And real-time communication is turning out to be ground-breaking for users and businesses alike.


How do businesses use Twitter?


Twitter connects you to your customers right now, in a way that was never before possible. For example, let’s say you work for a custom bike company. If you run a search for your brand, you may find people posting messages about how happy they are riding your bikes in the French Alps—giving you a chance to share tips about cyclist-friendly cafes along their route.

Others may post minor equipment complaints or desired features that they would never bother to contact you about—providing you with invaluable customer feedback that you can respond to right away or use for future planning. Still others may twitter about serious problems with your bikes—letting you offer customer service that can turn around a bad situation.

You don’t have to run a bike shop or a relatively small company to get good stuff out of Twitter. Businesses of all kinds, including major brands, increasingly find that listening and engaging on the service leads to happier customers, passionate advocates, key product improvements and, in many cases, more sales.


A key benefit


One of Twitter’s key benefits is that it gives you the chance to communicate casually with customers on their terms, creating friendly relationships along the way—tough for corporations to do in most other mediums.

But Twitter isn’t just about useful immediacy. The conversational nature of the medium lets you build relationships with customers, partners and other people important to your business. Beyond transactions, Twitter gives your constituents direct access to employees and a way to contribute to your company; as marketers say, it shrinks the emotional distance between your company and your customers. Plus, the platform lends itself to integration with your existing communication channels and strategies. In combination, those factors can make Twitter a critical piece of your company’s bigger digital footprint.

For instance, let’s say you run a big retail website. In addition to learning more about what your customers want, you can provide exclusive Twitter coupon codes, link to key posts on your blog, share tips for shopping online, and announce specials at store locations. And you can take things a step further by occasionally posting messages about fun, quirky events at your HQ, giving others a small but valuable connection with the people in your company.

Tip: Companies sometimes worry that twittering might require a lot of staff time or even hiring new people to maintain an account. In fact, Twitter works best for businesses when you start slow, devoting a few minutes a day to see whether and how it’s valuable to you.


Twitter Application development


We need to use the Twitter API and Twitter Content to develop a Service to search, display, analyze, retrieve, view, and submit information to or on Twitter


Twitter API


http://dev.twitter.com/pages/api_overview

Face book Application Development

Facebook is one of the fastest growing social networking websites and is quickly becoming a powerful and cost effective portal, ideal for organizations to create that ‘brand connection’ in the Web2.0 world.

http://www.facebook.com


What are Facebook applications?


Facebook applications are the software programs that allow users to connect, interact and entertain themselves and their ‘friends’.

Most Facebook users today use 3rd party Facebook applications to add some fun and personality to their Facebook profile. Their purpose is to generate content that the user finds is relevant or of interest to them.

There is virtually an application for everything, ranging from a Facebook application that reminds a user when their favorite band is coming to town to a slide show of a collection of sentimental photos. The great thing about Facebook applications is that if it is to be added to a profile, the users listed as a individual’s ‘friends’ are sent an option of also using it. The application then circulates at such a rapid rate exposure is viral.


Now a day’s most company’s developing facebook applications like gaming, interactive interfaces to promote their products etc.

http://www.facebook.com/apps/directory.php


Many site are integrated their facebook features into their sites

http://developers.facebook.com/showcase/


Facebook Application Development


We can create an application completely focused on our business brand. Think of a travel application that links to booking information on our website or a product catalogue of our latest products. All applications are designed to generate maximum interest on our business and draw continual international traffic to our website.

http://developers.facebook.com/


How to create a Facebook  Application


To create an application we need to register our application with facebook. Also we need to install the facebook developer kit.  Using the facebook application we can access information about the facebook profile even the non public information. For example if a facebook user register with our site , we can use facebook login for registering. If the user login with facebook we can collect the public information of the user including the emailid. So no need to confirm the email again, because it Is already confirmed by facebook. Also we can collect address, phone no, gender etc.


Tutorials to develop a Facebook application

http://developers.facebook.com/


Scope of facebook social plug-in   


A reader on your site, who is logged into her Facebook account, can now give your story a “Thumbs up” by simply clicking this Like button. She will also have to option to publish a snippet of your blog story on to her Facebook profile.

Then you have the Activity widget that shows in near real-time how people are interacting with your stories. If the user is logged into Facebook, the activity widget will show the activity of her friends on your web site else it’ll show everyone’s activity.

However, the most exciting social plug in for Facebook in the new recommendations engine. It shows a list of most popular stories on your blog as determined by the count of Facebook users who have “liked” that story.


To get started, we need to add our domain name to Facebook.


http://www.facebook.com/insights/


We basically need to verify that we are the actual owner of the domain and we can do this by simply adding a unique HTML META tag to our blog header.

Facebook will check the tag in our blog and once it’s verified, we can link the reports to either our Facebook profile or any Facebook page, if we own one.

Once everything is in place, we can revisit the Facebook Insights page to get detailed sharing stats of our blog pages. It will even tell us the top countries / cities of users who are interacting with our stories including the demographics.


If you have a forum or a blog site that requires registration, you may also explore the Sign-on widget that will let user registers on your site using their Facebook ID

This new tools from makes it possible for websites to allow you to connect with your friends and their likings. It helps you get first hand views and reviews from friends about the new movie which is the talk of the town, or the menu in any restaurant or the latest news. Not that it doesn’t allow strangers to give their feedback but it makes it possible for your friends to stand prominently.


The plugins makes it possible to show your action in the following ways you can either ‘like’ content, or you can ‘recommend’ such contents.  This makes it possible for you to connect with any content that you like publicly.


Alternately the tool also helps to remove or ‘unlike’ any new content or previously liked content. Another possible way is through the activity feed. This lets you know what your friends are doing with their likes and recommendations while visiting a particularly popular website.


Social plugins

All social plugins are extensions of Facebook and are specifically designed so none of our data is shared with the sites on which they appear.

We can add these plugins into our site by adding a group of code into our website.


Facebook  Plugins


1: Like Button


The Like button lets a user share your content with friends on Facebook. When the user clicks the Like button on your site, a story appears in the user's friends' News Feed with a link back to your website.


http://developers.facebook.com/docs/reference/plugins/like


2: Activity Feed


The Activity Feed plugin displays the most interesting recent activity taking place on your site. Since the content is hosted by Facebook, the plugin can display personalized content whether or not the user has logged into your site. The activity feed displays stories both when users like content on your site and when users share content from your site back to Facebook.


http://developers.facebook.com/docs/reference/plugins/activity


3: Comments


The Comments Box easily enables your users to comment on your site's content — whether it's for a web page, article, photo, or other piece of content. Then the user can share the comment on Facebook on their Wall and in their friends' streams.


http://developers.facebook.com/docs/reference/plugins/comments


Sample code

<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=APP_ID&amp;xfbml=1"></script><fb:comments xid="1234" width="425"></fb:comments>


4: Facepile


The Facepile plugin shows the Face book profile pictures of the user's friends who have already signed up for your site.

You can specify the maximum number of rows of profile pictures to display. The plugin dynamically sizes its height; for example, if you specify a maximum of four rows, and there are only enough friends to fill two rows, the height of the plugin will be only what is needed for two rows of profile pictures. The plugin doesn't render if the user is logged out of Facebook or doesn't have friends who have signed up for your site using Facebook.


Sample code

<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=APP_ID&amp;xfbml=1"></script><fb:facepile max-rows="5" width="600"></fb:facepile>


http://developers.facebook.com/docs/reference/plugins/facepile


5: Like Box


The Like Box is a social plugin that enables Facebook Page owners to attract and gain Likes from their own website. The Like Box enables users to:



  • See how many users already like this page, and which of their friends like it too

  • Read recent posts from the page

  • Like the page with one click, without needing to visit the page


http://developers.facebook.com/docs/reference/plugins/like-box


6: Live Stream


The Live Stream plugin lets users visiting your site or application share activity and comments in real time. Live Stream works best when you are running a real-time event, like live streaming video for concerts, speeches, or webcasts, live Web chats, webinars, massively multiplayer games.


http://developers.facebook.com/docs/reference/plugins/live-stream


7: Login Button


The Login Button shows profile pictures of the user's friends who have already signed up for your site in addition to a login button.

You can specify the maximum number of rows of faces to display. The plugin dynamically sizes its height; for example, if you specify a maximum of four rows of faces, and there are only enough friends to fill two rows, the height of the plugin will be only what is needed for two rows of faces.


http://developers.facebook.com/docs/reference/plugins/login


8: Recommendations


The Recommendations plugin shows personalized recommendations to your users. Since the content is hosted by Facebook, the plugin can display personalized recommendations whether or not the user has logged into your site. To generate the recommendations, the plugin considers all the social interactions with URLs from your site. For a logged in Facebook user, the plugin will give preference to and highlight objects her friends have interacted with.


http://developers.facebook.com/docs/reference/plugins/recommendations

Replace a string in the mysql database using REPLACE function

Many times we have the need to change the values of database fields. If our table contains thousands of records, its not possible to manually edit the records. So we can use MySQL REPLACE function to replace the string. The syntax to use the replace function is as follows.


UPDATE `table_name` SET `field_name` = REPLACE(`field_name`, 'Keyword to be replaced', 'Replacement String');

For example if we have changed the website name , we also need to change the datas in the downloads table (if we have).


Now we can use a single sql query with REPLACE function , and it will affect the whole records.


UPDATE `tbl_downloads` SET `sitename` = REPLACE(`sitename`, 'www.old-sitename.com', 'www.new-sitename.com');

now all the datas with 'old-sitename' will replace with the new-sitename

Romove the title from the vimeo video.

Usually we are using iframe to embedd a vimeo video.

It similar as the follow.


<iframe src="http://player.vimeo.com/video/123456789" width="400" height="300" frameborder="0"></iframe><p><a href="http://vimeo.com/123456789">Video Title</a> from <a href="http://vimeo.com/user123456">vimeo user</a> on <a href="http://vimeo.com">Vimeo</a>.</p>

While embedding with the iframe code the video title also with the video


If we want to remove the title and video owner name from the vimeo video , we can use embedd code .


The code will similar as the follow.



<object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=123456789&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portr ait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=123456789&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portr ait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object><p><a href="http://vimeo.com/123456789">Video Title</a> from <a href="http://vimeo.com/user123456">vimeo user</a> on <a href="http://vimeo.com">Vimeo</a>.</p>