31a39529776df42465141c2e718b2f8fa3a13fae
[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('from'));
58       $this->tmpl->assign('to_date', $this->get_calendar('to'));
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       if(isset($_SESSION['selected_tags']))
343          unset($_SESSION['selected_tags']);
344
345    } // resetTags()
346
347    public function resetPhotoView()
348    {
349       if(isset($_SESSION['current_photo']))
350          unset($_SESSION['current_photo']);
351
352    } // resetPhotoView();
353
354    public function resetTagSearch()
355    {
356       if(isset($_SESSION['searchfor']))
357          unset($_SESSION['searchfor']);
358
359    } // resetTagSearch()
360
361    public function resetDateSearch()
362    {
363       if(isset($_SESSION['from_date']))
364          unset($_SESSION['from_date']);
365       if(isset($_SESSION['to_date']))
366          unset($_SESSION['to_date']);
367
368    } // resetDateSearch();
369
370    public function getPhotoSelection()
371    {  
372       $matched_photos = Array();
373
374       /* return a search result */
375       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '') {
376          $result = $this->db->db_query("
377             SELECT DISTINCT photo_id
378                FROM photo_tags pt
379             INNER JOIN photos p
380                ON p.id=pt.photo_id
381             INNER JOIN tags t
382                ON pt.tag_id=t.id
383             WHERE t.name LIKE '%". $_SESSION['searchfor'] ."%'
384                ORDER BY p.time ASC
385          ");
386          while($row = $this->db->db_fetch_object($result)) {
387             array_push($matched_photos, $row['photo_id']);
388          }
389          return $matched_photos;
390       }
391
392       /* return according the selected tags */
393       if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
394          $selected = "";
395          foreach($_SESSION['selected_tags'] as $tag)
396             $selected.= $tag .",";
397          $selected = substr($selected, 0, strlen($selected)-1);
398
399          if($_SESSION['tag_condition'] == 'or') {
400             $result = $this->db->db_query("
401                SELECT DISTINCT photo_id
402                   FROM photo_tags pt
403                INNER JOIN photos p
404                   ON p.id=pt.photo_id
405                WHERE pt.tag_id IN (". $selected .")
406                ORDER BY p.time ASC
407             ");
408          }
409          elseif($_SESSION['tag_condition'] == 'and') {
410
411             if(count($_SESSION['selected_tags']) >= 32) {
412                print "A SQLite limit of 32 tables within a JOIN SELECT avoids to<br />\n";
413                print "evaluate your tag selection. Please remove some tags from your selection.\n";
414                return Array();
415             } 
416
417             /* Join together a table looking like
418
419                pt1.photo_id pt1.tag_id pt2.photo_id pt2.tag_id ...
420
421                so the query can quickly return all images matching the
422                selected tags in an AND condition
423
424             */
425
426             $query_str = "
427                SELECT DISTINCT pt1.photo_id
428                   FROM photo_tags pt1
429             ";
430
431             for($i = 0; $i < count($_SESSION['selected_tags']); $i++) {
432                $query_str.= "
433                   INNER JOIN photo_tags pt". ($i+2) ."
434                      ON pt1.photo_id=pt". ($i+2) .".photo_id
435                ";
436             }
437             $query_str.= "WHERE pt1.tag_id=". $_SESSION['selected_tags'][0];
438             for($i = 1; $i < count($_SESSION['selected_tags']); $i++) {
439                $query_str.= "
440                   AND pt". ($i+1) .".tag_id=". $_SESSION['selected_tags'][$i] ."
441                "; 
442             }
443             $result = $this->db->db_query($query_str);
444          }
445
446          while($row = $this->db->db_fetch_object($result)) {
447             array_push($matched_photos, $row['photo_id']);
448          }
449          return $matched_photos;
450       }
451
452       if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
453          $from_date = strtotime($_SESSION['from_date']);
454          $to_date = strtotime($_SESSION['to_date']);
455          $result = $this->db->db_query("
456             SELECT DISTINCT photo_id
457                FROM photo_tags pt
458             INNER JOIN photos p
459                ON p.id=pt.photo_id
460             WHERE 
461                time>='". $from_date ."'
462             AND
463                time<='". $to_date ."'
464             ORDER BY p.time ASC
465          ");
466          while($row = $this->db->db_fetch_object($result)) {
467             array_push($matched_photos, $row['photo_id']);
468          }
469          return $matched_photos;
470       } 
471
472       /* return all available photos */
473       $result = $this->db->db_query("
474          SELECT DISTINCT photo_id
475             FROM photo_tags pt
476          INNER JOIN photos p
477             ON p.id=pt.photo_id
478          ORDER BY p.time ASC
479       ");
480       while($row = $this->db->db_fetch_object($result)) {
481          array_push($matched_photos, $row['photo_id']);
482       }
483       return $matched_photos;
484
485    } // getPhotoSelection()
486
487    public function showPhotoIndex()
488    {
489       $photos = $this->getPhotoSelection();
490
491       $count = count($photos);
492
493       if(isset($_SESSION['begin_with']) && $_SESSION['begin_with'] != "")
494          $anchor = $_SESSION['begin_with'];
495
496       if(!isset($this->cfg->rows_per_page) || $this->cfg->rows_per_page == 0) {
497
498          $begin_with = 0;
499          $end_with = $count;
500
501       }
502       elseif($this->cfg->rows_per_page > 0) {
503
504          if(!$_SESSION['begin_with'] || $_SESSION['begin_with'] == 0)
505             $begin_with = 0;
506          else {
507
508             $begin_with = $_SESSION['begin_with'];
509
510             // verify $begin_with - perhaps the thumbs-per-rows or
511             // rows-per-page variables have changed or the jump back
512             // from a photo wasn't exact - so calculate the real new
513             // starting point
514             $multiplicator = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
515             for($i = 0; $i <= $count; $i+=$multiplicator) {
516                if($begin_with >= $i && $begin_with < $i+$multiplicator) {
517                   $begin_with = $i;
518                   break;
519                }
520             }
521          }
522
523          $end_with = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
524       }
525
526    
527       $rows = 0;
528       $cols = 0;
529       $images[$rows] = Array();
530       $img_height[$rows] = Array();
531       $img_width[$rows] = Array();
532       $img_id[$rows] = Array();
533       $img_name[$rows] = Array();
534       $img_title = Array();
535
536       for($i = $begin_with; $i < $end_with; $i++) {
537
538          $images[$rows][$cols] = $photos[$i];
539          $img_id[$rows][$cols] = $i;
540          $img_name[$rows][$cols] = htmlspecialchars($this->getPhotoName($photos[$i], 15));
541          $img_title[$rows][$cols] = "Click to view photo ". htmlspecialchars($this->getPhotoName($photos[$i], 0));
542
543          $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->thumb_width ."_". $this->getMD5($photos[$i]);
544
545          if(file_exists($thumb_path)) {
546             $info = getimagesize($thumb_path); 
547             $img_width[$rows][$cols] = $info[0];
548             $img_height[$rows][$cols] = $info[1];
549          }
550
551          if($cols == $this->cfg->thumbs_per_row-1) {
552             $cols = 0;
553             $rows++;
554             $images[$rows] = Array();
555             $img_width[$rows] = Array();
556             $img_height[$rows] = Array();
557          }
558          else {
559             $cols++;
560          }
561       } 
562
563       // +1 for for smarty's selection iteration
564       $rows++;
565
566       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
567          $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
568
569       /* do we have to display the page selector ? */
570       if($this->cfg->rows_per_page != 0) {
571       
572          /* calculate the page switchers */
573          $previous_start = $begin_with - ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
574          $next_start = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
575
576          if($begin_with != 0) 
577             $this->tmpl->assign("previous_url", "javascript:showPhotoIndex(". $previous_start .");"); 
578          if($end_with < $count)
579             $this->tmpl->assign("next_url", "javascript:showPhotoIndex(". $next_start .");"); 
580
581          $photo_per_page  = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
582          $last_page = ceil($count / $photo_per_page);
583
584          /* get the current selected page */
585          if($begin_with == 0) {
586             $current_page = 1;
587          } else {
588             $current_page = 0;
589             for($i = $begin_with; $i >= 0; $i-=$photo_per_page) {
590                $current_page++;
591             }
592          } 
593
594          for($i = 1; $i <= $last_page; $i++) {
595
596             if($current_page == $i)
597                $style = "style=\"font-size: 125%;\"";
598             elseif($current_page-1 == $i || $current_page+1 == $i)
599                $style = "style=\"font-size: 105%;\"";
600             elseif(($current_page-5 >= $i) && ($i != 1) ||
601                ($current_page+5 <= $i) && ($i != $last_page))
602                $style = "style=\"font-size: 75%;\"";
603             else
604                $style = "";
605
606             $select = "<a href=\"javascript:showPhotoIndex(". (($i*$photo_per_page)-$photo_per_page) .");\"";
607                if($style != "")
608                   $select.= $style;
609             $select.= ">". $i ."</a>&nbsp;";
610
611             // until 9 pages we show the selector from 1-9
612             if($last_page <= 9) {
613                $page_select.= $select;
614                continue;
615             } else {
616                if($i == 1 /* first page */ || 
617                   $i == $last_page /* last page */ ||
618                   $i == $current_page /* current page */ ||
619                   $i == ceil($last_page * 0.25) /* first quater */ ||
620                   $i == ceil($last_page * 0.5) /* half */ ||
621                   $i == ceil($last_page * 0.75) /* third quater */ ||
622                   (in_array($i, array(1,2,3,4,5,6)) && $current_page <= 4) /* the first 6 */ ||
623                   (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 */ ||
624                   $i == $current_page-3 || $i == $current_page-2 || $i == $current_page-1 /* three before */ ||
625                   $i == $current_page+3 || $i == $current_page+2 || $i == $current_page+1 /* three after */) {
626
627                   $page_select.= $select;
628                   continue;
629
630                }
631             }
632
633             $page_select.= ".";
634          }
635
636          /* only show the page selector if we have more then one page */
637          if($last_page > 1)
638             $this->tmpl->assign('page_selector', $page_select);
639       }
640
641       
642       $current_tags = $this->getCurrentTags();
643       $extern_link = "index.php?mode=showpi";
644       if($current_tags != "") {
645          $extern_link.= "&tags=". $current_tags;
646       }
647
648       $export_link = "index.php?mode=export";
649
650       $this->tmpl->assign('extern_link', $extern_link);
651       $this->tmpl->assign('export_link', $export_link);
652       $this->tmpl->assign('count', $count);
653       $this->tmpl->assign('width', $this->cfg->thumb_width);
654       $this->tmpl->assign('images', $images);
655       $this->tmpl->assign('img_width', $img_width);
656       $this->tmpl->assign('img_height', $img_height);
657       $this->tmpl->assign('img_id', $img_id);
658       $this->tmpl->assign('img_name', $img_name);
659       $this->tmpl->assign('img_title', $img_title);
660       $this->tmpl->assign('rows', $rows);
661       $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
662
663       $this->tmpl->show("photo_index.tpl");
664
665       if(isset($anchor))
666          print "<script language=\"JavaScript\">self.location.hash = '#image". $anchor ."';</script>\n";
667
668    } // showPhotoIndex()
669
670    public function showCredits()
671    {
672       $this->tmpl->assign('version', $this->cfg->version);
673       $this->tmpl->assign('product', $this->cfg->product);
674       $this->tmpl->show("credits.tpl");
675
676    } // showCredits()
677
678    public function create_thumbnail($orig_image, $thumb_image, $width)
679    {  
680       if(!file_exists($orig_image))
681          return false;
682
683       $details = getimagesize($orig_image);
684       
685       /* check if original photo is a support image type */
686       if(!$this->checkifImageSupported($details['mime']))
687          return false;
688
689       $meta = $this->get_meta_informations($orig_image);
690
691       $rotate = 0;
692       $flip = false;
693
694       switch($meta['Orientation']) {
695
696          case 1: /* top, left */
697             $rotate = 0; $flip = false; break;
698          case 2: /* top, right */
699             $rotate = 0; $flip = true; break;
700          case 3: /* bottom, left */
701             $rotate = 180; $flip = false; break;
702          case 4: /* bottom, right */
703             $rotate = 180; $flip = true; break;
704          case 5: /* left side, top */
705             $rotate = 90; $flip = true; break;
706          case 6: /* right side, top */
707             $rotate = 90; $flip = false; break;
708          case 7: /* left side, bottom */
709             $rotate = 270; $flip = true; break;
710          case 8: /* right side, bottom */
711             $rotate = 270; $flip = false; break;
712       }
713
714       $src_img = @imagecreatefromjpeg($orig_image);
715
716       if(!$src_img) {
717          print "Can't load image from ". $orig_image ."\n";
718          return false;
719       }
720
721       /* grabs the height and width */
722       $cur_width = imagesx($src_img);
723       $cur_height = imagesy($src_img);
724
725       // If requested width is more then the actual image width,
726       // do not generate a thumbnail
727
728       if($width >= $cur_width) {
729          imagedestroy($src_img);
730          return true;
731       }
732
733       // If the image will be rotate because EXIF orientation said so
734       // 'virtually rotate' the image for further calculations
735       if($rotate == 90 || $rotate == 270) {
736          $tmp = $cur_width;
737          $cur_width = $cur_height;
738          $cur_height = $tmp;
739       }
740
741       /* calculates aspect ratio */
742       $aspect_ratio = $cur_height / $cur_width;
743
744       /* sets new size */
745       if($aspect_ratio < 1) {
746          $new_w = $width;
747          $new_h = abs($new_w * $aspect_ratio);
748       } else {
749          /* 'virtually' rotate the image and calculate it's ratio */
750          $tmp_w = $cur_height;
751          $tmp_h = $cur_width;
752          /* now get the ratio from the 'rotated' image */
753          $tmp_ratio = $tmp_h/$tmp_w;
754          /* now calculate the new dimensions */
755          $tmp_w = $width;
756          $tmp_h = abs($tmp_w * $tmp_ratio);
757
758          // now that we know, how high they photo should be, if it
759          // gets rotated, use this high to scale the image
760          $new_h = $tmp_h;
761          $new_w = abs($new_h / $aspect_ratio);
762
763          // If the image will be rotate because EXIF orientation said so
764          // now 'virtually rotate' back the image for the image manipulation
765          if($rotate == 90 || $rotate == 270) {
766             $tmp = $new_w;
767             $new_w = $new_h;
768             $new_h = $tmp;
769          }
770       }
771
772       /* creates new image of that size */
773       $dst_img = imagecreatetruecolor($new_w, $new_h);
774
775       imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
776
777       /* copies resized portion of original image into new image */
778       imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, imagesx($src_img), imagesy($src_img));
779
780       /* needs the image to be flipped horizontal? */
781       if($flip) {
782          print "(FLIP)";
783          $image = $dst_img;
784          for($x = 0; $x < $new_w; $x++) {
785             imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
786          }
787       }
788
789       if($rotate) {
790          $this->_debug("(ROTATE)");
791          $dst_img = $this->rotateImage($dst_img, $rotate);
792       }
793
794       /* write down new generated file */
795       $result = imagejpeg($dst_img, $thumb_image, 75);
796
797       /* free your mind */
798       imagedestroy($dst_img);
799       imagedestroy($src_img);
800
801       if($result === false) {
802          print "Can't write thumbnail ". $thumb_image ."\n";
803          return false;
804       }
805
806       return true;
807
808    } // create_thumbnail()
809
810    public function get_meta_informations($file)
811    {
812       return exif_read_data($file);
813
814    } // get_meta_informations()
815
816    public function check_config_table()
817    {
818       // if the config table doesn't exist yet, create it
819       if(!$this->cfg_db->db_check_table_exists("images")) {
820          $this->cfg_db->db_exec("
821             CREATE TABLE images (
822                img_idx int primary key,
823                img_md5 varchar(32)
824             )
825             ");
826       }
827
828    } // check_config_table
829
830    /**
831     * Generates a thumbnail from photo idx
832     *
833     * This function will generate JPEG thumbnails from provided F-Spot photo
834     * indizes.
835     *
836     * 1. Check if all thumbnail generations (width) are already in place and
837     *    readable
838     * 2. Check if the md5sum of the original file has changed
839     * 3. Generate the thumbnails if needed
840     */
841    public function gen_thumb($idx = 0, $force = 0)
842    {
843       $error = 0;
844
845       $resolutions = Array(
846          $this->cfg->thumb_width,
847          $this->cfg->photo_width,
848          $this->cfg->mini_width,
849       );
850
851       /* get details from F-Spot's database */
852       $details = $this->get_photo_details($idx);
853
854       /* calculate file MD5 sum */
855       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
856
857       if(!file_exists($full_path)) {
858          $this->_warning("File ". $full_path ." does not exist\n");
859          return;
860       }
861
862       if(!is_readable($full_path)) {
863          $this->_warning("File ". $full_path ." is not readable for ". get_current_user() ."\n");
864          return;
865       }
866
867       $file_md5 = md5_file($full_path);
868
869       $this->_debug("Image [". $idx ."] ". $details['name'] ." Thumbnails:");
870
871       foreach($resolutions as $resolution) {
872
873          $thumb_path = $this->cfg->base_path ."/thumbs/". $resolution ."_". $file_md5;
874
875          /* if the thumbnail file doesn't exist, create it */
876          if(!file_exists($thumb_path)) {
877
878             $this->_debug(" ". $resolution ."px");
879             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
880                $error = 1;
881          }
882
883          /* if the file hasn't changed there is no need to regen the thumb */
884          elseif($file_md5 != $this->getMD5($idx) || $force) {
885
886             $this->_debug(" ". $resolution ."px");
887             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
888                $error = 1;
889
890          }
891       }
892
893       /* set the new/changed MD5 sum for the current photo */
894       if(!$error) {
895          $this->setMD5($idx, $file_md5);
896       }
897
898       $this->_debug("\n");
899
900    } // gen_thumb()
901
902    public function getMD5($idx)
903    {
904       $result = $this->cfg_db->db_query("
905          SELECT img_md5 
906          FROM images
907          WHERE img_idx='". $idx ."'
908       ");
909
910       if(!$result)
911          return 0;
912
913       $img = $this->cfg_db->db_fetch_object($result);
914       return $img['img_md5'];
915       
916    } // getMD5()
917
918    private function setMD5($idx, $md5)
919    {
920       $result = $this->cfg_db->db_exec("
921          REPLACE INTO images (img_idx, img_md5)
922          VALUES ('". $idx ."', '". $md5 ."')
923       ");
924
925    } // setMD5()
926
927    public function setTagCondition($mode)
928    {
929       $_SESSION['tag_condition'] = $mode;
930
931    } // setTagCondition()
932
933    public function startTagSearch($searchfor)
934    {
935       $_SESSION['searchfor'] = $searchfor;
936       $_SESSION['selected_tags'] = Array();
937
938       foreach($this->avail_tags as $tag) {
939          if(preg_match('/'. $searchfor .'/i', $this->tags[$tag]))
940             array_push($_SESSION['selected_tags'], $tag);
941       }
942
943       $this->resetDateSearch();
944
945    } // startTagSearch()
946
947    public function startDateSearch($from, $to)
948    {
949       $_SESSION['from_date'] = $from;
950       $_SESSION['to_date'] = $to;
951    }
952
953    private function rotateImage($img, $degrees)
954    {
955       if(function_exists("imagerotate"))
956          $img = imagerotate($img, $degrees, 0);
957       else
958       {
959          function imagerotate($src_img, $angle)
960          {
961             $src_x = imagesx($src_img);
962             $src_y = imagesy($src_img);
963             if ($angle == 180) {
964                $dest_x = $src_x;
965                $dest_y = $src_y;
966             }
967             elseif ($src_x <= $src_y) {
968                $dest_x = $src_y;
969                $dest_y = $src_x;
970             }
971             elseif ($src_x >= $src_y) {
972                $dest_x = $src_y;
973                $dest_y = $src_x;
974             }
975                
976             $rotate=imagecreatetruecolor($dest_x,$dest_y);
977             imagealphablending($rotate, false);
978                
979             switch ($angle) {
980             
981                case 90:
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 - $y - 1, $x, $color);
986                      }
987                   }
988                   break;
989
990                case 270:
991                   for ($y = 0; $y < ($src_y); $y++) {
992                      for ($x = 0; $x < ($src_x); $x++) {
993                         $color = imagecolorat($src_img, $x, $y);
994                         imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
995                      }
996                   }
997                   break;
998
999                case 180:
1000                   for ($y = 0; $y < ($src_y); $y++) {
1001                      for ($x = 0; $x < ($src_x); $x++) {
1002                         $color = imagecolorat($src_img, $x, $y);
1003                         imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
1004                      }
1005                   }
1006                   break;
1007
1008                default: $rotate = $src_img;
1009             };
1010
1011             return $rotate;
1012
1013          }
1014
1015          $img = imagerotate($img, $degrees);
1016
1017       }
1018
1019       return $img;
1020
1021    } // rotateImage()
1022
1023    private function get_photo_tags($idx)
1024    {
1025       $result = $this->db->db_query("
1026          SELECT t.id, t.name
1027          FROM tags t
1028          INNER JOIN photo_tags pt
1029             ON t.id=pt.tag_id
1030          WHERE pt.photo_id='". $idx ."'
1031       ");
1032
1033       $tags = Array();
1034
1035       while($row = $this->db->db_fetch_object($result))
1036          $tags[$row['id']] = $row['name'];
1037
1038       return $tags;
1039
1040    } // get_photo_tags()
1041
1042    public function showTextImage($txt, $color=000000, $space=4, $font=4, $w=300)
1043    {
1044       if (strlen($color) != 6) 
1045          $color = 000000;
1046
1047       $int = hexdec($color);
1048       $h = imagefontheight($font);
1049       $fw = imagefontwidth($font);
1050       $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
1051       $lines = count($txt);
1052       $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
1053       $bg = imagecolorallocate($im, 255, 255, 255);
1054       $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
1055       $y = 0;
1056
1057       foreach ($txt as $text) {
1058          $x = (($w - ($fw * strlen($text))) / 2);
1059          imagestring($im, $font, $x, $y, $text, $color);
1060          $y += ($h + $space);
1061       }
1062
1063       Header("Content-type: image/png");
1064       ImagePng($im);
1065
1066    } // showTextImage()
1067
1068    private function checkRequirements()
1069    {
1070       if(!function_exists("imagecreatefromjpeg")) {
1071          print "PHP GD library extension is missing<br />\n";
1072          $missing = true;
1073       }
1074
1075       if(!function_exists("sqlite3_open")) {
1076          print "PHP SQLite3 library extension is missing<br />\n";
1077          $missing = true;
1078       }
1079
1080       /* Check for HTML_AJAX PEAR package, lent from Horde project */
1081       ini_set('track_errors', 1);
1082       @include_once 'HTML/AJAX/Server.php';
1083       if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1084          print "PEAR HTML_AJAX package is missing<br />\n";
1085          $missing = true;
1086       }
1087       @include_once 'Calendar/Calendar.php';
1088       if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1089          print "PEAR Calendar package is missing<br />\n";
1090          $missing = true;
1091       }
1092       ini_restore('track_errors');
1093
1094       if(isset($missing))
1095          return false;
1096
1097       return true;
1098
1099    } // checkRequirements()
1100
1101    private function _debug($text)
1102    {
1103       if($this->fromcmd) {
1104          print $text;
1105       }
1106
1107    } // _debug()
1108
1109    public function checkifImageSupported($mime)
1110    {
1111       if(in_array($mime, Array("image/jpeg")))
1112          return true;
1113
1114       return false;
1115
1116    } // checkifImageSupported()
1117
1118    public function _warning($text)
1119    {
1120       print "<img src=\"resources/green_info.png\" alt=\"warning\" />\n";
1121       print $text;
1122
1123    } // _warning()
1124
1125    private function get_calendar($mode)
1126    {
1127       $output = "<input type=\"text\" size=\"3\" id=\"". $mode ."year\" value=\"". date("Y") ."\" />\n";
1128       $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."month\" value=\"". date("m") ."\" />\n";
1129       $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."day\" value=\"". date("d") ."\" />\n";
1130       return $output;
1131
1132    } // get_calendar()
1133
1134    public function get_calendar_matrix($year = 0, $month = 0, $day = 0)
1135    {
1136       if (!isset($year)) $year = date('Y');
1137       if (!isset($month)) $month = date('m');
1138       if (!isset($day)) $day = date('d');
1139       $rows = 1;
1140       $cols = 1;
1141       $matrix = Array();
1142
1143       require_once CALENDAR_ROOT.'Month/Weekdays.php';
1144       require_once CALENDAR_ROOT.'Day.php';
1145
1146
1147       // Build the month
1148       $month = new Calendar_Month_Weekdays($year,$month);
1149
1150       // Create links
1151       $prevStamp = $month->prevMonth(true);
1152       $prev = "javascript:setMonth(". date('Y',$prevStamp) .", ". date('n',$prevStamp) .", ". date('j',$prevStamp) .");";
1153       $nextStamp = $month->nextMonth(true);
1154       $next = "javascript:setMonth(". date('Y',$nextStamp) .", ". date('n',$nextStamp) .", ". date('j',$nextStamp) .");";
1155
1156       $selectedDays = array (
1157          new Calendar_Day($year,$month,$day),
1158          new Calendar_Day($year,12,25),
1159       );
1160
1161       // Build the days in the month
1162       $month->build($selectedDays);
1163
1164       $this->tmpl->assign('current_month', date('F Y',$month->getTimeStamp()));
1165       $this->tmpl->assign('prev_month', $prev);
1166       $this->tmpl->assign('next_month', $next);
1167
1168       while ( $day = $month->fetch() ) {
1169    
1170          if(!isset($matrix[$rows]))
1171             $matrix[$rows] = Array();
1172
1173          $string = "";
1174
1175          $dayStamp = $day->thisDay(true);
1176          $link = "javascript:setCalendarDate(". date('Y',$dayStamp) .", ". date('n',$dayStamp).", ". date('j',$dayStamp) .");";
1177
1178          // isFirst() to find start of week
1179          if ( $day->isFirst() )
1180             $string.= "<tr>\n";
1181
1182          if ( $day->isSelected() ) {
1183             $string.= "<td class=\"selected\">".$day->thisDay()."</td>\n";
1184          } else if ( $day->isEmpty() ) {
1185             $string.= "<td>&nbsp;</td>\n";
1186          } else {
1187             $string.= "<td><a class=\"calendar\" href=\"".$link."\">".$day->thisDay()."</a></td>\n";
1188          }
1189
1190          // isLast() to find end of week
1191          if ( $day->isLast() )
1192             $string.= "</tr>\n";
1193
1194          $matrix[$rows][$cols] = $string;
1195
1196          $cols++;
1197
1198          if($cols > 7) {
1199             $cols = 1;
1200             $rows++;
1201          }
1202       }
1203
1204       $this->tmpl->assign('matrix', $matrix);
1205       $this->tmpl->assign('rows', $rows);
1206       $this->tmpl->show("calendar.tpl");
1207
1208    } // get_calendar_matrix()
1209
1210    public function getExport($mode)
1211    {
1212       $pictures = $this->getPhotoSelection();
1213       $current_tags = $this->getCurrentTags();  
1214
1215       if(!isset($_SERVER['HTTPS'])) $protocol = "http";
1216       else $protocol = "https";
1217
1218       $server_name = $_SERVER['SERVER_NAME'];
1219
1220       foreach($pictures as $picture) {
1221
1222          $orig_url = $protocol ."://". $server_name . $this->cfg->web_path ."index.php?mode=showp&id=". $picture;
1223          if($current_tags != "") {
1224             $orig_url.= "&tags=". $current_tags;
1225          } 
1226
1227          $thumb_url = $protocol ."://". $server_name . $this->cfg->web_path ."phpfspot_img.php?idx=". $picture ."&width=". $this->cfg->thumb_width;
1228
1229          switch($mode) {
1230
1231             case 'HTML':
1232                // <a href="%pictureurl%"><img src="%thumbnailurl%" ></a>
1233                print htmlspecialchars("<a href=\"". $orig_url ."\"><img src=\"". $thumb_url ."\" /></a>") ."<br />\n";
1234                break;
1235                
1236             case 'MoinMoin':
1237                // [%pictureurl% %thumbnailurl%]
1238                print htmlspecialchars(" * [".$orig_url." ".$thumb_url."&fake=1.jpg]") ."<br />\n";
1239                break;
1240          }
1241
1242       }
1243
1244    } // getExport()
1245
1246    private function getCurrentTags()
1247    {
1248       $current_tags = "";
1249       if($_SESSION['selected_tags'] != "") {
1250          foreach($_SESSION['selected_tags'] as $tag)
1251             $current_tags.= $tag .",";
1252          $current_tags = substr($current_tags, 0, strlen($current_tags)-1);
1253       }
1254       return $current_tags;
1255
1256    } // getCurrentTags()
1257
1258    public function getCurrentPhoto()
1259    {
1260       if(isset($_SESSION['current_photo'])) {
1261          print $_SESSION['current_photo'];
1262       }
1263    } // getCurrentPhoto()
1264
1265 }
1266
1267 ?>