5e25f21b81d446d3c1097b630a44b40ba7ae978c
[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 showBubbleDetails($photo, $direction)
639    {
640       if($direction == "up")
641          $direction = "bubbleimg_up";
642       else
643          $direction = "bubbleimg_down";
644
645       $details = $this->get_photo_details($photo);
646       $orig_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
647
648       $image_url = "phpfspot_img.php?idx=". $photo ."&amp;width=". $this->cfg->bubble_width;
649
650       $filesize = filesize($orig_path);
651       $filesize = rand($filesize/1024, 2);
652
653       if(!file_exists($orig_path)) {
654          $this->_warning("Photo ". $orig_path ." does not exist!<br />\n");
655          return;
656       }
657       
658       if(!is_readable($orig_path)) {
659          $this->_warning("Photo ". $orig_path ." is not readable for user ". get_current_user() ."<br />\n");
660          return;
661       }
662
663       $img = getimagesize($orig_path);
664
665       $this->tmpl->assign('file_size', $filesize);
666       $this->tmpl->assign('width', $img[0]);
667       $this->tmpl->assign('height', $img[1]);
668       $this->tmpl->assign('file_name', $details['name']);
669       $this->tmpl->assign('image_id', $direction);
670       $this->tmpl->assign('image_url', $image_url);
671       $this->tmpl->show("bubble_details.tpl");
672
673    } // showBubbleDetails()
674
675    public function showCredits()
676    {
677       $this->tmpl->assign('version', $this->cfg->version);
678       $this->tmpl->assign('product', $this->cfg->product);
679       $this->tmpl->show("credits.tpl");
680
681    } // showCredits()
682
683    public function create_thumbnail($orig_image, $thumb_image, $width)
684    {  
685       if(!file_exists($orig_image))
686          return false;
687
688       $details = getimagesize($orig_image);
689       
690       /* check if original photo is a support image type */
691       if(!$this->checkifImageSupported($details['mime']))
692          return false;
693
694       $meta = $this->get_meta_informations($orig_image);
695
696       $rotate = 0;
697       $flip = false;
698
699       switch($meta['Orientation']) {
700
701          case 1: /* top, left */
702             $rotate = 0; $flip = false; break;
703          case 2: /* top, right */
704             $rotate = 0; $flip = true; break;
705          case 3: /* bottom, left */
706             $rotate = 180; $flip = false; break;
707          case 4: /* bottom, right */
708             $rotate = 180; $flip = true; break;
709          case 5: /* left side, top */
710             $rotate = 90; $flip = true; break;
711          case 6: /* right side, top */
712             $rotate = 90; $flip = false; break;
713          case 7: /* left side, bottom */
714             $rotate = 270; $flip = true; break;
715          case 8: /* right side, bottom */
716             $rotate = 270; $flip = false; break;
717       }
718
719       $src_img = @imagecreatefromjpeg($orig_image);
720
721       if(!$src_img) {
722          print "Can't load image from ". $orig_image ."\n";
723          return false;
724       }
725
726       /* grabs the height and width */
727       $cur_width = imagesx($src_img);
728       $cur_height = imagesy($src_img);
729
730       // If requested width is more then the actual image width,
731       // do not generate a thumbnail
732
733       if($width >= $cur_width) {
734          imagedestroy($src_img);
735          return true;
736       }
737
738       // If the image will be rotate because EXIF orientation said so
739       // 'virtually rotate' the image for further calculations
740       if($rotate == 90 || $rotate == 270) {
741          $tmp = $cur_width;
742          $cur_width = $cur_height;
743          $cur_height = $tmp;
744       }
745
746       /* calculates aspect ratio */
747       $aspect_ratio = $cur_height / $cur_width;
748
749       /* sets new size */
750       if($aspect_ratio < 1) {
751          $new_w = $width;
752          $new_h = abs($new_w * $aspect_ratio);
753       } else {
754          /* 'virtually' rotate the image and calculate it's ratio */
755          $tmp_w = $cur_height;
756          $tmp_h = $cur_width;
757          /* now get the ratio from the 'rotated' image */
758          $tmp_ratio = $tmp_h/$tmp_w;
759          /* now calculate the new dimensions */
760          $tmp_w = $width;
761          $tmp_h = abs($tmp_w * $tmp_ratio);
762
763          // now that we know, how high they photo should be, if it
764          // gets rotated, use this high to scale the image
765          $new_h = $tmp_h;
766          $new_w = abs($new_h / $aspect_ratio);
767
768          // If the image will be rotate because EXIF orientation said so
769          // now 'virtually rotate' back the image for the image manipulation
770          if($rotate == 90 || $rotate == 270) {
771             $tmp = $new_w;
772             $new_w = $new_h;
773             $new_h = $tmp;
774          }
775       }
776
777       /* creates new image of that size */
778       $dst_img = imagecreatetruecolor($new_w, $new_h);
779
780       imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
781
782       /* copies resized portion of original image into new image */
783       imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, imagesx($src_img), imagesy($src_img));
784
785       /* needs the image to be flipped horizontal? */
786       if($flip) {
787          print "(FLIP)";
788          $image = $dst_img;
789          for($x = 0; $x < $new_w; $x++) {
790             imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
791          }
792       }
793
794       if($rotate) {
795          $this->_debug("(ROTATE)");
796          $dst_img = $this->rotateImage($dst_img, $rotate);
797       }
798
799       /* write down new generated file */
800       $result = imagejpeg($dst_img, $thumb_image, 75);
801
802       /* free your mind */
803       imagedestroy($dst_img);
804       imagedestroy($src_img);
805
806       if($result === false) {
807          print "Can't write thumbnail ". $thumb_image ."\n";
808          return false;
809       }
810
811       return true;
812
813    } // create_thumbnail()
814
815    public function get_meta_informations($file)
816    {
817       return exif_read_data($file);
818
819    } // get_meta_informations()
820
821    public function check_config_table()
822    {
823       // if the config table doesn't exist yet, create it
824       if(!$this->cfg_db->db_check_table_exists("images")) {
825          $this->cfg_db->db_exec("
826             CREATE TABLE images (
827                img_idx int primary key,
828                img_md5 varchar(32)
829             )
830             ");
831       }
832
833    } // check_config_table
834
835    /**
836     * Generates a thumbnail from photo idx
837     *
838     * This function will generate JPEG thumbnails from provided F-Spot photo
839     * indizes.
840     *
841     * 1. Check if all thumbnail generations (width) are already in place and
842     *    readable
843     * 2. Check if the md5sum of the original file has changed
844     * 3. Generate the thumbnails if needed
845     */
846    public function gen_thumb($idx = 0, $force = 0)
847    {
848       $error = 0;
849
850       $resolutions = Array(
851          $this->cfg->thumb_width,
852          $this->cfg->bubble_width,
853          $this->cfg->photo_width,
854          $this->cfg->mini_width,
855       );
856
857       /* get details from F-Spot's database */
858       $details = $this->get_photo_details($idx);
859
860       /* calculate file MD5 sum */
861       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
862
863       if(!file_exists($full_path)) {
864          $this->_warning("File ". $full_path ." does not exist\n");
865          return;
866       }
867
868       if(!is_readable($full_path)) {
869          $this->_warning("File ". $full_path ." is not readable for ". get_current_user() ."\n");
870          return;
871       }
872
873       $file_md5 = md5_file($full_path);
874
875       $this->_debug("Image [". $idx ."] ". $details['name'] ." Thumbnails:");
876
877       foreach($resolutions as $resolution) {
878
879          $thumb_path = $this->cfg->base_path ."/thumbs/". $resolution ."_". $file_md5;
880
881          /* if the thumbnail file doesn't exist, create it */
882          if(!file_exists($thumb_path)) {
883
884             $this->_debug(" ". $resolution ."px");
885             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
886                $error = 1;
887          }
888
889          /* if the file hasn't changed there is no need to regen the thumb */
890          elseif($file_md5 != $this->getMD5($idx) || $force) {
891
892             $this->_debug(" ". $resolution ."px");
893             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
894                $error = 1;
895
896          }
897       }
898
899       /* set the new/changed MD5 sum for the current photo */
900       if(!$error) {
901          $this->setMD5($idx, $file_md5);
902       }
903
904       $this->_debug("\n");
905
906    } // gen_thumb()
907
908    public function getMD5($idx)
909    {
910       $result = $this->cfg_db->db_query("
911          SELECT img_md5 
912          FROM images
913          WHERE img_idx='". $idx ."'
914       ");
915
916       if(!$result)
917          return 0;
918
919       $img = $this->cfg_db->db_fetch_object($result);
920       return $img['img_md5'];
921       
922    } // getMD5()
923
924    private function setMD5($idx, $md5)
925    {
926       $result = $this->cfg_db->db_exec("
927          REPLACE INTO images (img_idx, img_md5)
928          VALUES ('". $idx ."', '". $md5 ."')
929       ");
930
931    } // setMD5()
932
933    public function setTagCondition($mode)
934    {
935       $_SESSION['tag_condition'] = $mode;
936
937    } // setTagCondition()
938
939    public function startTagSearch($searchfor)
940    {
941       $_SESSION['searchfor'] = $searchfor;
942       $_SESSION['selected_tags'] = Array();
943
944       foreach($this->avail_tags as $tag) {
945          if(preg_match('/'. $searchfor .'/i', $this->tags[$tag]))
946             array_push($_SESSION['selected_tags'], $tag);
947       }
948
949    } // startTagSearch()
950
951    private function rotateImage($img, $degrees)
952    {
953       if(function_exists("imagerotate"))
954          $img = imagerotate($img, $degrees, 0);
955       else
956       {
957          function imagerotate($src_img, $angle)
958          {
959             $src_x = imagesx($src_img);
960             $src_y = imagesy($src_img);
961             if ($angle == 180) {
962                $dest_x = $src_x;
963                $dest_y = $src_y;
964             }
965             elseif ($src_x <= $src_y) {
966                $dest_x = $src_y;
967                $dest_y = $src_x;
968             }
969             elseif ($src_x >= $src_y) {
970                $dest_x = $src_y;
971                $dest_y = $src_x;
972             }
973                
974             $rotate=imagecreatetruecolor($dest_x,$dest_y);
975             imagealphablending($rotate, false);
976                
977             switch ($angle) {
978             
979                case 90:
980                   for ($y = 0; $y < ($src_y); $y++) {
981                      for ($x = 0; $x < ($src_x); $x++) {
982                         $color = imagecolorat($src_img, $x, $y);
983                         imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
984                      }
985                   }
986                   break;
987
988                case 270:
989                   for ($y = 0; $y < ($src_y); $y++) {
990                      for ($x = 0; $x < ($src_x); $x++) {
991                         $color = imagecolorat($src_img, $x, $y);
992                         imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
993                      }
994                   }
995                   break;
996
997                case 180:
998                   for ($y = 0; $y < ($src_y); $y++) {
999                      for ($x = 0; $x < ($src_x); $x++) {
1000                         $color = imagecolorat($src_img, $x, $y);
1001                         imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
1002                      }
1003                   }
1004                   break;
1005
1006                default: $rotate = $src_img;
1007             };
1008
1009             return $rotate;
1010
1011          }
1012
1013          $img = imagerotate($img, $degrees);
1014
1015       }
1016
1017       return $img;
1018
1019    } // rotateImage()
1020
1021    private function get_photo_tags($idx)
1022    {
1023       $result = $this->db->db_query("
1024          SELECT t.id, t.name
1025          FROM tags t
1026          INNER JOIN photo_tags pt
1027             ON t.id=pt.tag_id
1028          WHERE pt.photo_id='". $idx ."'
1029       ");
1030
1031       $tags = Array();
1032
1033       while($row = $this->db->db_fetch_object($result))
1034          $tags[$row['id']] = $row['name'];
1035
1036       return $tags;
1037
1038    } // get_photo_tags()
1039
1040    public function showTextImage($txt, $color=000000, $space=4, $font=4, $w=300)
1041    {
1042       if (strlen($color) != 6) 
1043          $color = 000000;
1044
1045       $int = hexdec($color);
1046       $h = imagefontheight($font);
1047       $fw = imagefontwidth($font);
1048       $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
1049       $lines = count($txt);
1050       $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
1051       $bg = imagecolorallocate($im, 255, 255, 255);
1052       $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
1053       $y = 0;
1054
1055       foreach ($txt as $text) {
1056          $x = (($w - ($fw * strlen($text))) / 2);
1057          imagestring($im, $font, $x, $y, $text, $color);
1058          $y += ($h + $space);
1059       }
1060
1061       Header("Content-type: image/png");
1062       ImagePng($im);
1063
1064    } // showTextImage()
1065
1066    private function checkRequirements()
1067    {
1068       if(!function_exists("imagecreatefromjpeg")) {
1069          print "PHP GD library extension is missing<br />\n";
1070          $missing = true;
1071       }
1072
1073       if(!function_exists("sqlite3_open")) {
1074          print "PHP SQLite3 library extension is missing<br />\n";
1075          $missing = true;
1076       }
1077
1078       /* Check for HTML_AJAX PEAR package, lent from Horde project */
1079       ini_set('track_errors', 1);
1080       @include_once 'HTML/AJAX/Server.php';
1081       if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1082          print "PEAR HTML_AJAX package is missing<br />\n";
1083          $missing = true;
1084       }
1085       @include_once 'Calendar/Calendar.php';
1086       if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1087          print "PEAR Calendar package is missing<br />\n";
1088          $missing = true;
1089       }
1090       ini_restore('track_errors');
1091
1092       if(isset($missing))
1093          return false;
1094
1095       return true;
1096
1097    } // checkRequirements()
1098
1099    private function _debug($text)
1100    {
1101       if($this->fromcmd) {
1102          print $text;
1103       }
1104
1105    } // _debug()
1106
1107    public function checkifImageSupported($mime)
1108    {
1109       if(in_array($mime, Array("image/jpeg")))
1110          return true;
1111
1112       return false;
1113
1114    } // checkifImageSupported()
1115
1116    public function _warning($text)
1117    {
1118       print "<img src=\"resources/green_info.png\" alt=\"warning\" />\n";
1119       print $text;
1120
1121    } // _warning()
1122
1123    private function get_calendar()
1124    {
1125 //      require_once CALENDAR_ROOT.'Year.php';
1126 //      require_once CALENDAR_ROOT.'Month.php';
1127 //      require_once CALENDAR_ROOT.'Day.php';
1128
1129 //      $Year = new Calendar_Year();
1130 //      $Month = new Calendar_Month();
1131 //      $Day = new Calendar_Day();
1132
1133       $output = "<select name=\"year\">\n";
1134       for($year = 1990; $year <= date("Y"); $year++) {
1135          $output.= "<option value=\"". $year ."\">". $year ."</option>\n";
1136       }
1137       $output.= "</select>\n";
1138
1139       $output.= "<select name=\"month\">\n";
1140       for($month = 1; $month <= 12; $month++) {
1141          $output.= "<option value=\"". $month ."\">". $month ."</option>\n";
1142       }
1143       $output.= "</select>\n";
1144
1145       $output.= "<select name=\"day\">\n";
1146       for($day = 1; $day <= 31; $day++) {
1147          $output.= "<option value=\"". $day ."\">". $day ."</option>\n";
1148       }
1149       $output.= "</select>\n";
1150
1151       return $output;
1152
1153    } // get_calendar()
1154
1155    public function getExport($mode)
1156    {
1157       $pictures = $this->getPhotoSelection();
1158       $current_tags = $this->getCurrentTags();  
1159
1160       if(!isset($_SERVER['HTTPS'])) $protocol = "http";
1161       else $protocol = "https";
1162
1163       $server_name = $_SERVER['SERVER_NAME'];
1164
1165       foreach($pictures as $picture) {
1166
1167          $orig_url = $protocol ."://". $server_name . $this->cfg->web_path ."index.php?mode=showp&id=". $picture;
1168          if($current_tags != "") {
1169             $orig_url.= "&tags=". $current_tags;
1170          } 
1171
1172          $thumb_url = $protocol ."://". $server_name . $this->cfg->web_path ."phpfspot_img.php?idx=". $picture ."&width=". $this->cfg->thumb_width;
1173
1174          switch($mode) {
1175
1176             case 'HTML':
1177                // <a href="%pictureurl%"><img src="%thumbnailurl%" ></a>
1178                print htmlspecialchars("<a href=\"". $orig_url ."\"><img src=\"". $thumb_url ."\" /></a>") ."<br />\n";
1179                break;
1180                
1181             case 'MoinMoin':
1182                // [%pictureurl% %thumbnailurl%]
1183                print htmlspecialchars(" * [".$orig_url." ".$thumb_url."&fake=1.jpg]") ."<br />\n";
1184                break;
1185          }
1186
1187       }
1188
1189    } // getExport()
1190
1191    private function getCurrentTags()
1192    {
1193       $current_tags = "";
1194       if($_SESSION['selected_tags'] != "") {
1195          foreach($_SESSION['selected_tags'] as $tag)
1196             $current_tags.= $tag .",";
1197          $current_tags = substr($current_tags, 0, strlen($current_tags)-1);
1198       }
1199       return $current_tags;
1200
1201    } // getCurrentTags()
1202
1203    public function getCurrentPhoto()
1204    {
1205       if(isset($_SESSION['current_photo'])) {
1206          print $_SESSION['current_photo'];
1207       }
1208    } // getCurrentPhoto()
1209
1210 }
1211
1212 ?>