#webliberty::App::Rss.pm (2006/02/18)
#Copyright(C) 2002-2006 Knight, All rights reserved.

package webliberty::App::Rss;

use strict;
use base qw(webliberty::Basis);
use webliberty::Rss;
use webliberty::App::Diary;

### コンストラクタ
sub new {
	my $class = shift;

	my $self = {
		init   => shift,
		config => shift,
		query  => shift,
		html   => undef
	};
	bless $self, $class;

	return $self;
}

### メイン処理
sub run {
	my $self = shift;

	$self->output;

	return;
}

### RSS表示
sub output {
	my $self = shift;

	if (!$self->{config}->{site_url}) {
		my $diary_ins = new webliberty::App::Diary($self->{init}, $self->{config}, $self->{query});
		$self->error('サイトのURLが設定されていません。');
	}

	opendir(DIR, "$self->{init}->{data_dir}$self->{init}->{data_diary_dir}") or $self->error("Read Error : $self->{init}->{data_dir}$self->{init}->{data_diary_dir}");
	my @dir = sort { $b <=> $a } readdir(DIR);
	closedir(DIR);

	my $info_script;
	if ($self->{init}->{script_file} =~ /([^\/\\]*)$/) {
		$info_script = "$self->{config}->{site_url}$1";
	}

	my $info_path;
	if ($self->{config}->{html_archive_mode}) {
		if ($self->{init}->{archive_dir} =~ /([^\/\\]*\/)$/) {
			$info_path = "$self->{config}->{site_url}$1";
		}
	} else {
		if ($self->{init}->{script_file} =~ /([^\/\\]*)$/) {
			$info_path = "$self->{config}->{site_url}$1";
		}
	}

	my($items, $last_date, $i);

	foreach my $entry (@dir) {
		if ($entry !~ /^\d\d\d\d\d\d\.$self->{init}->{data_ext}$/) {
			next;
		}
		open(FH, "$self->{init}->{data_dir}$self->{init}->{data_diary_dir}$entry") or $self->error("Read Error : $self->{init}->{data_dir}$self->{init}->{data_diary_dir}$entry");
		while (<FH>) {
			chomp;
			my($no, $id, $stat, $break, $comt, $tb, $field, $date, $name, $subj, $text, $color, $icon, $file, $host) = split(/\t/);

			if (!$stat) {
				next;
			}

			$i++;
			if ($i > $self->{config}->{page_size}) {
				last;
			}

			if (!$last_date) {
				$last_date = $date;
			}

			my $link;
			if ($self->{config}->{html_archive_mode}) {
				$link = "$info_path$no\.$self->{init}->{archive_ext}";
			} else {
				$link = "$info_path?no=$no";
			}

			$items .= "$subj\t$link\t$text\t$date\n";
		}
		close(FH);
	}

	print "Content-Type: text/xml\n\n";

	my $rss_ins = new webliberty::Rss;
	print $rss_ins->create_rss(
		rdf_about   => "$info_script?mode=rss",
		title       => $self->{config}->{site_title},
		link        => $self->{config}->{site_url},
		description => $self->{config}->{site_description},
		date        => $last_date,
		items       => $items
	);

	return;
}

1;
