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