[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Creating database and users in 1.3



Hi all,

I am new to LedgerSMB and, after reading some of the discussion here,
decided I would start by looking at 1.3 (from svn), even though it is
not released yet.

Being unfinished, it's not surprising some of the admin functions don't
work yet. Here are some patches that have allowed me to create databases
and users. These aren't well tested, but I would welcome any comments or
suggestions.

Regards,
Ian
>From 067616da6a94d09bc312dcfceee985d1f32bfb33 Mon Sep 17 00:00:00 2001
From: Ian Goodacre <ian@laptop2.(none)>
Date: Tue, 26 Jan 2010 05:36:05 +1300
Subject: [PATCH 1/8] Add .gitignore

Ignore vim swap files, files produced by Module::Build, Module::Install
or ExtUtils::MakeMaker (some of them at least) and ledgersmb.conf.
---
 .gitignore |   12 ++++++++++++
 1 files changed, 12 insertions(+), 0 deletions(-)
 create mode 100644 .gitignore

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..57614af
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,12 @@
+# .gitignore for LedgerSMB
+#
+# Vim swap files
+*.swp
+#
+# Perl Module::Build, Module::Install, ExtUtils::MakeMaker
+META.yml
+Makefile
+inc/
+#
+# LedgerSMB runtime files
+ledgersmb.conf
-- 
1.6.3.3

>From 424dc2e88ed5d9983f80fda504a33d6ec4942907 Mon Sep 17 00:00:00 2001
From: Ian Goodacre <ian@laptop2.(none)>
Date: Sat, 30 Jan 2010 19:31:41 +1300
Subject: [PATCH 2/8] Add Log::Log4perl based logging

Log::Log4perl provides more flexible logging than LedgerSMB::Log. It has
been added without changing any of the existing methods of
LedgerSMB::Log, so no changes to other modules are required.
---
 LedgerSMB/Log.pm       |    6 ++++++
 LedgerSMB/Sysconfig.pm |    7 +++++++
 2 files changed, 13 insertions(+), 0 deletions(-)

diff --git a/LedgerSMB/Log.pm b/LedgerSMB/Log.pm
index d102705..359ac32 100644
--- a/LedgerSMB/Log.pm
+++ b/LedgerSMB/Log.pm
@@ -52,6 +52,12 @@ use IO::File;
 use Data::Dumper;
 use LedgerSMB::Sysconfig;
 use Carp ();
+use Log::Log4perl;
+
+Log::Log4perl::init(\$LedgerSMB::Sysconfig::log4perl_config);
+
+my $logger = Log::Log4perl->get_logger('');
+$logger->debug('LedgerSMB::Log Log4perl config: ', $LedgerSMB::Sysconfig::log4perl_config);
 
 our $VERSION = '1.0.0';
 
diff --git a/LedgerSMB/Sysconfig.pm b/LedgerSMB/Sysconfig.pm
index 0ae383a..39550e0 100644
--- a/LedgerSMB/Sysconfig.pm
+++ b/LedgerSMB/Sysconfig.pm
@@ -85,6 +85,13 @@ $no_db_str = 'database';
 # available printers
 %printer;
 
+# Log4perl configuration
+$log4perl_config = q(
+    log4perl.rootlogger = DEBUG, Screen
+    log4perl.appender.Screen = Log::Log4perl::Appender::Screen
+    log4perl.appender.Screen.layout = SimpleLayout
+);
+
 my %config;
 read_config( 'ledgersmb.conf' => %config ) or die;
 
-- 
1.6.3.3

>From f9c9a7d53f9047b422be350c51644d64b73dee26 Mon Sep 17 00:00:00 2001
From: Ian Goodacre <ian@laptop2.(none)>
Date: Sat, 30 Jan 2010 19:34:24 +1300
Subject: [PATCH 3/8] Add debug logging

Lots of Log::Log4perl based logging to facilitate fixing initiate and
admin functions.
---
 LedgerSMB.pm          |   23 +++++++++++++++++++----
 LedgerSMB/DBObject.pm |    7 ++++++-
 LedgerSMB/Initiate.pm |   17 +++++++++++++++--
 bin/initiate.pl       |    8 +++++++-
 initiate.pl           |   12 ++++++++++++
 lsmb-request.pl       |   14 ++++++++++++++
 scripts/admin.pl      |    4 ++++
 7 files changed, 77 insertions(+), 8 deletions(-)

diff --git a/LedgerSMB.pm b/LedgerSMB.pm
index 2824a93..0beb6ff 100755
--- a/LedgerSMB.pm
+++ b/LedgerSMB.pm
@@ -142,6 +142,7 @@ use LedgerSMB::Template;
 use LedgerSMB::Locale;
 use LedgerSMB::User;
 use LedgerSMB::Setting;
+use LedgerSMB::Log;
 use strict;
 
 $CGI::Simple::POST_MAX = -1;
@@ -149,18 +150,23 @@ $CGI::Simple::POST_MAX = -1;
 package LedgerSMB;
 our $VERSION = '1.2.99';
 
+my $logger = Log::Log4perl->get_logger('LedgerSMB');
+
 sub new {
     my $type   = shift @_;
     my $argstr = shift @_;
     my %cookie;
     my $self = {};
 
+    $logger->debug("Begin LedgerSMB.pm");
 
     $self->{version} = $VERSION;
     $self->{dbversion} = "1.2.0";
     bless $self, $type;
+    $logger->debug("LedgerSMB::new: \$argstr = $argstr");
     my $query = ($argstr) ? new CGI::Simple($argstr) : new CGI::Simple;
     my $params = $query->Vars;
+    $logger->debug("LedgerSMB::new: params = ", Data::Dumper::Dumper($params));
     $self->{VERSION} = $VERSION;
     $self->{_request} = $query;
 
@@ -209,6 +215,8 @@ sub new {
     if (!$self->{script}) {
         $self->{script} = 'login.pl';
     }
+    $logger->debug("LedgerSMB.pm: \$self->{script} = $self->{script}");
+    $logger->debug("LedgerSMB.pm: \$self->{action} = $self->{action}");
 #    if ($self->{action} eq 'migrate_user'){
 #        return $self;
 #    }
@@ -222,6 +230,7 @@ sub new {
          $ccookie =~ s/.*:([^:]*)$/$1/;
          $self->{company} = $ccookie;
     }
+    $logger->debug("LedgerSMB.pm: \$self->{company} = $self->{company}");
 
     $self->_db_init;
 
@@ -230,10 +239,11 @@ sub new {
        #check for valid session unless this is an inital authentication
        #request -- CT
        if (!LedgerSMB::Auth::session_check( $cookie{${LedgerSMB::Sysconfig::cookie_name}}, $self) ) {
-            print STDERR "Session did not check";
+            $logger->error("Session did not check");
             $self->_get_password("Session Expired");
             exit;
        }
+       $logger->debug("LedgerSMB::new: session_check completed OK");
     }
     $self->get_user_info;
     my %date_setting = (
@@ -253,6 +263,8 @@ sub new {
 
     $self->{stylesheet} = $self->{_user}->{stylesheet};
 
+    $logger->debug("End LedgerSMB.pm");
+
     return $self;
 
 }
@@ -725,6 +737,8 @@ sub _db_init {
     my $self     = shift @_;
     my %args     = @_;
     my $creds = LedgerSMB::Auth::get_credentials();
+
+    $logger->debug("LedgerSMB::_db_init: start");
   
     $self->{login} = $creds->{login};
     if (!$self->{company}){ 
@@ -811,7 +825,7 @@ sub _db_init {
 #private, for db connection errors
 sub _on_connection_error {
     for (@_){
-        print STDERR "$_\n";
+        $logger->error("$_");
     }
 }
 
@@ -829,8 +843,8 @@ sub dberror{
 	'P0001' => $self->{_locale}->text('Error from Function:') . "\n" .
                     $self->{dbh}->errstr,
    };
-   print STDERR "Logging SQL State ".$self->{dbh}->state.", error ".
-           $self->{dbh}->err . ", string " .$self->{dbh}->errstr . "\n";
+   $logger->error("Logging SQL State ".$self->{dbh}->state.", error ".
+           $self->{dbh}->err . ", string " .$self->{dbh}->errstr);
    if (defined $state_error->{$self->{dbh}->state}){
        $self->error($state_error->{$self->{dbh}->state});
        exit;
@@ -886,6 +900,7 @@ sub merge {
         else {
             $dst_arg = $arg;
         }
+        $logger->debug("LedgerSMB.pm: merge setting $dst_arg to $src->{$arg}");
         $self->{$dst_arg} = $src->{$arg};
     }
 }
diff --git a/LedgerSMB/DBObject.pm b/LedgerSMB/DBObject.pm
index 98ddb0f..5a9e4bb 100644
--- a/LedgerSMB/DBObject.pm
+++ b/LedgerSMB/DBObject.pm
@@ -47,9 +47,12 @@ your software.
 package LedgerSMB::DBObject;
 use Scalar::Util;
 use base qw(LedgerSMB);
+use LedgerSMB::Log;
 use strict;
 use warnings;
 
+my $logger = Log::Log4perl->get_logger('LedgerSMB::DBObject');
+
 sub __validate__ {}
 
 sub new {
@@ -99,6 +102,7 @@ sub exec_method {
     my $self   = shift @_;
     my %args     = @_;
     my $funcname = $args{funcname};
+    $logger->debug("exec_method: \$funcname = $funcname");
     my @in_args;
     @in_args = @{ $args{args}} if $args{args};
     
@@ -131,17 +135,18 @@ sub exec_method {
     $ref->{pronargs} = 0 unless defined $ref->{pronargs};
     # If the user provided args..
     if (!defined  $args{args}) {
-    
         @proc_args = $self->_parse_array($pargs);
         if (@proc_args) {
             for my $arg (@proc_args) {
                 if ( $arg =~ s/^in_// ) {
+                    $logger->debug("exec_method pushing $arg = $self->{$arg}");
                      push @call_args, $self->{$arg};
                 }
             }
         }
         for (@in_args) { push @call_args, $_ } ;
         $self->{call_args} = \@call_args;
+        $logger->debug("exec_method: \$self = " . Data::Dumper::Dumper($self));
         return $self->call_procedure( procname => $funcname, args => \@call_args, order_by => $self->{_order_method}->{"$funcname"} );
     }
     else {
diff --git a/LedgerSMB/Initiate.pm b/LedgerSMB/Initiate.pm
index b5252bc..fdd887c 100644
--- a/LedgerSMB/Initiate.pm
+++ b/LedgerSMB/Initiate.pm
@@ -8,6 +8,9 @@ use LedgerSMB::Auth;
 use LedgerSMB::Locale;
 use Data::Dumper;
 use DBI;
+use LedgerSMB::Log;
+
+my $logger = Log::Log4perl->get_logger('LedgerSMB::Initiate');
 
 =over
 
@@ -162,6 +165,7 @@ sub get_countrys
 
 sub validateform
 {
+    $logger->debug("Begin LedgerSMB::Initiate::validateform");
 
     ($self,$form,$locale)=@_;
 
@@ -220,12 +224,13 @@ sub validateform
             );
         }
     }
-
+    $logger->debug("End LedgerSMB::Initiate::validateform");
 }
 
 
 sub save_database
 {
+    $logger->debug("Begin LedgerSMB::Initiate::save_database");
 
 	my($self,$form)=@_;
 	# check all files exist and valids (contrib files , pgdabase.sql and modules and chart accounts etc)
@@ -260,14 +265,20 @@ sub save_database
 
 		#Stage -  Wind up completed the task
 	process_roles($form);
+
+    $logger->debug("End LedgerSMB::Initiate::save_database");
 }
 
+
+
 sub process_roles {
+    $logger->debug("Begin LedgerSMB::Initiate::process_roles");
 	my ($form) = @_;
 	print STDERR "loading roles............\n";
 	LedgerSMB::Initiate->getdbh($form);
 	open (PSQL, '|-', 'psql') || $form->error($locale->text("Couldn't open psql"));
 	my $company = $form->{company};
+    $logger->debug("LedgerSMB::Initiate::process_roles: company = $company");
 
 	open (ROLEFILE, '<', 'sql/modules/Roles.sql') || $form->error($locale->text("Couldn't open Roles.sql"));
 
@@ -290,7 +301,9 @@ sub process_roles {
 			" TO " .
 			$form->{newdbh}->quote_identifier($form->{admin_username});
 	}
-	print PSQL $query;
+	print PSQL "$query";
+
+    $logger->debug("End LedgerSMB::Initiate::process_roles");
 }
 
 sub run_all_sql_scripts
diff --git a/bin/initiate.pl b/bin/initiate.pl
index 4897a66..a3cb744 100644
--- a/bin/initiate.pl
+++ b/bin/initiate.pl
@@ -4,6 +4,12 @@ use LedgerSMB::Locale;
 use LedgerSMB::User;
 use LedgerSMB::Initiate;
 use LedgerSMB::Auth;
+use LedgerSMB::Log;
+use Data::Dumper;
+
+my $logger = Log::Log4perl->get_logger('initiate');
+
+$logger->debug('start bin/initiate.pl');
 
 #use LedgerSMB::Session;
 
@@ -42,7 +48,7 @@ if ( -f "bin/custom/$form->{script}" ) {
 if ( $form->{action} ) {
 
     &check_password unless $form->{action} eq 'logout';
-   
+
     &{ $form->{action} };
 
 }
diff --git a/initiate.pl b/initiate.pl
index 9cf121f..6a77fda 100644
--- a/initiate.pl
+++ b/initiate.pl
@@ -53,6 +53,10 @@ require "common.pl";
 
 $| = 1;
 
+use LedgerSMB::Log;
+
+my $logger = Log::Log4perl->get_logger('initiate');
+
 if ( $ENV{CONTENT_LENGTH} > $LedgerSMB::Sysconfig::max_post_size ) {
     print "Status: 413\n Request entity too large\n\n";
     die "Error: Request entity too large\n";
@@ -62,14 +66,20 @@ if ( $ENV{CONTENT_LENGTH} > 0 ) {
     read( STDIN, $_, $ENV{CONTENT_LENGTH} );
 }
 
+$logger->debug("initiate.pl: \$_ = $_\n");
+
 if ( $ENV{QUERY_STRING} ) {
     $_ = $ENV{QUERY_STRING};
 }
 
+$logger->debug("initiate.pl: \$_ = $_\n");
+
 if ( $ARGV[0] ) {
     $_ = $ARGV[0];
 }
 
+$logger->debug("initiate.pl: \$_ = $_\n");
+
 %form = split /[&=]/;
 
 # fix for apache 2.0 bug
@@ -80,6 +90,8 @@ $0 =~ tr/\\/\//;
 $pos = rindex $0, '/';
 $script = substr( $0, $pos + 1 );
 
+$logger->debug("initiate.pl: \$script = $script\n");
+
 #this needs to be a db based function
 #if (-e "${LedgerSMB::Sysconfig::userspath}/nologin" && $script ne 'admin.pl') {
 #	print "Content-Type: text/html\n\n<html><body><strong>";
diff --git a/lsmb-request.pl b/lsmb-request.pl
index 82d0f83..743aade 100644
--- a/lsmb-request.pl
+++ b/lsmb-request.pl
@@ -30,12 +30,22 @@ use LedgerSMB::User;
 use LedgerSMB;
 use LedgerSMB::Locale;
 use Data::Dumper;
+use LedgerSMB::Log;
 use strict;
 
+my $logger = Log::Log4perl->get_logger('');
+
+$logger->debug("Begin lsmb-request.pl");
+
 # for custom preprocessing logic
 eval { require "custom.pl"; };
 
+$logger->debug("lsmb-request.pl: getting request");
+
 my $request = new LedgerSMB;
+
+$logger->debug("lsmb-request.pl: Got request");
+
 $request->{action} = '__default' if (!$request->{action});
 
 $ENV{SCRIPT_NAME} =~ m/([^\/\\]*.pl)\?*.*$/;
@@ -47,8 +57,12 @@ if (!$script){
 	$request->error($locale->text('No workflow script specified'));
 }
 
+$logger->debug("calling $script");
+
 &call_script( $script, $request );
 
+$logger->debug("End lsmb-request.pl");
+
 sub call_script {
         
     my $script = shift @_;
diff --git a/scripts/admin.pl b/scripts/admin.pl
index 5671be4..637e5e2 100644
--- a/scripts/admin.pl
+++ b/scripts/admin.pl
@@ -9,6 +9,9 @@ use LedgerSMB::DBObject::User;
 use LedgerSMB::DBObject::Location;
 use Data::Dumper;
 use LedgerSMB::Setting;
+use LedgerSMB::Log;
+
+my $logger = Log::Log4perl->get_logger('LedgerSMB::Scripts::admin');
 
 sub __edit_page {
     
@@ -85,6 +88,7 @@ sub new_user {
     
     my $groups = $admin->get_roles();
     
+    $logger->debug("scripts/admin.pl new_user: \$user = " . Data::Dumper::Dumper($user));
     
         my $template = LedgerSMB::Template->new( 
             user => $user, 
-- 
1.6.3.3

>From 0144417840aa85ca5206746ba90360d849716287 Mon Sep 17 00:00:00 2001
From: Ian Goodacre <ian@laptop2.(none)>
Date: Tue, 26 Jan 2010 05:38:52 +1300
Subject: [PATCH 4/8] Clarify requirement to install PostgreSQL contrib components.

---
 INSTALL |    4 +++-
 1 files changed, 3 insertions(+), 1 deletions(-)

diff --git a/INSTALL b/INSTALL
index 041d762..967e6e8 100644
--- a/INSTALL
+++ b/INSTALL
@@ -223,7 +223,9 @@ but typically not installed by default in most distributions.
 Identify the system package containing the files tsearch2.sql, tablefunc.sql,
 and pg_trgm.sql. Install that package, and locate the files on the filesystem.
 
-You only need to install these function libraries once per postgresql cluster.
+If you install these on template1 then you only need to install these function
+libraries once per postgresql cluster. They will be included in any new
+database created from template1.
 
 For the remainder of this INSTALL procedure, you will need to become user
 postgres, or have the ability to log in to psql as your current user, or issue
-- 
1.6.3.3

>From d8d39a319df720f20a936417c3f8433c99808275 Mon Sep 17 00:00:00 2001
From: Ian Goodacre <ian@laptop2.(none)>
Date: Sat, 23 Jan 2010 09:48:30 +1300
Subject: [PATCH 5/8] Minimal change to get the initiate script to run

---
 bin/initiate.pl |   13 ++++++++++++-
 1 files changed, 12 insertions(+), 1 deletions(-)
 mode change 100644 => 100755 initiate.pl

diff --git a/bin/initiate.pl b/bin/initiate.pl
index a3cb744..7a0a469 100644
--- a/bin/initiate.pl
+++ b/bin/initiate.pl
@@ -45,7 +45,10 @@ if ( -f "bin/custom/$form->{script}" ) {
 
 # because iniate.pl called only at admin for initializtion everything at default_db
 
+LedgerSMB::Log->debug("got here");
 if ( $form->{action} ) {
+    LedgerSMB::Log->debug("got here a",$form->{action});
+    LedgerSMB::Log->debug('action:',$form->{action});
 
     &check_password unless $form->{action} eq 'logout';
 
@@ -60,8 +63,11 @@ else {
 
      &check_password;
      
+    LedgerSMB::Log->debug("got here b");
      $form->{'action'}='login';
 
+    LedgerSMB::Log->debug('action:',$form->{action});
+
      &{ $form->{action} };
     
      
@@ -78,6 +84,7 @@ sub check_password {
 
 	my $auth_temp=LedgerSMB::Auth->get_credentials();
 
+
         LedgerSMB::Auth->credential_prompt unless($auth_temp);
 
         $form->{'login'}=$auth_temp->{'login'};
@@ -89,10 +96,14 @@ sub check_password {
 	$form->{'initiateon'}=1;
     
         $root=LedgerSMB::Initiate->new($form);
+    LedgerSMB::Log->debug("got root");
 
 	$form->{dbh}=$root->getdbh($form);   # get the connection if user exist as superuser
+    LedgerSMB::Log->debug("got dbh");
+    LedgerSMB::Log->dump($form->{dbh});
 
-	if ( lc($form->{dbh}) eq "no999" or !$root->checksuperuser($form)) {
+#	if ( lc($form->{dbh}) eq "no999" or !$root->checksuperuser($form)) {
+	if ( lc($form->{dbh}) eq "no999") {
             LedgerSMB::Auth->credential_prompt;
             exit;
         }
diff --git a/initiate.pl b/initiate.pl
old mode 100644
new mode 100755
-- 
1.6.3.3

>From 1decb66e10e4b3c8e8f749f56516979ffc5c9df3 Mon Sep 17 00:00:00 2001
From: Ian Goodacre <ian@laptop2.(none)>
Date: Tue, 26 Jan 2010 05:46:21 +1300
Subject: [PATCH 6/8] Fix the initiate scripts so a new database can be created.

---
 LedgerSMB/Initiate.pm |  258 ++++++++++++++++++++++---------------------------
 bin/initiate.pl       |   49 +--------
 2 files changed, 122 insertions(+), 185 deletions(-)

diff --git a/LedgerSMB/Initiate.pm b/LedgerSMB/Initiate.pm
index fdd887c..82df1ab 100644
--- a/LedgerSMB/Initiate.pm
+++ b/LedgerSMB/Initiate.pm
@@ -8,6 +8,8 @@ use LedgerSMB::Auth;
 use LedgerSMB::Locale;
 use Data::Dumper;
 use DBI;
+use Locale::Language;
+use Locale::Country;
 use LedgerSMB::Log;
 
 my $logger = Log::Log4perl->get_logger('LedgerSMB::Initiate');
@@ -50,62 +52,9 @@ sub initialize
 
       # In future if required use this function to initialize the attributes of the class "Initiate"
  
-      $self->{initiateon}=$form->{initiateon};
-
-      if(scalar($self->{initiateon})==1)
-      {
-          $form->{company}=${LedgerSMB::Sysconfig::default_db};
-	  $form->{port}=${LedgerSMB::Sysconfig::port};
-          $form->{host}=${LedgerSMB::Sysconfig::host};
-
-      }
-      
-
-
-}
-
-
-
-
-sub getdbh
-{
-
- my($self,$form)=@_;
-
- my($database,$host,$port,$username,$password);
-
- if($form->{initiateon}==1)
- {
-   $ENV{PGDATABASE} = $form->{company};
-   $ENV{PGHOST}=$form->{host};
-   $ENV{PGPORT}=$form->{port};
-   $username=$form->{username};
-   $password=$form->{password};
-   $ENV{PGUSER} = $form->{username};
-   $ENV{PGPASSWORD} = $form->{password};
- }
- else
- {
-
-    $ENV{PGDATABASE}=$form->{database};
-    $ENV{PGHOST}=$form->{dbhost};
-    $ENV{PGPORT}=$form->{dbport};
-    $username=$form->{username};
-    $password=$form->{password};
-
- }
-  
-
-   my $dbconnect = "dbi:Pg:user=$username password=$password";    # for easier debugging
-
-   my $dbh = DBI->connect($dbconnect) or return "no999";
-
-   return($dbh);
-
 }
 
 
-
 sub checksuperuser
 {
 
@@ -182,6 +131,10 @@ sub validateform
 
      
     $form->{dbhost}=~s/ //g;
+    $form->{dbhost} = 'localhost' unless($form->{dbhost});
+
+    $form->{dbport} =~ s/ //g;
+    $form->{dbport} = '5432' unless($form->{dbport});
 
    
 
@@ -210,15 +163,17 @@ sub validateform
 
     if ( !$form->{edit} ) {
 
-	$form->{initiateon}=0;	
-
-        $tempdbh = LedgerSMB::Initiate->getdbh($form);
+        # If we can connect to the database, then it already exists
+        my $tempdbh = DBI->connect(
+            "dbi:Pg:db=$form->{database};host=$form->{dbhost};port=$form->{dbport}",
+            $form->{username},
+            $form->{password},
+            { $RaiseError => 0 },
+        );
 
-	$form->{initiateon}=1;	
 
- 	$form->{tempdbh}=$tempdbh;        
-
-	if ( lc($tempdbh) ne "no999" ) {
+        if ( defined($tempdbh)) {
+            $tempdbh->disconnect;
             $form->error( __FILE__ . ':' . __LINE__ . ': '
                   . $locale->text( '[_1] is already a database!', $form->{database} )
             );
@@ -253,29 +208,57 @@ sub save_database
 
 		#Stage 1 -   Create the databse $form->{database}
 
-	LedgerSMB::Initiate->create_database($form,$form->{dbh},$form->{database},$form->{username}); 
+	LedgerSMB::Initiate->create_database($form); 
 		
 		#Stage 2 -  CReate the language plpgsql
 	
-	$form->{newdbh}=LedgerSMB::Initiate->handle_create_language($form);
+	LedgerSMB::Initiate->handle_create_language($form);
 		
-		#stage 3 -  Execute series of files which are located in array @totalexecutable_files in the database $form->{newdbh}
+		#stage 3 -  Execute series of files which are located in array @totalexecutable_files
 
 	LedgerSMB::Initiate->run_all_sql_scripts($form,\@totalexecutable_files);
 
-		#Stage -  Wind up completed the task
+		#Stage 4 -  Wind up completed the task
 	process_roles($form);
 
+        #stage 5 - Load languages
+    load_languages($form);
+
     $logger->debug("End LedgerSMB::Initiate::save_database");
+
 }
 
+sub load_languages {
+    $logger->debug("Beging LedgerSMB::Initiate::load_languages");
+    my ($form) = @_;
+
+    opendir DIR, $LedgerSMB::Sysconfig::localepath;
+    foreach my $dir (grep !/^\.\.?$/, readdir DIR) {
+        my $code = substr( $dir, 0, -3);
+        $logger->debug("add language $code");
+        my $description = code2language( substr( $code, 0, 2) );
+        $description .= '/' . code2country( substr( $code, 3, 2) ) if(length($code) > 4);
+        $description .= ' ' . substr( $code, 5 ) if(length($code) > 5);
+        $form->{dbh}->do("insert into language ( code, description ) values ( " .
+			$form->{dbh}->quote( $code ) . ', ' .
+            $form->{dbh}->quote( $description ) . ')'
+        ) || $form->error( __FILE__ . ':' . __LINE__ . ': '
+                  . $locale->text( 'language [_1]/[_2] creation failed',
+                      $code, $description));
+    }
+    closedir(DIR);
+    $logger->debug("End LedgerSMB::Initiate::load_languages");
+}
 
 
 sub process_roles {
     $logger->debug("Begin LedgerSMB::Initiate::process_roles");
 	my ($form) = @_;
-	print STDERR "loading roles............\n";
-	LedgerSMB::Initiate->getdbh($form);
+    $ENV{PGDATABASE} = $form->{database};
+    $ENV{PGHOST}     = $form->{dbhost};
+    $ENV{PGPORT}     = $form->{dbport};
+    $ENV{PGUSER}     = $form->{username};
+    $ENV{PGPASSWORD} = $form->{password};
 	open (PSQL, '|-', 'psql') || $form->error($locale->text("Couldn't open psql"));
 	my $company = $form->{company};
     $logger->debug("LedgerSMB::Initiate::process_roles: company = $company");
@@ -290,18 +273,43 @@ sub process_roles {
 	my $query;
 	if ($form->{createuser}){
 		$query = qq| create user | . 
-			$form->{newdbh}->quote_identifier($form->{admin_username}) .
+			$form->{dbh}->quote_identifier($form->{admin_username}) .
 			qq| WITH PASSWORD | .
-			$form->{newdbh}->quote($form->{admin_password}) .
+			$form->{dbh}->quote($form->{admin_password}) .
 			qq| IN ROLE | .
-			$form->{newdbh}->quote_identifier("lsmb_${company}__users_manage");
+			$form->{dbh}->quote_identifier("lsmb_${company}__users_manage") .
+            ";";
 	} else {
 		$query = "GRANT " .
-			$form->{newdbh}->quote_identifier("lsmb_${company}__users_manage")  . 
+			$form->{dbh}->quote_identifier("lsmb_${company}__users_manage")  . 
 			" TO " .
-			$form->{newdbh}->quote_identifier($form->{admin_username});
+			$form->{dbh}->quote_identifier($form->{admin_username}) . ";";
 	}
-	print PSQL "$query";
+	print PSQL "$query\n";
+
+    # Add the account used to create the database as a user
+    # with rights to manage users.
+    $query = "INSERT INTO entity (name, entity_class, created, country_id) " .
+        " VALUES ( '" . $form->{username} . "', 3, NOW(), " .
+        " (SELECT id FROM country WHERE short_name = '" .
+        uc($form->{countrycode}) .  "' ));";
+	print PSQL "$query\n";
+
+    $query = "INSERT INTO person (entity_id, first_name, last_name, created) " .
+        " VALUES ( (SELECT id FROM entity WHERE name = '" .
+        $form->{username} . "'), 'database', 'creator', NOW());";
+	print PSQL "$query\n";
+
+    $query = "INSERT INTO users (username, entity_id) " .
+        " VALUES ( '" . $form->{username} . "', " .
+        " (SELECT id FROM entity WHERE name = '" .
+        $form->{username} . "'));";
+	print PSQL "$query\n";
+
+    $query = "INSERT INTO user_preference (id) " .
+        " VALUES ((SELECT id FROM users WHERE entity_id = " .
+        " (SELECT id FROM entity WHERE name = '" . $form->{username} . "')));";
+	print PSQL "$query\n";
 
     $logger->debug("End LedgerSMB::Initiate::process_roles");
 }
@@ -313,7 +321,6 @@ sub run_all_sql_scripts
 
 	foreach $dbfile(@$totalexcfiles)
 	{
-		print STDERR "Loading $dbfile\n";
 
 		LedgerSMB::Initiate->run_db_file($form,$dbfile);
 
@@ -327,6 +334,11 @@ sub run_db_file
 {
 
  	my($self,$form,$dbfile)=@_;
+    $ENV{PGDATABASE} = $form->{database};
+    $ENV{PGHOST}     = $form->{dbhost};
+    $ENV{PGPORT}     = $form->{dbport};
+    $ENV{PGUSER}     = $form->{username};
+    $ENV{PGPASSWORD} = $form->{password};
 	system("psql < $dbfile");
 }
 
@@ -338,15 +350,27 @@ sub create_database
 {
 
 
-	my ($self,$form,$dbh,$database,$owner)=@_;
+	my ($self,$form)=@_;
 
-	my $locale=$form->{locale};
+    $form->{admindbh} = DBI->connect(
+        "dbi:Pg:db=postgres;host=$form->{dbhost};port=$form->{dbport}",
+        $form->{username},
+        $form->{password},
+    ) or $form->error( __FILE__ . ':' . __LINE__ . ': ' .
+        $locale->text( 'unable to connect to postgres database on [_1]:[_2]',
+            $form->{dbhost},$form->{dbport}));
 
-	$dbh->do("create database $database with owner $owner") || $form->error( __FILE__ . ':' . __LINE__ . ': '
+	$form->{admindbh}->do("create database $form->{database} with owner $form->{username}") || $form->error( __FILE__ . ':' . __LINE__ . ': '
                   . $locale->text( 'database [_1] creation failed',$database));
 
-	
+    $form->{admindbh}->disconnect;
 
+    $form->{dbh} = DBI->connect(
+        "dbi:Pg:db=$form->{database};host=$form->{dbhost};port=$form->{dbport}",
+        $form->{username},
+        $form->{password},
+        { RaiseError => 1 },
+    );
 }
 
 sub handle_create_language
@@ -354,53 +378,21 @@ sub handle_create_language
 
 	my($self,$form)=@_;
 
-	$form->{initiateon}=0;
-		
-	my $newdbh=LedgerSMB::Initiate->getdbh($form);	
-		
-	$form->{initiateon}=1;
-		
-
-	if(lc($newdbh) eq 'no999')
-	{
-		
- 		$form->{dbh}->do("drop database $form->{database}");
-
-		$form->error( __FILE__ . ':' . __LINE__ . ': '
-		        . $locale->text( 'connection failed to database [_1] might be port/localhost problem!', $form->{database} )
-		            );		
-
-	}
-
-	
-
-	if(!LedgerSMB::Initiate->create_language($newdbh))
-	{
+    eval {
+        local $form->{dbh}->{RaiseError} = 1;
+        $form->{dbh}->do("create language plpgsql");
+    };
+    if($@) {
 		$form->{dbh}->do("drop database $form->{database}");
 
 		$form->error( __FILE__ . ':' . __LINE__ . ': '
-	        . $locale->text( 'connection failed to database [_1] might be port/localhost problem!', $form->{database} )
+	        . $locale->text( 'create language plpgsql failed on database [_1]!', $form->{database} )
 		            );		
 
 	}
-
-
-	return($newdbh);
-	
 }
 
 
-sub create_language
-{
-
-	my ($self,$newdbh)=@_;
-	$newdbh->do("create language plpgsql") || return 0;
-	return 1;
-
-}
-
-
-
 
 
 sub check_contrib_valid_exist
@@ -529,35 +521,16 @@ sub merge_chart_gifi_valid_exist
         
 	$locale=$form->{locale};
 
-	my $dir=$ENV{SCRIPT_FILENAME};
-
-	my $location="/sql/coa/$form->{countrycode}/";
-
-	$dir =~s/\/[\w\d\.]*$/$location/;
-
-	my $chartdir=$dir."chart/";
-	
-	my $gifidir=$dir."gifi/";
-	@chartdir = LedgerSMB::Initiate->read_directory($form, $chartdir);
-
-        my @dest;	
-
-        my $i;
-	for($i=0;$i<=$#chartdir;$i++)
-	{
-		$dest[$i]=$chartdir.$chartdir[$i] if $chartdir[$i] = $coa;
-	}
-	for(my $j=0;$j<=$#gifidir;$j++,$i++)
-	{
-	  
-		$dest[$i]=$chartdir.$gifidir[$i] if $gifidir[$i] = $coa;
-	
-	}
-
-	
-	return(@dest);
+    my $dir = ($ENV{SCRIPT_FILENAME} =~ m/^(.*\/)/) ? $1 : './';
 
+    $dir .= "/sql/coa/$form->{countrycode}/";
 
+    return(
+        grep { -e $_ } (
+            $dir . 'chart/' . $coa,
+            $dir . 'gifi/' . $coa,
+        )
+    );
 }
 
 
@@ -609,6 +582,7 @@ sub get_fullpath
 
 
 
+# Return 1 if all values in @$search are in @$source, otherwise return 0
 sub all_files_found
 {
 
diff --git a/bin/initiate.pl b/bin/initiate.pl
index 7a0a469..f3ad985 100644
--- a/bin/initiate.pl
+++ b/bin/initiate.pl
@@ -37,6 +37,11 @@ $form->{timeout}    = 600;
 
 require "bin/pw.pl";
 
+my $auth = LedgerSMB::Auth->get_credentials();
+LedgerSMB::Auth->credential_prompt unless($auth and $auth->{login} and $auth->{password});
+$form->{username} = $auth->{login};
+$form->{password} = $auth->{password};
+
 # customization
 if ( -f "bin/custom/$form->{script}" ) {
     eval { require "bin/custom/$form->{script}"; };
@@ -45,12 +50,7 @@ if ( -f "bin/custom/$form->{script}" ) {
 
 # because iniate.pl called only at admin for initializtion everything at default_db
 
-LedgerSMB::Log->debug("got here");
 if ( $form->{action} ) {
-    LedgerSMB::Log->debug("got here a",$form->{action});
-    LedgerSMB::Log->debug('action:',$form->{action});
-
-    &check_password unless $form->{action} eq 'logout';
 
     &{ $form->{action} };
 
@@ -61,13 +61,8 @@ else {
      $form->error( __FILE__ . ':' . __LINE__ . ':' . $locale->text('No Database Drivers available!') )
      unless ( LedgerSMB::User->dbdrivers );
 
-     &check_password;
-     
-    LedgerSMB::Log->debug("got here b");
      $form->{'action'}='login';
 
-    LedgerSMB::Log->debug('action:',$form->{action});
-
      &{ $form->{action} };
     
      
@@ -79,38 +74,6 @@ else {
 
 # end
 
-sub check_password {
-
-
-	my $auth_temp=LedgerSMB::Auth->get_credentials();
-
-
-        LedgerSMB::Auth->credential_prompt unless($auth_temp);
-
-        $form->{'login'}=$auth_temp->{'login'};
-
-        $form->{'username'}=$auth_temp->{'login'};
-
-        $form->{'password'}=$auth_temp->{'password'};
-
-	$form->{'initiateon'}=1;
-    
-        $root=LedgerSMB::Initiate->new($form);
-    LedgerSMB::Log->debug("got root");
-
-	$form->{dbh}=$root->getdbh($form);   # get the connection if user exist as superuser
-    LedgerSMB::Log->debug("got dbh");
-    LedgerSMB::Log->dump($form->{dbh});
-
-#	if ( lc($form->{dbh}) eq "no999" or !$root->checksuperuser($form)) {
-	if ( lc($form->{dbh}) eq "no999") {
-            LedgerSMB::Auth->credential_prompt;
-            exit;
-        }
-    
-        
-}
-
 
 sub login {
 
@@ -145,7 +108,7 @@ sub prepare_initiate {
 				<th>$self->{title}</th>
 			</tr>
 			<tr size="5"></tr>
-			</tr>|;
+			|;
     
 
     print qq|		
-- 
1.6.3.3

>From bab192209925a482bccf38d9142ad275243240dd Mon Sep 17 00:00:00 2001
From: Ian Goodacre <ian@laptop2.(none)>
Date: Sat, 30 Jan 2010 17:42:40 +1300
Subject: [PATCH 7/8] Eliminate noise from CGI::Simple

CGI::Simple->vars() in scalar context returns a reference to a tied
hash which contains all the query variables as keys, but it also
contains other keys. Assigning to a hash instead gives only the
query variables as keys.
---
 LedgerSMB.pm |    8 +++++---
 1 files changed, 5 insertions(+), 3 deletions(-)

diff --git a/LedgerSMB.pm b/LedgerSMB.pm
index 0beb6ff..6566023 100755
--- a/LedgerSMB.pm
+++ b/LedgerSMB.pm
@@ -165,12 +165,14 @@ sub new {
     bless $self, $type;
     $logger->debug("LedgerSMB::new: \$argstr = $argstr");
     my $query = ($argstr) ? new CGI::Simple($argstr) : new CGI::Simple;
-    my $params = $query->Vars;
-    $logger->debug("LedgerSMB::new: params = ", Data::Dumper::Dumper($params));
+    # my $params = $query->Vars; returns a tied hash with keys that
+    # are not parameters of the CGI query.
+    my %params = $query->Vars;
+    $logger->debug("LedgerSMB::new: params = ", Data::Dumper::Dumper(\%params));
     $self->{VERSION} = $VERSION;
     $self->{_request} = $query;
 
-    $self->merge($params);
+    $self->merge(\%params);
     $self->{have_latex} = $LedgerSMB::Sysconfig::latex;
 
     # Adding this so that empty values are stored in the db as NULL's.  If
-- 
1.6.3.3

>From 6cda1a706a545ed6460e77171665568c14293914 Mon Sep 17 00:00:00 2001
From: Ian Goodacre <ian@laptop2.(none)>
Date: Sat, 30 Jan 2010 18:10:45 +1300
Subject: [PATCH 8/8] Set country when adding a user

The entity table now has country_id as a not null field and an entry
must be created when adding a user. Therefore, add country as a drop
down to the add user UI and pass the country ID through to the entity
table.
---
 LedgerSMB/DBObject/Admin.pm |    1 +
 UI/Admin/edit_user.html     |   17 +++++++++++++++++
 sql/modules/Person.sql      |    7 ++++---
 3 files changed, 22 insertions(+), 3 deletions(-)

diff --git a/LedgerSMB/DBObject/Admin.pm b/LedgerSMB/DBObject/Admin.pm
index d79698d..50b2715 100644
--- a/LedgerSMB/DBObject/Admin.pm
+++ b/LedgerSMB/DBObject/Admin.pm
@@ -39,6 +39,7 @@ sub save_user {
             'first_name',
             'last_name',
             'employeenumber',
+            'country_id',
         ]    
     );
     
diff --git a/UI/Admin/edit_user.html b/UI/Admin/edit_user.html
index b43e198..f73fc53 100644
--- a/UI/Admin/edit_user.html
+++ b/UI/Admin/edit_user.html
@@ -57,6 +57,23 @@
                     <input type="textarea" name="employeenumber" value="<?lsmb user.employee.employeenumber?>"/>
                 </td>
             </tr>
+            <tr>
+                <td><?lsmb text('Country') ?></td>
+                <td>
+                    <?lsmb IF edit_location.country; 
+                        country_id = edit_location.country_id;
+                        ELSE; 
+                        country_id = default_country;
+                        END; -?>
+                    <?lsmb PROCESS select element_data = {
+                        name = "country_id"
+                        options = countries
+                        default_values = [country_id]
+                        value_attr = "id"
+                        text_attr = "name"
+                    } ?>
+                </td>
+            </tr>
         </table>
         <button type="submit" value="save_user"><?lsmb text('Save User') ?>
         </button>
diff --git a/sql/modules/Person.sql b/sql/modules/Person.sql
index 303f54f..8ecba6b 100644
--- a/sql/modules/Person.sql
+++ b/sql/modules/Person.sql
@@ -5,7 +5,8 @@ $$ LANGUAGE SQL;
 
 CREATE OR REPLACE FUNCTION person__save
 (in_entity_id integer, in_salutation_id int, 
-in_first_name text, in_middle_name text, in_last_name text    
+in_first_name text, in_middle_name text, in_last_name text,
+in_country_id integer
 )
 RETURNS INT AS $$
 
@@ -21,8 +22,8 @@ RETURNS INT AS $$
     e_id := in_entity_id; 
     
     IF NOT FOUND THEN
-        INSERT INTO entity (name, entity_class) 
-	values (in_first_name || ' ' || in_last_name, 3);
+        INSERT INTO entity (name, entity_class, country_id) 
+	values (in_first_name || ' ' || in_last_name, 3, in_country_id);
 	e_id := currval('entity_id_seq');
        
     END IF;
-- 
1.6.3.3