issue28, use getimagesize if no exif data is available
[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       /* Check necessary requirements */
20       if(!$this->checkRequirements()) {
21          exit(1);
22       }
23
24       $this->cfg = new PHPFSPOT_CFG;
25
26       $this->db  = new PHPFSPOT_DB(&$this, $this->cfg->fspot_db);
27       $this->cfg_db = new PHPFSPOT_DB(&$this, $this->cfg->phpfspot_db);
28       $this->check_config_table();
29
30       $this->tmpl = new PHPFSPOT_TMPL($this);
31
32       $this->get_tags();
33
34       session_start();
35
36       if(!isset($_SESSION['tag_condition']))
37          $_SESSION['tag_condition'] = 'or';
38
39       if(!isset($_SESSION['searchfor']))
40          $_SESSION['searchfor'] = '';
41
42       // if begin_with is still set but rows_per_page is now 0, unset it
43       if(isset($_SESSION['begin_with']) && $this->cfg->rows_per_page == 0)
44          unset($_SESSION['begin_with']);
45
46    } // __construct()
47
48    public function __destruct()
49    {
50
51    } // __destruct()
52
53    public function show()
54    {
55       $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
56       $this->tmpl->assign('page_title', $this->cfg->page_title);
57       $this->tmpl->assign('current_condition', $_SESSION['tag_condition']);
58
59       switch($_GET['mode']) {
60          case 'showpi':
61             if(isset($_GET['tags'])) {
62                $_SESSION['selected_tags'] = split(',', $_GET['tags']);
63             }
64             break;
65       }
66
67       $this->tmpl->assign('content_page', 'welcome.tpl');
68       $this->tmpl->show("index.tpl");
69
70
71    } // show()
72
73    private function get_tags()
74    {
75    
76       $this->avail_tags = Array();
77       $count = 0;
78    
79       $result = $this->db->db_query("
80          SELECT id,name
81          FROM tags
82          ORDER BY sort_priority ASC
83       ");
84       
85       while($row = $this->db->db_fetch_object($result)) {
86
87          $tag_id = $row['id'];
88          $tag_name = $row['name'];
89
90          /* check if config requests to ignore this tag */
91          if(in_array($row['name'], $this->cfg->hide_tags))
92             continue;
93
94          $this->tags[$tag_id] = $tag_name; 
95          $this->avail_tags[$count] = $tag_id;
96
97          $count++;
98
99       }
100
101    } // get_tags()
102
103    public function get_photo_details($idx)
104    {
105       $result = $this->db->db_query("
106          SELECT *
107          FROM photos
108          WHERE id='". $idx ."'
109       ");
110       
111       return $this->db->db_fetch_object($result);
112
113    } // get_photo_details
114
115    public function getPhotoName($idx)
116    {
117       if($details = $this->get_photo_details($idx)) {
118
119          $name = $details['name'];
120
121          if(strlen($name) > 15) {
122             $name = substr($name, 0, 10) ."...". substr($name, -10);
123          }
124
125          return $name;
126    
127       }
128
129    } // getPhotoName()
130
131    public function translate_path($path, $width = 0)
132    {  
133       return str_replace($this->cfg->path_replace_from, $this->cfg->path_replace_to, $path);
134
135    } // translate_path
136
137    public function showPhoto($photo)
138    {
139       $all_photos = $this->getPhotoSelection();
140       $count = count($all_photos);
141
142       for($i = 0; $i < $count; $i++) {
143          
144          if($get_next) {
145             $next_img = $all_photos[$i];
146             break;
147          }
148
149          if($all_photos[$i] == $photo) {
150             $get_next = 1;
151          }
152          else {
153             $previous_img = $all_photos[$i];
154          }
155
156          if($photo == $all_photos[$i]) {
157                $current = $i;
158          }
159       }
160
161       $details = $this->get_photo_details($photo);
162       $orig_path = $this->translate_path($details['directory_path']) ."/". $details['name'];
163       $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->photo_width ."_". $this->getMD5($photo);
164
165       if(!file_exists($orig_path)) {
166          $this->_warning("Photo ". $orig_path ." does not exist!<br />\n");
167       }
168
169       if(!is_readable($orig_path)) {
170          $this->_warning("Photo ". $orig_path ." is not readable for user ". get_current_user() ."<br />\n");
171       }
172
173       /* If the thumbnail doesn't exist yet, try to create it */
174       if(!file_exists($thumb_path)) {
175          $this->gen_thumb($photo, true);
176       }
177
178       $meta = $this->get_meta_informations($orig_path);
179
180       /* If EXIF data are available, use them */
181       if(isset($meta['ExifImageWidth'])) {
182          $meta_res = $meta['ExifImageWidth'] ."x". $meta['ExifImageLength'];
183       } else {
184          $info = getimagesize($orig_path);
185          $meta_res = $info[0] ."x". $info[1]; 
186       }
187
188       $meta_date = isset($meta['FileDateTime']) ? strftime("%a %x %X", $meta['FileDateTime']) : "n/a";
189       $meta_make = isset($meta['Make']) ? $meta['Make'] ." ". $meta['Model'] : "n/a";
190       $meta_size = isset($meta['FileSize']) ? round($meta['FileSize']/1024, 1) ."kbyte" : "n/a";
191
192       if(file_exists($thumb_path)) {
193
194          $info = getimagesize($thumb_path);
195
196          $this->tmpl->assign('description', $details['description']);
197          $this->tmpl->assign('image_name', $details['name']);
198
199          $this->tmpl->assign('width', $info[0]);
200          $this->tmpl->assign('height', $info[1]);
201          $this->tmpl->assign('ExifMadeOn', $meta_date);
202          $this->tmpl->assign('ExifMadeWith', $meta_make);
203          $this->tmpl->assign('ExifOrigResolution', $meta_res);
204          $this->tmpl->assign('ExifFileSize', $meta_size);
205     
206          $this->tmpl->assign('image_url', 'phpfspot_img.php?idx='. $photo ."&amp;width=". $this->cfg->photo_width);
207          $this->tmpl->assign('image_url_full', 'phpfspot_img.php?idx='. $photo);
208
209          $this->tmpl->assign('tags', $this->get_photo_tags($photo));
210          $this->tmpl->assign('current', $current);
211       }
212       else {
213          $this->_warning("Can't open file ". $thumb_path ."\n");
214       }
215
216       if($previous_img) {
217          $this->tmpl->assign('previous_url', "javascript:showImage(". $previous_img .");");
218       }
219
220       if($next_img) {
221          $this->tmpl->assign('next_url', "javascript:showImage(". $next_img .");");
222       }
223
224       $this->tmpl->show("single_photo.tpl");
225
226    } // showPhoto()
227
228    public function getAvailableTags()
229    {
230       $result = $this->db->db_query("
231          SELECT tag_id as id, count(tag_id) as quantity
232          FROM photo_tags
233          INNER JOIN tags t
234             ON t.id = tag_id
235          GROUP BY tag_id
236          ORDER BY t.name ASC
237       ");
238
239       $tags = Array();
240
241       while($row = $this->db->db_fetch_object($result)) {
242          $tags[$row['id']] = $row['quantity'];
243       }
244
245       // change these font sizes if you will
246       $max_size = 125; // max font size in %
247       $min_size = 75; // min font size in %
248
249       // get the largest and smallest array values
250       $max_qty = max(array_values($tags));
251       $min_qty = min(array_values($tags));
252
253       // find the range of values
254       $spread = $max_qty - $min_qty;
255       if (0 == $spread) { // we don't want to divide by zero
256          $spread = 1;
257       }
258
259       // determine the font-size increment
260       // this is the increase per tag quantity (times used)
261       $step = ($max_size - $min_size)/($spread);
262
263       // loop through our tag array
264       foreach ($tags as $key => $value) {
265
266          if(isset($_SESSION['selected_tags']) && in_array($key, $_SESSION['selected_tags']))
267             continue;
268
269           // calculate CSS font-size
270           // find the $value in excess of $min_qty
271           // multiply by the font-size increment ($size)
272           // and add the $min_size set above
273          $size = $min_size + (($value - $min_qty) * $step);
274           // uncomment if you want sizes in whole %:
275          $size = ceil($size);
276
277          print "<a href=\"javascript:Tags('add', ". $key .");\" class=\"tag\" style=\"font-size: ". $size ."%;\">". $this->tags[$key] ."</a>, ";
278
279       }
280
281    } // getAvailableTags()
282
283    public function getSelectedTags()
284    {
285       foreach($this->avail_tags as $tag)
286       {
287          // return all selected tags
288          if(isset($_SESSION['selected_tags']) && in_array($tag, $_SESSION['selected_tags'])) {
289             print "<a href=\"javascript:Tags('del', ". $tag .");\" class=\"tag\">". $this->tags[$tag] ."</a>&nbsp;";
290          }
291
292       }
293
294    } // getSelectedTags()
295
296    public function addTag($tag)
297    {
298       if(!isset($_SESSION['selected_tags']))
299          $_SESSION['selected_tags'] = Array();
300
301       if(!in_array($tag, $_SESSION['selected_tags']))
302          array_push($_SESSION['selected_tags'], $tag);
303    
304    } // addTag()
305
306    public function delTag($tag)
307    {
308       if(isset($_SESSION['selected_tags'])) {
309          $key = array_search($tag, $_SESSION['selected_tags']);
310          unset($_SESSION['selected_tags'][$key]);
311          sort($_SESSION['selected_tags']);
312       }
313
314    } // delTag()
315
316    public function resetTags()
317    {
318       unset($_SESSION['selected_tags']);
319
320    } // resetTags()
321
322    public function resetTagSearch()
323    {
324       unset($_SESSION['searchfor']);
325
326    } // resetTagSearch()
327
328    public function getPhotoSelection()
329    {  
330       $tagged_photos = Array();
331
332       /* return a search result */
333       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '') {
334          $result = $this->db->db_query("
335             SELECT DISTINCT photo_id
336                FROM photo_tags pt
337             INNER JOIN photos p
338                ON p.id=pt.photo_id
339             INNER JOIN tags t
340                ON pt.tag_id=t.id
341             WHERE t.name LIKE '%". $_SESSION['searchfor'] ."%'
342                ORDER BY p.time ASC
343          ");
344          while($row = $this->db->db_fetch_object($result)) {
345             array_push($tagged_photos, $row['photo_id']);
346          }
347          return $tagged_photos;
348       }
349
350       /* return according the selected tags */
351       if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
352          $selected = "";
353          foreach($_SESSION['selected_tags'] as $tag)
354             $selected.= $tag .",";
355          $selected = substr($selected, 0, strlen($selected)-1);
356
357          if($_SESSION['tag_condition'] == 'or') {
358             $result = $this->db->db_query("
359                SELECT DISTINCT photo_id
360                   FROM photo_tags pt
361                INNER JOIN photos p
362                   ON p.id=pt.photo_id
363                WHERE pt.tag_id IN (". $selected .")
364                ORDER BY p.time ASC
365             ");
366          }
367          elseif($_SESSION['tag_condition'] == 'and') {
368
369             /* Join together a table looking like
370
371                pt1.photo_id pt1.tag_id pt2.photo_id pt2.tag_id ...
372
373                so the query can quickly return all images matching the
374                selected tags in an AND condition
375
376             */
377
378             $query_str = "
379                SELECT DISTINCT pt1.photo_id
380                   FROM photo_tags pt1
381             ";
382
383             for($i = 0; $i < count($_SESSION['selected_tags']); $i++) {
384                $query_str.= "
385                   INNER JOIN photo_tags pt". ($i+2) ."
386                      ON pt1.photo_id=pt". ($i+2) .".photo_id
387                ";
388             }
389             $query_str.= "WHERE pt1.tag_id=". $_SESSION['selected_tags'][0];
390             for($i = 1; $i < count($_SESSION['selected_tags']); $i++) {
391                $query_str.= "
392                   AND pt". ($i+1) .".tag_id=". $_SESSION['selected_tags'][$i] ."
393                "; 
394             }
395             $result = $this->db->db_query($query_str);
396          }
397
398          while($row = $this->db->db_fetch_object($result)) {
399             array_push($tagged_photos, $row['photo_id']);
400          }
401          return $tagged_photos;
402       }
403
404       /* return all available photos */
405       $result = $this->db->db_query("
406          SELECT DISTINCT photo_id
407             FROM photo_tags pt
408          INNER JOIN photos p
409             ON p.id=pt.photo_id
410          ORDER BY p.time ASC
411       ");
412       while($row = $this->db->db_fetch_object($result)) {
413          array_push($tagged_photos, $row['photo_id']);
414       }
415       return $tagged_photos;
416
417    } // getPhotoSelection()
418
419    public function showPhotoIndex()
420    {
421       $photos = $this->getPhotoSelection();
422
423       $count = count($photos);
424
425       if(isset($_SESSION['begin_with']) && $_SESSION['begin_with'] != "")
426          $anchor = $_SESSION['begin_with'];
427
428       if(!isset($this->cfg->rows_per_page) || $this->cfg->rows_per_page == 0) {
429
430          $begin_with = 0;
431          $end_with = $count;
432
433       }
434       elseif($this->cfg->rows_per_page > 0) {
435
436          if(!$_SESSION['begin_with'] || $_SESSION['begin_with'] == 0)
437             $begin_with = 0;
438          else {
439
440             $begin_with = $_SESSION['begin_with'];
441
442             // verify $begin_with - perhaps the thumbs-per-rows or
443             // rows-per-page variables have changed or the jump back
444             // from a photo wasn't exact - so calculate the real new
445             // starting point
446             $multiplicator = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
447             for($i = 0; $i <= $count; $i+=$multiplicator) {
448                if($begin_with >= $i && $begin_with < $i+$multiplicator) {
449                   $begin_with = $i;
450                   break;
451                }
452             }
453          }
454
455          $end_with = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
456       }
457
458    
459       $rows = 0;
460       $cols = 0;
461       $images[$rows] = Array();
462       $img_height[$rows] = Array();
463       $img_width[$rows] = Array();
464       $img_id[$rows] = Array();
465       $img_name[$rows] = Array();
466
467       for($i = $begin_with; $i < $end_with; $i++) {
468
469          $images[$rows][$cols] = $photos[$i];
470          $img_id[$rows][$cols] = $i;
471          $img_name[$rows][$cols] = $this->getPhotoName($photos[$i]);
472
473          $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->thumb_width ."_". $this->getMD5($photos[$i]);
474
475          if(file_exists($thumb_path)) {
476             $info = getimagesize($thumb_path); 
477             $img_width[$rows][$cols] = $info[0];
478             $img_height[$rows][$cols] = $info[1];
479          }
480
481          if($cols == $this->cfg->thumbs_per_row-1) {
482             $cols = 0;
483             $rows++;
484             $images[$rows] = Array();
485             $img_width[$rows] = Array();
486             $img_height[$rows] = Array();
487          }
488          else {
489             $cols++;
490          }
491       } 
492
493       // +1 for for smarty's selection iteration
494       $rows++;
495
496       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
497          $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
498
499       if($this->cfg->rows_per_page != 0) {
500       
501          /* calculate the page switchers */
502          $previous_start = $begin_with - ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
503          $next_start = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
504
505          if($begin_with != 0) 
506             $this->tmpl->assign("previous_url", "javascript:showPhotoIndex(". $previous_start .");"); 
507          if($end_with < $count)
508             $this->tmpl->assign("next_url", "javascript:showPhotoIndex(". $next_start .");"); 
509
510          /* page selector */
511          $photo_per_page  = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
512
513          /* until 6 pages we show the selector from 1-6
514             everything large will be
515             1 ... 2 3 4 (5) 6 7 ... 9
516          */ 
517          $last_page = ceil($count / $photo_per_page);
518
519          if($begin_with == 0) {
520             $current_page = 1;
521          } 
522          else {
523             $current_page = 0;
524             for($i = $begin_with; $i >= 0; $i-=$photo_per_page) {
525                $current_page++;
526             }
527          } 
528
529          for($i = 1; $i <= $last_page; $i++) {
530
531             if($current_page == $i)
532                $style = "style=\"font-size: 125%;\"";
533             elseif($current_page-1 == $i || $current_page+1 == $i)
534                $style = "style=\"font-size: 105%;\"";
535             elseif(($current_page-5 >= $i) && ($i != 1) ||
536                ($current_page+5 <= $i) && ($i != $last_page))
537                $style = "style=\"font-size: 75%;\"";
538             else
539                $style = "";
540
541             $page_select.= "<a href=\"javascript:showPhotoIndex(". (($i*$photo_per_page)-$photo_per_page) .");\"";
542             if($style != "")
543                $page_select.= $style;
544             $page_select.= ">". $i ."</a>&nbsp;";
545
546          }
547
548          /* only show the page selector if we have more then one page */
549          if($last_page > 1)
550             $this->tmpl->assign('page_selector', $page_select);
551       }
552
553       $current_tags = "";
554       if($_SESSION['selected_tags'] != "") {
555          foreach($_SESSION['selected_tags'] as $tag)
556             $current_tags.= $tag .",";
557          $current_tags = substr($current_tags, 0, strlen($current_tags)-1);
558       }
559
560       $extern_link = "http://". $_SERVER['SERVER_NAME'] ."/index.php?mode=showpi";
561       if($current_tags != "") {
562          $extern_link.= "&tags=". $current_tags;
563       }
564
565       $this->tmpl->assign('extern_link', $extern_link);
566       $this->tmpl->assign('count', $count);
567       $this->tmpl->assign('width', $this->cfg->thumb_width);
568       $this->tmpl->assign('images', $images);
569       $this->tmpl->assign('img_width', $img_width);
570       $this->tmpl->assign('img_height', $img_height);
571       $this->tmpl->assign('img_id', $img_id);
572       $this->tmpl->assign('img_name', $img_name);
573       $this->tmpl->assign('rows', $rows);
574       $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
575
576       $this->tmpl->show("photo_index.tpl");
577
578       if(isset($anchor))
579          print "<script language=\"JavaScript\">self.location.hash = '#image". $anchor ."';</script>\n";
580
581    } // showPhotoIndex()
582
583    public function showBubbleDetails($photo, $direction)
584    {
585       if($direction == "up")
586          $direction = "bubbleimg_up";
587       else
588          $direction = "bubbleimg_down";
589
590       $details = $this->get_photo_details($photo);
591       $orig_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
592
593       $image_url = "phpfspot_img.php?idx=". $photo ."&amp;width=". $this->cfg->bubble_width;
594
595       $filesize = filesize($orig_path);
596       $filesize = rand($filesize/1024, 2);
597
598       if(!file_exists($orig_path)) {
599          $this->_warning("Photo ". $orig_path ." does not exist!<br />\n");
600          return;
601       }
602       
603       if(!is_readable($orig_path)) {
604          $this->_warning("Photo ". $orig_path ." is not readable for user ". get_current_user() ."<br />\n");
605          return;
606       }
607
608       $img = getimagesize($orig_path);
609
610       $this->tmpl->assign('file_size', $filesize);
611       $this->tmpl->assign('width', $img[0]);
612       $this->tmpl->assign('height', $img[1]);
613       $this->tmpl->assign('file_name', $details['name']);
614       $this->tmpl->assign('image_id', $direction);
615       $this->tmpl->assign('image_url', $image_url);
616       $this->tmpl->show("bubble_details.tpl");
617
618    } // showBubbleDetails()
619
620    public function showCredits()
621    {
622       $this->tmpl->assign('version', $this->cfg->version);
623       $this->tmpl->assign('product', $this->cfg->product);
624       $this->tmpl->show("credits.tpl");
625
626    } // showCredits()
627
628    public function create_thumbnail($orig_image, $thumb_image, $width)
629    {  
630       if(!file_exists($orig_image))
631          return false;
632
633       $details = getimagesize($orig_image);
634       
635       /* check if original photo is a support image type */
636       if(!$this->checkifImageSupported($details['mime']))
637          return false;
638
639       $meta = $this->get_meta_informations($orig_image);
640
641       $rotate = 0;
642       $flip = false;
643
644       switch($meta['Orientation']) {
645
646          case 1: /* top, left */
647             $rotate = 0; $flip = false; break;
648          case 2: /* top, right */
649             $rotate = 0; $flip = true; break;
650          case 3: /* bottom, left */
651             $rotate = 180; $flip = false; break;
652          case 4: /* bottom, right */
653             $rotate = 180; $flip = true; break;
654          case 5: /* left side, top */
655             $rotate = 90; $flip = true; break;
656          case 6: /* right side, top */
657             $rotate = 90; $flip = false; break;
658          case 7: /* left side, bottom */
659             $rotate = 270; $flip = true; break;
660          case 8: /* right side, bottom */
661             $rotate = 270; $flip = false; break;
662       }
663
664       $src_img = @imagecreatefromjpeg($orig_image);
665
666       if(!$src_img) {
667          print "Can't load image from ". $orig_image ."\n";
668          return false;
669       }
670
671       /* grabs the height and width */
672       $cur_width = imagesx($src_img);
673       $cur_height = imagesy($src_img);
674
675       // If requested width is more then the actual image width,
676       // do not generate a thumbnail
677
678       if($width >= $cur_width) {
679          imagedestroy($src_img);
680          return true;
681       }
682
683       // If the image will be rotate because EXIF orientation said so
684       // 'virtually rotate' the image for further calculations
685       if($rotate == 90 || $rotate == 270) {
686          $tmp = $cur_width;
687          $cur_width = $cur_height;
688          $cur_height = $tmp;
689       }
690
691       /* calculates aspect ratio */
692       $aspect_ratio = $cur_height / $cur_width;
693
694       /* sets new size */
695       if($aspect_ratio < 1) {
696          $new_w = $width;
697          $new_h = abs($new_w * $aspect_ratio);
698       } else {
699          /* 'virtually' rotate the image and calculate it's ratio */
700          $tmp_w = $cur_height;
701          $tmp_h = $cur_width;
702          /* now get the ratio from the 'rotated' image */
703          $tmp_ratio = $tmp_h/$tmp_w;
704          /* now calculate the new dimensions */
705          $tmp_w = $width;
706          $tmp_h = abs($tmp_w * $tmp_ratio);
707
708          // now that we know, how high they photo should be, if it
709          // gets rotated, use this high to scale the image
710          $new_h = $tmp_h;
711          $new_w = abs($new_h / $aspect_ratio);
712
713          // If the image will be rotate because EXIF orientation said so
714          // now 'virtually rotate' back the image for the image manipulation
715          if($rotate == 90 || $rotate == 270) {
716             $tmp = $new_w;
717             $new_w = $new_h;
718             $new_h = $tmp;
719          }
720       }
721
722       /* creates new image of that size */
723       $dst_img = imagecreatetruecolor($new_w, $new_h);
724
725       imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
726
727       /* copies resized portion of original image into new image */
728       imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, imagesx($src_img), imagesy($src_img));
729
730       /* needs the image to be flipped horizontal? */
731       if($flip) {
732          print "(FLIP)";
733          $image = $dst_img;
734          for($x = 0; $x < $new_w; $x++) {
735             imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
736          }
737       }
738
739       if($rotate) {
740          $this->_debug("(ROTATE)");
741          $dst_img = $this->rotateImage($dst_img, $rotate);
742       }
743
744       /* write down new generated file */
745       $result = imagejpeg($dst_img, $thumb_image, 75);
746
747       /* free your mind */
748       imagedestroy($dst_img);
749       imagedestroy($src_img);
750
751       if($result === false) {
752          print "Can't write thumbnail ". $thumb_image ."\n";
753          return false;
754       }
755
756       return true;
757
758    } // create_thumbnail()
759
760    public function get_meta_informations($file)
761    {
762       return exif_read_data($file);
763
764    } // get_meta_informations()
765
766    public function check_config_table()
767    {
768       // if the config table doesn't exist yet, create it
769       if(!$this->cfg_db->db_check_table_exists("images")) {
770          $this->cfg_db->db_exec("
771             CREATE TABLE images (
772                img_idx int primary key,
773                img_md5 varchar(32)
774             )
775             ");
776       }
777
778    } // check_config_table
779
780    /**
781     * Generates a thumbnail from photo idx
782     *
783     * This function will generate JPEG thumbnails from provided F-Spot photo
784     * indizes.
785     *
786     * 1. Check if all thumbnail generations (width) are already in place and
787     *    readable
788     * 2. Check if the md5sum of the original file has changed
789     * 3. Generate the thumbnails if needed
790     */
791    public function gen_thumb($idx = 0, $force = 0)
792    {
793       $error = 0;
794
795       $resolutions = Array(
796          $this->cfg->thumb_width,
797          $this->cfg->bubble_width,
798          $this->cfg->photo_width,
799       );
800
801       /* get details from F-Spot's database */
802       $details = $this->get_photo_details($idx);
803
804       /* calculate file MD5 sum */
805       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
806
807       if(!file_exists($full_path)) {
808          $this->_warning("File ". $full_path ." does not exist\n");
809          return;
810       }
811
812       if(!is_readable($full_path)) {
813          $this->_warning("File ". $full_path ." is not readable for ". get_current_user() ."\n");
814          return;
815       }
816
817       $file_md5 = md5_file($full_path);
818
819       $this->_debug("Image [". $idx ."] ". $details['name'] ." Thumbnails:");
820
821       foreach($resolutions as $resolution) {
822
823          $thumb_path = $this->cfg->base_path ."/thumbs/". $resolution ."_". $file_md5;
824
825          /* if the thumbnail file doesn't exist, create it */
826          if(!file_exists($thumb_path)) {
827
828             $this->_debug(" ". $resolution ."px");
829             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
830                $error = 1;
831          }
832
833          /* if the file hasn't changed there is no need to regen the thumb */
834          elseif($file_md5 != $this->getMD5($idx) || $force) {
835
836             $this->_debug(" ". $resolution ."px");
837             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
838                $error = 1;
839
840          }
841       }
842
843       /* set the new/changed MD5 sum for the current photo */
844       if(!$error) {
845          $this->setMD5($idx, $file_md5);
846       }
847
848       $this->_debug("\n");
849
850    } // gen_thumb()
851
852    public function getMD5($idx)
853    {
854       $result = $this->cfg_db->db_query("
855          SELECT img_md5 
856          FROM images
857          WHERE img_idx='". $idx ."'
858       ");
859
860       if(!$result)
861          return 0;
862
863       $img = $this->cfg_db->db_fetch_object($result);
864       return $img['img_md5'];
865       
866    } // getMD5()
867
868    private function setMD5($idx, $md5)
869    {
870       $result = $this->cfg_db->db_exec("
871          REPLACE INTO images (img_idx, img_md5)
872          VALUES ('". $idx ."', '". $md5 ."')
873       ");
874
875    } // setMD5()
876
877    public function setTagCondition($mode)
878    {
879       $_SESSION['tag_condition'] = $mode;
880
881    } // setTagCondition()
882
883    public function startTagSearch($searchfor)
884    {
885       $_SESSION['searchfor'] = $searchfor;
886       $_SESSION['selected_tags'] = Array();
887
888       foreach($this->avail_tags as $tag) {
889          if(preg_match('/'. $searchfor .'/i', $this->tags[$tag]))
890             array_push($_SESSION['selected_tags'], $tag);
891       }
892
893    } // startTagSearch()
894
895    private function rotateImage($img, $degrees)
896    {
897       if(function_exists("imagerotate"))
898          $img = imagerotate($img, $degrees, 0);
899       else
900       {
901          function imagerotate($src_img, $angle)
902          {
903             $src_x = imagesx($src_img);
904             $src_y = imagesy($src_img);
905             if ($angle == 180) {
906                $dest_x = $src_x;
907                $dest_y = $src_y;
908             }
909             elseif ($src_x <= $src_y) {
910                $dest_x = $src_y;
911                $dest_y = $src_x;
912             }
913             elseif ($src_x >= $src_y) {
914                $dest_x = $src_y;
915                $dest_y = $src_x;
916             }
917                
918             $rotate=imagecreatetruecolor($dest_x,$dest_y);
919             imagealphablending($rotate, false);
920                
921             switch ($angle) {
922             
923                case 90:
924                   for ($y = 0; $y < ($src_y); $y++) {
925                      for ($x = 0; $x < ($src_x); $x++) {
926                         $color = imagecolorat($src_img, $x, $y);
927                         imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
928                      }
929                   }
930                   break;
931
932                case 270:
933                   for ($y = 0; $y < ($src_y); $y++) {
934                      for ($x = 0; $x < ($src_x); $x++) {
935                         $color = imagecolorat($src_img, $x, $y);
936                         imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
937                      }
938                   }
939                   break;
940
941                case 180:
942                   for ($y = 0; $y < ($src_y); $y++) {
943                      for ($x = 0; $x < ($src_x); $x++) {
944                         $color = imagecolorat($src_img, $x, $y);
945                         imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
946                      }
947                   }
948                   break;
949
950                default: $rotate = $src_img;
951             };
952
953             return $rotate;
954
955          }
956
957          $img = imagerotate($img, $degrees);
958
959       }
960
961       return $img;
962
963    } // rotateImage()
964
965    private function get_photo_tags($idx)
966    {
967       $result = $this->db->db_query("
968          SELECT t.id, t.name
969          FROM tags t
970          INNER JOIN photo_tags pt
971             ON t.id=pt.tag_id
972          WHERE pt.photo_id='". $idx ."'
973       ");
974
975       $tags = Array();
976
977       while($row = $this->db->db_fetch_object($result))
978          $tags[$row['id']] = $row['name'];
979
980       return $tags;
981
982    } // get_photo_tags()
983
984    public function showTextImage($txt, $color=000000, $space=4, $font=4, $w=300)
985    {
986       if (strlen($color) != 6) 
987          $color = 000000;
988
989       $int = hexdec($color);
990       $h = imagefontheight($font);
991       $fw = imagefontwidth($font);
992       $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
993       $lines = count($txt);
994       $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
995       $bg = imagecolorallocate($im, 255, 255, 255);
996       $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
997       $y = 0;
998
999       foreach ($txt as $text) {
1000          $x = (($w - ($fw * strlen($text))) / 2);
1001          imagestring($im, $font, $x, $y, $text, $color);
1002          $y += ($h + $space);
1003       }
1004
1005       Header("Content-type: image/png");
1006       ImagePng($im);
1007
1008    } // showTextImage()
1009
1010    private function checkRequirements()
1011    {
1012       if(!function_exists("imagecreatefromjpeg")) {
1013          print "PHP GD library extension is missing<br />\n";
1014          $missing = true;
1015       }
1016
1017       if(!function_exists("sqlite3_open")) {
1018          print "PHP SQLite3 library extension is missing<br />\n";
1019          $missing = true;
1020       }
1021
1022       /* Check for HTML_AJAX PEAR package, lent from Horde project */
1023       ini_set('track_errors', 1);
1024       @include_once 'HTML/AJAX/Server.php';
1025       if(isset($php_errormsg)) {
1026          print "PEAR HTML_AJAX package is missing<br />\n";
1027          $missing = true;
1028       }
1029       ini_restore('track_errors');
1030
1031       if(isset($missing))
1032          return false;
1033
1034       return true;
1035
1036    } // checkRequirements()
1037
1038    private function _debug($text)
1039    {
1040       if($this->fromcmd) {
1041          print $text;
1042       }
1043
1044    } // _debug()
1045
1046    public function checkifImageSupported($mime)
1047    {
1048       if(in_array($mime, Array("image/jpeg")))
1049          return true;
1050
1051       return false;
1052
1053    } // checkifImageSupported()
1054
1055    public function _warning($text)
1056    {
1057       print "<img src=\"resources/green_info.png\" alt=\"warning\" />\n";
1058       print $text;
1059
1060    } // _warning()
1061
1062 }
1063
1064 ?>