<?php

require_once "phpfspot_cfg.php";
require_once "phpfspot_db.php";
require_once "phpfspot_tmpl.php";

class PHPFSPOT {

   var $cfg;
   var $db;
   var $cfg_db;
   var $tmpl;
   var $tags;
   var $avail_tags;
   var $current_tags;

   public function __construct()
   {
      $this->cfg = new PHPFSPOT_CFG;

      $this->db = new PHPFSPOT_DB(&$this, $this->cfg->fspot_db);

      $this->cfg_db = new PHPFSPOT_DB(&$this, $this->cfg->phpfspot_db);
      $this->check_config_table();

      $this->tmpl = new PHPFSPOT_TMPL($this);

      $this->get_tags();

      session_start();

      if(!isset($_SESSION['tag_condition']))
         $_SESSION['tag_condition'] = 'or';

      if(!isset($_SESSION['searchfor']))
         $_SESSION['searchfor'] = '';

   } // __construct()

   public function __destruct()
   {

   } // __destruct()

   public function show()
   {
      $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
      $this->tmpl->assign('page_title', $this->cfg->page_title);
      $this->tmpl->assign('current_condition', $_SESSION['tag_condition']);
      $this->tmpl->show("index.tpl");

   } // show()

   private function get_tags()
   {
      $this->avail_tags = Array();
      $count = 0;
   
      $result = $this->db->db_query("
         SELECT id,name
         FROM tags
         ORDER BY sort_priority ASC
      ");
      
      while($row = $this->db->db_fetch_object($result)) {

         $tag_id = $row['id'];
         $tag_name = $row['name'];

         /* check if config requests to ignore this tag */
         if(in_array($row['name'], $this->cfg->hide_tags))
            continue;

         $this->tags[$tag_id] = $tag_name; 
         $this->avail_tags[$count] = $tag_id;

         $count++;

      }

   } // get_tags()

   public function get_photo_details($idx)
   {
      $result = $this->db->db_query("
         SELECT *
         FROM photos
         WHERE id='". $idx ."'
      ");
      
      return $this->db->db_fetch_object($result);

   } // get_photo_details

   public function translate_path($path, $width = 0)
   {  
      return str_replace($this->cfg->path_replace_from, $this->cfg->path_replace_to, $path);

   } // translate_path

   public function showPhoto($photo)
   {
      $all_photos = $this->getPhotoSelection();

      foreach($all_photos as $all_photo) {
         
         if($get_next) {
            $next_img = $all_photo;
            break;
         }

         if($all_photo == $photo) {
            $get_next = 1;
         }
         else {
            $previous_img = $all_photo;
         }
      }

      $details = $this->get_photo_details($photo);
      $orig_path = $this->translate_path($details['directory_path']) ."/". $details['name'];
      $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->photo_width ."_". $this->getMD5($photo);

      /* If the thumbnail doesn't exist yet, try to create it */
      if(!file_exists($thumb_path)) {
         $this->gen_thumb($photo, 0, 1);
      }

      $meta = $this->get_meta_informations($orig_path);

      if(file_exists($thumb_path)) {

         $info = getimagesize($thumb_path);

         $this->tmpl->assign('description', $details['description']);
         $this->tmpl->assign('image_name', $details['name']);

         $this->tmpl->assign('width', $info[0]);
         $this->tmpl->assign('height', $info[1]);
         $this->tmpl->assign('ExifMadeOn', strftime("%a %x %X", $meta['FileDateTime']));
         $this->tmpl->assign('ExifMadeWith', $meta['Make'] ." ". $meta['Model']);
         $this->tmpl->assign('ExifOrigResolution', $meta['ExifImageWidth'] ."x". $meta['ExifImageLength']);
         $this->tmpl->assign('ExifFileSize', round($meta['FileSize']/1024, 1));
    
         $this->tmpl->assign('image_url', 'phpfspot_img.php?idx='. $photo ."&amp;width=". $this->cfg->photo_width);
         $this->tmpl->assign('image_url_full', 'phpfspot_img.php?idx='. $photo);

         $this->tmpl->assign('tags', $this->get_photo_tags($photo));
      }
      else {
         print "Can't open file ". $thumb_path ."\n";
      }

      if($previous_img) {
         $this->tmpl->assign('previous_url', "javascript:showImage(". $previous_img .");");
      }

      if($next_img) {
         $this->tmpl->assign('next_url', "javascript:showImage(". $next_img .");");
      }

      $this->tmpl->show("single_photo.tpl");

   } // showPhoto()

   public function getAvailableTags()
   {
      $result = $this->db->db_query("
         SELECT tag_id as id, count(tag_id) as quantity
         FROM photo_tags
         INNER JOIN tags t
            ON t.id = tag_id
         GROUP BY tag_id
         ORDER BY t.name ASC
      ");

      $tags = Array();

      while($row = $this->db->db_fetch_object($result)) {
         $tags[$row['id']] = $row['quantity'];
      }

      // change these font sizes if you will
      $max_size = 125; // max font size in %
      $min_size = 75; // min font size in %

      // get the largest and smallest array values
      $max_qty = max(array_values($tags));
      $min_qty = min(array_values($tags));

      // find the range of values
      $spread = $max_qty - $min_qty;
      if (0 == $spread) { // we don't want to divide by zero
         $spread = 1;
      }

      // determine the font-size increment
      // this is the increase per tag quantity (times used)
      $step = ($max_size - $min_size)/($spread);

      // loop through our tag array
      foreach ($tags as $key => $value) {

         if(isset($_SESSION['selected_tags']) && in_array($key, $_SESSION['selected_tags']))
            continue;

          // calculate CSS font-size
          // find the $value in excess of $min_qty
          // multiply by the font-size increment ($size)
          // and add the $min_size set above
         $size = $min_size + (($value - $min_qty) * $step);
          // uncomment if you want sizes in whole %:
         $size = ceil($size);

         print "<a href=\"javascript:Tags('add', ". $key .");\" class=\"tag\" style=\"font-size: ". $size ."%;\">". $this->tags[$key] ."</a>, ";

      }

   } // getAvailableTags()

   public function getSelectedTags()
   {
      foreach($this->avail_tags as $tag)
      {
         // return all selected tags
         if(isset($_SESSION['selected_tags']) && in_array($tag, $_SESSION['selected_tags'])) {
            print "<a href=\"javascript:Tags('del', ". $tag .");\" class=\"tag\">". $this->tags[$tag] ."</a>&nbsp;";
         }

      }

   } // getSelectedTags()

   public function addTag($tag)
   {
      if(!isset($_SESSION['selected_tags']))
         $_SESSION['selected_tags'] = Array();

      if(!in_array($tag, $_SESSION['selected_tags']))
         array_push($_SESSION['selected_tags'], $tag);
   
   } // addTag()

   public function delTag($tag)
   {
      if(isset($_SESSION['selected_tags'])) {
         $key = array_search($tag, $_SESSION['selected_tags']);
         unset($_SESSION['selected_tags'][$key]);
         sort($_SESSION['selected_tags']);
      }

   } // delTag()

   public function resetTags()
   {
      unset($_SESSION['selected_tags']);

   } // resetTags()

   public function getPhotoSelection()
   {  
      $tagged_photos = Array();

      /* return a search result */
      if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '') {
         $result = $this->db->db_query("
            SELECT DISTINCT photo_id
               FROM photo_tags pt
            INNER JOIN photos p
               ON p.id=pt.photo_id
            INNER JOIN tags t
               ON pt.tag_id=t.id
            WHERE t.name LIKE '%". $_SESSION['searchfor'] ."%'
               ORDER BY p.time ASC
         ");
         while($row = $this->db->db_fetch_object($result)) {
            array_push($tagged_photos, $row['photo_id']);
         }
         return $tagged_photos;
      }

      /* return according the selected tags */
      if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
         $selected = "";
         foreach($_SESSION['selected_tags'] as $tag)
            $selected.= $tag .",";
         $selected = substr($selected, 0, strlen($selected)-1);

         if($_SESSION['tag_condition'] == 'or') {
            $result = $this->db->db_query("
               SELECT DISTINCT photo_id
                  FROM photo_tags pt
               INNER JOIN photos p
                  ON p.id=pt.photo_id
               WHERE pt.tag_id IN (". $selected .")
               ORDER BY p.time ASC
            ");
         }
         elseif($_SESSION['tag_condition'] == 'and') {

            /* Join together a table looking like

               pt1.photo_id pt1.tag_id pt2.photo_id pt2.tag_id ...

               so the query can quickly return all images matching the
               selected tags in an AND condition

            */

            $query_str = "
               SELECT DISTINCT pt1.photo_id
                  FROM photo_tags pt1
            ";

            for($i = 0; $i < count($_SESSION['selected_tags']); $i++) {
               $query_str.= "
                  INNER JOIN photo_tags pt". ($i+2) ."
                     ON pt1.photo_id=pt". ($i+2) .".photo_id
               ";
            }
            $query_str.= "WHERE pt1.tag_id=". $_SESSION['selected_tags'][0];
            for($i = 1; $i < count($_SESSION['selected_tags']); $i++) {
               $query_str.= "
                  AND pt". ($i+1) .".tag_id=". $_SESSION['selected_tags'][$i] ."
               "; 
            }
            $result = $this->db->db_query($query_str);
         }

         while($row = $this->db->db_fetch_object($result)) {
            array_push($tagged_photos, $row['photo_id']);
         }
         return $tagged_photos;
      }

      /* return all available photos */
      $result = $this->db->db_query("
         SELECT DISTINCT photo_id
            FROM photo_tags pt
         INNER JOIN photos p
            ON p.id=pt.photo_id
         ORDER BY p.time ASC
      ");
      while($row = $this->db->db_fetch_object($result)) {
         array_push($tagged_photos, $row['photo_id']);
      }
      return $tagged_photos;

   } // getPhotoSelection()

   public function showPhotoIndex()
   {
      $photos = $this->getPhotoSelection();

      $count = count($photos);

      if(!$_SESSION['begin_with'] || $_SESSION['begin_with'] == 0)
         $begin_with = 0;
      else
         $begin_with = $_SESSION['begin_with'];

      if($this->cfg->rows_per_page == 0)
         $end_with = $count;
      else
         $end_with = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);

   
      $rows = 0;
      $cols = 0;
      $images[$rows] = Array();
      $img_height[$rows] = Array();
      $img_width[$rows] = Array();

      for($i = $begin_with; $i < $end_with; $i++) {

         $images[$rows][$cols] = $photos[$i];

         $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->thumb_width ."_". $this->getMD5($photos[$i]);

         if(file_exists($thumb_path)) {
            $info = getimagesize($thumb_path); 
            $img_width[$rows][$cols] = $info[0];
            $img_height[$rows][$cols] = $info[1];
         }

         if($cols == $this->cfg->thumbs_per_row-1) {
            $cols = 0;
            $rows++;
            $images[$rows] = Array();
            $img_width[$rows] = Array();
            $img_height[$rows] = Array();
         }
         else {
            $cols++;
         }
      } 

      // +1 for for smarty's selection iteration
      $rows++;

      if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
         $this->tmpl->assign('searchfor', $_SESSION['searchfor']);

      if($this->cfg->rows_per_page != 0) {
         $previous_start = $begin_with - ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
         $next_start = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);

         if($begin_with != 0) 
            $this->tmpl->assign("previous_url", "javascript:showPhotoIndex(". $previous_start .");"); 
         if($end_with < $count)
            $this->tmpl->assign("next_url", "javascript:showPhotoIndex(". $next_start .");"); 
      }
   
      $this->tmpl->assign('count', $count);
      $this->tmpl->assign('width', $this->cfg->thumb_width);
      $this->tmpl->assign('images', $images);
      $this->tmpl->assign('img_width', $img_width);
      $this->tmpl->assign('img_height', $img_height);
      $this->tmpl->assign('rows', $rows);
      $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
      $this->tmpl->show("photo_index.tpl");


   } // showPhotoIndex()

   public function showBubbleDetails($photo, $direction)
   {
      if($direction == "up")
         $direction = "bubbleimg_up";
      else
         $direction = "bubbleimg_down";

      $details = $this->get_photo_details($photo);

      $image_url = "phpfspot_img.php?idx=". $photo ."&amp;width=". $this->cfg->bubble_width;

      $filesize = filesize($this->translate_path($details['directory_path'])  ."/". $details['name']);
      $filesize = rand($filesize/1024, 2);

      $img = getimagesize($this->translate_path($details['directory_path'])  ."/". $details['name']);

      $this->tmpl->assign('file_size', $filesize);
      $this->tmpl->assign('width', $img[0]);
      $this->tmpl->assign('height', $img[1]);
      $this->tmpl->assign('file_name', $details['name']);
      $this->tmpl->assign('image_id', $direction);
      $this->tmpl->assign('image_url', $image_url);
      $this->tmpl->show("bubble_details.tpl");

   } // showBubbleDetails()

   public function showCredits()
   {
      $this->tmpl->assign('version', $this->cfg->version);
      $this->tmpl->assign('product', $this->cfg->product);
      $this->tmpl->show("credits.tpl");

   } // showCredits()

   public function create_thumbnail($orig_image, $thumb_image, $width)
   {  
      if(!file_exists($orig_image))
         return false;

      $meta = $this->get_meta_informations($orig_image);

      $rotate = 0;
      $flip = false;

      switch($meta['Orientation']) {

         case 1:
            $rotate = 0; $flip = false; break;
         case 2:
            $rotate = 0; $flip = true; break;
         case 3:
            $rotate = 180; $flip = false; break;
         case 4:
            $rotate = 180; $flip = true; break;
         case 5:
            $rotate = 90; $flip = true; break;
         case 6:
            $rotate = 90; $flip = false; break;
         case 7:
            $rotate = 270; $flip = true; break;
         case 8:
            $rotate = 270; $flip = false; break;
      }

      $src_img = @imagecreatefromjpeg($orig_image);

      if(!$src_img) {
         print "Can't load image from ". $orig_image ."\n";
         return false;
      }

      /* grabs the height and width */
      $new_w = imagesx($src_img);
      $new_h = imagesy($src_img);

      // If requested width is more then the actual image width,
      // do not generate a thumbnail

      if($width >= $new_w) {
         imagedestroy($src_img);
         return true;
      }

      /* calculates aspect ratio */
      $aspect_ratio = $new_h / $new_w;

      /* sets new size */
      $new_w = $width;
      $new_h = abs($new_w * $aspect_ratio);

      /* creates new image of that size */
      $dst_img = imagecreatetruecolor($new_w, $new_h);

      imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));

      /* copies resized portion of original image into new image */
      imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));

      /* needs the image to be flipped horizontal? */
      if($flip) {
         print "(FLIP)";
         $image = $dst_img;
         for($x = 0; $x < $new_w; $x++) {
            imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
         }
      }

      if($rotate) {
         print "(ROTATE)";
         $dst_img = $this->rotateImage($dst_img, $rotate);
      }

      /* write down new generated file */
      $result = imagejpeg($dst_img, $thumb_image, 75);

      /* free your mind */
      imagedestroy($dst_img);
      imagedestroy($src_img);

      if($result === false) {
         print "Can't write thumbnail ". $thumb_image ."\n";
         return false;
      }

      return true;

   } // create_thumbnail()

   public function get_meta_informations($file)
   {
      return exif_read_data($file);

   } // get_meta_informations()

   public function check_config_table()
   {
      // if the config table doesn't exist yet, create it
      if(!$this->cfg_db->db_check_table_exists("images")) {
         $this->cfg_db->db_exec("
            CREATE TABLE images (
               img_idx int primary key,
               img_md5 varchar(32)
            )
            ");
      }

   } // check_config_table

   /**
    * Generates a thumbnail from photo idx
    *
    * This function will generate JPEG thumbnails from provided F-Spot photo
    * indizes.
    *
    * 1. Check if all thumbnail generations (width) are already in place and
    *    readable
    * 2. Check if the md5sum of the original file has changed
    * 3. Generate the thumbnails if needed
    */
   public function gen_thumb($idx = 0, $fromcmd = 0, $force = 0)
   {
      $resolutions = Array(
         $this->cfg->thumb_width,
         $this->cfg->bubble_width,
         $this->cfg->photo_width,
      );

      $details = $this->get_photo_details($idx);
      $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
      $file_md5 = md5_file($full_path);

      if($fromcmd) print "Image [". $idx ."] ". $details['name'] ." Thumbnails:";

      $error = 0;

      foreach($resolutions as $resolution) {

         $thumb_path = $this->cfg->base_path ."/thumbs/". $resolution ."_". $file_md5;

         /* if the thumbnail file doesn't exist, create it */
         if(!file_exists($thumb_path)) {

            if($fromcmd) print " ". $resolution ."px";
            if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
               $error = 1;

         }

         /* if the file hasn't changed there is no need to regen the thumb */
         elseif($file_md5 != $this->getMD5($idx) || $force) {

            if($fromcmd) print " ". $resolution ."px";
            if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
               $error = 1;

         }
      }

      /* set the new/changed MD5 sum for the current photo */
      if(!$error)
         $this->setMD5($idx, $file_md5);

      if($fromcmd) print "\n";

   } // gen_thumb()

   public function getMD5($idx)
   {
      $result = $this->cfg_db->db_query("
         SELECT img_md5 
         FROM images
         WHERE img_idx='". $idx ."'
      ");

      if(!$result)
         return 0;

      $img = $this->cfg_db->db_fetch_object($result);
      return $img['img_md5'];
      
   } // getMD5()

   private function setMD5($idx, $md5)
   {
      $result = $this->cfg_db->db_exec("
         REPLACE INTO images (img_idx, img_md5)
         VALUES ('". $idx ."', '". $md5 ."')
      ");

   } // setMD5()

   public function setTagCondition($mode)
   {
      $_SESSION['tag_condition'] = $mode;

   } // setTagCondition()

   public function startSearch($searchfor)
   {
      $_SESSION['searchfor'] = $searchfor;

   } // startSearch()

   private function rotateImage($img, $degrees)
   {
      if(function_exists("imagerotate"))
         $img = imagerotate($img, $degrees, 0);
      else
      {
         function imagerotate($src_img, $angle)
         {
            $src_x = imagesx($src_img);
            $src_y = imagesy($src_img);
            if ($angle == 180) {
               $dest_x = $src_x;
               $dest_y = $src_y;
            }
            elseif ($src_x <= $src_y) {
               $dest_x = $src_y;
               $dest_y = $src_x;
            }
            elseif ($src_x >= $src_y) {
               $dest_x = $src_y;
               $dest_y = $src_x;
            }
               
            $rotate=imagecreatetruecolor($dest_x,$dest_y);
            imagealphablending($rotate, false);
               
            switch ($angle) {
            
               case 90:
                  for ($y = 0; $y < ($src_y); $y++) {
                     for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
                     }
                  }
                  break;

               case 270:
                  for ($y = 0; $y < ($src_y); $y++) {
                     for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
                     }
                  }
                  break;

               case 180:
                  for ($y = 0; $y < ($src_y); $y++) {
                     for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
                     }
                  }
                  break;

               default: $rotate = $src_img;
            };

            return $rotate;

         }

         $img = imagerotate($img, $degrees);

      }

      return $img;

   } // rotateImage()

   private function get_photo_tags($idx)
   {
      $result = $this->db->db_query("
         SELECT t.id, t.name
         FROM tags t
         INNER JOIN photo_tags pt
            ON t.id=pt.tag_id
         WHERE pt.photo_id='". $idx ."'
      ");

      $tags = Array();

      while($row = $this->db->db_fetch_object($result))
         $tags[$row['id']] = $row['name'];

      return $tags;

   } // get_photo_tags()

}

?>