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