some error handling on 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
121       $details = $this->get_photo_details($photo);
122       $meta = $this->get_meta_informations($this->translate_path($details['directory_path']) ."/". $details['name']);
123       $info = getimagesize($this->translate_path($details['directory_path']) ."/thumbs/". $this->cfg->photo_width ."_". $details['name']);
124
125       $this->tmpl->assign('description', $details['description']);
126       $this->tmpl->assign('image_name', $details['name']);
127
128       $this->tmpl->assign('width', $info[0]);
129       $this->tmpl->assign('height', $info[1]);
130       $this->tmpl->assign('ExifMadeOn', strftime("%a %x %X", $meta['FileDateTime']));
131       $this->tmpl->assign('ExifMadeWith', $meta['Make'] ." ". $meta['Model']);
132       $this->tmpl->assign('ExifOrigResolution', $meta['ExifImageWidth'] ."x". $meta['ExifImageLength']);
133       $this->tmpl->assign('ExifFileSize', round($meta['FileSize']/1024, 1));
134  
135       $this->tmpl->assign('image_url', 'phpfspot_img.php?idx='. $photo ."&amp;width=". $this->cfg->photo_width);
136       $this->tmpl->assign('image_url_full', 'phpfspot_img.php?idx='. $photo);
137
138       $this->tmpl->assign('tags', $this->get_photo_tags($photo));
139
140       if($previous_img) {
141          $this->tmpl->assign('previous_url', "javascript:showImage(". $previous_img .");");
142       }
143
144       if($next_img) {
145          $this->tmpl->assign('next_url', "javascript:showImage(". $next_img .");");
146       }
147
148       $this->tmpl->show("single_photo.tpl");
149
150    } // showPhoto()
151
152    public function getAvailableTags()
153    {
154       $result = $this->db->db_query("
155          SELECT tag_id as id, count(tag_id) as quantity
156          FROM photo_tags
157          INNER JOIN tags t
158             ON t.id = tag_id
159          GROUP BY tag_id
160          ORDER BY t.name ASC
161       ");
162
163       $tags = Array();
164
165       while($row = $this->db->db_fetch_object($result)) {
166          $tags[$row['id']] = $row['quantity'];
167       }
168
169       // change these font sizes if you will
170       $max_size = 125; // max font size in %
171       $min_size = 75; // min font size in %
172
173       // get the largest and smallest array values
174       $max_qty = max(array_values($tags));
175       $min_qty = min(array_values($tags));
176
177       // find the range of values
178       $spread = $max_qty - $min_qty;
179       if (0 == $spread) { // we don't want to divide by zero
180          $spread = 1;
181       }
182
183       // determine the font-size increment
184       // this is the increase per tag quantity (times used)
185       $step = ($max_size - $min_size)/($spread);
186
187       // loop through our tag array
188       foreach ($tags as $key => $value) {
189
190          if(isset($_SESSION['selected_tags']) && in_array($key, $_SESSION['selected_tags']))
191             continue;
192
193           // calculate CSS font-size
194           // find the $value in excess of $min_qty
195           // multiply by the font-size increment ($size)
196           // and add the $min_size set above
197          $size = $min_size + (($value - $min_qty) * $step);
198           // uncomment if you want sizes in whole %:
199          $size = ceil($size);
200
201          print "<a href=\"javascript:Tags('add', ". $key .");\" class=\"tag\" style=\"font-size: ". $size ."%;\">". $this->tags[$key] ."</a>, ";
202
203       }
204
205    } // getAvailableTags()
206
207    public function getSelectedTags()
208    {
209       foreach($this->avail_tags as $tag)
210       {
211          // return all selected tags
212          if(isset($_SESSION['selected_tags']) && in_array($tag, $_SESSION['selected_tags'])) {
213             print "<a href=\"javascript:Tags('del', ". $tag .");\" class=\"tag\">". $this->tags[$tag] ."</a>&nbsp;";
214          }
215
216       }
217
218    } // getSelectedTags()
219
220    public function addTag($tag)
221    {
222       if(!isset($_SESSION['selected_tags']))
223          $_SESSION['selected_tags'] = Array();
224
225       if(!in_array($tag, $_SESSION['selected_tags']))
226          array_push($_SESSION['selected_tags'], $tag);
227    
228    } // addTag()
229
230    public function delTag($tag)
231    {
232       if(isset($_SESSION['selected_tags'])) {
233          $key = array_search($tag, $_SESSION['selected_tags']);
234          unset($_SESSION['selected_tags'][$key]);
235          sort($_SESSION['selected_tags']);
236       }
237
238    } // delTag()
239
240    public function resetTags()
241    {
242       unset($_SESSION['selected_tags']);
243
244    } // resetTags()
245
246    public function getPhotoSelection()
247    {  
248       $tagged_photos = Array();
249
250       /* return a search result */
251       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '') {
252          $result = $this->db->db_query("
253             SELECT DISTINCT photo_id
254                FROM photo_tags pt
255             INNER JOIN photos p
256                ON p.id=pt.photo_id
257             INNER JOIN tags t
258                ON pt.tag_id=t.id
259             WHERE t.name LIKE '%". $_SESSION['searchfor'] ."%'
260                ORDER BY p.time ASC
261          ");
262          while($row = $this->db->db_fetch_object($result)) {
263             array_push($tagged_photos, $row['photo_id']);
264          }
265          return $tagged_photos;
266       }
267
268       /* return according the selected tags */
269       if(isset($_SESSION['selected_tags'])) {
270          $selected = "";
271          foreach($_SESSION['selected_tags'] as $tag)
272             $selected.= $tag .",";
273          $selected = substr($selected, 0, strlen($selected)-1);
274
275          if($_SESSION['tag_condition'] == 'or') {
276             $result = $this->db->db_query("
277                SELECT DISTINCT photo_id
278                   FROM photo_tags pt
279                INNER JOIN photos p
280                   ON p.id=pt.photo_id
281                WHERE pt.tag_id IN (". $selected .")
282                ORDER BY p.time ASC
283             ");
284          }
285          elseif($_SESSION['tag_condition'] == 'and') {
286
287             /* Join together a table looking like
288
289                pt1.photo_id pt1.tag_id pt2.photo_id pt2.tag_id ...
290
291                so the query can quickly return all images matching the
292                selected tags in an AND condition
293
294             */
295
296             $query_str = "
297                SELECT DISTINCT pt1.photo_id
298                   FROM photo_tags pt1
299             ";
300
301             for($i = 0; $i < count($_SESSION['selected_tags']); $i++) {
302                $query_str.= "
303                   INNER JOIN photo_tags pt". ($i+2) ."
304                      ON pt1.photo_id=pt". ($i+2) .".photo_id
305                ";
306             }
307             $query_str.= "WHERE pt1.tag_id=". $_SESSION['selected_tags'][0];
308             for($i = 1; $i < count($_SESSION['selected_tags']); $i++) {
309                $query_str.= "
310                   AND pt". ($i+1) .".tag_id=". $_SESSION['selected_tags'][$i] ."
311                "; 
312             }
313             $result = $this->db->db_query($query_str);
314          }
315
316          while($row = $this->db->db_fetch_object($result)) {
317             array_push($tagged_photos, $row['photo_id']);
318          }
319          return $tagged_photos;
320       }
321
322       /* return all available photos */
323       $result = $this->db->db_query("
324          SELECT DISTINCT photo_id
325             FROM photo_tags pt
326          INNER JOIN photos p
327             ON p.id=pt.photo_id
328          ORDER BY p.time ASC
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    } // getPhotoSelection()
336
337    public function showPhotoIndex()
338    {
339       $photos = $this->getPhotoSelection();
340
341       $count = count($photos);
342
343       $rows = 0;
344       $cols = 0;
345       $images[$rows] = Array();
346
347       for($i = 0; $i < $count; $i++) {
348
349          $images[$rows][$cols] = $photos[$i];
350
351          if($cols == $this->cfg->thumbs_per_row-1) {
352             $cols = 0;
353             $rows++;
354             $images[$rows] = Array();
355          }
356          else {
357             $cols++;
358          }
359       } 
360
361       // +1 for for smarty's selection iteration
362       $rows++;
363
364       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
365          $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
366
367       $this->tmpl->assign('count', $count);
368       $this->tmpl->assign('width', $this->cfg->thumb_width);
369       $this->tmpl->assign('images', $images);
370       $this->tmpl->assign('rows', $rows);
371       $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
372       $this->tmpl->show("photo_index.tpl");
373
374
375    } // showPhotoIndex()
376
377    public function showBubbleDetails($photo, $direction)
378    {
379       if($direction == "up")
380          $direction = "bubbleimg_up";
381       else
382          $direction = "bubbleimg_down";
383
384       $details = $this->get_photo_details($photo);
385
386       $image_url = "phpfspot_img.php?idx=". $photo ."&amp;width=". $this->cfg->bubble_width;
387
388       $filesize = filesize($this->translate_path($details['directory_path'])  ."/". $details['name']);
389       $filesize = rand($filesize/1024, 2);
390
391       $img = getimagesize($this->translate_path($details['directory_path'])  ."/". $details['name']);
392
393       $this->tmpl->assign('file_size', $filesize);
394       $this->tmpl->assign('width', $img[0]);
395       $this->tmpl->assign('height', $img[1]);
396       $this->tmpl->assign('file_name', $details['name']);
397       $this->tmpl->assign('image_id', $direction);
398       $this->tmpl->assign('image_url', $image_url);
399       $this->tmpl->show("bubble_details.tpl");
400
401    } // showBubbleDetails()
402
403    public function showCredits()
404    {
405       $this->tmpl->assign('version', $this->cfg->version);
406       $this->tmpl->assign('product', $this->cfg->product);
407       $this->tmpl->show("credits.tpl");
408
409    } // showCredits()
410
411    public function create_thumbnail($image, $width)
412    {  
413       if(!file_exists($image))
414          return false;
415
416       $meta = $this->get_meta_informations($image);
417
418       $rotate = 0;
419       $flip = false;
420
421       switch($meta['Orientation']) {
422
423          case 1:
424             $rotate = 0; $flip = false; break;
425          case 2:
426             $rotate = 0; $flip = true; break;
427          case 3:
428             $rotate = 180; $flip = false; break;
429          case 4:
430             $rotate = 180; $flip = true; break;
431          case 5:
432             $rotate = 90; $flip = true; break;
433          case 6:
434             $rotate = 90; $flip = false; break;
435          case 7:
436             $rotate = 270; $flip = true; break;
437          case 8:
438             $rotate = 270; $flip = false; break;
439       }
440
441       $src_img = @imagecreatefromjpeg($image);
442
443       if(!$src_img) {
444          print "Can't load image from ". $image ."\n";
445          return false;
446       }
447
448       /* grabs the height and width */
449       $new_w = imagesx($src_img);
450       $new_h = imagesy($src_img);
451
452       // If requested width is more then the actual image width,
453       // do not generate a thumbnail
454
455       if($width >= $new_w) {
456          imagedestroy($src_img);
457          return true;
458       }
459
460       /* calculates aspect ratio */
461       $aspect_ratio = $new_h / $new_w;
462
463       /* sets new size */
464       $new_w = $width;
465       $new_h = abs($new_w * $aspect_ratio);
466
467       /* creates new image of that size */
468       $dst_img = imagecreatetruecolor($new_w,$new_h);
469
470       imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
471
472       /* copies resized portion of original image into new image */
473       imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
474
475       /* needs the image to be flipped horizontal? */
476       if($flip) {
477          print "(FLIP)";
478          $image = $dst_img;
479          for($x = 0; $x < $new_w; $x++) {
480             imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
481          }
482       }
483
484       if($rotate) {
485          print "(ROTATE)";
486          $dst_img = $this->rotateImage($dst_img, $rotate);
487       }
488
489       /* write down new generated file */
490
491       if(!file_exists(dirname($image) ."/thumbs")) {
492          $result = mkdir(dirname($image) ."/thumbs");
493          if($result === false) {
494             print "Can't create thumb directory ". dirname($image) ."/thumbs\n";
495             return false;
496          }
497       }
498
499       $newfile = dirname($image) ."/thumbs/". $width ."_". basename($image);
500       $result = imagejpeg($dst_img, $newfile, 75);
501
502       /* free your mind */
503       imagedestroy($dst_img);
504       imagedestroy($src_img);
505
506       if($result === false) {
507          print "Can't write thumbnail ". $newfile ."\n";
508          return false;
509       }
510
511       return true;
512
513    } // create_thumbnail()
514
515    public function get_meta_informations($file)
516    {
517       return exif_read_data($file);
518
519    } // get_meta_informations()
520
521    public function check_config_table()
522    {
523       // if the config table doesn't exist yet, create it
524       if(!$this->cfg_db->db_check_table_exists("images")) {
525          $this->cfg_db->db_exec("
526             CREATE TABLE images (
527                img_idx int primary key,
528                img_md5 varchar(32)
529             )
530             ");
531       }
532
533    } // check_config_table
534
535    public function gen_thumb($idx = 0, $fromcmd = 0, $force = 0)
536    {
537       $details = $this->get_photo_details($idx);
538
539       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
540       $file_md5 = md5_file($full_path);
541
542       if($fromcmd) print "Image [". $idx ."] ". $details['name'] ." Thumbnails:";
543
544       /* if the file hasn't changed there is no need to regen the thumb */
545       if(!$force && $file_md5 == $this->getMD5($idx)) {
546          if($fromcmd) print " file has not changed - skipping\n";
547          return;
548       }
549
550       $resolutions = Array(
551          $this->cfg->thumb_width,
552          $this->cfg->bubble_width,
553          $this->cfg->photo_width
554       );
555       
556       $error = 0;
557
558       /* create thumbnails for the requested resolutions */
559       foreach($resolutions as $resolution) {
560          if($fromcmd) print " ". $resolution ."px";
561          if(!$this->create_thumbnail($full_path, $resolution))
562             $error = 1;
563       }
564
565       /* set the new/changed MD5 sum for the current photo */
566       if(!$error)
567          $this->setMD5($idx, $file_md5);
568
569       if($fromcmd) print "\n";
570
571    } // gen_thumb()
572
573    private function getMD5($idx)
574    {
575       $result = $this->cfg_db->db_query("
576          SELECT img_md5 
577          FROM images
578          WHERE img_idx='". $idx ."'
579       ");
580
581       if(!$result)
582          return 0;
583
584       $img = $this->cfg_db->db_fetch_object($result);
585       return $img['img_md5'];
586       
587    } // getMD5()
588
589    private function setMD5($idx, $md5)
590    {
591       $result = $this->cfg_db->db_exec("
592          REPLACE INTO images (img_idx, img_md5)
593          VALUES ('". $idx ."', '". $md5 ."')
594       ");
595
596    } // setMD5()
597
598    public function setTagCondition($mode)
599    {
600       $_SESSION['tag_condition'] = $mode;
601
602    } // setTagCondition()
603
604    public function startSearch($searchfor)
605    {
606       $_SESSION['searchfor'] = $searchfor;
607
608    } // startSearch()
609
610    private function rotateImage($img, $degrees)
611    {
612       if(function_exists("imagerotate"))
613          $img = imagerotate($img, $degrees, 0);
614       else
615       {
616          function imagerotate($src_img, $angle)
617          {
618             $src_x = imagesx($src_img);
619             $src_y = imagesy($src_img);
620             if ($angle == 180) {
621                $dest_x = $src_x;
622                $dest_y = $src_y;
623             }
624             elseif ($src_x <= $src_y) {
625                $dest_x = $src_y;
626                $dest_y = $src_x;
627             }
628             elseif ($src_x >= $src_y) {
629                $dest_x = $src_y;
630                $dest_y = $src_x;
631             }
632                
633             $rotate=imagecreatetruecolor($dest_x,$dest_y);
634             imagealphablending($rotate, false);
635                
636             switch ($angle) {
637             
638                case 90:
639                   for ($y = 0; $y < ($src_y); $y++) {
640                      for ($x = 0; $x < ($src_x); $x++) {
641                         $color = imagecolorat($src_img, $x, $y);
642                         imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
643                      }
644                   }
645                   break;
646
647                case 270:
648                   for ($y = 0; $y < ($src_y); $y++) {
649                      for ($x = 0; $x < ($src_x); $x++) {
650                         $color = imagecolorat($src_img, $x, $y);
651                         imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
652                      }
653                   }
654                   break;
655
656                case 180:
657                   for ($y = 0; $y < ($src_y); $y++) {
658                      for ($x = 0; $x < ($src_x); $x++) {
659                         $color = imagecolorat($src_img, $x, $y);
660                         imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
661                      }
662                   }
663                   break;
664
665                default: $rotate = $src_img;
666             };
667
668             return $rotate;
669
670          }
671
672          $img = imagerotate($img, $degrees);
673
674       }
675
676       return $img;
677
678    } // rotateImage()
679
680    private function get_photo_tags($idx)
681    {
682       $result = $this->db->db_query("
683          SELECT t.id, t.name
684          FROM tags t
685          INNER JOIN photo_tags pt
686             ON t.id=pt.tag_id
687          WHERE pt.photo_id='". $idx ."'
688       ");
689
690       $tags = Array();
691
692       while($row = $this->db->db_fetch_object($result))
693          $tags[$row['id']] = $row['name'];
694
695       return $tags;
696
697    } // get_photo_tags()
698
699 }
700
701 ?>