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