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