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