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