Archive for Uncategorized

xml on php 5.1.x and obsolete google code fix

Some of the google php example code does not work in php 5 dot something.

And also you might find this map stuff certainly wont work properly in the versions of Firefox that exist at the time of this post. Something to do with ajax I believe. This code fixes that.

Over the years, lots of people hunting down fatal errors like:

undefined function: domxml_open_mem() or

Call to undefined function domxml_new_doc()

and its evident they are trying to make work the same sample code that I have. (The correct code is now on the google site btw)
The problem might be that they are using the wrong version of code with the release of PHP they have installed. The internet has been sending people down the wrong tracks trying to solve the problem.
It is also apparent that 5.x of PHP has, by default, the modules available for handling php.
Some basic checks first before moving onto the code:

To get it working in Centos you need to have  libxml2.x86_64 0:2.6.26-2.1.2.6 libxml2.i386 0:2.6.26-2.1.2.6

which means yum install libxml2

You should check the modules dir, e.g. /usr/lib64/php/modules/ for the presence of dom.so

Look at your php.ini (usually in /etc)

extension=dom.so

may not be necessary, errors like

PHP Warning: Module ‘mysql’ already loaded in Unknown on line 0 that appear when trying to run code from the command line may occur because in /etc/php.d/mysql.ini the module is already declared and subsequently loaded, therefore you can edit out the extentions = section of your /etc/php.ini

I’ve butchered the code of Google to suit my own application and table def. The critical lines changed are

$doc = new DOMDocument(‘1.0′);    (was create_document)
$node = $doc->createElement ….    (was create_element)
$doc->appendChild($node) …          (was append_child)
$newnode->setAttribute(“…             (was set_attribute)
$xmlfile = $doc->saveXML($markers_node);           (was dump_mem)

<?php

require(“./phpsqlajax_dbinfo.php”);

// Start XML file, create parent node

$doc = new DOMDocument(‘1.0′);

$markers_node = $doc->createElement(“markers”);$parnode = $doc->appendChild($node);
//markers_node is a node we’ll need as part of the FF fix. Basically somehow an extra line gets inserted which contains whitespace which leads to the error, Error: XML or text declaration not at start of entity. It will still work in IE though.

// Opens a connection to a mySQL server

$connection=mysql_connect ($mysql_host, $mysql_login, $mysql_pass);

if (!$connection) {

die(‘Not connected : ‘ . mysql_error());

}
// Set the active mySQL database

$db_selected = mysql_select_db($mysql_db, $connection);

if (!$db_selected) {

die (‘Can\’t use db : ‘ . mysql_error());

}
// Select all the rows in the markers table

$query = “SELECT * FROM ch_points WHERE 1″;

$result = mysql_query($query);

if (!$result) {

die(‘Invalid query: ‘ . mysql_error());

}
header(“Content-type: text/xml”);
// Iterate through the rows, adding XML nodes for each

while ($row = @mysql_fetch_assoc($result)){

// ADD TO XML DOCUMENT NODE

$node = $doc->createElement(“marker”);

$newnode = $parnode->appendChild($node);
$newnode->setAttribute(“name”, $row['owner']);

$newnode->setAttribute(“address”, $row['postcode']);

$newnode->setAttribute(“lat”, $row['lat']);

$newnode->setAttribute(“lng”, $row['lon']);

$newnode->setAttribute(“type”, $row['phases']);

}
$xmlfile = $doc->saveXML($markers_node);
//This is the other part of the firefox fix. Just pump out the nodes we need via markers_node.
echo $xmlfile;
?>

Leave a Comment

Warning to customers of BitDefender

Once BitDefender has your card details you’re screwed.

Another faceless company that treats you like dirt once they have your payment.

Not all software is bad. In 2007 I discovered fabulous packages like OpenLaszlo and Blender – so good they are beyond words. But at the other end of the spectrum, little is more is appauling than BitDefender.

I chose the product to protect my PC from viruses etc. based on poll results which, if my experience is anything to go by, these results are completely bogus and probably rigged. 

I bought BitDefender for 4 machines. One machine is on 24/7 as it forms part of a security system.
It became unstable and ran out of memory – despite increasing the swapfile to its limits, it had to be rebooted weekly.

The removal of BitDefender has since resulted in complete stability and it only requires boots after mandatory OS patches.

2 other machines became increasinly sluggish and unuseable. BitDefender services started crashing and refused to start, warning me my machine was not protected. Not the sort of thing I wanted to read.

After a catalogue of problems, I canned BitDefender and tried McAfee and AVG – these were found be far more suitable – the removal of BitDefender offered a noticeable performance increase on these machines.

BitDefender have ignored what is now 4 communications in cancelling auto-renewals. This is something that should be possible to be done through their web interface but unfortunately, they have constructed it in such a way that you can’t cancel (at least I can’t find a way to and have screen-shotted their web interface.)

Taking that on board with the fact that they ignore web and standard emails to them, you are left with facing the problem of cancelling your credit card. If they wont communicate then there is no other option: either take the renewal or cancel the card or force the card company to get involved (the least painful).

Frankly this is an awful company with zero PR cabability and an inadequate technical support department that does not seem to be able to read basic English.

Leave a Comment

load words into mysql table using infile

mysql> load data infile ‘/mnt/everyone/wordlist.txt’ into table words fields terminated by ‘\r’;

where the table is called words and has a field called word

Leave a Comment

Convert postcode to longitude and latitude

Usage:

./postcodetolonglat.sh 'SK99 9LZ'

Creates a little temp file called ‘postcode’. The file is put in /tmp and is of course unique for each execution of the program.  These files can be cleared out quite easily as part of maintenance of the /tmp folder. (i.e. a weekly cron that executes

find /tmp -mtime +1 -user apache -exec rm {} \;

where the file will be at least a day old and is owned by apache which (in my case) is the apache user for the apache web server.

Script:

#!/bin/bash
. `/usr/bin/wget "http://maps.google.com/maps/geo?q=$1" -O "/tmp/$1"`
LAT=`cat "/tmp/$1" | awk -F "[" '{print $4}' | awk -F "," '{print $2}'`
LON=`cat "/tmp/$1" | awk -F "[" '{print $4}' | awk -F "," '{print $1}'`
echo "<script language=JavaScript>"
echo "   var Lon=$LON;"
echo "   var Lat=$LAT;"
echo "   var orig='$1';"
echo "</script>"

Then in, say, google maps:

From your browser, call (for example for the Warminster postcode of the R.E.M.E - BA12 0BS)

http://server.com/map4.php?pc=BA12%200BS

The code for map4.php is below.

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <?php
$Postcode= $_GET['pc'];
echo passthru("./postcodetolonglat.sh '$Postcode'");
?>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA2OgjrxQMCCnZOIKNKqdqqxQQ2LfZc7AlgWy0LicD3n_XCYU-EBSRAF96CM-HbX18JJscTSEShXpbfg"
            type="text/javascript"></script>
    <script type="text/javascript">
    function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        var gll = new GLatLng(Lat,Lon);
        map.setCenter(gll,17);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        GEvent.addListener(map,"click", function(overlay,latlng) {
          if (latlng) {
            var myHtml = "The GLatLng value is: " + map.fromLatLngToDivPixel(latlng) + " at zoom level " + map.getZoom();
            //map.openInfoWindow(latlng, myHtml);
                alert(gll.toUrlValue(10));
          }
        });

      }
    }
    </script>
  </head>

  <body onload="initialize()" onunload="GUnload()">
    <div id="map_canvas" style="width: 100%; height: 100%"></div>
    <div id="message"></div>
  </body>
</html>

Leave a Comment

mysql 5 trigger upgrade

Mysql triggers are not the best in the world and it seems you can’t call something external from the db – like, for example, running a script.

Well, I needed to know if an update had occurred on a table and to fire off a remote command to another server.

The solution was:

1. Add a field to the table called action – default it to NULL
2. Perl script to check the table for rows which contained default=NULL
3. If such a row existed then do some file system action
4. Update the table so that action is no longer null
5. Make the whole thing reliable

Step 1. Create a shell script

check_relay.sh
#!/bin/bash
echo “running application”;
while [ 1 ]; do
echo “running”
perl /home/user/relay2.pl
sleep 3
done

2. create a perl script to query the db table we spoke off earlier (relay2.pl – in my app)

my $database = ‘relay’;
my $host = ‘localhost’;
my $user = ‘relay_user’;
my $pass = ‘relay_pass’;
my $dbh = DBI->connect(“DBI:mysql:database=$database;host=$host”,”$user”,”$pass”) or die “Can’t open DB: $!”;
my $sth = $dbh->prepare(q{SELECT tr_id, actioned FROM relay where actioned is null});
$sth->execute() or die $dbh->errstr;
my $actioned;
my $tr_id; # should use a transaction id so you know which row was updated in case there is more than one.
$sth->bind_columns(\$actioned,\$tr_id);

while($sth->fetch()) {
#here we do stuff on the os, e.g. system(“php ./relay2.php $field_from_db_etc”);
#now update the db so the row no longer requires a trigged type event
my $newQ2 = “UPDATE transactions SET actioned =true WHERE tr_id=$tr_id”;
my $sth3 = $dbh->prepare($newQ2);
$sth3->execute() or die $dbh->errstr;
$sth3->finish;
}
$sth2->finish;
}
$sth->finish;
$dbh->disconnect;

3. create a perl script to check the process is actually running (which it wont be unless you ran it by hand)

#!/usr/bin/perl
open PROS, “ps -ef|grep check_relay.sh |”;
while ($line = <PROS>){
unless ($line =~ m/grep/){
#print “is already running\n”;
exit;
}
}
print “check_relay was not running. Trying to start it.\n”;
exec ‘nohup /home/user/./check_relay.sh &’;
4. Make sure the damn thing boots up about 60 seconds after the system starts and check it is still running every 60 seconds.

Edit cron for the user under which this script will run -

(crontab -e)

* * * * * /home/user/ps_check.pl

If you have done everything right then kill the process and see that it launches again within 60 secs which is the resolution of cron.

Obviously make sure mysql is configured to autostart at the correct run levels if the machine is booted up.

(if I remember correctly on centos, chkconfig mysqld on –level 35)

Comments (1)

ImageMagick Annotate/Watermark/Add text to graphic image

Where logo_01.jpg is the source image.
The output image is out.jpg
The text put on is 12345
The font was installed on the system by default and standard TTF which can be found with a basic search FS.

convert logo_01.jpg -fill ‘#0008′ -draw ‘rectangle 5,128,114,145′ -font /usr/share/fonts/bitstream-vera/Vera.ttf  -fill white   -annotate +10+141 ‘12345′ out.jpg

Leave a Comment

Nicest email ever received

Hi K######,

It is not often that we get a chance to stop, and give recognition to an individual who has been a great team player, an expert in the field, and an awesome individual to work with, who for the past 3-4 weeks has assisted the US ### team to successfully deliver a solution on the RFS# ######-## for the XXXXXXXX customer. This RFS was recently signed.

I am taking that opportunity to do so now with regards to Kevin Yeandel, who has been working with the team in terms of educating us on the nuances of Documentum, and how it should be architected to be backed up and recovered. Additionally, Kevin identified “risk” and also “risk mitigation” strategies.

We still a bit of closure to do with the customer, due to no fault of our own, however to date, and given the 5-6 hr time difference, I am very pleased with Kevin, in that with very brief notice, Kevin has been able to make all calls, take charge on the calls and educate the XXXXXXXX customer, and team ### as to how to do it and do it the correct way. I look forward to working with Kevin on future assignments.

I also tried to follow up with a “Thanks award”, and received this response “Either the CNUM or the e-mail address you have entered is incorrect or the person whose e-mail address you have entered is not eligible to participate in the Thanks! Award Program at this time.

Thanks,
Dxxxxxx

Leave a Comment

mysql autostart runlevel

chkconfig –level 3 mysqld on

chkconfig –list mysqld

service mysqld status

Leave a Comment

How to waste 5 hours of your life….. ZTE MF622 and stuff

Personal Web Server

I Googled all over the web for an answer to why oh why oh why can’t I see my webserver behind my router.

I port forwarded the web server in the router, nothing special there.
I checked iptables, turned the firewall off completely (madness, you’ll see why).
I changed the port on Apache to various others, taking care to restart.
I rebooted the server and rebooted the router. No joy.

Midnight to 3am – 3 hours. It was already working, the problem was that I could not reach my server by going out and back in via the router. In other words (warning to others who down firewalls as part of testing) just because I couldn’t see it doesn’t mean others can’t! Silly old me.
Once I tried to access my machine from a wireless network from the WAN and not my LAN it became obvious.

Three – Mobile Broadband – warning to Windows and Esp. MAC users

Firstly in order to get up and running, you need a CD – IF you are a MAC user. My sealed box had no CD. After 20 minutes of hunting down drivers from the website of three.co.uk, I downloaded them thanks to a fellow blogger who also had obviously had problems finding them.

Part of the installation involves a password which is sent to you by SMS. i.e. an SMS to your modem! Fine if you are using Windows… NOT so fine on the Mac as Three forgot to finish the software. The SMS Text appears in your inbox – not on the Mac as there is no inbox.  Options are to: take the sim and install it into a three enabled phone and get the password this way. Or take the phone to the shop and install the sim in one of their phones (no, really, I was told this). Last option is to plug the modem into a Windows box where the software magically appears from some sort of internal storage device and you should be good to go. I tried it on a Windows XP on VMWare from my Mac and it did not work so I plugged it into a laptop with XP and it was fine – I could retrieve the password and put it in as required.

No contracts, No Wires, No Worries

Actually BIG problem here…

It says, read this before you do anything… little green CD size brochure. So if you get in a muddle with getting it working on your Mac with it not having the Inbox and that, do not forget under any circumstances to go to their website and using the addon page, convert your credit into  broadband or face getting charged £1 per MB. Do this BEFORE using any credit from vouchers.
The people at Three are very nice, as are the people at Phones4U. Not only this but the system works really well, it did cost me 2 hours to get it all sorted. It would be nice if Hutchingson Telecom FINISHED the software before releasing it.

Comments (1)

SMS via Skype when server is down (fails ping)

Requires registration of downloadable ActiveX comp from Skype web site on Windows machine.
Register with:
regsvr32 Skype4COM.dll
Make sure Skype is installed and logged in. When you run the prog the first time you are asked a
security question. You will need credit on your Skype account and it must be useable
through the network (if doing this from within a company and behind a firewall).
Copy the code from Option Explicit to bottom into a file called isalive.ebs

usage:cscript isalive.ebs <server> <phone> <interval> <mail recipient>
Returns: Writes to console. Sends a text if server goes off line. Sends an email also
with contents of a log file.
Requires a batch file containing words to the affect:
tracert -d %1 >> c:\diags.txt
echo "Further Info:
ping server1.fdqn >>c:\diags.txt
ping server2.fqdn >>c:\diags.txt
.
Batch file must be in same dir as the vbs.
Sends a text when it comes back on-line. Code below:

Option Explicit
'skype me a text or voicemail when my server disappears off the network.
'runs on a windows platform (whatever)
'useage:
'cscript isalive.vbs 192.168.1.109 004412345678 3000 xxxxxxxxxxxx@gmail.com
'where 192.168.1.109 is the server to ping
'and 004412345678 is the number to send a message to

Dim strHost
Dim strPhoneUser
Dim fault_detected
Dim strMessage
Dim strRecipient
Dim sleeptime
Dim oSkype
Set oSkype = WScript.CreateObject("Skype4COM.Skype", "Skype_")
If Not oSkype.Client.IsRunning Then oSkype.Client.Start() End If
' Check that all arguments required have been passed.
If Wscript.Arguments.Count < 2 Then
    Wscript.Echo "Arguments required" & vbCrLf
     Wscript.Quit(0)
End If
strHost = Wscript.Arguments(0)
strPhoneUser=Wscript.Arguments(1)
sleeptime=3000
If (Wscript.Arguments.Count > 2) Then
	sleeptime = Wscript.Arguments(2)
End If
strRecipient = ""
If (Wscript.Arguments.Count >3 ) Then
	strRecipient = Wscript.Arguments(3)
End If

Wscript.Echo "Host " & strHost
Wscript.Echo "Phone " & strPhoneUser
Wscript.Echo "Recipient " & strRecipient
Wscript.Echo "sleep " & sleeptime

fault_detected = 0
do
if Ping(strHost) = True then
    Wscript.Echo "Host " & strHost & " contacted"
	if (fault_detected > 0) Then
		strMessage= "Server " & strHost & " back on network after " & ((fault_detected * sleeptime)/1000) & " seconds"
		call_contact

		fault_detected = 0
	End If
Else
    Wscript.Echo "Host " & strHost & " could not be contacted"
	fault_detected = fault_detected + 1
	If (fault_detected = 1) Then
		strMessage= "Server " & strHost & " missing from network"
		Wscript.Echo "Contacting user on tel. no." & strPhoneUser
		call_contact
		do_diagnostics ' do further research then mail someone with the information
		mailuser
	End If
end if
WScript.sleep (3000)
loop until (1=0)

Function call_contact
Dim oSMS
	Wscript.Echo "SMS : " & strMessage
         Set oSkype = WScript.CreateObject("Skype4COM.Skype", "Skype_")
        Set oSMS = oSkype.SendSms(strPhoneUser, strMessage)
         WScript.Sleep(20000)
End Function

 'Message event handler:
 Public Sub Skype_SmsMessageStatusChanged(ByRef aSms, ByVal aStatus)
   WScript.Echo  ">Sms " & aSms.Id & " status " & aStatus & " " & oSkype.Convert.SmsMessageStatusToText(aStatus)
 End Sub

 'Target event handler:
 Public Sub Skype_SmsTargetStatusChanged(ByRef aTarget, ByVal aStatus)
   WScript.Echo  ">Sms " & aTarget.Message.Id & " target " & aTarget.Number & " status " & aStatus & " " & oSkype.Convert.SmsTargetStatusToText(aStatus)
 End Sub

Function Ping(strHost)
    dim objPing, objRetStatus
    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
    Ping = False
        else
            Ping = True
         end if
    next
End Function

Function mailuser
Wscript.Echo "Mailing user"
Dim cdoConfig
Dim sch
Dim objMessage
Set cdoConfig = CreateObject("CDO.Configuration")
 sch = "http://schemas.microsoft.com/cdo/configuration/"
    With cdoConfig.Fields
        .Item(sch & "sendusing") = 2 ' cdoSendUsingPort
        .Item(sch & "smtpserver") = "aserver.net"
        .update
    End With 

Set objMessage = CreateObject("CDO.Message")
Set objMessage.Configuration = cdoConfig
objMessage.Subject = "Server Status for: " + StrHost
objMessage.From = "xxxx@xxxx.com"
objMessage.To = strRecipient
objMessage.TextBody = "The Server vanished from the network. Please see the attached file."
 objMessage.AddAttachment "c:\diags.txt"
objMessage.Send
set cdoConfig = nothing
set objMessage = nothing
set sch = nothing
End Function

Function do_diagnostics ' creates an attachment that will be emailed. diags.bat runs a tracert on the server and pings a few
Wscript.Echo "Running further diags"
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "diags.bat " + strHost '
'WshShell.Run "command.com /k " & CommandLine 'run DOS commands
WScript.Sleep(20000)
Set WshShell= nothing
End Function

Comments (1)

« Newer Posts · Older Posts »