//
// to fix
//           handle alternate charsets (for churchyard)
//
// etogal version 1.1 beta 3
// Fixes
// 14/04/06: MySQL 3.x compatibility: Join replaced by Left Join
// 29/04/06: 'Save Changes' string corrected for internationalisation
// 6 May : added prefix of EG to class names to avoid conflicts (EGthumbnail and EGimageview)
// 7 may : fix descriptions handling in is_target display (contributed by doze)
//         generate URLs using makeURL (tested with FURLs)
//
// Additions
// 29/04/06:
//    quality   low, medium or high (low is the original Etogal setting, high mikef's improved quality)
//    delete   0 or 1 (0=only administrators can delete images)
//    display  additional option of 'none' gives no image display, only manage button or management functions (when valid)
//
// this version retains the EtoGal 1.0 database table structure
// ----- Setting(s) ------
// Path where the galleries will be stored (you have to create it and make it writeable!)
$path_to_galleries="assets/galleries/";
// -----------------------

// etoGal is copyright 2005-2006 Frank Siegert and Mike Finley
//     and is available under the GPL licence

// Internationalization
$strings['previous']="&laquo; previous";
$strings['index']="Index";
$strings['next']="next &raquo;";
$strings['click_to_zoom']=" (Click to zoom ->)";
$strings['click_to_go_back']="<- Click to go back";
$strings['back_to_normal_view']="Back to normal view";
$strings['no_more_pictures_found_return_to']="No more pictures found. Return to ";
$strings['go_to_gallery']="Go to gallery ->";
$strings['pictures_successfully_uploaded']="Pictures successfully uploaded.";
$strings['changes_have_been_saved']="Changes have been saved.";
$strings['delete']="Delete";
$strings['title']="Title";
$strings['save_changes']="Save changes";
$strings['upload_pictures']="Upload pictures";
$strings['check_to_delete_this_picture']="Check to delete this picture";
$strings['manage_pictures']="Manage Pictures";
$strings['date']="Date";
$strings['description']="Description";
$strings['database_no_description_support']="<em>This database table does not permit the use of picture descriptions!</em><br />";

/*
// German
$strings['previous']="&laquo; vorheriges";
$strings['index']="Index";
$strings['next']="n&auml;chstes &raquo;";
$strings['click_to_zoom']="Zoom ->";
$strings['click_to_go_back']="<- Back";
$strings['back_to_normal_view']="Normalansicht";
$strings['no_more_pictures_found_return_to']="Keine weiteren Bilder gefunden. Zur&uuml;ck zu ";
$strings['go_to_gallery']="Galerie anschauen ->";
$strings['pictures_successfully_uploaded']="Bilder erfolgreich hochgeladen.";
$strings['changes_have_been_saved']="&Auml;nderungen gespeichert.";
$strings['delete']="L&ouml;schen";
$strings['title']="Titel";
$strings['save_changes']="&Auml;nderungen speichern";
$strings['upload_pictures']="Bilder hochladen";
$strings['check_to_delete_this_picture']="Ankreuzen, um Bild zu l&ouml;schen";
$strings['manage_pictures']="Bilderverwaltung";
$strings['date']="Datum";
$strings['description']="Beschreibung";
$strings['database_no_description_support']="<em>Diese Datenbank untersttzt die Verwendung von Beschreibungen nicht.</em><br />";
*/

// set parameters
if(!isset($pics_in_a_row))   $pics_in_a_row=3;
if(!isset($max_thumb_size))  $max_thumb_size=150;
if(!isset($max_pic_size))    $max_pic_size=800;
if(!isset($order_by))        $order_by="date";
if(!isset($order_direction)) $order_direction="DESC";
if(!isset($gtable))          $gtable="etogal";
// new
if (!isset($quality))       $quality="low"; //"medium" probably a better choice, but "low" mtaches the original etoGal
if (!isset($delete))        $delete=1; //default to delete enabled (0 implies only admins can delete)

// image functions
function createthumb($filename,$path_to_gal,$max_thumb_size,$prefix="") {
  // Create resized images
  $src=imagecreatefromjpeg($path_to_gal.$filename);
  $src_size = getimagesize( $path_to_gal.$filename );

  if($src_size[0]>$src_size[1]) { //if width > height
    $new_width=$max_thumb_size;
    $new_height=$src_size[1]*($new_width/$src_size[0]);
  } else {
    $new_height=$max_thumb_size;
    $new_width=$src_size[0]*($new_height/$src_size[1]);
  }
  $dest=imagecreatetruecolor($new_width,$new_height);
  if ($quality=="low") {
    imagecopyresized($dest,$src,0,0,0,0,$new_width,$new_height,$src_size[0],$src_size[1]);
  } else {
    imagecopyresampled($dest,$src,0,0,0,0,$new_width,$new_height,$src_size[0],$src_size[1]);
  }
  if ($quality=="high") {
    imagejpeg($dest,$path_to_gal.$prefix.$filename, 100);
  } else {
    imagejpeg($dest,$path_to_gal.$prefix.$filename);
  }
}

// access control functions
// shared data
global $canEdit, $canAdd, $canDelete, $access_permitted;
$canEdit = 0;
$canAdd = 0;
$canDelete = $delete;
$access_permitted = 0;

function checkPermissions()
{
  global $etomite, $access_permitted, $canDelete;
// figure out access permissions of the user viewing this page
  $userdetails=$etomite->userLoggedIn();
  if($userdetails['id']) {
  // check whether user is allowed to modify this page
    $rs1=$etomite->dbQuery("SELECT * FROM (" . $etomite->db . "member_groups LEFT JOIN " . $etomite->db . "membergroup_access ON user_group=membergroup) LEFT JOIN " . $etomite->db . "document_groups ON documentgroup=document_group WHERE member='" . $userdetails['id'] . "' and document='" . $etomite->documentIdentifier . "'");
    if (mysql_num_rows($rs1)) {
      $access_permitted=1;
      $canEdit=1;
    }
  // check if user is administrator  (more efficient if this is first test ...)
    $rs2=$etomite->dbQuery("SELECT * FROM " . $etomite->db . "user_attributes WHERE id='" . $userdetails['id'] . "' AND role='1'");
    if(mysql_num_rows($rs2)) {
      $access_permitted=1;
      $canAdd=1;
      $canEdit=1;
//      $canDelete=1;
    }
  }
//  return $access_permitted;
}

// retrieve data from etomite
$pageinfo=$etomite->getPageInfo($etomite->documentIdentifier,1, "id, pagetitle, longtitle, description, alias, createdby");
$path_to_gal=$path_to_galleries.$pageinfo['id']."/";
//$phpself="index.php?id=".$pageinfo['id'];
$phpself=$etomite->makeURL($pageinfo['id']);
if (strpos($phpself,"?")) $sep="&amp;"; else $sep="?";

// check for table and descriptions
$pics_tbl = $etomite->db.$gtable;
// If gallery table has not been created yet, create it now:
$descvalid = 0; // assume descriptions not supported
$query=mysql_query("DESC $pics_tbl");
if(!$query) {
  $sql="CREATE TABLE $pics_tbl (
          `id` int(10) unsigned NOT NULL auto_increment,
          `gal_id` int(10) unsigned NOT NULL,
          `filename` varchar(50) NOT NULL,
          `title` text NOT NULL,
          `date` datetime NOT NULL,
          `descr` text default NULL,
          PRIMARY KEY  (`id`)
          ) TYPE=MyISAM AUTO_INCREMENT=1 ;";
  $query1=$etomite->dbQuery($sql);
  $descvalid = 1; // they are with this table
}
else {
  //test for the descr field
  for($i=0;$i<$this->recordCount($query);$i++)  {
    $temprow=@$this->fetchRow($query, 'assoc');
    if ($temprow["Field"]=="descr") {
      $descvalid=1;
      break;
    }
  }
  if($descvalid==0) { // If no descr-field there: add it.
    $query2=@$etomite->dbQuery("ALTER TABLE $pics_tbl ADD `descr` TEXT DEFAULT NULL ;");
    if($query2) { $descvalid=1; }
  }
}



if($is_target=="yes" && $_REQUEST['gal_id']) { // only display the picture of another gallery
  if ($_REQUEST['pic']) {
    $pics=$etomite->getIntTableRows("id,title,filename,descr", $gtable, "gal_id='" . $_REQUEST['gal_id'] . "'", $order_by, $order_direction);

    $i=0;
    foreach($pics as $pic) {
      if($pic['id']==$_REQUEST['pic']) {
        $current=$i;
        break;
    }
      $i++;
  }
    $returnstring.="
    <p style='text-align:center;'>
      <a href='".$phpself.$sep."pic=".$pics[$i-1]['id']."&amp;gal_id=".$_REQUEST['gal_id']."'>" . $strings['previous'] . "</a> |
      <a href='".$etomite->makeURL($_REQUEST['gal_id'])."'>". $strings['index'] . "</a> |
      <a href='".$phpself.$sep."pic=".$pics[$i+1]['id']."&amp;gal_id=".$_REQUEST['gal_id']."'>" . $strings['next'] . "</a>
    </p>
    <center>
      <a href='".$etomite->makeURL($_REQUEST['gal_id'])."'><img src='" . $path_to_galleries.$_REQUEST['gal_id']."/".$pics[$i]['filename'] . "' class='EGimageview' title='".$strings['click_to_go_back']."' alt='".$strings['click_to_go_back']."' /></a><br/>
    <p><b>" . htmlentities(stripslashes($pics[$i]['title'])) . "</b></p>";
    if ($descvalid==1) $returnstring .= "<p>" . stripslashes($pics[$i]['descr']) . "</p>";
    $returnstring .= "</center>";
  }
  else {
    $returnstring.="<center>" . $strings['no_more_pictures_found_return_to'] . "<a href='".$etomite->makeURL($_REQUEST['gal_id'])."'>" . $strings['index'] . "</a></center>";
  }
  return $returnstring;
}

if($display=="childgalleries") {
  $pageinfo=$etomite->getPageInfo($etomite->documentIdentifier,1, "id, pagetitle, description, alias, createdby");
  $children = $etomite->getActiveChildren($pageinfo['id'], "menuindex", "ASC", $fields='id, pagetitle, longtitle, description, parent, alias');
  $returnstring.="<table border=\"0\" width=\"100%\">";

  $number_in_row=0;
  $total_number=0;
  foreach($children as $child) {
    $thumb=$etomite->getIntTableRows("filename", $gtable, "gal_id='" . $child['id'] . "'",$order_by,$order_direction,"1");
    if($thumb[0]['filename']=="") continue ;
    if($number_in_row==0) {
      $returnstring.="<tr>";
    }
    $childself = "index.php?id=".$child['id']; //MF removed use of alias

    $returnstring.="
      <td align=\"center\" style=\"width:" . floor(100/$pics_in_a_row) . "%\">
      <a href=\"".$childself."\">
      <img src=\"".$path_to_galleries.$child['id']."/tn_".$thumb[0]['filename']."\" class=\"EGthumbnail\" title=\"" .$strings['go_to_gallery'] . "\" alt=\"" . $strings['go_to_gallery'] . "\" />
      </a>
      <br/>" . htmlentities(stripslashes($child['pagetitle'])) . "</td>";

    if($number_in_row==($pics_in_a_row-1) || $total_number==count($children)) {
      $returnstring.="</tr>";
      $number_in_row=-1;
    }
    $number_in_row++;
    $total_number++;
  }

  $returnstring.="</table>";
  return $returnstring;
}

//************************************* begin admin block

// figure out access permissions of the user viewing this page
checkPermissions();

//at present we neither create nor use all access codes - only specific test is for delete capability
if($access_permitted==1) {
  if($_REQUEST['mode']=="admin") {  // if user is allowed to modify and has entered admin mode:
    if($descvalid==0) $returnstring.=$strings['database_no_description_support']; //MF 2005
    /* Processors -----------------*/
    if($_REQUEST['action']=="upload_pics") {    // If "Upload pictures" has been used
      if(!file_exists($path_to_gal)) {
        mkdir($path_to_gal);
        chmod($path_to_gal,0777);
      }
      for($i=0;$i<10;$i++) { // for each of the ten upload fields:
        $name=strtolower($_FILES['file'.$i]['name']);
        if (file_exists($path_to_gal.$name)) { $name="a" . $name; }
        if($name!="" && $name!="a") {
          // Upload file(s) to gallery folder
          //if(substr_count($name,".jpg")>0 || substr_count($name,".jpeg")>0) {
          if(substr($name,-4)==".jpg" || substr($name,-5)==".jpeg") {
            move_uploaded_file( $_FILES['file'.$i]['tmp_name'] , $path_to_gal.$name );
            chmod($path_to_gal.$name,0666);
            $pic_date = "NOW()";
            // Read EXIF information
            if(function_exists("exif_read_data")) {
              $exif = exif_read_data($path_to_gal.$name, 0, true);
              if(array_key_exists("EXIF", $exif)) {
                $pic_date = " '".$exif["EXIF"]["DateTimeOriginal"]."' ";
              }
            }

            createthumb($name,$path_to_gal,$max_thumb_size,"tn_");
            $imagesize=getimagesize($path_to_gal.$name);
            if($max_pic_size>0 && ($imagesize[0]>$max_pic_size || $imagesize[1]>$max_pic_size)) {
              createthumb($name,$path_to_gal,$max_pic_size);
            }
            $rs1=$etomite->dbQuery("INSERT INTO " . $pics_tbl . "(id, gal_id, filename, title, date) VALUES(NULL,'" . $pageinfo['id'] . "','" . $name . "',''," . $pic_date . ")"); //MF Oct2005
          }

          //if(substr_count($name,".zip")>0) {
          if(substr($name,-4)==".zip") {
            move_uploaded_file( $_FILES['file'.$i]['tmp_name'] , $path_to_gal.$name );
            chmod($path_to_gal.$name,0644);

            $zip = zip_open($path_to_gal.$name);

            if ($zip) {
              while ($zip_entry = zip_read($zip)) {
                $jpgfilename=strtolower(zip_entry_name($zip_entry));
                if (file_exists($path_to_gal.$jpgfilename)) { $jpgfilename="a" . $jpgfilename; }
                if (zip_entry_open($zip, $zip_entry, "r")) {
                  $jpgfile=fopen($path_to_gal.$jpgfilename,"a+b");
                  fwrite($jpgfile,zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
                  fclose($jpgfile);
                  $imagesize=getimagesize($path_to_gal.$jpgfilename);
                  if($max_pic_size>0 && ($imagesize[0]>$max_pic_size || $imagesize[1]>$max_pic_size)) {
                    createthumb($jpgfilename,$path_to_gal,$max_pic_size);
                  }

                  $pic_date = "NOW()";
                  // Read EXIF information
                  if(function_exists("exif_read_data")) {
                    $exif = exif_read_data($path_to_gal.$jpgfilename, 0, true);
                    if(array_key_exists("EXIF", $exif)) {
                      $pic_date = " '".$exif["EXIF"]["DateTimeOriginal"]."' ";
                    }
                  }

                  createthumb($jpgfilename,$path_to_gal,$max_thumb_size,"tn_");
                  $rs1=$etomite->dbQuery("INSERT INTO " . $pics_tbl . " (id, gal_id, filename, title, date)VALUES(NULL,'" . $pageinfo['id'] . "','" . $jpgfilename . "',''," . $pic_date . ")"); //MF Oct2005
                  zip_entry_close($zip_entry);
                }
              }
              zip_close($zip);
            }
            unlink($path_to_gal.$name);
          }



        }
      }
      $returnstring.=$strings['pictures_successfully_uploaded'];
    }


    if($_REQUEST['action']=="edit_pics") {    // If "Edit Gallery and its pictures" has been used
      for($i=0;$i<$_REQUEST['number'];$i++) {
        if($_REQUEST['delete'.$i]=="yes") {
          $rs0=$etomite->dbQuery("SELECT id,filename FROM $pics_tbl WHERE id='" . $_REQUEST['pic_id'.$i] . "'");
          $deletepic=$etomite->fetchRow($rs0);
          if(file_exists($path_to_gal.$deletepic['filename'])) unlink($path_to_gal.$deletepic['filename']);
          if(file_exists($path_to_gal."tn_".$deletepic['filename'])) unlink($path_to_gal . "tn_" . $deletepic['filename']);
          $rs1=$etomite->dbQuery("DELETE FROM $pics_tbl WHERE id='" . $_REQUEST['pic_id'.$i] . "'");
}
        if($_REQUEST['modified'.$i]=="yes") {
          // restructured for clarity and extended MF oct2005
          $updateQueryString= "UPDATE ".$pics_tbl." SET ";
          $updateQueryString.= "title='".addslashes($_REQUEST['title'.$i])."'"; //add title content
          if($keep_date!="yes") $updateQueryString.=",date=NOW()";
          if($descvalid==1) $updateQueryString.=", descr='".addslashes($_REQUEST['descr'.$i])."'"; //MF add descr content
          $updateQueryString.=" WHERE id='" .$_REQUEST['pic_id'.$i]."'";
          $rs2=$etomite->dbQuery( $updateQueryString );
        }
      }
      $returnstring.=$strings['changes_have_been_saved'];
    }

    /* Forms ----------- */
    // Edit gallery and its pictures
    $returnstring.="
    <form action=\"".$phpself."\" method=\"post\" name=\"activateviewform\">
    <input type=\"hidden\" name=\"mode\" value=\"view\">
    <center><input type=\"submit\" value=\"" . $strings['back_to_normal_view'] . "\"></center>
    </form>";
    $returnstring.="<p style=\"padding-left:4px;\">" . htmlentities($pageinfo['description']) . "</p>
    <form action=\"".$phpself."\" method=\"post\" name=\"editform\">
    <input type=\"hidden\" name=\"action\" value=\"edit_pics\">
    <input type=\"hidden\" name=\"mode\" value=\"admin\">
    <input type=\"submit\" value=\"".$strings['save_changes']."\">
    <table border=\"0\">
    ";

    $rs1=$etomite->dbQuery("SELECT * FROM " . $pics_tbl . " WHERE gal_id='" . $pageinfo['id'] . "' ORDER BY " . $order_by . " " . $order_direction);
    $i=0;
    while($pic=$etomite->fetchRow($rs1)) {
      $file = $path_to_gal.$pic['filename'] ;
      $tn_file = $path_to_gal . "tn_" . $pic['filename'] ;
//form definition modified Oct2005 by MF to add description
      $returnstring.="
      <input type=\"hidden\" name=\"pic_id$i\" value=\"" . $pic['id'] . "\">
      <input type=\"hidden\" name=\"modified$i\" value=\"no\">
      <tr>
        <td><a href=\"$file\" target=_new><img src=\"$tn_file\" class=\"EGthumbnail\" alt=\"" . $strings['click_to_zoom'] . "\" /></a></td>";
        if ($canDelete) $returnstring.="<td>" . $strings['delete'] . ": <input type=\"checkbox\" name=\"delete$i\" value=\"yes\" title=\"" . $strings['check_to_delete_this_picture'] . "\"></td>";
        $returnstring.="<td>" . $strings['title'] . ":<br/><textarea name=\"title$i\" rows=\"5\" cols=\"20\" onKeyDown=\"document.editform.modified$i.value='yes'\">" . stripslashes($pic['title']) . "</textarea></td>
        ";
        if ($descvalid==1) $returnstring .= "<td>" . $strings['description'] . ":<br/><textarea name=\"descr$i\" rows=\"5\" cols=\"40\" onKeyDown=\"document.editform.modified$i.value='yes'\">" . stripslashes($pic['descr']) . "</textarea></td>";
        $returnstring .= "
      </tr>
      ";
      $i++;
    }


    $returnstring.="
    </table>
    <input type=\"hidden\" name=\"number\" value=\"$i\">
    <input type=\"submit\" value=\"".$strings['save_changes']."\">
    </form>
    <form action=\"".$phpself."\" method=\"post\" enctype=\"multipart/form-data\" name=\"uploadform\">
    <input type=\"hidden\" name=\"action\" value=\"upload_pics\">
    <input type=\"hidden\" name=\"mode\" value=\"admin\">
    ";
    for($i=0;$i<10;$i++) $returnstring.="<input name=\"file$i\" type=\"file\">";
    $returnstring.="
    <input type=\"submit\" value=\"".$strings['upload_pictures']."\">
    </form>
    ";

    return $returnstring;
  }


  else { // if user is allowed to modify, but has not entered admin mode yet
    $returnstring.="
    <form action=\"".$phpself."\" method=\"post\" name=\"activateadminform\">
    <input type=\"hidden\" name=\"mode\" value=\"admin\">
    <center><input type=\"submit\" value=\"" . $strings['manage_pictures']."\"></center>
    </form>
    ";
  }
}

// ************ end admin block

if($display=="none") return $returnstring;

if ($_REQUEST['pic']) { // Show single Pic
// we retrieve all the pics for the gallery here, so that we can fill in the previous and next links later
  $pics=$etomite->getIntTableRows("*", $gtable, "gal_id='" . $pageinfo['id'] . "'", $order_by, $order_direction);
  $i=0;
  foreach($pics as $pic) {
    if($pic['id']==$_REQUEST['pic']) {
      $current=$i;
      break;
    }
    $i++;
  }
  $returnstring.="
  <p style=\"text-align:center;\">
    <a href=\"".$phpself.$sep."pic=".$pics[$i-1]['id']."\">" . $strings['previous'] . "</a> |
    <a href=\"".$phpself."\">" . $strings['index'] . "</a> |
    <a href=\"".$phpself.$sep."pic=".$pics[$i+1]['id']."\">" . $strings['next'] . "</a>
  </p>
  <center>
    <a href=\"".$phpself."\"><img src=\"" . $path_to_gal.$pics[$i]['filename'] . "\" class=\"EGimageview\" title=\"".$strings['date'].": ".$pics[$i]['date']."\" alt=\"" . $strings['click_to_go_back']. "\" /></a><br/>
    <p><b>" . htmlentities(stripslashes($pics[$i]['title'])) . "</b></p>";
    if ($descvalid==1) $returnstring .= "<p>" . stripslashes($pics[$i]['descr']) . "</p>"; //MF Oct2005
    $returnstring .= "
  </center>
  ";
} else {
// Show gallery overview with thumbnails
  $returnstring.="
  <table border=\"0\" width=\"100%\">";

  $pics=$etomite->getIntTableRows("id,title,filename", $gtable, "gal_id='" . $pageinfo['id'] . "'",$order_by,$order_direction);
  $number_in_row=0;
  $total_number=0;
  foreach($pics as $pic) {
    $file = $path_to_gal . $pic['filename'] ;
    $tn_file = $path_to_gal . "tn_" . $pic['filename'] ;

    if($number_in_row==0) {
      $returnstring.="<tr>";
    }

    $link= ( $display==embedded ? "<a href=\"" . $file . "\" target=_blank>" : "<a href=\"" . $phpself.$sep."pic=" . $pic['id'] . "\">" );

    if(isset($picture_target)) {
      $link="<a href='".$etomite->makeURL($picture_target,'',"?gal_id=".$pageinfo['id']."&amp;pic=".$pic['id'] ) . "'>";
    }

    $pictitle=htmlentities(stripslashes($pic['title']));
    $returnstring.="
    <td align=\"center\" style=\"width:" . floor(100/$pics_in_a_row) . "%\">".
      $link . "<img src=\"$tn_file\" class=\"EGthumbnail\" title=\"" . $pictitle . $strings['click_to_zoom'] . "\" alt=\"" . $pictitle . $strings['click_to_zoom'] . "\" /></a>" . ($titles_in_overview=="yes" ? "<br />".$pictitle : "") . "
    </td>";

    if($number_in_row==($pics_in_a_row-1) || $total_number==(count($pics)-1)) {
      $returnstring.="
      </tr>";
      $number_in_row=-1;
    }
    $number_in_row++;
    $total_number++;
  }
  $returnstring.="
  </table>";
}

return $returnstring;
