Send & Receive mails to & from localhost

Mails don't work when locally but sometimes it might prove to be very useful in development if one can send & receive mails to & from localhost. It can be setup pretty easily too. Basic idea is to configure postfix for localhost & then use mutt to read local mails. Here is how it is done (should work fine for any UNIX based OS):

Install postfix

sudo apt-get install postfix

Install mutt

sudo apt-get install mutt

To configure postfix for localhost, specify the following in its config file at /etc/postfix/main.cf

myorigin = localhost
mydestination = $myhostname, localhost.$mydomain, localhost
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
relayhost =

Restart postfix

sudo /etc/init.d/postfix restart

Now you can read localhost mails using mutt

mutt

It will read emails from /var/mail/USERNAME

Ubuntu controlling network adapters through terminal

We all know that Ubuntu's network management is quite good but not there yet. One big issue with it is that, on some machines, disabling one type of network adapter, disables the other one too.

Like I use wifi to connect to the internet but my bluetooth is switched on by default all the time. And if I try to disable bluetooth it disables wifi too.

To control them via terminal or command line, you can do this (Atleast from Ubuntu 10.10 onwards):

ashfame@ashfame-xps:~$ rfkill list all
0: phy0: Wireless LAN
Soft blocked: no
Hard blocked: no
4: hci0: Bluetooth
Soft blocked: yes
Hard blocked: no

You see how it says soft blocked & hard blocked. Soft block is a switch in OS & hard block is a hardware switch in your machine.

You can disable the ones you don't want by:

rfkill block bluetooth

and enable the ones you want by:

rfkill unblock wifi

Disabling the ones you don't want will save you some battery if you are on a laptop/notebook/ultrabook.

Fetch comments of a specific category in WordPress

WordPress already provides an easy function for fetching the comments get_comments() but the function only supports fetching comments of a particular user, or for a particular post and not fetching comments of a particular category. The code for the former two cases, is pretty simple but the last one is not so simple. Here are the code snippets as examples:

Fetching Comments of a particular user

$args = array( 'number' => 10, 'status' => 'approve', 'user_id' => 1 );
$comments_list_by_user = get_comments( $args );
print_r ( $comments_list_by_user );

Fetching Comments of a particular post

$args = array( 'number' => 10, 'status' => 'approve', 'post_id' => 30 );
$comments_list_post = get_comments( $args );
print_r ( $comments_list_post );

Fetching Comments of a particular category

Here is how you can fetch comments for a specific category:

// Posts per page setting
$ppp = get_option('posts_per_page'); // either use the WordPress global Posts per page setting or set a custom one like $ppp = 10;
$custom_offset = 0; // If you are dealing with your custom pagination, then you can calculate the value of this offset using a formula

// category (can be a parent category)
$category_parent = 3;

// lets fetch sub categories of this category and build an array
$categories = get_terms( 'category', array( 'child_of' => $category_parent, 'hide_empty' => false ) );
$category_list =  array( $category_parent );
foreach( $categories as $term ) {
 $category_list[] = (int) $term->term_id;
}

// fetch posts in all those categories
$posts = get_objects_in_term( $category_list, 'category' );

$sql = "SELECT comment_ID, comment_date, comment_content, comment_post_ID
 FROM {$wpdb->comments} WHERE
 comment_post_ID in (".implode(',', $posts).") AND comment_approved = 1
 ORDER by comment_date DESC LIMIT $ppp OFFSET $custom_offset";

$comments_list = $wpdb->get_results( $sql );

if ( count( $comments_list ) > 0 ) {
 $date_format = get_option( 'date_format' );
 echo '<ul>';
 foreach ( $comments_list as $comment ) {
 echo '<li>Comment: '.substr( $comment->comment_content, 0, 50 ).'..<br />'.date( $date_format, strtotime( $comment->comment_date ) ).'<br />Post: <a href="'.get_permalink( $comment->comment_post_ID ).'">'.get_the_title( $comment->comment_post_ID ).'</a></li>';
 }
 echo '</ul>';
} else {
 echo '<p>No comments</p>';
}
?>

What we have done here is that, first we fetch sub categories of the category specified so as to include comments on those posts too which are under a sub-category of the specified category. Then we build an array of all these categories, where we need to look up for comments. Then we fetch the posts ID under those categories and then we use a query to fetch the comments on those posts. Finally, we display them as per our need by iterating $comments_list.

In case you want to fetch the comments of a  particular user under a specific category, then you can just change the SQL query in the above code to this:

$user_id = 1; // change this to the user ID either manually or let it come from some other code
$sql = "SELECT comment_ID, comment_date, comment_content, comment_post_ID
 FROM {$wpdb->comments} WHERE
 comment_post_ID in (".implode(',', $posts).") AND comment_approved = 1 AND user_id = $user_id
 ORDER by comment_date DESC LIMIT $ppp OFFSET $custom_offset";

I have used simple names for variables here to make it easy to understand. Always take care to provide your code in its own namespace, choose unique (non-generic) names. Read prefix everything in WordPress.

Need help? Got questions? Comment section is all yours! :)

WordPress plugin Facebook Like Thumbnail Updates

I have updated my WordPress plugin to fix Facebook Like Thumbnails to version 0.2 which I am sure will make the existing users happy! :)

Some of the users who quickly upgraded might be facing issues because of a silly mistake on my part. If the plugin has disappeared from the plugins listing, then you would have to delete the folder "facebook-like-thumbnail" folder in your plugins folder (/wp-content/plugins/) and then reinstall the plugin by typing "Facebook Like Thumbnail" in Add New Plugins screen. I apologise for the issue, please excuse me, I am not used to pushing updates to public repositories.

The plugin now features an options pages which can be found under Settings > Facebook Like Thumbnail. You can specify your default thumbnail image on that page, no more code edits are required. This was a necessary move as the users would have to edit the plugin to specify their default image after every upgrade.

The plugin now supports featured thumbnails and NextGEN galleries (other than the slideshow ones).

The plugin picks the thumbnail in the following order (whichever is found first)

  • If its a post or page
    • Featured Thumbnail
    • First Image in the post
    • Default
  • If its a Front Page or Search Page
    • Default
  • Anything else
    • First image in the first post of the loop
    • Default

Facebook Like Thumbnail

Author: Ashfame, version: 0.3.4, updated: September 9, 2014,
Requires WP version: 3.1 or higher, tested up to: 4.0.
Download (52 726 hits) (32 votes)

Adding the author avatar on author pages to be used as thumbnail and ignoring smilies as a possible match for thumbnail are on my To-do lists. If you have any suggestions, comments section is all yours.

Also the plugin can be totally uninstalled by using the delete option from WordPress dashboard, it won't leave anything behind in the database.

I have tried to keep the plugin as fast as it can be. If any developer can provide any suggestions/improvements, I would love that. If you have any questions or facing any issues because of the early upgrade or need any help, give me a shout in the comments.

Pagination approach using get_posts() in WordPress

Yesterday, I talk about using WP_query or query_posts or get_posts and today I am going to explain the approach I use to have pagination using get_posts(). The other two methods take care of the pagination by them self by just passing the paged parameter along with the function call. But get_posts() is more of a raw function which I used to create paginated data on the basis of already existing pagination.

Here for the sake of explanation of approach, I am making the content paginated where content is already paginated. We will make our extra content work in order to the global $paged variable.

<?php
// Posts Per Page option
$ppp = get_option('posts_per_page');

if (!is_paged()) {
    $custom_offset = 0;
} else {
    $custom_offset = $ppp*($paged-1);
}

// Lets suppose we are querying for posts of a certain author in a particular category
$args = array(
'numberposts' => $ppp,
'offset' => $custom_offset,
'category' => 7, // Category ID of category 'Articles'
'author' => $author_id
);

$posts_data = get_posts( $args );

if ( count( $posts_data ) > 0 ) {
    echo '<ul>';
    foreach ( $posts_data as $post ) {
        echo '<li><a href="'.get_permalink( $post->ID ).'">'.$post->post_title.'</a></li>';
    }
    echo '</ul>';
} else {
    echo '<p>No articles by this user</p>';
}
?>

This way the code make use of the global $paged variable to see which page it is on, and set the value of offset accordingly making the fetched content using get_posts itself paginated. On Page 1, the offset will be zero, it will fetch the posts limited by the posts per page value and on Page 2, the offset will be calculated to leave the posts already shown on previous page and query further posts limited by the posts per page value.

Got questions? Comment section is down below.

Using Ubuntu Notification System – NotifyOSD

Ubuntu features a notification system, where you can see a message notifying you about some particular event. Rhythmbox uses it to show the next track when a track ends, Filezilla shows a notification that file transfers are completed when its window is not in focus (Very handy!) and so on several applications can use it to notify users in the same way (keeping the UI consistent, which is a good design principle).

Rhythmbox Song Notification

rhythmbox notify

Filezilla Transfer Complete Notification

filezilla notify

We too can use this easily in our shell scripts. It supports more functionality if you are working in Python or C (Read Ubuntu NotifyOSD) but for shell scripts it does the pretty fine job too, if you just want to make Ubuntu work for you.

Using NotifyOSD in shell scripts

Make sure you have libnotify-bin installed, if not, just install it by typing the following command in a terminal:

sudo apt-get install libnotify-bin

notify-send - Program to send desktop notifications

With notify-send you can sends desktop notifications to the user via a notification daemon from the command line. These notifications can be used to inform the user about an event or display some form of information without getting in the user’s way.

Check out the man page for it, to see the options it has to offer - man notify-send

Enter this in a terminal, notify-send "Hello" "this is just a test" and you will see the notification appearing up on your desktop.I usually collect icons that I would like to use and then use them in notification bubbles in the following manner:

In terminal, you can use it like

notify-send -t 2000 -i /home/ashfame/Dropbox/Ubuntu/icons/console.png "Hello Ashfame" "This is your computer, lets start with work"

In a shell script, use it like (take care of the screen where you want to display the message - I am on a dual screen setup)

DISPLAY=:0 notify-send -t 2000 -i /home/ashfame/Dropbox/Ubuntu/icons/console.png "Hello Ashfame" "This is your computer, lets start with work"

notify example

Time parameter (-t) lets you specify the time in miliseconds after which the notification will fade away. Its affected with a bug right now (will work on the default timeout even if you set it, but will be fixed in upcoming releases anyway, so better use it).

Icon parameter (-i) is used to specify the icon which is to be used in the notification.

You can also use it to notify you when a certain command has completed in the terminal, like when you were compiling some code or anything which takes a good amount of time so that you can get to know the moment it is ready. As an example, you can use it like

make && notify-send "DONE"

Making practical use of NotifyOSD using notify-send

You can create shell scripts for additional functionality you want, right? Just use notify-send where you want you to be informed or alerted.

Here are the examples, where I use them:

  1. WordPress new version alert
  2. Alert if my site is down
  3. Health check - Tells me to take breaks, sleep at night and if I resist, lock the screen
  4. Pomodoro technique for quantizing time for increasing productivity
  5. Random fun facts from randomfunfacts.com

You can build a lot more useful stuff as per your needs. Share your ideas in the comments and we can discuss :)

Quickly setup a localhost environment in Ubuntu

Although, I use Ubuntu, this should apply to a large number of linux distros. Every developer uses a local environment to develop locally before testing it live. I kinda avoid that root by mounting my FTP webspace in Ubuntu and directly working on live files (there is no need of download and upload as you might think), but I wanted to do some CPU intensive job for a client for which I needed to setup a localhost environment, so I thought I would share this with everyone on my blog.

Install LAMP stack

Fire up a terminal (Applications > Accessories > Terminal) and enter this command:

sudo apt-get install lamp-server^

lamp-server

Enter y for yes when it asks to continue after estimation of how much data will be downloaded and how much will be used on disk.

It will install quickly and can take a few minutes depending on your internet speed, and then it will ask you to setup the password for MySQL user root. It is usually left blank on localhost machines as they are used only for development purposes but last time I left it blank, I had to deal with the issues that it didn't change the password to blank but has something else and I had to turn off the password prompt for root access. Avoid doing all that by just selecting "root" or anything you want as the password of the root user of MySQL.

mysql-root-password

Confirm it once (Type the password and press Tab key).

mysql-root-password-confirm

and you are done.

Test Apache Webserver

Just open http://localhost/ in your browser and it will show up a message "It works!" which means Apache is working fine.

Test PHP

Create a file named phpinfo.php in /var/www/ to check if PHP is working fine.

sudo nano /var/www/phpinfo.php

Enter the content as <?php phpinfo(); ?> and save the file by hitting Ctrl + X and then y (for yes) and return key (enter).

Restart Apache webserver by the following command - sudo /etc/init.d/apache2 restart

Now open http://localhost/phpinfo.php and it will show up a page with lots of php related information, if you can see it, PHP is working fine.

Install phpMyAdmin

Enter this command in terminal - sudo apt-get install libapache2-mod-auth-mysql phpmyadmin

phpmyadmin-install

Select Apache as the web server by pressing Space and then Tab key and press enter key.

select-apache

Press Yes to configure database for phpmyadmin.

configure-phpmyadmin

Provide password which we set as "root" earlier.

phpmyadmin1

Again, enter "root".

phpmyadmin2

Confirm it, and then you are done.

phpmyadmin3

Test phpMyAdmin

Now open http://localhost/phpmyadmin/ in your brower to access phpmyadmin and you can login with username and password both as root.

Pretty quick & easy!

Everything is done, you have your web root at /var/www/ where you will need super user permissions to write files, I will do a follow up post on how you can make this easier by keeping your files in your Home directory instead and a bit of extra which will make it totally complete.

Subscribe so that you don't miss updates! RSS/Email options are in the sidebar.