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