Category: programming

Twitter Script Update

Howdy. Twitter changed the search format, which means my php twitter script wasn’t working correctly. I finally took the time to remedy that tonight. Here’s the updated source code:

', $content);
        $content = explode('', $content[1]);
        return html_entity_decode($content[0]);
    }
    $my_tweet = get_latest_tweet('Username');
    if ($my_tweet != NULL)
        {

            echo "$my_tweet";
        }
    else {
        echo "Twitter is having issues again . . . .";
        }

    ?>

You can reference my old blog post if you want to know more how it works. For the copy/paste types: make sure you cange “Username” on line 20 to your twitter ID.


Compiling Wget on Windows

Last night, I managed to compile Wget on windows, with the SSL options. Compiling wget on windows isn’t really that hard. With MingW is works pretty well. What doesn’t work that well is getting SSL to work, because you need to compile OpenSSL, which is a pretty crappy distribution of SSL. And I never seemed to be able to build OpenSSL within MingW because it relies on autotools which doesn’t work on windows.

Brief note for authors of software: If you want a windows port, make it so I use make, or nmake. Which ever compiler you choose, build it so that I can just build the software, not fight it for an hour, then give up. I will hate you, I will hate your software. And I will have nothing nice to say.

Anyway, I reinstalled windows on my computer. Which means in theory I lost everything I had previously installed. I’m taking a C++ class, and I need a local compiler to code on. So after alot of deliberation, I settled on using MSVC. Then for grins, I decided to build wget with it, and try to get SSL working. I managed it. Here’s my notes on the process:
Installation Setup

  • install visual studio 2008 professional. You might be able to use an express version, but courtesy my colleges I have copies of MCVS 2008. So, I’m making use of it.
  • install active perl 5.10. I don’t care for the activestate distro of perl, but this is what the authors list for openssl and its best to stick as close to the readme files as possible.
  • there is a enough nasm included with vs2008, so you don’t need to install anything extra
  • Update VS2008. Use MS Update.

Compile Open SSL. I used version openssl-1.0.0a.tar.gz. Note that you won’t have the assembly libraries with the following commands, but wget a)doesn’t seem to need them, and b) you won’t have any errors this way :).

  • > perl Configure VC-WIN32 no-asm --prefix=c:/openssl
  • > msdo_ms
  • We want to make a static version, so we don’t have to include the DLLs with our wget distro. Of course, this increases file size, but picky picky.

  • > nmake -f msnt.mak
  • > nmake -f msnt.mak test (optional)
  • > nmake -f msnt.mak install

Build Wget:
The authors of wget include a long winded about compiling Wget 1.12. The short version is, the make routines are mangled and unusable withing wget 1.12. A better windows developer then I want to step up and help? Since it doesn’t work on windows, I used the previous version, wget-1.11.4.tar.gz.

Now, if you don’t’ want SSL, you can skip this part. If you do want SSL, then readfollow.

The wget readme says:

For MSVC the current default is to build Wget with SSL support.  For this to work, you will need to have penSSL installed.  First, get OpenSSL (http://www.openssl.org), compile it and install the relevant headers and libraries where your compiler can find them; currently this could mean (presuming default installation directories for MSVC 6.0) copy (from the compiled OpenSSL directory) the whole inc32openssl directory and its contents to “C:Program FilesMicrosoft Visual StudioVC98Includeopenssl”, and from out32dll (in the openSSL directory) the two needed libraries (libeay32.lib and ssleay32.lib) to “C:Program FilesMicrosoft Visual StudioVC98lib”.  These locations aren’t exactly the best but will get you started if you don’t know where to place these headers and libraries, you should find similar paths for later compiler versions. Usually at run-time some OpenSSL libraries (currently ssleay32.dll and libeay32.dll) will need to be available in your environment PATH.

My distilled version is:

  • copy the C:opensslinc32openssl directory to “C:Program FilesMicrosoft Visual StudioVCIncludeopenssl”
  • Copy the contents of C:openssllib to “C:Program FilesMicrosoft Visual StudioVClib”.

Now, change directories to the extracted wget dir and execute the following:

  • >configure.bat --msvc
  • >nmake

You’ll probably get some errors related to makeinfo.exe or other stuff. But if you execute dir src/*.exe you should see a wget.exe listed in the directory. If so, success. If not, sorry. The final test is to execute src/wget - -help and see if you have SSL options.

To be honest, this guide is really a lot of copy/paste from the various readme files included in the distributions of openssl and wget and my smart aleck comments. I’m just listing the way I did it because there’s only really one good guide online, and its sadly outdated.

I’ve uploaded my binary here, for those who just want wget. Really, you only need to build it you don’t trust me. Everything should be statically compiled, with no dependencies. I’ll be testing it in virtual machine later to be sure.


Quick PHP Note

I’ve been busy hacking the code on somebody’s site.  I just wanna mention the fopen command in PHP.  And how you shouldn’t use it.  It’s frightfully frail, and there’s little to no information on how to make it work.  And sometimes webhosts disable it in the php.ini config, so it doesn’t always work.    Use $data = file_get_contents(“some_random_file.file”) instead to put the contents int a variable.  If you need to make an array from it,$ array = explode (“n”, $data);  instead of fget.  Then call $items_in_array= count($array) – 1; to get the total number of items in the array.  Its a little more wordy, but I think has the same number of lines as the while() loop would require.

Just don’t use fopen.  Please.  Its buggy at best, and possible maybe seemingly unusable in wordpress.  Which is why I had to convert my code from using fopen to file_get_contents.

One more note.  A function’s “present working directory” in wordpress is the directory it’s installed to.  echo getcwd(); as proof 🙂  Which, if I say so myself and I will is stupid.  Total stupid.


The importance of Coding Small

What does “Coding Small” mean?

Simple. It means code small. A small bit of code is easier to debug then a large program.

Take for instance my current Perl coding project. I’m writing a script that will reside on my server and download a comic, and news headlines and then print it out at about 5 in the morning so everybody can have a bit of happiness, and find out what hell has broken loose in the world today.

The comic I want to use is Sheldon. Sometimes, however the creator doesn’t keep strictly to posting the link on his RSS feed. So, I have to make sure that I grab that, or I will get a perl error later on. How you ask?

Until tonight, this comic meant absoloutely nothing to me . . . .

Stand Back!

Yes indeed.

use warnings; use strict;
my @file_contents;

open FILE, "text.txt" or die "$!"; #open with write rights
@file_contents = <FILE>;
close FILE;
foreach my $text (@file_contents){
 chomp $text;
 if ($text =~ m/^Strip for /){
 print $text;
 } else {
 print "No goodness here (Text:$text) n"
 }
}

Pretty much what this snippet does is takes and loads the contents of the file into an array, with each line being an item in the array.  It then stores one value of the array, chomps the newline character off of the end, and check if it starts with “Strip for”, case sensitively via a regular expression.  If the value starts as wanted, then I’m good and it prints that line from the file.  If  the line does not start with “Strip for”, then it prints “No Goodness here” and what the line actually was.

This can then be turned into a subroutine to use with perl.

use warnings; use strict;
my @file_contents;

open FILE, "text.txt" or die "$!"; #open with write rights
@file_contents = <FILE>;
close FILE;

&reg_ex(@file_contents);

sub reg_ex{
 foreach my $text (@file_contents){
 chomp $text;
 if ($text =~ m/^Strip for /){
 print $text;
 } else {
 print "No goodness here (Text:$text) n"
 }
 }
}

Now, no matter how many different types of data I wanna shove at the array, I just call &reg_ex(array of data), and it parse and prints.

Why is this nice?  Let say that I have a more complicated program.  Now that I know that section of code works, I can paste that subroutine in, call when needed, and know that it works and is not affecting other parts of my program.  Then I can work on debugging the rest of my crappy code.

Lemme know what you think in the comments, and hopefully I’ll be posting more of this stuff as I go on . . . .


Email Updates on Server IP Change

Here’s a script I wrote in perl (yes perl) that checks your ip and will email you if the ip changes. Because I’m using private IP’s, I need to check via an external server. What I want to know is if my IP changes, because if it does, I probably need to restart my IRC Bot. Because of the private IP mess, I need to use an external to get my external IP. I use a simple PHP script on my server from Fivebean to tell me the IP.
The PHP is:

<?php
echo $_SERVER['REMOTE_ADDR'];
?>

Stick that somewhere that’s not on your local LAN.
Now, make a batch file with this
perl ip_checker.pl location_of_previous_php_script file_to_write_some_info_to

Coincidentally, I think it would be best if I maybe removed those option and just put them in the configuration section of the perl script . . .

Copy this and save this within the same place as that bat file, using the name ip_checker.pl. Make sure you have Net::SMTP::SSL installed in your perl modules.

use LWP::Simple;
use Net::SMTP::SSL;

use warnings; use strict;
sub text;

#texting information
#configure whether to send alerts.  Email based
################################
######Script configuration######
################################
################################
#####Options Confiugration######
################################
my $send_alert = 'true'; #set true to allow messages to be sent informing you of changes to the local IP
################################
#####Email send information#####
################################

my $email_from = '';
my $email_password = '';
my $send_to= '';
my $email_host ='smtp.gmail.com'; #something link that anyway

################################
##End of Configuration Section##
################################

if (@ARGV ne 2){
    die 'Usage: perl ipchecker.pl (URL To Retrieve External IP From) (File to ReadWrite LastCurrent IP From)n';
}

my $ip_bouncer = shift;
my $read_file_location = shift;
my $current_ip = get($ip_bouncer); die "Couldn't get it!" unless $current_ip;
my $old_ip; my $new_ip;

my $read_file; my $print_file;

open OLD_IP, "$read_file_location" or die "$!"; #open with write rights
$old_ip = <OLD_IP>;
close OLD_IP;
open OLD_IP, ">$read_file_location" or die "$!"; #open with write rights

print "Current IP Address: $current_ip n";
print "Last IP Address: $old_ip n";
print OLD_IP $current_ip;
close OLD_IP;

if ($current_ip ne $old_ip){  #ne is a string comparison of equal or not == is numeric comparison
    #/&text ($host, $from, $password, $message );
    print "Alert!  IP address has changedn";
    if ($send_alert eq 'true'){
    print "Sending Alert!n";
    my $desired_message = "IP Change $current_ip";
    &text ( $send_to, $email_host, $email_from, $email_password, $desired_message);
    print "Alert Sentn";
    }
} else {
    print "All is welln";
    }

sub text { # ($to, $host, $from, $password, $message )
    #mostly from http://robertmaldon.blogspot.com/2006/10/sending-email-through-google-smtp-from.html
    #modified to suit my needs

    my $to = shift;
    my $host = shift;
    my $from = shift;
    my $password = shift;
    my $message = shift;

    my $smtp;
    if (not $smtp = Net::SMTP::SSL->new($host,
                    Port=> 465,
                    Debug => 1,
                  ) ) { die "Couldn't connect" };
    $smtp->auth($from, $password) || die "Authentication failed!n";

    $smtp->mail($from."n" );     # use the sender's address here
    $smtp->to($to."n" );        # recipient's address
    $smtp->data();                      # Start the mail

    # Send the header.
    $smtp->datasend("To: $to n" );
    $smtp->datasend("From: $from n" );
    $smtp->datasend("Subject: Server Alertn");
    $smtp->datasend('Content-Type: text/plain; charset=ISO-8859-1;' . "nn");
    # Send the body.
    $smtp->datasend("Automated Server Message n", $message, "n");
    $smtp->dataend();                   # Finish sending the mail
    $smtp->quit;                        # Close the SMTP connection
}

Schedule every 6 hours or so. I did it with the scheduled jobs thingy in windows server 2003.

Sorry for the poor write up, hit me up in the comments if you need help setting this up or if you have other general questions. Right now, I have to go mess with a wordpress theme in need of fixin . . . .

use warnings; use strict;
sub text;

#texting information
#configure whether to send alerts.  Email based
################################
######Script configuration######
################################
################################
#####Options Confiugration######
################################
my $send_alert = ‘true’; #set true to allow messages to be sent informing you of changes to the local IP
################################
#####Email send information#####
################################

my $email_from = ”;
my $email_password = ”;
my $send_to= ”;
my $email_host =’smtp.gmail.com’; #something link that anyway

################################
##End of Configuration Section##
################################

if (@ARGV ne 2){
die ‘Usage: perl ipchecker.pl (URL To Retrieve External IP From) (File to ReadWrite LastCurrent IP From)n’;
}

my $ip_bouncer = shift;
my $read_file_location = shift;
my $current_ip = get($ip_bouncer); die “Couldn’t get it!” unless $current_ip;
my $old_ip; my $new_ip;

my $read_file; my $print_file;

open OLD_IP, “$read_file_location” or die “$!”; #open with write rights
$old_ip = <OLD_IP>;
close OLD_IP;
open OLD_IP, “>$read_file_location” or die “$!”; #open with write rights

print “Current IP Address: $current_ip n”;
print “Last IP Address: $old_ip n”;
print OLD_IP $current_ip;
close OLD_IP;

if ($current_ip ne $old_ip){  #ne is a string comparison of equal or not == is numeric comparison
#/&text ($host, $from, $password, $message );
print “Alert!  IP address has changedn”;
if ($send_alert eq ‘true’){
print “Sending Alert!n”;
my $desired_message = “IP Change $current_ip”;
&text ( $send_to, $email_host, $email_from, $email_password, $desired_message);
print “Alert Sentn”;
}
} else {
print “All is welln”;
}

sub text { # ($to, $host, $from, $password, $message )
#mostly from http://robertmaldon.blogspot.com/2006/10/sending-email-through-google-smtp-from.html
#modified to suit my needs

my $to = shift;
my $host = shift;
my $from = shift;
my $password = shift;
my $message = shift;

my $smtp;
if (not $smtp = Net::SMTP::SSL->new($host,
Port=> 465,
Debug => 1,
) ) { die “Couldn’t connect” };
$smtp->auth($from, $password) || die “Authentication failed!n”;

$smtp->mail($from.”n” );     # use the sender’s address here
$smtp->to($to.”n” );        # recipient’s address
$smtp->data();                      # Start the mail

# Send the header.
$smtp->datasend(“To: $to n” );
$smtp->datasend(“From: $from n” );
$smtp->datasend(“Subject: Server Alertn”);
$smtp->datasend(‘Content-Type: text/plain; charset=ISO-8859-1;’ . “nn”);
# Send the body.
$smtp->datasend(“Automated Server Message n”, $message, “n”);
$smtp->dataend();                   # Finish sending the mail
$smtp->quit;                        # Close the SMTP connection


Twitter Feed on HomePage Code

On my homepage, you may notice that I have a bit of code to get my latest tweet for this website’s twitter account. Usually this is blog updates, but it may show other things.

I originally found this code on http://www.phoenixheart.net/2009/05/code-snippet-1-get-latest-tweet/. Since twitter has been having issues lately, I realized a need for a fall back value if the code couldn’t get anything. I also removed a variable declaration and then copied the returned value from the function to another variable, to hopefully optimize the code and make it work better and faster.

<?php

 // the function
 /**
 * @desc Get latest tweet from a Twitter account
 * @param string The account's username
 * @return string The tweet
 * http://www.phoenixheart.net/2009/05/code-snippet-1-get-latest-tweet/
 *
 */
 function get_latest_tweet($username) {
 $url = "http://search.twitter.com/search.atom?q=from:$username&rpp=1";
 $content = file_get_contents($url);
 $content = explode('<content type="html">', $content);
 $content = explode('</content>', $content[1]);
 return html_entity_decode($content[0]);
 }
 $my_tweet = get_latest_tweet('TWITTERLOGIN');
 if ($my_tweet == NULL)
 {
echo "Twitter is having issues again . . . .";
 }
 else {
 echo "$my_tweet";
 }

 ?>

Just paste this in a php file and change your twitter name so it gets the right feeds!


SSH Window Forwarding

Recently, I put out a call on freecycle for an old computer (I’d like a laptop to, as well, but . . .) and I got one Sunday. Why did I do this?

SSH Window Forwarding finally got the better of me. What is window forwarding? Well, its a simple enough concept, if you know what you are doing. The concept is that you enable X11 Forwarding and then whenever you open an application with an window interface, like Xterm or Geany, it is opened on your local computer.

This means that if have a remote server with X11 Forwarding and you open Firefox on the commandline, you will be browsing with firefox window forwarded from that computer! You can set this up, then check it out be visting perhaps ipchicken. It will show the ip of the remote computer.

Enough concept, let’s get our fingers dirty!

The first thing you need is a computer. You could also use a Virtual Machine in VBox to do this, but I don’t really have any computers powerful enough to run virtual machines. That was why I requested a old computer. Boy, was it old. Its a HP XE743. Designed for Windows 98. Computer stats: 600 mhz Intel Celeron, and 64 megs of RAM. I was really, really lucky and had a extra stick of RAM that fit the computer (no reason). Now I have 128 megs of RAM.

I mention this for two reasons: 1)to show the power of linux. This is a computer that should be in the graveyard by window’s standards, and yet it is alive and very well by running a slightly outdated copy of Ubuntu Server. 2) Windows forwarding doesn’t take that much power. Running it over my local LAN, my experiences are that even with the low power, it still acts pretty snappily.

The second thing is Linux. I’m sure that there are ways to do this with windows, but linux works. Its also free. My choice was Ubuntu Server 8.10. Yes, I need to update but this was the disc I had handy. I wasn’t expecting to have to do a whole lot with it, though that might change.

Install Ubuntu Server on the machine. Something you really need to be aware of with this machine is that you need to change a few settings in the BIOS. First of all, turn off the quick boot and such. Make it do the full tests to insure everything is correct. Then set the disk access to other, so it knows its using linux. Otherwise, it will act like a turd and not boot at all. Install everything, and when it asks for services, install the sshd. If you forget it, you can install it later. I would recommend using a static ip for all servers. It can be a pain when your server’s ip address changes constantly and you have to find it in the DHCP loan list.

Now, you need to install Xorg. I remember install Xorg, then installing a window manager. It should be sufficient to run something like sudo apt-get install fluxbox. That should pull all dependencies, including xorg for fluxbox. Fluxbox isn’t the best, but it gets the job done, which is what I am concerned about. It also isn’t a resource hog. On this machine, there isn’t a whole lot to hog!

You’ll need to configure Xorg. Run xorg -configure, then copy the config file to the proper location: sudo mv /etc/X11/xorg.conf /etc/X11/xorg.conf.old
cp /home/user/xorg.conf.new /etc/X11/xorg.conf

Edit the sshd conf file to allow window forwarding, and the ssh to try to do window forwarding. These should be in /etc/ssh/sshd_config and /etc/ssh/ssh_config respectively. Run startx and again, then pull up xterm and do ssh localhost. This will ssh to yourself. Run Xterm on the commandline, and you should have a new xterm window popup. You may need to install Xterm first, however. Close out the ssh windows.

Now, head over to your windows machine (cause this is where it gets really cool). Install Xming and start it up. Then start putty. I’m also starting to use Kitty now, which is a port of putty with more features, with some really nice features that make me like it more then putty.

For putty, enter the ip address of the server (I chose 192.168.1.5, and yes that’s a local ip). Go to Connection, then SSH, then X11. Check the box to enable forwarding. Then click connect. Enter login and password. Then, type xterm. If you’ve done everything right on the windows side, Xterm will run and you will have a graphical shell.

*UPDATE*

I installed Ubuntu 10.4, which seems to be a bit friendlier on the resources side of things.  Anyway, I didn’t install or configure xorg.  I simply did <code>sudo apt-get install xterm</code>.  After running Xming on my windows machine and connection, everything ran fine.  So, you’ll need the dependencies (one of which I believe was X11 common) but you don’t have to setup Xorg if you don’t want to.


Random Quotes on Page

I’ve converted my homepage to php. This has the benefit of maintaining standard HTML interaction, while allowing me to script certain things into my page. I wrote this because I hate java and java script with a passion. I blame it on my college’s use of blackboard. Its enough to make any one think twice.

(more…)


Geany Portable, Nightly Edition

So, around January, I started playing with batch scripting (I’m terrible at it still).  Anyway, I had installed MingW so that I could compile geany nightlies from source on my server.  The ones hosted at geany.org are cross compiled, unlike mine.

Anyway, I created a script that would download the svn posted on the server, extract it, compile, and then copy it into a folder and then compress it so I would have a portable version of the geany nightly, natively compiled.

The trick was to get it up to a server.  Windows (my server is Windows Server 2003), has a built-in ftp client, that can be called from the command line.  It can even be scripted.  The problem is that it didn’t work for my.  So I was stuck trying to get it to the outside world until I figured out how to ftp it to another site.

The answer is WinSCP.  WinSCP allows scripting, in a variety of forms.  I had stumbled across this at some point, it wasn’t until I created a backup script for my mother’s computer (more to come on that one) that I rehashed the script I had been using to add upload abilities.

The script itself is far from complete but I thought that by posting this, I might help someone else in a similar situation.  I’ve tried to comment it pretty well, since it sucks when someone posts something and there is no comments.

REM This script requires you to have wget either in the script folder or in your %PATH%
REM It also requires a copy of the 7Zip command line tools
REM You also need the winscp binaries

cd ........
REM Change directory to root of drive
cd nightly
REM change to nightly folder
wget http://files.uvena.de/geany/geany_svn.tar.gz
REM download the nightly tar ball generated by Geany Project from server
7za e geany_svn.tar.gz
7za x geany_svn.tar
REM extract geany via 7zip command line
MakeBuilder.exe
REM this is a custom program that changes a single line within the geany make file so that it is compatible with a stock mingw install
cd geany_svn
mingw32-make -f makefile.win32
REM go the the geany svn folder and build the binary
cd ..
REM get out of the geany_svn folder
erase C:nightlyGeanyPortableAppGeanybingeany.exe
erase geany_svn.tar
erase geany_svn.tar.gz
REM clear out unneeded stuff
copy geany_svngeany.exe C:nightlyGeanyPortableAppGeanybin
REM copy the binary over to the bin folder in Geany Portable
rmdir /s /q C:nightlyGeanyPortableDatasettings
REM delete the datasettings folder so that any of my settings are not copied to you
7za a -sfx7z.sfx GeanyPortable%date:~4,2%-%date:~-7,2%-%date:~-4,4%.exe GeanyPortable
REM create a self extracting 7-zip package with a month-data-year ending name
winscp /console /command "option batch on" "open login:password@host" "put GeanyPortable%date:~4,2%-%date:~-7,2%-%date:~-4,4%.exe /downloads/Geany/nightlies/" "exit" "close"
REM upload the file to the intellilaunch server via winscp binary
erase GeanyPortable%date:~4,2%-%date:~-7,2%-%date:~-4,4%.exe
REM erase the file from the "local" location
rmdir /s /q geany_svn
REM delete the geany_svn folder so that the directory can be extracted without needing to overwrite anything

If you are wondering where to get those Geany nightlies I mentioned, they are right over here.