issue6, first implementation of paged photo index view
[phpfspot.git] / phpfspot.class.php
1 <?php
2
3 require_once "phpfspot_cfg.php";
4 require_once "phpfspot_db.php";
5 require_once "phpfspot_tmpl.php";
6
7 class PHPFSPOT {
8
9    var $cfg;
10    var $db;
11    var $cfg_db;
12    var $tmpl;
13    var $tags;
14    var $avail_tags;
15    var $current_tags;
16
17    public function __construct()
18    {
19       $this->cfg = new PHPFSPOT_CFG;
20
21       $this->db = new PHPFSPOT_DB(&$this, $this->cfg->fspot_db);
22
23       $this->cfg_db = new PHPFSPOT_DB(&$this, $this->cfg->phpfspot_db);
24       $this->check_config_table();
25
26       $this->tmpl = new PHPFSPOT_TMPL($this);
27
28       $this->get_tags();
29
30       session_start();
31
32       if(!isset($_SESSION['tag_condition']))
33          $_SESSION['tag_condition'] = 'or';
34
35       if(!isset($_SESSION['searchfor']))
36          $_SESSION['searchfor'] = '';
37
38    } // __construct()
39
40    public function __destruct()
41    {
42
43    } // __destruct()
44
45    public function show()
46    {
47       $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
48       $this->tmpl->assign('page_title', $this->cfg->page_title);
49       $this->tmpl->assign('current_condition', $_SESSION['tag_condition']);
50       $this->tmpl->show("index.tpl");
51
52    } // show()
53
54    private function get_tags()
55    {
56       $this->avail_tags = Array();
57       $count = 0;
58    
59       $result = $this->db->db_query("
60          SELECT id,name
61          FROM tags
62          ORDER BY sort_priority ASC
63       ");
64       
65       while($row = $this->db->db_fetch_object($result)) {
66
67          $tag_id = $row['id'];
68          $tag_name = $row['name'];
69
70          /* check if config requests to ignore this tag */
71          if(in_array($row['name'], $this->cfg->hide_tags))
72             continue;
73
74          $this->tags[$tag_id] = $tag_name; 
75          $this->avail_tags[$count] = $tag_id;
76
77          $count++;
78
79       }
80
81    } // get_tags()
82
83    public function get_photo_details($idx)
84    {
85       $result = $this->db->db_query("
86          SELECT *
87          FROM photos
88          WHERE id='". $idx ."'
89       ");
90       
91       return $this->db->db_fetch_object($result);
92
93    } // get_photo_details
94
95    public function translate_path($path, $width = 0)
96    {  
97       return str_replace($this->cfg->path_replace_from, $this->cfg->path_replace_to, $path);
98
99    } // translate_path
100
101    public function showPhoto($photo)
102    {
103       $all_photos = $this->getPhotoSelection();
104
105       foreach($all_photos as $all_photo) {
106          
107          if($get_next) {
108             $next_img = $all_photo;
109             break;
110          }
111
112          if($all_photo == $photo) {
113             $get_next = 1;
114          }
115          else {
116             $previous_img = $all_photo;
117          }
118       }
119
120       $details = $this->get_photo_details($photo);
121       $orig_path = $this->translate_path($details['directory_path']) ."/". $details['name'];
122       $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->photo_width ."_". $this->getMD5($photo);
123
124       /* If the thumbnail doesn't exist yet, try to create it */
125       if(!file_exists($thumb_path)) {
126          $this->gen_thumb($photo, 0, 1);
127       }
128
129       $meta = $this->get_meta_informations($orig_path);
130
131       if(file_exists($thumb_path)) {
132
133          $info = getimagesize($thumb_path);
134
135          $this->tmpl->assign('description', $details['description']);
136          $this->tmpl->assign('image_name', $details['name']);
137
138          $this->tmpl->assign('width', $info[0]);
139          $this->tmpl->assign('height', $info[1]);
140          $this->tmpl->assign('ExifMadeOn', strftime("%a %x %X", $meta['FileDateTime']));
141          $this->tmpl->assign('ExifMadeWith', $meta['Make'] ." ". $meta['Model']);
142          $this->tmpl->assign('ExifOrigResolution', $meta['ExifImageWidth'] ."x". $meta['ExifImageLength']);
143          $this->tmpl->assign('ExifFileSize', round($meta['FileSize']/1024, 1));
144     
145          $this->tmpl->assign('image_url', 'phpfspot_img.php?idx='. $photo ."&amp;width=". $this->cfg->photo_width);
146          $this->tmpl->assign('image_url_full', 'phpfspot_img.php?idx='. $photo);
147
148          $this->tmpl->assign('tags', $this->get_photo_tags($photo));
149       }
150       else {
151          print "Can't open file ". $thumb_path ."\n";
152       }
153
154       if($previous_img) {
155          $this->tmpl->assign('previous_url', "javascript:showImage(". $previous_img .");");
156       }
157
158       if($next_img) {
159          $this->tmpl->assign('next_url', "javascript:showImage(". $next_img .");");
160       }
161
162       $this->tmpl->show("single_photo.tpl");
163
164    } // showPhoto()
165
166    public function getAvailableTags()
167    {
168       $result = $this->db->db_query("
169          SELECT tag_id as id, count(tag_id) as quantity
170          FROM photo_tags
171          INNER JOIN tags t
172             ON t.id = tag_id
173          GROUP BY tag_id
174          ORDER BY t.name ASC
175       ");
176
177       $tags = Array();
178
179       while($row = $this->db->db_fetch_object($result)) {
180          $tags[$row['id']] = $row['quantity'];
181       }
182
183       // change these font sizes if you will
184       $max_size = 125; // max font size in %
185       $min_size = 75; // min font size in %
186
187       // get the largest and smallest array values
188       $max_qty = max(array_values($tags));
189       $min_qty = min(array_values($tags));
190
191       // find the range of values
192       $spread = $max_qty - $min_qty;
193       if (0 == $spread) { // we don't want to divide by zero
194          $spread = 1;
195       }
196
197       // determine the font-size increment
198       // this is the increase per tag quantity (times used)
199       $step = ($max_size - $min_size)/($spread);
200
201       // loop through our tag array
202       foreach ($tags as $key => $value) {
203
204          if(isset($_SESSION['selected_tags']) && in_array($key, $_SESSION['selected_tags']))
205             continue;
206
207           // calculate CSS font-size
208           // find the $value in excess of $min_qty
209           // multiply by the font-size increment ($size)
210           // and add the $min_size set above
211          $size = $min_size + (($value - $min_qty) * $step);
212           // uncomment if you want sizes in whole %:
213          $size = ceil($size);
214
215          print "<a href=\"javascript:Tags('add', ". $key .");\" class=\"tag\" style=\"font-size: ". $size ."%;\">". $this->tags[$key] ."</a>, ";
216
217       }
218
219    } // getAvailableTags()
220
221    public function getSelectedTags()
222    {
223       foreach($this->avail_tags as $tag)
224       {
225          // return all selected tags
226          if(isset($_SESSION['selected_tags']) && in_array($tag, $_SESSION['selected_tags'])) {
227             print "<a href=\"javascript:Tags('del', ". $tag .");\" class=\"tag\">". $this->tags[$tag] ."</a>&nbsp;";
228          }
229
230       }
231
232    } // getSelectedTags()
233
234    public function addTag($tag)
235    {
236       if(!isset($_SESSION['selected_tags']))
237          $_SESSION['selected_tags'] = Array();
238
239       if(!in_array($tag, $_SESSION['selected_tags']))
240          array_push($_SESSION['selected_tags'], $tag);
241    
242    } // addTag()
243
244    public function delTag($tag)
245    {
246       if(isset($_SESSION['selected_tags'])) {
247          $key = array_search($tag, $_SESSION['selected_tags']);
248          unset($_SESSION['selected_tags'][$key]);
249          sort($_SESSION['selected_tags']);
250       }
251
252    } // delTag()
253
254    public function resetTags()
255    {
256       unset($_SESSION['selected_tags']);
257
258    } // resetTags()
259
260    public function getPhotoSelection()
261    {  
262       $tagged_photos = Array();
263
264       /* return a search result */
265       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '') {
266          $result = $this->db->db_query("
267             SELECT DISTINCT photo_id
268                FROM photo_tags pt
269             INNER JOIN photos p
270                ON p.id=pt.photo_id
271             INNER JOIN tags t
272                ON pt.tag_id=t.id
273             WHERE t.name LIKE '%". $_SESSION['searchfor'] ."%'
274                ORDER BY p.time ASC
275          ");
276          while($row = $this->db->db_fetch_object($result)) {
277             array_push($tagged_photos, $row['photo_id']);
278          }
279          return $tagged_photos;
280       }
281
282       /* return according the selected tags */
283       if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
284          $selected = "";
285          foreach($_SESSION['selected_tags'] as $tag)
286             $selected.= $tag .",";
287          $selected = substr($selected, 0, strlen($selected)-1);
288
289          if($_SESSION['tag_condition'] == 'or') {
290             $result = $this->db->db_query("
291                SELECT DISTINCT photo_id
292                   FROM photo_tags pt
293                INNER JOIN photos p
294                   ON p.id=pt.photo_id
295                WHERE pt.tag_id IN (". $selected .")
296                ORDER BY p.time ASC
297             ");
298          }
299          elseif($_SESSION['tag_condition'] == 'and') {
300
301             /* Join together a table looking like
302
303                pt1.photo_id pt1.tag_id pt2.photo_id pt2.tag_id ...
304
305                so the query can quickly return all images matching the
306                selected tags in an AND condition
307
308             */
309
310             $query_str = "
311                SELECT DISTINCT pt1.photo_id
312                   FROM photo_tags pt1
313             ";
314
315             for($i = 0; $i < count($_SESSION['selected_tags']); $i++) {
316                $query_str.= "
317                   INNER JOIN photo_tags pt". ($i+2) ."
318                      ON pt1.photo_id=pt". ($i+2) .".photo_id
319                ";
320             }
321             $query_str.= "WHERE pt1.tag_id=". $_SESSION['selected_tags'][0];
322             for($i = 1; $i < count($_SESSION['selected_tags']); $i++) {
323                $query_str.= "
324                   AND pt". ($i+1) .".tag_id=". $_SESSION['selected_tags'][$i] ."
325                "; 
326             }
327             $result = $this->db->db_query($query_str);
328          }
329
330          while($row = $this->db->db_fetch_object($result)) {
331             array_push($tagged_photos, $row['photo_id']);
332          }
333          return $tagged_photos;
334       }
335
336       /* return all available photos */
337       $result = $this->db->db_query("
338          SELECT DISTINCT photo_id
339             FROM photo_tags pt
340          INNER JOIN photos p
341             ON p.id=pt.photo_id
342          ORDER BY p.time ASC
343       ");
344       while($row = $this->db->db_fetch_object($result)) {
345          array_push($tagged_photos, $row['photo_id']);
346       }
347       return $tagged_photos;
348
349    } // getPhotoSelection()
350
351    public function showPhotoIndex()
352    {
353       $photos = $this->getPhotoSelection();
354
355       $count = count($photos);
356
357       if(!$_SESSION['begin_with'] || $_SESSION['begin_with'] == 0)
358          $begin_with = 0;
359       else
360          $begin_with = $_SESSION['begin_with'];
361
362       if($this->cfg->rows_per_page == 0)
363          $end_with = $count;
364       else
365          $end_with = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
366
367    
368       $rows = 0;
369       $cols = 0;
370       $images[$rows] = Array();
371       $img_height[$rows] = Array();
372       $img_width[$rows] = Array();
373
374       for($i = $begin_with; $i < $end_with; $i++) {
375
376          $images[$rows][$cols] = $photos[$i];
377
378          $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->thumb_width ."_". $this->getMD5($photos[$i]);
379
380          if(file_exists($thumb_path)) {
381             $info = getimagesize($thumb_path); 
382             $img_width[$rows][$cols] = $info[0];
383             $img_height[$rows][$cols] = $info[1];
384          }
385
386          if($cols == $this->cfg->thumbs_per_row-1) {
387             $cols = 0;
388             $rows++;
389             $images[$rows] = Array();
390             $img_width[$rows] = Array();
391             $img_height[$rows] = Array();
392          }
393          else {
394             $cols++;
395          }
396       } 
397
398       // +1 for for smarty's selection iteration
399       $rows++;
400
401       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
402          $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
403
404       if($this->cfg->rows_per_page != 0) {
405          $previous_start = $begin_with - ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
406          $next_start = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
407
408          if($begin_with != 0) 
409             $this->tmpl->assign("previous_url", "javascript:showPhotoIndex(". $previous_start .");"); 
410          if($end_with < $count)
411             $this->tmpl->assign("next_url", "javascript:showPhotoIndex(". $next_start .");"); 
412       }
413    
414       $this->tmpl->assign('count', $count);
415       $this->tmpl->assign('width', $this->cfg->thumb_width);
416       $this->tmpl->assign('images', $images);
417       $this->tmpl->assign('img_width', $img_width);
418       $this->tmpl->assign('img_height', $img_height);
419       $this->tmpl->assign('rows', $rows);
420       $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
421       $this->tmpl->show("photo_index.tpl");
422
423
424    } // showPhotoIndex()
425
426    public function showBubbleDetails($photo, $direction)
427    {
428       if($direction == "up")
429          $direction = "bubbleimg_up";
430       else
431          $direction = "bubbleimg_down";
432
433       $details = $this->get_photo_details($photo);
434
435       $image_url = "phpfspot_img.php?idx=". $photo ."&amp;width=". $this->cfg->bubble_width;
436
437       $filesize = filesize($this->translate_path($details['directory_path'])  ."/". $details['name']);
438       $filesize = rand($filesize/1024, 2);
439
440       $img = getimagesize($this->translate_path($details['directory_path'])  ."/". $details['name']);
441
442       $this->tmpl->assign('file_size', $filesize);
443       $this->tmpl->assign('width', $img[0]);
444       $this->tmpl->assign('height', $img[1]);
445       $this->tmpl->assign('file_name', $details['name']);
446       $this->tmpl->assign('image_id', $direction);
447       $this->tmpl->assign('image_url', $image_url);
448       $this->tmpl->show("bubble_details.tpl");
449
450    } // showBubbleDetails()
451
452    public function showCredits()
453    {
454       $this->tmpl->assign('version', $this->cfg->version);
455       $this->tmpl->assign('product', $this->cfg->product);
456       $this->tmpl->show("credits.tpl");
457
458    } // showCredits()
459
460    public function create_thumbnail($orig_image, $thumb_image, $width)
461    {  
462       if(!file_exists($orig_image))
463          return false;
464
465       $meta = $this->get_meta_informations($orig_image);
466
467       $rotate = 0;
468       $flip = false;
469
470       switch($meta['Orientation']) {
471
472          case 1:
473             $rotate = 0; $flip = false; break;
474          case 2:
475             $rotate = 0; $flip = true; break;
476          case 3:
477             $rotate = 180; $flip = false; break;
478          case 4:
479             $rotate = 180; $flip = true; break;
480          case 5:
481             $rotate = 90; $flip = true; break;
482          case 6:
483             $rotate = 90; $flip = false; break;
484          case 7:
485             $rotate = 270; $flip = true; break;
486          case 8:
487             $rotate = 270; $flip = false; break;
488       }
489
490       $src_img = @imagecreatefromjpeg($orig_image);
491
492       if(!$src_img) {
493          print "Can't load image from ". $orig_image ."\n";
494          return false;
495       }
496
497       /* grabs the height and width */
498       $new_w = imagesx($src_img);
499       $new_h = imagesy($src_img);
500
501       // If requested width is more then the actual image width,
502       // do not generate a thumbnail
503
504       if($width >= $new_w) {
505          imagedestroy($src_img);
506          return true;
507       }
508
509       /* calculates aspect ratio */
510       $aspect_ratio = $new_h / $new_w;
511
512       /* sets new size */
513       $new_w = $width;
514       $new_h = abs($new_w * $aspect_ratio);
515
516       /* creates new image of that size */
517       $dst_img = imagecreatetruecolor($new_w, $new_h);
518
519       imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
520
521       /* copies resized portion of original image into new image */
522       imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
523
524       /* needs the image to be flipped horizontal? */
525       if($flip) {
526          print "(FLIP)";
527          $image = $dst_img;
528          for($x = 0; $x < $new_w; $x++) {
529             imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
530          }
531       }
532
533       if($rotate) {
534          print "(ROTATE)";
535          $dst_img = $this->rotateImage($dst_img, $rotate);
536       }
537
538       /* write down new generated file */
539       $result = imagejpeg($dst_img, $thumb_image, 75);
540
541       /* free your mind */
542       imagedestroy($dst_img);
543       imagedestroy($src_img);
544
545       if($result === false) {
546          print "Can't write thumbnail ". $thumb_image ."\n";
547          return false;
548       }
549
550       return true;
551
552    } // create_thumbnail()
553
554    public function get_meta_informations($file)
555    {
556       return exif_read_data($file);
557
558    } // get_meta_informations()
559
560    public function check_config_table()
561    {
562       // if the config table doesn't exist yet, create it
563       if(!$this->cfg_db->db_check_table_exists("images")) {
564          $this->cfg_db->db_exec("
565             CREATE TABLE images (
566                img_idx int primary key,
567                img_md5 varchar(32)
568             )
569             ");
570       }
571
572    } // check_config_table
573
574    /**
575     * Generates a thumbnail from photo idx
576     *
577     * This function will generate JPEG thumbnails from provided F-Spot photo
578     * indizes.
579     *
580     * 1. Check if all thumbnail generations (width) are already in place and
581     *    readable
582     * 2. Check if the md5sum of the original file has changed
583     * 3. Generate the thumbnails if needed
584     */
585    public function gen_thumb($idx = 0, $fromcmd = 0, $force = 0)
586    {
587       $resolutions = Array(
588          $this->cfg->thumb_width,
589          $this->cfg->bubble_width,
590          $this->cfg->photo_width,
591       );
592
593       $details = $this->get_photo_details($idx);
594       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
595       $file_md5 = md5_file($full_path);
596
597       if($fromcmd) print "Image [". $idx ."] ". $details['name'] ." Thumbnails:";
598
599       $error = 0;
600
601       foreach($resolutions as $resolution) {
602
603          $thumb_path = $this->cfg->base_path ."/thumbs/". $resolution ."_". $file_md5;
604
605          /* if the thumbnail file doesn't exist, create it */
606          if(!file_exists($thumb_path)) {
607
608             if($fromcmd) print " ". $resolution ."px";
609             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
610                $error = 1;
611
612          }
613
614          /* if the file hasn't changed there is no need to regen the thumb */
615          elseif($file_md5 != $this->getMD5($idx) || $force) {
616
617             if($fromcmd) print " ". $resolution ."px";
618             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
619                $error = 1;
620
621          }
622       }
623
624       /* set the new/changed MD5 sum for the current photo */
625       if(!$error)
626          $this->setMD5($idx, $file_md5);
627
628       if($fromcmd) print "\n";
629
630    } // gen_thumb()
631
632    public function getMD5($idx)
633    {
634       $result = $this->cfg_db->db_query("
635          SELECT img_md5 
636          FROM images
637          WHERE img_idx='". $idx ."'
638       ");
639
640       if(!$result)
641          return 0;
642
643       $img = $this->cfg_db->db_fetch_object($result);
644       return $img['img_md5'];
645       
646    } // getMD5()
647
648    private function setMD5($idx, $md5)
649    {
650       $result = $this->cfg_db->db_exec("
651          REPLACE INTO images (img_idx, img_md5)
652          VALUES ('". $idx ."', '". $md5 ."')
653       ");
654
655    } // setMD5()
656
657    public function setTagCondition($mode)
658    {
659       $_SESSION['tag_condition'] = $mode;
660
661    } // setTagCondition()
662
663    public function startSearch($searchfor)
664    {
665       $_SESSION['searchfor'] = $searchfor;
666
667    } // startSearch()
668
669    private function rotateImage($img, $degrees)
670    {
671       if(function_exists("imagerotate"))
672          $img = imagerotate($img, $degrees, 0);
673       else
674       {
675          function imagerotate($src_img, $angle)
676          {
677             $src_x = imagesx($src_img);
678             $src_y = imagesy($src_img);
679             if ($angle == 180) {
680                $dest_x = $src_x;
681                $dest_y = $src_y;
682             }
683             elseif ($src_x <= $src_y) {
684                $dest_x = $src_y;
685                $dest_y = $src_x;
686             }
687             elseif ($src_x >= $src_y) {
688                $dest_x = $src_y;
689                $dest_y = $src_x;
690             }
691                
692             $rotate=imagecreatetruecolor($dest_x,$dest_y);
693             imagealphablending($rotate, false);
694                
695             switch ($angle) {
696             
697                case 90:
698                   for ($y = 0; $y < ($src_y); $y++) {
699                      for ($x = 0; $x < ($src_x); $x++) {
700                         $color = imagecolorat($src_img, $x, $y);
701                         imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
702                      }
703                   }
704                   break;
705
706                case 270:
707                   for ($y = 0; $y < ($src_y); $y++) {
708                      for ($x = 0; $x < ($src_x); $x++) {
709                         $color = imagecolorat($src_img, $x, $y);
710                         imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
711                      }
712                   }
713                   break;
714
715                case 180:
716                   for ($y = 0; $y < ($src_y); $y++) {
717                      for ($x = 0; $x < ($src_x); $x++) {
718                         $color = imagecolorat($src_img, $x, $y);
719                         imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
720                      }
721                   }
722                   break;
723
724                default: $rotate = $src_img;
725             };
726
727             return $rotate;
728
729          }
730
731          $img = imagerotate($img, $degrees);
732
733       }
734
735       return $img;
736
737    } // rotateImage()
738
739    private function get_photo_tags($idx)
740    {
741       $result = $this->db->db_query("
742          SELECT t.id, t.name
743          FROM tags t
744          INNER JOIN photo_tags pt
745             ON t.id=pt.tag_id
746          WHERE pt.photo_id='". $idx ."'
747       ");
748
749       $tags = Array();
750
751       while($row = $this->db->db_fetch_object($result))
752          $tags[$row['id']] = $row['name'];
753
754       return $tags;
755
756    } // get_photo_tags()
757
758 }
759
760 ?>