Location: PHPKode > scripts > Yappa-Yet Another PHP Photo Album > yappa-13027/index.php
<?php
/*
 *   Yappa: Yet Another PHP Photo Album
 *   A simple php file to put on a web server to administrate 
 *   and see in a easy way all your photos.
 *   Currently the easyest program to INSTALL AND  MANAGE photos.
 *   Author: manu at agat.net, oachler at ucsd.edu
 *   WEB page: http://manu.agat.net/yappa/
 *   LICENSE: GPL.
 *   Date: see version (YYYYMMDD)
 *   Requirement: http://www.sentex.net/~mwandel/jhead/ for jpeg comments
 *
 *   Don't forget to make the current dir writeable by the web server
 *   
 */
// The next line must ONLY contain the version , no comments or other!
$version="20030411"; 
			//Forked 3.1.3 equivalent
			// Let's rename it to: 3.1.4
error_reporting(1);

function writeconfig($dir,$varallow_comments,$varallow_jpeginfo,$varimg_per_row) {
  global $allow_comments,$img_per_row,$allow_jpeginfo;
  $allow_comments=$varallow_comments;
  $img_per_row=$varimg_per_row;
  $allow_jpeginfo=$varallow_jpeginfo;
  
  $fd=fopen("$dir/config.php","w");
  $data="<? \$img_per_row=$img_per_row;\n";
  $data.="\$allow_comments=$allow_comments;\n";
  $data.="\$allow_jpeginfo=$allow_jpeginfo;\n";
  $data.=" \n?>";
  fwrite($fd,$data);
  fflush($fd);
  fclose($fd);
};


function adminheaders($baseURL) {
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<!DOCTYPE html\n";
echo "     PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n";
echo "    \"DTD/xhtml1-strict.dtd\">\n";
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n";
echo "  <head>\n";
echo "    <title>Yappa: Administration web photo album</title>\n";
echo "  </head>\n";
echo "  <body>\n";
echo "<table border=\"1\" cellspacing=\"0\"><tr><td><a href=\"http://manu.agat.net/yappa\">Yappa</a> generated</td>";
echo "<td align=center><a href=$baseURL>Administration center</a>  &nbsp;| &nbsp;   <a href=".dirname($baseURL).">Base of the photo album</a></td></tr>";
echo "<tr><td></td><td>";
}

function adminendhtml() {
echo "</td></tr></table>";
echo "    <p>.</p>\n";
echo "  </body>\n";
echo "</html>\n";
}

// cut the begin of a path
function stripbeginfrompath($base,$dir) {
$data=split($base,$dir);
return($data[1]);
}

// display directories recurslivy, $base is used to strip the begin of path.
function recursdir($adir,$base) {
$handle=opendir($adir);
while ($file = readdir($handle)) {
      if (is_dir($adir."/".$file) && ($file!=".") && ($file!="..")&& ($file!=".tn") && ($file!="admin")) {
         $dir=$adir."/".$file;
         $actiondir=stripbeginfrompath($base,$dir);
         echo "<tr><td><a href=?actiondir=".rawurlencode($actiondir)."> $actiondir</a> </td>";
         echo "<td><a href=?deletedir=".rawurlencode($actiondir).">delete directory</a></td></tr>";
         recursdir($dir,$base);
      }
   };

};

function writealldirectories() {
$basedir=dirname(getcwd());
$base=basename($basedir);
echo "<table>";
// Add a line for the base directory. so users can create directories on base.
echo "<tr><td><a href=?actiondir=.> Base directory</a> </td>";
echo "<td>&nbsp; </td></tr>";
recursdir($basedir,$base);
echo "</table>";
}


//return 1 if  version in $contentversion > $version
function goodversion($version,$content) {
   $data=explode("\n",$content);
   for($i=0;$i<count($data);$i++) {
       if (ereg("version=",$data[$i])) {
          $data2=explode("\"",$data[$i]);
          $remotevers=$data2[1];
          if (strcmp($remotevers,$version)>0) {
             echo "New version detected";
             return 1;
          } else {
             echo "No new version";
             return 0;
          };
      }
   }
   return(0);
}


//write operation available on main admin page
function sendnormaloperations($basedir,$baseURL) {
global $actiondir, $deletedir,$addaccess,$pass,$email,$PHP_AUTH_USER,$autoinstall,$version,$testunarchiver;

echo "<b>";
//gestion des actions
if (isset($deletedir)) {
// we must clean up misc files: .tn directory and index.php
rmdir($basedir."/".$deletedir."/.tn");
unlink($basedir."/".$deletedir."/index.php");
if (rmdir($basedir."/".$deletedir)) {
   echo "<br/>Directory $deletedir deleted.<br/>";
} else {
    echo "<br/>The directory $deletedir couldn't be deleted (access denied, not empty or nonexistant)<br/>";
};
};
if (isset($addaccess)) {
   if ($pass=="") {
      echo "Password can't be empty. No action taken";
   } else {
       if (!file_exists("$basedir/admin/.htaccess")) {
          $fd=fopen("$basedir/admin/.htaccess","w");
          $data="AuthName \"Acces administration de yappa. give your admin email as login\"\n";
          $data.="AuthType Basic\n";
          $data.="AuthUserFile  $basedir/admin/.htpasswd\n";
          $data.="AuthGroupFile None\n";
          $data.="require valid-user";
          fwrite($fd,$data);
          fclose($fd);
       };
       if (file_exists("$basedir/admin/.htpasswd")) {
          $command="htpasswd -mb $basedir/admin/.htpasswd $email $pass";
          system($command);
       } else {
          $fd=fopen("$basedir/admin/.htpasswd","w");
          $data=$email.":".crypt($pass);
          fwrite($fd,$data);
          fclose($fd);
       };
       mail($email,"Yappa administration","From: hide@address.com\nThe password for administration is :\n$pass\nSee you later");
       echo "Change done";
   };
};

if (isset($autoinstall)) {
   $url="http://manu.agat.net/yappa/yappa.txt";
   $fcontents = join( '', file( $url ) );
   if ($fcontents!="" && goodversion($version,$fcontents)==1) {
      $fd=fopen($basedir."/yappa.txt","w");
      fwrite($fd,$fcontents);
      fclose($fd);
      if (file_exists("$basedir/index.php.old")) {
          unlink("$basedir/index.php.old");
      };
      rename("$basedir/index.php","$basedir/index.php.old");
      rename("$basedir/yappa.txt","$basedir/index.php");
      echo "Update done";
   };
};
if (isset($testunarchiver)) {
   exec("which unrar",$devnull,$data);
   if ($data==0) { 
      echo "unrar available";
   } else {
      echo "unrar unavailable";
   }
echo "<br/>";
   exec("which unzip",$devnull,$data);
   if ($data==0) { 
      echo "unzip available";
   } else {
      echo "unzip unavailable";
   }
echo "<br/>";
   exec("which tar",$devnull,$data);
   if ($data==0) { 
      echo "tar available";
   } else {
      echo "tar unavailable";
   }
echo "<br/>";

};

echo "</b>";
echo "<ul><li>Directories in the photo album: (click on a directory for more actions)<br>";
writealldirectories();
echo "</li>";
//echo "<li>Change option TODO</li>";// see what options we can change.
echo "<li><a href=?testunarchiver=test>Verify if some unarchiver are present.</a> (May not work on all system).</li>";
echo "<li><form method=post action=\"$baseURL\">Add the email <input type=text name=email value=hide@address.com> ";
echo "and the password <input type=password name=pass>";
echo "to connect to the admin";
echo "<input type=submit name=addaccess value=send></form>";
echo "A mail will be send to this adress with the password</li>";
echo "<li><a href=?autoinstall=ok>Install latest version of yappa</a> (Internet connected only)</li>";
echo "</ul>";
};

function listallphotofromdir($actiondir,$basedir,$baseURL) {
$handle=opendir($basedir."/".rawurldecode($actiondir));
echo "<table border=1 cellspacing=0>\n";$nbphotos=0;
while ($file = readdir($handle)) {
$filename=$basedir."/".$actiondir."/".$file;
if (is_file($filename) && ($file!="index.php")) {
   echo "<tr><td>".$file."</td>";
   if ((ereg(".jpg$",$filename)) || (ereg(".JPG$",$filename)) || (ereg(".jpeg$",$filename))) {
	echo "<td><img src=\"".dirname($baseURL).ereg_replace(" ","%20",$actiondir)."/.tn/tn_".rawurlencode($file)."\" border=\"0\" /></td>";
   } else {
	if (ereg(".*\.txt$",$filename)) {
	     echo "<td>photo's comment</td>";
	} else {
          if (ereg("config.php$",$filename)) {
             echo "<td>config file</td>";
          } else {
	     echo "<td>&nbsp;</td>";
          }
	}
   }
   echo "<td><a href=?actiondir=".rawurlencode($actiondir)."&deletefile=$file>delete file</a></td> " ;
   if ((ereg(".jpg$",$filename)) || (ereg(".JPG$",$filename)) || (ereg(".jpeg$",$filename))) {
       echo "<td>add a comment:";
       echo "<form><input type=text name=textecommentaire value=commentaire>";
       echo "<input type=hidden name=actiondir value=\"$actiondir\">";
       echo "<input type=hidden name=file value=\"$file\">";
       echo "<input type=submit name=commentfile value=comment>";
       echo "</td>";
   } else {
       if (ereg("config.php$",$filename)) {
           echo "<td>To use general options for comments and number of thumbnails per line, delete this file</td>";
       } else {
           echo "<td>&nbsp;</td>";
       }
   }
   echo "</tr>\n";
   $nbphotos=1;
};
};
echo "</table>";
if ($nbphotos==0) {
echo "No photo in this directory";
};
};

function workonadirectory($actiondir,$basedir,$baseURL) {
global $deletefile,$directory,$nom,$sendfile,$sendfile_name,$sendfile_type,$file,$textecommentaire,$commentfile,$createthetn,$version,$comment,$allow_comments,$allow_jpeginfo,$img_per_row,$newallowcom,$newjpeginfo,$newimgperrow;

// en gras pour montrer les actions effectués.
echo "<b>";
//gestion de l'effacement d'un fichier
if (isset($deletefile)) {
if (unlink($basedir."/".$actiondir."/".$deletefile) ) {
   if (file_exists($basedir."/".$actiondir."/.tn/tn_".$deletefile)) {unlink($basedir."/".$actiondir."/.tn/tn_".$deletefile);};
   if (file_exists($basedir."/".$actiondir."/".$deletefile.".txt")) {unlink($basedir."/".$actiondir."/".$deletefile.".txt");};
   echo "<br/>File $deletefile deleted.<br/>";
} else {
   echo "<br/>The file $deletefile couldn't bze deleted (acces denied or non existent)<br/>";
};
};
//gestion de la creation d'un répertoire
if (isset($directory)) {
if ($directory=="create") {
  if (mkdir($basedir."/".$actiondir."/".$nom,0755)) {
      echo "Directory $nom created<br/>";
  } else {
      echo "Directory couldn't be created. Check permissions on  $actiondir<br/>";
  };
};
};
// gestion des envois de fichiers
if (isset($sendfile)) {
// On vérifie qu'on a des fichiers jpeg rar ou zip. un system("file") devrait etre tres efficace poru connaitre le contenu
if (ereg(".*\.jpg$",$sendfile_name) || ereg(".*\.JPG$",$sendfile_name) || ereg(".*\.jpeg$",$sendfile_name)) {
 echo "File $sendfile_name accepted<br>";
 move_uploaded_file($sendfile, $basedir."/".rawurldecode($actiondir)."/".$sendfile_name);
} else {
 if (ereg(".*\.tar$",$sendfile_name)) {
    move_uploaded_file($sendfile, $basedir."/".rawurldecode($actiondir)."/".$sendfile_name);
    $command="tar xf \"$basedir".rawurldecode($actiondir)."/$sendfile_name\" -C \"$basedir".rawurldecode($actiondir)."\" && rm -f \"$basedir".rawurldecode($actiondir)."/$sendfile_name\"";
    system($command);
    echo "File in place.";
 };
 if (ereg(".*\.tar\.gz$",$sendfile_name)) {
    move_uploaded_file($sendfile, $basedir."/".rawurldecode($actiondir)."/".$sendfile_name);
    $command="tar xfz \"$basedir".rawurldecode($actiondir)."/$sendfile_name\" -C \"$basedir".rawurldecode($actiondir)."\" && rm -f \"$basedir".rawurldecode($actiondir)."/$sendfile_name\"";
    system($command);
    echo "File in place.";
 };
 if (ereg(".*\.tgz$",$sendfile_name)) {
    move_uploaded_file($sendfile, $basedir."/".rawurldecode($actiondir)."/".$sendfile_name);
    $command="tar xfz \"$basedir".rawurldecode($actiondir)."/$sendfile_name\" -C \"$basedir".rawurldecode($actiondir)."\" && rm -f \"$basedir".rawurldecode($actiondir)."/$sendfile_name\"";
    system($command);
 };
 if (ereg(".*\.zip$",$sendfile_name)) {
    move_uploaded_file($sendfile, $basedir."/".rawurldecode($actiondir)."/".$sendfile_name);
    $command="unzip \"$basedir".rawurldecode($actiondir)."/$sendfile_name\" -d \"$basedir".rawurldecode($actiondir)."\" && rm -f \"$basedir".rawurldecode($actiondir)."/$sendfile_name\"";
    system($command);
    echo "File in place.";
 };
 if (ereg(".*\.rar$",$sendfile_name)) {
    move_uploaded_file($sendfile, $basedir."/".rawurldecode($actiondir)."/".$sendfile_name);
    $command="unrar x \"$basedir".rawurldecode($actiondir)."/$sendfile_name\" -C \"$basedir".rawurldecode($actiondir)."\" && rm -f \"$basedir".rawurldecode($actiondir)."/$sendfile_name\"";
    system($command);
    echo "file in place.";
 };
}
};
//gestion de l'ajout d'un commentaire a une photo.
if (isset($commentfile)) {
$fd=fopen($basedir."/".rawurldecode($actiondir)."/".rawurldecode($file).".txt","a+");
fwrite($fd,"127.0.0.1|".date("Y-m-d H:i")."|admin|$textecommentaire\n");
fclose($fd);
echo "Added comment";
};
//gestion add a comment for all photos comment wil be written in comment.html in the dir.
if (isset($comment)) {
$fd=fopen($basedir."/".rawurldecode($actiondir)."/comment.html","w");
fputs($fd,$nom);
fclose($fd);
};
//gestion de la creation des thumbnails
if (isset($createthetn)) {
  createtn($basedir."/".$actiondir,$createthetn) ;
  echo "Thumbnails created";
};
//gestion de l'autorisation des commentaires
if (isset($newallowcom)) {
   writeconfig($basedir."/".rawurldecode($actiondir),$newallowcom,$allow_jpeginfo,$img_per_row); 
   if ($allow_comments==0) { 
      echo "Comments are now denied.";
   } else {
      echo "Comments are now allowed.";
   };
};
if (isset($newimgperrow)) {
   writeconfig($basedir."/".rawurldecode($actiondir),$allow_comments,$allow_jpeginfo,$newimgperrow);
   echo "Now, $img_per_row picture(s) per line will be displayed";
};

// affichage du menu
echo "</b>\n";
echo "<br><br>Work directory: $actiondir";
echo "<ul>\n";
echo "<li><form>Create a new directory:";
echo "<input type=text name=nom>";
echo "<input type=hidden name=actiondir value=\"$actiondir\">";
echo "<input type=submit name=directory value=\"create\"></form></li>\n";
echo "<li><form enctype=\"multipart/form-data\"  method=post action=\"$baseURL?actiondir=".rawurlencode($actiondir)."\">Add new photos.";
echo "<input name=\"sendfile\" type=\"file\">";
echo "<input type=hidden name=actiondir value=\"$actiondir\">";
echo "<input type=\"submit\" value=\"Send\">";
echo "</form> (you can send one photo at time ( .jpg, .jpeg) or a  zip, rar, tar, tar.gz, tgz archive. Warning: The specified unarchiver must be present on the host computer, and the archive cannot be larger as 2 Mo.</li>\n";

echo "<li>List of photos in the current dir.<br>";
listallphotofromdir($actiondir,$basedir,$baseURL);
echo "</li>";

//part add a comment for the serie
echo "<li><form>add a comment for all photos ";
echo "<input type=text name=nom value=\"comment\">";
echo "<input type=hidden name=actiondir value=\"$actiondir\">";
echo "<input type=\"submit\" name=comment value=\"Send\">";
echo "</form><br> (HTML tags allowed)</li>\n";

echo "<li><a href=?actiondir=".rawurlencode($actiondir)."&deletefile=comment.html>remove comment for all photos</a></li>";
echo "<li><a href=?actiondir=".rawurlencode($actiondir)."&newallowcom=";
if ($allow_comments==0) {
   echo "1>Allow ";
} else {
   echo "0>Deny ";
}
echo "</a> public comments </li>";
echo "<li> <form>Number of thumbnails per line:";
echo "<input type=text name=newimgperrow value=\"$img_per_row\" size=\"2\" maxlength=\"1\">";
echo "<input type=hidden name=actiondir value=\"$actiondir\">";
echo "<input type=\"submit\" name=comment value=\"Change\">";
echo "</form></li>";
//echo "<li>Changer la classe d'appartenance de ce répertoire (seuls les images de cette classes pourraont etre vu par des utilisateurs connaissant l'URL. cela permet de restreindre la vue des images TODO</li>";

echo "<li><a href=?createthetn=color&actiondir=".rawurlencode($actiondir).">Create color thumbnails  for all photos </a> <a href=?createthetn=gray&actiondir=".rawurlencode($actiondir)."> (click here for gray) </a>  (this can take a time) </li>";

echo "</ul>\n";
echo "You have found a bug ? no problems, the bug will disappear in a few minutes/hours/days/weeks/months/never if you write me what you have done, the yappa version and of course the error :)";

echo "<br><a href=mailto:manu(@)agat.net?subject=Yappa:%20$version:%20bug%20report>Write me</a> (please don't change the subject)";
};


// No need to touch these variable unless you nkow exactly what happens.
// default values are *best* values :)
// Propagate the index.php file in subdirectories. 1 = activate it. 0 disable it. default=1
$autopropagateindex=1;

// Name of the file to block autopropagation
$blockautopropagate=".yappa.nopropage";

//autocreate thumbnails on fly 1 = enabled. 0 = disabled. default=1
$autocreatethumbnails=1;

// allow comment. Available value: 0/1 (0 disable, default: 1)

/*
***************     Configuration stop here.    **********
*/

/*
*  FUNCTIONS
*/


/* return html code to create link running in the following directories.*/
function mysplit($thestring2) {
global $base_dir_picture;
if (ereg("\?",$thestring2)) {
$thestring3=explode("?",$thestring2);
$thestring=$thestring3[0];
} else {
$thestring=$thestring2;
};

$res=explode("/",$thestring);
for($i=0;(strcmp($res[$i],$base_dir_picture)!=0) && ($i<1000) ;$i++);
if ($i>999) {echo "ERROR";};
for($j=$i;$j<count($res)-1;$j++) {
$partialaref="";
for($k=0;$k<=$j;$k++) { $partialaref.=$res[$k]."/"; }
echo "<a href=$partialaref>".rawurldecode($res[$j])."</a> / \n";
}
}


/* return html code to create link running in the following directories.*/
function mydirectorylist($thestring2) {
	global $basedir,$base_dir_picture,$autopropagateindex, $index;


	if (ereg("\?",$thestring2)) {
		$thestring3=explode("?",$thestring2);
		$thestring= $thestring3[0];
	} else {
		$thestring=$thestring2;
	};

	$res=explode("/",$thestring);
	if (basename($thestring)!=basename($basedir)) {
		$parent=dirname($thestring);
		echo "<a href=$parent>Parent directory</a><br>";
	};

	echo "<a href=$thestring>Thumbnails view<BR>(current album)</a><br><br>";


	$subdirsexists=0;
	$handle=opendir(".");
	while ($file = readdir($handle)) {
		if (($file=="admin") && (is_dir($file)) && (!file_exists("$file/index.php"))) {
		symlink("$basedir/index.php","$file/index.php");
		}
		if (($file != ".") && ($file != "..") && ($file != "admin") && ($file != ".tn") && (is_dir($file))) {
			// echo "<a href=".rawurlencode($file).">$file</a><br>\n";
			$dirs[]=$file;
			$subdirsexists=1;
			if (($autopropagateindex==1) && (!file_exists($blockautopropagate)) &&(!file_exists("$file/index.php"))) {
				symlink("$basedir/index.php","$file/index.php");
			};
		}
	}

	sort($dirs);

	// count and write number of photos
	for ($key=0; $key < count($dirs); $key++) {
		$file=$dirs[$key];
		echo "<a href=".rawurlencode($file).">$file</a><br>\n";
		$d=dir($file);
		$a=0;$b=0;
		while ($subfile=$d->read()) {
			if ( (( eregi("\.jpg$",$file."/".$subfile) ) || (eregi("\.jpeg$",$file."/".$subfile)))
			&& (is_file($file."/".$subfile)) ) {
				$a++;
			};
			if ( is_dir($file."/".$subfile) && (($subfile!=".") && ($subfile!="..") && ($subfile!=".tn"))  ) {
				$b++;
			};
		}
		// count and write subdirs
		echo "<font size=\"-1\">$a pictures<br>";
		echo "$b subdirs</font><br><br>";
	}

	closedir($handle);
	if ($subdirsexists==0) {
		echo "No subdirs.";
	}
}

// Create thumbnails
function createtn($dir,$style) {
   if (file_exists("$dir/.tn") && (is_dir("$dir/.tn"))) {
   } else {
       mkdir("$dir/.tn",0775);
   }
   $d=dir("$dir");
   while ($file=$d->read()) {
       if ( ( (eregi("\.jpg$",$dir."/".$file)) || (eregi("\.JPG$",$dir."/".$file)) || (eregi("\.jpeg$",$dir."/".$file)))
          && (is_file($dir."/".$file)) && ((!file_exists($dir."/.tn/tn_".$file)) || (!file_exists($dir."/.tn/tf_".$file))) ) {
              if ($style=="gray") {  $commstyle=" -colorspace GRAY ";};
              system("convert -quality 30   $commstyle -geometry 120x100 \"$dir/$file\" \"$dir/.tn/tn_$file\"");
	      // Build Thumb Finger (oo, im clever)
	      // Fingersize used for later option stuff
	      $fingersize = 640;
	      system("convert -sharpen 3 -normalize -geometry ".$fingersize."x$fingersize \"$dir/$file\" \"$dir/.tn/tf_$file\"");
	      echo ".";
       };
   }
};


function displaytn($thestring2) {
global $img_per_row;
if (ereg("\?",$thestring2)) {
$thestring3=explode("?",$thestring2);
$thedir= $thestring3[0];
} else {
$thedir=$thestring2;
};


//da  is a sorted array of available files.
$da=GetDirArray(".");
$counter=0;

if (count($da)>0) {
      while (list($key,$file)=each($da)) {
	 if ( ((ereg(".*\.jpg$",$file)) || (ereg("\.JPG$",$dir."/".$file)) || (ereg(".*\.jpeg$",$file))) 
	     && (is_file($file)) ) { 
	    $oneimageexist=1;
	    if ($counter==0) { echo "\n<table width=\"80%\" cellspacing=\"5\"><tr>\n";}
	    echo "<td><a href=?big=".rawurlencode($file)."><img src=\"$thedir.tn/tn_".rawurlencode($file)."\" border=\"0\" /><br />$file</a><br />";

	    displaycomment($file);
	    echo "</td>\n" ;
	    $counter++;
	    if ($counter==$img_per_row+1)  { echo "</tr></table>\n"; $counter=0;}
	 };
      };
   };
       
   if ( $oneimageexist==1) {
      if  ($counter!=0)  {
	 for ($i=$counter;$i<$img_per_row+1;$i++) {
	    echo "<td>&nbsp;</td>";
	 };
	 echo "</tr></table>\n"; $counter=0;}
   } else {
      echo "<center>No images in this directory</center>";
   }

};

function fulldisplay($image,$da) {
global $allow_comments,$allow_jpeginfo,$yappanom;
   $current="";
   $counter=0;
   while ($image!=$da[$counter]) {
      $counter++;
   };
   if ($counter==0) { 
      $prec="";
   } else {
      $prec=$da[$counter-1];
   };
   if ($counter==count($da)) {
      $suiv="";
   } else {
      $suiv=$da[$counter+1];
   };
   
   if ($prec!="") {
      echo " <a href=?big=".rawurlencode($prec)."> PREV </a>";
   };
   if ($allow_jpeginfo==1) {
      echo " <a href=?jpeginfo=".rawurlencode($thedir.$image). " target=_jpeginfo> Image Info </a>";
   };
   if ($suiv!="") {
      echo " <a href=?big=".rawurlencode($suiv).">NEXT</a>";
   };

   echo "<br/><a href=?original=".rawurlencode($thedir.$image)."><img src=\".tn/tf_".rawurlencode($thedir.$image)."\" border=\"0\" /></a><br/>";

   if ($allow_comments==1) {
      echo "<FORM  METHOD=get>\n";
      echo "<INPUT TYPE=HIDDEN NAME=img VALUE=\"$image\"/>\n";
      echo "<INPUT TYPE=TEXT NAME=text VALUE=\"Comment\"/><BR>\n";
      if (!isset($yappanom)) {
	 $nom="your name";
      } else { 
	 $nom=$yappanom;
      }; 
      echo "<INPUT TYPE=TEXT NAME=nom VALUE=\"$nom\"/><BR>\n";
      echo "<INPUT TYPE=SUBMIT NAME=Valider VALUE=\"Submit\"/> \n";
      echo "</FORM>\n";
   }
}

function originaldisplay($image,$da) {
global $allow_comments,$allow_jpeginfo,$yappanom;
   $current="";
   $counter=0;
   while ($image!=$da[$counter]) {
      $counter++;
   };
   if ($counter==0) { 
      $prec="";
   } else {
      $prec=$da[$counter-1];
   };
   if ($counter==count($da)) {
      $suiv="";
   } else {
      $suiv=$da[$counter+1];
   };
   
   if ($prec!="") {
      echo " <a href=?original=".rawurlencode($prec)."> PREV </a>";
   };
   if ($allow_jpeginfo==1) {
      echo " <a href=?jpeginfo=".rawurlencode($thedir.$image). " target=_jpeginfo> Image Info </a>";
   };
   if ($suiv!="") {
      echo " <a href=?original=".rawurlencode($suiv).">NEXT</a>";
   };

   echo "<br/><a href=?big=".rawurlencode($thedir.$image)."><img src=\"".rawurlencode($thedir.$image)."\" border=\"0\" /></a><br/>";

   if ($allow_comments==1) {
      echo "<FORM  METHOD=get>\n";
      echo "<INPUT TYPE=HIDDEN NAME=img VALUE=\"$image\"/>\n";
      echo "<INPUT TYPE=TEXT NAME=text VALUE=\"Comment\"/><BR>\n";
      if (!isset($yappanom)) {
	 $nom="your name";
      } else { 
	 $nom=$yappanom;
      }; 
      echo "<INPUT TYPE=TEXT NAME=nom VALUE=\"$nom\"/><BR>\n";
      echo "<INPUT TYPE=SUBMIT NAME=Valider VALUE=\"Submit\"/> \n";
      echo "</FORM>\n";
   }
}

function infodisplay($image,$da) {
global $allow_comments,$allow_jpeginfo,$yappanom;
   $current="";
   $counter=0;

   echo "<br/><center><b>Image Info For ".rawurlencode($thedir.$image)."</b></center><br/>";
   // For cleanleness
   echo "<pre>";
   system("jhead \"".rawurlencode($thedir.$image)."\"");
   echo "</pre>";

   if ($allow_comments==1) {
      echo "<FORM  METHOD=get>\n";
      echo "<INPUT TYPE=HIDDEN NAME=img VALUE=\"$image\"/>\n";
      echo "<INPUT TYPE=TEXT NAME=text VALUE=\"Comment\"/><BR>\n";
      if (!isset($yappanom)) {
	 $nom="your name";
      } else { 
	 $nom=$yappanom;
      }; 
      echo "<INPUT TYPE=TEXT NAME=nom VALUE=\"$nom\"/><BR>\n";
      echo "<INPUT TYPE=SUBMIT NAME=Valider VALUE=\"Submit\"/> \n";
      echo "</FORM>\n";
   }
}


//write a file in the current directory with al data for a comment
function  addcomment($remote,$date,$text,$name,$file) {
   if (is_writable(".")) {
      $fd=fopen($file.".txt","a+");
      fwrite($fd,"$remote|$date|$name|$text\n");
      fclose($fd);
   } else {
      echo "pb pour ecrire";
   };
};


// display a text file passed as argument
function displaycomment($file) {
  if ((file_exists($file.".txt")) && (is_readable($file))) {
     $fd=fopen($file.".txt","r");
     $data=fread($fd,filesize($file));
     fclose($fd);
     $dataexploded=explode("\n",$data);
     for($i=0;$i<count($dataexploded)-1;$i++) {
          $dataexploded2=explode("|",$dataexploded[$i]);
          echo $dataexploded2[2].": ".$dataexploded2[3]." <br><font size=\"-2\">(".$dataexploded2[1].")</font><br>";
     } 
  }

};

//return a table of all pictures.
function GetDirArray($sPath) {

   //Load Directory Into Array 
   $handle=opendir($sPath); 
   while ($file = readdir($handle))
     if ( ((ereg(".*\.jpg$",$file)) || (ereg("\.JPG$",$dir."/".$file))|| (ereg(".*\.jpeg$",$file)))
          && (is_file($file)) ) {
          $retVal[count($retVal)] = $file;
     };

   //Clean up and sort
   closedir($handle);
   if (count($retVal)>0) {
      sort($retVal);
   };
   return $retVal;
};

function sendHTMLhead($TITLE) {
   echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"";
   echo  "    \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
   echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";   
   echo "<head>\n";
   echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"/>\n";
   echo "<meta name=\"author\" content=\"Mooby\"/>\n";
   echo "<meta name=\"GENERATOR\" content=\"yappa\" />\n";
   echo "<title>$TITLE</title>\n";
   echo "<style>\n";
   echo "    img { border: none; }\n";
   echo "    body { background: white;\n";
   echo "           color: black;\n";
   echo "           font-family: Arial, Helvetica, sans-serif;\n";
   echo "           margin: 5pt; }\n";
   echo " </style>\n";
   echo "</head>\n";
   echo "<body>\n";
};


function footerandendHTML() {
   echo "</body>\n";
   echo "</html>\n";
};

// in normal operation, display picturess and menu.
function normalaction($uri,$ip) {
   global $original,$big,$jpeginfo,$text,$nom,$img,$Valider,$allow_comments,$allow_jpeginfo,$autocreatethumbnails;
   echo "<table border=\"1\" width=\"80%\" cellspacing=\"0\">\n";

   // ############## START OF TOP LINE
   echo "<tr>\n";
   echo "<td> <a href=\"http://manu.agat.net/yappa/\">Yappa</a> generated</td><td>\n";
   mysplit($uri);
   echo "\n";
   echo "";
   echo "</td>\n";
   echo "</tr>\n";
   // end of top line
   //
   // ############### BEGIN left side for sub dirs
   echo "<tr>\n";
   echo "<td width=18% valign=top>\n";
   mydirectorylist($uri);
   echo "\n";
   // If we are on the base directory, add admin link and forgotten pass
   if (!is_link("index.php")) {
      echo "<hr/><hr/>";
      echo "<a href=admin/>Administration</a> (restricted area)";
      echo "<hr/>";
      echo "<form>Forgotten password? type your admin email to get a new password: ";
      echo "<input type=text name=email><input type=submit value=Send>";
      echo "</form> (email will be verified before)";
   }
   echo "</td>\n";
   // end left side


   // ###############  begin for right side for photos
   echo "<td align=center>\n";
   // compute a table of all files.
   $indexpictures=GetDirArray(realpath("."));
   if (isset($big)) {
     fulldisplay($big,$indexpictures);
   } else if (isset($jpeginfo))
   {
     infodisplay($jpeginfo,$indexpictures);
   } else if (isset($original))
   {
     originaldisplay($original,$indexpictures);
   } else
     {
     if ((isset($Valider)) && ($allow_comments==1) ) {
       addcomment($ip,date("Y-m-d H:i"),$text,$nom,$img);
     }
     // create thumbnails if they don't exists.
     if ($autocreatethumbnails==1) {
       createtn(getcwd(),"color");
     }
     displaygeneralcomment();
     // display them
     displaytn($uri);
   }
   echo "\n";
   echo "</td>\n";
   // ############### end right side
   echo "</tr>\n";
   echo "</table>\n";
};

// display a comment general for the current album
function displaygeneralcomment() {
   if (file_exists("comment.html")) {
      readfile("comment.html");
   };
};

function compareandall($email) {
global $basedir;
   // first compage email and an entry in .htpasswd
   $fd=fopen("admin/.htpasswd","r");
   $found="";
   while (!feof($fd) && ($found=="")) {
       $buffer = fgets($fd, 4096);
       $bufferexploded=explode(":",$buffer);
       if ($bufferexploded[0]==rawurldecode($email)) {
          $found=$bufferexploded[0];
       };
   };
   fclose ($fd);
   if ($found!="") {
        echo "found Email";
        $time=gettimeofday();
        $pass=$time["usec"];
        $time=gettimeofday();
        $pass.=$time["usec"];
        if (file_exists("$basedir/admin/.htpasswd")) {
           $command="htpasswd -mb $basedir/admin/.htpasswd $email $pass";
           system($command);
        } else {
           $fd=fopen("$basedir/admin/.htpasswd","w");
           $data=$email.":".crypt($pass);
           fwrite($fd,$data);
           fclose($fd);
        };
        mail($email,"Yappa administration","From: hide@address.com\nPassword is :\n$pass\nSee you later");
        echo "Update done";
   } else {
        echo "No corresponding email found";
   }
}


function createadminstuff() {
};

/*
  END OF FUNCTIONS
*/

//begin of CODE

  if (is_link("index.php")) {
   //we are not in the base of the admin dir.
    $basedir=dirname(readlink("index.php"));
  } else {
    //we are on the base of the photo album
    $basedir=getcwd();
  };
  $base_dir_picture=basename($basedir);
 
  if ((!file_exists("$basedir/config.php")) ) {
       writeconfig($basedir,1,1,3);
  };
  include("$basedir/config.php");

  if (file_exists("config.php")) {
     include("config.php");
  }
  
  
//echo "basedir=$basedir<br>";
//echo "base_dir_picture:$base_dir_picture<br>";
$base=basename($basedir);
//echo "base:$base<br>";
$data1=explode("?",$GLOBALS["REQUEST_URI"]);
$baseURL=$data1[0];
//echo "baseURL:$baseURL";

// START OF PAGE
if ((basename(getcwd())!=$base) || (file_exists("admin") && is_dir("admin"))) {
   //normal stuff. look if we are in admin or not:
   if (basename(getcwd())=="admin") {
      //ADMIN PART
      adminheaders($baseURL);
      if (isset($actiondir)) {
         //test valididy of $actiondir: ../.. and other tricks must be intercepted.
         //if realpath don't contain $base, $actiondir must have ../.. or something like that.
         $realpath=realpath($basedir."/".$actiondir);
         if (ereg(".*$base.*",$realpath)) {
            if (file_exists("$realpath/config.php")) {
                include("$realpath/config.php");
            }
            workonadirectory($actiondir,$basedir,$baseURL);
         } else {
             echo "Sorry cannot read the specified dir";
         }
      } else {
         sendnormaloperations($basedir,$baseURL);
      }
      adminendhtml();
   } else {
      // NORMAL PAGE
      sendHTMLhead($TITLE);
      if (isset($email)) {
         compareandall($email);
      };
      normalaction($GLOBALS["REQUEST_URI"],$GLOBALS["REMOTE_ADDR"]);
      footerandendHTML();
   }
} else {
   if (!isset($firsttime)) {
      sendHTMLhead($TITLE);
      if (is_writeable(".")) {
         echo "<p><br/><br/>Welcome to yappa. Please write your email, so I can send you a new password to administrate your <code>Yet Another PHP Photo Album</code>. If you don't have htpasswd in your path, edit and modifiy the script, or you won't be able to change your password! (will be fixed in next version)";
         echo "<p/><form>Your email:<input type=text name=firstemail><input type=submit name=firsttime value=\"Get my first password\"></form>";
         echo "Thanks for using YAPPA!";
      } else {
         echo "Please make your current dir (".getcwd().") writeable by the web server!!!";
      }
      footerandendHTML();
   } else {
      mkdir("admin","0755");
      sendHTMLhead($TITLE);
      if (!file_exists("$basedir/admin/.htaccess")) {
          $fd=fopen("$basedir/admin/.htaccess","w");
          $data="AuthName \"Admin yappa. (Email as login)\"\n";
          $data.="AuthType Basic\n";
          $data.="AuthUserFile  $basedir/admin/.htpasswd\n";
          $data.="AuthGroupFile None\n";
          $data.="require valid-user";
          fwrite($fd,$data);
          fclose($fd);
       };

      // TODO: test email validity
      $time=gettimeofday();
      $pass=$time["usec"];
      $time=gettimeofday();
      $pass.=$time["usec"];
//      $command="htpasswd -cmb $basedir/admin/.htpasswd $firstemail $pass";
//Removed, and to be propaged: binary not in path?...
// A function must be done for that!
      if (!file_exists("$basedir/admin/.htpasswd")) {
          $fd=fopen("$basedir/admin/.htpasswd","w");
          $data=$firstemail.":".crypt($pass);
          fwrite($fd,$data);
          fclose($fd);
      }

      mail($firstemail,"Yappa administration","From: hide@address.com\nThe password is  :\n$pass\nSee you later");
      echo "Thanks for using YAPPA!<br>";
      echo "<a href=".$baseURL.">Click here to access to the photo album</a>";
      footerandendHTML();

   }
}
?>
Return current item: Yappa-Yet Another PHP Photo Album