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