#!/usr/bin/perl
##########################################################
# News Script Xtra 05/May/2005
# © 1999-2005 EZscripting.com / Newsscript.co.uk
# Script by Alexandre Golovkine Updated by Babelnotes.be
##########################################################
# Instructions: http://www.newsscript.co.uk/instructions/
# FAQ:          http://www.newsscript.co.uk/faq/
# Help Forum:   http://www.newsscript.co.uk/helpforum/
##########################################################
my $script_name                   = 'http://www.gylling.no/cgi-bin/forside.pl';
my $databasefile                  = "news.txt"; 
my $idField	                  = "ID";
my $image_dir                     = "../nyhetsbilder";              
my $image_url                     = "http://www.gylling.no/nyhetsbilder";       
my $html_template                 = "forsidenyheter.htm";        
my $record_template               = "nyhet1.htm";
my $admin_mode                    = 'admin';             
my $select_image                  = 1;
my $add_fields                    = 1;
my $hspace                        = 9;
my $vspace                        = 2;
my $Username                      = 'gylling';
my $Password                      = 'sunwind';
my $not_found                     = '<b>Ingen resultater funnet</b><br><br><br>';
my $news_up                       = 1;
my $newstarget                    = "_self";
##########################################################
# Page Selector
my $textPrevious                  = "Forrige";
my $textNext                      = "Neste";
my $pageSelectorRange             = 10;
my $records_per_page              = 7;
##########################################################
# Scrolling News Headlines
my $Number_of_headlines_to_scroll = 5;
my $speed                         = 4;
my $bgcolor                       = "#eeeeee";
##########################################################
# News letter
my $Number_of_news                = 10;
my $head_news_separator           = "<hr noshade color=#000000><br>";
my $news_news_separator           = "<hr noshade color=#000000><br>";
##########################################################
# Search Term Highlighting
my $highLighting                  = 1;
my @highLightColors               = ("#FFFF00", "#FF0000", "#00FFFF", "#00FF00", "#C0C0C0");
##########################################################
# Pure HTML tag
my $start_pure_html               = '<purehtml>';
my $end_pure_html                 = '</purehtml>';
##########################################################
# Ordering
my $order                         = "123";      # abc, cba, 123 or 321     
my $order_by                      = "headline"; # fieldname on which to order
##########################################################
# RSS Feed
my $usefeeds                      = 1;
my $feed                          = "../forside/rss.xml";
my $feed_title                    = "Nyheter fra Gylling Teknikk";
my $feed_description              = "Følg med hva som skjer hos Gylling Teknikk AS";
########################################################## 
# EZscripting.com © 1999 - 2005
# The scripts are available for private and commercial use
# Once purchased this script can be used in any website you build personally
# You may not sell the script in any format to anybody    
# The scripts may only be distributed by EZscripting.com
# Do not post or email all or part of the this code in any form whatsoever
# The redistribution of modified versions of the scripts is prohibited
# EZscripting.com accepts no responsibility or liability
# whatsoever for any damages however caused when using our services or scripts
# By downloading and using this script you agree to the terms and conditions
##########################################################

use CGI qw/:standard/;

$FORM{mode}=param('mode');
$FORM{record}=param('record');
$FORM{login}=param('login');
$FORM{password}=param('password');
$FORM{action}=param('action');
$FORM{new_field}=param('new_name');
$FORM{action}="default" if !$FORM{action};
$FORM{headlines} = param('headlines');
$FORM{search}=param('search');
$FORM{method}=param('method');
$FORM{field}=param('field');
#$FORM{order} = param('order');
#$FORM{order_by} = param('order_by');
$FORM{order} = $order;      
$FORM{order_by} = $order_by;

$page=param('page')+1;
$default_mode=1 if param('mode') eq 'shtml';
$default_mode=2 if param('mode') eq 'newsletter';
$default_mode=3 if param('mode') eq 'scrollingnews';

my @field_name = ();

#check password

if($Username && $FORM{mode} eq $admin_mode){
	%COOKIES = get_cookie('USER_Login');
	if($FORM{login}){
		if($FORM{password} eq $Password && $FORM{login} eq $Username){
			print "Set-Cookie: USER_Login=login&$FORM{login}&pass&$FORM{password}; path=/\n";
			print "Location: $script_name?mode=$admin_mode\n\n";
			exit;
		}
		else{print "Content-type: text/html\n\n";  error("Feil brukerdata !");}
	}
	elsif(!$COOKIES{login}){promt();}
	elsif($COOKIES{pass} ne $Password or $COOKIES{login} ne $Username){promt();}
}
if($FORM{action} eq 'logout'){
	print "Set-Cookie: USER_Login=login&boerkenaas&pass&boerkenaas; path=/\n";
	print "Location: $script_name\n\n";
	exit;
}

sub CheckAdminMode {
   if ($FORM{mode} ne $admin_mode) {
      error("You need to be logged in!");
      exit (1);
   }
}

print "Content-type: text/html\n\n" unless $FORM{action} eq 'delete';
create_db() unless -f $databasefile;
my $txt;
%SUB = (
	default=> \&default,
	main   => \&main,
	add    => \&add,
	save   => \&save,
	logout => \&logout,
	delete => \&delete,
	update => \&update,
	view   => \&view,
	show   => \&show,
        refresh_feed => \&refresh_feed,
	add_field    => \&add_field
	);

$SUB{$FORM{action}}->();
html_text($txt);
exit;
##########################################################
sub read_file{
	open(F, $_[0]) || error("Can't open file $_[0]!");
	my @data = <F>;
	close F;
	return @data;
}
sub read_base{
	my @content;
	my @data = read_file("$databasefile");

	chomp $data[0];
	@field_name=split('\|',$data[0]);
	my $p=0; my $idPosition=-1;
	foreach(@field_name){
		$idPosition = $p if $_ eq $idField;
		$show_position=$p if $_ eq 'show'; $p++;
	}
	error ('Old style database, please use dbconvert.pl first!') if $idPosition<0;
	error('Bad database file') if @field_name<1;
	
	$word = $FORM{search};
        $field = $FORM{field};
        $method = $FORM{method};
	my @keys;
	$position=-1; 
	$p=0;
	if($field){foreach(@field_name){if($_ eq $field){$position=$p; last;}$p++;}} 
	
	if($word=~m/\A"(.*)"\Z/){$keys[0]=$1;}
	elsif(!$action and ($method eq "perfect" or $method eq "exact")){$keys[0]=$word;}
	else{@keys= split(" ", $word);}
	my $b =0;
	for(1..@data-1){
		chomp $data[$_];
		@line=split('\|',$data[$_]); 
		my $a=0;
		if($_[0] == 1){
			if($line[$show_position] eq 'Ja'){
				if(@keys){
				    if($field && $position>-1){
					my $found=0;
					foreach $word (@keys){
						if($method eq "perfect"){if ($line[$position]  eq $word){$found=1; last;} }
						elsif($line[$position] =~m/$word/i){$found=1; last;} 
					}
					if($found){
						$content->[$b]->{'record'} = $line[0];
						foreach $name (@field_name){$content->[$b]->{$name} = $line[$a++];}
						$b++;
					}				    
				    }
				    else{
					my $found=0;
					foreach $word (@keys){
						foreach $value (@line){
							if($method eq "perfect"){if($value eq $word){$found=1; last;}} 
							elsif($value=~m/$word/i){$found=1; last;} 
						}
					}
					if($found){
						$content->[$b]->{'record'} = $line[0];
						foreach $name (@field_name){$content->[$b]->{$name} = $line[$a++];}
						$b++;
					}
				    }	
				}
				else{
					$content->[$b]->{'record'} = $line[0];
					foreach $name (@field_name){$content->[$b]->{$name} = $line[$a++];}
					$b++;
				}
			
			}
			
		}
		else{
			$content->[$_]->{'record'} = $line[0];
			foreach $name (@field_name){$content->[$_]->{$name} = $line[$a++];}
		}
		                
	} 
	return $content;
}
sub order{
	my @new=();
        my $valid_fieldname = 0;
        my $orderfield = $FORM{order_by};
        my $field = "";
        my $entry;
        
        chomp($orderfield);                             
        my @fields = @field_name;
 	foreach $field(@fields)
        { 
          if ($field eq $orderfield)
          {
            $valid_fieldname = 1;
          }; 
        };
        if ($valid_fieldname)
        {
          if ($FORM{order} eq '123' or $FORM{order} eq '321')
          {
            @new = sort { $a->{$orderfield} <=> $b->{$orderfield} } @data;
            if ($FORM{order} eq '321') { @new = reverse @new; }
          }
          if ($FORM{order} eq 'abc' or $FORM{order} eq 'cba')
          {                                         
            @new = sort { uc($a->{$orderfield}) cmp uc($b->{$orderfield}) } @data;
            if ($FORM{order} eq 'cba') { @new = reverse @new; }
          }
        }
        else
        {
          print "Error : invalid field name <b>$orderfield</b> specified";
        }
        
 	return @new;
}
sub get_record{
	my $text = $_[0]; 
	$text =~ s{\[\[(.*?)\]\]}{exists($INSERT{$1}) ? $INSERT{$1} : ""}gsex;
	return $text;
}
sub get_html{
	my @txt = read_file($_[0]);
	foreach(@txt){$txt.=$_;}
	$txt=~/(.*)<template>(.*)<\/template>(.*)/s;
	error("Template-tag not found!") if !$1 or !$2;
	return ($1,$2,$3);
}
sub create_db{
	open(F, ">$databasefile") || error ("Can't create DB-file!");
	print F "$idField|date|headline|short_text|text|image|image_align|image2|image_align2|show\n";
	close F;
}
sub default{
	$records=$FORM{'headlines'};
	if($FORM{mode} eq $admin_mode){main(); return;}
	record($FORM{record}) if $FORM{record};
	show() unless $default_mode;
	
	
	if($default_mode ==3){
		$records=$Number_of_headlines_to_scroll;
	}
	elsif($default_mode ==2){
		($head2, $tmp2, $foot2) = get_html($record_template);
		$records=$Number_of_news;
	}
	$data=read_base(1);
	if($news_up){@data = reverse @$data;}
	else{@data =  @$data;}
        if($FORM{order} || $FORM{order_by})
        { 
          @sorteddata = order(); 
        }
        else
        { 
          @sorteddata = @data; 
        }
	$records=@sorteddata if $records > @sorteddata;
	$records=@sorteddata if !$records;
	$sorteddata =\@sorteddata; my $txt;
	($head, $tmp, $foot) = get_html($html_template);
	
	for(0..$records-1){
		%INSERT={};
		foreach $name (@field_name){$INSERT{$name}=$sorteddata->[$_]->{$name};}
		$INSERT{image} = "<img src=\"$INSERT{image}\" border=0 align=$INSERT{image_align} hspace=$hspace vspace=$vspace>" if $INSERT{image};
		$INSERT{image2} = "<img src=\"$INSERT{image2}\" border=0 align=$INSERT{image_align2} hspace=$hspace vspace=$vspace>" if $INSERT{image2};
		if($INSERT{text} ne ''){
			#$INSERT{image} = "<img src=\"$INSERT{image}\" border=0 align=$INSERT{image_align} hspace=$hspace vspace=$vspace>" if $INSERT{image};
			$INSERT{more} = "&nbsp;&nbsp;<a href=$script_name?record=".$sorteddata->[$_]->{'record'}." target=\"$newstarget\">Les mer...</a>";
			
		}
		if ($default_mode ==2){
			$INSERT{headline} = "<a name=\"news$_\">$INSERT{headline}</a>";
		 	$down.= get_record($tmp2)."<p align=right><a href=\"#top\">Top</a></p>$news_news_separator";
			$INSERT{headline} =~s/name="news$_"/href="#news$_"/s;	
			$INSERT{more} = "&nbsp;&nbsp;<a href=\"#news$_\">More</a>";
		}
		elsif ($default_mode ==3){$marquee.=" <a href=$script_name?record=".$sorteddata->[$_]->{'record'}." target=\"$newstarget\">$INSERT{headline}</font></a> &nbsp;&nbsp;&nbsp;";}
		else{$INSERT{headline} = "<a href=$script_name?record=".$sorteddata->[$_]->{'record'}." target=\"$newstarget\">$INSERT{headline}</a>" if $INSERT{text} ne '';}
		
		$result.= get_record($tmp);
		
	}
if($default_mode ==3){$result="<marquee scrollamount=$speed  bgcolor=$bgcolor>$marquee</marquee>";} 
print $result;
print $head_news_separator.$down if $default_mode ==2;
exit;	
}

sub record{
	$recordID = shift;
	$data=read_base();
	($head, $tmp, $foot) = get_html($record_template);
	
	for(@$data){
		if($_->{record} eq $recordID){
			foreach $name (@field_name){$INSERT{$name}=$_->{$name};}
			last;
		}
	}
	
	
	
	
	
	$INSERT{image} = "<img src=\"$INSERT{image}\" border=0 align=$INSERT{image_align} hspace=$hspace vspace=$vspace>" if $INSERT{image};
	$INSERT{image2} = "<img src=\"$INSERT{image2}\" border=0 align=$INSERT{image_align2} hspace=$hspace vspace=$vspace>" if $INSERT{image2};
	$result = get_record($tmp);

print get_record($head), $result, $foot;
exit;
}
sub add_field{
        CheckAdminMode();
	$data=read_base();
	$txt .= qq|<table width=1000><tr><th class=of colspan=4>Nyhetsoversikt for Gylling Teknikk AS</th></tr><tr><td colspan=4 align=right>
		
		<a href=$script_name?mode=$admin_mode>Tilbake til hovedside</a>|;
	$txt .= qq|	<a href=$script_name?mode=$admin_mode&action=logout>Logg ut</a></td></tr>
		<tr><td colspan=4>&nbsp;</td><tr>
		<tr><th class=of colspan=4>Add new field in database</th><tr>|;
	
	if($FORM{new_field}){
		add_new_field($FORM{new_field});
		$txt.= qq|<td colspan=4 align=center><br><br><br>Field &lt;<b>$FORM{new_field}</b>&gt; has added!</td>|;}
	else{
		$txt.= qq|
		  <form action=$script_name>
		  <input type=hidden name=mode value=$admin_mode>
		  <input type=hidden name=action value=add_field>|;
		  
		$txt.= qq|<input type=hidden name=password value=$FORM{password}>
		  <input type=hidden name=login value=$FORM{login}>| if $FORM{login};
		$txt.= qq|  <tr><td colspan=2>Field name:</td><td colspan=2><input type=text name=new_name></td></tr>
		  <tr><td colspan=4 align=center><input type=submit value="[ submit ]"> <input type=reset value="[ reset ]"></td>
		  </form>
		|;
	}
	$txt.="</tr></table>\n";
return;
}
sub add_new_field{
        CheckAdminMode();
	my @data = read_file("$databasefile");
	my $name = shift;
	$name =~ s/ /_/g; 
	my $a=0;
	chomp $data[0];
	@fields = split('\|', $data[0]);
	foreach(@fields){
		error("Field &lt;<i>$name</i>&gt; already use in database!") if $name eq $_;
	}
	foreach (@data){
		chomp $data[$a];
		$data[0].="|".$name."\n" if $a==0;
		$data[$a].="|\n" if $a!=0;
		$a++;
	}
	open (F, ">$databasefile") || error("Can't open file for alter table");
	print F join ("", @data);
	close F;
}

sub not_in_tag
{
  (my $string) = @_;
  
  my @arr = split(//, $string);
  my $num_tag_open = grep(/</, @arr);
  my $num_tag_close = grep(/>/, @arr);
  
  return ($num_tag_open == $num_tag_close);
}


sub iindex {
   (my $string, my $searchingfor) = @_;

   my $idx = index(uc($string), uc($searchingfor));
   if ($idx >= 0)
   {
     $_[1] = substr($string, $idx, length($searchingfor));
   }
   return $idx;
}


sub show{
        my $searchTerms;

	$data=read_base(1);
	($head, $tmp, $foot) = get_html($html_template);
	my $a=0;
	if($news_up){@data = reverse @$data;}
	else{@data =  @$data;}
        if($FORM{order} || $FORM{order_by})
        { 
          @sorteddata = order(); 
        }
        else
        { 
          @sorteddata = @data; 
        }        
        
        ## do search term highlighting
        my $rec;
        my $searchRec = $FORM{search};
        my $searchField = "";
        if ($searchRec)    { $searchField  = "&search=$FORM{search}";  }
        if ($FORM{field})  { $searchField .= "&field=$FORM{field}";   }
        if ($FORM{method}) { $searchField .= "&method=$FORM{method}"; }
        $searchTerms = $searchRec;
        if ($highLighting) 
        {
          foreach $rec(@sorteddata)
          {
            my @terms = split(/\s/, $searchTerms);
            my $term; 
            my $cnt = 0;
            foreach $term(@terms)
            {
              my $colorIndex = $cnt % (@highLightColors);
              my $highLightColor = $highLightColors[$colorIndex];
              my $fronthl = '<span style="background-color: '.$highLightColor.'">';
              my $endhl = '</span>';
              
              my $part;
              foreach $part(($rec->{'headline'}, $rec->{'short_text'}))
              {
                my $temp1 = $part;
                my $temp2 = "";
                my $oldindex = 0;
                my $i = iindex($temp1, $term);
                $pos_in_tot_string = $i;
                while ($i >= 0) 
                {
                   my $pre = substr($temp1, 0, $i);
                   $temp2 .= $pre;
                   if (not_in_tag(substr($part, 0, $pos_in_tot_string)))
                   {
                     $temp2 .= $fronthl.$term.$endhl;
                   }
                   else 
                   {
                     $temp2 .= $term;
                   }
                   $temp1 = substr($temp1, $i+length($term));
                   $oldindex = $i;
                   $i = iindex($temp1, $term);
                   $pos_in_tot_string = length($temp2) + $i;
                }
                $temp2 .= $temp1;
                $part = $temp2;
              } 
              $cnt++;
            }
          }
        }
        ## end ST highlighting

        
	$sorteddata =\@sorteddata; my $txt;
	$page = param('page');	
	$show_records = @sorteddata;
	$records_per_page = $FORM{headlines} if $FORM{headlines};
	$start = $page*$records_per_page;
	$end = $start + $records_per_page-1;
	$end = $show_records-1 if $end>$show_records-1;
	
	for($start..$end){
			%INSERT={};
			foreach $name (@field_name){$INSERT{$name}=$sorteddata->[$_]->{$name};}
			$INSERT{image} = "<img src=\"$INSERT{image}\" border=0 align=$INSERT{image_align} hspace=$hspace vspace=$vspace>" if $INSERT{image};
			$INSERT{image2} = "<img src=\"$INSERT{image2}\" border=0 align=$INSERT{image_align2} hspace=$hspace vspace=$vspace>" if $INSERT{image2};
			if($INSERT{text} ne ''){
				$INSERT{more} = "&nbsp;&nbsp;<a href=$script_name?record=$sorteddata->[$_]->{'record'} target=\"$newstarget\">Les mer...</a>";
				$INSERT{headline} = "<a href=$script_name?record=$sorteddata->[$_]->{'record'} target=\"$newstarget\">$INSERT{headline}</a>";
			}
			$result.= get_record($tmp);
	}

	$heads = "&headlines=$FORM{headlines}" if $FORM{headlines};
	
        #set page selector
	$INSERT{records} = @sorteddata-1;
	$INSERT{page_selector} = "";  
        $INSERT{page_selector}= "<a href=\"$script_name?page=".($page-1)."$searchField&action=show"."$heads\"\">$textPrevious</a>" if $page>0;
	my $pageStart=0;
	my $pageEnd = 0;
	$pageEnd = $INSERT{records}/$records_per_page if $records_per_page;
	
	if($pageSelectorRange){
		$pageStart=$page- int($pageSelectorRange/2) if $page- int($pageSelectorRange/2)>0;
		if($page<int($pageSelectorRange/2)){$pageEnd=$pageSelectorRange if $pageSelectorRange < $pageEnd;}
		else{$pageEnd=$page+ int($pageSelectorRange/2) if $page+ int($pageSelectorRange/2)<$pageEnd;}
	}
	
	for($pages=$pageStart; $pages <= $pageEnd; $pages++){
		$p=$pages+1;
		
		if($page==$pages){$INSERT{page_selector}.= " $p ";}
		else{$INSERT{page_selector}.= qq| <a href="$script_name?page=$pages$searchField&action=show|.qq|$heads">$p</a>|;}
		
	}  
	
	$INSERT{page_selector}.= " <a href=\"$script_name?page=".(1+$page)."$searchField&action=show"."$heads\"\">$textNext</a>" if  $page < $INSERT{records}/$records_per_page-1 && $records_per_page>1;

	$INSERT{search}.=param('search');
	$foot = get_record($foot);
	$head = get_record($head);
	$result = $not_found unless @sorteddata;
	print $head, $result, $foot;
	exit;
}

sub main{                                                                                                                                              
	$data=read_base();
	$txt .= qq|<table width=1000><tr><th class=of colspan=4>Nyhetsoversikt for Gylling Teknikk AS</th></tr><tr><td colspan=4 align=right><a href=$script_name?mode=$admin_mode&action=add>Lag ny nyhet</a>|;
        if ($usefeeds) {$txt .= qq| <a href=$script_name?mode=$admin_mode&action=refresh_feed>Oppdater/refresh feed</a>|;}
	$txt .= qq| <a href=$script_name?mode=$admin_mode&action=add_field>Legg til nytt felt</a>| if $add_fields;	
	$txt .= qq|	<a href=$script_name?mode=$admin_mode&action=logout>Logg ut</a></td></tr>
		<tr class=on><th class=of width=120>Valg</th><th class=of width=130>Dato</th><th class=of width=400>Overskrift</th><th class=of width=80>Vis på nyhetsside</th></tr>|;
		$start=1; $end=@$data-1;
		
		if($news_up){
			foreach($i=$end; $i>=$start;$i--){
				$txt.= qq|<tr class=off><td align=center valign=top><a href=$script_name?mode=$admin_mode&action=delete&record=$data->[$i]->{'record'} onclick="return confirm('Delete record: «$data->[$i]->{headline}»')">Slett</a> 
				<a href=$script_name?mode=$admin_mode&action=update&record=$data->[$i]->{'record'}>Redigér</a> 
				<a href=$script_name?mode=$admin_mode&action=view&record=$data->[$i]->{'record'}>Se på</a></td><td valign=top>$data->[$i]->{'date'}</td><td>$data->[$i]->{'headline'}</td>|;
				$txt.= qq|<td align=center>$data->[$i]->{'show'}</td>|;
				$txt.= qq| </tr>|;
			}
		}
		else{
			for($start..$end){
				$txt.= qq|<tr class=off><td align=center valign=top><a href=$script_name?mode=$admin_mode&action=delete&record=$data->[$i]->{'record'} onclick="return confirm('Delete record: «$data->[$_]->{headline}»')">Slett</a> 
				<a href=$script_name?mode=$admin_mode&action=update&record=$data->[$i]->{'record'}>Redigér</a> 
				<a href=$script_name?mode=$admin_mode&action=view&record=$data->[$i]->{'record'}>Se på</a></td><td valign=top>$data->[$_]->{'date'}</td><td>$data->[$_]->{'headline'}</td>|;
				$txt.= qq|<td align=center>$data->[$_]->{'show'}</td>|;
				$txt.= qq| </tr>|;
			}
		}
	$txt.="</table>\n";	

}
sub view{
	$data=read_base(); my $a=0;
	$length = @$data-1;
	$current = $FORM{record};
	my $recData = {};
	my @Indexes; my $i=0; my $index;
	for(@$data){
		if($current==$_->{'record'}){
			$recData = $_;
			$index=$i;
		}
		push @Indexes, $_->{'record'};
		$i++;
	}
	
	
	$txt .= qq|<table width=1000><tr><th class=of colspan=2>Nyhetsoversikt for Gylling Teknikk AS</th></tr><tr><td colspan=4 align=right><a href=$script_name?mode=$admin_mode>Tilbake til hovedside</a> <a href=$script_name?mode=$admin_mode&action=logout>Logg ut</a></td></tr>|;
	$txt .= qq|<tr><td class=of colspan=2 align=left>&nbsp;&nbsp; <b>Nyhet#$current av $length</b> [<a href=$script_name?mode=$admin_mode&action=add>Lag ny nyhet</a>] [ <a href=$script_name?mode=$admin_mode&action=update&record=$FORM{record}>Redigér</a> ] </td></tr>
			<tr class=off><td width=100>Dato:</td><td width=488>$recData->{'date'}</td></tr>
			<tr class=off><td>Overskrift:</td><td>$recData->{'headline'}</td></tr>
			<tr class=off><td valign=top>Forside-tekst:</td><td>$recData->{'short_text'}</td></tr>
			<tr class=off><td valign=top>Tekst:</td><td>$recData->{'text'}</td></tr>|;
	$txt .= qq|	<tr class=off><td valign=top>Hovedbilde:</td><td><img src="$recData->{'image'}" border=0 alt"$recData->{'image'}" align="$recData->{'image_align'}"></td></tr>| if $recData->{'image'};
	

	$txt .= qq|	<tr class=off><td valign=top>Vis nyhet:</td><td>$recData->{'show'}</td></tr>|;
	
	if($add_fields){
		for(10..@field_name-1){$txt .= qq|<tr class=off><td valign=top>$field_name[$_]:</td><td>$recData->{$field_name[$_]}</td></tr>\n|;}
	}
	
	$txt .= qq|	<tr class=off><td colspan=2>&nbsp;&nbsp;|;
	$txt .= qq|&lt;&lt; <a href="$script_name?mode=$admin_mode&action=view&record=|.($Indexes[$index-1]).qq|">forrige</a> | unless $index==1;
	for(1..@Indexes-1){
		$txt .= qq| [|;
		$txt .= qq|<a href="$script_name?mode=$admin_mode&action=view&record=$Indexes[$_]">| unless $_ eq $FORM{record};
		$txt .= qq|$_|;
		$txt .= qq|</a>| unless $_ eq $FORM{record};
		$txt .= qq|] |;
	}
	$txt .= qq|&nbsp; <a href="$script_name?mode=$admin_mode&action=view&record=|.($Indexes[$index+1]).qq|">neste</a> &gt;&gt;| if $index<$length;
	$txt .= qq|</td></tr></table>|;

}
sub save_image{
	$file=param($_[0]);
	$file =~m/([^\\\/]*\.\w*\Z)/i;
	$filename=$1; 
	open(FILE,">$_[1]/$1") || error("Can't save image file!");
	binmode FILE; 
	while ($bytesread=read($file,$buffer,1024)) {print FILE $buffer;} 
	close(FILE);
        return "$filename"; 
}
sub save{
        CheckAdminMode();
	$data = read_base();
	#find position:
	my $pos =0; my $i;
	for(@$data){
		if($FORM{record} eq $_->{'record'}){$pos=$i;}
		$maxId = $_->{'record'} if $_->{'record'}>$maxId;
		$i++;
	}
	$maxId++;
	my $new_record;
	foreach(@field_name){
		my $text;
		if($_ eq $idField){
			$text.= $FORM{record}? $FORM{record}:$maxId;
		}
		elsif($_ eq 'image' && param('image') ne ''){
			$dir = $image_dir; $text = $image_url."/";
			$text .= save_image($_, $dir);
		}
		elsif($_ eq 'image' && param('_image')){$text .=param('_image');}
		elsif($_ eq 'image' && param('set_image')){$text .="$image_url/".param('set_image');}
		elsif($_ eq 'image2' && param('image2') ne ''){
			$dir = $image_dir; $text = $image_url."/";
			$text .= save_image($_, $dir);
		}
		elsif($_ eq 'image2' && param('_image2')){$text .=param('_image2');}
		elsif($_ eq 'image2' && param('set_image2')){$text .="$image_url/".param('set_image2');}
		elsif($_ eq 'show'){$text=param($_); $text="Nei" unless param($_);}
		else{
			$text=param($_);
                        $text=~s/\r//g;
			$text=~s/\|/I/g;
                        if ($_ eq 'text') 
                        {
                          my @split_text = split(/\n/, $text);
                          my $nobreaks = 0;
                          my $line;
                          foreach $line(@split_text)
                          {
                            if ($line =~/$start_pure_html/) { $nobreaks = 1;}
                            if ($line =~/$end_pure_html/) { $nobreaks = 0;}
                            if (!$nobreaks) { $line .= '<br>';}
                          }
                          $text = join(//,@split_text);
                        }
                        else { $text=~s/\n/<br>/g; }
                        
		}
		$new_record .= $text."|";
	}  
	chop $new_record;
	$new_record .= "\n";
	if(param('record')){
		open (F, "$databasefile") || error("Can't open databasefile!");
		@data = <F>;
		close F;	
		$data[$pos] = $new_record;	
		open (F, ">$databasefile") || error("Can't open databasefile!");
		foreach(@data) {print F }
		close F;
	}
	else{
		open (F, ">>$databasefile") || error("Can't open databasefile!");
		print F $new_record;
		close F;
	}
        if ($usefeeds) { make_feed(); }
	main();
}
sub delete{
        CheckAdminMode();
	$data=read_base();
	my $pos=-1; $i;
	for(@$data){
		if($FORM{record}==$_->{'record'}){
			$pos=$i;
			last;
		}
		$i++;
	}
	if($FORM{record}){
		open (F, "$databasefile") || error("Can't open databasefile!");
		@data = <F>;
		close F;	
		$data[$pos] = "";	
		open (F, ">$databasefile") || error("Can't open databasefile!");
		foreach(@data) {print F }
		close F;
	}
        if ($usefeeds) {make_feed();}
	print "Location: $script_name?mode=$admin_mode\n\n";
	exit;
}
sub add{ CheckAdminMode();
	$data=read_base();
	my $recData = {};
	for(@$data){
		if($_[0]==$_->{'record'}){
			$recData = $_;
			last;
		}
	}
	
	if ($_[0]){
		$hidden=qq|<input type=hidden name=record value=$_[0]>|;
		
		$recData->{'short_text'}=~s/<br>/\n/g;
		$recData->{'text'}=~s/<br>/\n/g;
		$image = "<input type=checkbox name=_image value=$recData->{'image'} checked><a href=$recData->{'image'} target=_blank>$recData->{'image'}</a><br>" if $recData->{'image'};
		$image2 = "<input type=checkbox name=_image2 value=$recData->{'image2'} checked><a href=$recData->{'image2'} target=_blank>$recData->{'image2'}</a><br>" if $recData->{'image2'};
	
	}
	if($select_image){
		opendir(DIR, "$image_dir");
		foreach(readdir DIR)
		{
			$img_select.="<option>$_</option>\n" if -f "$image_dir/$_" && $_=~m/.\gif|.\jpg/i;
		}
		close DIR;
		$img_select1 = "<br><select name=set_image><option value=''>eller velg bilde</option>$img_select</select>";
		$img_select2 = "<br><select name=set_image2><option value=''>eller velg bilde</option>$img_select</select>";
	
	}
	$show = "checked" unless $recData->{'show'} eq "No";
	$left = "selected" if $recData->{'image_align'} eq "left";
	$center = "selected" if $recData->{'image_align'} eq "center";
	$right = "selected" if $recData->{'image_align'} eq "right";
	$left2 = "selected" if $recData->{'image_align2'} eq "left";
	$center2 = "selected" if $recData->{'image_align2'} eq "center";
	$right2 = "selected" if $recData->{'image_align2'} eq "right";	
	$hidden.= qq|<input type=hidden name=password value=$FORM{password}>
		  <input type=hidden name=login value=$FORM{login}>| if $FORM{login};
	
	$txt .= qq|<table width=1000<tr><th class=of colspan=2>Nyhetsoversikt for Gylling Teknikk AS</th></tr><tr><td colspan=4 align=right><a href=$script_name?mode=$admin_mode>Tilbake til hovedside</a> <a href=$script_name?mode=$admin_mode&action=logout>Logg ut</a></td></tr>|;
	$txt .= qq|<form action=$script_name method=post  name=myform ENCTYPE="multipart/form-data">
		<input type=hidden name=mode value=$admin_mode>
		<input type=hidden name=action value=save>$hidden
			<tr class=off><td><b>Dato:</b></td><td><input name=date value="$recData->{'date'}"></td></tr>
			<tr class=off><td><b>Overskrift:</b></td><td><input name=headline size=75  value="$recData->{'headline'}"></td></tr>
			<tr class=off><td><b>Utvidet overskrift:</b><br>(Blir plassert over evnt. bilde, men er ikke påkrevet)</td><td><textarea name=short_text rows=4 cols=100>$recData->{'short_text'}</textarea></td></tr>
			<tr class=off><td><b>Hovedtekst:</b><br>(blir plassert under evnt. bilde og <b>må fylles ut</b>)</td><td><textarea name=text rows=24 cols=100>$recData->{'text'}</textarea></td></tr>|;
			$txt .= qq|	<tr class=off><td valign="top"><b>Last opp bilde:</b></td><td>$image<input type=file name=image>$img_select1</td></tr>
			<tr class=off><td><b>Bilde-plassering:</b></td><td><select name=image_align><option $left>Venstre<option $center>Midten<option $right>Høyre</select></td></tr>
				
		        <tr class=off><td colspan=2><input type=checkbox name=show value="Ja" $show>Vis denne nyheten.</td></td></tr>|;
			
	if($add_fields){
		for(10..@field_name-1){$txt .= qq|<tr class=off><td valign=top>$field_name[$_]:</td><td><input type=text name="$field_name[$_]" value="$recData->{$field_name[$_]}"></td></tr>\n|;}
	}			
			
	$txt .= qq|	<tr class=off><td colspan=2 align=center><input type=submit value=" [ submit] "> <input type=reset value=" [ reset] "></td></tr></table></form></center>|;
}

sub update{
 CheckAdminMode();
 add($FORM{record});
 }


sub get_cookie{
my %COOK;# print $ENV{HTTP_COOKIE};
	@cookies=split('; ',$ENV{HTTP_COOKIE});
	foreach $line (@cookies){
		($c_name, $c_value) = split(/=/,$line,2);
		if ($c_name eq $_[0]){
			@cook=split(/&/,$c_value);
			for($a=0; $a<@cook; $a+=2){
				$cook[$a+1] =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
				$COOK{$cook[$a]}=$cook[$a+1];
			}
		}
	}
	return %COOK;
}
sub promt{
	print "Content-Type: text/html\n\n";
	print <<EOF;
	<br><br><br><br><center><form method=post action=$script_name>
	<input type=hidden name=mode value=$admin_mode>
	<table border=0 width=280>
	  <tr><th colspan=2 class=of>Nyhetsoversikt Gylling Teknikk - Logg inn:</th></tr>
	  <tr class=on><td width=43% align=right>Logg inn: </td>
	      <td width=57%><input type=text name=login size=13></td></tr>
	  <tr class=on><td align=right>Passord: </td>
	      <td><input type=password name=password size=13></td></tr>
	  <tr class=on><td colspan=2 align=center><input type=submit></td></tr>
	</table></form></center>
EOF
	exit;
}
sub error{
	html_text ("<br><br><br><center><font color=red><h3>$_[0]</h3></font></center>\n");
	exit;
} 
sub html_text{
	print qq|<html>
		<head>
		<title>NewsScript.co.uk - News Content Management System</title>
		<style>
			tr,td,body {font-family: Tahoma, Arial; font-size:10pt;}  
			.of {border-style:solid; border-width: 1; border-color : #999999; background-color:#dddddd}
			.on {border-style:none;background-color:#ddeedd}
			.off {border-style:none;background-color:#f3f3f3}
		</style>
		</head>
		<body>
		$_[0]
		</body></html>|;
}

sub refresh_feed {
   CheckAdminMode();
   make_feed();
   main();
}

sub make_feed {
   CheckAdminMode();
   $data=read_base(1);
   @data =  @$data;
   @data = reverse @data if $reverse_feed;
   my $feedout = "";

   $feedout .= <<EOF;
<?xml version="1.0" encoding="iso-8859-1" ?>
<rss version="2.0">
     <channel>
       <title>$feed_title</title>
       <link>$script_name</link>
       <description>$feed_description</description>
      
EOF
       
   my $rec;  my $cnt = 1;
   foreach $rec(@data)
   {
      if ($rec->{'show'} eq 'Yes') 
      {
         my $shorttext = $rec->{'short_text'};
         $shorttext =~ s/<br>//g;
         $feedout .= <<EOF;
         <item>
           <title>$rec->{'headline'}</title>
	     <link>$script_name?record=$rec->{$idField}</link>
           <description>$shorttext</description>
<guid>$script_name?record=$rec->{$idField}</guid>

</item>

EOF
      }
      $cnt++;
   }
   $feedout .= <<EOF;
   
</channel>
   </rss>
EOF
  
  open(FEED, "> $feed") || error("Cannot create rss feed $feed");
  print FEED $feedout;
  close(FEED)
}

sub load_includes {
   return 1 if ($use_includes == 0);
   my @incs = keys(%INCL);  my $key;  my $retval = 1;
   foreach $key(@incs)
   {
     open(INCF, "< $INCL{$key}") or ($retval = 0);
     my @incfile = <INCF>; close(INCF);
     $INCL{$key} = join('', @incfile);
   }
   return $retval;
}


##########################################################
# EZscripting.com © 1999 - 2005
# The scripts are available for private and commercial use
# Once purchased this script can be used in any website you build personally
# You may not sell the script in any format to anybody
# The scripts may only be distributed by EZscripting.com
# Do not post or email all or part of the this code in any form whatsoever
# The redistribution of modified versions of the scripts is prohibited
# EZscripting.com accepts no responsibility or liability
# whatsoever for any damages however caused when using our services or scripts
# By downloading and using this script you agree to the terms and conditions
##########################################################
