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']);
120 if(isset($_GET['to_date']) && $this->isValidDate($_GET['to_date'])) {
121 $_SESSION['to_date'] = strtotime($_GET['to_date']);
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 = $details['name'];
230 if($limit != 0 && strlen($name) > $limit) {
231 $name = substr($name, 0, $limit-5) ."...". substr($name, -($limit-5));
239 * translate f-spoth photo path
241 * as the full-qualified path recorded in the f-spot database
242 * is usally not the same as on the webserver, this function
243 * will replace the path with that one specified in the cfg
245 public function translate_path($path, $width = 0)
247 return str_replace($this->cfg->path_replace_from, $this->cfg->path_replace_to, $path);
252 * control HTML ouput for a single photo
254 * this function provides all the necessary information
255 * for the single photo template.
257 public function showPhoto($photo)
259 /* get all photos from the current photo selection */
260 $all_photos = $this->getPhotoSelection();
261 $count = count($all_photos);
263 for($i = 0; $i < $count; $i++) {
265 // $get_next will be set, when the photo which has to
266 // be displayed has been found - this means that the
267 // next available is in fact the NEXT image (for the
269 if(isset($get_next)) {
270 $next_img = $all_photos[$i];
274 /* the next photo is our NEXT photo */
275 if($all_photos[$i] == $photo) {
279 $previous_img = $all_photos[$i];
282 if($photo == $all_photos[$i]) {
287 $details = $this->get_photo_details($photo);
294 $orig_path = $this->translate_path($details['directory_path']) ."/". $details['name'];
295 $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->photo_width ."_". $this->getMD5($photo);
297 if(!file_exists($orig_path)) {
298 $this->_error("Photo ". $orig_path ." does not exist!<br />\n");
301 if(!is_readable($orig_path)) {
302 $this->_error("Photo ". $orig_path ." is not readable for user ". $this->getuid() ."<br />\n");
305 /* If the thumbnail doesn't exist yet, try to create it */
306 if(!file_exists($thumb_path)) {
307 $this->gen_thumb($photo, true);
308 $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->photo_width ."_". $this->getMD5($photo);
311 /* get f-spot database meta information */
312 $meta = $this->get_meta_informations($orig_path);
314 /* If EXIF data are available, use them */
315 if(isset($meta['ExifImageWidth'])) {
316 $meta_res = $meta['ExifImageWidth'] ."x". $meta['ExifImageLength'];
318 $info = getimagesize($orig_path);
319 $meta_res = $info[0] ."x". $info[1];
322 $meta_date = isset($meta['FileDateTime']) ? strftime("%a %x %X", $meta['FileDateTime']) : "n/a";
323 $meta_make = isset($meta['Make']) ? $meta['Make'] ." / ". $meta['Model'] : "n/a";
324 $meta_size = isset($meta['FileSize']) ? round($meta['FileSize']/1024, 1) ."kbyte" : "n/a";
326 $extern_link = "index.php?mode=showp&id=". $photo;
327 $current_tags = $this->getCurrentTags();
328 if($current_tags != "") {
329 $extern_link.= "&tags=". $current_tags;
331 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
332 $extern_link.= "&from_date=". $this->ts2str($_SESSION['from_date']) ."&to_date=". $this->ts2str($_SESSION['to_date']);
335 $this->tmpl->assign('extern_link', $extern_link);
337 if(file_exists($thumb_path)) {
339 $info = getimagesize($thumb_path);
341 $this->tmpl->assign('description', $details['description']);
342 $this->tmpl->assign('image_name', $details['name']);
344 $this->tmpl->assign('width', $info[0]);
345 $this->tmpl->assign('height', $info[1]);
346 $this->tmpl->assign('ExifMadeOn', $meta_date);
347 $this->tmpl->assign('ExifMadeWith', $meta_make);
348 $this->tmpl->assign('ExifOrigResolution', $meta_res);
349 $this->tmpl->assign('ExifFileSize', $meta_size);
351 $this->tmpl->assign('image_url', 'phpfspot_img.php?idx='. $photo ."&width=". $this->cfg->photo_width);
352 $this->tmpl->assign('image_url_full', 'phpfspot_img.php?idx='. $photo);
354 $this->tmpl->assign('tags', $this->get_photo_tags($photo));
355 $this->tmpl->assign('current', $current);
358 $this->_error("Can't open file ". $thumb_path ."\n");
363 $this->tmpl->assign('previous_url', "javascript:showImage(". $previous_img .");");
364 $this->tmpl->assign('prev_img', $previous_img);
368 $this->tmpl->assign('next_url', "javascript:showImage(". $next_img .");");
369 $this->tmpl->assign('next_img', $next_img);
371 $this->tmpl->assign('mini_width', $this->cfg->mini_width);
372 $this->tmpl->assign('photo_number', $i);
373 $this->tmpl->assign('photo_count', count($all_photos));
375 $this->tmpl->show("single_photo.tpl");
380 * all available tags and tag cloud
382 * this function outputs all available tags (time ordered)
383 * and in addition output them as tag cloud (tags which have
384 * many photos will appears more then others)
386 public function getAvailableTags()
390 $result = $this->db->db_query("
391 SELECT tag_id as id, count(tag_id) as quantity
401 while($row = $this->db->db_fetch_object($result)) {
402 $tags[$row['id']] = $row['quantity'];
405 // change these font sizes if you will
406 $max_size = 125; // max font size in %
407 $min_size = 75; // min font size in %
409 // get the largest and smallest array values
410 $max_qty = max(array_values($tags));
411 $min_qty = min(array_values($tags));
413 // find the range of values
414 $spread = $max_qty - $min_qty;
415 if (0 == $spread) { // we don't want to divide by zero
419 // determine the font-size increment
420 // this is the increase per tag quantity (times used)
421 $step = ($max_size - $min_size)/($spread);
423 // loop through our tag array
424 foreach ($tags as $key => $value) {
426 if(isset($_SESSION['selected_tags']) && in_array($key, $_SESSION['selected_tags']))
429 // calculate CSS font-size
430 // find the $value in excess of $min_qty
431 // multiply by the font-size increment ($size)
432 // and add the $min_size set above
433 $size = $min_size + (($value - $min_qty) * $step);
434 // uncomment if you want sizes in whole %:
437 $output.= "<a href=\"javascript:Tags('add', ". $key .");\" class=\"tag\" style=\"font-size: ". $size ."%;\">". $this->tags[$key] ."</a>, ";
441 $output = substr($output, 0, strlen($output)-2);
444 } // getAvailableTags()
447 * output all selected tags
449 * this function output all tags which have been selected
450 * by the user. the selected tags are stored in the
451 * session-variable $_SESSION['selected_tags']
453 public function getSelectedTags()
456 foreach($this->avail_tags as $tag)
458 // return all selected tags
459 if(isset($_SESSION['selected_tags']) && in_array($tag, $_SESSION['selected_tags'])) {
460 $output.= "<a href=\"javascript:Tags('del', ". $tag .");\" class=\"tag\">". $this->tags[$tag] ."</a>, ";
464 $output = substr($output, 0, strlen($output)-2);
467 } // getSelectedTags()
470 * add tag to users session variable
472 * this function will add the specified to users current
473 * tag selection. if a date search has been made before
474 * it will be now cleared
476 public function addTag($tag)
478 if(!isset($_SESSION['selected_tags']))
479 $_SESSION['selected_tags'] = Array();
481 if(!in_array($tag, $_SESSION['selected_tags']))
482 array_push($_SESSION['selected_tags'], $tag);
487 * remove tag to users session variable
489 * this function removes the specified tag from
490 * users current tag selection
492 public function delTag($tag)
494 if(isset($_SESSION['selected_tags'])) {
495 $key = array_search($tag, $_SESSION['selected_tags']);
496 unset($_SESSION['selected_tags'][$key]);
497 sort($_SESSION['selected_tags']);
503 * reset tag selection
505 * if there is any tag selection, it will be
508 public function resetTags()
510 if(isset($_SESSION['selected_tags']))
511 unset($_SESSION['selected_tags']);
518 * if a specific photo was requested (external link)
519 * unset the session variable now
521 public function resetPhotoView()
523 if(isset($_SESSION['current_photo']))
524 unset($_SESSION['current_photo']);
526 } // resetPhotoView();
531 * if any tag search has taken place, reset
534 public function resetTagSearch()
536 if(isset($_SESSION['searchfor']))
537 unset($_SESSION['searchfor']);
539 } // resetTagSearch()
544 * if any date search has taken place, reset
547 public function resetDateSearch()
549 if(isset($_SESSION['from_date']))
550 unset($_SESSION['from_date']);
551 if(isset($_SESSION['to_date']))
552 unset($_SESSION['to_date']);
554 } // resetDateSearch();
557 * return all photo according selection
559 * this function returns all photos based on
560 * the tag-selection, tag- or date-search.
561 * the tag-search also has to take care of AND
562 * and OR conjunctions
564 public function getPhotoSelection()
566 $matched_photos = Array();
568 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
569 $from_date = $_SESSION['from_date'];
570 $to_date = $_SESSION['to_date'];
571 $additional_where_cond = "
572 p.time>='". $from_date ."'
574 p.time<='". $to_date ."'
578 if(isset($_SESSION['sort_order'])) {
579 $order_str = $this->get_sort_order();
582 /* return a search result */
583 if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '') {
585 SELECT DISTINCT photo_id
591 WHERE t.name LIKE '%". $_SESSION['searchfor'] ."%'";
593 if(isset($additional_where_cond))
594 $query_str.= "AND ". $additional_where_cond ." ";
595 if(isset($order_str))
596 $query_str.= $order_str;
598 $result = $this->db->db_query($query_str);
599 while($row = $this->db->db_fetch_object($result)) {
600 array_push($matched_photos, $row['photo_id']);
602 return $matched_photos;
605 /* return according the selected tags */
606 if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
608 foreach($_SESSION['selected_tags'] as $tag)
609 $selected.= $tag .",";
610 $selected = substr($selected, 0, strlen($selected)-1);
612 if($_SESSION['tag_condition'] == 'or') {
614 SELECT DISTINCT photo_id
618 WHERE pt.tag_id IN (". $selected .")
620 if(isset($additional_where_cond))
621 $query_str.= "AND ". $additional_where_cond ." ";
622 if(isset($order_str))
623 $query_str.= $order_str;
625 elseif($_SESSION['tag_condition'] == 'and') {
627 if(count($_SESSION['selected_tags']) >= 32) {
628 print "A SQLite limit of 32 tables within a JOIN SELECT avoids to<br />\n";
629 print "evaluate your tag selection. Please remove some tags from your selection.\n";
633 /* Join together a table looking like
635 pt1.photo_id pt1.tag_id pt2.photo_id pt2.tag_id ...
637 so the query can quickly return all images matching the
638 selected tags in an AND condition
643 SELECT DISTINCT pt1.photo_id
647 for($i = 0; $i < count($_SESSION['selected_tags']); $i++) {
649 INNER JOIN photo_tags pt". ($i+2) ."
650 ON pt1.photo_id=pt". ($i+2) .".photo_id
657 $query_str.= "WHERE pt1.tag_id=". $_SESSION['selected_tags'][0];
658 for($i = 1; $i < count($_SESSION['selected_tags']); $i++) {
660 AND pt". ($i+1) .".tag_id=". $_SESSION['selected_tags'][$i] ."
663 if(isset($additional_where_cond))
664 $query_str.= "AND ". $additional_where_cond;
665 if(isset($order_str))
666 $query_str.= $order_str;
669 $result = $this->db->db_query($query_str);
670 while($row = $this->db->db_fetch_object($result)) {
671 array_push($matched_photos, $row['photo_id']);
673 return $matched_photos;
676 /* return all available photos */
678 SELECT DISTINCT photo_id
683 if(isset($additional_where_cond))
684 $query_str.= "WHERE ". $additional_where_cond ." ";
685 if(isset($order_str))
686 $query_str.= $order_str;
688 $result = $this->db->db_query($query_str);
689 while($row = $this->db->db_fetch_object($result)) {
690 array_push($matched_photos, $row['photo_id']);
692 return $matched_photos;
694 } // getPhotoSelection()
697 * control HTML ouput for photo index
699 * this function provides all the necessary information
700 * for the photo index template.
702 public function showPhotoIndex()
704 $photos = $this->getPhotoSelection();
706 $count = count($photos);
708 if(isset($_SESSION['begin_with']) && $_SESSION['begin_with'] != "")
709 $anchor = $_SESSION['begin_with'];
711 if(!isset($this->cfg->rows_per_page) || $this->cfg->rows_per_page == 0) {
717 elseif($this->cfg->rows_per_page > 0) {
719 if(!$_SESSION['begin_with'] || $_SESSION['begin_with'] == 0)
723 $begin_with = $_SESSION['begin_with'];
725 // verify $begin_with - perhaps the thumbs-per-rows or
726 // rows-per-page variables have changed or the jump back
727 // from a photo wasn't exact - so calculate the real new
729 $multiplicator = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
730 for($i = 0; $i <= $count; $i+=$multiplicator) {
731 if($begin_with >= $i && $begin_with < $i+$multiplicator) {
738 $end_with = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
744 $images[$rows] = Array();
745 $img_height[$rows] = Array();
746 $img_width[$rows] = Array();
747 $img_id[$rows] = Array();
748 $img_name[$rows] = Array();
749 $img_title = Array();
751 for($i = $begin_with; $i < $end_with; $i++) {
753 $images[$rows][$cols] = $photos[$i];
754 $img_id[$rows][$cols] = $i;
755 $img_name[$rows][$cols] = htmlspecialchars($this->getPhotoName($photos[$i], 15));
756 $img_title[$rows][$cols] = "Click to view photo ". htmlspecialchars($this->getPhotoName($photos[$i], 0));
758 $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->thumb_width ."_". $this->getMD5($photos[$i]);
760 if(file_exists($thumb_path)) {
761 $info = getimagesize($thumb_path);
762 $img_width[$rows][$cols] = $info[0];
763 $img_height[$rows][$cols] = $info[1];
766 if($cols == $this->cfg->thumbs_per_row-1) {
769 $images[$rows] = Array();
770 $img_width[$rows] = Array();
771 $img_height[$rows] = Array();
778 // +1 for for smarty's selection iteration
781 if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
782 $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
784 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
785 $this->tmpl->assign('from_date', $this->ts2str($_SESSION['from_date']));
786 $this->tmpl->assign('to_date', $this->ts2str($_SESSION['to_date']));
789 if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
790 $this->tmpl->assign('tag_result', 1);
793 /* do we have to display the page selector ? */
794 if($this->cfg->rows_per_page != 0) {
796 /* calculate the page switchers */
797 $previous_start = $begin_with - ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
798 $next_start = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
801 $this->tmpl->assign("previous_url", "javascript:showPhotoIndex(". $previous_start .");");
802 if($end_with < $count)
803 $this->tmpl->assign("next_url", "javascript:showPhotoIndex(". $next_start .");");
805 $photo_per_page = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
806 $last_page = ceil($count / $photo_per_page);
808 /* get the current selected page */
809 if($begin_with == 0) {
813 for($i = $begin_with; $i >= 0; $i-=$photo_per_page) {
820 for($i = 1; $i <= $last_page; $i++) {
822 if($current_page == $i)
823 $style = "style=\"font-size: 125%; text-decoration: underline;\"";
824 elseif($current_page-1 == $i || $current_page+1 == $i)
825 $style = "style=\"font-size: 105%;\"";
826 elseif(($current_page-5 >= $i) && ($i != 1) ||
827 ($current_page+5 <= $i) && ($i != $last_page))
828 $style = "style=\"font-size: 75%;\"";
832 $select = "<a href=\"javascript:showPhotoIndex(". (($i*$photo_per_page)-$photo_per_page) .");\"";
835 $select.= ">". $i ."</a> ";
837 // until 9 pages we show the selector from 1-9
838 if($last_page <= 9) {
839 $page_select.= $select;
842 if($i == 1 /* first page */ ||
843 $i == $last_page /* last page */ ||
844 $i == $current_page /* current page */ ||
845 $i == ceil($last_page * 0.25) /* first quater */ ||
846 $i == ceil($last_page * 0.5) /* half */ ||
847 $i == ceil($last_page * 0.75) /* third quater */ ||
848 (in_array($i, array(1,2,3,4,5,6)) && $current_page <= 4) /* the first 6 */ ||
849 (in_array($i, array($last_page, $last_page-1, $last_page-2, $last_page-3, $last_page-4, $last_page-5)) && $current_page >= $last_page-4) /* the last 6 */ ||
850 $i == $current_page-3 || $i == $current_page-2 || $i == $current_page-1 /* three before */ ||
851 $i == $current_page+3 || $i == $current_page+2 || $i == $current_page+1 /* three after */) {
853 $page_select.= $select;
861 $page_select.= "......... ";
866 /* only show the page selector if we have more then one page */
868 $this->tmpl->assign('page_selector', $page_select);
872 $current_tags = $this->getCurrentTags();
873 $extern_link = "index.php?mode=showpi";
874 if($current_tags != "") {
875 $extern_link.= "&tags=". $current_tags;
877 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
878 $extern_link.= "&from_date=". $this->ts2str($_SESSION['from_date']) ."&to_date=". $this->ts2str($_SESSION['to_date']);
881 $export_link = "index.php?mode=export";
882 $slideshow_link = "index.php?mode=slideshow";
884 $this->tmpl->assign('extern_link', $extern_link);
885 $this->tmpl->assign('slideshow_link', $slideshow_link);
886 $this->tmpl->assign('export_link', $export_link);
887 $this->tmpl->assign('count', $count);
888 $this->tmpl->assign('width', $this->cfg->thumb_width);
889 $this->tmpl->assign('images', $images);
890 $this->tmpl->assign('img_width', $img_width);
891 $this->tmpl->assign('img_height', $img_height);
892 $this->tmpl->assign('img_id', $img_id);
893 $this->tmpl->assign('img_name', $img_name);
894 $this->tmpl->assign('img_title', $img_title);
895 $this->tmpl->assign('rows', $rows);
896 $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
898 $this->tmpl->show("photo_index.tpl");
901 print "<script language=\"JavaScript\">self.location.hash = '#image". $anchor ."';</script>\n";
903 } // showPhotoIndex()
906 * show credit template
908 public function showCredits()
910 $this->tmpl->assign('version', $this->cfg->version);
911 $this->tmpl->assign('product', $this->cfg->product);
912 $this->tmpl->show("credits.tpl");
917 * create_thumbnails for the requested width
919 * this function creates image thumbnails of $orig_image
920 * stored as $thumb_image. It will check if the image is
921 * in a supported format, if necessary rotate the image
922 * (based on EXIF orientation meta headers) and re-sizing.
924 public function create_thumbnail($orig_image, $thumb_image, $width)
926 if(!file_exists($orig_image)) {
930 $details = getimagesize($orig_image);
932 /* check if original photo is a support image type */
933 if(!$this->checkifImageSupported($details['mime']))
936 $meta = $this->get_meta_informations($orig_image);
941 switch($meta['Orientation']) {
943 case 1: /* top, left */
944 $rotate = 0; $flip = false; break;
945 case 2: /* top, right */
946 $rotate = 0; $flip = true; break;
947 case 3: /* bottom, left */
948 $rotate = 180; $flip = false; break;
949 case 4: /* bottom, right */
950 $rotate = 180; $flip = true; break;
951 case 5: /* left side, top */
952 $rotate = 90; $flip = true; break;
953 case 6: /* right side, top */
954 $rotate = 90; $flip = false; break;
955 case 7: /* left side, bottom */
956 $rotate = 270; $flip = true; break;
957 case 8: /* right side, bottom */
958 $rotate = 270; $flip = false; break;
961 $src_img = @imagecreatefromjpeg($orig_image);
964 print "Can't load image from ". $orig_image ."\n";
968 /* grabs the height and width */
969 $cur_width = imagesx($src_img);
970 $cur_height = imagesy($src_img);
972 // If requested width is more then the actual image width,
973 // do not generate a thumbnail, instead safe the original
974 // as thumbnail but with lower quality
976 if($width >= $cur_width) {
977 $result = imagejpeg($src_img, $thumb_image, 75);
978 imagedestroy($src_img);
982 // If the image will be rotate because EXIF orientation said so
983 // 'virtually rotate' the image for further calculations
984 if($rotate == 90 || $rotate == 270) {
986 $cur_width = $cur_height;
990 /* calculates aspect ratio */
991 $aspect_ratio = $cur_height / $cur_width;
994 if($aspect_ratio < 1) {
996 $new_h = abs($new_w * $aspect_ratio);
998 /* 'virtually' rotate the image and calculate it's ratio */
999 $tmp_w = $cur_height;
1000 $tmp_h = $cur_width;
1001 /* now get the ratio from the 'rotated' image */
1002 $tmp_ratio = $tmp_h/$tmp_w;
1003 /* now calculate the new dimensions */
1005 $tmp_h = abs($tmp_w * $tmp_ratio);
1007 // now that we know, how high they photo should be, if it
1008 // gets rotated, use this high to scale the image
1010 $new_w = abs($new_h / $aspect_ratio);
1012 // If the image will be rotate because EXIF orientation said so
1013 // now 'virtually rotate' back the image for the image manipulation
1014 if($rotate == 90 || $rotate == 270) {
1021 /* creates new image of that size */
1022 $dst_img = imagecreatetruecolor($new_w, $new_h);
1024 imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
1026 /* copies resized portion of original image into new image */
1027 imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, imagesx($src_img), imagesy($src_img));
1029 /* needs the image to be flipped horizontal? */
1033 for($x = 0; $x < $new_w; $x++) {
1034 imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
1039 $this->_debug("(ROTATE)");
1040 $dst_img = $this->rotateImage($dst_img, $rotate);
1043 /* write down new generated file */
1044 $result = imagejpeg($dst_img, $thumb_image, 75);
1046 /* free your mind */
1047 imagedestroy($dst_img);
1048 imagedestroy($src_img);
1050 if($result === false) {
1051 print "Can't write thumbnail ". $thumb_image ."\n";
1057 } // create_thumbnail()
1060 * return all exif meta data from the file
1062 public function get_meta_informations($file)
1064 return exif_read_data($file);
1066 } // get_meta_informations()
1069 * create phpfspot own sqlite database
1071 * this function creates phpfspots own sqlite database
1072 * if it does not exist yet. this own is used to store
1073 * some necessary informations (md5 sum's, ...).
1075 public function check_config_table()
1077 // if the config table doesn't exist yet, create it
1078 if(!$this->cfg_db->db_check_table_exists("images")) {
1079 $this->cfg_db->db_exec("
1080 CREATE TABLE images (
1081 img_idx int primary key,
1087 } // check_config_table
1090 * Generates a thumbnail from photo idx
1092 * This function will generate JPEG thumbnails from provided F-Spot photo
1095 * 1. Check if all thumbnail generations (width) are already in place and
1097 * 2. Check if the md5sum of the original file has changed
1098 * 3. Generate the thumbnails if needed
1100 public function gen_thumb($idx = 0, $force = 0)
1104 $resolutions = Array(
1105 $this->cfg->thumb_width,
1106 $this->cfg->photo_width,
1107 $this->cfg->mini_width,
1110 /* get details from F-Spot's database */
1111 $details = $this->get_photo_details($idx);
1113 /* calculate file MD5 sum */
1114 $full_path = $this->translate_path($details['directory_path']) ."/". $details['name'];
1116 if(!file_exists($full_path)) {
1117 $this->_error("File ". $full_path ." does not exist\n");
1121 if(!is_readable($full_path)) {
1122 $this->_error("File ". $full_path ." is not readable for ". $this->getuid() ."\n");
1126 $file_md5 = md5_file($full_path);
1128 $this->_debug("Image [". $idx ."] ". $details['name'] ." Thumbnails:");
1130 foreach($resolutions as $resolution) {
1132 $thumb_path = $this->cfg->base_path ."/thumbs/". $resolution ."_". $file_md5;
1134 /* if the thumbnail file doesn't exist, create it */
1135 if(!file_exists($thumb_path)) {
1137 $this->_debug(" ". $resolution ."px");
1138 if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
1141 /* if the file hasn't changed there is no need to regen the thumb */
1142 elseif($file_md5 != $this->getMD5($idx) || $force) {
1144 $this->_debug(" ". $resolution ."px");
1145 if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
1151 /* set the new/changed MD5 sum for the current photo */
1153 $this->setMD5($idx, $file_md5);
1156 $this->_debug("\n");
1161 * returns stored md5 sum for a specific photo
1163 * this function queries the phpfspot database for a
1164 * stored MD5 checksum of the specified photo
1166 public function getMD5($idx)
1168 $result = $this->cfg_db->db_query("
1171 WHERE img_idx='". $idx ."'
1177 $img = $this->cfg_db->db_fetch_object($result);
1178 return $img['img_md5'];
1183 * set MD5 sum for the specific photo
1185 private function setMD5($idx, $md5)
1187 $result = $this->cfg_db->db_exec("
1188 REPLACE INTO images (img_idx, img_md5)
1189 VALUES ('". $idx ."', '". $md5 ."')
1195 * store current tag condition
1197 * this function stores the current tag condition
1198 * (AND or OR) in the users session variables
1200 public function setTagCondition($mode)
1202 $_SESSION['tag_condition'] = $mode;
1204 } // setTagCondition()
1207 * invoke tag & date search
1209 * this function will return all matching tags and store
1210 * them in the session variable selected_tags. furthermore
1211 * it also handles the date search.
1212 * getPhotoSelection() will then only return the matching
1215 public function startSearch($searchfor, $sort_order, $from = 0, $to = 0)
1217 $_SESSION['searchfor'] = $searchfor;
1218 $_SESSION['sort_order'] = $sort_order;
1220 $_SESSION['from_date'] = strtotime($from);
1222 unset($_SESSION['from_date']);
1224 $_SESSION['to_date'] = strtotime($to);
1226 unset($_SESSION['to_date']);
1228 if($searchfor != "") {
1229 /* new search, reset the current selected tags */
1230 $_SESSION['selected_tags'] = Array();
1231 foreach($this->avail_tags as $tag) {
1232 if(preg_match('/'. $searchfor .'/i', $this->tags[$tag]))
1233 array_push($_SESSION['selected_tags'], $tag);
1242 * this function rotates the image according the
1245 private function rotateImage($img, $degrees)
1247 if(function_exists("imagerotate")) {
1248 $img = imagerotate($img, $degrees, 0);
1250 function imagerotate($src_img, $angle)
1252 $src_x = imagesx($src_img);
1253 $src_y = imagesy($src_img);
1254 if ($angle == 180) {
1258 elseif ($src_x <= $src_y) {
1262 elseif ($src_x >= $src_y) {
1267 $rotate=imagecreatetruecolor($dest_x,$dest_y);
1268 imagealphablending($rotate, false);
1273 for ($y = 0; $y < ($src_y); $y++) {
1274 for ($x = 0; $x < ($src_x); $x++) {
1275 $color = imagecolorat($src_img, $x, $y);
1276 imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
1282 for ($y = 0; $y < ($src_y); $y++) {
1283 for ($x = 0; $x < ($src_x); $x++) {
1284 $color = imagecolorat($src_img, $x, $y);
1285 imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
1291 for ($y = 0; $y < ($src_y); $y++) {
1292 for ($x = 0; $x < ($src_x); $x++) {
1293 $color = imagecolorat($src_img, $x, $y);
1294 imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
1308 $img = imagerotate($img, $degrees);
1317 * return all assigned tags for the specified photo
1319 private function get_photo_tags($idx)
1321 $result = $this->db->db_query("
1324 INNER JOIN photo_tags pt
1326 WHERE pt.photo_id='". $idx ."'
1331 while($row = $this->db->db_fetch_object($result))
1332 $tags[$row['id']] = $row['name'];
1336 } // get_photo_tags()
1339 * create on-the-fly images with text within
1341 public function showTextImage($txt, $color=000000, $space=4, $font=4, $w=300)
1343 if (strlen($color) != 6)
1346 $int = hexdec($color);
1347 $h = imagefontheight($font);
1348 $fw = imagefontwidth($font);
1349 $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
1350 $lines = count($txt);
1351 $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
1352 $bg = imagecolorallocate($im, 255, 255, 255);
1353 $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
1356 foreach ($txt as $text) {
1357 $x = (($w - ($fw * strlen($text))) / 2);
1358 imagestring($im, $font, $x, $y, $text, $color);
1359 $y += ($h + $space);
1362 Header("Content-type: image/png");
1365 } // showTextImage()
1368 * check if all requirements are met
1370 private function checkRequirements()
1372 if(!function_exists("imagecreatefromjpeg")) {
1373 print "PHP GD library extension is missing<br />\n";
1377 if(!function_exists("sqlite3_open")) {
1378 print "PHP SQLite3 library extension is missing<br />\n";
1382 /* Check for HTML_AJAX PEAR package, lent from Horde project */
1383 ini_set('track_errors', 1);
1384 @include_once 'HTML/AJAX/Server.php';
1385 if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1386 print "PEAR HTML_AJAX package is missing<br />\n";
1389 @include_once 'Calendar/Calendar.php';
1390 if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1391 print "PEAR Calendar package is missing<br />\n";
1394 ini_restore('track_errors');
1401 } // checkRequirements()
1403 private function _debug($text)
1405 if($this->fromcmd) {
1412 * check if specified MIME type is supported
1414 public function checkifImageSupported($mime)
1416 if(in_array($mime, Array("image/jpeg")))
1421 } // checkifImageSupported()
1423 public function _error($text)
1425 switch($this->cfg->logging) {
1427 print "<img src=\"resources/green_info.png\" alt=\"warning\" />\n";
1434 error_log($text, 3, $his->cfg->log_file);
1441 * output calendard input fields
1443 private function get_calendar($mode)
1445 $year = $_SESSION[$mode .'_date'] ? date("Y", strtotime($_SESSION[$mode .'_date'])) : date("Y");
1446 $month = $_SESSION[$mode .'_date'] ? date("m", strtotime($_SESSION[$mode .'_date'])) : date("m");
1447 $day = $_SESSION[$mode .'_date'] ? date("d", strtotime($_SESSION[$mode .'_date'])) : date("d");
1449 $output = "<input type=\"text\" size=\"3\" id=\"". $mode ."year\" value=\"". $year ."\"";
1450 if(!isset($_SESSION[$mode .'_date'])) $output.= " disabled=\"disabled\"";
1452 $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."month\" value=\"". $month ."\"";
1453 if(!isset($_SESSION[$mode .'_date'])) $output.= " disabled=\"disabled\"";
1455 $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."day\" value=\"". $day ."\"";
1456 if(!isset($_SESSION[$mode .'_date'])) $output.= " disabled=\"disabled\"";
1463 * output calendar matrix
1465 public function get_calendar_matrix($year = 0, $month = 0, $day = 0)
1467 if (!isset($year)) $year = date('Y');
1468 if (!isset($month)) $month = date('m');
1469 if (!isset($day)) $day = date('d');
1474 require_once CALENDAR_ROOT.'Month/Weekdays.php';
1475 require_once CALENDAR_ROOT.'Day.php';
1478 $month = new Calendar_Month_Weekdays($year,$month);
1481 $prevStamp = $month->prevMonth(true);
1482 $prev = "javascript:setMonth(". date('Y',$prevStamp) .", ". date('n',$prevStamp) .", ". date('j',$prevStamp) .");";
1483 $nextStamp = $month->nextMonth(true);
1484 $next = "javascript:setMonth(". date('Y',$nextStamp) .", ". date('n',$nextStamp) .", ". date('j',$nextStamp) .");";
1486 $selectedDays = array (
1487 new Calendar_Day($year,$month,$day),
1488 new Calendar_Day($year,12,25),
1491 // Build the days in the month
1492 $month->build($selectedDays);
1494 $this->tmpl->assign('current_month', date('F Y',$month->getTimeStamp()));
1495 $this->tmpl->assign('prev_month', $prev);
1496 $this->tmpl->assign('next_month', $next);
1498 while ( $day = $month->fetch() ) {
1500 if(!isset($matrix[$rows]))
1501 $matrix[$rows] = Array();
1505 $dayStamp = $day->thisDay(true);
1506 $link = "javascript:setCalendarDate(". date('Y',$dayStamp) .", ". date('n',$dayStamp).", ". date('j',$dayStamp) .");";
1508 // isFirst() to find start of week
1509 if ( $day->isFirst() )
1512 if ( $day->isSelected() ) {
1513 $string.= "<td class=\"selected\">".$day->thisDay()."</td>\n";
1514 } else if ( $day->isEmpty() ) {
1515 $string.= "<td> </td>\n";
1517 $string.= "<td><a class=\"calendar\" href=\"".$link."\">".$day->thisDay()."</a></td>\n";
1520 // isLast() to find end of week
1521 if ( $day->isLast() )
1522 $string.= "</tr>\n";
1524 $matrix[$rows][$cols] = $string;
1534 $this->tmpl->assign('matrix', $matrix);
1535 $this->tmpl->assign('rows', $rows);
1536 $this->tmpl->show("calendar.tpl");
1538 } // get_calendar_matrix()
1541 * output export page
1543 public function getExport($mode)
1545 $pictures = $this->getPhotoSelection();
1546 $current_tags = $this->getCurrentTags();
1548 if(!isset($_SERVER['HTTPS'])) $protocol = "http";
1549 else $protocol = "https";
1551 $server_name = $_SERVER['SERVER_NAME'];
1553 foreach($pictures as $picture) {
1555 $orig_url = $protocol ."://". $server_name . $this->cfg->web_path ."index.php?mode=showp&id=". $picture;
1556 if($current_tags != "") {
1557 $orig_url.= "&tags=". $current_tags;
1559 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
1560 $orig_url.= "&from_date=". $_SESSION['from_date'] ."&to_date=". $_SESSION['to_date'];
1563 $thumb_url = $protocol ."://". $server_name . $this->cfg->web_path ."phpfspot_img.php?idx=". $picture ."&width=". $this->cfg->thumb_width;
1568 // <a href="%pictureurl%"><img src="%thumbnailurl%" ></a>
1569 print htmlspecialchars("<a href=\"". $orig_url ."\"><img src=\"". $thumb_url ."\" /></a>") ."<br />\n";
1573 // "[%pictureurl% %thumbnailurl%]"
1574 print htmlspecialchars("[".$orig_url." ".$thumb_url."&fake=1.jpg]") ."<br />\n";
1577 case 'MoinMoinList':
1578 // " * [%pictureurl% %thumbnailurl%]"
1579 print " " . htmlspecialchars("* [".$orig_url." ".$thumb_url."&fake=1.jpg]") ."<br />\n";
1588 * return all selected tags as one string
1590 private function getCurrentTags()
1593 if($_SESSION['selected_tags'] != "") {
1594 foreach($_SESSION['selected_tags'] as $tag)
1595 $current_tags.= $tag .",";
1596 $current_tags = substr($current_tags, 0, strlen($current_tags)-1);
1598 return $current_tags;
1600 } // getCurrentTags()
1603 * return the current photo
1605 public function getCurrentPhoto()
1607 if(isset($_SESSION['current_photo'])) {
1608 print $_SESSION['current_photo'];
1610 } // getCurrentPhoto()
1613 * tells the client browser what to do
1615 * this function is getting called via AJAX by the
1616 * client browsers. it will tell them what they have
1617 * to do next. This is necessary for directly jumping
1618 * into photo index or single photo view when the are
1619 * requested with specific URLs
1621 public function whatToDo()
1623 if(isset($_SESSION['current_photo']) && $_SESSION['start_action'] == 'showp') {
1624 return "show_photo";
1626 elseif((isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) ||
1627 (isset($_SESSION['from_date']) && isset($_SESSION['to_date']))) {
1630 elseif(isset($_SESSION['start_action']) && $_SESSION['start_action'] == 'showpi') {
1634 return "nothing special";
1639 * return the current process-user
1641 private function getuid()
1643 if($uid = posix_getuid()) {
1644 if($user = posix_getpwuid($uid)) {
1645 return $user['name'];
1654 * returns a select-dropdown box to select photo index sort parameters
1656 private function get_sort_field()
1658 $output = "<select name=\"sort_order\">";
1659 foreach(array('date_asc', 'date_desc', 'name_asc', 'name_desc') as $sort_order) {
1660 $output.= "<option value=\"". $sort_order ."\"";
1661 if($sort_order == $_SESSION['sort_order']) {
1662 $output.= " selected=\"selected\"";
1664 $output.= ">". $sort_order ."</option>";
1666 $output.= "</select>";
1669 } // get_sort_field()
1672 * returns the currently selected sort order
1674 private function get_sort_order()
1676 switch($_SESSION['sort_order']) {
1678 return " ORDER BY p.time ASC";
1681 return " ORDER BY p.time DESC";
1684 return " ORDER BY p.name ASC";
1687 return " ORDER BY p.name DESC";
1691 } // get_sort_order()
1694 * return the next to be shown slide show image
1696 * this function returns the URL of the next image
1697 * in the slideshow sequence.
1699 public function getNextSlideShowImage()
1701 $all_photos = $this->getPhotoSelection();
1703 if(!isset($_SESSION['slideshow_img']) || $_SESSION['slideshow_img'] == count($all_photos)-1)
1704 $_SESSION['slideshow_img'] = 0;
1706 $_SESSION['slideshow_img']++;
1708 $server_name = $_SERVER['SERVER_NAME'];
1709 if(!isset($_SERVER['HTTPS'])) $protocol = "http";
1710 else $protocol = "https";
1712 return $protocol ."://". $server_name . $this->cfg->web_path ."phpfspot_img.php?idx=". $all_photos[$_SESSION['slideshow_img']] ."&width=". $this->cfg->photo_width;
1714 } // getNextSlideShowImage()
1717 * return the previous to be shown slide show image
1719 * this function returns the URL of the previous image
1720 * in the slideshow sequence.
1722 public function getPrevSlideShowImage()
1724 $all_photos = $this->getPhotoSelection();
1726 if(!isset($_SESSION['slideshow_img']) || $_SESSION['slideshow_img'] == 0)
1727 $_SESSION['slideshow_img'] = 0;
1729 $_SESSION['slideshow_img']--;
1731 $server_name = $_SERVER['SERVER_NAME'];
1732 if(!isset($_SERVER['HTTPS'])) $protocol = "http";
1733 else $protocol = "https";
1735 return $protocol ."://". $server_name . $this->cfg->web_path ."phpfspot_img.php?idx=". $all_photos[$_SESSION['slideshow_img']] ."&width=". $this->cfg->photo_width;
1737 } // getPrevSlideShowImage()
1739 public function resetSlideShow()
1741 if(isset($_SESSION['slideshow_img']))
1742 unset($_SESSION['slideshow_img']);
1743 } // resetSlideShow()
1748 * this function will get all photos from the fspot
1749 * database and randomly return ONE entry
1751 * saddly there is yet no sqlite3 function which returns
1752 * the bulk result in array, so we have to fill up our
1755 public function get_random_photo()
1759 $result = $this->db->db_query("
1764 while($row = $this->db->db_fetch_object($result)) {
1765 array_push($all, $row['id']);
1768 return $all[array_rand($all)];
1770 } // get_random_photo()
1773 * validates provided date
1775 * this function validates if the provided date
1776 * contains a valid date and will return true
1779 public function isValidDate($date_str)
1781 $timestamp = strtotime($date_str);
1783 if(is_numeric($timestamp))
1791 * timestamp to string conversion
1793 private function ts2str($timestamp)
1795 return strftime("%Y-%m-%d", $timestamp);
1798 private function extractTags($tags_str)
1800 $not_validated = split(',', $_GET['tags']);
1801 $validated = array();
1803 foreach($not_validated as $tag) {
1804 if(is_numeric($tag))
1805 array_push($validated, $tag);