Password protect WordPress

This is for people who need to protect their blog with username and password that can be easyly set from the WordPress backend.

1. Go to Users → Authors & Users sub-panel.
2. Add a new user in the Add New User section. This login will be used to access your WordPress by other user. Or go to Settings → General → Membership and check “Anyone can register”.
3. Add the following lines to your WordPress Theme’s template functions.php file (For example, functions.php file for a Theme named “default” would probably reside in the directory wp-content/themes/default/functions.php) or create it as a Plugin by filling the additional Standard Plugin Information:

    <?php
    function password_protected() {
    	if ( !is_user_logged_in() )
    		auth_redirect();
    }

    add_action('login_head', 'rsd_link');
    add_action('login_head', 'wlwmanifest_link');
    add_action('template_redirect', 'password_protected');
    add_action('do_feed', 'password_protected');
    ?>

4. Go to Settings → Discussion sub-panel. Under Default article settings, uncheck “Attempt to notify any blogs linked to from the article (slows down posting.)”.
5. Finally, go to Settings → Privacy and set “Blog Visibility to I would like to block search engines, but allow normal visitors”. Click Save Changes.

Now visitors will be asked to log in using WordPress login form to view your WordPress blog / site. This is very suitable for someone that wanted privacy or owned a private password protected WordPress blog / site.
It can be used with the plugin wassup for visitors tracking.

Add first and last class to WordPress custom menu

This code will add class for first and last item in WordPress custom menus:

//This add class first and last to the custom menus
function add_first_and_last($output) {
  $output = preg_replace('/class="menu-item/', 'class="first-menu-item menu-item', $output, 1);
  $output = substr_replace($output, 'class="last-menu-item menu-item', strripos($output, 'class="menu-item'), strlen('class="menu-item'));
  return $output;
}
add_filter('wp_nav_menu', 'add_first_and_last');

Apache Landing Page

This code list the directories and files in a table.

<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <title>Ze Master Server of The Universe</title>
   <style>
     *{
         padding:0;
         margin:0;
     }
     html,body {
         color:#333;
         font-family: "Lucida Console", Courier, monospace;
         font-size:14px;
         text-shadow:1px 1px 1px #cacaca;
         -webkit-text-shadow:1px 1px 1px #cacaca;
         -moz-text-shadow:1px 1px 1px #cacaca;
     }
     a{
         padding: 2px 0 0 24px;
         color:#FE4902;
         text-decoration:none;
     }
     a:hover{
         color:#000;
         cursor:url(hand.gif), progress;
     }
     #container{
         margin:0 auto;
         width:700px;
         margin-top:20px;
         padding-top:10px;
         border:1px solid #EEE;
         border-radius:10px;
         -moz-border-radius:10px;
     }
     .head{
         background-color:#38AF64;
         color:#FFF;
         font-weight:bold;
         padding:7px 0 5px 10px;
         font-size:14px;
         letter-spacing:1px;
         font-family: Verdana, Arial, Helvetica, sans-serif;
     }
     .head:hover{background-color:#FE4902;}
     .head span{font-size:9px; letter-spacing:0;}
     td{
         background-color:#F3F3F3;
         padding:6px;
     }
     td:hover{background-color:#EFEFEF;}
     h1{
         font-size:18px;
         font-weight:bold;
         padding:0 0 10px 10px;
     }

     /*icons for file types (add more to suit your needs - icons by famfamfam.)*/

     /*images*/
     a[href$=".jpg"] {background: url(image.gif) no-repeat left 50%;}
     a[href$=".gif"] {background: url(image.gif) no-repeat left 50%;}
     a[href$=".png"] {background: url(image.gif) no-repeat left 0%;}

     /*pdfs*/
     a[href$=".pdf"] {background: url(pdf.gif) no-repeat left 50%;}

     /*psds*/
     a[href$=".psd"] {background: url(psd.gif) no-repeat left 50%;}

     /*docs*/
     a[href$=".doc"] {background: url(doc.gif) no-repeat left 50%;}
     a[href$=".txt"] {background: url(doc.gif) no-repeat left 50%;}

     /*videos*/
     a[href$=".avi"] {background: url(video.gif) no-repeat left 50%;}
     a[href$=".m4a"] {background: url(video.gif) no-repeat left 50%;}
     a[href$=".mov"] {background: url(video.gif) no-repeat left 50%;}
     a[href$=".mp4"] {background: url(video.gif) no-repeat left 50%;}
     a[href$=".wmv"] {background: url(video.gif) no-repeat left 50%;}

     /*audio*/
     a[href$=".mp3"] {background: url(audio.gif) no-repeat left 50%;}
     a[href$=".wma"] {background: url(audio.gif) no-repeat left 50%;}
     a[href$=".aac"] {background: url(audio.gif) no-repeat left 50%;}

     /*web pages*/
     a[href$=".html"] {background: url(html.gif) no-repeat left 50%;}
     a[href$=".php"] {background: url(html.gif) no-repeat left 50%;}

   </style>

</head>
<body>
   <div id="container">
       <?php
         // opens this directory
         $myDirectory = opendir(".");

         // gets each entry
         while($entryName = readdir($myDirectory)) {
           $dirArray[] = $entryName;
         }

         // finds extention of file
         function findexts ($filename)
         {
           $filename = strtolower($filename) ;
           $exts = split("[/\\.]", $filename) ;
           $n = count($exts)-1;
           $exts = $exts[$n];
           return $exts;
         }

         // closes directory
         closedir($myDirectory);

         //  counts elements in array
         $indexCount   = count($dirArray);

         // sorts files
         sort($dirArray);

         // print 'em
         print("<h1>Directory Contents</h1>");
         print("<table width='100%' cellspacing='10'>
                 <tr>
                   <td class='head'>Directory/File</td>
                   <td class='head'>Type</td>
                   <td class='head'>Size <span>(bytes)</span></td></tr>\n");

         // loops through the array of files and print them all
         for($index=0; $index < $indexCount; $index++) {
               if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
               print("<tr><td><a href='$dirArray[$index]'>$dirArray[$index]</a></td>");
               print("<td>");
               print(findexts($dirArray[$index]));
               print("</td>");
               print("<td>");
               print(filesize($dirArray[$index]));
               print("</td>");
               print("</tr>\n");
           }
         }
         print("</table>\n");
       ?>
   </div>

</body>
</html>

Simple JavaScript Calculator





















<html>
<form name="calculator">
<table border=4>
<tr>
<td>
<input type="text" name="text" size="18">
<br>
</td>
</tr>
<tr>
<td>
<input type="button" value="1" onclick="calculator.text.value += '1'">
<input type="button" value="2" onclick="calculator.text.value += '2'">
<input type="button" value="3" onclick="calculator.text.value += '3'">
<input type="button" value="+" onclick="calculator.text.value += ' + '">
<br>
<input type="button" value="4" onclick="calculator.text.value += '4'">
<input type="button" value="5" onclick="calculator.text.value += '5'">
<input type="button" value="6" onclick="calculator.text.value += '6'">
<input type="button" value="-" onclick="calculator.text.value += ' - '">
<br>
<input type="button" value="7" onclick="calculator.text.value += '7'">
<input type="button" value="8" onclick="calculator.text.value += '8'">
<input type="button" value="9" onclick="calculator.text.value += '9'">
<input type="button" value="*" onclick="calculator.text.value += ' * '">
<br>
<input type="button" value="c" onclick="calculator.text.value = ''">
<input type="button" value="0" onclick="calculator.text.value += '0'">
<input type="button" value="=" onclick="calculator.text.value = eval(calculator.text.value)">
<input type="button" value="/" onclick="calculator.text.value += ' / '">
<br>
</td>
</tr>
</table>
</form>
</html>

Contact Form and send e-mail

<?php 
if ($_POST["email"]<>'') { 
    $ToEmail = 'youremail@site.com'; 
    $EmailSubject = 'Site contact form'; 
    $mailheader = "From: ".$_POST["email"]."\r\n"; 
    $mailheader .= "Reply-To: ".$_POST["email"]."\r\n"; 
    $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; 
    $MESSAGE_BODY = "Name: ".$_POST["name"].""; 
    $MESSAGE_BODY .= "Email: ".$_POST["email"].""; 
    $MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"]).""; 
    mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure"); 
?> 
Your message was sent
<?php 
} else { 
?> 
<form action="test.php" method="post">
<table width="400" border="0" cellspacing="2" cellpadding="0">
<tr>
<td width="29%" class="bodytext">Your name:</td>
<td width="71%"><input name="name" type="text" id="name" size="32"></td>
</tr>
<tr>
<td class="bodytext">Email address:</td>
<td><input name="email" type="text" id="email" size="32"></td>
</tr>
<tr>
<td class="bodytext">Comment:</td>
<td><textarea name="comment" cols="45" rows="6" id="comment" class="bodytext"></textarea></td>
</tr>
<tr>
<td class="bodytext"> </td>
<td align="left" valign="top"><input type="submit" name="Submit" value="Send"></td>
</tr>
</table>
</form> 
<?php 
}; 
?>

Breadcrumbs

Features of my version of WordPress breadcrumbs

  • Displays a full chain of linksto the current page. For example, if the current post is in a second level category, so breadcrumbs will looks like this:Home » Category » Subcategory » Post TitleBut all, what I have seen, displays only such an option (excluding plugins):

    Home » Subcategory » Post Title

    The same applies to pages and subpages. For example, for a 3rd level page breadcrumbs will looks like this:

    Home » Page Level 1 » Page Level 2 » Page Level 3

  • Breadcrumbs is appearing on a following types of WordPress pages:
    • paged navigation (like sitename.com/page/2/);
    • category archive;
    • tag archive;
    • daily archive;
    • monthly archive;
    • yearly archive;
    • author archive;
    • single post page;
    • single page;
    • attachment page;
    • search results;
    • 404 error page.
  • adding a page number (if archive page is second or more);
  • custom symbol of delimiter;
  • custom text for a ‘Home’ link;
  • current crumb styling.

WordPress breadcrumbs function (last updated: 03.31.2012)

function custom_breadcrumbs() {

  $showOnHome = 0; // 1 - show breadcrumbs on the homepage, 0 - don't show
  $delimiter = '&raquo;'; // delimiter between crumbs
  $home = 'Home'; // text for the 'Home' link
  $showCurrent = 1; // 1 - show current post/page title in breadcrumbs, 0 - don't show
  $before = '<span>'; // tag before the current crumb
  $after = '</span>'; // tag after the current crumb

  global $post;
  $homeLink = get_bloginfo('url');

  if (is_home() || is_front_page()) {

    if ($showOnHome == 1) echo '<div id="crumbs"><a href="' . $homeLink . '">' . $home . '</a></div>';

  } else {

    echo '<div id="crumbs"><a href="' . $homeLink . '">' . $home . '</a> ' . $delimiter . ' ';

    if ( is_category() ) {
      global $wp_query;
      $cat_obj = $wp_query->get_queried_object();
      $thisCat = $cat_obj->term_id;
      $thisCat = get_category($thisCat);
      $parentCat = get_category($thisCat->parent);
      if ($thisCat->parent != 0) echo(get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' '));
      echo $before . 'Archive by category "' . single_cat_title('', false) . '"' . $after;

    } elseif ( is_search() ) {
      echo $before . 'Search results for "' . get_search_query() . '"' . $after;

    } elseif ( is_day() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo '<a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
      echo $before . get_the_time('d') . $after;

    } elseif ( is_month() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo $before . get_the_time('F') . $after;

    } elseif ( is_year() ) {
      echo $before . get_the_time('Y') . $after;

    } elseif ( is_single() && !is_attachment() ) {
      if ( get_post_type() != 'post' ) {
        $post_type = get_post_type_object(get_post_type());
        $slug = $post_type->rewrite;
        echo '<a href="' . $homeLink . '/' . $slug['slug'] . '/">' . $post_type->labels->singular_name . '</a> ' . $delimiter . ' ';
        if ($showCurrent == 1) echo $before . get_the_title() . $after;
      } else {
        $cat = get_the_category(); $cat = $cat[0];
        echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
        if ($showCurrent == 1) echo $before . get_the_title() . $after;
      }

    } elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) {
      $post_type = get_post_type_object(get_post_type());
      echo $before . $post_type->labels->singular_name . $after;

    } elseif ( is_attachment() ) {
      $parent = get_post($post->post_parent);
      $cat = get_the_category($parent->ID); $cat = $cat[0];
      echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
      echo '<a href="' . get_permalink($parent) . '">' . $parent->post_title . '</a> ' . $delimiter . ' ';
      if ($showCurrent == 1) echo $before . get_the_title() . $after;

    } elseif ( is_page() && !$post->post_parent ) {
      if ($showCurrent == 1) echo $before . get_the_title() . $after;

    } elseif ( is_page() && $post->post_parent ) {
      $parent_id  = $post->post_parent;
      $breadcrumbs = array();
      while ($parent_id) {
        $page = get_page($parent_id);
        $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
        $parent_id  = $page->post_parent;
      }
      $breadcrumbs = array_reverse($breadcrumbs);
      foreach ($breadcrumbs as $crumb) echo $crumb . ' ' . $delimiter . ' ';
      if ($showCurrent == 1) echo $before . get_the_title() . $after;

    } elseif ( is_tag() ) {
      echo $before . 'Posts tagged "' . single_tag_title('', false) . '"' . $after;

    } elseif ( is_author() ) {
       global $author;
      $userdata = get_userdata($author);
      echo $before . 'Articles posted by ' . $userdata->display_name . $after;

    } elseif ( is_404() ) {
      echo $before . 'Error 404' . $after;
    }

    if ( get_query_var('paged') ) {
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
      echo __('Page') . ' ' . get_query_var('paged');
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
    }

    echo '</div>';

  }
} // end custom_breadcrumbs()

Simply paste this function into a functions.php file of your theme and then paste the following code in a place of your theme, where breadcrumbs must appearing:

<?php if (function_exists('custom_breadcrumbs')) custom_breadcrumbs(); ?>

All that remains to do for now, is to design your breadcrumbs with CSS. You can use #crumbs for styling breadcrumbs block and #crumbs .current for styling a current crumb.

Php year code snippet

Display year with type 2011-2012

<?php 
$copyYear = 2011; 
$curYear = date('Y'); 
echo $copyYear . (($copyYear != $curYear) ? '-' . $curYear : '');
?>

Simple echo year

<?php echo date("Y") ?> 

LAMP on Ubuntu 11.10

Install LAMP and phpMyAdmin on Ubuntu 11.10

The Ubuntu development team has made it very easy to install and set up a web server. Open a terminal window and enter the following command.
sudo apt-get install lamp-server^

Please enter the command exactly as it’s shown above. The carat (^) is not a typo and the command will not work without it.

Command to install LAMP

If prompted, enter your password.

The package manager will now display a list of packages to be installed. Hit to confirm that you want to go ahead with the install.

Installing LAMP packages

Apt will now start downloading and installing the packages on your computer.

After a short wait, you will be prompted to set a password for MySQL’s administrative user. Enter a password at the prompt and make sure it’s something you will remember or make a note of it.

MySQL password

You will then be prompted to confirm your password.

Confirm MySQL password

Type in the same password and hit . The package manager will now continue downloading and installing packages. After a short wait the installation will complete.
Testing Apache

Now we’ll run a quick test to make sure that the Apache web server is working. Open a web browser and enter the address https://localhost/. You should see a page that says “It Works!”

Testing Apache installation
Testing php

Now that we’ve verified that Apache works, we need to verify that php is working properly. We’re going to create a file in the /var/www directory called testing.php. Enter the following command in the terminal to create the file.
echo “” | sudo tee /var/www/testing.php

Enter your password if prompted.

Now you’ll need to restart the Apache web server. Enter into the terminal:
sudo service apache2 restart

Now open your web browser and enter the following address: https://localhost/testing.php

You should see a web page that displays a bunch of information about your php and Apache environment.

Testing php
Configure MySQL

Since this is for a local development environment, the MySQL database needs to be bound to the localhost IP address. This should be 127.0.0.1 by default. You can verify your localhost address with the following terminal command.
cat /etc/hosts | grep localhost

You should see output something like this:

127.0.0.1 localhost
::1 ip6-localhost ip6-loopback

Now you need to verify that this address is the bind address MySQL’s my.cnf file. Use the following terminal command.
cat /etc/mysql/my.cnf | grep bind-address

You should see output like this.

bind-address = 127.0.0.1

If it’s not correct you’ll need to edit /etc/mysql/my.cnf as root to fix it.
Install phpMyAdmin

You now have a functioning LAMP installation. You don’t need to install phpMyAdmin, but it provides a much easier way to administer your MySQL databases if you’re not familiar with MySQL’s commands. You can install phpMyAdmin with:
sudo apt-get install libapache2-mod-auth-mysql phpmyadmin

Enter your password if prompted.

Installing phpMyAdmin

Again the package manger will show you the packages it’s about to install. Hit to move forward with the installation.

The package manager will now begin downloading and installing packages. After a short wait you will be prompted to choose the web server to configure for phpMyAdmin. Hit to mark apache2 with an asterisk (*) as it’s shown in the following picture (click on the image to see it in full size). Then hit .

Select apache2

The next screen will ask about some automatic database configuration with dbconfig-common. Hit to accept the default and move on.

Configure phpMyAdmin with dbconfig-common

Next you’ll be prompted for the MySQL administrator password. Enter the password that your created earlier.

Enter MySQL administrator password

Now you’ll be prompted for a MySQL application password. You can allow the system to generate a random password or choose your own.

Enter MySQL application password

If you choose your own password, you will be prompted to verify it at the next screen.

Verify MySQL application password

Your phpMyAdmin installation and configuration is now complete.
Testing phpMyAdmin

Open your web browser and enter the address https://localhost/phpmyadmin/.

You should see a page like this.

phpMyAdmin login screen

Now log in with the user name root and the password that you created earlier in the tutorial.

phpMyAdmin Home screen

Congratulations, you now have a working web development environment set up on Ubuntu 11.10. You can place the files for your website under /var/www. Note that this location is owned by the root user, so you’ll need to copy your files over as root for it to work. Otherwise, you can do some further Apache configuration so you can place the files for your website in a directory somewhere under your home directory.
Fixing some common problems
Fixing phpMyAdmin

One common error that some people make is that they forget to mark apache2 during the phpMyAdmin configuration. When this happens you’ll get a 404 Not Found error when trying to navigate to https://localhost/phpmyadmin/.

phpMyAdmin Not Found

If this happens, enter the following terminal command.
sudo dpkg-reconfigure phpmyadmin

You will be prompted about reinstalling the database. Accept the default of “No” and hit .

Don’t reinstall phpMyAdmin database

Make sure to then mark apache2 by having the cursor next to apache2 and then hitting to mark it with a *, then hit .

Reconfigure phpMyAdmin for Apache

You will then need to reload Apache.
sudo service apache2 reload

You should now be able to load https://localhost/phpmyadmin/. If you’re still seeing the 404 Not Found error, then you will need to clear your web browser cache and try again.

phpMyAdmin login screen
Fixing the Apache fully qualified domain name

During the above steps you may have seen an error message like this when reloading Apache.

apache2: Could not reliably determine the server’s fully qualified domain name,
using 127.0.1.1 for ServerName

This doesn’t seem to cause any problems for me, but if you don’t like seeing that error, you can fix it with this command.
echo “ServerName localhost” | sudo tee /etc/apache2/conf.d/fqdn

Then reload Apache with
sudo service apache2 reload

Enjoy your new web development environment!

Flash On BackTrack 5

Just copy and paste this text in terminal

#!/bin/bash

mkdir ~/flashinstaller && cd ~/flashinstaller

apt-get purge flashplugin-nonfree flashplugin-installer gnash gnash-common mozilla-plugin-gnash swfdec-mozilla
rm -f /usr/lib/firefox/plugins/libflashplayer.so
rm -f /usr/lib/mozilla/plugins/libflashplayer.so
rm -f /usr/lib/mozilla/plugins/flashplugin-alternative.so
rm -f /usr/lib/mozilla/plugins/npwrapper*flash*so
rm -f ~/.mozilla/plugins/*flash*so

# download flash square and flash player from:
wget https://fpdownload.macromedia.com/get/flashplayer/current/install_flash_player_10_linux.tar.gz
wget https://download.macromedia.com/pub/labs/flashplatformruntimes/flashplayer11/flashplayer11_b1_install_lin_64_071311.tar.gz

tar xfvz flashplayer11_b1_install_lin_64_071311.tar.gz
chown root:root libflashplayer.so
chmod 0644 libflashplayer.so
cp -f libflashplayer.so /usr/lib/mozilla/plugins/
rm -rf libflashplayer.so
ln -s /usr/lib/mozilla/plugins/libflashplayer.so /usr/lib/firefox/plugins/
tar xvfz install_flash_player_10_linux.tar.gz
mkdir ~/.mozilla/plugins
mv -f libflashplayer.so ~/.mozilla/plugins/
cd