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 $this->check_config_table();
63 $this->tmpl = new PHPFSPOT_TMPL($this);
69 if(!isset($_SESSION['tag_condition']))
70 $_SESSION['tag_condition'] = 'or';
72 if(!isset($_SESSION['searchfor']))
73 $_SESSION['searchfor'] = '';
75 // if begin_with is still set but rows_per_page is now 0, unset it
76 if(isset($_SESSION['begin_with']) && $this->cfg->rows_per_page == 0)
77 unset($_SESSION['begin_with']);
81 public function __destruct()
87 * show - generate html output
89 * this function can be called after the constructor has
90 * prepared everyhing. it will load the index.tpl smarty
91 * template. if necessary it will registere pre-selects
92 * (photo index, photo, tag search, date search) into
95 public function show()
97 $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
98 $this->tmpl->assign('page_title', $this->cfg->page_title);
99 $this->tmpl->assign('current_condition', $_SESSION['tag_condition']);
101 $_SESSION['start_action'] = $_GET['mode'];
103 switch($_GET['mode']) {
105 if(isset($_GET['tags'])) {
106 $_SESSION['selected_tags'] = split(',', $_GET['tags']);
108 if(isset($_GET['from_date'])) {
109 $_SESSION['from_date'] = $_GET['from_date'];
111 if(isset($_GET['to_date'])) {
112 $_SESSION['to_date'] = $_GET['to_date'];
116 if(isset($_GET['tags'])) {
117 $_SESSION['selected_tags'] = split(',', $_GET['tags']);
118 $_SESSION['start_action'] = 'showp';
120 if(isset($_GET['id'])) {
121 $_SESSION['current_photo'] = $_GET['id'];
122 $_SESSION['start_action'] = 'showp';
124 if(isset($_GET['from_date'])) {
125 $_SESSION['from_date'] = $_GET['from_date'];
127 if(isset($_GET['to_date'])) {
128 $_SESSION['to_date'] = $_GET['to_date'];
132 $this->tmpl->show("export.tpl");
137 $this->tmpl->assign('from_date', $this->get_calendar('from'));
138 $this->tmpl->assign('to_date', $this->get_calendar('to'));
139 $this->tmpl->assign('content_page', 'welcome.tpl');
140 $this->tmpl->show("index.tpl");
146 * get_tags - grab all tags of f-spot's database
148 * this function will get all available tags from
149 * the f-spot database and store them within two
150 * arrays within this clase for later usage. in
151 * fact, if the user requests (hide_tags) it will
152 * opt-out some of them.
154 * this function is getting called once by show()
156 private function get_tags()
158 $this->avail_tags = Array();
161 $result = $this->db->db_query("
164 ORDER BY sort_priority ASC
167 while($row = $this->db->db_fetch_object($result)) {
169 $tag_id = $row['id'];
170 $tag_name = $row['name'];
172 /* check if config requests to ignore this tag */
173 if(in_array($row['name'], $this->cfg->hide_tags))
176 $this->tags[$tag_id] = $tag_name;
177 $this->avail_tags[$count] = $tag_id;
186 * extract all photo details
188 * retrieve all available details from f-spot's
189 * database and return them as object
191 public function get_photo_details($idx)
193 $result = $this->db->db_query("
196 WHERE id='". $idx ."'
199 return $this->db->db_fetch_object($result);
201 } // get_photo_details
204 * returns aligned photo names
206 * this function returns aligned (length) names for
207 * an specific photo. If the length of the name exceeds
208 * $limit the name will be shrinked (...)
210 public function getPhotoName($idx, $limit = 0)
212 if($details = $this->get_photo_details($idx)) {
213 $name = $details['name'];
214 if($limit != 0 && strlen($name) > $limit) {
215 $name = substr($name, 0, $limit-5) ."...". substr($name, -($limit-5));
223 * translate f-spoth photo path
225 * as the full-qualified path recorded in the f-spot database
226 * is usally not the same as on the webserver, this function
227 * will replace the path with that one specified in the cfg
229 public function translate_path($path, $width = 0)
231 return str_replace($this->cfg->path_replace_from, $this->cfg->path_replace_to, $path);
236 * control HTML ouput for a single photo
238 * this function provides all the necessary information
239 * for the single photo template.
241 public function showPhoto($photo)
243 /* get all photos from the current photo selection */
244 $all_photos = $this->getPhotoSelection();
245 $count = count($all_photos);
247 for($i = 0; $i < $count; $i++) {
249 // $get_next will be set, when the photo which has to
250 // be displayed has been found - this means that the
251 // next available is in fact the NEXT image (for the
253 if(isset($get_next)) {
254 $next_img = $all_photos[$i];
258 /* the next photo is our NEXT photo */
259 if($all_photos[$i] == $photo) {
263 $previous_img = $all_photos[$i];
266 if($photo == $all_photos[$i]) {
271 $details = $this->get_photo_details($photo);
278 $orig_path = $this->translate_path($details['directory_path']) ."/". $details['name'];
279 $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->photo_width ."_". $this->getMD5($photo);
281 if(!file_exists($orig_path)) {
282 $this->_warning("Photo ". $orig_path ." does not exist!<br />\n");
285 if(!is_readable($orig_path)) {
286 $this->_warning("Photo ". $orig_path ." is not readable for user ". $this->getuid() ."<br />\n");
289 /* If the thumbnail doesn't exist yet, try to create it */
290 if(!file_exists($thumb_path)) {
291 $this->gen_thumb($photo, true);
292 $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->photo_width ."_". $this->getMD5($photo);
295 /* get f-spot database meta information */
296 $meta = $this->get_meta_informations($orig_path);
298 /* If EXIF data are available, use them */
299 if(isset($meta['ExifImageWidth'])) {
300 $meta_res = $meta['ExifImageWidth'] ."x". $meta['ExifImageLength'];
302 $info = getimagesize($orig_path);
303 $meta_res = $info[0] ."x". $info[1];
306 $meta_date = isset($meta['FileDateTime']) ? strftime("%a %x %X", $meta['FileDateTime']) : "n/a";
307 $meta_make = isset($meta['Make']) ? $meta['Make'] ." ". $meta['Model'] : "n/a";
308 $meta_size = isset($meta['FileSize']) ? round($meta['FileSize']/1024, 1) ."kbyte" : "n/a";
310 $extern_link = "index.php?mode=showp&id=". $photo;
311 $current_tags = $this->getCurrentTags();
312 if($current_tags != "") {
313 $extern_link.= "&tags=". $current_tags;
315 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
316 $extern_link.= "&from_date=". $_SESSION['from_date'] ."&to_date=". $_SESSION['to_date'];
319 $this->tmpl->assign('extern_link', $extern_link);
321 if(file_exists($thumb_path)) {
323 $info = getimagesize($thumb_path);
325 $this->tmpl->assign('description', $details['description']);
326 $this->tmpl->assign('image_name', $details['name']);
328 $this->tmpl->assign('width', $info[0]);
329 $this->tmpl->assign('height', $info[1]);
330 $this->tmpl->assign('ExifMadeOn', $meta_date);
331 $this->tmpl->assign('ExifMadeWith', $meta_make);
332 $this->tmpl->assign('ExifOrigResolution', $meta_res);
333 $this->tmpl->assign('ExifFileSize', $meta_size);
335 $this->tmpl->assign('image_url', 'phpfspot_img.php?idx='. $photo ."&width=". $this->cfg->photo_width);
336 $this->tmpl->assign('image_url_full', 'phpfspot_img.php?idx='. $photo);
338 $this->tmpl->assign('tags', $this->get_photo_tags($photo));
339 $this->tmpl->assign('current', $current);
342 $this->_warning("Can't open file ". $thumb_path ."\n");
347 $this->tmpl->assign('previous_url', "javascript:showImage(". $previous_img .");");
348 $this->tmpl->assign('prev_img', $previous_img);
352 $this->tmpl->assign('next_url', "javascript:showImage(". $next_img .");");
353 $this->tmpl->assign('next_img', $next_img);
355 $this->tmpl->assign('mini_width', $this->cfg->mini_width);
357 $this->tmpl->show("single_photo.tpl");
362 * all available tags and tag cloud
364 * this function outputs all available tags (time ordered)
365 * and in addition output them as tag cloud (tags which have
366 * many photos will appears more then others)
368 public function getAvailableTags()
372 $result = $this->db->db_query("
373 SELECT tag_id as id, count(tag_id) as quantity
383 while($row = $this->db->db_fetch_object($result)) {
384 $tags[$row['id']] = $row['quantity'];
387 // change these font sizes if you will
388 $max_size = 125; // max font size in %
389 $min_size = 75; // min font size in %
391 // get the largest and smallest array values
392 $max_qty = max(array_values($tags));
393 $min_qty = min(array_values($tags));
395 // find the range of values
396 $spread = $max_qty - $min_qty;
397 if (0 == $spread) { // we don't want to divide by zero
401 // determine the font-size increment
402 // this is the increase per tag quantity (times used)
403 $step = ($max_size - $min_size)/($spread);
405 // loop through our tag array
406 foreach ($tags as $key => $value) {
408 if(isset($_SESSION['selected_tags']) && in_array($key, $_SESSION['selected_tags']))
411 // calculate CSS font-size
412 // find the $value in excess of $min_qty
413 // multiply by the font-size increment ($size)
414 // and add the $min_size set above
415 $size = $min_size + (($value - $min_qty) * $step);
416 // uncomment if you want sizes in whole %:
419 $output.= "<a href=\"javascript:Tags('add', ". $key .");\" class=\"tag\" style=\"font-size: ". $size ."%;\">". $this->tags[$key] ."</a>, ";
423 $output = substr($output, 0, strlen($output)-2);
426 } // getAvailableTags()
429 * output all selected tags
431 * this function output all tags which have been selected
432 * by the user. the selected tags are stored in the
433 * session-variable $_SESSION['selected_tags']
435 public function getSelectedTags()
438 foreach($this->avail_tags as $tag)
440 // return all selected tags
441 if(isset($_SESSION['selected_tags']) && in_array($tag, $_SESSION['selected_tags'])) {
442 $output.= "<a href=\"javascript:Tags('del', ". $tag .");\" class=\"tag\">". $this->tags[$tag] ."</a>, ";
446 $output = substr($output, 0, strlen($output)-2);
449 } // getSelectedTags()
452 * add tag to users session variable
454 * this function will add the specified to users current
455 * tag selection. if a date search has been made before
456 * it will be now cleared
458 public function addTag($tag)
460 // if the result of a date search are displayed, reset them
461 $this->resetDateSearch();
463 if(!isset($_SESSION['selected_tags']))
464 $_SESSION['selected_tags'] = Array();
466 if(!in_array($tag, $_SESSION['selected_tags']))
467 array_push($_SESSION['selected_tags'], $tag);
472 * remove tag to users session variable
474 * this function removes the specified tag from
475 * users current tag selection
477 public function delTag($tag)
479 if(isset($_SESSION['selected_tags'])) {
480 $key = array_search($tag, $_SESSION['selected_tags']);
481 unset($_SESSION['selected_tags'][$key]);
482 sort($_SESSION['selected_tags']);
488 * reset tag selection
490 * if there is any tag selection, it will be
493 public function resetTags()
495 if(isset($_SESSION['selected_tags']))
496 unset($_SESSION['selected_tags']);
503 * if a specific photo was requested (external link)
504 * unset the session variable now
506 public function resetPhotoView()
508 if(isset($_SESSION['current_photo']))
509 unset($_SESSION['current_photo']);
511 } // resetPhotoView();
516 * if any tag search has taken place, reset
519 public function resetTagSearch()
521 if(isset($_SESSION['searchfor']))
522 unset($_SESSION['searchfor']);
524 } // resetTagSearch()
529 * if any date search has taken place, reset
532 public function resetDateSearch()
534 if(isset($_SESSION['from_date']))
535 unset($_SESSION['from_date']);
536 if(isset($_SESSION['to_date']))
537 unset($_SESSION['to_date']);
539 } // resetDateSearch();
542 * return all photo according selection
544 * this function returns all photos based on
545 * the tag-selection, tag- or date-search.
546 * the tag-search also has to take care of AND
547 * and OR conjunctions
549 public function getPhotoSelection()
551 $matched_photos = Array();
553 /* return a search result */
554 if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '') {
555 $result = $this->db->db_query("
556 SELECT DISTINCT photo_id
562 WHERE t.name LIKE '%". $_SESSION['searchfor'] ."%'
565 while($row = $this->db->db_fetch_object($result)) {
566 array_push($matched_photos, $row['photo_id']);
568 return $matched_photos;
571 /* return according the selected tags */
572 if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
574 foreach($_SESSION['selected_tags'] as $tag)
575 $selected.= $tag .",";
576 $selected = substr($selected, 0, strlen($selected)-1);
578 if($_SESSION['tag_condition'] == 'or') {
579 $result = $this->db->db_query("
580 SELECT DISTINCT photo_id
584 WHERE pt.tag_id IN (". $selected .")
588 elseif($_SESSION['tag_condition'] == 'and') {
590 if(count($_SESSION['selected_tags']) >= 32) {
591 print "A SQLite limit of 32 tables within a JOIN SELECT avoids to<br />\n";
592 print "evaluate your tag selection. Please remove some tags from your selection.\n";
596 /* Join together a table looking like
598 pt1.photo_id pt1.tag_id pt2.photo_id pt2.tag_id ...
600 so the query can quickly return all images matching the
601 selected tags in an AND condition
606 SELECT DISTINCT pt1.photo_id
610 for($i = 0; $i < count($_SESSION['selected_tags']); $i++) {
612 INNER JOIN photo_tags pt". ($i+2) ."
613 ON pt1.photo_id=pt". ($i+2) .".photo_id
616 $query_str.= "WHERE pt1.tag_id=". $_SESSION['selected_tags'][0];
617 for($i = 1; $i < count($_SESSION['selected_tags']); $i++) {
619 AND pt". ($i+1) .".tag_id=". $_SESSION['selected_tags'][$i] ."
622 $result = $this->db->db_query($query_str);
625 while($row = $this->db->db_fetch_object($result)) {
626 array_push($matched_photos, $row['photo_id']);
628 return $matched_photos;
631 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
632 $from_date = strtotime($_SESSION['from_date']);
633 $to_date = strtotime($_SESSION['to_date']);
634 $result = $this->db->db_query("
635 SELECT DISTINCT photo_id
640 time>='". $from_date ."'
642 time<='". $to_date ."'
645 while($row = $this->db->db_fetch_object($result)) {
646 array_push($matched_photos, $row['photo_id']);
648 return $matched_photos;
651 /* return all available photos */
652 $result = $this->db->db_query("
653 SELECT DISTINCT photo_id
659 while($row = $this->db->db_fetch_object($result)) {
660 array_push($matched_photos, $row['photo_id']);
662 return $matched_photos;
664 } // getPhotoSelection()
667 * control HTML ouput for photo index
669 * this function provides all the necessary information
670 * for the photo index template.
672 public function showPhotoIndex()
674 $photos = $this->getPhotoSelection();
676 $count = count($photos);
678 if(isset($_SESSION['begin_with']) && $_SESSION['begin_with'] != "")
679 $anchor = $_SESSION['begin_with'];
681 if(!isset($this->cfg->rows_per_page) || $this->cfg->rows_per_page == 0) {
687 elseif($this->cfg->rows_per_page > 0) {
689 if(!$_SESSION['begin_with'] || $_SESSION['begin_with'] == 0)
693 $begin_with = $_SESSION['begin_with'];
695 // verify $begin_with - perhaps the thumbs-per-rows or
696 // rows-per-page variables have changed or the jump back
697 // from a photo wasn't exact - so calculate the real new
699 $multiplicator = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
700 for($i = 0; $i <= $count; $i+=$multiplicator) {
701 if($begin_with >= $i && $begin_with < $i+$multiplicator) {
708 $end_with = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
714 $images[$rows] = Array();
715 $img_height[$rows] = Array();
716 $img_width[$rows] = Array();
717 $img_id[$rows] = Array();
718 $img_name[$rows] = Array();
719 $img_title = Array();
721 for($i = $begin_with; $i < $end_with; $i++) {
723 $images[$rows][$cols] = $photos[$i];
724 $img_id[$rows][$cols] = $i;
725 $img_name[$rows][$cols] = htmlspecialchars($this->getPhotoName($photos[$i], 15));
726 $img_title[$rows][$cols] = "Click to view photo ". htmlspecialchars($this->getPhotoName($photos[$i], 0));
728 $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->thumb_width ."_". $this->getMD5($photos[$i]);
730 if(file_exists($thumb_path)) {
731 $info = getimagesize($thumb_path);
732 $img_width[$rows][$cols] = $info[0];
733 $img_height[$rows][$cols] = $info[1];
736 if($cols == $this->cfg->thumbs_per_row-1) {
739 $images[$rows] = Array();
740 $img_width[$rows] = Array();
741 $img_height[$rows] = Array();
748 // +1 for for smarty's selection iteration
751 if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
752 $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
754 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
755 $this->tmpl->assign('from_date', $_SESSION['from_date']);
756 $this->tmpl->assign('to_date', $_SESSION['to_date']);
759 if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
760 $this->tmpl->assign('tag_result', 1);
763 /* do we have to display the page selector ? */
764 if($this->cfg->rows_per_page != 0) {
766 /* calculate the page switchers */
767 $previous_start = $begin_with - ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
768 $next_start = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
771 $this->tmpl->assign("previous_url", "javascript:showPhotoIndex(". $previous_start .");");
772 if($end_with < $count)
773 $this->tmpl->assign("next_url", "javascript:showPhotoIndex(". $next_start .");");
775 $photo_per_page = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
776 $last_page = ceil($count / $photo_per_page);
778 /* get the current selected page */
779 if($begin_with == 0) {
783 for($i = $begin_with; $i >= 0; $i-=$photo_per_page) {
788 for($i = 1; $i <= $last_page; $i++) {
790 if($current_page == $i)
791 $style = "style=\"font-size: 125%;\"";
792 elseif($current_page-1 == $i || $current_page+1 == $i)
793 $style = "style=\"font-size: 105%;\"";
794 elseif(($current_page-5 >= $i) && ($i != 1) ||
795 ($current_page+5 <= $i) && ($i != $last_page))
796 $style = "style=\"font-size: 75%;\"";
800 $select = "<a href=\"javascript:showPhotoIndex(". (($i*$photo_per_page)-$photo_per_page) .");\"";
803 $select.= ">". $i ."</a> ";
805 // until 9 pages we show the selector from 1-9
806 if($last_page <= 9) {
807 $page_select.= $select;
810 if($i == 1 /* first page */ ||
811 $i == $last_page /* last page */ ||
812 $i == $current_page /* current page */ ||
813 $i == ceil($last_page * 0.25) /* first quater */ ||
814 $i == ceil($last_page * 0.5) /* half */ ||
815 $i == ceil($last_page * 0.75) /* third quater */ ||
816 (in_array($i, array(1,2,3,4,5,6)) && $current_page <= 4) /* the first 6 */ ||
817 (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 */ ||
818 $i == $current_page-3 || $i == $current_page-2 || $i == $current_page-1 /* three before */ ||
819 $i == $current_page+3 || $i == $current_page+2 || $i == $current_page+1 /* three after */) {
821 $page_select.= $select;
830 /* only show the page selector if we have more then one page */
832 $this->tmpl->assign('page_selector', $page_select);
836 $current_tags = $this->getCurrentTags();
837 $extern_link = "index.php?mode=showpi";
838 if($current_tags != "") {
839 $extern_link.= "&tags=". $current_tags;
841 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
842 $extern_link.= "&from_date=". $_SESSION['from_date'] ."&to_date=". $_SESSION['to_date'];
845 $export_link = "index.php?mode=export";
847 $this->tmpl->assign('extern_link', $extern_link);
848 $this->tmpl->assign('export_link', $export_link);
849 $this->tmpl->assign('count', $count);
850 $this->tmpl->assign('width', $this->cfg->thumb_width);
851 $this->tmpl->assign('images', $images);
852 $this->tmpl->assign('img_width', $img_width);
853 $this->tmpl->assign('img_height', $img_height);
854 $this->tmpl->assign('img_id', $img_id);
855 $this->tmpl->assign('img_name', $img_name);
856 $this->tmpl->assign('img_title', $img_title);
857 $this->tmpl->assign('rows', $rows);
858 $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
860 $this->tmpl->show("photo_index.tpl");
863 print "<script language=\"JavaScript\">self.location.hash = '#image". $anchor ."';</script>\n";
865 } // showPhotoIndex()
868 * show credit template
870 public function showCredits()
872 $this->tmpl->assign('version', $this->cfg->version);
873 $this->tmpl->assign('product', $this->cfg->product);
874 $this->tmpl->show("credits.tpl");
879 * create_thumbnails for the requested width
881 * this function creates image thumbnails of $orig_image
882 * stored as $thumb_image. It will check if the image is
883 * in a supported format, if necessary rotate the image
884 * (based on EXIF orientation meta headers) and re-sizing.
886 public function create_thumbnail($orig_image, $thumb_image, $width)
888 if(!file_exists($orig_image)) {
892 $details = getimagesize($orig_image);
894 /* check if original photo is a support image type */
895 if(!$this->checkifImageSupported($details['mime']))
898 $meta = $this->get_meta_informations($orig_image);
903 switch($meta['Orientation']) {
905 case 1: /* top, left */
906 $rotate = 0; $flip = false; break;
907 case 2: /* top, right */
908 $rotate = 0; $flip = true; break;
909 case 3: /* bottom, left */
910 $rotate = 180; $flip = false; break;
911 case 4: /* bottom, right */
912 $rotate = 180; $flip = true; break;
913 case 5: /* left side, top */
914 $rotate = 90; $flip = true; break;
915 case 6: /* right side, top */
916 $rotate = 90; $flip = false; break;
917 case 7: /* left side, bottom */
918 $rotate = 270; $flip = true; break;
919 case 8: /* right side, bottom */
920 $rotate = 270; $flip = false; break;
923 $src_img = @imagecreatefromjpeg($orig_image);
926 print "Can't load image from ". $orig_image ."\n";
930 /* grabs the height and width */
931 $cur_width = imagesx($src_img);
932 $cur_height = imagesy($src_img);
934 // If requested width is more then the actual image width,
935 // do not generate a thumbnail, instead safe the original
936 // as thumbnail but with lower quality
938 if($width >= $cur_width) {
939 $result = imagejpeg($src_img, $thumb_image, 75);
940 imagedestroy($src_img);
944 // If the image will be rotate because EXIF orientation said so
945 // 'virtually rotate' the image for further calculations
946 if($rotate == 90 || $rotate == 270) {
948 $cur_width = $cur_height;
952 /* calculates aspect ratio */
953 $aspect_ratio = $cur_height / $cur_width;
956 if($aspect_ratio < 1) {
958 $new_h = abs($new_w * $aspect_ratio);
960 /* 'virtually' rotate the image and calculate it's ratio */
961 $tmp_w = $cur_height;
963 /* now get the ratio from the 'rotated' image */
964 $tmp_ratio = $tmp_h/$tmp_w;
965 /* now calculate the new dimensions */
967 $tmp_h = abs($tmp_w * $tmp_ratio);
969 // now that we know, how high they photo should be, if it
970 // gets rotated, use this high to scale the image
972 $new_w = abs($new_h / $aspect_ratio);
974 // If the image will be rotate because EXIF orientation said so
975 // now 'virtually rotate' back the image for the image manipulation
976 if($rotate == 90 || $rotate == 270) {
983 /* creates new image of that size */
984 $dst_img = imagecreatetruecolor($new_w, $new_h);
986 imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
988 /* copies resized portion of original image into new image */
989 imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, imagesx($src_img), imagesy($src_img));
991 /* needs the image to be flipped horizontal? */
995 for($x = 0; $x < $new_w; $x++) {
996 imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
1001 $this->_debug("(ROTATE)");
1002 $dst_img = $this->rotateImage($dst_img, $rotate);
1005 /* write down new generated file */
1006 $result = imagejpeg($dst_img, $thumb_image, 75);
1008 /* free your mind */
1009 imagedestroy($dst_img);
1010 imagedestroy($src_img);
1012 if($result === false) {
1013 print "Can't write thumbnail ". $thumb_image ."\n";
1019 } // create_thumbnail()
1022 * return all exif meta data from the file
1024 public function get_meta_informations($file)
1026 return exif_read_data($file);
1028 } // get_meta_informations()
1031 * create phpfspot own sqlite database
1033 * this function creates phpfspots own sqlite database
1034 * if it does not exist yet. this own is used to store
1035 * some necessary informations (md5 sum's, ...).
1037 public function check_config_table()
1039 // if the config table doesn't exist yet, create it
1040 if(!$this->cfg_db->db_check_table_exists("images")) {
1041 $this->cfg_db->db_exec("
1042 CREATE TABLE images (
1043 img_idx int primary key,
1049 } // check_config_table
1052 * Generates a thumbnail from photo idx
1054 * This function will generate JPEG thumbnails from provided F-Spot photo
1057 * 1. Check if all thumbnail generations (width) are already in place and
1059 * 2. Check if the md5sum of the original file has changed
1060 * 3. Generate the thumbnails if needed
1062 public function gen_thumb($idx = 0, $force = 0)
1066 $resolutions = Array(
1067 $this->cfg->thumb_width,
1068 $this->cfg->photo_width,
1069 $this->cfg->mini_width,
1072 /* get details from F-Spot's database */
1073 $details = $this->get_photo_details($idx);
1075 /* calculate file MD5 sum */
1076 $full_path = $this->translate_path($details['directory_path']) ."/". $details['name'];
1078 if(!file_exists($full_path)) {
1079 $this->_warning("File ". $full_path ." does not exist\n");
1083 if(!is_readable($full_path)) {
1084 $this->_warning("File ". $full_path ." is not readable for ". $this->getuid() ."\n");
1088 $file_md5 = md5_file($full_path);
1090 $this->_debug("Image [". $idx ."] ". $details['name'] ." Thumbnails:");
1092 foreach($resolutions as $resolution) {
1094 $thumb_path = $this->cfg->base_path ."/thumbs/". $resolution ."_". $file_md5;
1096 /* if the thumbnail file doesn't exist, create it */
1097 if(!file_exists($thumb_path)) {
1099 $this->_debug(" ". $resolution ."px");
1100 if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
1103 /* if the file hasn't changed there is no need to regen the thumb */
1104 elseif($file_md5 != $this->getMD5($idx) || $force) {
1106 $this->_debug(" ". $resolution ."px");
1107 if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
1113 /* set the new/changed MD5 sum for the current photo */
1115 $this->setMD5($idx, $file_md5);
1118 $this->_debug("\n");
1123 * returns stored md5 sum for a specific photo
1125 * this function queries the phpfspot database for a
1126 * stored MD5 checksum of the specified photo
1128 public function getMD5($idx)
1130 $result = $this->cfg_db->db_query("
1133 WHERE img_idx='". $idx ."'
1139 $img = $this->cfg_db->db_fetch_object($result);
1140 return $img['img_md5'];
1145 * set MD5 sum for the specific photo
1147 private function setMD5($idx, $md5)
1149 $result = $this->cfg_db->db_exec("
1150 REPLACE INTO images (img_idx, img_md5)
1151 VALUES ('". $idx ."', '". $md5 ."')
1157 * store current tag condition
1159 * this function stores the current tag condition
1160 * (AND or OR) in the users session variables
1162 public function setTagCondition($mode)
1164 $_SESSION['tag_condition'] = $mode;
1166 } // setTagCondition()
1171 * this function will return all matching tags and store
1172 * them in the session variable selected_tags.
1173 * getPhotoSelection() will then only return the matching
1176 public function startTagSearch($searchfor)
1178 $_SESSION['searchfor'] = $searchfor;
1179 $_SESSION['selected_tags'] = Array();
1181 foreach($this->avail_tags as $tag) {
1182 if(preg_match('/'. $searchfor .'/i', $this->tags[$tag]))
1183 array_push($_SESSION['selected_tags'], $tag);
1186 $this->resetDateSearch();
1188 } // startTagSearch()
1191 * invoke date search
1193 * this function in fact does nothing then only setting
1194 * the from- and to-date in the users session variables.
1195 * the result is generated by getPhotoSelection().
1197 public function startDateSearch($from, $to)
1199 $_SESSION['from_date'] = $from;
1200 $_SESSION['to_date'] = $to;
1206 * this function rotates the image according the
1209 private function rotateImage($img, $degrees)
1211 if(function_exists("imagerotate")) {
1212 $img = imagerotate($img, $degrees, 0);
1214 function imagerotate($src_img, $angle)
1216 $src_x = imagesx($src_img);
1217 $src_y = imagesy($src_img);
1218 if ($angle == 180) {
1222 elseif ($src_x <= $src_y) {
1226 elseif ($src_x >= $src_y) {
1231 $rotate=imagecreatetruecolor($dest_x,$dest_y);
1232 imagealphablending($rotate, false);
1237 for ($y = 0; $y < ($src_y); $y++) {
1238 for ($x = 0; $x < ($src_x); $x++) {
1239 $color = imagecolorat($src_img, $x, $y);
1240 imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
1246 for ($y = 0; $y < ($src_y); $y++) {
1247 for ($x = 0; $x < ($src_x); $x++) {
1248 $color = imagecolorat($src_img, $x, $y);
1249 imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
1255 for ($y = 0; $y < ($src_y); $y++) {
1256 for ($x = 0; $x < ($src_x); $x++) {
1257 $color = imagecolorat($src_img, $x, $y);
1258 imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
1272 $img = imagerotate($img, $degrees);
1281 * return all assigned tags for the specified photo
1283 private function get_photo_tags($idx)
1285 $result = $this->db->db_query("
1288 INNER JOIN photo_tags pt
1290 WHERE pt.photo_id='". $idx ."'
1295 while($row = $this->db->db_fetch_object($result))
1296 $tags[$row['id']] = $row['name'];
1300 } // get_photo_tags()
1303 * create on-the-fly images with text within
1305 public function showTextImage($txt, $color=000000, $space=4, $font=4, $w=300)
1307 if (strlen($color) != 6)
1310 $int = hexdec($color);
1311 $h = imagefontheight($font);
1312 $fw = imagefontwidth($font);
1313 $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
1314 $lines = count($txt);
1315 $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
1316 $bg = imagecolorallocate($im, 255, 255, 255);
1317 $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
1320 foreach ($txt as $text) {
1321 $x = (($w - ($fw * strlen($text))) / 2);
1322 imagestring($im, $font, $x, $y, $text, $color);
1323 $y += ($h + $space);
1326 Header("Content-type: image/png");
1329 } // showTextImage()
1332 * check if all requirements are met
1334 private function checkRequirements()
1336 if(!function_exists("imagecreatefromjpeg")) {
1337 print "PHP GD library extension is missing<br />\n";
1341 if(!function_exists("sqlite3_open")) {
1342 print "PHP SQLite3 library extension is missing<br />\n";
1346 /* Check for HTML_AJAX PEAR package, lent from Horde project */
1347 ini_set('track_errors', 1);
1348 @include_once 'HTML/AJAX/Server.php';
1349 if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1350 print "PEAR HTML_AJAX package is missing<br />\n";
1353 @include_once 'Calendar/Calendar.php';
1354 if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1355 print "PEAR Calendar package is missing<br />\n";
1358 ini_restore('track_errors');
1365 } // checkRequirements()
1367 private function _debug($text)
1369 if($this->fromcmd) {
1376 * check if specified MIME type is supported
1378 public function checkifImageSupported($mime)
1380 if(in_array($mime, Array("image/jpeg")))
1385 } // checkifImageSupported()
1387 public function _warning($text)
1389 print "<img src=\"resources/green_info.png\" alt=\"warning\" />\n";
1395 * output calendard input fields
1397 private function get_calendar($mode)
1399 $year = $_SESSION[$mode .'_date'] ? date("Y", strtotime($_SESSION[$mode .'_date'])) : date("Y");
1400 $month = $_SESSION[$mode .'_date'] ? date("m", strtotime($_SESSION[$mode .'_date'])) : date("m");
1401 $day = $_SESSION[$mode .'_date'] ? date("d", strtotime($_SESSION[$mode .'_date'])) : date("d");
1403 $output = "<input type=\"text\" size=\"3\" id=\"". $mode ."year\" value=\"". $year ."\" />\n";
1404 $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."month\" value=\"". $month ."\" />\n";
1405 $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."day\" value=\"". $day ."\" />\n";
1411 * output calendar matrix
1413 public function get_calendar_matrix($year = 0, $month = 0, $day = 0)
1415 if (!isset($year)) $year = date('Y');
1416 if (!isset($month)) $month = date('m');
1417 if (!isset($day)) $day = date('d');
1422 require_once CALENDAR_ROOT.'Month/Weekdays.php';
1423 require_once CALENDAR_ROOT.'Day.php';
1426 $month = new Calendar_Month_Weekdays($year,$month);
1429 $prevStamp = $month->prevMonth(true);
1430 $prev = "javascript:setMonth(". date('Y',$prevStamp) .", ". date('n',$prevStamp) .", ". date('j',$prevStamp) .");";
1431 $nextStamp = $month->nextMonth(true);
1432 $next = "javascript:setMonth(". date('Y',$nextStamp) .", ". date('n',$nextStamp) .", ". date('j',$nextStamp) .");";
1434 $selectedDays = array (
1435 new Calendar_Day($year,$month,$day),
1436 new Calendar_Day($year,12,25),
1439 // Build the days in the month
1440 $month->build($selectedDays);
1442 $this->tmpl->assign('current_month', date('F Y',$month->getTimeStamp()));
1443 $this->tmpl->assign('prev_month', $prev);
1444 $this->tmpl->assign('next_month', $next);
1446 while ( $day = $month->fetch() ) {
1448 if(!isset($matrix[$rows]))
1449 $matrix[$rows] = Array();
1453 $dayStamp = $day->thisDay(true);
1454 $link = "javascript:setCalendarDate(". date('Y',$dayStamp) .", ". date('n',$dayStamp).", ". date('j',$dayStamp) .");";
1456 // isFirst() to find start of week
1457 if ( $day->isFirst() )
1460 if ( $day->isSelected() ) {
1461 $string.= "<td class=\"selected\">".$day->thisDay()."</td>\n";
1462 } else if ( $day->isEmpty() ) {
1463 $string.= "<td> </td>\n";
1465 $string.= "<td><a class=\"calendar\" href=\"".$link."\">".$day->thisDay()."</a></td>\n";
1468 // isLast() to find end of week
1469 if ( $day->isLast() )
1470 $string.= "</tr>\n";
1472 $matrix[$rows][$cols] = $string;
1482 $this->tmpl->assign('matrix', $matrix);
1483 $this->tmpl->assign('rows', $rows);
1484 $this->tmpl->show("calendar.tpl");
1486 } // get_calendar_matrix()
1489 * output export page
1491 public function getExport($mode)
1493 $pictures = $this->getPhotoSelection();
1494 $current_tags = $this->getCurrentTags();
1496 if(!isset($_SERVER['HTTPS'])) $protocol = "http";
1497 else $protocol = "https";
1499 $server_name = $_SERVER['SERVER_NAME'];
1501 foreach($pictures as $picture) {
1503 $orig_url = $protocol ."://". $server_name . $this->cfg->web_path ."index.php?mode=showp&id=". $picture;
1504 if($current_tags != "") {
1505 $orig_url.= "&tags=". $current_tags;
1507 if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
1508 $orig_url.= "&from_date=". $_SESSION['from_date'] ."&to_date=". $_SESSION['to_date'];
1511 $thumb_url = $protocol ."://". $server_name . $this->cfg->web_path ."phpfspot_img.php?idx=". $picture ."&width=". $this->cfg->thumb_width;
1516 // <a href="%pictureurl%"><img src="%thumbnailurl%" ></a>
1517 print htmlspecialchars("<a href=\"". $orig_url ."\"><img src=\"". $thumb_url ."\" /></a>") ."<br />\n";
1521 // [%pictureurl% %thumbnailurl%]
1522 print htmlspecialchars(" * [".$orig_url." ".$thumb_url."&fake=1.jpg]") ."<br />\n";
1531 * return all selected tags as one string
1533 private function getCurrentTags()
1536 if($_SESSION['selected_tags'] != "") {
1537 foreach($_SESSION['selected_tags'] as $tag)
1538 $current_tags.= $tag .",";
1539 $current_tags = substr($current_tags, 0, strlen($current_tags)-1);
1541 return $current_tags;
1543 } // getCurrentTags()
1546 * return the current photo
1548 public function getCurrentPhoto()
1550 if(isset($_SESSION['current_photo'])) {
1551 print $_SESSION['current_photo'];
1553 } // getCurrentPhoto()
1556 * tells the client browser what to do
1558 * this function is getting called via AJAX by the
1559 * client browsers. it will tell them what they have
1560 * to do next. This is necessary for directly jumping
1561 * into photo index or single photo view when the are
1562 * requested with specific URLs
1564 public function whatToDo()
1566 if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
1567 return "showpi_tags";
1569 elseif(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
1570 return "showpi_date";
1572 elseif(isset($_SESSION['current_photo'])) {
1573 return "show_photo";
1575 elseif(isset($_SESSION['start_action']) && $_SESSION['start_action'] == 'showpi') {
1579 return "nothing special";
1584 * return the current process-user
1586 private function getuid()
1588 if($uid = posix_getuid()) {
1589 if($user = posix_getpwuid($uid)) {
1590 return $user['name'];