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