issue26, new icon
[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       if(isset($_SESSION['begin_with']) && $_SESSION['begin_with'] != "")
403          $anchor = $_SESSION['begin_with'];
404
405       if(!isset($this->cfg->rows_per_page) || $this->cfg->rows_per_page == 0) {
406
407          $begin_with = 0;
408          $end_with = $count;
409
410       }
411       elseif($this->cfg->rows_per_page > 0) {
412
413          if(!$_SESSION['begin_with'] || $_SESSION['begin_with'] == 0)
414             $begin_with = 0;
415          else {
416
417             $begin_with = $_SESSION['begin_with'];
418
419             // verify $begin_with - perhaps the thumbs-per-rows or
420             // rows-per-page variables have changed or the jump back
421             // from a photo wasn't exact - so calculate the real new
422             // starting point
423             $multiplicator = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
424             for($i = 0; $i <= $count; $i+=$multiplicator) {
425                if($begin_with >= $i && $begin_with < $i+$multiplicator) {
426                   $begin_with = $i;
427                   break;
428                }
429             }
430          }
431
432          $end_with = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
433       }
434
435    
436       $rows = 0;
437       $cols = 0;
438       $images[$rows] = Array();
439       $img_height[$rows] = Array();
440       $img_width[$rows] = Array();
441       $img_id[$rows] = Array();
442
443       for($i = $begin_with; $i < $end_with; $i++) {
444
445          $images[$rows][$cols] = $photos[$i];
446          $img_id[$rows][$cols] = $i;
447
448          $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->thumb_width ."_". $this->getMD5($photos[$i]);
449
450          if(file_exists($thumb_path)) {
451             $info = getimagesize($thumb_path); 
452             $img_width[$rows][$cols] = $info[0];
453             $img_height[$rows][$cols] = $info[1];
454          }
455
456          if($cols == $this->cfg->thumbs_per_row-1) {
457             $cols = 0;
458             $rows++;
459             $images[$rows] = Array();
460             $img_width[$rows] = Array();
461             $img_height[$rows] = Array();
462          }
463          else {
464             $cols++;
465          }
466       } 
467
468       // +1 for for smarty's selection iteration
469       $rows++;
470
471       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
472          $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
473
474       if($this->cfg->rows_per_page != 0) {
475       
476          /* calculate the page switchers */
477          $previous_start = $begin_with - ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
478          $next_start = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
479
480          if($begin_with != 0) 
481             $this->tmpl->assign("previous_url", "javascript:showPhotoIndex(". $previous_start .");"); 
482          if($end_with < $count)
483             $this->tmpl->assign("next_url", "javascript:showPhotoIndex(". $next_start .");"); 
484
485          /* page selector */
486          $photo_per_page  = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
487
488          /* until 6 pages we show the selector from 1-6
489             everything large will be
490             1 ... 2 3 4 (5) 6 7 ... 9
491          */ 
492          $last_page = ceil($count / $photo_per_page);
493
494          if($begin_with == 0) {
495             $current_page = 1;
496          } 
497          else {
498             $current_page = 0;
499             for($i = $begin_with; $i >= 0; $i-=$photo_per_page) {
500                $current_page++;
501             }
502          } 
503
504          for($i = 1; $i <= $last_page; $i++) {
505
506             if($current_page == $i)
507                $style = "style=\"font-size: 125%;\"";
508             elseif($current_page-1 == $i || $current_page+1 == $i)
509                $style = "style=\"font-size: 105%;\"";
510             elseif(($current_page-5 >= $i) && ($i != 1) ||
511                ($current_page+5 <= $i) && ($i != $last_page))
512                $style = "style=\"font-size: 75%;\"";
513             else
514                $style = "";
515
516             $page_select.= "<a href=\"javascript:showPhotoIndex(". (($i*$photo_per_page)-$photo_per_page) .");\"";
517             if($style != "")
518                $page_select.= $style;
519             $page_select.= ">". $i ."</a>&nbsp;";
520
521          }
522
523          /* only show the page selector if we have more then one page */
524          if($last_page > 1)
525             $this->tmpl->assign('page_selector', $page_select);
526       }
527
528       $current_tags = "";
529       if($_SESSION['selected_tags'] != "") {
530          foreach($_SESSION['selected_tags'] as $tag)
531             $current_tags.= $tag .",";
532          $current_tags = substr($current_tags, 0, strlen($current_tags)-1);
533       }
534
535       $extern_link = "http://". $_SERVER['SERVER_NAME'] ."/index.php?mode=showpi&tags=". $current_tags;
536
537       $this->tmpl->assign('extern_link', $extern_link);
538       $this->tmpl->assign('count', $count);
539       $this->tmpl->assign('width', $this->cfg->thumb_width);
540       $this->tmpl->assign('images', $images);
541       $this->tmpl->assign('img_width', $img_width);
542       $this->tmpl->assign('img_height', $img_height);
543       $this->tmpl->assign('img_id', $img_id);
544       $this->tmpl->assign('rows', $rows);
545       $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
546
547       $this->tmpl->show("photo_index.tpl");
548
549       if(isset($anchor))
550          print "<script language=\"JavaScript\">self.location.hash = '#image". $anchor ."';</script>\n";
551
552    } // showPhotoIndex()
553
554    public function showBubbleDetails($photo, $direction)
555    {
556       if($direction == "up")
557          $direction = "bubbleimg_up";
558       else
559          $direction = "bubbleimg_down";
560
561       $details = $this->get_photo_details($photo);
562       $orig_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
563
564       $image_url = "phpfspot_img.php?idx=". $photo ."&amp;width=". $this->cfg->bubble_width;
565
566       $filesize = filesize($orig_path);
567       $filesize = rand($filesize/1024, 2);
568
569       if(!file_exists($orig_path)) {
570          $this->_warning("Photo ". $orig_path ." does not exist!<br />\n");
571          return;
572       }
573       
574       if(!is_readable($orig_path)) {
575          $this->_warning("Photo ". $orig_path ." is not readable for user ". get_current_user() ."<br />\n");
576          return;
577       }
578
579       $img = getimagesize($orig_path);
580
581       $this->tmpl->assign('file_size', $filesize);
582       $this->tmpl->assign('width', $img[0]);
583       $this->tmpl->assign('height', $img[1]);
584       $this->tmpl->assign('file_name', $details['name']);
585       $this->tmpl->assign('image_id', $direction);
586       $this->tmpl->assign('image_url', $image_url);
587       $this->tmpl->show("bubble_details.tpl");
588
589    } // showBubbleDetails()
590
591    public function showCredits()
592    {
593       $this->tmpl->assign('version', $this->cfg->version);
594       $this->tmpl->assign('product', $this->cfg->product);
595       $this->tmpl->show("credits.tpl");
596
597    } // showCredits()
598
599    public function create_thumbnail($orig_image, $thumb_image, $width)
600    {  
601       if(!file_exists($orig_image))
602          return false;
603
604       $details = getimagesize($orig_image);
605       
606       /* check if original photo is a support image type */
607       if(!$this->checkifImageSupported($details['mime']))
608          return false;
609
610       $meta = $this->get_meta_informations($orig_image);
611
612       $rotate = 0;
613       $flip = false;
614
615       switch($meta['Orientation']) {
616
617          case 1:
618             $rotate = 0; $flip = false; break;
619          case 2:
620             $rotate = 0; $flip = true; break;
621          case 3:
622             $rotate = 180; $flip = false; break;
623          case 4:
624             $rotate = 180; $flip = true; break;
625          case 5:
626             $rotate = 90; $flip = true; break;
627          case 6:
628             $rotate = 90; $flip = false; break;
629          case 7:
630             $rotate = 270; $flip = true; break;
631          case 8:
632             $rotate = 270; $flip = false; break;
633       }
634
635       $src_img = @imagecreatefromjpeg($orig_image);
636
637       if(!$src_img) {
638          print "Can't load image from ". $orig_image ."\n";
639          return false;
640       }
641
642       /* grabs the height and width */
643       $cur_width = imagesx($src_img);
644       $cur_height = imagesy($src_img);
645
646       // If requested width is more then the actual image width,
647       // do not generate a thumbnail
648
649       if($width >= $cur_width) {
650          imagedestroy($src_img);
651          return true;
652       }
653
654       /* calculates aspect ratio */
655       $aspect_ratio = $cur_height / $cur_width;
656
657       /* sets new size */
658       if($aspect_ratio < 1) {
659          $new_w = $width;
660          $new_h = abs($new_w * $aspect_ratio);
661       } else {
662          /* 'virtually' rotate the image and calculate it's ratio */
663          $tmp_w = $cur_height;
664          $tmp_h = $cur_width;
665          /* now get the ratio from the 'rotated' image */
666          $tmp_ratio = $tmp_h/$tmp_w;
667          /* now calculate the new dimensions */
668          $tmp_w = $width;
669          $tmp_h = abs($tmp_w * $tmp_ratio);
670
671          // now that we know, how high they photo should be, if it
672          // gets rotated, use this high to scale the image
673          $new_h = $tmp_h;
674          $new_w = abs($new_h / $aspect_ratio);
675       }
676
677       /* creates new image of that size */
678       $dst_img = imagecreatetruecolor($new_w, $new_h);
679
680       imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
681
682       /* copies resized portion of original image into new image */
683       imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
684
685       /* needs the image to be flipped horizontal? */
686       if($flip) {
687          print "(FLIP)";
688          $image = $dst_img;
689          for($x = 0; $x < $new_w; $x++) {
690             imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
691          }
692       }
693
694       if($rotate) {
695          $this->_debug("(ROTATE)");
696          $dst_img = $this->rotateImage($dst_img, $rotate);
697       }
698
699       /* write down new generated file */
700       $result = imagejpeg($dst_img, $thumb_image, 75);
701
702       /* free your mind */
703       imagedestroy($dst_img);
704       imagedestroy($src_img);
705
706       if($result === false) {
707          print "Can't write thumbnail ". $thumb_image ."\n";
708          return false;
709       }
710
711       return true;
712
713    } // create_thumbnail()
714
715    public function get_meta_informations($file)
716    {
717       return exif_read_data($file);
718
719    } // get_meta_informations()
720
721    public function check_config_table()
722    {
723       // if the config table doesn't exist yet, create it
724       if(!$this->cfg_db->db_check_table_exists("images")) {
725          $this->cfg_db->db_exec("
726             CREATE TABLE images (
727                img_idx int primary key,
728                img_md5 varchar(32)
729             )
730             ");
731       }
732
733    } // check_config_table
734
735    /**
736     * Generates a thumbnail from photo idx
737     *
738     * This function will generate JPEG thumbnails from provided F-Spot photo
739     * indizes.
740     *
741     * 1. Check if all thumbnail generations (width) are already in place and
742     *    readable
743     * 2. Check if the md5sum of the original file has changed
744     * 3. Generate the thumbnails if needed
745     */
746    public function gen_thumb($idx = 0, $force = 0)
747    {
748       $error = 0;
749
750       $resolutions = Array(
751          $this->cfg->thumb_width,
752          $this->cfg->bubble_width,
753          $this->cfg->photo_width,
754       );
755
756       /* get details from F-Spot's database */
757       $details = $this->get_photo_details($idx);
758
759       /* calculate file MD5 sum */
760       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
761
762       if(!file_exists($full_path)) {
763          $this->_warning("File ". $full_path ." does not exist\n");
764          return;
765       }
766
767       if(!is_readable($full_path)) {
768          $this->_warning("File ". $full_path ." is not readable for ". get_current_user() ."\n");
769          return;
770       }
771
772       $file_md5 = md5_file($full_path);
773
774       $this->_debug("Image [". $idx ."] ". $details['name'] ." Thumbnails:");
775
776       foreach($resolutions as $resolution) {
777
778          $thumb_path = $this->cfg->base_path ."/thumbs/". $resolution ."_". $file_md5;
779
780          /* if the thumbnail file doesn't exist, create it */
781          if(!file_exists($thumb_path)) {
782
783             $this->_debug(" ". $resolution ."px");
784             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
785                $error = 1;
786          }
787
788          /* if the file hasn't changed there is no need to regen the thumb */
789          elseif($file_md5 != $this->getMD5($idx) || $force) {
790
791             $this->_debug(" ". $resolution ."px");
792             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
793                $error = 1;
794
795          }
796       }
797
798       /* set the new/changed MD5 sum for the current photo */
799       if(!$error) {
800          $this->setMD5($idx, $file_md5);
801       }
802
803       $this->_debug("\n");
804
805    } // gen_thumb()
806
807    public function getMD5($idx)
808    {
809       $result = $this->cfg_db->db_query("
810          SELECT img_md5 
811          FROM images
812          WHERE img_idx='". $idx ."'
813       ");
814
815       if(!$result)
816          return 0;
817
818       $img = $this->cfg_db->db_fetch_object($result);
819       return $img['img_md5'];
820       
821    } // getMD5()
822
823    private function setMD5($idx, $md5)
824    {
825       $result = $this->cfg_db->db_exec("
826          REPLACE INTO images (img_idx, img_md5)
827          VALUES ('". $idx ."', '". $md5 ."')
828       ");
829
830    } // setMD5()
831
832    public function setTagCondition($mode)
833    {
834       $_SESSION['tag_condition'] = $mode;
835
836    } // setTagCondition()
837
838    public function startTagSearch($searchfor)
839    {
840       $_SESSION['searchfor'] = $searchfor;
841       $_SESSION['selected_tags'] = Array();
842
843       foreach($this->avail_tags as $tag) {
844          if(preg_match('/'. $searchfor .'/i', $this->tags[$tag]))
845             array_push($_SESSION['selected_tags'], $tag);
846       }
847
848    } // startTagSearch()
849
850    private function rotateImage($img, $degrees)
851    {
852       if(function_exists("imagerotate"))
853          $img = imagerotate($img, $degrees, 0);
854       else
855       {
856          function imagerotate($src_img, $angle)
857          {
858             $src_x = imagesx($src_img);
859             $src_y = imagesy($src_img);
860             if ($angle == 180) {
861                $dest_x = $src_x;
862                $dest_y = $src_y;
863             }
864             elseif ($src_x <= $src_y) {
865                $dest_x = $src_y;
866                $dest_y = $src_x;
867             }
868             elseif ($src_x >= $src_y) {
869                $dest_x = $src_y;
870                $dest_y = $src_x;
871             }
872                
873             $rotate=imagecreatetruecolor($dest_x,$dest_y);
874             imagealphablending($rotate, false);
875                
876             switch ($angle) {
877             
878                case 90:
879                   for ($y = 0; $y < ($src_y); $y++) {
880                      for ($x = 0; $x < ($src_x); $x++) {
881                         $color = imagecolorat($src_img, $x, $y);
882                         imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
883                      }
884                   }
885                   break;
886
887                case 270:
888                   for ($y = 0; $y < ($src_y); $y++) {
889                      for ($x = 0; $x < ($src_x); $x++) {
890                         $color = imagecolorat($src_img, $x, $y);
891                         imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
892                      }
893                   }
894                   break;
895
896                case 180:
897                   for ($y = 0; $y < ($src_y); $y++) {
898                      for ($x = 0; $x < ($src_x); $x++) {
899                         $color = imagecolorat($src_img, $x, $y);
900                         imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
901                      }
902                   }
903                   break;
904
905                default: $rotate = $src_img;
906             };
907
908             return $rotate;
909
910          }
911
912          $img = imagerotate($img, $degrees);
913
914       }
915
916       return $img;
917
918    } // rotateImage()
919
920    private function get_photo_tags($idx)
921    {
922       $result = $this->db->db_query("
923          SELECT t.id, t.name
924          FROM tags t
925          INNER JOIN photo_tags pt
926             ON t.id=pt.tag_id
927          WHERE pt.photo_id='". $idx ."'
928       ");
929
930       $tags = Array();
931
932       while($row = $this->db->db_fetch_object($result))
933          $tags[$row['id']] = $row['name'];
934
935       return $tags;
936
937    } // get_photo_tags()
938
939    public function showTextImage($txt, $color=000000, $space=4, $font=4, $w=300)
940    {
941       if (strlen($color) != 6) 
942          $color = 000000;
943
944       $int = hexdec($color);
945       $h = imagefontheight($font);
946       $fw = imagefontwidth($font);
947       $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
948       $lines = count($txt);
949       $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
950       $bg = imagecolorallocate($im, 255, 255, 255);
951       $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
952       $y = 0;
953
954       foreach ($txt as $text) {
955          $x = (($w - ($fw * strlen($text))) / 2);
956          imagestring($im, $font, $x, $y, $text, $color);
957          $y += ($h + $space);
958       }
959
960       Header("Content-type: image/png");
961       ImagePng($im);
962
963    } // showTextImage()
964
965    private function checkRequirements()
966    {
967       if(!function_exists("imagecreatefromjpeg")) {
968          print "PHP GD library extension is missing<br />\n";
969          $missing = true;
970       }
971
972       if(!function_exists("sqlite3_open")) {
973          print "PHP SQLite3 library extension is missing<br />\n";
974          $missing = true;
975       }
976
977       /* Check for HTML_AJAX PEAR package, lent from Horde project */
978       ini_set('track_errors', 1);
979       @include_once 'HTML/AJAX/Server.php';
980       if(isset($php_errormsg)) {
981          print "PEAR HTML_AJAX package is missing<br />\n";
982          $missing = true;
983       }
984       ini_restore('track_errors');
985
986       if(isset($missing))
987          return false;
988
989       return true;
990
991    } // checkRequirements()
992
993    private function _debug($text)
994    {
995       if($this->fromcmd) {
996          print $text;
997       }
998
999    } // _debug()
1000
1001    public function checkifImageSupported($mime)
1002    {
1003       if(in_array($mime, Array("image/jpeg")))
1004          return true;
1005
1006       return false;
1007
1008    } // checkifImageSupported()
1009
1010    public function _warning($text)
1011    {
1012       print "<img src=\"resources/green_info.png\" alt=\"warning\" />\n";
1013       print $text;
1014
1015    } // _warning()
1016
1017 }
1018
1019 ?>