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