Bread's plonk spot

This is merely a place for me to dump stuff I have written, feel free to peruse.
All scripts are provided as is and without warranty.

Simplejax is a javascript library that simplifies JHR (Also known as JHR) requests. Using a simple, but clean paridigm it allows for dynamic applications with very little javascript knowledge.

Visit website

Simplewall is a basic linux firewall written in perl, utilizing iptables it accepts a simplified format for vetting incoming connections. Perfect if you want to allow specific people access.

Download

jstidy is a javascript cleaner written in python. Written to comprehend the source of Google's adwords script.

View source
# Python JS Cleanup
import sys
import re

# File pointer
fp = open(sys.argv[1], 'r')

# Data buffer
data = ''

while(1):
   # Read current position
   dataRead = fp.read(1024)
   # Append data onto buffer
   data += dataRead

   # No more data to retrieve
   if not dataRead: break

# Clean braces
data = data.replace('{', '\n{\n')
data = data.replace('}', '\n}\n')

# Nest data
data = re.sub('((function|if|else|else if).*)\n\{', "\\1\n{", data)
data = re.sub('\{(.*;)\}', "\\1\n", data, re.M)

# Break down semi colon's to new lines
data = data.replace(';', ';\n')

# Clean up operators
data = data.replace('&&', ' && ')
data = data.replace('||', ' || ')

#Split the data
lines = data.split('\n')

INDENT_LEVEL  = 0
CURRENT_TOKEN = 0

TOKENS = {}

# Tokenize code block
for i in xrange(len(lines)):
   line = lines[i]
   if line == '{':
      # Tokenize parent brace
      lines[i] = line.replace('{', str(CURRENT_TOKEN) + '/{')

      # Store line associated to token
      TOKENS[CURRENT_TOKEN] = i

      # Increase indentation
      INDENT_LEVEL  += 3
      # Increment current token
      CURRENT_TOKEN += 1

   # End block identifier
   elif line == '}':
      # Step back indentation
      INDENT_LEVEL  -= 3
      # Padding
      padding = ((INDENT_LEVEL) * ' ')
      # Replace close block brace with padding
      lines[i] = line.replace('}', padding + '}')

      # Token
      token = TOKENS[CURRENT_TOKEN-1]
      # Needle
      withToken = str(CURRENT_TOKEN-1) + '/{'
      # Reference back to stored token and replace line to remove token and add padding
      lines[token] = lines[token].replace(withToken, padding + '{')
      CURRENT_TOKEN -= 1
   else:
      padding = ((INDENT_LEVEL) * ' ')
      lines[i] = line.replace(line, padding + line)

print '\n'.join(lines)

rswget is an incredibly simple bash script for downloading from rapidshare via cli. It does require a premium member cookie registered in firefox

View source
#!/bin/bash
# @author Ed Cradock 
# 
# Use wget with cookie based websites, primarily written for use with
# rapidshare. But most cookie websites should work. Also download resolution
# support. If supplied with file comment out any files downloaded.
#
BROWSER_DIR=$HOME/.mozilla/firefox
COOKIE_FILE=$HOME/.cookies



# If the cookie file doesn't exist; create it
if [ ! -e  "$COOKIE_FILE" ]
then
   DEFAULT_PROFILE=0;
   IN_BLOCK=0

   while read line
   do
      if [ "$line" == "Name=default" ]; then
         IN_BLOCK=1
      fi

      if [ $IN_BLOCK -eq 1 ] && [ "${line:0:4}" == "Path" ]; then
         DEFAULT_PROFILE=${line:5};
         break;
      fi
   done < "$BROWSER_DIR/profiles.ini";

   if [ -e "$BROWSER_DIR/$DEFAULT_PROFILE/cookies.txt" ]; then
      echo "Setting up symbolic link for .cookies file"
      ln -s "$BROWSER_DIR/$DEFAULT_PROFILE/cookies.txt" "$COOKIE_FILE"
   fi
else
   wget -c --load-cookies=$COOKIE_FILE $@
fi

imgup is another basic bash script used for uploading images to imghost via cli.

View source
   #!/bin/bash
   while [ $1 ]
   do
      if [ -f $1 ]
      then
         echo "Image $1 : "
         curl -# -F imagefile=@$1 -F Submit=Upload http://imghost.us/ | grep ">\(http://.*\.imghost\.us/.*\.\(jpg\|png\|gif\)\)" --only-matching | sed "s/>//"
         echo ""
      else
         echo "File does $1 not exist."
      fi
   
      shift
   done
   
   echo "## Image uploads complete"
   

MySpace ripper - This was a proof of concept to demonstrate that content served from MySpace is rippable.

View source

<?php
/**
* MySpace ripping proof of concept
*
* @author : Ed Cradock
*/

/*
 * Because of the absolutely abismal page optimization
 * of MySpace, a byte amount must be defined here to
 * not cause too much overhead.
 * 
 * If no matches are found (and the artist exists), 
 * increase this value as MySpace
 * have added more bloat. If still to no avail, then
 * this script won't work as MySpace have altered something.  
*/
define('MAX_BYTES_OFFSET'12025);


/*
 * Set the myspace artist url
*/
$ms_url 'http://www.myspace.com/futurebound';

/**
* Rips apart the XML file and builds an array of title / durl
* for each track
*
* @access public
* @param string $url - The MySpace URL
* @return array  
*/
function getMusic($url)
{
   
$match_pat '#viewPicture&amp;friendID=([0-9]+)#i';
   
$src file_get_contents($urlfalsenull0MAX_BYTES_OFFSET);
   
$songs = array();

   
preg_match($match_pat$src$matches);
   
   if(
$matches[1])
   {
      
$xml = new DOMDocument();
      
$xml->load('http://mediaservices.myspace.com/services/media/musicplayerxml.ashx?b=' $matches[1]);
   
      
$xpath = new DOMXPath($xml);
      
$songNodes $xpath->query('playlist/song');

      
$i 0;
      foreach(
$songNodes as $songNode)
      {
         
$songs[$i]['title'] = $songNode->getAttribute('title');
         
$songs[$i]['url']   = $songNode->getAttribute('durl');

         
$i++;
      }

   }else
      return 
false;

   return 
$songs;
}

/* 
 * Output the links for MP3 and title of track.
*/
$songs getMusic($ms_url);

if(
is_array($songs))
{
   foreach(
$songs as $song)
   {
      
printf("<a href=\"%s\">%s</a><br />\n"$song['url'], $song['title']);
   }
}
else
   echo 
'Failure to extract tracks.';
?>

Benchmarking

Include vs file_get_contents for serving static content:

The static content was 10 paragraphs of lorem ipsum. The results are shown to two decimal places.
Iterations Include time file_get_content time difference (in seconds)
100 0.50 0.44 0.06
1000 6.70 6.01 0.69
10000 55.12 50.55 4.57

That is an average 10% increase in execution time by using include to serve static content.

The benchmark driver:

View source

<?php
/**
* Benchmarking include vs file_get_contents for serving
* static content.
*
* @author : Ed Cradock
* @require timer
*/

define('ITERATION_OFFSET'10000);

require_once 
'class/timer.php';

$timer = new timer();

/*
 * Time include
*/
$timer->start();
for(
$i 0$i <= ITERATION_OFFSET-1$i++)
{
   include 
'benchmark_content.txt';
}
$timer->finish();

$dump_include $timer->result();

// Reset the timer
$timer->reset();

/*
 * Time file_get_contents
*/
$timer->start();
for(
$i 0$i <= ITERATION_OFFSET-1$i++)
{
   echo 
file_get_contents('benchmark_content.txt');
}
$timer->finish();

echo 
'Benchmark of include : '$dump_include"\n";
echo 
'Benchmark of file_get_contents : '$timer->result(), "\n";
?>

The timer class:

View source

<?php
/**
* Basic timer class
* Returns value in seconds

* @name : timer
* @author : Ed Cradock
*/
class timer
{
   
/**
    * Start time
    * @var float
    * @access private
   */
   
private $start;

   
/**
    * End time
    * @var float
    * @access private
   */
   
private $end;

   
/**
   * Class constructor
   *
   * @access public
   */
   
public function __construct()
   {
      
$this->reset();
   }

   
/**
   * Start the timer
   *
   * @access public
   * @param foo $foo - bar
   * @return void
   */
   
public function start()
   {
      
$this->start microtime(true);
   }

   
/**
   * Finish the timer
   *
   * @access public
   * @return void
   */
   
public function finish()
   {
      
$this->finish microtime(true);
   }

   
/**
   * Returns the elapsed time in seconds (not rounded off)
   *
   * @access public
   * @return float
   */
   
public function result()
   {
      return (
$this->finish $this->start);
   }

   
/**
   * Reset the timer
   *
   * @access public
   * @return void
   */
   
public function reset()
   {
      
$this->start 0;
      
$this->finish 0;
   }
}
?>