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