<?php
/*
This document does all the heavy lifting
*/
define ("ALBUMFILE", "./albums.txt", false); //the name of the database
define ("MAXSIZE", 400, false); //this is the max size in pixels that the images will be scaled to
define ("IMAGEPATH", "./images/", false); // the relative path (or absolute) to save albums
define ("ALLOWZIP", true); //defines whether bulk uploads are allowed in zip format. Must support unix ZIP commands.
define ("METADATA", "./metadata.txt");
define ("INIT", true); // change this to false to stop the file initialisation
define ("MAXFILESIZE", "3MB"); //maximum file upload size;
switchboard(); //start the machine
function switchboard(){
if (INIT) init();
$action = isset($_POST['action']) ? $_POST['action'] : '';
switch ($action) {
case "submitNewAlbum":
processNewAlbumRequest();
break;
case "uploadfile":
processUploadedFile();
break;
case "New Album":
newAlbumForm();
break;
case "Upload":
displayUploadForm();
break;
case "Display":
displayAlbum();
break;
default:
displayAlbum();
}
}
function init(){
if (!file_exists(ALBUMFILE)){
$fh = fopen(ALBUMFILE, "w");
}
if (!file_exists(IMAGEPATH)){
mkdir(IMAGEPATH);
}
if (!file_exists(METADATA)){
$fh = fopen(METADATA, "w");
}
}
function newAlbumForm($msg=""){
//make the album name sticky from page refreshes
$albumName = isset($_POST['albumName']) ? $_POST['albumName'] : '';
$msg = (empty($msg)) ? NULL: '<div class="errorMessage">'.$msg.'</div>';
$contentObject = <<<HTML
$msg
<form method="post" action="{$_SERVER['PHP_SELF']}" >
<fieldset>
<legend>New Album</legend>
Album Name: <input type="text" maxlength="255" value="$albumName" name="albumName" /><br/>
<input type="submit" name="submit" value="Create Album" />
<input type="hidden" name="action" value="submitNewAlbum"/>
</fieldset>
</form>
HTML;
require 'template.tpl';
}
function processNewAlbumRequest(){
//prep the album name
if (!empty($_POST['albumName'])){
$albumName = trim($_POST['albumName']);
} else {
newAlbumForm("No Album Name Provided");
exit();
}
$albums = getAlbumNames();
//check that the album name does not exist
if (in_array($albumName, $albums)){
newAlbumForm("Sorry, that album name has already been taken");
exit();
} else {
$fh = fopen(ALBUMFILE, "ab");
fwrite ($fh, $albumName."\r\n");
fclose ($fh);
}
//create the album directory
mkdir(IMAGEPATH."$albumName");
displayAlbum();
}
function getAlbumNames(){
//returns an array of album names or a blank string if there are no albums
$albums = array();
$fh = @fopen(ALBUMFILE, "rb");
if (!$fh){
return '';
} else {
while ( ($data = fgetcsv($fh, 1024, ",", '"')) !== false){
$albums[] = $data[0];
}
fclose ($fh);
return $albums;
}
}
function displayUploadForm($msg=NULL){
$maxsize = MAXFILESIZE;
$msg = (empty($msg)) ? NULL: '<div class="errorMessage">'.$msg.'</div>';
$shortdescription = (isset($_POST['shortdescripton'])) ? $_POST['shortdescripton'] : '';
$albums = getAlbumNames();
$select = "<select name=\"albumName\">\r\n";
foreach ($albums as $album){
$select .= "\t<option value=\"$album\">$album</option>\r\n";
}
$select.= "</select>";
$contentObject = <<<HTML
$msg
<form method="post" action="{$_SERVER['PHP_SELF']}" enctype="multipart/form-data" >
<fieldset>
<legend>Upload images</legend>
<p>You can upload gif, png or jpegs either singly or in bulk as a zip file</p>
Choose file (max $maxsize): <input type="file" name="upload" /><br/>
Short description: <input type="text" maxlength="255" name="shortdescription" value="$shortdescription" /><br/>
Which album: $select
<input type="submit" name="submit" value="Upload" />
<input type="hidden" name="action" value="uploadfile" />
</fieldset>
</form>
HTML;
require 'template.tpl';
}
function processUploadedFile(){
//check for errors
$msg = "";
if (isset($_FILES['upload'])){
switch ($_FILES['upload']['error']){
case 0:
break;
case 1:
case 2:
$msg = "The uploaded file is too large";
break;
case 3:
$msg = "The uploaded file was only partially uploaded";
break;
case 4:
$msg = "No file was uploaded";
break;
case 6:
case 7:
case 8;
$msg = "There was a problem saving ths uploaded file.";
break;
}
}
//if we have a problem, tell the user
if (!empty($msg)){
displayUploadForm($msg);
exit();
}
//check the file type.
//simple check against the file extension. not ideal...
if (!empty($_POST['upload']['type'])){
$type = $_POST['upload']['type'];
}else {
$type = getFileType($_FILES['upload']['name']);
}
switch ($type){
case "application/x-zip":
if (ALLOWZIP){
processUploadedZipFile($_FILES['upload']['tmp_name']);
} else {
displayUploadForm("Sorry we do not allow Zip files");
}
break;
case "unsupported":
displayUploadForm("Only zip files and jpegs are allowed to be uploaded");
exit();
break;
default:
processUploadedPhoto($_FILES['upload']['tmp_name'], $type);
}
displayAlbum();
}
function processUploadedPhoto($file, $type){
//grab a uniqueID
if (!isset($_POST['albumName'])){
displayUploadForm("You have not selected an album");
exit();
}
$albumName = $_POST['albumName'];
$albums= getAlbumNames();
if (!in_array($albumName,$albums)){
displayUploadForm("You have not selected an existing album");
}
$extension = getExtensionFromType($type);
$uid = uniqid("photo_", true) .".$extension";
$file = reSizePhoto($file, $type);
if (rename($file, IMAGEPATH.$albumName.'/'.$uid) === false){
displayUploadForm("Problem saving file");
exit();
}
//save the metadata for the file
$shortdescription = addslashes (trim($_POST['shortdescription']));
$fh = fopen(METADATA, "ab");
flock($fh, LOCK_EX);
fwrite($fh, "\"$albumName\",\"$uid\",\"$shortdescription\", \"".$GLOBALS['orientation']."\"\r\n");
fclose ($fh);
}
function processUploadedZipFile($file){
//dummy out for the time being...
//alpha code
$dir = "./".uniqid("tempzip_", true) .'/';
mkdir ($dir);
$command = "unzip $file -d $dir";
//unzip the file to the new directory
exec (escapeshellcmd($command));
$fh = opendir($dir);
while ( false !== ($file = readdir($fh))){
if (!is_file($file)){
//do nothing
}
//really need a function to test the filetype naturally here ...
$type = getfiletype($dir.$file);
$extension = getExtensionFromType($type);
if ($type !== "unsupported"){
processUploadedPhoto($dir.$file,$type);
} else {
//do nothing
}
}
removeDirectory($dir, false);
}
function getfiletype($file){
if (function_exists("mime_content_type")){
return(mime_content_type($file));
}else{
$ext = getExtension($file);
switch ($ext){
case "jpeg":
case "jpg":
return "image/jpeg";
break;
case "gif":
return "image/gif";
break;
case "png":
return "image/png";
break;
case "zip":
return "application/x-zip";
break;
default:
return "unsupported";
}
}
}
function getExtensionFromType($type){
switch ($type){
case "image/jpeg":
return "jpeg";
break;
case "image/gif":
return "gif";
break;
case "image/png":
return "png";
break;
}
}
function getExtension($file){
//really need a better way of doing this...
$tmp = explode(".", $file);
$type = $tmp[count($tmp)-1];
return strtolower($type);
}
function reSizePhoto($file, $type){
$newsize = MAXSIZE;
//we know it is a jpeg because this is a limited applet
//but allow for future expansion!
set_time_limit(0);
switch ($type) {
case 'image/jpeg':
$src_img = imagecreatefromjpeg($file);
$func = 'imagejpeg';
$ext = '.jpeg';
break;
case 'image/gif':
$src_img = imagecreatefromgif($file);
$func = 'imagegif';
$ext = '.gif';
break;
case 'image/png':
$src_img = imagecreatefrompng($file);
$func = 'imagepng';
$ext = '.png';
break;
case 'image/bmp':
$src_img = imagecreatefromwbmp($file);
$func = 'imagewbmp';
$ext = '.bmp';
break;
default:
displayUploadForm("error - file is not of a supported image type");
exit();
}
if ($src_img == '') {
displayUploadForm("error - file is not a $type file");
exit();
}
//get current image sizes
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y){
$GLOBALS['orientation'] = "hr";
$thumb_w=$newsize;
$thumb_h=$old_y*($newsize/$old_x);
} elseif ($old_x < $old_y) {
$GLOBALS['orientation'] = "vt";
$thumb_w=$old_x*($newsize/$old_y);
$thumb_h=$newsize;
} else {
$GLOBALS['orientation'] = "hr";
$thumb_w= $thumb_h = $newsize;
}
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
$func($dst_img,$file);
imagedestroy($dst_img);
imagedestroy($src_img);
return $file;
}
function displayAlbum(){
$albums = getAlbumNames();
if (count($albums) === 0) {newAlbumForm();exit();}
$albumName = (isset($_POST['albumName']))?$_POST['albumName']:$albums[0];
$select = "<select name=\"albumName\">\r\n";
foreach ($albums as $album){
$selected = ($album === $albumName) ? "selected=\"selected\"": '';
$select .= "\t<option value=\"$album\" $selected >$album</option>\r\n";
}
$select.= "</select>";
$contentObject = <<<HTML
<form method="post" action="{$_SERVER['PHP_SELF']}" enctype="multipart/form-data" >
<fieldset>
<legend>Choose Album</legend>
$select <input type="submit" name="action" value="Display" /><br/>
or <input type="submit" name="action" value="New Album" /> <input type="submit" name="action" value="Upload" />
</fieldset>
</form>
HTML;
$contentObject .= <<<HTML
<div id="scroller">
<em></em>
<span><b id="copyright">© 2007 Stu Nicholls</b></span>
<b id="thumbs">
LINKS
</b>
</div>
HTML;
//now get the file list
$fh = @fopen(METADATA, "rb") or die("cannot open metadata file");
$links = '';
while (false !== ($data = fgetcsv($fh, 2048, ",", '"'))){
if ($data[0] == $albumName){
$src = IMAGEPATH.$data[0].'/'.$data[1];
$links .= <<<HTML
<a href="#nogo"><img class="{$data[3]}" src="$src" alt="{$data[2]}" title="{$data[2]}" /></a>
HTML;
}
}
$contentObject = str_replace("LINKS", $links, $contentObject);
require 'template.tpl';
}
function removeDirectory($dirname,$only_empty=false) {
//taken from php.net user notes on rmdir()
if (!is_dir($dirname))
return false;
$dscan = array(realpath($dirname));
$darr = array();
while (!empty($dscan)) {
$dcur = array_pop($dscan);
$darr[] = $dcur;
if ($d=opendir($dcur)) {
while ($f=readdir($d)) {
if ($f=='.' || $f=='..')
continue;
$f=$dcur.'/'.$f;
if (is_dir($f))
$dscan[] = $f;
else
unlink($f);
}
closedir($d);
}
}
$i_until = ($only_empty)? 1 : 0;
for ($i=count($darr)-1; $i>=$i_until; $i--) {
@rmdir($darr[$i]);
}
return (($only_empty)? (count(scandir)<=2) : (!is_dir($dirname)));
}
?>