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