00c84dbd9884e4d074972ea6fd8f5c589b192514
[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
723       $details = getimagesize($orig_image);
724       
725       /* check if original photo is a support image type */
726       if(!$this->checkifImageSupported($details['mime']))
727          return false;
728
729       $meta = $this->get_meta_informations($orig_image);
730
731       $rotate = 0;
732       $flip = false;
733
734       switch($meta['Orientation']) {
735
736          case 1: /* top, left */
737             $rotate = 0; $flip = false; break;
738          case 2: /* top, right */
739             $rotate = 0; $flip = true; break;
740          case 3: /* bottom, left */
741             $rotate = 180; $flip = false; break;
742          case 4: /* bottom, right */
743             $rotate = 180; $flip = true; break;
744          case 5: /* left side, top */
745             $rotate = 90; $flip = true; break;
746          case 6: /* right side, top */
747             $rotate = 90; $flip = false; break;
748          case 7: /* left side, bottom */
749             $rotate = 270; $flip = true; break;
750          case 8: /* right side, bottom */
751             $rotate = 270; $flip = false; break;
752       }
753
754       $src_img = @imagecreatefromjpeg($orig_image);
755
756       if(!$src_img) {
757          print "Can't load image from ". $orig_image ."\n";
758          return false;
759       }
760
761       /* grabs the height and width */
762       $cur_width = imagesx($src_img);
763       $cur_height = imagesy($src_img);
764
765       // If requested width is more then the actual image width,
766       // do not generate a thumbnail, instead safe the original
767       // as thumbnail but with lower quality
768
769       if($width >= $cur_width) {
770          $result = imagejpeg($src_img, $thumb_image, 75);
771          imagedestroy($src_img);
772          return true;
773       }
774
775       // If the image will be rotate because EXIF orientation said so
776       // 'virtually rotate' the image for further calculations
777       if($rotate == 90 || $rotate == 270) {
778          $tmp = $cur_width;
779          $cur_width = $cur_height;
780          $cur_height = $tmp;
781       }
782
783       /* calculates aspect ratio */
784       $aspect_ratio = $cur_height / $cur_width;
785
786       /* sets new size */
787       if($aspect_ratio < 1) {
788          $new_w = $width;
789          $new_h = abs($new_w * $aspect_ratio);
790       } else {
791          /* 'virtually' rotate the image and calculate it's ratio */
792          $tmp_w = $cur_height;
793          $tmp_h = $cur_width;
794          /* now get the ratio from the 'rotated' image */
795          $tmp_ratio = $tmp_h/$tmp_w;
796          /* now calculate the new dimensions */
797          $tmp_w = $width;
798          $tmp_h = abs($tmp_w * $tmp_ratio);
799
800          // now that we know, how high they photo should be, if it
801          // gets rotated, use this high to scale the image
802          $new_h = $tmp_h;
803          $new_w = abs($new_h / $aspect_ratio);
804
805          // If the image will be rotate because EXIF orientation said so
806          // now 'virtually rotate' back the image for the image manipulation
807          if($rotate == 90 || $rotate == 270) {
808             $tmp = $new_w;
809             $new_w = $new_h;
810             $new_h = $tmp;
811          }
812       }
813
814       /* creates new image of that size */
815       $dst_img = imagecreatetruecolor($new_w, $new_h);
816
817       imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
818
819       /* copies resized portion of original image into new image */
820       imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, imagesx($src_img), imagesy($src_img));
821
822       /* needs the image to be flipped horizontal? */
823       if($flip) {
824          print "(FLIP)";
825          $image = $dst_img;
826          for($x = 0; $x < $new_w; $x++) {
827             imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
828          }
829       }
830
831       if($rotate) {
832          $this->_debug("(ROTATE)");
833          $dst_img = $this->rotateImage($dst_img, $rotate);
834       }
835
836       /* write down new generated file */
837       $result = imagejpeg($dst_img, $thumb_image, 75);
838
839       /* free your mind */
840       imagedestroy($dst_img);
841       imagedestroy($src_img);
842
843       if($result === false) {
844          print "Can't write thumbnail ". $thumb_image ."\n";
845          return false;
846       }
847
848       return true;
849
850    } // create_thumbnail()
851
852    public function get_meta_informations($file)
853    {
854       return exif_read_data($file);
855
856    } // get_meta_informations()
857
858    public function check_config_table()
859    {
860       // if the config table doesn't exist yet, create it
861       if(!$this->cfg_db->db_check_table_exists("images")) {
862          $this->cfg_db->db_exec("
863             CREATE TABLE images (
864                img_idx int primary key,
865                img_md5 varchar(32)
866             )
867             ");
868       }
869
870    } // check_config_table
871
872    /**
873     * Generates a thumbnail from photo idx
874     *
875     * This function will generate JPEG thumbnails from provided F-Spot photo
876     * indizes.
877     *
878     * 1. Check if all thumbnail generations (width) are already in place and
879     *    readable
880     * 2. Check if the md5sum of the original file has changed
881     * 3. Generate the thumbnails if needed
882     */
883    public function gen_thumb($idx = 0, $force = 0)
884    {
885       $error = 0;
886
887       $resolutions = Array(
888          $this->cfg->thumb_width,
889          $this->cfg->photo_width,
890          $this->cfg->mini_width,
891       );
892
893       /* get details from F-Spot's database */
894       $details = $this->get_photo_details($idx);
895
896       /* calculate file MD5 sum */
897       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
898
899       if(!file_exists($full_path)) {
900          $this->_warning("File ". $full_path ." does not exist\n");
901          return;
902       }
903
904       if(!is_readable($full_path)) {
905          $this->_warning("File ". $full_path ." is not readable for ". $this->getuid() ."\n");
906          return;
907       }
908
909       $file_md5 = md5_file($full_path);
910
911       $this->_debug("Image [". $idx ."] ". $details['name'] ." Thumbnails:");
912
913       foreach($resolutions as $resolution) {
914
915          $thumb_path = $this->cfg->base_path ."/thumbs/". $resolution ."_". $file_md5;
916
917          /* if the thumbnail file doesn't exist, create it */
918          if(!file_exists($thumb_path)) {
919
920             $this->_debug(" ". $resolution ."px");
921             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
922                $error = 1;
923          }
924          /* if the file hasn't changed there is no need to regen the thumb */
925          elseif($file_md5 != $this->getMD5($idx) || $force) {
926
927             $this->_debug(" ". $resolution ."px");
928             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
929                $error = 1;
930
931          }
932       }
933
934       /* set the new/changed MD5 sum for the current photo */
935       if(!$error) {
936          $this->setMD5($idx, $file_md5);
937       }
938
939       $this->_debug("\n");
940
941    } // gen_thumb()
942
943    public function getMD5($idx)
944    {
945       $result = $this->cfg_db->db_query("
946          SELECT img_md5 
947          FROM images
948          WHERE img_idx='". $idx ."'
949       ");
950
951       if(!$result)
952          return 0;
953
954       $img = $this->cfg_db->db_fetch_object($result);
955       return $img['img_md5'];
956       
957    } // getMD5()
958
959    private function setMD5($idx, $md5)
960    {
961       $result = $this->cfg_db->db_exec("
962          REPLACE INTO images (img_idx, img_md5)
963          VALUES ('". $idx ."', '". $md5 ."')
964       ");
965
966    } // setMD5()
967
968    public function setTagCondition($mode)
969    {
970       $_SESSION['tag_condition'] = $mode;
971
972    } // setTagCondition()
973
974    public function startTagSearch($searchfor)
975    {
976       $_SESSION['searchfor'] = $searchfor;
977       $_SESSION['selected_tags'] = Array();
978
979       foreach($this->avail_tags as $tag) {
980          if(preg_match('/'. $searchfor .'/i', $this->tags[$tag]))
981             array_push($_SESSION['selected_tags'], $tag);
982       }
983
984       $this->resetDateSearch();
985
986    } // startTagSearch()
987
988    public function startDateSearch($from, $to)
989    {
990       $_SESSION['from_date'] = $from;
991       $_SESSION['to_date'] = $to;
992    }
993
994    private function rotateImage($img, $degrees)
995    {
996       if(function_exists("imagerotate"))
997          $img = imagerotate($img, $degrees, 0);
998       else
999       {
1000          function imagerotate($src_img, $angle)
1001          {
1002             $src_x = imagesx($src_img);
1003             $src_y = imagesy($src_img);
1004             if ($angle == 180) {
1005                $dest_x = $src_x;
1006                $dest_y = $src_y;
1007             }
1008             elseif ($src_x <= $src_y) {
1009                $dest_x = $src_y;
1010                $dest_y = $src_x;
1011             }
1012             elseif ($src_x >= $src_y) {
1013                $dest_x = $src_y;
1014                $dest_y = $src_x;
1015             }
1016                
1017             $rotate=imagecreatetruecolor($dest_x,$dest_y);
1018             imagealphablending($rotate, false);
1019                
1020             switch ($angle) {
1021             
1022                case 90:
1023                   for ($y = 0; $y < ($src_y); $y++) {
1024                      for ($x = 0; $x < ($src_x); $x++) {
1025                         $color = imagecolorat($src_img, $x, $y);
1026                         imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
1027                      }
1028                   }
1029                   break;
1030
1031                case 270:
1032                   for ($y = 0; $y < ($src_y); $y++) {
1033                      for ($x = 0; $x < ($src_x); $x++) {
1034                         $color = imagecolorat($src_img, $x, $y);
1035                         imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
1036                      }
1037                   }
1038                   break;
1039
1040                case 180:
1041                   for ($y = 0; $y < ($src_y); $y++) {
1042                      for ($x = 0; $x < ($src_x); $x++) {
1043                         $color = imagecolorat($src_img, $x, $y);
1044                         imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
1045                      }
1046                   }
1047                   break;
1048
1049                default: $rotate = $src_img;
1050             };
1051
1052             return $rotate;
1053
1054          }
1055
1056          $img = imagerotate($img, $degrees);
1057
1058       }
1059
1060       return $img;
1061
1062    } // rotateImage()
1063
1064    private function get_photo_tags($idx)
1065    {
1066       $result = $this->db->db_query("
1067          SELECT t.id, t.name
1068          FROM tags t
1069          INNER JOIN photo_tags pt
1070             ON t.id=pt.tag_id
1071          WHERE pt.photo_id='". $idx ."'
1072       ");
1073
1074       $tags = Array();
1075
1076       while($row = $this->db->db_fetch_object($result))
1077          $tags[$row['id']] = $row['name'];
1078
1079       return $tags;
1080
1081    } // get_photo_tags()
1082
1083    public function showTextImage($txt, $color=000000, $space=4, $font=4, $w=300)
1084    {
1085       if (strlen($color) != 6) 
1086          $color = 000000;
1087
1088       $int = hexdec($color);
1089       $h = imagefontheight($font);
1090       $fw = imagefontwidth($font);
1091       $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
1092       $lines = count($txt);
1093       $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
1094       $bg = imagecolorallocate($im, 255, 255, 255);
1095       $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
1096       $y = 0;
1097
1098       foreach ($txt as $text) {
1099          $x = (($w - ($fw * strlen($text))) / 2);
1100          imagestring($im, $font, $x, $y, $text, $color);
1101          $y += ($h + $space);
1102       }
1103
1104       Header("Content-type: image/png");
1105       ImagePng($im);
1106
1107    } // showTextImage()
1108
1109    private function checkRequirements()
1110    {
1111       if(!function_exists("imagecreatefromjpeg")) {
1112          print "PHP GD library extension is missing<br />\n";
1113          $missing = true;
1114       }
1115
1116       if(!function_exists("sqlite3_open")) {
1117          print "PHP SQLite3 library extension is missing<br />\n";
1118          $missing = true;
1119       }
1120
1121       /* Check for HTML_AJAX PEAR package, lent from Horde project */
1122       ini_set('track_errors', 1);
1123       @include_once 'HTML/AJAX/Server.php';
1124       if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1125          print "PEAR HTML_AJAX package is missing<br />\n";
1126          $missing = true;
1127       }
1128       @include_once 'Calendar/Calendar.php';
1129       if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1130          print "PEAR Calendar package is missing<br />\n";
1131          $missing = true;
1132       }
1133       ini_restore('track_errors');
1134
1135       if(isset($missing))
1136          return false;
1137
1138       return true;
1139
1140    } // checkRequirements()
1141
1142    private function _debug($text)
1143    {
1144       if($this->fromcmd) {
1145          print $text;
1146       }
1147
1148    } // _debug()
1149
1150    public function checkifImageSupported($mime)
1151    {
1152       if(in_array($mime, Array("image/jpeg")))
1153          return true;
1154
1155       return false;
1156
1157    } // checkifImageSupported()
1158
1159    public function _warning($text)
1160    {
1161       print "<img src=\"resources/green_info.png\" alt=\"warning\" />\n";
1162       print $text;
1163
1164    } // _warning()
1165
1166    private function get_calendar($mode)
1167    {
1168       $year = $_SESSION[$mode .'_date'] ? date("Y", strtotime($_SESSION[$mode .'_date'])) : date("Y");
1169       $month = $_SESSION[$mode .'_date'] ? date("m", strtotime($_SESSION[$mode .'_date'])) : date("m");
1170       $day = $_SESSION[$mode .'_date'] ? date("d", strtotime($_SESSION[$mode .'_date'])) : date("d");
1171
1172       $output = "<input type=\"text\" size=\"3\" id=\"". $mode ."year\" value=\"". $year ."\" />\n";
1173       $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."month\" value=\"". $month ."\" />\n";
1174       $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."day\" value=\"". $day ."\" />\n";
1175       return $output;
1176
1177    } // get_calendar()
1178
1179    public function get_calendar_matrix($year = 0, $month = 0, $day = 0)
1180    {
1181       if (!isset($year)) $year = date('Y');
1182       if (!isset($month)) $month = date('m');
1183       if (!isset($day)) $day = date('d');
1184       $rows = 1;
1185       $cols = 1;
1186       $matrix = Array();
1187
1188       require_once CALENDAR_ROOT.'Month/Weekdays.php';
1189       require_once CALENDAR_ROOT.'Day.php';
1190
1191
1192       // Build the month
1193       $month = new Calendar_Month_Weekdays($year,$month);
1194
1195       // Create links
1196       $prevStamp = $month->prevMonth(true);
1197       $prev = "javascript:setMonth(". date('Y',$prevStamp) .", ". date('n',$prevStamp) .", ". date('j',$prevStamp) .");";
1198       $nextStamp = $month->nextMonth(true);
1199       $next = "javascript:setMonth(". date('Y',$nextStamp) .", ". date('n',$nextStamp) .", ". date('j',$nextStamp) .");";
1200
1201       $selectedDays = array (
1202          new Calendar_Day($year,$month,$day),
1203          new Calendar_Day($year,12,25),
1204       );
1205
1206       // Build the days in the month
1207       $month->build($selectedDays);
1208
1209       $this->tmpl->assign('current_month', date('F Y',$month->getTimeStamp()));
1210       $this->tmpl->assign('prev_month', $prev);
1211       $this->tmpl->assign('next_month', $next);
1212
1213       while ( $day = $month->fetch() ) {
1214    
1215          if(!isset($matrix[$rows]))
1216             $matrix[$rows] = Array();
1217
1218          $string = "";
1219
1220          $dayStamp = $day->thisDay(true);
1221          $link = "javascript:setCalendarDate(". date('Y',$dayStamp) .", ". date('n',$dayStamp).", ". date('j',$dayStamp) .");";
1222
1223          // isFirst() to find start of week
1224          if ( $day->isFirst() )
1225             $string.= "<tr>\n";
1226
1227          if ( $day->isSelected() ) {
1228             $string.= "<td class=\"selected\">".$day->thisDay()."</td>\n";
1229          } else if ( $day->isEmpty() ) {
1230             $string.= "<td>&nbsp;</td>\n";
1231          } else {
1232             $string.= "<td><a class=\"calendar\" href=\"".$link."\">".$day->thisDay()."</a></td>\n";
1233          }
1234
1235          // isLast() to find end of week
1236          if ( $day->isLast() )
1237             $string.= "</tr>\n";
1238
1239          $matrix[$rows][$cols] = $string;
1240
1241          $cols++;
1242
1243          if($cols > 7) {
1244             $cols = 1;
1245             $rows++;
1246          }
1247       }
1248
1249       $this->tmpl->assign('matrix', $matrix);
1250       $this->tmpl->assign('rows', $rows);
1251       $this->tmpl->show("calendar.tpl");
1252
1253    } // get_calendar_matrix()
1254
1255    public function getExport($mode)
1256    {
1257       $pictures = $this->getPhotoSelection();
1258       $current_tags = $this->getCurrentTags();  
1259
1260       if(!isset($_SERVER['HTTPS'])) $protocol = "http";
1261       else $protocol = "https";
1262
1263       $server_name = $_SERVER['SERVER_NAME'];
1264
1265       foreach($pictures as $picture) {
1266
1267          $orig_url = $protocol ."://". $server_name . $this->cfg->web_path ."index.php?mode=showp&id=". $picture;
1268          if($current_tags != "") {
1269             $orig_url.= "&tags=". $current_tags;
1270          } 
1271          if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
1272             $orig_url.= "&from_date=". $_SESSION['from_date'] ."&to_date=". $_SESSION['to_date'];
1273          }
1274
1275          $thumb_url = $protocol ."://". $server_name . $this->cfg->web_path ."phpfspot_img.php?idx=". $picture ."&width=". $this->cfg->thumb_width;
1276
1277          switch($mode) {
1278
1279             case 'HTML':
1280                // <a href="%pictureurl%"><img src="%thumbnailurl%" ></a>
1281                print htmlspecialchars("<a href=\"". $orig_url ."\"><img src=\"". $thumb_url ."\" /></a>") ."<br />\n";
1282                break;
1283                
1284             case 'MoinMoin':
1285                // [%pictureurl% %thumbnailurl%]
1286                print htmlspecialchars(" * [".$orig_url." ".$thumb_url."&fake=1.jpg]") ."<br />\n";
1287                break;
1288          }
1289
1290       }
1291
1292    } // getExport()
1293
1294    private function getCurrentTags()
1295    {
1296       $current_tags = "";
1297       if($_SESSION['selected_tags'] != "") {
1298          foreach($_SESSION['selected_tags'] as $tag)
1299             $current_tags.= $tag .",";
1300          $current_tags = substr($current_tags, 0, strlen($current_tags)-1);
1301       }
1302       return $current_tags;
1303
1304    } // getCurrentTags()
1305
1306    public function getCurrentPhoto()
1307    {
1308       if(isset($_SESSION['current_photo'])) {
1309          print $_SESSION['current_photo'];
1310       }
1311    } // getCurrentPhoto()
1312
1313    public function whatToDo()
1314    {
1315       if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
1316          return "showpi_tags";
1317       }
1318       elseif(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
1319          return "showpi_date";
1320       }
1321       elseif(isset($_SESSION['current_photo'])) {
1322          return "show_photo";
1323       }
1324       elseif(isset($_SESSION['start_action']) && $_SESSION['start_action'] == 'showpi') {
1325          return "showpi";
1326       }
1327
1328       return "nothing special";
1329
1330    } // whatToDo()
1331
1332    private function getuid()
1333    {
1334       if($uid = posix_getuid()) {
1335          if($user = posix_getpwuid($uid)) {
1336             return $user['name'];
1337          }
1338       }
1339    
1340       return 'n/a';
1341    
1342    } // getuid()
1343
1344 }
1345
1346 ?>