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