#!/usr/bin/perl

use strict;
use CGI;

use Opals::Context;
use Opals::Template_ajax qw(
    tmpl_read
    tmpl_write
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);


 
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'ajax/portlet/getOWLLeafDB.tmpl',
    }
);


    my $leafId      = $input->{"leafId"};
    if(defined $leafId && $leafId>0){
        my ($title,$url,$description) = ("","","");
        my $sth=$dbh->prepare("select  name as title,url,description,rank from opl_extDatabase where page='OWL' && rank=?");
        my $rv =$sth->execute($leafId);  
        ($title,$url,$description) = $sth->fetchrow_array;
        if($url !~ m/http:\/\/|https:\/\//i){
            $url = "http://" . $url;
        }
        $title =~ s/'/\'/g;
        $url =~ s/[\r\n]//g;
        $description =~ s/</&lt;/g ;
        $description =~ s/>/&gt;/g ;
        #$description =~ s/\n/<br>/g;
        $sth->finish;  
        my $status = ($rv eq '0E0') ? 0 : 1;        
        $template->param(
            status      => $status,
            leafId      => $leafId,
            title       => $title,
            url         => $url,
            description => $description
        );
    }
    else{
        my $url = "";
        my $sth=$dbh->prepare("select  name as title ,url,description,rank  from opl_extDatabase where page='OWL' order by rank");
        my $rv =$sth->execute();
        my @leavesList; 
        while(my $l = $sth->fetchrow_hashref){
            $url = $l->{'url'};
            if($url !~ m/http:\/\/|https:\/\//i){
                $url = "http://" . $url;
            }
            $l->{'url'} = $url;
            $l->{'description'} =~ s/</&lt;/g ;
            $l->{'description'} =~ s/>/&gt;/g ;
            $l->{'description'} =~ s/\n/<br>/g;
            
            push @leavesList, $l;

        } 
 
        $template->param(leavesList =>\@leavesList);
    }


tmpl_write($dbh, $cgi, $cookie, $template);


