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