fixed content type header
[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          GROUP BY tag_id
158          ORDER BY tag_id ASC
159       ");
160
161       $tags = Array();
162
163       while($row = $this->db->db_fetch_object($result)) {
164          $tags[$row['id']] = $row['quantity'];
165       }
166
167       // change these font sizes if you will
168       $max_size = 125; // max font size in %
169       $min_size = 75; // min font size in %
170
171       // get the largest and smallest array values
172       $max_qty = max(array_values($tags));
173       $min_qty = min(array_values($tags));
174
175       // find the range of values
176       $spread = $max_qty - $min_qty;
177       if (0 == $spread) { // we don't want to divide by zero
178          $spread = 1;
179       }
180
181       // determine the font-size increment
182       // this is the increase per tag quantity (times used)
183       $step = ($max_size - $min_size)/($spread);
184
185       // loop through our tag array
186       foreach ($tags as $key => $value) {
187
188          if(isset($_SESSION['selected_tags']) && in_array($key, $_SESSION['selected_tags']))
189             continue;
190
191           // calculate CSS font-size
192           // find the $value in excess of $min_qty
193           // multiply by the font-size increment ($size)
194           // and add the $min_size set above
195          $size = $min_size + (($value - $min_qty) * $step);
196           // uncomment if you want sizes in whole %:
197          $size = ceil($size);
198
199          print "<a href=\"javascript:Tags('add', ". $key .");\" class=\"tag\" style=\"font-size: ". $size ."%;\">". $this->tags[$key] ."</a>&nbsp;";
200
201       }
202
203    } // getAvailableTags()
204
205    public function getSelectedTags()
206    {
207       foreach($this->avail_tags as $tag)
208       {
209          // return all selected tags
210          if(isset($_SESSION['selected_tags']) && in_array($tag, $_SESSION['selected_tags'])) {
211             print "<a href=\"javascript:Tags('del', ". $tag .");\" class=\"tag\">". $this->tags[$tag] ."</a>&nbsp;";
212          }
213
214       }
215
216    } // getSelectedTags()
217
218    public function addTag($tag)
219    {
220       if(!isset($_SESSION['selected_tags']))
221          $_SESSION['selected_tags'] = Array();
222
223       if(!in_array($tag, $_SESSION['selected_tags']))
224          array_push($_SESSION['selected_tags'], $tag);
225    
226    } // addTag()
227
228    public function delTag($tag)
229    {
230       if(isset($_SESSION['selected_tags'])) {
231          $key = array_search($tag, $_SESSION['selected_tags']);
232          unset($_SESSION['selected_tags'][$key]);
233          sort($_SESSION['selected_tags']);
234       }
235
236    } // delTag()
237
238    public function resetTags()
239    {
240       unset($_SESSION['selected_tags']);
241
242    } // resetTags()
243
244    public function getPhotoSelection()
245    {  
246       $tagged_photos = Array();
247
248       /* return a search result */
249       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '') {
250          $result = $this->db->db_query("
251             SELECT DISTINCT photo_id
252                FROM photo_tags pt
253             INNER JOIN photos p
254                ON p.id=pt.photo_id
255             INNER JOIN tags t
256                ON pt.tag_id=t.id
257             WHERE t.name LIKE '%". $_SESSION['searchfor'] ."%'
258                ORDER BY p.time ASC
259          ");
260          while($row = $this->db->db_fetch_object($result)) {
261             array_push($tagged_photos, $row['photo_id']);
262          }
263          return $tagged_photos;
264       }
265
266       /* return according the selected tags */
267       if(isset($_SESSION['selected_tags'])) {
268          $selected = "";
269          foreach($_SESSION['selected_tags'] as $tag)
270             $selected.= $tag .",";
271          $selected = substr($selected, 0, strlen($selected)-1);
272
273          if($_SESSION['tag_condition'] == 'or') {
274             $result = $this->db->db_query("
275                SELECT DISTINCT photo_id
276                   FROM photo_tags pt
277                INNER JOIN photos p
278                   ON p.id=pt.photo_id
279                WHERE pt.tag_id IN (". $selected .")
280                ORDER BY p.time ASC
281             ");
282          }
283          elseif($_SESSION['tag_condition'] == 'and') {
284
285             /* Join together a table looking like
286
287                pt1.photo_id pt1.tag_id pt2.photo_id pt2.tag_id ...
288
289                so the query can quickly return all images matching the
290                selected tags in an AND condition
291
292             */
293
294             $query_str = "
295                SELECT DISTINCT pt1.photo_id
296                   FROM photo_tags pt1
297             ";
298
299             for($i = 0; $i < count($_SESSION['selected_tags']); $i++) {
300                $query_str.= "
301                   INNER JOIN photo_tags pt". ($i+2) ."
302                      ON pt1.photo_id=pt". ($i+2) .".photo_id
303                ";
304             }
305             $query_str.= "WHERE pt1.tag_id=". $_SESSION['selected_tags'][0];
306             for($i = 1; $i < count($_SESSION['selected_tags']); $i++) {
307                $query_str.= "
308                   AND pt". ($i+1) .".tag_id=". $_SESSION['selected_tags'][$i] ."
309                "; 
310             }
311             $result = $this->db->db_query($query_str);
312          }
313
314          while($row = $this->db->db_fetch_object($result)) {
315             array_push($tagged_photos, $row['photo_id']);
316          }
317          return $tagged_photos;
318       }
319
320       /* return all available photos */
321       $result = $this->db->db_query("
322          SELECT DISTINCT photo_id
323             FROM photo_tags pt
324          INNER JOIN photos p
325             ON p.id=pt.photo_id
326          ORDER BY p.time ASC
327       ");
328       while($row = $this->db->db_fetch_object($result)) {
329          array_push($tagged_photos, $row['photo_id']);
330       }
331       return $tagged_photos;
332
333    } // getPhotoSelection()
334
335    public function showPhotoIndex()
336    {
337       $photos = $this->getPhotoSelection();
338
339       $count = count($photos);
340
341       $rows = 0;
342       $cols = 0;
343       $images[$rows] = Array();
344
345       for($i = 0; $i < $count; $i++) {
346
347          $images[$rows][$cols] = $photos[$i];
348
349          if($cols == $this->cfg->thumbs_per_row-1) {
350             $cols = 0;
351             $rows++;
352             $images[$rows] = Array();
353          }
354          else {
355             $cols++;
356          }
357       } 
358
359       // +1 for for smarty's selection iteration
360       $rows++;
361
362       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
363          $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
364
365       $this->tmpl->assign('count', $count);
366       $this->tmpl->assign('width', $this->cfg->thumb_width);
367       $this->tmpl->assign('images', $images);
368       $this->tmpl->assign('rows', $rows);
369       $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
370       $this->tmpl->show("photo_index.tpl");
371
372
373    } // showPhotoIndex()
374
375    public function showBubbleDetails($photo, $direction)
376    {
377       if($direction == "up")
378          $direction = "bubbleimg_up";
379       else
380          $direction = "bubbleimg_down";
381
382       $details = $this->get_photo_details($photo);
383
384       $image_url = "phpfspot_img.php?idx=". $photo ."&amp;width=". $this->cfg->bubble_width;
385
386       $filesize = filesize($this->translate_path($details['directory_path'])  ."/". $details['name']);
387       $filesize = rand($filesize/1024, 2);
388
389       $img = getimagesize($this->translate_path($details['directory_path'])  ."/". $details['name']);
390
391       $this->tmpl->assign('file_size', $filesize);
392       $this->tmpl->assign('width', $img[0]);
393       $this->tmpl->assign('height', $img[1]);
394       $this->tmpl->assign('file_name', $details['name']);
395       $this->tmpl->assign('image_id', $direction);
396       $this->tmpl->assign('image_url', $image_url);
397       $this->tmpl->show("bubble_details.tpl");
398
399    } // showBubbleDetails()
400
401    public function showCredits()
402    {
403       $this->tmpl->assign('version', $this->cfg->version);
404       $this->tmpl->assign('product', $this->cfg->product);
405       $this->tmpl->show("credits.tpl");
406
407    } // showCredits()
408
409    public function create_thumbnail($image, $width)
410    {  
411       $meta = $this->get_meta_informations($image);
412
413       $rotate = 0;
414       $flip = false;
415
416       switch($meta['Orientation']) {
417
418          case 1:
419             $rotate = 0;
420             $flip = false;
421             break;
422
423          case 2:
424             $rotate = 0;
425             $flip = true;
426             break;
427
428          case 3:
429             $rotate = 180;
430             $flip = false;
431             break;
432
433          case 4:
434             $rotate = 180;
435             $flip = true;
436             break;
437
438          case 5:
439             $rotate = 90;
440             $flip = true;
441             break;
442
443          case 6:
444             $rotate = 90;
445             $flip = false;
446             break;
447
448          case 7:
449             $rotate = 270;
450             $flip = true;
451             break;
452
453          case 8:
454             $rotate = 270;
455             $flip = false;
456             break;
457       }
458
459       $src_img = @imagecreatefromjpeg($image);
460
461       if($src_img)
462       {  
463          /* grabs the height and width */
464          $new_w = imagesx($src_img);
465          $new_h = imagesy($src_img);
466
467          // If requested width is more then the actual image width,
468          // do not generate a thumbnail
469
470          if($width >= $new_w) {
471             imagedestroy($src_img);
472             return;
473          }
474
475          /* calculates aspect ratio */
476          $aspect_ratio = $new_h / $new_w;
477
478          /* sets new size */
479          $new_w = $width;
480          $new_h = abs($new_w * $aspect_ratio);
481
482          /* creates new image of that size */
483          $dst_img = imagecreatetruecolor($new_w,$new_h);
484
485          imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
486
487          /* copies resized portion of original image into new image */
488          imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
489
490          /* needs the image to be flipped horizontal? */
491          if($flip) {
492             print "(FLIP)";
493             $image = $dst_img;
494             for($x = 0; $x < $new_w; $x++) {
495                imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
496             }
497          }
498
499          if($rotate) {
500             print "(ROTATE)";
501             $dst_img = $this->rotateImage($dst_img, $rotate);
502          }
503
504          /* write down new generated file */
505
506          if(!file_exists(dirname($image) ."/thumbs"))
507             mkdir(dirname($image) ."/thumbs");
508
509          $newfile = dirname($image) ."/thumbs/". $width ."_". basename($image);
510          imagejpeg($dst_img, $newfile, 75);
511
512          /* free your mind */
513          imagedestroy($dst_img);
514          imagedestroy($src_img);
515       }
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    public function gen_thumb($idx = 0, $fromcmd = 0)
540    {
541       $details = $this->get_photo_details($idx);
542
543       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
544       $file_md5 = md5_file($full_path);
545
546       if($fromcmd) print "Image [". $idx ."] ". $details['name'] ." Thumbnails:";
547
548       /* if the file hasn't changed there is no need to regen the thumb */
549       if($file_md5 == $this->getMD5($idx)) {
550          if($fromcmd) print " file has not changed - skipping\n";
551          return;
552       }
553
554       /* set the new/changed MD5 sum for the current photo */
555       $this->setMD5($idx, $file_md5);
556
557       $resolutions = Array(
558          $this->cfg->thumb_width,
559          $this->cfg->bubble_width,
560          $this->cfg->photo_width
561       );
562
563       /* create thumbnails for the requested resolutions */
564       foreach($resolutions as $resolution) {
565          if($fromcmd) print " ". $resolution ."px";
566          $this->create_thumbnail($full_path, $resolution);
567       }
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 ?>