package Neighbouring; use strict; use warnings; use Apache2::Cookie; use Apache2::Request (); use Apache2::RequestRec (); use Apache2::RequestIO (); use Apache2::RequestUtil (); use Apache::Session::File; use Apache2::Const -compile => qw(OK); use SQLConnection; use JSON; sub handler { my $r = shift; my $req = Apache2::Request->new($r); my $page = $req->param('.state') || 'start'; my $sid; my $j = Apache2::Cookie::Jar->new($r); my $c_in = $j->cookies('nb_session_id'); # get cookie from request headers if (($c_in) && ($page ne 'start')) { # retrieve existing cookies only if we are not on the start page $sid = $c_in->value; } else { my %session; tie %session, 'Apache::Session::File', undef, { Directory => '/tmp', LockDirectory =>'/tmp', }; $sid = $session{'_session_id'}; my $c_out = Apache2::Cookie->new($r, -name => 'nb_session_id', -value => $sid, -expires => '+8H'); $c_out->bake($r); # send cookie in response headers } my $template = Template->new({INCLUDE_PATH => '/template_dir', PRE_PROCESS => 'config',}); my %states = ( 'start' => \&start_page, 'notfound' => \¬found_page, 'auto_input' => \&autocomplete_input, ); if ($states{$page}) { $states{$page}->($r,$template,$sid); # call the correct subroutine } else { $states{'notfound'}->($r,$template,$sid); } } sub autocomplete_input { my ($r,$template,$sid) = @_; my $req = Apache2::Request->new($r); my $cellid = $req->param('query'); $cellid = quotemeta($cellid); my $sth = SQLConnection->dbh->prepare('select distinct LAC,CI,UserLabel from Cell where UserLabel like \'%'.$cellid.'%\' order by UserLabel'); $sth->execute; my @results; while (my @row = $sth->fetchrow_array) { $row[2] =~ s/\"//g; push @results,$row[0].','.$row[1].'/'.$row[2]; } my $ret = {'query' => $cellid, 'suggestions' =>\@results}; $r->content_type('application/json'); $r->no_cache(1); $r->headers_out; print to_json($ret); return Apache2::Const::OK; }