#!/usr/bin/perl use DBI; use Getopt::Long; # Database info my $db_name = "tasks"; my $db_user = "DB_USER"; my $db_pass = "DB_PASSWORD"; GetOptions( \%arg => 'type=s','notes=s','title=s','parent=s', 'url=s','debug','h'); &getArgs; &doInsert; sub getArgs{ if ($arg{'debug'}){ $debug = 1; print "Running in DEBUG mode\n\n"; } print "entering getArgs\n" if $debug; if ($arg{'h'}) { &showUsage; } #type = 0 (task) or type = 1 (note) types '0' and '1' are used in the mysql db 'type' field if ($arg{'type'} && $arg{'type'} ne 'task' && $arg{'type'} ne 'note'){ print "ERROR: Only 'task' and 'note' are allowed for the 'type=' option\n"; $err=1} elsif ( $arg{'type'} && $arg{'type'} eq "task") { $type = 0; } elsif ( $arg{'type'} && $arg{'type'} eq "note") { $type = 1; } else { $type = 0; } if (!$arg{'title'} || $arg{'title'} =~ /^\s+$/) {print "ERROR: '-title' is a required option, and it must contain more than whitespace\n"; $err=1;} else { $task_title = $arg{'title'}; $task_title =~ s/\'/\\'/g;} if ($arg{'parent'} && ($arg{'parent'} !~ /^\d+$/ || $arg{'parent'} < 0) ) { print "ERROR: '-parent' must be 0 or higher\n"; $err=1; } elsif ($arg{'parent'}) { $parent = $arg{'parent'}; } else { $parent = 0; } if($arg{'notes'}) { $notes = $arg{'notes'}; $notes =~ s/\'/\\'/g;} else { $notes = ""; } if($arg{'url'}) { $url = $arg{'url'}; if ($url !~ /^http:\/\/[^\/]/ && $url !~ /^https:\/\/[^\/]/ && $url !~ /^ftp:\/\/[^\/]/) { print "ERROR: \"-url\" must start with [http|https|ftp]://\n"; exit; } $url_size = length($url); } else { $url = ""; } #if there were any errors at all, show the proper usage format if ($err){ &showUsage; } print "leaving getArgs\n\n" if $debug; } #END getArgs sub showUsage{ print "\n\n Usage: newtask -title [-type=task|note] [-notes ] [-parent #] [-url ] [-debug] [-h]\n"; print "\t the only required field is \"-title\"\n"; print "\t \"-type\" has a default value of \'task\', so you dont need to explicitly set it to \'task\'\n"; print "\t NOTE: You do NOT need to escape single quotes used in \"-title\" or \"-notes\"\n"; print "\n\n\n"; exit; } sub doInsert{ print "entering doInsert\n" if $debug; chop($date = `date +"%Y%m%d%H%M%S"`); #format: YYYYmmddHHMMSS example: 20040428165010 (4/28/2004 16:50:10) # Connect to the database my $dbh = DBI->connect("dbi:mysql:$db_name","$db_user","$db_pass") || die "Could not connect to database because: $DBI::errstr" ; $sql = "INSERT INTO tasks (title,parent,type,notes,URLs,date_entered) VALUES('$task_title','$parent','$type','$notes','a:1:{i:0;s:$url_size:\"$url\";}','$date')"; print " Using this SQL: >$sql<\n" if $debug; #dont do an actual INSERT if we are in debug mode if (!$debug) { $dbh->do($sql) or die "Can't execute statement $sql because: $DBI::errstr"; } $dbh->disconnect; print "leaving doInsert\n\n" if $debug; }#END doInsert