#!/usr/bin/perl -Tw use strict; use Storable qw/lock_store lock_retrieve/; use CGI qw/:standard/; ######################### # Begin Config # File to store 'rotate' data in. # CGI instance must have read/write access my $data_file = '/var/www/images.dat'; # Image to show if there's an error # ie: "Error", "404 Not Found" image my $err_img = '/var/www/images/err.jpg'; # Catagories for 'rotate' and 'random' # Keys are the catagory names to pass as 'c' argument, # arrays are the directories for that catagory. my $cat = { 'banners' => ['/home/user/imgs/banners', '/home/user/imgs/banners2'], 'logos' => ['/home/user/imgs/logos', '/home/user/imgs/logos2'] }; ######################### # End Config # Automatically generate an 'all' catagory @{$cat->{'all'}} = map{@{$cat->{$_}}}keys %{$cat}; # Rotate the image number for a catagory sub rotate_img { my $q = shift; my @imgs = get_imgs(@{$cat->{$q}}); my $data = -e $data_file ? lock_retrieve($data_file) : {}; $data->{$q} = 0 if $data->{$q}++ == $#imgs; lock_store $data, $data_file; return $imgs[$data->{$q}]; } # Get list of images from directories sub get_imgs { sort grep {-f && /(?:\.gif|jpe?g|png)$/i } map{ glob("$_/*") } @_ } # Output an image to the browser sub show_img { my $img = shift; my ($mime) = $img =~ /\.(gif|jpe?g|png)$/; $mime = 'jpeg' if $mime eq 'jpg'; open my $fh, '<', $img or die "Could not open $img for read: $!"; binmode $fh; my $img_data = do { local $/; <$fh> }; close $fh; print header('image/' . $mime), $img_data; exit; } my $m = param('m') || ''; # Mode my $c = param('c') || ''; # Catagory # Rotated image if ($m eq 'rotate') { show_img( $cat->{$c} ? rotate_img($c) : $err_img ); } # Random image elsif ($m eq 'random') { show_img($err_img) unless $cat->{$c}; my @imgs = get_imgs(@{$cat->{$c}}); show_img($imgs[rand @imgs]); } # Specific Image elsif ($m eq 'image') { ($m,$c) = split(/\//, $c, 2); show_img($err_img) unless $cat->{$m} && $c; for ( get_imgs(@{$cat->{$m}}) ) { show_img($_) if m#/\Q$c\E\.(?:gif|jpe?g|png)$#; } show_img($err_img); } # Invalid Call else { show_img($err_img); }