Revision 219 (by dpavlin, 2008/06/22 14:41:23) exctract cache handling code to A3C::Cache
package Strix;

use strict;
use warnings;

use base qw(Jifty::Object Class::Accessor::Fast A3C::Cache);
__PACKAGE__->mk_accessors( qw(instance uid) );

use DBI;
use Data::Dump qw/dump/;
use Carp qw/confess/;
use Jifty;

use Carp qw/confess/;
use URI::Escape;

our $debug = 0;

=head1 NAME

Strix

=head1 METHODS

=head2 new

  my $strix = Strix->new({ instance => 'os-test0604-zg' });

=head2 dbh

  my $dbh = Strix->dbh( $strix_instance );

  my $dbh = $strix->dbh;

=cut

our $instance_dbh;
our @instances_active;

sub dbh {
	my $self = shift;

	my $instance = shift || ref($self) && $self->instance || confess "no instance";

	return $instance_dbh->{$instance} if $instance_dbh->{$instance};

	my $config = Jifty->config->app('strix') or die "need strix config";
	my $database = $config->{database} or die "no strix.database in config";

	Jifty->log->debug("using config ", dump( $database ));

	my $dsn =
		'DBI:Pg:dbname=' . $instance .
		';host=' . $database->{host} .
		';port=' . $database->{port};

	Jifty->log->info("Connect to instance $instance with dsn $dsn");

	my $dbh = DBI->connect( $dsn, $database->{user}, $database->{passwd} ) or die "$DBI::errstr\n";

	# force database to send us back UTF-8 no metter what it's encoding
	$dbh->do("set client_encoding='utf-8'");
	$dbh->{pg_enable_utf8} = 1;

	$instance_dbh->{$instance} = $dbh;
	push @instances_active, $instance;

	if ( $#instances_active > 5 ) {
		my $i = shift @instances_active;
		warn "## remove connection to instance $instance\n";
		delete( $instance_dbh->{$i} );
	}

	warn "## instance_dbh = ",dump( $instance_dbh ) if $debug;

	return $dbh;
}

=head2 category

	my $category = Strix->category( $url );

=cut

sub category {
	my $self = shift;

	my $url = shift || confess "no url";

	my $data = $self->read_cache( uri_escape($url) );
	return $data if $data;

	# sysinc/profiles.php
	my $sth = $self->dbh->prepare(qq{
	SELECT kategorija.*, lang.langid, lang.locale, template.tfilename, template.tflags, site.naziv as sitename, site.admin_mail, site.address, site.root as site_root, getPathFromNav(kategorija.id) as path, site.ordstr as site_ordstr FROM kategorija, template, site, lang WHERE kategorija.url = ? AND kategorija.template_id = template.id AND kategorija.site_id = site.id AND lang.id = kategorija.lang
	});
	$sth->execute($url);

	my $category = $sth->fetchrow_hashref() or die "can't fetch category $url from instance ",$self->instance,"\n";
	$self->write_cache( $category, uri_escape($url) );
	return $category;
}

=head2 layout

	my $layout = $strix->layout( $url );

=cut

sub layout {
	my $self = shift;

	my $url = shift || confess "no url";

	my $data = $self->read_cache( uri_escape($url) );
	return $data if $data;

	my $dbh = $self->dbh;
	my $category = $self->category( $url );

	my $sth = $dbh->prepare(qq{
	SELECT template.tfilename, template.tflags FROM template WHERE id = ?
	});
	$sth->execute( $category->{template_id} );

	my $template = $sth->fetchrow_hashref() or die "can't fetch template";

	warn "template = ",dump( $template ) if $debug;

	my $page;
	warn "### free layout...\n" if $debug;

	# index.php
	$sth = $dbh->prepare(qq{
	SELECT layout_id, module_id, pozicija, module_args, name, fname, notitle, class_name
	FROM pre_layout, modules
	WHERE id=module_id AND ? = template_id AND redoslijed >= 0
	ORDER BY redoslijed DESC
	});
	$sth->execute( $category->{template_id} );

	sub module_args {
		my $row = shift;
		return undef unless $row->{module_args};
		my $args;
		foreach my $a ( split(/\&/, $row->{module_args} ) ) {
			$args->{$1} = $2 if $a =~ m/^(.+)=(.+)$/;
		}
		return $args;
	}

	while (my $row = $sth->fetchrow_hashref() ) {
		warn dump( $row ) if $debug;
		push @{ $page->{free} }, { $row->{name} => module_args( $row ) };
	}

	warn "### pre layout...\n" if $debug;

	$sth = $dbh->prepare(qq{
	SELECT
		l.id as layout_id, l.user_id, l.kategorija_id, l.module_id, l.pozicija, l.redoslijed, l.module_args, l.state, l.notitle,
		m.name, m.fname, m.hidden, m.nocache, m.pos, m.class_name,
		acl_module.acl_register_id
	FROM layout as l, modules as m LEFT JOIN acl_module ON (acl_module.modules_id = m.id)
	WHERE l.user_id=?
	AND l.kategorija_id=?
	AND m.id=l.module_id
	ORDER BY pozicija,redoslijed DESC
	});
	$sth->execute( 1, $category->{id} );

	while (my $row = $sth->fetchrow_hashref() ) {
		warn dump( $row ) if $debug;
		push @{ $page->{pre}->{ $row->{pos} } }, { $row->{name} => module_args( $row ) };
	}

	warn "### post layout...\n" if $debug;

	$sth = $dbh->prepare(qq{
	SELECT layout_id, module_id, pozicija, module_args, name, notitle
	FROM pre_layout, modules
	WHERE id=module_id AND ? = template_id AND redoslijed < 0
	ORDER BY redoslijed DESC
	});
	$sth->execute( $category->{template_id} );

	while (my $row = $sth->fetchrow_hashref() ) {
		warn dump( $row ) if $debug;
		push @{ $page->{post}->{ $row->{pozicija} } }, { $row->{name} => module_args( $row ) };
	}

	$self->write_cache( $page, uri_escape($url) );

	return $page;

}

=head2 sites

	my @sites = $strix->sites;

=cut

sub sites {
	my $self = shift;

	my @sites = $self->read_cache;
	return @sites if @sites;

	my $sth = $self->dbh->prepare(
	"SELECT *, coalesce(( length(ordstr)/3 ) - 1,0) AS depth FROM site ORDER BY ordstr"
	);
	$sth->execute;

	while (my $row = $sth->fetchrow_hashref() ) {
		push @sites, $row;
	}

	$self->write_cache( \@sites );

	return @sites;
}

=head2 site_navigation

  my $navigation = $strix->site_navigation( $site_id, $uid );

=cut

sub site_navigation {
	my $self = shift;

	my ( $site_id, $uid ) = @_;

	$uid ||= 1; # anonymous
#	$uid ||= 2; # admin

	my $data = $self->read_cache( $site_id, $uid );
	return $data if $data;

	my $sth = $self->dbh->prepare(
	"SELECT kategorija.*, ((length(prikaz)+length(coalesce(ordstr,'')))/3)-1 as depth FROM kategorija JOIN navigacija ON (kategorija.id = kategorija_id), site WHERE site_id = ? AND site.id = site_id AND userCanDoOnObject(?, 1, 'kats', kategorija.id) ORDER BY prikaz");
	$sth->execute( $site_id, $uid );

	Jifty->log->debug("site $site_id has ", $sth->rows, " categories for uid $uid");

	my $navigation = [];

	my @pos = ( 0 );

	while (my $kat = $sth->fetchrow_hashref() ) {
		warn "# kat = ",dump( $kat ) if $debug;
		if ( ! $kat->{depth} ) {
			Jifty->log->error("depth increased to 1 in ",dump( $kat ));
			$kat->{depth} = 1;
		}

		my $node = { type => 'category' };
		foreach my $c ( qw/naziv url/ ) {
			$node->{$c} = $kat->{$c};
		}

		my $depth = $kat->{depth};
		if ( ! defined $pos[ $depth - 2 ] ) {
			warn "FIXING CATEGORY: ",dump( $kat );
			$node->{class} = "error";
			$depth--;
		}
		@pos = splice( @pos, 0, $depth );
		$pos[ $depth - 1 ]++;

		warn "## category depth = $depth pos = ",dump( @pos ) if $debug;

		my $code = '$navigation';
		map { $code .= '->[' . ( $_ - 1 ) . ']->{children}' } @pos;
		$code =~ s/->{children}$//;
		warn "## category code: $code\n" if $debug;
		eval $code . '= $node';
		if ( $@ ) {
			warn "SKIPPED CATEGORY: $@ ",dump( $kat );
			next;
		}

		my $sth_ms = $self->dbh->prepare(
		"SELECT
			multistatic.id, multistatic.title, multistatic.kname,
			multistatic_navigation.kategorija_id, multistatic_navigation.prikaz,
			(LENGTH(multistatic_navigation.prikaz)/3) AS depth
		FROM multistatic, multistatic_navigation
		WHERE multistatic.id = multistatic_navigation.multistatic_id
			AND multistatic_navigation.prikaz != ''
			AND multistatic_navigation.kategorija_id = ?
			AND multistatic.title != ''
		ORDER BY multistatic_navigation.prikaz");
		$sth_ms->execute( $kat->{id} );

		if ( my $rows = $sth_ms->rows ) {
			Jifty->log->debug("$site_id has $rows multistatic pages");

			while (my $ms = $sth_ms->fetchrow_hashref() ) {
				warn "# ms = ",dump( $ms ) if $debug;

				my $node = {
					naziv => $ms->{title},
					url => $kat->{url} . '?ms_nav=' . $ms->{prikaz},
					type => 'multistatic',
				};
				
				my $ms_depth = $ms->{depth} + $depth;
				my $p = $pos[ $ms_depth - 1 ]++;
				warn "## multistatic depth = $ms_depth pos = ",dump( @pos ) if $debug;

				my $ms_code = $code . '->{children}->[ ' . $p . ']  = $node';
				warn "## multistatic code: $ms_code\n" if $debug;
				eval $ms_code;
				if ( $@ ) {
					warn "SKIPPED MULTISTATIC: $@ ",dump( $ms );
					next;
				}
			}
		}

	}

	$self->write_cache( $navigation, $site_id, $uid );

	return $navigation;

}

1;