set svn:ignore correctly
[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'])) {
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($orig_image, $thumb_image, $width)
426    {  
427       if(!file_exists($orig_image))
428          return false;
429
430       $meta = $this->get_meta_informations($orig_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($orig_image);
456
457       if(!$src_img) {
458          print "Can't load image from ". $orig_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       $result = imagejpeg($dst_img, $thumb_image, 75);
505
506       /* free your mind */
507       imagedestroy($dst_img);
508       imagedestroy($src_img);
509
510       if($result === false) {
511          print "Can't write thumbnail ". $thumb_image ."\n";
512          return false;
513       }
514
515       return true;
516
517    } // create_thumbnail()
518
519    public function get_meta_informations($file)
520    {
521       return exif_read_data($file);
522
523    } // get_meta_informations()
524
525    public function check_config_table()
526    {
527       // if the config table doesn't exist yet, create it
528       if(!$this->cfg_db->db_check_table_exists("images")) {
529          $this->cfg_db->db_exec("
530             CREATE TABLE images (
531                img_idx int primary key,
532                img_md5 varchar(32)
533             )
534             ");
535       }
536
537    } // check_config_table
538
539    /**
540     * Generates a thumbnail from photo idx
541     *
542     * This function will generate JPEG thumbnails from provided F-Spot photo
543     * indizes.
544     *
545     * 1. Check if all thumbnail generations (width) are already in place and
546     *    readable
547     * 2. Check if the md5sum of the original file has changed
548     * 3. Generate the thumbnails if needed
549     */
550    public function gen_thumb($idx = 0, $fromcmd = 0, $force = 0)
551    {
552       $resolutions = Array(
553          $this->cfg->thumb_width,
554          $this->cfg->bubble_width,
555          $this->cfg->photo_width,
556       );
557
558       $details = $this->get_photo_details($idx);
559       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
560       $file_md5 = md5_file($full_path);
561
562       if($fromcmd) print "Image [". $idx ."] ". $details['name'] ." Thumbnails:";
563
564       $error = 0;
565
566       foreach($resolutions as $resolution) {
567
568          $thumb_path = $this->cfg->base_path ."/thumbs/". $resolution ."_". $file_md5;
569
570          /* if the thumbnail file doesn't exist, create it */
571          if(!file_exists($thumb_path)) {
572
573             if($fromcmd) print " ". $resolution ."px";
574             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
575                $error = 1;
576
577          }
578
579          /* if the file hasn't changed there is no need to regen the thumb */
580          elseif($file_md5 != $this->getMD5($idx) || $force) {
581
582             if($fromcmd) print " ". $resolution ."px";
583             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
584                $error = 1;
585
586          }
587       }
588
589       /* set the new/changed MD5 sum for the current photo */
590       if(!$error)
591          $this->setMD5($idx, $file_md5);
592
593       if($fromcmd) print "\n";
594
595    } // gen_thumb()
596
597    public function getMD5($idx)
598    {
599       $result = $this->cfg_db->db_query("
600          SELECT img_md5 
601          FROM images
602          WHERE img_idx='". $idx ."'
603       ");
604
605       if(!$result)
606          return 0;
607
608       $img = $this->cfg_db->db_fetch_object($result);
609       return $img['img_md5'];
610       
611    } // getMD5()
612
613    private function setMD5($idx, $md5)
614    {
615       $result = $this->cfg_db->db_exec("
616          REPLACE INTO images (img_idx, img_md5)
617          VALUES ('". $idx ."', '". $md5 ."')
618       ");
619
620    } // setMD5()
621
622    public function setTagCondition($mode)
623    {
624       $_SESSION['tag_condition'] = $mode;
625
626    } // setTagCondition()
627
628    public function startSearch($searchfor)
629    {
630       $_SESSION['searchfor'] = $searchfor;
631
632    } // startSearch()
633
634    private function rotateImage($img, $degrees)
635    {
636       if(function_exists("imagerotate"))
637          $img = imagerotate($img, $degrees, 0);
638       else
639       {
640          function imagerotate($src_img, $angle)
641          {
642             $src_x = imagesx($src_img);
643             $src_y = imagesy($src_img);
644             if ($angle == 180) {
645                $dest_x = $src_x;
646                $dest_y = $src_y;
647             }
648             elseif ($src_x <= $src_y) {
649                $dest_x = $src_y;
650                $dest_y = $src_x;
651             }
652             elseif ($src_x >= $src_y) {
653                $dest_x = $src_y;
654                $dest_y = $src_x;
655             }
656                
657             $rotate=imagecreatetruecolor($dest_x,$dest_y);
658             imagealphablending($rotate, false);
659                
660             switch ($angle) {
661             
662                case 90:
663                   for ($y = 0; $y < ($src_y); $y++) {
664                      for ($x = 0; $x < ($src_x); $x++) {
665                         $color = imagecolorat($src_img, $x, $y);
666                         imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
667                      }
668                   }
669                   break;
670
671                case 270:
672                   for ($y = 0; $y < ($src_y); $y++) {
673                      for ($x = 0; $x < ($src_x); $x++) {
674                         $color = imagecolorat($src_img, $x, $y);
675                         imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
676                      }
677                   }
678                   break;
679
680                case 180:
681                   for ($y = 0; $y < ($src_y); $y++) {
682                      for ($x = 0; $x < ($src_x); $x++) {
683                         $color = imagecolorat($src_img, $x, $y);
684                         imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
685                      }
686                   }
687                   break;
688
689                default: $rotate = $src_img;
690             };
691
692             return $rotate;
693
694          }
695
696          $img = imagerotate($img, $degrees);
697
698       }
699
700       return $img;
701
702    } // rotateImage()
703
704    private function get_photo_tags($idx)
705    {
706       $result = $this->db->db_query("
707          SELECT t.id, t.name
708          FROM tags t
709          INNER JOIN photo_tags pt
710             ON t.id=pt.tag_id
711          WHERE pt.photo_id='". $idx ."'
712       ");
713
714       $tags = Array();
715
716       while($row = $this->db->db_fetch_object($result))
717          $tags[$row['id']] = $row['name'];
718
719       return $tags;
720
721    } // get_photo_tags()
722
723 }
724
725 ?>