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