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