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