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