<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/local/bin/perl

# parser.pl v 1.5 - 16th December, 1999
# by wayne.myers@bbc.co.uk (et al)
# Enormous thanks to:
# Chay Palton, Damion Yates, Matt Blakemore, Dan Tagg, T.V. Raman, Mark Foster
# and many others.

# parser.pl aka BETSIE is Copyright 1998,1999 BBC Digital Media
# See licence.txt for full licence details
# See readme.txt for more information
# These documents and more are available on the Betsie website:
# http://www.bbc.co.uk/education/betsie/

# Changes: 1.5
# 1 - Made move_nav a seperate subroutine
# 2 - Fixed anchors bug in auto-detected referers
# 3 - Cleaned up code some.
# 4 - Added some notion of changeable settings

# modules

use Socket;
#use strict;

# variables

my $VERSION = "1.5";	# version number
my @x = ();         	# this array holds all the lines of the html page we're parsing
my $contents = "";  	# this string is @x concatenated
my $inpath = "";    	# this is the path_info string from which we get the rest
my $root = "";      	# this is the domain of the page we are looking at
my $path = "";      	# this is the path of the page we are looking at
my $file = "";      	# this is the name of the file we are looking at
my $postdata = "";  	# this is any POST method data
my $method = "GET"; 	# and remains this way unless we get POST data
my $length = -1;    	# but is the length of content if any greater in a POST
my $count;				# counter for main request loop
my $httptype;			# http type of request
my $code;				# http return code
my $msg;				# http message
my $newurl;				# used to store redirect target
my $tag;				# used to store meta redirect tags
my $loop_flag;			# flag used to make sure we get the right page
my $script_flag;    	# flag used to see if we are in script tags or not
my $ws_flag;			# flag used to minimise unnecessary white space
my $set = 0;            # is 1 if we want the settings page
my $body; 				# holds the body tag

# VARIABLES YOU MIGHT WANT TO CHANGE:

my $maxpost = 65536; # is maximum number of bytes in a POST
my $parsehome = "http://www.bbc.co.uk/education/betsie/";
my $name = "betsie-1.5.pl";					# name of this file
my $agent = $ENV{'HTTP_USER_AGENT'};	# pretend to be the calling browser

# variables for colour/font settings etc
# be sure to amend make_body() if you amend them
my $setstr = "/0005";	# is default string for settings.
my $chsetstr = "/1005";  # string used for default change settings page
# next five arrays are for each set of colour options. feel free to add to or amend these.
my @bg = qw(#000000 #FFFFFF #0000FF #FFFFCC);
my @text = qw(#FFFF00 #000000 #FFFFFF #000000);
my @link = qw(#00FFFF #0000FF #FFFFCC #0000FF);
my @vlink = qw(#00CCFF #0000CC #FFFF99 #0000CC);
my @alink = qw(#FFFF00 #000000 #FFFFFF #000000);
# ten fonts. again, you can change these if you like
my @font_face = ("Verdana, Arial", "Times", "Courier", "Helvetica", "Arial",
				 "Bookman Old Style", "Geneva", "Chicago", "Courier New", "System");


# VARIABLES YOU MUST SUPPLY:

my $pathtoparser = "http://$ENV{'SERVER_NAME'}/cgi-bin/education/betsie/$name";
#my $pathtoparser = "http://localhost/cgi-bin/betsie/$name";
my $parsecontact = "education.online\@bbc.co.uk";
my $localhost = "www.bbc.co.uk";
my @safe = qw (	bbc.co.uk
				beeb.com
				bbcworldwide.com
				bbcresources.com
				bbcshop.com
				radiotimes.com
				open.ac.uk
				open2.net
				freebeeb.net
				);

# VARIABLES YOU (PROBABLY) DON'T WANT TO TOUCH:

my ($rec_test) = $pathtoparser =~ /^http:\/(.*)$/;	# var to solve recursion problem

# Set alarm handler (comment this out on systems that can't handle it)
alarm 10;
$SIG{ALRM} = \&amp;alarm;

# main loop

$|=1;
print "Content-type: text/html\n\n";

# handle POST requests

if ($ENV{'REQUEST_METHOD'} eq "POST") {

  $length = $ENV{'CONTENT_LENGTH'};

  if ($length &gt; 65536) {
    $x[0] = "Too much data for POST method.";
    error();
    exit;
  }

  if ($length) {

    read(STDIN, $postdata, $length, 0);
    $method = "POST";

  }
}

# take path info or referer allowing easy linking in...
$inpath = $ENV{'PATH_INFO'} || $ENV{'HTTP_REFERER'};
# strip http/ftp/gopher etc scheme if present (ie came from referer)
$inpath =~ s/^\w+:\///;

# Uncomment the following ugly hack for servers that don't do PATH_INFO properly 
# (if you couldn't do alarm above, you probably need this too :( )
# $inpath =~ s/^.*?$name//;

unless ($inpath =~ /^[a-zA-Z0-9_.\-\/\#]+$/) {
  $x[0] = "Unknown error";
  error();
  exit;
}

# beat recursive betsie bug

$inpath =~ s/^$rec_test//i;

# get optional settings string
$inpath =~ s#(\/\d+)\/#\/#;
$setstr = $1 || "/0005";
if (length $setstr != 5) { $setstr = "/0005"; }
$chsetstr = $setstr;
$chsetstr =~ s/^\/(\d)/\/1/;
if ($1 eq "1") { $set = 1;};

($root, $path, $file) = urlcalc($inpath);

unless (safe("http:\/\/$root")) {
  $x[0] = "&lt;A HREF=\"http:\/\/$root$path$file\"&gt;http:\/\/$root$path$file&lt;\/A&gt; not on safe list. Sorry";
  error();
  exit;
}

$loop_flag = 0;
$count = 0;

LOOP: while ($loop_flag == 0) {

  $count++;
  if ($count == 9) {
    $x[0] = "Too many times through the loop.";
    error();
    exit;
  }

  if ($ENV{'QUERY_STRING'} ne "") { $file .= "\?$ENV{'QUERY_STRING'}" }

  @x = graburl($root, $path . $file);
  $contents="";

  foreach (@x) {
     $contents .= $_;
  }

  # handle http codes
  # 3xx we follow the redirect
  # anything other than 200 is an error.

  ($httptype, $code, $msg) = split /\s+/, $x[0];

  if ($code =~ /^3\d\d/) {
    $contents =~ s/^.*Location:\s+(\S+)\s.*$/$1/s;
    $newurl = $contents;
    redir();
    next LOOP;
  }

  if ($code !~ /200/) {
    error();
    exit;
  }

  # check for autoredirects of all sorts

  if ($contents =~ /(&lt;META[^&gt;]*?HTTP-EQUIV[^&gt;]*?REFRESH[^&gt;]*?&gt;)/is) {
    $tag = $1;
    unless ($tag =~ /content=\"\d{3,}/is) {     # only deal with refreshes of 99 secs or less
      if ($tag =~ /url=(.*?)\"/is) {            # don't refresh if no url given
        $newurl = $1;
        unless ($file =~ /$newurl$/) {         # don't refresh to same page
          redir();
          next LOOP;
        }
      }
    }
  }
  
  # if we got here we must have got something and can end the loop

  $loop_flag = 1;

}

	# make the body tag
	$body = make_body();

	# if we're on the settings page, send that and exit
	if ($set != 0) {
		print &lt;&lt;HTML;	
&lt;HTML&gt;
&lt;HEAD&gt;
&lt;TITLE&gt;Betsie Settings Page&lt;/TITLE&gt;
&lt;META NAME="ROBOTS" CONTENT="NO INDEX, NO FOLLOW"&gt;
&lt;/HEAD&gt;
$body
&lt;/BODY&gt;
&lt;/HTML&gt;
HTML

		exit;
		}

  # we're not on the settings page. call parser routines

  $contents = preparse($contents);

  @x = split /\n/, $contents;

  $contents = "";

  # start sending

  $script_flag = 0; # it will be 1 if we are in &lt;SCRIPT&gt; tags
  $ws_flag = 0;   # it will be 2 if we just printed a second &lt;BR&gt; in a row

  for (@x) {
    $contents = parse($_);
    unless ((!$contents) || ($script_flag == 1) || ($contents =~ /^\s+$/s) || (($ws_flag &gt; 1) &amp;&amp; ($contents =~ /^(\s*&lt;BR[^&gt;]*?&gt;\s*)+$/is))) {
        print $contents;
        if ($contents !~ /&lt;BR[^&gt;]*?&gt;\s*$/is) { $ws_flag = 0; }
        unless ($contents =~ /\n$/) { print "\n"; }
    }
    if ($contents =~ /&lt;BR[^&gt;]*?&gt;\s*$/is) { $ws_flag++; }
  }


# subroutines

# redir
# handles redirects.
# assumes $newurl contains the new url to redirect to...

sub redir {

  # case 1 - it begins with /

  if ($newurl =~ /^\//) {
    $newurl = "\/" . $root . $newurl;
    ($root, $path, $file) = urlcalc($newurl);
    return;
  }

  # case 2 - it's the full path

  if ($newurl =~ /^http/) {
    $newurl =~ s/^http:\///;
    ($root, $path, $file) = urlcalc($newurl);
    return;
  }

  # case 3 - it's a filename

  if ($newurl =~ /^(\w|-|_)+\.\w+$/) {
    $file = $newurl;
    return;
  }

  # case 4 - it's a relative path

  if ($newurl =~ /[(\w|-|_)+\/]*(\w|-|_)+\.\w+/) {
    $path .= $newurl;
    $path =~ s/\/((\w|-|_)+\.\w+)$/\//;
    $file = $1;
    $path =~ s#\/(\w|-|_)+\/\.\.##g;
    return;
  }

  # case 5 - the ones i haven't thought of...

  $x[0] = "Unknown redirect - $newurl";

  error();
  exit;

}

# error
# displays error page with message

sub error {

print &lt;&lt;HTML;
&lt;HTML&gt;
&lt;HEAD&gt;
&lt;TITLE&gt;Betsie Error Page&lt;/TITLE&gt;
&lt;/HEAD&gt;
$body
&lt;P&gt;Sorry, but Betsie was unable to find the page at http://$root$path$file.

&lt;P&gt;The error was as follows: $x[0].

&lt;P&gt;If you have just found a bug in Betsie (it's possible), please email the details
to &lt;A HREF=\"mailto:$parsecontact\"&gt;$parsecontact&lt;/A&gt;

&lt;P&gt;&lt;A HREF=\"$parsehome\"&gt;Return to the Betsie
homepage&lt;/A&gt;, or select your browser's 'back' button (or equivalent) to return to the
page you just came from.

&lt;P&gt;Inpath: $inpath
&lt;P&gt;Root: $root
&lt;P&gt;Path: $path
&lt;P&gt;File: $file
&lt;P&gt;Contents: $contents

&lt;/FONT&gt;
&lt;/BODY&gt;
&lt;/HTML&gt;
HTML

}


# graburl
# homebrewed page grabber thing. gets remote page.

sub graburl {
  my ($host, $file) = @_;

  my ($remote, # the name of the SMTP server
      $port,   # the mail port
      $iaddr, $paddr, $proto, $line); # these vars used internally

  $remote  = $host;
  $port    = 80;

  #DMY
  if ($host eq "www.bbc.co.uk") {
    $host = "localhost";
  }

  unless ($iaddr   = inet_aton($remote)) {
    warn "no host: $remote";
    return ("Error: no host", "$!");
  }


  $paddr   = sockaddr_in($port, $iaddr);
  $proto   = getprotobyname('tcp');
  select(SOCK);
  $| = 1;

  unless (socket(SOCK, PF_INET, SOCK_STREAM, $proto)) {
    warn "socket: $!";
    return ("Error: socket problem", "$!");
  }

  unless (connect(SOCK, $paddr)) {
    warn "connect: $!";
    return ("Error: connection problem", "$!");
  }

  select(STDOUT);

  print SOCK "$method $file HTTP/1.0\n";
  print SOCK "Accept: */*\n";
  print SOCK "User-Agent: $agent\n";
  print SOCK "Host: $host\n";
  if ($length &gt; -1) { print SOCK "Content-Length: $length\n"; }
  print SOCK "\n";
  if ($length &gt; -1) {
    print SOCK "$postdata\n";
  }

#  sleep(5);

  @x = &lt;SOCK&gt;;

  unless (close (SOCK)) {
    warn "close: $!";
    return ("Error: problem closing socket", "$!");
  }

  $method = "GET";
  $length = -1;
  $postdata = "";

  return @x;

}

# parser routines

# preparse
# preparses take the whole page and does the bits that need the whole of the page

sub preparse {

	my $page = shift;

	# preparsing:

	# remove http header lines and insert missing html/body tags
	
	if ($page !~ /&lt;HTML&gt;/is) {
		$page =~ s/^(.+?)\n\n/&lt;HTML&gt;/s;
	} else {
		$page =~ s/.*?&lt;HTML&gt;/&lt;HTML&gt;/is;
	}

	if ($page !~ /&lt;\/HTML&gt;/is) {
		$page .= "&lt;\/HTML&gt;";
	}

    if ($page !~ /&lt;FRAMESET/is) {    # don't do this to frames pages

		if ($page !~ /&lt;\/BODY&gt;/is) {
			$page =~ s/&lt;\/HTML&gt;/&lt;\/BODY&gt;\n&lt;\/HTML&gt;/is;
		}

		if ($page !~ /&lt;BODY/is) {						# if there's no body tag
			if ($page =~ /&lt;\/HEAD&gt;/is) {					# look for an end head tag
				$page =~ s/&lt;\/HEAD&gt;/&lt;\/HEAD&gt;\n&lt;BODY&gt;/is;	# put body tag there if we find it
			} else {
				if ($page =~ /&lt;\/TITLE&gt;/is) {			# if we don't find end head look for end title
					$page =~ s/&lt;\/TITLE&gt;/&lt;\/TITLE&gt;&lt;\/HEAD&gt;\n&lt;BODY&gt;/is;	# insert both end head and body start
				} else {
					$page =~ s/&lt;HTML&gt;/&lt;HTML&gt;&lt;HEAD&gt;&lt;TITLE&gt;$root$path$file&lt;\/TITLE&gt;&lt;\/HEAD&gt;&lt;BODY&gt;/is;
					# this is clumsy, true, but so is the code it's trying to fix.
				}
			}
		}

	}

	# now we have a head we can look out for and exclude robots.
	$page =~ s/(&lt;\/HEAD&gt;)/&lt;META NAME="ROBOTS" CONTENT="NO INDEX, NO FOLLOW"&gt;\n$1/is;

	# remove stylesheets part 1

	$page =~ s/&lt;STYLE.+?&lt;\/STYLE&gt;//gis;

	# remove java

	$page =~ s/&lt;APPLET.+?&lt;\/APPLET&gt;/&lt;P&gt;Java applet removed\.\n/gis;

	# put MAPs in BODY (later on AREAs become As...)
# beginning of body?	
#	while ($page =~ s/&lt;MAP[^&gt;]*?&gt;(.*?)&lt;\/MAP&gt;(.*?&lt;BODY[^&gt;]*?&gt;)/$2\n$1/is) {};
# or end of body...
	while ($page =~ s/&lt;MAP[^&gt;]*?&gt;(.*?)&lt;\/MAP&gt;(.*)(&lt;\/BODY&gt;)/$2\n$1\n$3/is) {};


	# remove all extraneous whitespace and newlines in tags

	$page =~ s/\s+=/=/gs;
	$page =~ s/=\s+/=/gs;
	$page =~ s/&lt;\s+([^&gt;]+)&gt;/&lt;$1&gt;/gs;
	$page =~ s/&lt;([^&gt;]+)\s+&gt;/&lt;$1&gt;/gs;
 # $page =~ s/&lt;([^&gt;]+?)\s+&gt;/&lt;$1&gt;/gs;
	while ($page =~ s/&lt;([^&gt;]+)\n([^&gt;]+)&gt;/&lt;$1 $2&gt;/gs) {}
 # $page =~ s/&lt;([^&gt;]+?)\n([^&gt;]+?)&gt;/&lt;$1 $2&gt;/gs;
	while ($page =~ s/&lt;([^&gt;]+?)\s{2,}([^&gt;]+)&gt;/&lt;$1 $2&gt;/gs) {}
	
	# remove empty links - mucho ta to Matt Blakemore for suggesting this one
	
	$page =~ s/&lt;A[^&gt;]*HREF\s*\=\s*[^&gt;]*&gt;\s*&lt;IMG[^&gt;]*ALT\s*\=\s*\"\"[^&gt;]*&gt;\s*&lt;\/A&gt;//gis;

	# go to move_nav and move the nav
	
	$page = move_nav($page);  

	# remove hidden javascript. and comments. (sorry).

	$page =~ s/&lt;!--.*?--&gt;//gs;

  # make sure no two tags are on same line

  $page =~ s/(&gt;)([^\n|=])/$1\n$2/gs;

  # remove blank lines

  #$page =~ s/\n\n/\n/gs;
  $page =~ s/\s{2,}/\n/gs;
  return $page;
}

# move_nav
# moves the nav bar around
# this one is for the BBC site. your site may need a whole different one...

sub move_nav {

	my $page = shift;
	
	if ($root =~ /\.bbc\.co\.uk$/) {

    # first make sure all table widths have double quotes

    $page =~ s/(&lt;T[^&gt;]*?)WIDTH=(\d+)/$1WIDTH="$2"/gis;
  
    for ($root) {

      /^news/ and do {
    
                  # news nav mangling - sits in a table width 90 pixels... Or 100 pixels. Depends on the template.

                  $page =~ s/(.*?)&lt;TABLE([^&gt;]*?)WIDTH=["|']?(?:90|100)["|']?.*?&gt;(.*?)&lt;\/TABLE&gt;(.*)&lt;\/BODY&gt;/$1$4$3&lt;\/BODY&gt;/is;

                  last;

                  };

      /^www/  and do {
    
                  # normal or worldservice...

                  if ($path =~ /worldservice|arabic|cantonese|mandarin|russian|spanish|ukrainian/) {

                      # world service nav mangling - sits in a td width 98 pixels and followed by td width 1 pixel
                      # but mileage varies, hence all the \d's...

                      $page =~ s/(.*?)&lt;TD([^&gt;]*?)WIDTH=["|'](?:9\d|1\d\d)["|'].*?&gt;(.*?)&lt;TD([^&gt;]*?)WIDTH=["|']\d["|'].*?&gt;(.*)&lt;\/BODY&gt;/$1$5$3&lt;\/BODY&gt;/is;

                  } elsif ($path =~ /^\/news\//) {

                      # news nav mangling - sits in a table width 90 pixels... Or 100 pixels. Depends on the template.

                      $page =~ s/(.*?)&lt;TABLE([^&gt;]*?)WIDTH=["|'](?:90|100)["|'].*?&gt;(.*?)&lt;\/TABLE&gt;(.*)&lt;\/BODY&gt;/$1$4$3&lt;\/BODY&gt;/is;

                  } else {

                    # deal with old education navbar

                    last if ($page =~ s#(&lt;A HREF=\"\/education\/nav\/bbcedbar\.map\"&gt;).*?(&lt;/A&gt;)#$1BBC Education$2#is);
                      
                    if ($page =~ /&lt;!--\s+GLOBALNAVBEGIN/s) {

                      	# code for new templates here --&gt;
                      	$page =~ s/(.*?)&lt;!--\s+GLOBALNAVBEGIN[^&gt;]+?&gt;(.*?)&lt;!--\s+SERVICESNAVEND\s+--&gt;(.*)&lt;\/BODY&gt;/$1$3$2&lt;\/BODY&gt;/is;
 
                    } else {
                      
                      	# Old standard navs. Should be 107 and 3 pixels, but you never know...
                    	$page =~ s/(.*?)&lt;TD([^&gt;]*?)WIDTH=["|']1\d\d["|'].*?&gt;(.*?)&lt;TD([^&gt;]*?)WIDTH=["|']\d["|'].*?&gt;(.*)&lt;\/BODY&gt;/$1$5$3&lt;\/BODY&gt;/is;

					}
					

                  }

                  last;

                  };
 
		# i don't know where we are, here, but lets try for standard nav bars anyway...
		if ($page =~ /&lt;!--\s+GLOBALNAVBEGIN/s) {
           	# code for new templates here --&gt;
           	$page =~ s/(.*?)&lt;!--\s+GLOBALNAVBEGIN[^&gt;]+?&gt;(.*?)&lt;!--\s+SERVICESNAVEND\s+--&gt;(.*)&lt;\/BODY&gt;/$1$3$2&lt;\/BODY&gt;/is;
		} else {
            # Old standard navs. Should be 107 and 3 pixels, but you never know...
            $page =~ s/(.*?)&lt;TD([^&gt;]*?)WIDTH=["|']1\d\d["|'].*?&gt;(.*?)&lt;TD([^&gt;]*?)WIDTH=["|']\d["|'].*?&gt;(.*)&lt;\/BODY&gt;/$1$5$3&lt;\/BODY&gt;/is;
		}
    }
  }
	
	
	return $page;	
	
}

# parse
# handles the line-by-line bits of betsification

sub parse {

	my ($line) = shift;
	my $link;
	my $alt;    # used in area tag handler
	my $target; # ditto

	$line =~ s/click here/select this link/gis;

	# nuke javascript event handlers

	while ($line =~ s/(&lt;[^&gt;]*?)(\s+on\S+?=\".*?\")+(.*?&gt;)/$1 $3/i) {}; # dbl quotes
	while ($line =~ s/(&lt;[^&gt;]*?)(\s+on\S+?=\'.*?\')+(.*?&gt;)/$1 $3/i) {}; # sgl quotes
	while ($line =~ s/(&lt;[^&gt;]*?)(\s+on\S+?=\S+?)(&gt;)/$1 $3/i) {};     # no quotes. naughty!

    # lose inline stylesheeting

    $line =~ s/(&lt;[^&gt;]*?)STYLE\s*=\s*\".*?\"/$1/gis;

    # lose arbitrary justification arbitrarily

    $line =~ s/(&lt;[^&gt;]*?)ALIGN\s*=\s*\".*?\"/$1/gis;

    # S T O P   P E O P L E   L I K E   T H I S (thanx to T.V.Raman for the suggestion)

    if ($line =~ /(\w ){3,}/) {
    	$line =~ s/(\w) /$1/g;
    }

	my $tag = "";
	($tag) = $line =~ /&lt;(\S+)[^&gt;]*?&gt;/;
	if ($tag eq "") { return $line; }
	$tag = uc $tag;

	for ($tag) {

	# handle javascript script
	
		/NOSCRIPT/		 and do {
									 $line =~ s/&lt;(?:\/)?NOSCRIPT[^&gt;]*?&gt;//gis;	 
									 last;
								 };

		/SCRIPT/ and do {
							if ($line =~ /&lt;SCRIPT/i) {
								$script_flag = 1;
								$line =~ s/&lt;SCRIPT.*$//gis;
							} elsif ($line =~ /&lt;\/SCRIPT/i) {
								$line =~ s/^.*?&lt;\/SCRIPT&gt;//i;
								$script_flag = 0;
							}
							last;
						 };
						 
	# lose NOBR

		/NOBR/   and do {
							$line =~ s/&lt;(?:\/)?NOBR&gt;//gis;
							last;
						};

	# lose link rel=stylesheet *only*

		/LINK/   and do {
							if ($line =~ /REL\s*=\s*\"?stylesheet\"?/gis) {
								$line =~ s/&lt;LINK[^&gt;]*?&gt;//gis;
							}
							last;
						};

	# lose that deprecated CENTER tag!

		/CENTER/		 and do {
									 $line =~ s/&lt;(?:\/)?CENTER[^&gt;]*?&gt;//gis;	 
									 last;
								 };


	# nuke all fonts

		/FONT/	 and do {
									 $line =~ s/&lt;(?:\/)?FONT[^&gt;]*?&gt;//gis;
									 $line =~ s/&lt;(?:\/)?BASEFONT[^&gt;]*?&gt;//gis;
									 last;
								 };

		/BASE/	 and do {
		
									 if (($link) = $line =~ /&lt;BASE[^&gt;]+?HREF\s*=\s*(\S+)[^&gt;]*?&gt;/i) {
										 $link =~ s/\"//g;
										 $link =~ s#^http:\/##i;
										 ($root, $path) = urlcalc($link);
									 }

									 last;
								 };
								 
	# lose layers

		/LAYER/	and do {
									 $line =~ s/&lt;(?:\/)?LAYER[^&gt;]*?&gt;//gis;
									 last;
								 };
								 
	# lose divs

		/DIV/	and do {
									 $line =~ s/&lt;(?:\/)?DIV[^&gt;]*?&gt;//gis;
									 last;
								 };
	# detableiser

		/TABLE/	and do {
									 $line =~ s/&lt;(?:\/)?TABLE[^&gt;]*?&gt;//gis;
									 last;
								 };
		/TR$/		 and do {
									 $line =~ s/&lt;(?:\/)?TR[^&gt;]*?&gt;//gis;	 
									 last;
								 };
		/TD$/		 and do {
									 $line =~ s/&lt;\/TD&gt;//gis;
									 $line =~ s/&lt;TD.*?&gt;/&lt;BR&gt;/gis;
									 last;
								 };

	# link masher

		/^A$/		 and do {

									# get the link out and remove any quoting
										($link) = $line =~ /&lt;A[^&gt;]+?HREF\s*=\s*(\S+)[^&gt;]*?&gt;/i;
										$link =~ s/\"//g;
										$link =~ s/\'//g;
										last if ($link =~ /^\#/);	 # ignore anchors

										$line =~ s/\s*=\s*/=/;

									# check for URL passing scripts and make them external
									# this should fix webguide and all other script based
									# URL passers for whom A HREF is just too easy... :)
									# note that URLs automatically end if an &amp; is present. For some reason. ;)

										if ($link =~ m#\?.*?http(:|CHR\(58\))\/\/#i) {

											$link =~ s/CHR\(58\)/:/gi;
											$link =~ s/.*?(\?.*)/$1/;
											$link =~ s#^\?.*?(http:\/\/.*)$#$1#i;
											$link =~ s/&amp;.*$//;
											unless (safe($link)) {
												$line =~ s#(&lt;A[^&gt;]+?HREF=)\S+([^&gt;]*?&gt;)#$1$link$2 (External)#i;
												last;
											}
										}

										# handle real audio

										if ($link =~ /\.(ram|rm|ra)$/i) {
											if ($link =~ /^http:/i) {
												last;
											}
											if ($link =~ /^\//) {
												$link = "http:\/\/" . $root . $link;
												$line =~ s/(&lt;A[^&gt;]+?HREF=)\S+([^&gt;]*?&gt;)/$1"$link"$2/i;
												last;
											}
											$link = $root . $path . $link;
											$link =~ s#\/\w+\/\.\.\/#\/#g;
											$link = "http:\/\/" . $link;
											$line =~ s/(&lt;A[^&gt;]+?HREF=)\S+([^&gt;]*?&gt;)/$1"$link"$2/i;
											last;
										}

									# handle fully qualified links

										if ($link =~ /^\w+:/) {
											unless (safe($link)) {
												$line =~ s/(&lt;A[^&gt;]+&gt;)/$1 (External)/i;
												last;
											}
											if ($link =~ /^http/i) {
												$link =~ s/^http:\/(\/.*)$/$pathtoparser$setstr$1/i;
												$line =~ s/(&lt;A[^&gt;]+?HREF=)\S+([^&gt;]*?&gt;)/$1"$link"$2/i;
											} elsif ($link =~ /javascript:/) {
													$line =~ s/&lt;A[^&gt;]+&gt;/&lt;A HREF=""&gt;/i;
											}
											last;
										}

									# now the slash led links

										if ($link =~ /^\//) {
											$link = $pathtoparser . "$setstr" ."\/". $root . $link;
											$line =~ s/(&lt;A[^&gt;]+?HREF=)\S+([^&gt;]*?&gt;)/$1"$link"$2/i;
											last;
										}

									# now the rest of them

										$link = "\/" . $root . $path . $link;
										$link =~ s#\/\w+\/\.\.\/#\/#g;
										$link = $pathtoparser. "$setstr" . $link;
										$line =~ s/(&lt;A[^&gt;]+?HREF=)\S+([^&gt;]*?&gt;)/$1"$link"$2/i;
										last;
									};

/^AREA$/			and do {
									
									# get the link out and remove any quoting
										($link) = $line =~ /&lt;AREA[^&gt;]+?HREF\s*=\s*(\S+)[^&gt;]*?&gt;/i;
										$link =~ s/\"//g;
										$link =~ s/\'//g;
										last if ($link =~ /^\#/);	 # ignore anchors

									# get ALT out

										($alt) = $line =~ /&lt;AREA[^&gt;]+?ALT\s*=\s*\"(.*?)\"[^&gt;]*?&gt;/i;

										$alt = $alt || $link;  # so non-ALT tagged stuff sort of works...

									# get TARGET out (if present) - we don't need to do this elsewhere
									# because it's retained, but here we're rewriting the whole tag...

										($target) = $line =~ /&lt;AREA[^&gt;]+?TARGET\s*=\s*\"(.*?)\"[^&gt;]*?&gt;/i;

										$target = $target || "_top";  # so non-targeted stuff sort of works...

									# handle fully qualified links

										if ($link =~ /^\w+:/) {
											unless (safe($link)) {
												$line = "&lt;A HREF=\"$link\" TARGET=\"$target\"&gt;$alt (External)&lt;/A&gt;&amp;nbsp;";
												last;
											}
											if ($link =~ /^http/i) {
												$link =~ s/^http:\/(\/.*)$/$pathtoparser$setstr$1/i;
												$line = "&lt;A HREF=\"$link\" TARGET=\"$target\"&gt;$alt&lt;/A&gt;&amp;nbsp;"
											} elsif ($link =~ /javascript:/) {
													$line = "&lt;A HREF=\"\"&gt;&amp;nbsp;";
											}
											last;
										}

									# now the slash led links

										if ($link =~ /^\//) {
											$link = $pathtoparser . "$setstr" ."\/". $root . $link;
											$line = "&lt;A HREF=\"$link\" TARGET=\"$target\"&gt;$alt&lt;/A&gt;&amp;nbsp;";
											last;
										}

									# now the rest of them

										$link = "\/" . $root . $path . $link;
										$link =~ s#\/\w+\/\.\.\/#\/#g;
										$link = $pathtoparser. "$setstr" . $link;
										$line = "&lt;A HREF=\"$link\" TARGET=\"$target\"&gt;$alt&lt;/A&gt;&amp;nbsp;";
										last;

								};


/^FRAMESET$/	and do {
									 $line =~ s/(&lt;FRAMESET[^&gt;]*?) COLS/$1 ROWS/i;
									 $line =~ s/(&lt;FRAMESET[^&gt;]+)FRAMEBORDER\s*=\s*['|"]?[NO|0]['|"]?([^&gt;]*)&gt;/$1 $2&gt;/i;
									 $line =~ s/(&lt;FRAMESET[^&gt;]+)BORDER\s*=\s*['|"]?0['|"]?([^&gt;]*)&gt;/$1 $2&gt;/i;
									 while ($line =~ s/(&lt;FRAMESET[^&gt;]*?\=\s*["|']?\s*)\d{1,2}\%?,/$1\*/i) {};
									 last;
								 };																	 

/^FRAME$/		 and do {


									# make all frames resizeable...

										$line =~ s/(&lt;FRAME[^&gt;]+?)NORESIZE[="NORESIZE"]?([^&gt;]*&gt;)/$1 $2/ig;
										$line =~ s/(&lt;FRAME[^&gt;]+)FRAMEBORDER\s*=\s*['|"]?[NO|0]['|"]?([^&gt;]*)&gt;/$1 $2&gt;/i;
										$line =~ s/(&lt;FRAME[^&gt;]+)BORDER\s*=\s*['|"]?0['|"]?([^&gt;]*)&gt;/$1 $2&gt;/i;
										
									# get the link out and remove any quoting
									
										($link) = $line =~ /&lt;FRAME[^&gt;]+?SRC\s*=\s*(\S+)[^&gt;]*?&gt;/i;
										last if ($link eq "");
										$link =~ s/\"//g;
										$link =~ s/\'//g;
										$line =~ s/\s*=\s*/=/;
										if ($line !~ /scrolling/i) {
										
											$line =~ s/(&lt;FRAME[^&gt;]+)&gt;/$1 SCROLLING=YES&gt;/i;

										} else {

											$line =~ s/(&lt;FRAME[^&gt;]+)SCROLLING\s*=\s*['|"]?NO['|"]?([^&gt;]*)&gt;/$1 SCROLLING=\"YES\" $2&gt;/i;

										}
									# handle fully qualified links

										if ($link =~ /^\w+:/) {
											if ($link =~ /^http/i) {
												$link =~ s/^http:\/(\/.*)$/$pathtoparser$setstr$1/i;
												$line =~ s/(&lt;FRAME[^&gt;]+?SRC=)\S+([^&gt;]*?&gt;)/$1"$link"$2/i;
											}
											last;
										}

									# now the slash led links

										if ($link =~ /^\//) {
											$link = $pathtoparser . "$setstr" ."\/". $root . $link;
											$line =~ s/(&lt;FRAME[^&gt;]+?SRC=)\S+([^&gt;]*?&gt;)/$1"$link"$2/i;
											last;
										}

									# now the rest of them

										$link = "\/" . $root . $path . $link;
										$link =~ s#\/\w+\/\.\.\/#\/#g;
										$link = $pathtoparser . "$setstr". $link;
										$line =~ s/(&lt;FRAME[^&gt;]+?SRC=)\S+([^&gt;]*?&gt;)/$1"$link"$2/i;
										last;
									};

/^FORM$/		 and do {

									# get the link out and remove any quoting

										($link) = $line =~ /&lt;FORM[^&gt;]+?ACTION\s*=\s*(\S+)[^&gt;]*?&gt;/i;
										last if ($link eq "");
										$link =~ s/\"//g;
										$link =~ s/\'//g;
										$line =~ s/\s*=\s*/=/;

									# handle fully qualified links

										if ($link =~ /^\w+:/) {
											if ($link =~ /^http/i) {
												$link =~ s/^http:\/(\/.*)$/$pathtoparser$setstr$1/i;
												$line =~ s/(&lt;FORM[^&gt;]+?ACTION=)\S+([^&gt;]*?&gt;)/$1"$link"$2/i;
											}
											last;
										}

									# now the slash led links

										if ($link =~ /^\//) {
											$link = $pathtoparser .$setstr. "\/".$root . $link;
											$line =~ s/(&lt;FORM[^&gt;]+?ACTION=)\S+([^&gt;]*?&gt;)/$1"$link"$2/i;
											last;
										}

									# now the rest of them

										$link = "\/" . $root . $path . $link;
										$link =~ s#\/\w+\/\.\.\/#\/#g;
										$link = $pathtoparser .$setstr. $link;
										$line =~ s/(&lt;FORM[^&gt;]+?ACTION=)\S+([^&gt;]*?&gt;)/$1"$link"$2/i;
										last;
									};

		/IMG/		 and do {

										# case 1 - image has empty alt tag

										$line =~ s/&lt;IMG[^&gt;]*?ALT="".*?&gt;//i;

										# case 2 - image has non-empty alt tag

										$line =~ s/&lt;IMG[^&gt;]*?ALT="(.+?)".*?&gt;/&lt;P&gt;$1/i;

										# case 3 - image has no alt tag at all

										$line =~ s/&lt;IMG.*?&gt;//i;

										last;

									};

		/INPUT/		 and do {

										# only screw with it if it's an image...

										if ($line =~ /(&lt;INPUT[^&gt;]*?TYPE=("|')?)IMAGE/gis) {
											$line =~ s/($1)IMAGE/$1SUBMIT/gis;
											last;
										}
										
										last;

									};

		/EMBED/	 and do {

										# sort shockwave etc plus anything else embedded with SRC

										# currently attempts to make sure all SRC left after losing images has the right path

										$line =~ s/&lt;([^&gt;]+?)SRC=(['|"]?)(\/\S+?)(['|"]?)([^&gt;]*?)&gt;/&lt;$1SRQ=$2http:\/\/$root$3$4$5&gt;/i;
										$line =~ s/&lt;([^&gt;]+?)SRC=(['|"]?)(http:\/\/\S+?)(['|"]?)([^&gt;]*?)&gt;/&lt;$1SRQ=$2$3$4$5&gt;/i;
										$line =~ s/&lt;([^&gt;]+?)SRC=(['|"]?)(\S+?)(['|"]?)([^&gt;]*?)&gt;/&lt;$1SRC=$2http:\/\/$root$path$3$4$5&gt;/i;
										$line =~ s#\/\w+\/\.\.\/#\/#g;
										$line =~ s/&lt;([^&gt;]+?)SRQ/&lt;$1SRC/i;
	
									};

		/BODY/		and do {

	                    if ($line =~ /&lt;BODY/i ) {
    	                  	$line =~ s/&lt;BODY[^&gt;]*?&gt;/$body/i;
            	          	last;
						}

						$line =~ s#&lt;\/BODY&gt;#\n&lt;P&gt;&lt;A HREF=\"$pathtoparser$chsetstr/$root$path$file\"&gt;Change Text Only Settings&lt;\/A&gt;\n&lt;P&gt;&lt;A HREF=\"http:\/\/$root$path$file\"&gt;Graphic version of this page&lt;\/A&gt;\n&lt;\/FONT&gt;\n&lt;!-- This page parsed by Betsie version $VERSION--&gt;\n&lt;\/BODY&gt;#is;

									};

	}

	return $line;

}

# url calc takes an inpath (is full url without http:/ at beginning
# ie it expects it to begin with a slash and then have the domain name,
# and then whatever else we have or have not got...

sub urlcalc {

  my $url = shift;
  my $root = "";
  my $path = "";
  my $file = "";

  $url =~ s#^\/([^\/]*)##;
  $root = $1;
  ($path, $file) = $url =~ /(.*\/)(.*?)$/;
  if ($path eq "") { $path = "\/"; }
  if ($file eq "/") { $file = ""; }

  return $root, $path, $file;

}

# alarm
# kills hanging Betsies. added by Damion Yates From BBC R&amp;D (Kingswood)
# doesn't work on machines that don't implement alarm
sub alarm {
    my $signame = shift;
    die "Betsie Alert: Timeout after 10 minutes SIG$signame received\n";
}

# safe
# makes sure the url given is in the safe list

sub safe {

  my $url = shift;

  return 1 if ($url =~ /^(javascript|mailto):/is);

  for (@safe) {
    return 1 if ($url =~ /\w+:\/\/((\w|-)+\.)*$_/is);
  }
  return 0;

}

# make_body
# returns a suitable body tag
# including settings page if appropriate
sub make_body {

	my $b = "";
	my ($slash, $set, $code, $font, $font_size) = split '', $setstr;
	
	# brief sanity check - font size must be 1 to 7, code 0 to 3, font 0 to 9 (hence no check)
	# we don't really care about set or slash. in fact we don't even use slash.
	if ($font_size &gt; 7 || $font_size == 0) { $font_size = 5; }
	if ($code &gt; 3) { $code = 0; }
	
	if ($set == 1) {
		
		$b = "&lt;H1&gt;Text Only Settings Page:&lt;/H1&gt;
&lt;P&gt;You can change the text-only settings by selecting from the following links. Select the last link when you are done.
&lt;P&gt;Alternatively, &lt;A HREF=\"$pathtoparser/1005/$root$path$file\"&gt;select this link&lt;/A&gt; to return to the default settings.
&lt;H2&gt;Colours:&lt;/H2&gt;
&lt;P&gt;&lt;A HREF=\"$pathtoparser/10$font$font_size/$root$path$file\"&gt;Yellow On Black&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/11$font$font_size/$root$path$file\"&gt;Black On White&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/12$font$font_size/$root$path$file\"&gt;White On Blue&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/13$font$font_size/$root$path$file\"&gt;Black On Cream&lt;/A&gt;	
&lt;H2&gt;Font Size:&lt;/H2&gt;
&lt;P&gt;&lt;A HREF=\"$pathtoparser/1".$code.$font."1/$root$path$file\"&gt;Tiny&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code.$font."2/$root$path$file\"&gt;Small&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code.$font."3/$root$path$file\"&gt;Medium Small&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code.$font."4/$root$path$file\"&gt;Medium&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code.$font."5/$root$path$file\"&gt;Large&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code.$font."6/$root$path$file\"&gt;Extra Large&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code.$font."7/$root$path$file\"&gt;Extra Extra Large&lt;/A&gt;
&lt;H2&gt;Font:&lt;/H2&gt;
&lt;P&gt;&lt;A HREF=\"$pathtoparser/1".$code."0$font_size/$root$path$file\"&gt;Verdana&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code."1$font_size/$root$path$file\"&gt;Times&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code."2$font_size/$root$path$file\"&gt;Courier&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code."3$font_size/$root$path$file\"&gt;Helvetica&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code."4$font_size/$root$path$file\"&gt;Arial&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code."5$font_size/$root$path$file\"&gt;Bookman Old Style&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code."6$font_size/$root$path$file\"&gt;Geneva&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code."7$font_size/$root$path$file\"&gt;Chicago&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code."8$font_size/$root$path$file\"&gt;Courier New&lt;/A&gt;
, &lt;A HREF=\"$pathtoparser/1".$code."9$font_size/$root$path$file\"&gt;System&lt;/A&gt;
&lt;H2&gt;Notes:&lt;/H2&gt;
&lt;P&gt;Not all browsers support all possible font, size and colour combinations.
&lt;P&gt;Most browsers allow you to specifiy your own font, size and colour combinations, overriding any given 
by the current page. You may find that route more flexible than the options allowed here. Consult your browser
documentation for details.
&lt;HR&gt;
&lt;P&gt;&lt;B&gt;&lt;A HREF=\"$pathtoparser/0$code$font$font_size/$root$path$file\"&gt;Select this link when done&lt;/A&gt;&lt;/B&gt;";

	}
	

	
	$b = "&lt;BODY BGCOLOR=\"$bg[$code]\" TEXT=\"$text[$code]\" LINK=\"$link[$code]\" ALINK=\"$alink[$code]\" VLINK=\"$vlink[$code]\"&gt;\n&lt;FONT FACE=\"$font_face[$font]\" SIZE=\"$font_size\"&gt;\n" . $b;
	
	return $b;
	
}

=head1 NAME

Betsie - the BBC Education Text To Speech Internet Enhancer

=head1 DESCRIPTION

Betsie is a simple CGI filter to improve the accessibility of arbitrary valid HTML pages.

=head1 README

Betsie is a simple CGI filter to improve the accessibility of arbitrary valid HTML pages. It
effectively creates an on-the-fly text-only version of your site.

For full details of how to use and install Betsie, please refer to the following URL:

http://www.bbc.co.uk/education/betsie/readme.txt

For full details of Betsie's current functionality, contact details, etc etc etc, 
visit the Betsie website: http://www.bbc.co.uk/education/betsie/

=head1 LICENCE

For full details of the licence arrangements for Betsie, please refer to the following URL:

http://www.bbc.co.uk/education/betsie/licence.txt

Executive summary - it's free if you want to use it but you can't sell it.

=head1 PREREQUISITES

This script requires the C&lt;socket&gt; module.

=head2 COREQUISITES

none

=pod OSNAMES

any

=pod SCRIPT CATEGORIES

CGI/Filter
Web

=cut</pre></body></html>