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