c70478cd8ec2f5f50d9c1a9f554f73883ca182ee
[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       $meta = $this->get_meta_informations($image);
414
415       $rotate = 0;
416       $flip = false;
417
418       switch($meta['Orientation']) {
419
420          case 1:
421             $rotate = 0;
422             $flip = false;
423             break;
424
425          case 2:
426             $rotate = 0;
427             $flip = true;
428             break;
429
430          case 3:
431             $rotate = 180;
432             $flip = false;
433             break;
434
435          case 4:
436             $rotate = 180;
437             $flip = true;
438             break;
439
440          case 5:
441             $rotate = 90;
442             $flip = true;
443             break;
444
445          case 6:
446             $rotate = 90;
447             $flip = false;
448             break;
449
450          case 7:
451             $rotate = 270;
452             $flip = true;
453             break;
454
455          case 8:
456             $rotate = 270;
457             $flip = false;
458             break;
459       }
460
461       $src_img = @imagecreatefromjpeg($image);
462
463       if($src_img)
464       {  
465          /* grabs the height and width */
466          $new_w = imagesx($src_img);
467          $new_h = imagesy($src_img);
468
469          // If requested width is more then the actual image width,
470          // do not generate a thumbnail
471
472          if($width >= $new_w) {
473             imagedestroy($src_img);
474             return;
475          }
476
477          /* calculates aspect ratio */
478          $aspect_ratio = $new_h / $new_w;
479
480          /* sets new size */
481          $new_w = $width;
482          $new_h = abs($new_w * $aspect_ratio);
483
484          /* creates new image of that size */
485          $dst_img = imagecreatetruecolor($new_w,$new_h);
486
487          imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
488
489          /* copies resized portion of original image into new image */
490          imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
491
492          /* needs the image to be flipped horizontal? */
493          if($flip) {
494             print "(FLIP)";
495             $image = $dst_img;
496             for($x = 0; $x < $new_w; $x++) {
497                imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
498             }
499          }
500
501          if($rotate) {
502             print "(ROTATE)";
503             $dst_img = $this->rotateImage($dst_img, $rotate);
504          }
505
506          /* write down new generated file */
507
508          if(!file_exists(dirname($image) ."/thumbs"))
509             mkdir(dirname($image) ."/thumbs");
510
511          $newfile = dirname($image) ."/thumbs/". $width ."_". basename($image);
512          imagejpeg($dst_img, $newfile, 75);
513
514          /* free your mind */
515          imagedestroy($dst_img);
516          imagedestroy($src_img);
517       }
518
519    } // create_thumbnail()
520
521    public function get_meta_informations($file)
522    {
523       return exif_read_data($file);
524
525    } // get_meta_informations()
526
527    public function check_config_table()
528    {
529       // if the config table doesn't exist yet, create it
530       if(!$this->cfg_db->db_check_table_exists("images")) {
531          $this->cfg_db->db_exec("
532             CREATE TABLE images (
533                img_idx int primary key,
534                img_md5 varchar(32)
535             )
536             ");
537       }
538
539    } // check_config_table
540
541    public function gen_thumb($idx = 0, $fromcmd = 0, $force = 0)
542    {
543       $details = $this->get_photo_details($idx);
544
545       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
546       $file_md5 = md5_file($full_path);
547
548       if($fromcmd) print "Image [". $idx ."] ". $details['name'] ." Thumbnails:";
549
550       /* if the file hasn't changed there is no need to regen the thumb */
551       if(!$force && $file_md5 == $this->getMD5($idx)) {
552          if($fromcmd) print " file has not changed - skipping\n";
553          return;
554       }
555
556       /* set the new/changed MD5 sum for the current photo */
557       $this->setMD5($idx, $file_md5);
558
559       $resolutions = Array(
560          $this->cfg->thumb_width,
561          $this->cfg->bubble_width,
562          $this->cfg->photo_width
563       );
564
565       /* create thumbnails for the requested resolutions */
566       foreach($resolutions as $resolution) {
567          if($fromcmd) print " ". $resolution ."px";
568          $this->create_thumbnail($full_path, $resolution);
569       }
570
571       if($fromcmd) print "\n";
572
573    } // gen_thumb()
574
575    private function getMD5($idx)
576    {
577       $result = $this->cfg_db->db_query("
578          SELECT img_md5 
579          FROM images
580          WHERE img_idx='". $idx ."'
581       ");
582
583       if(!$result)
584          return 0;
585
586       $img = $this->cfg_db->db_fetch_object($result);
587       return $img['img_md5'];
588       
589    } // getMD5()
590
591    private function setMD5($idx, $md5)
592    {
593       $result = $this->cfg_db->db_exec("
594          REPLACE INTO images (img_idx, img_md5)
595          VALUES ('". $idx ."', '". $md5 ."')
596       ");
597
598    } // setMD5()
599
600    public function setTagCondition($mode)
601    {
602       $_SESSION['tag_condition'] = $mode;
603
604    } // setTagCondition()
605
606    public function startSearch($searchfor)
607    {
608       $_SESSION['searchfor'] = $searchfor;
609
610    } // startSearch()
611
612    private function rotateImage($img, $degrees)
613    {
614       if(function_exists("imagerotate"))
615          $img = imagerotate($img, $degrees, 0);
616       else
617       {
618          function imagerotate($src_img, $angle)
619          {
620             $src_x = imagesx($src_img);
621             $src_y = imagesy($src_img);
622             if ($angle == 180) {
623                $dest_x = $src_x;
624                $dest_y = $src_y;
625             }
626             elseif ($src_x <= $src_y) {
627                $dest_x = $src_y;
628                $dest_y = $src_x;
629             }
630             elseif ($src_x >= $src_y) {
631                $dest_x = $src_y;
632                $dest_y = $src_x;
633             }
634                
635             $rotate=imagecreatetruecolor($dest_x,$dest_y);
636             imagealphablending($rotate, false);
637                
638             switch ($angle) {
639             
640                case 90:
641                   for ($y = 0; $y < ($src_y); $y++) {
642                      for ($x = 0; $x < ($src_x); $x++) {
643                         $color = imagecolorat($src_img, $x, $y);
644                         imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
645                      }
646                   }
647                   break;
648
649                case 270:
650                   for ($y = 0; $y < ($src_y); $y++) {
651                      for ($x = 0; $x < ($src_x); $x++) {
652                         $color = imagecolorat($src_img, $x, $y);
653                         imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
654                      }
655                   }
656                   break;
657
658                case 180:
659                   for ($y = 0; $y < ($src_y); $y++) {
660                      for ($x = 0; $x < ($src_x); $x++) {
661                         $color = imagecolorat($src_img, $x, $y);
662                         imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
663                      }
664                   }
665                   break;
666
667                default: $rotate = $src_img;
668             };
669
670             return $rotate;
671
672          }
673
674          $img = imagerotate($img, $degrees);
675
676       }
677
678       return $img;
679
680    } // rotateImage()
681
682    private function get_photo_tags($idx)
683    {
684       $result = $this->db->db_query("
685          SELECT t.id, t.name
686          FROM tags t
687          INNER JOIN photo_tags pt
688             ON t.id=pt.tag_id
689          WHERE pt.photo_id='". $idx ."'
690       ");
691
692       $tags = Array();
693
694       while($row = $this->db->db_fetch_object($result))
695          $tags[$row['id']] = $row['name'];
696
697       return $tags;
698
699    } // get_photo_tags()
700
701 }
702
703 ?>