#!/usr/bin/perl

use strict;
push(@INC,'/home/oc/cgi-bin/');
use lib '/home/oc/cgi-bin/';
use lib './';
use OC;
use CGI qw/:standard/;
use HTML::Template;
use Tie::IxHash;
use Digest::MD5 qw(md5_hex);
use Mail::Sender;

use vars qw/
%CONFIG
$template
%form
%cookie
$self_url
$TITLE
@LINKS
$BODY
@DISPLAYED
$CAN_EDIT
$CAN_ADD
$LOGGED_IN
@NOTE
$NAVIGATION
$USERNAME
/;


sub Initialize {
    %form=();
    my $query=new CGI;
    foreach ($query->param) {
        $form{$_}=$query->param($_);
    }   
    foreach ($query->cookie) {
        $cookie{$_}=$query->cookie($_);
    }
    %CONFIG=%OC::CONFIG;

    $self_url=$CONFIG{news_url};

#    $self_url=$ENV{REQUEST_URI};
#    $self_url=~s/^(.*)\?.*$/$1/;
#    $self_url=~s/^(.*.cgi).*$/$1/;

    @DISPLAYED=();
    @LINKS=();
    $TITLE='';
    $BODY='';
    @NOTE=();
    $NAVIGATION='';
    $LOGGED_IN=0;
    $CAN_EDIT=0;
    $CAN_ADD=0;
}


sub ConnectToDatabase {
    if (!defined $::db) {
      $::db = DBI->connect("DBI:mysql:$CONFIG{db_name}:$CONFIG{db_host}:
        $CONFIG{db_port}",$CONFIG{db_username},$CONFIG{db_password})
        || die "Can't connect to database server.";
    }
    return $::db;
}

sub PrepareSQL {
    my ($str) = (@_);
    $::sth=$::db->prepare($str);
}
 
sub ExecuteSQL {
    $::sth->execute(@_) || die "Could not execute SQL statement";
}

sub SendSQL {
    PrepareSQL(@_); 
    ExecuteSQL();
}

sub FetchSQLData {
    return $::sth->fetchrow_array();
}

sub Note {
    push(@NOTE,$_[0]);
}

sub Output_Notes {
    my $result="<font color=red>";
    foreach (@NOTE) {
        $result.="$_<br>";
    }
    $result.="</font><p>";
    return $result;
}

sub Prepare_Template {
    $template=HTML::Template->new(
	filename=>$_[0],
        die_on_bad_params=>0,
        loop_context_vars=>1,
        global_vars=>0,
        shared_cache=>0,
    );
    $template->param(table_color1=>$CONFIG{color}{table1});
    $template->param(table_color3=>$CONFIG{color}{table3});
}

sub Add_News_Screen {
    $TITLE="Add news";
    unless ($CAN_ADD) {
        $BODY.="You don't have permission to add news. Are you logged in?";
    } else {
        $BODY.="News shouldn't be longer than 330 characters.<p>";
        $BODY.=Output_Notes;
        $BODY.="<form action='$self_url' method=post>";
        $BODY.="<table><tr><td><b>Type</b><br><select name=type>";
        SendSQL("select type  from news_types");
        while(my $result=FetchSQLData) {
            my $selected='';
            $selected=' selected ' if ($form{type} eq $result);
            $BODY.="<option $selected value='$result'>$result</option>";
        }
        $BODY.="</select><p>
          <b>Source</b><br><input type=query name=source value='$form{source}' size=40><p>
          <b>Title</b><br><input type=query name=title value='$form{title}' size=40><p>
          <b>Body</b><br><textarea name=body value='' cols=70 rows=10 wrap=soft>$form{body}</textarea>
          <input type=hidden name=cmd value='add_news'><center><hr noshade size=1>
          <input type=submit value='Add'></td></tr></table>";
        $BODY.="</form>";
    }
}

sub Add_News {
    @NOTE=();
    unless ($CAN_ADD) {
        Note("You don't have permissions to add news! Are you logged in?");
    }    
    if (length($form{title})<3) {
        Note("Title too short!");
    }
    if (length($form{body})<10) {
        Note("Body too short!");
    }
    if (length($form{body})>330) {
        Note("Body can contain max. 330 characters!");
    }
    if (scalar(@NOTE)) {
        Add_News_Screen;
        return;
    }

    PrepareSQL("insert into news (author,type,title,body,added,status,source) values (?,?,?,?,?,?,?)");
    ExecuteSQL($cookie{username},$form{type},$form{title},$form{body},time,'pending',$form{source});

    $TITLE="Add news";
    $BODY.="News sucessfully added to queue. In next 24 hours they will be approved or rejected!
     You can check status on your personal page.";        

    OC::Mail_Webmaster("Request for news..");
}

sub Show_Queue {
    $TITLE="News queue";

    unless ($CAN_EDIT) {
        $BODY.="You don't have permissions to edit news! Are you logged in?";
        return;
    }
    
    $BODY.=Output_Notes;

    my @news=();
    SendSQL("select title,body,author,added,id,type,source from news where status='pending'");
    while (my @result=FetchSQLData) {
        my %row=();
        $row{title}=$result[0];
        $row{body}=$result[1];
        $row{author}=$result[2];
        $row{added}=OC::Time_To_Str($result[3],'nice');
        $row{author}=$result[2]; 
        $row{id}=$result[4];
        $row{type}=$result[5];
        $row{source}=$result[6];
        push(@news,\%row);
    }

    if (scalar(@news)) {
        $BODY.="<table border=0 cellpadding=3 cellspacing=1>";
        my ($color1,$color2)=($CONFIG{color}{table3},$CONFIG{color}{table1});
        foreach (@news) {
            my %row=%{$_};
            SendSQL("select fullname from account where username='$row{author}'");
            $row{author}=FetchSQLData;
	    $BODY.="<tr bgcolor='$color1'><td valign=top>$row{added}</td>
              <td valign=top><b>$row{title}</b><br>$row{body}
              <table width=100%><tr><td align=right><a href='$self_url/admin?cmd=edit&id=$row{id}'>Edit</a>&nbsp;
              </td></tr></table>  </td></tr>";
            $BODY.="<tr bgcolor='$color1'><td valign=top>Source</td>
              <td>$row{source}</td></tr>";
            $BODY.="<tr bgcolor='$color1'><td valign=top>Author</td>
              <td>$row{author}</td></tr>";
            $BODY.="<tr bgcolor='$color1'><td>Type</td>
              <td>$row{type}</td></tr>";
            $BODY.="<tr bgcolor='$color1'><td colspan=2 align=center>
              <form action='$self_url/admin' method=post>
              <textarea name=response rows=4 cols=50 wrap=soft></textarea>
              <br><input type=submit name=approve_news value='Approve'>
              <input type=submit name=reject_news value='Reject'>
              <input type=hidden name=id value=$row{id}>
              </form></td></tr>";
            ($color1,$color2)=($color2,$color1);
        }

        $BODY.="</table>";
    } else {
        $BODY.="No news in queue..";
    }
    
}

sub Edit_News {
    my ($title,$body,$author);
    SendSQL("select title,body,author from news where id=$form{id}");
    unless (($title,$body,$author)=FetchSQLData) {
        Note("Invalid id: $form{id}!");
        Show_Queue;
        return;
    }

    $TITLE="Edit news";
    $BODY.=Output_Notes;
    $BODY.="<form action='$self_url/admin' method=post>";
    $BODY.="<table>";
    $BODY.="<tr><td>Author<br><input type=query name=author value='$author' size=20><p>";
    $BODY.="Type<br><select name=type>";
    SendSQL("select type  from news_types");
    while(my $result=FetchSQLData) {
        my $selected='';
        $selected=' selected ' if ($form{type} eq $result);
        $BODY.="<option $selected value='$result'>$result</option>";
    }
    $BODY.="</select><p>Title<br><input type=query name=title value='$title' size=70><p>
      Body<br><textarea name=body cols=70 rows=20 wrap=soft>$body</textarea>
      <input type=hidden name=id value='$form{id}'>
      <input type=hidden name=cmd value='save'><p><center>
      <input type=submit value='Save'>
      <input type=reset value='Reset'></td></tr></table>";
    $BODY.="</form>";
}

sub Save_News {
    PrepareSQL("update news set type=?, title=?, body=?, author=? where id=?");
    ExecuteSQL($form{type},$form{title},$form{body},$form{author},$form{id});
}


sub Approve_News {
    PrepareSQL("update news set status=?, response=? where id=?");
    ExecuteSQL('approved',$form{response},$form{id});
}

sub Reject_News {
    PrepareSQL("update news set status=?, response=? where id=?");
    ExecuteSQL('rejected',$form{response},$form{id});
}

sub Browse_News {
    my $offset=$form{offset};
    my @news=();
    my $filter='';
    if ($form{id}=~m/^[0-9]{1,7}$/) {
        $filter=" and id=$form{id}";
    }
    SendSQL("select title,body,author,added,type,source,id from news where status='approved' $filter order by added desc");
    while (my @result=FetchSQLData) {
        my %row=();
        $row{title}=$result[0];
        $row{body}=${OC::Smart_Reformat(\$result[1])};
        $row{author}=$result[2];
        $row{added}=OC::Time_To_Str($result[3],'nice');
        $row{type}=$result[4];
        $row{source}=$result[5];
        $row{id}=$result[6];
        push(@news,\%row);
    }

    $TITLE="News";
    if (scalar @news) {
        my ($color1,$color2)=($CONFIG{color}{table3});
        foreach (@news) {
            my %row=%{$_};
            SendSQL("select fullname from account where username='$row{author}'");
            $row{fullname}=FetchSQLData;
            $row{source}.=" - " if ($row{source} ne '');
            
            my $link='';
            if ($CAN_EDIT) {
                $link="<a href='$self_url/admin?cmd=edit&id=$row{id}'>
                  <img src='$CONFIG{edit_image}' border=0 alt='Click here to edit this block'></a>";
            }

            $BODY.="<b>$row{title}</b> $link<br>";
            $BODY.="<i>$row{added} - $row{source} <a href='$CONFIG{account_url}/$row{author}'>$row{fullname}</a></i>";
            $BODY.="<br>$row{body}<p>";
        }

        if ($form{cmd} ne 'first_page') {
            SendSQL("select count(added) from news where status='approved'");
            my $news_count=FetchSQLData;
            $BODY.="<p>Archive contains $news_count news.";
        }
    } else {
        if ($filter eq '') {
           $BODY.="No news yet..";
        } else {
           $BODY.="News not found..";
        }
    }
}



sub Tmpl_Links {
    my ($screen)=@_;
    @LINKS=();
    if ($CAN_EDIT) {
        my %row=();
        $row{name}="Admin";
        $row{link}="$self_url/admin/" if ($screen ne 'admin');
        push(@LINKS,\%row);
    }
    if ($CAN_ADD) {
        my %row=();
        $row{name}="Add news";
        $row{link}="$self_url?cmd=add_news_screen" if ($screen ne 'add');
        push(@LINKS,\%row);
    }
    if ($CAN_ADD) {
        my %row=();
        $row{name}="Browse";
        $row{link}="$self_url" if ($screen ne '');
        push(@LINKS,\%row);
    }
}


sub Output {
    $template->param(
        links=>\@LINKS,
        title=>$TITLE,
        body=>$BODY,
        no_panel=>1,
    );
    print $template->output;
}

sub First_Page_News {
    my @news=();
    my $filter="OC related";
    $filter="General" if ($ARGV[0] eq '-hw_news');
    SendSQL("select title,body,author,added,type,source from news where status='approved' and type like '\%$filter\%' order by added desc limit 5");
    while (my @result=FetchSQLData) {
        my %row=();
        $row{title}=$result[0];
        $row{body}=${OC::Smart_Reformat(\$result[1])};
        $row{author}=$result[2];
        $row{added}=OC::Time_To_Str($result[3],'nice');
        $row{type}=$result[4];
        $row{source}=$result[5];
        push(@news,\%row);
    }

    if (scalar @news) {
        my ($color1,$color2)=($CONFIG{color}{table3});
        foreach (@news) {
            my %row=%{$_};
            SendSQL("select fullname from account where username='$row{author}'");
            $row{fullname}=FetchSQLData;
            $row{source}.=" - " if ($row{source} ne '');
            $BODY.="<b>$row{title}</b><br>";
            $BODY.="<i>$row{added} - $row{source} <a href='$CONFIG{account_url}/$row{author}'>$row{fullname}</a></i>";
            $BODY.="<br>$row{body}<p>";
        }

    } else {
        $BODY.="No news yet..";
    }
    print $BODY;
}


sub Main {
    Initialize;
    Prepare_Template($CONFIG{tmpl_account_file});
    my ($junk,$cmd)=split(/\//,$ENV{PATH_INFO});
    ConnectToDatabase();
    if ($ARGV[0]=~m!-.._news!) {
        First_Page_News;
        exit;
    }
    print header(-type  =>  'text/html',-charset=>'');
    SendSQL("select username,password,type from account where username='$cookie{username}'");
    my @result=FetchSQLData;
    if (OC::Login($cookie{username},$cookie{password}) ne '') {
        $LOGGED_IN=1;
        if ($result[2] eq 'admin') {
            $CAN_EDIT=1;
            $CAN_ADD=1;
        } elsif ($result[2] eq 'project' || $result[2] eq 'article') {
            $CAN_ADD=1;
        }
    }
    if ($cmd eq 'admin' && $CAN_EDIT) {
        if ($form{approve_news}) {
            Approve_News;
            Show_Queue;
        } elsif ($form{reject_news}) {
            Reject_News;
            Show_Queue;
        } elsif ($form{cmd} eq 'edit') {
            Edit_News;
        } elsif ($form{cmd} eq 'save') {
            Save_News;
            Edit_News;
        } else {
            Show_Queue;
        }
        Tmpl_Links('admin');
    } else {
        if ($form{cmd} eq 'add_news_screen') {
            Tmpl_Links('add');
            Add_News_Screen;
        } elsif ($form{cmd} eq 'add_news') {
            Tmpl_Links('add');
            Add_News;
        } else {
            Tmpl_Links('');
            Browse_News;
        }
    }
    Output;
}

Main;
