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