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