some much more flexible thumbnail generation
[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->translate_path($details['directory_path']) ."/thumbs/". $this->cfg->photo_width ."_". $details['name'];
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'])) {
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       $rows = 0;
358       $cols = 0;
359       $images[$rows] = Array();
360
361       for($i = 0; $i < $count; $i++) {
362
363          $images[$rows][$cols] = $photos[$i];
364
365          if($cols == $this->cfg->thumbs_per_row-1) {
366             $cols = 0;
367             $rows++;
368             $images[$rows] = Array();
369          }
370          else {
371             $cols++;
372          }
373       } 
374
375       // +1 for for smarty's selection iteration
376       $rows++;
377
378       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
379          $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
380
381       $this->tmpl->assign('count', $count);
382       $this->tmpl->assign('width', $this->cfg->thumb_width);
383       $this->tmpl->assign('images', $images);
384       $this->tmpl->assign('rows', $rows);
385       $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
386       $this->tmpl->show("photo_index.tpl");
387
388
389    } // showPhotoIndex()
390
391    public function showBubbleDetails($photo, $direction)
392    {
393       if($direction == "up")
394          $direction = "bubbleimg_up";
395       else
396          $direction = "bubbleimg_down";
397
398       $details = $this->get_photo_details($photo);
399
400       $image_url = "phpfspot_img.php?idx=". $photo ."&amp;width=". $this->cfg->bubble_width;
401
402       $filesize = filesize($this->translate_path($details['directory_path'])  ."/". $details['name']);
403       $filesize = rand($filesize/1024, 2);
404
405       $img = getimagesize($this->translate_path($details['directory_path'])  ."/". $details['name']);
406
407       $this->tmpl->assign('file_size', $filesize);
408       $this->tmpl->assign('width', $img[0]);
409       $this->tmpl->assign('height', $img[1]);
410       $this->tmpl->assign('file_name', $details['name']);
411       $this->tmpl->assign('image_id', $direction);
412       $this->tmpl->assign('image_url', $image_url);
413       $this->tmpl->show("bubble_details.tpl");
414
415    } // showBubbleDetails()
416
417    public function showCredits()
418    {
419       $this->tmpl->assign('version', $this->cfg->version);
420       $this->tmpl->assign('product', $this->cfg->product);
421       $this->tmpl->show("credits.tpl");
422
423    } // showCredits()
424
425    public function create_thumbnail($image, $width)
426    {  
427       if(!file_exists($image))
428          return false;
429
430       $meta = $this->get_meta_informations($image);
431
432       $rotate = 0;
433       $flip = false;
434
435       switch($meta['Orientation']) {
436
437          case 1:
438             $rotate = 0; $flip = false; break;
439          case 2:
440             $rotate = 0; $flip = true; break;
441          case 3:
442             $rotate = 180; $flip = false; break;
443          case 4:
444             $rotate = 180; $flip = true; break;
445          case 5:
446             $rotate = 90; $flip = true; break;
447          case 6:
448             $rotate = 90; $flip = false; break;
449          case 7:
450             $rotate = 270; $flip = true; break;
451          case 8:
452             $rotate = 270; $flip = false; break;
453       }
454
455       $src_img = @imagecreatefromjpeg($image);
456
457       if(!$src_img) {
458          print "Can't load image from ". $image ."\n";
459          return false;
460       }
461
462       /* grabs the height and width */
463       $new_w = imagesx($src_img);
464       $new_h = imagesy($src_img);
465
466       // If requested width is more then the actual image width,
467       // do not generate a thumbnail
468
469       if($width >= $new_w) {
470          imagedestroy($src_img);
471          return true;
472       }
473
474       /* calculates aspect ratio */
475       $aspect_ratio = $new_h / $new_w;
476
477       /* sets new size */
478       $new_w = $width;
479       $new_h = abs($new_w * $aspect_ratio);
480
481       /* creates new image of that size */
482       $dst_img = imagecreatetruecolor($new_w,$new_h);
483
484       imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
485
486       /* copies resized portion of original image into new image */
487       imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
488
489       /* needs the image to be flipped horizontal? */
490       if($flip) {
491          print "(FLIP)";
492          $image = $dst_img;
493          for($x = 0; $x < $new_w; $x++) {
494             imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
495          }
496       }
497
498       if($rotate) {
499          print "(ROTATE)";
500          $dst_img = $this->rotateImage($dst_img, $rotate);
501       }
502
503       /* write down new generated file */
504
505       if(!file_exists(dirname($image) ."/thumbs")) {
506          $result = mkdir(dirname($image) ."/thumbs");
507          if($result === false) {
508             print "Can't create thumb directory ". dirname($image) ."/thumbs\n";
509             return false;
510          }
511       }
512
513       $newfile = dirname($image) ."/thumbs/". $width ."_". basename($image);
514       $result = imagejpeg($dst_img, $newfile, 75);
515
516       /* free your mind */
517       imagedestroy($dst_img);
518       imagedestroy($src_img);
519
520       if($result === false) {
521          print "Can't write thumbnail ". $newfile ."\n";
522          return false;
523       }
524
525       return true;
526
527    } // create_thumbnail()
528
529    public function get_meta_informations($file)
530    {
531       return exif_read_data($file);
532
533    } // get_meta_informations()
534
535    public function check_config_table()
536    {
537       // if the config table doesn't exist yet, create it
538       if(!$this->cfg_db->db_check_table_exists("images")) {
539          $this->cfg_db->db_exec("
540             CREATE TABLE images (
541                img_idx int primary key,
542                img_md5 varchar(32)
543             )
544             ");
545       }
546
547    } // check_config_table
548
549    /**
550     * Generates a thumbnail from photo idx
551     *
552     * This function will generate JPEG thumbnails from provided F-Spot photo
553     * indizes.
554     *
555     * 1. Check if all thumbnail generations (width) are already in place and
556     *    readable
557     * 2. Check if the md5sum of the original file has changed
558     * 3. Generate the thumbnails if needed
559     */
560    public function gen_thumb($idx = 0, $fromcmd = 0, $force = 0)
561    {
562       $resolutions = Array(
563          $this->cfg->thumb_width,
564          $this->cfg->bubble_width,
565          $this->cfg->photo_width,
566       );
567
568       $details = $this->get_photo_details($idx);
569       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
570       $file_md5 = md5_file($full_path);
571
572       if($fromcmd) print "Image [". $idx ."] ". $details['name'] ." Thumbnails:";
573
574       $error = 0;
575
576       foreach($resolutions as $resolution) {
577          $thumb_path = $this->translate_path($details['directory_path'])  ."/thumbs/". $resolution ."_". $details['name'];
578          if(!file_exists($thumb_path)) {
579
580             if($fromcmd) print " ". $resolution ."px";
581             if(!$this->create_thumbnail($full_path, $resolution))
582                $error = 1;
583
584          }
585          /* if the file hasn't changed there is no need to regen the thumb */
586          elseif($file_md5 != $this->getMD5($idx) || $force) {
587
588             if($fromcmd) print " ". $resolution ."px";
589             if(!$this->create_thumbnail($full_path, $resolution))
590                $error = 1;
591
592          }
593       }
594
595       /* set the new/changed MD5 sum for the current photo */
596       if(!$error)
597          $this->setMD5($idx, $file_md5);
598
599       if($fromcmd) print "\n";
600
601    } // gen_thumb()
602
603    private function getMD5($idx)
604    {
605       $result = $this->cfg_db->db_query("
606          SELECT img_md5 
607          FROM images
608          WHERE img_idx='". $idx ."'
609       ");
610
611       if(!$result)
612          return 0;
613
614       $img = $this->cfg_db->db_fetch_object($result);
615       return $img['img_md5'];
616       
617    } // getMD5()
618
619    private function setMD5($idx, $md5)
620    {
621       $result = $this->cfg_db->db_exec("
622          REPLACE INTO images (img_idx, img_md5)
623          VALUES ('". $idx ."', '". $md5 ."')
624       ");
625
626    } // setMD5()
627
628    public function setTagCondition($mode)
629    {
630       $_SESSION['tag_condition'] = $mode;
631
632    } // setTagCondition()
633
634    public function startSearch($searchfor)
635    {
636       $_SESSION['searchfor'] = $searchfor;
637
638    } // startSearch()
639
640    private function rotateImage($img, $degrees)
641    {
642       if(function_exists("imagerotate"))
643          $img = imagerotate($img, $degrees, 0);
644       else
645       {
646          function imagerotate($src_img, $angle)
647          {
648             $src_x = imagesx($src_img);
649             $src_y = imagesy($src_img);
650             if ($angle == 180) {
651                $dest_x = $src_x;
652                $dest_y = $src_y;
653             }
654             elseif ($src_x <= $src_y) {
655                $dest_x = $src_y;
656                $dest_y = $src_x;
657             }
658             elseif ($src_x >= $src_y) {
659                $dest_x = $src_y;
660                $dest_y = $src_x;
661             }
662                
663             $rotate=imagecreatetruecolor($dest_x,$dest_y);
664             imagealphablending($rotate, false);
665                
666             switch ($angle) {
667             
668                case 90:
669                   for ($y = 0; $y < ($src_y); $y++) {
670                      for ($x = 0; $x < ($src_x); $x++) {
671                         $color = imagecolorat($src_img, $x, $y);
672                         imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
673                      }
674                   }
675                   break;
676
677                case 270:
678                   for ($y = 0; $y < ($src_y); $y++) {
679                      for ($x = 0; $x < ($src_x); $x++) {
680                         $color = imagecolorat($src_img, $x, $y);
681                         imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
682                      }
683                   }
684                   break;
685
686                case 180:
687                   for ($y = 0; $y < ($src_y); $y++) {
688                      for ($x = 0; $x < ($src_x); $x++) {
689                         $color = imagecolorat($src_img, $x, $y);
690                         imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
691                      }
692                   }
693                   break;
694
695                default: $rotate = $src_img;
696             };
697
698             return $rotate;
699
700          }
701
702          $img = imagerotate($img, $degrees);
703
704       }
705
706       return $img;
707
708    } // rotateImage()
709
710    private function get_photo_tags($idx)
711    {
712       $result = $this->db->db_query("
713          SELECT t.id, t.name
714          FROM tags t
715          INNER JOIN photo_tags pt
716             ON t.id=pt.tag_id
717          WHERE pt.photo_id='". $idx ."'
718       ");
719
720       $tags = Array();
721
722       while($row = $this->db->db_fetch_object($result))
723          $tags[$row['id']] = $row['name'];
724
725       return $tags;
726
727    } // get_photo_tags()
728
729 }
730
731 ?>