3 /***************************************************************************
5 * Copyright (c) by Andreas Unterkircher, unki@netshadow.at
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
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.
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.
22 ***************************************************************************/
24 require_once "phpfspot_cfg.php";
25 require_once "phpfspot_db.php";
26 require_once "phpfspot_tmpl.php";
40 * this function will be called on class construct
41 * and will check requirements, loads configuration,
42 * open databases and start the user session
44 public function __construct()
46 /* Check necessary requirements */
47 if(!$this->checkRequirements()) {
51 $this->cfg = new PHPFSPOT_CFG;
53 $this->db = new PHPFSPOT_DB(&$this, $this->cfg->fspot_db);
55 if(!is_writeable(dirname($this->cfg->phpfspot_db))) {
56 print dirname($this->cfg->phpfspot_db) .": directory is not writeable!";
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";
65 $this->check_config_table();
68 $this->tmpl = new PHPFSPOT_TMPL($this);
74 if(!isset($_SESSION['tag_condition']))
75 $_SESSION['tag_condition'] = 'or';
77 if(!isset($_SESSION['sort_order']))
78 $_SESSION['sort_order'] = 'date_asc';
80 if(!isset($_SESSION['searchfor']))
81 $_SESSION['searchfor'] = '';
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']);
89 public function __destruct()
95 * show - generate html output
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
103 public function show()
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);
110 $_SESSION['start_action'] = $_GET['mode'];
112 switch($_GET['mode']) {
114 if(isset($_GET['tags'])) {
115 $_SESSION['selected_tags'] = $this->extractTags($_GET['tags']);
117 if(isset($_GET['from_date']) && $this->isValidDate($_GET['from_date'])) {
118 $_SESSION['from_date'] = strtotime($_GET['from_date'] ." 00:00:00");
120 if(isset($_GET['to_date']) && $this->isValidDate($_GET['to_date'])) {
121 $_SESSION['to_date'] = strtotime($_GET['to_date'] ." 23:59:59");
125 if(isset($_GET['tags'])) {
126 $_SESSION['selected_tags'] = $this->extractTags($_GET['tags']);
127 $_SESSION['start_action'] = 'showp';
129 if(isset($_GET['id']) && is_numeric($_GET['id'])) {
130 $_SESSION['current_photo'] = $_GET['id'];
131 $_SESSION['start_action'] = 'showp';
133 if(isset($_GET['from_date']) && $this->isValidDate($_GET['from_date'])) {
134 $_SESSION['from_date'] = strtotime($_GET['from_date']);
136 if(isset($_GET['to_date']) && $this->isValidDate($_GET['to_date'])) {
137 $_SESSION['to_date'] = strtotime($_GET['to_date']);
141 $this->tmpl->show("export.tpl");
145 $this->tmpl->show("slideshow.tpl");
150 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date']))
151 $this->tmpl->assign('date_search_enabled', true);
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");
162 * get_tags - grab all tags of f-spot's database
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.
170 * this function is getting called once by show()
172 private function get_tags()
174 $this->avail_tags = Array();
177 $result = $this->db->db_query("
180 ORDER BY sort_priority ASC
183 while($row = $this->db->db_fetch_object($result)) {
185 $tag_id = $row['id'];
186 $tag_name = $row['name'];
188 /* check if config requests to ignore this tag */
189 if(in_array($row['name'], $this->cfg->hide_tags))
192 $this->tags[$tag_id] = $tag_name;
193 $this->avail_tags[$count] = $tag_id;
202 * extract all photo details
204 * retrieve all available details from f-spot's
205 * database and return them as object
207 public function get_photo_details($idx)
209 $result = $this->db->db_query("
212 WHERE id='". $idx ."'
215 return $this->db->db_fetch_object($result);
217 } // get_photo_details
220 * returns aligned photo names
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 (...)
226 public function getPhotoName($idx, $limit = 0)
228 if($details = $this->get_photo_details($idx)) {
229 $name = $this->shrink_text($details['name'], $limit);
236 * shrink text according provided limit
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 "..."
242 private function shrink_text($text, $limit)
244 if($limit != 0 && strlen($text) > $limit) {
245 $text = substr($text, 0, $limit-5) ."...". substr($text, -($limit-5));
253 * translate f-spoth photo path
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
259 public function translate_path($path, $width = 0)
261 return str_replace($this->cfg->path_replace_from, $this->cfg->path_replace_to, $path);
266 * control HTML ouput for a single photo
268 * this function provides all the necessary information
269 * for the single photo template.
271 public function showPhoto($photo)
273 /* get all photos from the current photo selection */
274 $all_photos = $this->getPhotoSelection();
275 $count = count($all_photos);
277 for($i = 0; $i < $count; $i++) {
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
283 if(isset($get_next)) {
284 $next_img = $all_photos[$i];
288 /* the next photo is our NEXT photo */
289 if($all_photos[$i] == $photo) {
293 $previous_img = $all_photos[$i];
296 if($photo == $all_photos[$i]) {
301 $details = $this->get_photo_details($photo);
308 $orig_path = $this->translate_path($details['directory_path']) ."/". $details['name'];
309 $thumb_path = $this->get_thumb_path($this->cfg->photo_width, $photo);
311 if(!file_exists($orig_path)) {
312 $this->_error("Photo ". $orig_path ." does not exist!<br />\n");
315 if(!is_readable($orig_path)) {
316 $this->_error("Photo ". $orig_path ." is not readable for user ". $this->getuid() ."<br />\n");
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);
325 /* get f-spot database meta information */
326 $meta = $this->get_meta_informations($orig_path);
328 /* If EXIF data are available, use them */
329 if(isset($meta['ExifImageWidth'])) {
330 $meta_res = $meta['ExifImageWidth'] ."x". $meta['ExifImageLength'];
332 $info = getimagesize($orig_path);
333 $meta_res = $info[0] ."x". $info[1];
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";
340 $extern_link = "index.php?mode=showp&id=". $photo;
341 $current_tags = $this->getCurrentTags();
342 if($current_tags != "") {
343 $extern_link.= "&tags=". $current_tags;
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']);
349 $this->tmpl->assign('extern_link', $extern_link);
351 if(file_exists($thumb_path)) {
353 $info = getimagesize($thumb_path);
355 $this->tmpl->assign('description', $details['description']);
356 $this->tmpl->assign('image_name', $details['name']);
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);
365 $this->tmpl->assign('image_url', 'phpfspot_img.php?idx='. $photo ."&width=". $this->cfg->photo_width);
366 $this->tmpl->assign('image_url_full', 'phpfspot_img.php?idx='. $photo);
368 $this->tmpl->assign('tags', $this->get_photo_tags($photo));
369 $this->tmpl->assign('current', $current);
372 $this->_error("Can't open file ". $thumb_path ."\n");
377 $this->tmpl->assign('previous_url', "javascript:showImage(". $previous_img .");");
378 $this->tmpl->assign('prev_img', $previous_img);
382 $this->tmpl->assign('next_url', "javascript:showImage(". $next_img .");");
383 $this->tmpl->assign('next_img', $next_img);
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));
389 $this->tmpl->show("single_photo.tpl");
394 * all available tags and tag cloud
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)
400 public function getAvailableTags()
404 $result = $this->db->db_query("
405 SELECT tag_id as id, count(tag_id) as quantity
415 while($row = $this->db->db_fetch_object($result)) {
416 $tags[$row['id']] = $row['quantity'];
419 // change these font sizes if you will
420 $max_size = 125; // max font size in %
421 $min_size = 75; // min font size in %
423 // get the largest and smallest array values
424 $max_qty = max(array_values($tags));
425 $min_qty = min(array_values($tags));
427 // find the range of values
428 $spread = $max_qty - $min_qty;
429 if (0 == $spread) { // we don't want to divide by zero
433 // determine the font-size increment
434 // this is the increase per tag quantity (times used)
435 $step = ($max_size - $min_size)/($spread);
437 // loop through our tag array
438 foreach ($tags as $key => $value) {
440 if(isset($_SESSION['selected_tags']) && in_array($key, $_SESSION['selected_tags']))
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 %:
451 $output.= "<a href=\"javascript:Tags('add', ". $key .");\" class=\"tag\" style=\"font-size: ". $size ."%;\">". $this->tags[$key] ."</a>, ";
455 $output = substr($output, 0, strlen($output)-2);
458 } // getAvailableTags()
461 * output all selected tags
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']
467 public function getSelectedTags()
470 foreach($this->avail_tags as $tag)
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>, ";
478 $output = substr($output, 0, strlen($output)-2);
481 } // getSelectedTags()
484 * add tag to users session variable
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
490 public function addTag($tag)
492 if(!isset($_SESSION['selected_tags']))
493 $_SESSION['selected_tags'] = Array();
495 if(!in_array($tag, $_SESSION['selected_tags']))
496 array_push($_SESSION['selected_tags'], $tag);
501 * remove tag to users session variable
503 * this function removes the specified tag from
504 * users current tag selection
506 public function delTag($tag)
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']);
517 * reset tag selection
519 * if there is any tag selection, it will be
522 public function resetTags()
524 if(isset($_SESSION['selected_tags']))
525 unset($_SESSION['selected_tags']);
532 * if a specific photo was requested (external link)
533 * unset the session variable now
535 public function resetPhotoView()
537 if(isset($_SESSION['current_photo']))
538 unset($_SESSION['current_photo']);
540 } // resetPhotoView();
545 * if any tag search has taken place, reset
548 public function resetTagSearch()
550 if(isset($_SESSION['searchfor']))
551 unset($_SESSION['searchfor']);
553 } // resetTagSearch()
558 * if any date search has taken place, reset
561 public function resetDateSearch()
563 if(isset($_SESSION['from_date']))
564 unset($_SESSION['from_date']);
565 if(isset($_SESSION['to_date']))
566 unset($_SESSION['to_date']);
568 } // resetDateSearch();
571 * return all photo according selection
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
578 public function getPhotoSelection()
580 $matched_photos = Array();
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 ."'
588 p.time<='". $to_date ."'
592 if(isset($_SESSION['sort_order'])) {
593 $order_str = $this->get_sort_order();
596 /* return a search result */
597 if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '') {
599 SELECT DISTINCT photo_id
605 WHERE t.name LIKE '%". $_SESSION['searchfor'] ."%'";
607 if(isset($additional_where_cond))
608 $query_str.= "AND ". $additional_where_cond ." ";
609 if(isset($order_str))
610 $query_str.= $order_str;
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']);
616 return $matched_photos;
619 /* return according the selected tags */
620 if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
622 foreach($_SESSION['selected_tags'] as $tag)
623 $selected.= $tag .",";
624 $selected = substr($selected, 0, strlen($selected)-1);
626 if($_SESSION['tag_condition'] == 'or') {
628 SELECT DISTINCT photo_id
632 WHERE pt.tag_id IN (". $selected .")
634 if(isset($additional_where_cond))
635 $query_str.= "AND ". $additional_where_cond ." ";
636 if(isset($order_str))
637 $query_str.= $order_str;
639 elseif($_SESSION['tag_condition'] == 'and') {
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";
647 /* Join together a table looking like
649 pt1.photo_id pt1.tag_id pt2.photo_id pt2.tag_id ...
651 so the query can quickly return all images matching the
652 selected tags in an AND condition
657 SELECT DISTINCT pt1.photo_id
661 for($i = 0; $i < count($_SESSION['selected_tags']); $i++) {
663 INNER JOIN photo_tags pt". ($i+2) ."
664 ON pt1.photo_id=pt". ($i+2) .".photo_id
671 $query_str.= "WHERE pt1.tag_id=". $_SESSION['selected_tags'][0];
672 for($i = 1; $i < count($_SESSION['selected_tags']); $i++) {
674 AND pt". ($i+1) .".tag_id=". $_SESSION['selected_tags'][$i] ."
677 if(isset($additional_where_cond))
678 $query_str.= "AND ". $additional_where_cond;
679 if(isset($order_str))
680 $query_str.= $order_str;
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']);
687 return $matched_photos;
690 /* return all available photos */
692 SELECT DISTINCT photo_id
697 if(isset($additional_where_cond))
698 $query_str.= "WHERE ". $additional_where_cond ." ";
699 if(isset($order_str))
700 $query_str.= $order_str;
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']);
706 return $matched_photos;
708 } // getPhotoSelection()
711 * control HTML ouput for photo index
713 * this function provides all the necessary information
714 * for the photo index template.
716 public function showPhotoIndex()
718 $photos = $this->getPhotoSelection();
720 $count = count($photos);
722 if(isset($_SESSION['begin_with']) && $_SESSION['begin_with'] != "")
723 $anchor = $_SESSION['begin_with'];
725 if(!isset($this->cfg->rows_per_page) || $this->cfg->rows_per_page == 0) {
731 elseif($this->cfg->rows_per_page > 0) {
733 if(!$_SESSION['begin_with'] || $_SESSION['begin_with'] == 0)
737 $begin_with = $_SESSION['begin_with'];
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
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) {
752 $end_with = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
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();
765 for($i = $begin_with; $i < $end_with; $i++) {
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));
772 $thumb_path = $this->get_thumb_path($this->cfg->thumb_width, $photos[$i]);
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];
780 if($cols == $this->cfg->thumbs_per_row-1) {
783 $images[$rows] = Array();
784 $img_width[$rows] = Array();
785 $img_height[$rows] = Array();
792 // +1 for for smarty's selection iteration
795 if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
796 $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
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']));
803 if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
804 $this->tmpl->assign('tag_result', 1);
807 /* do we have to display the page selector ? */
808 if($this->cfg->rows_per_page != 0) {
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);
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 .");");
819 $photo_per_page = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
820 $last_page = ceil($count / $photo_per_page);
822 /* get the current selected page */
823 if($begin_with == 0) {
827 for($i = $begin_with; $i >= 0; $i-=$photo_per_page) {
834 for($i = 1; $i <= $last_page; $i++) {
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%;\"";
846 $select = "<a href=\"javascript:showPhotoIndex(". (($i*$photo_per_page)-$photo_per_page) .");\"";
849 $select.= ">". $i ."</a> ";
851 // until 9 pages we show the selector from 1-9
852 if($last_page <= 9) {
853 $page_select.= $select;
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 */) {
867 $page_select.= $select;
875 $page_select.= "......... ";
880 /* only show the page selector if we have more then one page */
882 $this->tmpl->assign('page_selector', $page_select);
886 $current_tags = $this->getCurrentTags();
887 $extern_link = "index.php?mode=showpi";
888 if($current_tags != "") {
889 $extern_link.= "&tags=". $current_tags;
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']);
895 $export_link = "index.php?mode=export";
896 $slideshow_link = "index.php?mode=slideshow";
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);
912 $this->tmpl->show("photo_index.tpl");
915 print "<script language=\"JavaScript\">self.location.hash = '#image". $anchor ."';</script>\n";
917 } // showPhotoIndex()
920 * show credit template
922 public function showCredits()
924 $this->tmpl->assign('version', $this->cfg->version);
925 $this->tmpl->assign('product', $this->cfg->product);
926 $this->tmpl->show("credits.tpl");
931 * create_thumbnails for the requested width
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.
938 public function create_thumbnail($orig_image, $thumb_image, $width)
940 if(!file_exists($orig_image)) {
944 $details = getimagesize($orig_image);
946 /* check if original photo is a support image type */
947 if(!$this->checkifImageSupported($details['mime']))
950 $meta = $this->get_meta_informations($orig_image);
955 switch($meta['Orientation']) {
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;
975 $src_img = @imagecreatefromjpeg($orig_image);
978 print "Can't load image from ". $orig_image ."\n";
982 /* grabs the height and width */
983 $cur_width = imagesx($src_img);
984 $cur_height = imagesy($src_img);
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
990 if($width >= $cur_width) {
991 $result = imagejpeg($src_img, $thumb_image, 75);
992 imagedestroy($src_img);
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) {
1000 $cur_width = $cur_height;
1004 /* calculates aspect ratio */
1005 $aspect_ratio = $cur_height / $cur_width;
1008 if($aspect_ratio < 1) {
1010 $new_h = abs($new_w * $aspect_ratio);
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 */
1019 $tmp_h = abs($tmp_w * $tmp_ratio);
1021 // now that we know, how high they photo should be, if it
1022 // gets rotated, use this high to scale the image
1024 $new_w = abs($new_h / $aspect_ratio);
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) {
1035 /* creates new image of that size */
1036 $dst_img = imagecreatetruecolor($new_w, $new_h);
1038 imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
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));
1043 /* needs the image to be flipped horizontal? */
1047 for($x = 0; $x < $new_w; $x++) {
1048 imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
1053 $this->_debug("(ROTATE)");
1054 $dst_img = $this->rotateImage($dst_img, $rotate);
1057 /* write down new generated file */
1058 $result = imagejpeg($dst_img, $thumb_image, 75);
1060 /* free your mind */
1061 imagedestroy($dst_img);
1062 imagedestroy($src_img);
1064 if($result === false) {
1065 print "Can't write thumbnail ". $thumb_image ."\n";
1071 } // create_thumbnail()
1074 * return all exif meta data from the file
1076 public function get_meta_informations($file)
1078 return exif_read_data($file);
1080 } // get_meta_informations()
1083 * create phpfspot own sqlite database
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, ...).
1089 public function check_config_table()
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,
1101 } // check_config_table
1104 * Generates a thumbnail from photo idx
1106 * This function will generate JPEG thumbnails from provided F-Spot photo
1109 * 1. Check if all thumbnail generations (width) are already in place and
1111 * 2. Check if the md5sum of the original file has changed
1112 * 3. Generate the thumbnails if needed
1114 public function gen_thumb($idx = 0, $force = 0)
1118 $resolutions = Array(
1119 $this->cfg->thumb_width,
1120 $this->cfg->photo_width,
1121 $this->cfg->mini_width,
1124 /* get details from F-Spot's database */
1125 $details = $this->get_photo_details($idx);
1127 /* calculate file MD5 sum */
1128 $full_path = $this->translate_path($details['directory_path']) ."/". $details['name'];
1130 if(!file_exists($full_path)) {
1131 $this->_error("File ". $full_path ." does not exist\n");
1135 if(!is_readable($full_path)) {
1136 $this->_error("File ". $full_path ." is not readable for ". $this->getuid() ."\n");
1140 $file_md5 = md5_file($full_path);
1142 $this->_debug("Image [". $idx ."] ". $this->shrink_text($details['name'], 20) ." Thumbnails:");
1144 foreach($resolutions as $resolution) {
1146 $thumb_sub_path = substr($file_md5, 0, 2);
1147 $thumb_path = $this->cfg->base_path ."/thumbs/". $thumb_sub_path ."/". $resolution ."_". $file_md5;
1149 if(!file_exists(dirname($thumb_path))) {
1150 mkdir(dirname($thumb_path), 0755);
1153 /* if the thumbnail file doesn't exist, create it */
1154 if(!file_exists($thumb_path)) {
1156 $this->_debug(" ". $resolution ."px");
1157 if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
1160 /* if the file hasn't changed there is no need to regen the thumb */
1161 elseif($file_md5 != $this->getMD5($idx) || $force) {
1163 $this->_debug(" ". $resolution ."px");
1164 if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
1170 /* set the new/changed MD5 sum for the current photo */
1172 $this->setMD5($idx, $file_md5);
1175 $this->_debug("\n");
1180 * returns stored md5 sum for a specific photo
1182 * this function queries the phpfspot database for a
1183 * stored MD5 checksum of the specified photo
1185 public function getMD5($idx)
1187 $result = $this->cfg_db->db_query("
1190 WHERE img_idx='". $idx ."'
1196 $img = $this->cfg_db->db_fetch_object($result);
1197 return $img['img_md5'];
1202 * set MD5 sum for the specific photo
1204 private function setMD5($idx, $md5)
1206 $result = $this->cfg_db->db_exec("
1207 REPLACE INTO images (img_idx, img_md5)
1208 VALUES ('". $idx ."', '". $md5 ."')
1214 * store current tag condition
1216 * this function stores the current tag condition
1217 * (AND or OR) in the users session variables
1219 public function setTagCondition($mode)
1221 $_SESSION['tag_condition'] = $mode;
1223 } // setTagCondition()
1226 * invoke tag & date search
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
1234 public function startSearch($searchfor, $sort_order, $from = 0, $to = 0)
1236 $_SESSION['searchfor'] = $searchfor;
1237 $_SESSION['sort_order'] = $sort_order;
1239 $_SESSION['from_date'] = strtotime($from);
1241 unset($_SESSION['from_date']);
1243 $_SESSION['to_date'] = strtotime($to);
1245 unset($_SESSION['to_date']);
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);
1261 * this function rotates the image according the
1264 private function rotateImage($img, $degrees)
1266 if(function_exists("imagerotate")) {
1267 $img = imagerotate($img, $degrees, 0);
1269 function imagerotate($src_img, $angle)
1271 $src_x = imagesx($src_img);
1272 $src_y = imagesy($src_img);
1273 if ($angle == 180) {
1277 elseif ($src_x <= $src_y) {
1281 elseif ($src_x >= $src_y) {
1286 $rotate=imagecreatetruecolor($dest_x,$dest_y);
1287 imagealphablending($rotate, false);
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);
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);
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);
1327 $img = imagerotate($img, $degrees);
1336 * return all assigned tags for the specified photo
1338 private function get_photo_tags($idx)
1340 $result = $this->db->db_query("
1343 INNER JOIN photo_tags pt
1345 WHERE pt.photo_id='". $idx ."'
1350 while($row = $this->db->db_fetch_object($result))
1351 $tags[$row['id']] = $row['name'];
1355 } // get_photo_tags()
1358 * create on-the-fly images with text within
1360 public function showTextImage($txt, $color=000000, $space=4, $font=4, $w=300)
1362 if (strlen($color) != 6)
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);
1375 foreach ($txt as $text) {
1376 $x = (($w - ($fw * strlen($text))) / 2);
1377 imagestring($im, $font, $x, $y, $text, $color);
1378 $y += ($h + $space);
1381 Header("Content-type: image/png");
1384 } // showTextImage()
1387 * check if all requirements are met
1389 private function checkRequirements()
1391 if(!function_exists("imagecreatefromjpeg")) {
1392 print "PHP GD library extension is missing<br />\n";
1396 if(!function_exists("sqlite3_open")) {
1397 print "PHP SQLite3 library extension is missing<br />\n";
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";
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";
1413 ini_restore('track_errors');
1420 } // checkRequirements()
1422 private function _debug($text)
1424 if($this->fromcmd) {
1431 * check if specified MIME type is supported
1433 public function checkifImageSupported($mime)
1435 if(in_array($mime, Array("image/jpeg")))
1440 } // checkifImageSupported()
1442 public function _error($text)
1444 switch($this->cfg->logging) {
1446 print "<img src=\"resources/green_info.png\" alt=\"warning\" />\n";
1453 error_log($text, 3, $his->cfg->log_file);
1460 * output calendard input fields
1462 private function get_calendar($mode)
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");
1468 $output = "<input type=\"text\" size=\"3\" id=\"". $mode ."year\" value=\"". $year ."\"";
1469 if(!isset($_SESSION[$mode .'_date'])) $output.= " disabled=\"disabled\"";
1471 $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."month\" value=\"". $month ."\"";
1472 if(!isset($_SESSION[$mode .'_date'])) $output.= " disabled=\"disabled\"";
1474 $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."day\" value=\"". $day ."\"";
1475 if(!isset($_SESSION[$mode .'_date'])) $output.= " disabled=\"disabled\"";
1482 * output calendar matrix
1484 public function get_calendar_matrix($year = 0, $month = 0, $day = 0)
1486 if (!isset($year)) $year = date('Y');
1487 if (!isset($month)) $month = date('m');
1488 if (!isset($day)) $day = date('d');
1493 require_once CALENDAR_ROOT.'Month/Weekdays.php';
1494 require_once CALENDAR_ROOT.'Day.php';
1497 $month = new Calendar_Month_Weekdays($year,$month);
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) .");";
1505 $selectedDays = array (
1506 new Calendar_Day($year,$month,$day),
1507 new Calendar_Day($year,12,25),
1510 // Build the days in the month
1511 $month->build($selectedDays);
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);
1517 while ( $day = $month->fetch() ) {
1519 if(!isset($matrix[$rows]))
1520 $matrix[$rows] = Array();
1524 $dayStamp = $day->thisDay(true);
1525 $link = "javascript:setCalendarDate(". date('Y',$dayStamp) .", ". date('n',$dayStamp).", ". date('j',$dayStamp) .");";
1527 // isFirst() to find start of week
1528 if ( $day->isFirst() )
1531 if ( $day->isSelected() ) {
1532 $string.= "<td class=\"selected\">".$day->thisDay()."</td>\n";
1533 } else if ( $day->isEmpty() ) {
1534 $string.= "<td> </td>\n";
1536 $string.= "<td><a class=\"calendar\" href=\"".$link."\">".$day->thisDay()."</a></td>\n";
1539 // isLast() to find end of week
1540 if ( $day->isLast() )
1541 $string.= "</tr>\n";
1543 $matrix[$rows][$cols] = $string;
1553 $this->tmpl->assign('matrix', $matrix);
1554 $this->tmpl->assign('rows', $rows);
1555 $this->tmpl->show("calendar.tpl");
1557 } // get_calendar_matrix()
1560 * output export page
1562 public function getExport($mode)
1564 $pictures = $this->getPhotoSelection();
1565 $current_tags = $this->getCurrentTags();
1567 if(!isset($_SERVER['HTTPS'])) $protocol = "http";
1568 else $protocol = "https";
1570 $server_name = $_SERVER['SERVER_NAME'];
1572 foreach($pictures as $picture) {
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;
1578 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
1579 $orig_url.= "&from_date=". $_SESSION['from_date'] ."&to_date=". $_SESSION['to_date'];
1582 $thumb_url = $protocol ."://". $server_name . $this->cfg->web_path ."phpfspot_img.php?idx=". $picture ."&width=". $this->cfg->thumb_width;
1587 // <a href="%pictureurl%"><img src="%thumbnailurl%" ></a>
1588 print htmlspecialchars("<a href=\"". $orig_url ."\"><img src=\"". $thumb_url ."\" /></a>") ."<br />\n";
1592 // "[%pictureurl% %thumbnailurl%]"
1593 print htmlspecialchars("[".$orig_url." ".$thumb_url."&fake=1.jpg]") ."<br />\n";
1596 case 'MoinMoinList':
1597 // " * [%pictureurl% %thumbnailurl%]"
1598 print " " . htmlspecialchars("* [".$orig_url." ".$thumb_url."&fake=1.jpg]") ."<br />\n";
1607 * return all selected tags as one string
1609 private function getCurrentTags()
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);
1617 return $current_tags;
1619 } // getCurrentTags()
1622 * return the current photo
1624 public function getCurrentPhoto()
1626 if(isset($_SESSION['current_photo'])) {
1627 print $_SESSION['current_photo'];
1629 } // getCurrentPhoto()
1632 * tells the client browser what to do
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
1640 public function whatToDo()
1642 if(isset($_SESSION['current_photo']) && $_SESSION['start_action'] == 'showp') {
1643 return "show_photo";
1645 elseif(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
1646 return "showpi_tags";
1648 elseif(isset($_SESSION['start_action']) && $_SESSION['start_action'] == 'showpi') {
1652 return "nothing special";
1657 * return the current process-user
1659 private function getuid()
1661 if($uid = posix_getuid()) {
1662 if($user = posix_getpwuid($uid)) {
1663 return $user['name'];
1672 * returns a select-dropdown box to select photo index sort parameters
1674 private function get_sort_field()
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\"";
1682 $output.= ">". $sort_order ."</option>";
1684 $output.= "</select>";
1687 } // get_sort_field()
1690 * returns the currently selected sort order
1692 private function get_sort_order()
1694 switch($_SESSION['sort_order']) {
1696 return " ORDER BY p.time ASC";
1699 return " ORDER BY p.time DESC";
1702 return " ORDER BY p.name ASC";
1705 return " ORDER BY p.name DESC";
1709 } // get_sort_order()
1712 * return the next to be shown slide show image
1714 * this function returns the URL of the next image
1715 * in the slideshow sequence.
1717 public function getNextSlideShowImage()
1719 $all_photos = $this->getPhotoSelection();
1721 if(!isset($_SESSION['slideshow_img']) || $_SESSION['slideshow_img'] == count($all_photos)-1)
1722 $_SESSION['slideshow_img'] = 0;
1724 $_SESSION['slideshow_img']++;
1726 $server_name = $_SERVER['SERVER_NAME'];
1727 if(!isset($_SERVER['HTTPS'])) $protocol = "http";
1728 else $protocol = "https";
1730 return $protocol ."://". $server_name . $this->cfg->web_path ."phpfspot_img.php?idx=". $all_photos[$_SESSION['slideshow_img']] ."&width=". $this->cfg->photo_width;
1732 } // getNextSlideShowImage()
1735 * return the previous to be shown slide show image
1737 * this function returns the URL of the previous image
1738 * in the slideshow sequence.
1740 public function getPrevSlideShowImage()
1742 $all_photos = $this->getPhotoSelection();
1744 if(!isset($_SESSION['slideshow_img']) || $_SESSION['slideshow_img'] == 0)
1745 $_SESSION['slideshow_img'] = 0;
1747 $_SESSION['slideshow_img']--;
1749 $server_name = $_SERVER['SERVER_NAME'];
1750 if(!isset($_SERVER['HTTPS'])) $protocol = "http";
1751 else $protocol = "https";
1753 return $protocol ."://". $server_name . $this->cfg->web_path ."phpfspot_img.php?idx=". $all_photos[$_SESSION['slideshow_img']] ."&width=". $this->cfg->photo_width;
1755 } // getPrevSlideShowImage()
1757 public function resetSlideShow()
1759 if(isset($_SESSION['slideshow_img']))
1760 unset($_SESSION['slideshow_img']);
1761 } // resetSlideShow()
1766 * this function will get all photos from the fspot
1767 * database and randomly return ONE entry
1769 * saddly there is yet no sqlite3 function which returns
1770 * the bulk result in array, so we have to fill up our
1773 public function get_random_photo()
1777 $result = $this->db->db_query("
1782 while($row = $this->db->db_fetch_object($result)) {
1783 array_push($all, $row['id']);
1786 return $all[array_rand($all)];
1788 } // get_random_photo()
1791 * validates provided date
1793 * this function validates if the provided date
1794 * contains a valid date and will return true
1797 public function isValidDate($date_str)
1799 $timestamp = strtotime($date_str);
1801 if(is_numeric($timestamp))
1809 * timestamp to string conversion
1811 private function ts2str($timestamp)
1813 return strftime("%Y-%m-%d", $timestamp);
1816 private function extractTags($tags_str)
1818 $not_validated = split(',', $_GET['tags']);
1819 $validated = array();
1821 foreach($not_validated as $tag) {
1822 if(is_numeric($tag))
1823 array_push($validated, $tag);
1831 * returns the full path to a thumbnail
1833 public function get_thumb_path($width, $photo)
1835 $sub_path = substr($this->getMD5($photo), 0, 2);
1836 return $this->cfg->base_path
1842 . $this->getMD5($photo);
1844 } // get_thumb_path()