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