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