Archive for November, 2008

Simple Reg-Ex to Validate an Email Address

by Matt Danger on Nov.24, 2008, under PHP

Regular expressions can be a pain sometimes. Here’s a code snippet to make your life a little easier when validating email addresses:

$email = 'user@example.com';
if (!eregi("^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3}$", $email)) {
    print_error("Your email address is invalid!");
}
Leave a Comment :, , , more...

Update Your Facebook Status from the Command Line

by Matt Danger on Nov.24, 2008, under Perl

The Facebook Developer Platform doesn’t give us the ability to set a user’s status so I decided to write my own method that would allow Facebook users to update their status messages without having to log into the website.

The first version that I wrote in 2006 was a little complicated. The script had to connect to several Facebook pages and collect cookies and challenge codes that were necessary to login and update the user’s status.

Facebook changed their login and status update mechanisms in version 2.0 breaking my original script. I’ve rewritten it to work with Facebook 2.0. It is now actually shorter because Facebook uses the user’s homepage as the central information area.

Any feedback is welcome. I plan to implement this in other utilities soon. Enjoy!

Updated on May 6, 2010 to version 2.1

#!/usr/bin/perl -w
 
#===============================================================================
#
# Facebook status script v2.1
#
# This script allows you to update your Facebook status from the shell.
#
# Copyright (C) 2010 Matt West <matt at mattdanger dot net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# For a copy of the GNU General Public License visit <http://www.gnu.org/licenses/>.
#
#===============================================================================
 
# Be sure you have installed the LWP and Crypt::SSLeay packages from CPAN
use LWP;
use HTTP::Cookies;
use Term::ReadKey;
use strict;
 
# General vars
my $login;
my $password;
my $status;
my $auth_key;
my $response;
my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ( 'Referer' => 'http://www.facebook.com/', 
               'User-Agent' => $user_agent);
my $cookie_jar = HTTP::Cookies->new(
                file => 'cookies.dat',
                autosave => 1,
                ignore_discard => 1);
my $browser = LWP::UserAgent->new;
$browser->cookie_jar($cookie_jar);
 
# Get login information & the status message to send.
print "Facebook login name: ";
$login = <>; chomp($login);
 
print "Password: ";
ReadMode('noecho');
$password = ReadLine(0); chomp($password); ReadMode 0;
 
print "\nYour status (Facebook appears to have a 232 character limit): ";
$status = <>; chomp($status);
print "\nSending... ";
 
 
#================================================
# Login and get auth key
#================================================
 
$response = $browser->post('https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php', 
                           ['email' => $login,
                            'pass' => $password,
                            'login' => 'Log In'], @header);
$cookie_jar->extract_cookies( $response );
$cookie_jar->save;
$response = $browser->get('http://m.facebook.com/a/home.php', @header);
 
$auth_key = $response->content;
$auth_key =~ s/\n//g;
$auth_key =~ s/^.*name="post_form_id" value="//;
$auth_key =~ s/".*$//;
 
#================================================
# Submit the status update
#================================================
 
@header = ('Referer' => 'http://m.facebook.com/a/home.php', 
           'User-Agent' => $user_agent, 
           'Host' => 'm.facebook.com');
 
$response = $browser->post('http://m.facebook.com/a/home.php?re974fcaf&refid=7&rbb94a931', 
                           ['fb_dtsg' => 'jYNZj',
                            'post_form_id' => $auth_key,
                            'status' => $status,
                            'update' => 'Share'], @header);
 
# Did we do good here?
if ($response->content eq '') {
  print "Done!\n\n";
} else {
  print "An error occurred while setting your profile status.\n\n";
}
 
# Now that we're done we can delete the cookies.dat file.
exec('rm cookies.dat');
2 Comments :, , more...

Hacking “Share This” to Configure Sharing Options

by Matt Danger on Nov.24, 2008, under PHP

Thomas likes to use Alex King’s Share This plugin on his Wordpress install but wanted a little more configurability from it. I wrote a little hack to allow him to select which sharing tab appears by default. This was written for version 1.3 and I’m not sure if it could be successfully implemented into the 2.3 version.

To select the default tab set “DEFAULT_TAB” to either ’social’ or ‘email’ for which tab you’d like to be displayed when Share This is activated. Set “FIRST_TAB” to either ’social’ or ‘email’ for which tab you’d like to appear first in the tab order when Share This is activated.

To begin, add this code at line 26:

@define('DEFAULT_TAB', 'email'); // 'social' or 'email' 
@define('FIRST_TAB', 'email'); // 'social' or 'email' as the first tab.

Then add this code at line 123:

function get_default_tab() {
  switch (DEFAULT_TAB) {
    case 'email':
      $tab_number = 2;
      break;
    case 'social':
      $tab_number = 1;
      break;
    default: die("Error with the Share This plugin: Please define DEFAULT_TAB as either 'social' or 'email'.");  
  }
  echo $tab_number;
}

Then add this code at line 174:

akst_share_tab('<?php get_default_tab(); ?>');

Finally, at line 442 replace:

<li id="akst_tab1" onclick="akst_share_tab('1');"><?php _e('Social Web', 'alexking.org'); ?></li>
<li id="akst_tab2" class="selected" onclick="akst_share_tab('2');"><?php _e('E-mail', 'alexking.org'); ?></li>

with:

<?php 
switch (FIRST_TAB) {
  case 'social':
?>
    <li id="akst_tab1" onclick="akst_share_tab('1');"><?php _e('Social Web', 'alexking.org'); ?></li>
    <li id="akst_tab2" class="selected" onclick="akst_share_tab('2');"><?php _e('E-mail', 'alexking.org'); ?></li>
<?php
    break;
  case 'email':
?>
    <li id="akst_tab2" class="selected" onclick="akst_share_tab('2');"><?php _e('E-mail', 'alexking.org'); ?></li>
    <li id="akst_tab1" onclick="akst_share_tab('1');"><?php _e('Social Web', 'alexking.org'); ?></li>
<?php
    break;
  default: die("Error with the Share This plugin: Please define FIRST_TAB as either 'social' or 'email'.");
}
?>
Leave a Comment :, , more...

Bash Examples

by Matt Danger on Nov.23, 2008, under Shell Scripting, Unix

A while ago a friend was taking an entry level Unix programming class and asked me to help him study. I came up with some sample problems for him. Here are my solutions:

The first is a program that will allow a user to input as many numbers as the user wants (999 as the choice that ends the user input). The program will then output the highest number, the lowest number, the sum of all the numbers, and the average number.

#!/bin/bash
COUNT=0
echo -n "Enter a number (999 to quit): "
 
while read NUM; do
  # Set initials
  if [ $COUNT -eq 0 ]; then
    HIGHEST=$NUM
    LOWEST=$NUM
    SUM=$NUM
  fi
 
  # If 999 is entered, break out
  if [ $NUM -eq 999 ]; then
    break
  else
    # See if inputted number is the highest number
    if [ $NUM -gt $HIGHEST ]; then
      HIGHEST=$NUM
    fi
 
    # See if inputted number is the lowest number
    if [ $NUM -lt $LOWEST ]; then
      LOWEST=$NUM;
    fi
 
    # Calculate sum
    SUM=$(($SUM+$NUM))
 
    echo -n "Enter another number (999 to quit): "
  fi
 
  COUNT=$(($COUNT+1))
done
 
AVERAGE=$(($SUM/$COUNT))
echo "Highest number: $HIGHEST"
echo "Lowest number: $LOWEST"
echo "Sum of the numbers: $SUM"
echo "Average of the numbers: $AVERAGE"

The second program is a number guessing game. The computer picks a number from 0-60 then allows the user to guess at the number until the user gets it right. The program gives the user a hint on whether they should guess a higher or lower number.

#!/bin/bash 
RAN=$((RANDOM%60))
COUNTER=1
echo -n "I've guessed a number between 0-60, what is it? "
 
while read GUESS; do
 
  if [ $GUESS -eq $RAN ]; then
    break;
  else
    echo
    if [ $GUESS -lt $RAN ]; then
      echo -n "Nope, try a higher number: "
    else
      echo -n "Nope, try a lower number: "
    fi	
  fi
  COUNTER=$((COUNTER+1))
 
done
 
echo
echo "Yep, good job! It took you $COUNTER tries to guess correctly."

The third program allows a user to type in a number, then the program will either count up to the number provided by the user or count down from that number. In addition, a menu lets the user choose which counter they wish to use. In both cases that counter will either count down to 0, or start counting from 0.

#!/bin/bash 
echo -n "Enter a number: "; read NUM
echo -n "Enter U to count up to $NUM and D to count down to 0: "; read CHOICE
 
case $CHOICE in
  'u'|'U') 
    COUNTER=0
    while [ $COUNTER -le $NUM ]; do
      echo $COUNTER
      COUNTER=$(($COUNTER+1))
    done ;;
  'd'|'D')
    while [ $NUM -ge 0 ]; do
      echo $NUM;
      NUM=$(($NUM-1))
    done ;;
  *) echo "Error: You entered an invalid argument."
esac

The last program asks the user if they want to add, subtract, multiply or divide two user inputted numbers. Then the program outputs the sum of number 1 and number 2, the difference of number 1 and number 2, the product of number 1 and number 2, and the quotient of number 1 and number 2

This program will run until the user wants to quit. Also, if the user puts in a 0 as the second number, we let the user know that if they choose divide that a division by zero error will occur.

#!/bin/bash
while true; do
  echo "Please enter two numbers (type 'q' to quit): "
  echo -n "Number 1: "
  read NUM1
  if [ $NUM1 == "q" ]; then exit; fi
  echo -n "Number 2: "
  read NUM2
  echo -n "Enter (a) to add, (s) to subtract, (m) to multiply, or (d) to divide these numbers: "
  read OPERATION
 
  case $OPERATION in
    a) echo "The sum of $NUM1 and $NUM2 is: $(($NUM1+$NUM2))" ;;
    s) echo "The difference of $NUM1 and $NUM2 is: $(($NUM1-$NUM2))";;
    m) echo "The product of $NUM1 and $NUM2 is: $(($NUM1*$NUM2))" ;;
    d) if [ $NUM2 -eq 0 ]; then
        echo "You can't divide by 0, a division by zero error will occur."
      else 			
	    echo "The quotient of $NUM1 and $NUM2 is: $(($NUM1/$NUM2))"
      fi ;;
  esac
done
Leave a Comment :, more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Send me a message on AIM!

Friends

Read what I read...