remove a unnecessary AJAX call
[phpfspot.git] / phpfspot.class.php
1 <?php
2
3 require_once "phpfspot_cfg.php";
4 require_once "phpfspot_db.php";
5 require_once "phpfspot_tmpl.php";
6
7 class PHPFSPOT {
8
9    var $cfg;
10    var $db;
11    var $cfg_db;
12    var $tmpl;
13    var $tags;
14    var $avail_tags;
15
16    public function __construct()
17    {
18       /* Check necessary requirements */
19       if(!$this->checkRequirements()) {
20          exit(1);
21       }
22
23       $this->cfg = new PHPFSPOT_CFG;
24
25       $this->db  = new PHPFSPOT_DB(&$this, $this->cfg->fspot_db);
26       $this->cfg_db = new PHPFSPOT_DB(&$this, $this->cfg->phpfspot_db);
27       $this->check_config_table();
28
29       $this->tmpl = new PHPFSPOT_TMPL($this);
30
31       $this->get_tags();
32
33       session_start();
34
35       if(!isset($_SESSION['tag_condition']))
36          $_SESSION['tag_condition'] = 'or';
37
38       if(!isset($_SESSION['searchfor']))
39          $_SESSION['searchfor'] = '';
40
41       // if begin_with is still set but rows_per_page is now 0, unset it
42       if(isset($_SESSION['begin_with']) && $this->cfg->rows_per_page == 0)
43          unset($_SESSION['begin_with']);
44
45    } // __construct()
46
47    public function __destruct()
48    {
49
50    } // __destruct()
51
52    public function show()
53    {
54       $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
55       $this->tmpl->assign('page_title', $this->cfg->page_title);
56       $this->tmpl->assign('current_condition', $_SESSION['tag_condition']);
57
58       $_SESSION['start_action'] = $_GET['mode'];
59
60       switch($_GET['mode']) {
61          case 'showpi':
62             if(isset($_GET['tags'])) {
63                $_SESSION['selected_tags'] = split(',', $_GET['tags']);
64             }
65             if(isset($_GET['from_date'])) {
66                $_SESSION['from_date'] = $_GET['from_date'];
67             }
68             if(isset($_GET['to_date'])) {
69                $_SESSION['to_date'] = $_GET['to_date'];
70             }
71             break;
72          case 'showp':
73             if(isset($_GET['tags'])) {
74                $_SESSION['selected_tags'] = split(',', $_GET['tags']);
75                $_SESSION['start_action'] = 'showp';
76             }
77             if(isset($_GET['id'])) {
78                $_SESSION['current_photo'] = $_GET['id'];
79                $_SESSION['start_action'] = 'showp';
80             }
81             if(isset($_GET['from_date'])) {
82                $_SESSION['from_date'] = $_GET['from_date'];
83             }
84             if(isset($_GET['to_date'])) {
85                $_SESSION['to_date'] = $_GET['to_date'];
86             }
87             break;
88          case 'export':
89             $this->tmpl->show("export.tpl");
90             return;
91             break;
92
93       }
94
95       $this->tmpl->assign('from_date', $this->get_calendar('from'));
96       $this->tmpl->assign('to_date', $this->get_calendar('to'));
97       $this->tmpl->assign('content_page', 'welcome.tpl');
98       $this->tmpl->show("index.tpl");
99
100
101    } // show()
102
103    private function get_tags()
104    {
105    
106       $this->avail_tags = Array();
107       $count = 0;
108    
109       $result = $this->db->db_query("
110          SELECT id,name
111          FROM tags
112          ORDER BY sort_priority ASC
113       ");
114       
115       while($row = $this->db->db_fetch_object($result)) {
116
117          $tag_id = $row['id'];
118          $tag_name = $row['name'];
119
120          /* check if config requests to ignore this tag */
121          if(in_array($row['name'], $this->cfg->hide_tags))
122             continue;
123
124          $this->tags[$tag_id] = $tag_name; 
125          $this->avail_tags[$count] = $tag_id;
126
127          $count++;
128
129       }
130
131    } // get_tags()
132
133    public function get_photo_details($idx)
134    {
135       $result = $this->db->db_query("
136          SELECT *
137          FROM photos
138          WHERE id='". $idx ."'
139       ");
140       
141       return $this->db->db_fetch_object($result);
142
143    } // get_photo_details
144
145    public function getPhotoName($idx, $limit = 0)
146    {
147       if($details = $this->get_photo_details($idx)) {
148          $name = $details['name'];
149          if($limit != 0 && strlen($name) > $limit) {
150             $name = substr($name, 0, $limit-5) ."...". substr($name, -($limit-5));
151          }
152          return $name;
153       }
154
155    } // getPhotoName()
156
157    public function translate_path($path, $width = 0)
158    {  
159       return str_replace($this->cfg->path_replace_from, $this->cfg->path_replace_to, $path);
160
161    } // translate_path
162
163    public function showPhoto($photo)
164    {
165       $all_photos = $this->getPhotoSelection();
166       $count = count($all_photos);
167
168       for($i = 0; $i < $count; $i++) {
169          
170          if($get_next) {
171             $next_img = $all_photos[$i];
172             break;
173          }
174
175          if($all_photos[$i] == $photo) {
176             $get_next = 1;
177          }
178          else {
179             $previous_img = $all_photos[$i];
180          }
181
182          if($photo == $all_photos[$i]) {
183                $current = $i;
184          }
185       }
186
187       $details = $this->get_photo_details($photo);
188       $orig_path = $this->translate_path($details['directory_path']) ."/". $details['name'];
189       $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->photo_width ."_". $this->getMD5($photo);
190
191       if(!file_exists($orig_path)) {
192          $this->_warning("Photo ". $orig_path ." does not exist!<br />\n");
193       }
194
195       if(!is_readable($orig_path)) {
196          $this->_warning("Photo ". $orig_path ." is not readable for user ". get_current_user() ."<br />\n");
197       }
198
199       /* If the thumbnail doesn't exist yet, try to create it */
200       if(!file_exists($thumb_path)) {
201          $this->gen_thumb($photo, true);
202       }
203
204       $meta = $this->get_meta_informations($orig_path);
205
206       /* If EXIF data are available, use them */
207       if(isset($meta['ExifImageWidth'])) {
208          $meta_res = $meta['ExifImageWidth'] ."x". $meta['ExifImageLength'];
209       } else {
210          $info = getimagesize($orig_path);
211          $meta_res = $info[0] ."x". $info[1]; 
212       }
213
214       $meta_date = isset($meta['FileDateTime']) ? strftime("%a %x %X", $meta['FileDateTime']) : "n/a";
215       $meta_make = isset($meta['Make']) ? $meta['Make'] ." ". $meta['Model'] : "n/a";
216       $meta_size = isset($meta['FileSize']) ? round($meta['FileSize']/1024, 1) ."kbyte" : "n/a";
217
218       $current_tags = $this->getCurrentTags();
219       $extern_link = "index.php?mode=showp&id=". $photo;
220       if($current_tags != "") {
221          $extern_link.= "&tags=". $current_tags;
222       }
223       if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
224          $extern_link.= "&from_date=". $_SESSION['from_date'] ."&to_date=". $_SESSION['to_date'];
225       }
226
227       $this->tmpl->assign('extern_link', $extern_link);
228
229       if(file_exists($thumb_path)) {
230
231          $info = getimagesize($thumb_path);
232
233          $this->tmpl->assign('description', $details['description']);
234          $this->tmpl->assign('image_name', $details['name']);
235
236          $this->tmpl->assign('width', $info[0]);
237          $this->tmpl->assign('height', $info[1]);
238          $this->tmpl->assign('ExifMadeOn', $meta_date);
239          $this->tmpl->assign('ExifMadeWith', $meta_make);
240          $this->tmpl->assign('ExifOrigResolution', $meta_res);
241          $this->tmpl->assign('ExifFileSize', $meta_size);
242     
243          $this->tmpl->assign('image_url', 'phpfspot_img.php?idx='. $photo ."&amp;width=". $this->cfg->photo_width);
244          $this->tmpl->assign('image_url_full', 'phpfspot_img.php?idx='. $photo);
245
246          $this->tmpl->assign('tags', $this->get_photo_tags($photo));
247          $this->tmpl->assign('current', $current);
248       }
249       else {
250          $this->_warning("Can't open file ". $thumb_path ."\n");
251       }
252
253       if($previous_img) {
254          $this->tmpl->assign('previous_url', "javascript:showImage(". $previous_img .");");
255          $this->tmpl->assign('prev_img', $previous_img);
256       }
257
258       if($next_img) {
259          $this->tmpl->assign('next_url', "javascript:showImage(". $next_img .");");
260          $this->tmpl->assign('next_img', $next_img);
261       }
262       $this->tmpl->assign('mini_width', $this->cfg->mini_width);
263
264       $this->tmpl->show("single_photo.tpl");
265
266    } // showPhoto()
267
268    public function getAvailableTags()
269    {
270       $result = $this->db->db_query("
271          SELECT tag_id as id, count(tag_id) as quantity
272          FROM photo_tags
273          INNER JOIN tags t
274             ON t.id = tag_id
275          GROUP BY tag_id
276          ORDER BY t.name ASC
277       ");
278
279       $tags = Array();
280
281       while($row = $this->db->db_fetch_object($result)) {
282          $tags[$row['id']] = $row['quantity'];
283       }
284
285       // change these font sizes if you will
286       $max_size = 125; // max font size in %
287       $min_size = 75; // min font size in %
288
289       // get the largest and smallest array values
290       $max_qty = max(array_values($tags));
291       $min_qty = min(array_values($tags));
292
293       // find the range of values
294       $spread = $max_qty - $min_qty;
295       if (0 == $spread) { // we don't want to divide by zero
296          $spread = 1;
297       }
298
299       // determine the font-size increment
300       // this is the increase per tag quantity (times used)
301       $step = ($max_size - $min_size)/($spread);
302
303       // loop through our tag array
304       foreach ($tags as $key => $value) {
305
306          if(isset($_SESSION['selected_tags']) && in_array($key, $_SESSION['selected_tags']))
307             continue;
308
309           // calculate CSS font-size
310           // find the $value in excess of $min_qty
311           // multiply by the font-size increment ($size)
312           // and add the $min_size set above
313          $size = $min_size + (($value - $min_qty) * $step);
314           // uncomment if you want sizes in whole %:
315          $size = ceil($size);
316
317          print "<a href=\"javascript:Tags('add', ". $key .");\" class=\"tag\" style=\"font-size: ". $size ."%;\">". $this->tags[$key] ."</a>, ";
318
319       }
320
321    } // getAvailableTags()
322
323    public function getSelectedTags()
324    {
325       $output = "";
326       foreach($this->avail_tags as $tag)
327       {
328          // return all selected tags
329          if(isset($_SESSION['selected_tags']) && in_array($tag, $_SESSION['selected_tags'])) {
330             $output.= "<a href=\"javascript:Tags('del', ". $tag .");\" class=\"tag\">". $this->tags[$tag] ."</a>, ";
331          }
332       }
333
334       $output = substr($output, 0, strlen($output)-2);
335       print $output;
336
337    } // getSelectedTags()
338
339    public function addTag($tag)
340    {
341       // if the result of a date search are displayed, reset them
342       $this->resetDateSearch();
343
344       if(!isset($_SESSION['selected_tags']))
345          $_SESSION['selected_tags'] = Array();
346
347       if(!in_array($tag, $_SESSION['selected_tags']))
348          array_push($_SESSION['selected_tags'], $tag);
349    
350    } // addTag()
351
352    public function delTag($tag)
353    {
354       if(isset($_SESSION['selected_tags'])) {
355          $key = array_search($tag, $_SESSION['selected_tags']);
356          unset($_SESSION['selected_tags'][$key]);
357          sort($_SESSION['selected_tags']);
358       }
359
360    } // delTag()
361
362    public function resetTags()
363    {
364       if(isset($_SESSION['selected_tags']))
365          unset($_SESSION['selected_tags']);
366
367    } // resetTags()
368
369    public function resetPhotoView()
370    {
371       if(isset($_SESSION['current_photo']))
372          unset($_SESSION['current_photo']);
373
374    } // resetPhotoView();
375
376    public function resetTagSearch()
377    {
378       if(isset($_SESSION['searchfor']))
379          unset($_SESSION['searchfor']);
380
381    } // resetTagSearch()
382
383    public function resetDateSearch()
384    {
385       if(isset($_SESSION['from_date']))
386          unset($_SESSION['from_date']);
387       if(isset($_SESSION['to_date']))
388          unset($_SESSION['to_date']);
389
390    } // resetDateSearch();
391
392    public function getPhotoSelection()
393    {  
394       $matched_photos = Array();
395
396       /* return a search result */
397       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '') {
398          $result = $this->db->db_query("
399             SELECT DISTINCT photo_id
400                FROM photo_tags pt
401             INNER JOIN photos p
402                ON p.id=pt.photo_id
403             INNER JOIN tags t
404                ON pt.tag_id=t.id
405             WHERE t.name LIKE '%". $_SESSION['searchfor'] ."%'
406                ORDER BY p.time ASC
407          ");
408          while($row = $this->db->db_fetch_object($result)) {
409             array_push($matched_photos, $row['photo_id']);
410          }
411          return $matched_photos;
412       }
413
414       /* return according the selected tags */
415       if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
416          $selected = "";
417          foreach($_SESSION['selected_tags'] as $tag)
418             $selected.= $tag .",";
419          $selected = substr($selected, 0, strlen($selected)-1);
420
421          if($_SESSION['tag_condition'] == 'or') {
422             $result = $this->db->db_query("
423                SELECT DISTINCT photo_id
424                   FROM photo_tags pt
425                INNER JOIN photos p
426                   ON p.id=pt.photo_id
427                WHERE pt.tag_id IN (". $selected .")
428                ORDER BY p.time ASC
429             ");
430          }
431          elseif($_SESSION['tag_condition'] == 'and') {
432
433             if(count($_SESSION['selected_tags']) >= 32) {
434                print "A SQLite limit of 32 tables within a JOIN SELECT avoids to<br />\n";
435                print "evaluate your tag selection. Please remove some tags from your selection.\n";
436                return Array();
437             } 
438
439             /* Join together a table looking like
440
441                pt1.photo_id pt1.tag_id pt2.photo_id pt2.tag_id ...
442
443                so the query can quickly return all images matching the
444                selected tags in an AND condition
445
446             */
447
448             $query_str = "
449                SELECT DISTINCT pt1.photo_id
450                   FROM photo_tags pt1
451             ";
452
453             for($i = 0; $i < count($_SESSION['selected_tags']); $i++) {
454                $query_str.= "
455                   INNER JOIN photo_tags pt". ($i+2) ."
456                      ON pt1.photo_id=pt". ($i+2) .".photo_id
457                ";
458             }
459             $query_str.= "WHERE pt1.tag_id=". $_SESSION['selected_tags'][0];
460             for($i = 1; $i < count($_SESSION['selected_tags']); $i++) {
461                $query_str.= "
462                   AND pt". ($i+1) .".tag_id=". $_SESSION['selected_tags'][$i] ."
463                "; 
464             }
465             $result = $this->db->db_query($query_str);
466          }
467
468          while($row = $this->db->db_fetch_object($result)) {
469             array_push($matched_photos, $row['photo_id']);
470          }
471          return $matched_photos;
472       }
473
474       if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
475          $from_date = strtotime($_SESSION['from_date']);
476          $to_date = strtotime($_SESSION['to_date']);
477          $result = $this->db->db_query("
478             SELECT DISTINCT photo_id
479                FROM photo_tags pt
480             INNER JOIN photos p
481                ON p.id=pt.photo_id
482             WHERE 
483                time>='". $from_date ."'
484             AND
485                time<='". $to_date ."'
486             ORDER BY p.time ASC
487          ");
488          while($row = $this->db->db_fetch_object($result)) {
489             array_push($matched_photos, $row['photo_id']);
490          }
491          return $matched_photos;
492       } 
493
494       /* return all available photos */
495       $result = $this->db->db_query("
496          SELECT DISTINCT photo_id
497             FROM photo_tags pt
498          INNER JOIN photos p
499             ON p.id=pt.photo_id
500          ORDER BY p.time ASC
501       ");
502       while($row = $this->db->db_fetch_object($result)) {
503          array_push($matched_photos, $row['photo_id']);
504       }
505       return $matched_photos;
506
507    } // getPhotoSelection()
508
509    public function showPhotoIndex()
510    {
511       $photos = $this->getPhotoSelection();
512
513       $count = count($photos);
514
515       if(isset($_SESSION['begin_with']) && $_SESSION['begin_with'] != "")
516          $anchor = $_SESSION['begin_with'];
517
518       if(!isset($this->cfg->rows_per_page) || $this->cfg->rows_per_page == 0) {
519
520          $begin_with = 0;
521          $end_with = $count;
522
523       }
524       elseif($this->cfg->rows_per_page > 0) {
525
526          if(!$_SESSION['begin_with'] || $_SESSION['begin_with'] == 0)
527             $begin_with = 0;
528          else {
529
530             $begin_with = $_SESSION['begin_with'];
531
532             // verify $begin_with - perhaps the thumbs-per-rows or
533             // rows-per-page variables have changed or the jump back
534             // from a photo wasn't exact - so calculate the real new
535             // starting point
536             $multiplicator = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
537             for($i = 0; $i <= $count; $i+=$multiplicator) {
538                if($begin_with >= $i && $begin_with < $i+$multiplicator) {
539                   $begin_with = $i;
540                   break;
541                }
542             }
543          }
544
545          $end_with = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
546       }
547
548    
549       $rows = 0;
550       $cols = 0;
551       $images[$rows] = Array();
552       $img_height[$rows] = Array();
553       $img_width[$rows] = Array();
554       $img_id[$rows] = Array();
555       $img_name[$rows] = Array();
556       $img_title = Array();
557
558       for($i = $begin_with; $i < $end_with; $i++) {
559
560          $images[$rows][$cols] = $photos[$i];
561          $img_id[$rows][$cols] = $i;
562          $img_name[$rows][$cols] = htmlspecialchars($this->getPhotoName($photos[$i], 15));
563          $img_title[$rows][$cols] = "Click to view photo ". htmlspecialchars($this->getPhotoName($photos[$i], 0));
564
565          $thumb_path = $this->cfg->base_path ."/thumbs/". $this->cfg->thumb_width ."_". $this->getMD5($photos[$i]);
566
567          if(file_exists($thumb_path)) {
568             $info = getimagesize($thumb_path); 
569             $img_width[$rows][$cols] = $info[0];
570             $img_height[$rows][$cols] = $info[1];
571          }
572
573          if($cols == $this->cfg->thumbs_per_row-1) {
574             $cols = 0;
575             $rows++;
576             $images[$rows] = Array();
577             $img_width[$rows] = Array();
578             $img_height[$rows] = Array();
579          }
580          else {
581             $cols++;
582          }
583       } 
584
585       // +1 for for smarty's selection iteration
586       $rows++;
587
588       if(isset($_SESSION['searchfor']) && $_SESSION['searchfor'] != '')
589          $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
590
591       /* do we have to display the page selector ? */
592       if($this->cfg->rows_per_page != 0) {
593       
594          /* calculate the page switchers */
595          $previous_start = $begin_with - ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
596          $next_start = $begin_with + ($this->cfg->rows_per_page * $this->cfg->thumbs_per_row);
597
598          if($begin_with != 0) 
599             $this->tmpl->assign("previous_url", "javascript:showPhotoIndex(". $previous_start .");"); 
600          if($end_with < $count)
601             $this->tmpl->assign("next_url", "javascript:showPhotoIndex(". $next_start .");"); 
602
603          $photo_per_page  = $this->cfg->rows_per_page * $this->cfg->thumbs_per_row;
604          $last_page = ceil($count / $photo_per_page);
605
606          /* get the current selected page */
607          if($begin_with == 0) {
608             $current_page = 1;
609          } else {
610             $current_page = 0;
611             for($i = $begin_with; $i >= 0; $i-=$photo_per_page) {
612                $current_page++;
613             }
614          } 
615
616          for($i = 1; $i <= $last_page; $i++) {
617
618             if($current_page == $i)
619                $style = "style=\"font-size: 125%;\"";
620             elseif($current_page-1 == $i || $current_page+1 == $i)
621                $style = "style=\"font-size: 105%;\"";
622             elseif(($current_page-5 >= $i) && ($i != 1) ||
623                ($current_page+5 <= $i) && ($i != $last_page))
624                $style = "style=\"font-size: 75%;\"";
625             else
626                $style = "";
627
628             $select = "<a href=\"javascript:showPhotoIndex(". (($i*$photo_per_page)-$photo_per_page) .");\"";
629                if($style != "")
630                   $select.= $style;
631             $select.= ">". $i ."</a>&nbsp;";
632
633             // until 9 pages we show the selector from 1-9
634             if($last_page <= 9) {
635                $page_select.= $select;
636                continue;
637             } else {
638                if($i == 1 /* first page */ || 
639                   $i == $last_page /* last page */ ||
640                   $i == $current_page /* current page */ ||
641                   $i == ceil($last_page * 0.25) /* first quater */ ||
642                   $i == ceil($last_page * 0.5) /* half */ ||
643                   $i == ceil($last_page * 0.75) /* third quater */ ||
644                   (in_array($i, array(1,2,3,4,5,6)) && $current_page <= 4) /* the first 6 */ ||
645                   (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 */ ||
646                   $i == $current_page-3 || $i == $current_page-2 || $i == $current_page-1 /* three before */ ||
647                   $i == $current_page+3 || $i == $current_page+2 || $i == $current_page+1 /* three after */) {
648
649                   $page_select.= $select;
650                   continue;
651
652                }
653             }
654
655             $page_select.= ".";
656          }
657
658          /* only show the page selector if we have more then one page */
659          if($last_page > 1)
660             $this->tmpl->assign('page_selector', $page_select);
661       }
662
663       
664       $current_tags = $this->getCurrentTags();
665       $extern_link = "index.php?mode=showpi";
666       if($current_tags != "") {
667          $extern_link.= "&tags=". $current_tags;
668       }
669       if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
670          $extern_link.= "&from_date=". $_SESSION['from_date'] ."&to_date=". $_SESSION['to_date'];
671       }
672
673       $export_link = "index.php?mode=export";
674
675       $this->tmpl->assign('extern_link', $extern_link);
676       $this->tmpl->assign('export_link', $export_link);
677       $this->tmpl->assign('count', $count);
678       $this->tmpl->assign('width', $this->cfg->thumb_width);
679       $this->tmpl->assign('images', $images);
680       $this->tmpl->assign('img_width', $img_width);
681       $this->tmpl->assign('img_height', $img_height);
682       $this->tmpl->assign('img_id', $img_id);
683       $this->tmpl->assign('img_name', $img_name);
684       $this->tmpl->assign('img_title', $img_title);
685       $this->tmpl->assign('rows', $rows);
686       $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
687
688       $this->tmpl->show("photo_index.tpl");
689
690       if(isset($anchor))
691          print "<script language=\"JavaScript\">self.location.hash = '#image". $anchor ."';</script>\n";
692
693    } // showPhotoIndex()
694
695    public function showCredits()
696    {
697       $this->tmpl->assign('version', $this->cfg->version);
698       $this->tmpl->assign('product', $this->cfg->product);
699       $this->tmpl->show("credits.tpl");
700
701    } // showCredits()
702
703    public function create_thumbnail($orig_image, $thumb_image, $width)
704    {  
705       if(!file_exists($orig_image))
706          return false;
707
708       $details = getimagesize($orig_image);
709       
710       /* check if original photo is a support image type */
711       if(!$this->checkifImageSupported($details['mime']))
712          return false;
713
714       $meta = $this->get_meta_informations($orig_image);
715
716       $rotate = 0;
717       $flip = false;
718
719       switch($meta['Orientation']) {
720
721          case 1: /* top, left */
722             $rotate = 0; $flip = false; break;
723          case 2: /* top, right */
724             $rotate = 0; $flip = true; break;
725          case 3: /* bottom, left */
726             $rotate = 180; $flip = false; break;
727          case 4: /* bottom, right */
728             $rotate = 180; $flip = true; break;
729          case 5: /* left side, top */
730             $rotate = 90; $flip = true; break;
731          case 6: /* right side, top */
732             $rotate = 90; $flip = false; break;
733          case 7: /* left side, bottom */
734             $rotate = 270; $flip = true; break;
735          case 8: /* right side, bottom */
736             $rotate = 270; $flip = false; break;
737       }
738
739       $src_img = @imagecreatefromjpeg($orig_image);
740
741       if(!$src_img) {
742          print "Can't load image from ". $orig_image ."\n";
743          return false;
744       }
745
746       /* grabs the height and width */
747       $cur_width = imagesx($src_img);
748       $cur_height = imagesy($src_img);
749
750       // If requested width is more then the actual image width,
751       // do not generate a thumbnail
752
753       if($width >= $cur_width) {
754          imagedestroy($src_img);
755          return true;
756       }
757
758       // If the image will be rotate because EXIF orientation said so
759       // 'virtually rotate' the image for further calculations
760       if($rotate == 90 || $rotate == 270) {
761          $tmp = $cur_width;
762          $cur_width = $cur_height;
763          $cur_height = $tmp;
764       }
765
766       /* calculates aspect ratio */
767       $aspect_ratio = $cur_height / $cur_width;
768
769       /* sets new size */
770       if($aspect_ratio < 1) {
771          $new_w = $width;
772          $new_h = abs($new_w * $aspect_ratio);
773       } else {
774          /* 'virtually' rotate the image and calculate it's ratio */
775          $tmp_w = $cur_height;
776          $tmp_h = $cur_width;
777          /* now get the ratio from the 'rotated' image */
778          $tmp_ratio = $tmp_h/$tmp_w;
779          /* now calculate the new dimensions */
780          $tmp_w = $width;
781          $tmp_h = abs($tmp_w * $tmp_ratio);
782
783          // now that we know, how high they photo should be, if it
784          // gets rotated, use this high to scale the image
785          $new_h = $tmp_h;
786          $new_w = abs($new_h / $aspect_ratio);
787
788          // If the image will be rotate because EXIF orientation said so
789          // now 'virtually rotate' back the image for the image manipulation
790          if($rotate == 90 || $rotate == 270) {
791             $tmp = $new_w;
792             $new_w = $new_h;
793             $new_h = $tmp;
794          }
795       }
796
797       /* creates new image of that size */
798       $dst_img = imagecreatetruecolor($new_w, $new_h);
799
800       imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
801
802       /* copies resized portion of original image into new image */
803       imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, imagesx($src_img), imagesy($src_img));
804
805       /* needs the image to be flipped horizontal? */
806       if($flip) {
807          print "(FLIP)";
808          $image = $dst_img;
809          for($x = 0; $x < $new_w; $x++) {
810             imagecopy($dst_img, $image, $x, 0, $w - $x - 1, 0, 1, $h);
811          }
812       }
813
814       if($rotate) {
815          $this->_debug("(ROTATE)");
816          $dst_img = $this->rotateImage($dst_img, $rotate);
817       }
818
819       /* write down new generated file */
820       $result = imagejpeg($dst_img, $thumb_image, 75);
821
822       /* free your mind */
823       imagedestroy($dst_img);
824       imagedestroy($src_img);
825
826       if($result === false) {
827          print "Can't write thumbnail ". $thumb_image ."\n";
828          return false;
829       }
830
831       return true;
832
833    } // create_thumbnail()
834
835    public function get_meta_informations($file)
836    {
837       return exif_read_data($file);
838
839    } // get_meta_informations()
840
841    public function check_config_table()
842    {
843       // if the config table doesn't exist yet, create it
844       if(!$this->cfg_db->db_check_table_exists("images")) {
845          $this->cfg_db->db_exec("
846             CREATE TABLE images (
847                img_idx int primary key,
848                img_md5 varchar(32)
849             )
850             ");
851       }
852
853    } // check_config_table
854
855    /**
856     * Generates a thumbnail from photo idx
857     *
858     * This function will generate JPEG thumbnails from provided F-Spot photo
859     * indizes.
860     *
861     * 1. Check if all thumbnail generations (width) are already in place and
862     *    readable
863     * 2. Check if the md5sum of the original file has changed
864     * 3. Generate the thumbnails if needed
865     */
866    public function gen_thumb($idx = 0, $force = 0)
867    {
868       $error = 0;
869
870       $resolutions = Array(
871          $this->cfg->thumb_width,
872          $this->cfg->photo_width,
873          $this->cfg->mini_width,
874       );
875
876       /* get details from F-Spot's database */
877       $details = $this->get_photo_details($idx);
878
879       /* calculate file MD5 sum */
880       $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
881
882       if(!file_exists($full_path)) {
883          $this->_warning("File ". $full_path ." does not exist\n");
884          return;
885       }
886
887       if(!is_readable($full_path)) {
888          $this->_warning("File ". $full_path ." is not readable for ". get_current_user() ."\n");
889          return;
890       }
891
892       $file_md5 = md5_file($full_path);
893
894       $this->_debug("Image [". $idx ."] ". $details['name'] ." Thumbnails:");
895
896       foreach($resolutions as $resolution) {
897
898          $thumb_path = $this->cfg->base_path ."/thumbs/". $resolution ."_". $file_md5;
899
900          /* if the thumbnail file doesn't exist, create it */
901          if(!file_exists($thumb_path)) {
902
903             $this->_debug(" ". $resolution ."px");
904             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
905                $error = 1;
906          }
907
908          /* if the file hasn't changed there is no need to regen the thumb */
909          elseif($file_md5 != $this->getMD5($idx) || $force) {
910
911             $this->_debug(" ". $resolution ."px");
912             if(!$this->create_thumbnail($full_path, $thumb_path, $resolution))
913                $error = 1;
914
915          }
916       }
917
918       /* set the new/changed MD5 sum for the current photo */
919       if(!$error) {
920          $this->setMD5($idx, $file_md5);
921       }
922
923       $this->_debug("\n");
924
925    } // gen_thumb()
926
927    public function getMD5($idx)
928    {
929       $result = $this->cfg_db->db_query("
930          SELECT img_md5 
931          FROM images
932          WHERE img_idx='". $idx ."'
933       ");
934
935       if(!$result)
936          return 0;
937
938       $img = $this->cfg_db->db_fetch_object($result);
939       return $img['img_md5'];
940       
941    } // getMD5()
942
943    private function setMD5($idx, $md5)
944    {
945       $result = $this->cfg_db->db_exec("
946          REPLACE INTO images (img_idx, img_md5)
947          VALUES ('". $idx ."', '". $md5 ."')
948       ");
949
950    } // setMD5()
951
952    public function setTagCondition($mode)
953    {
954       $_SESSION['tag_condition'] = $mode;
955
956    } // setTagCondition()
957
958    public function startTagSearch($searchfor)
959    {
960       $_SESSION['searchfor'] = $searchfor;
961       $_SESSION['selected_tags'] = Array();
962
963       foreach($this->avail_tags as $tag) {
964          if(preg_match('/'. $searchfor .'/i', $this->tags[$tag]))
965             array_push($_SESSION['selected_tags'], $tag);
966       }
967
968       $this->resetDateSearch();
969
970    } // startTagSearch()
971
972    public function startDateSearch($from, $to)
973    {
974       $_SESSION['from_date'] = $from;
975       $_SESSION['to_date'] = $to;
976    }
977
978    private function rotateImage($img, $degrees)
979    {
980       if(function_exists("imagerotate"))
981          $img = imagerotate($img, $degrees, 0);
982       else
983       {
984          function imagerotate($src_img, $angle)
985          {
986             $src_x = imagesx($src_img);
987             $src_y = imagesy($src_img);
988             if ($angle == 180) {
989                $dest_x = $src_x;
990                $dest_y = $src_y;
991             }
992             elseif ($src_x <= $src_y) {
993                $dest_x = $src_y;
994                $dest_y = $src_x;
995             }
996             elseif ($src_x >= $src_y) {
997                $dest_x = $src_y;
998                $dest_y = $src_x;
999             }
1000                
1001             $rotate=imagecreatetruecolor($dest_x,$dest_y);
1002             imagealphablending($rotate, false);
1003                
1004             switch ($angle) {
1005             
1006                case 90:
1007                   for ($y = 0; $y < ($src_y); $y++) {
1008                      for ($x = 0; $x < ($src_x); $x++) {
1009                         $color = imagecolorat($src_img, $x, $y);
1010                         imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
1011                      }
1012                   }
1013                   break;
1014
1015                case 270:
1016                   for ($y = 0; $y < ($src_y); $y++) {
1017                      for ($x = 0; $x < ($src_x); $x++) {
1018                         $color = imagecolorat($src_img, $x, $y);
1019                         imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
1020                      }
1021                   }
1022                   break;
1023
1024                case 180:
1025                   for ($y = 0; $y < ($src_y); $y++) {
1026                      for ($x = 0; $x < ($src_x); $x++) {
1027                         $color = imagecolorat($src_img, $x, $y);
1028                         imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
1029                      }
1030                   }
1031                   break;
1032
1033                default: $rotate = $src_img;
1034             };
1035
1036             return $rotate;
1037
1038          }
1039
1040          $img = imagerotate($img, $degrees);
1041
1042       }
1043
1044       return $img;
1045
1046    } // rotateImage()
1047
1048    private function get_photo_tags($idx)
1049    {
1050       $result = $this->db->db_query("
1051          SELECT t.id, t.name
1052          FROM tags t
1053          INNER JOIN photo_tags pt
1054             ON t.id=pt.tag_id
1055          WHERE pt.photo_id='". $idx ."'
1056       ");
1057
1058       $tags = Array();
1059
1060       while($row = $this->db->db_fetch_object($result))
1061          $tags[$row['id']] = $row['name'];
1062
1063       return $tags;
1064
1065    } // get_photo_tags()
1066
1067    public function showTextImage($txt, $color=000000, $space=4, $font=4, $w=300)
1068    {
1069       if (strlen($color) != 6) 
1070          $color = 000000;
1071
1072       $int = hexdec($color);
1073       $h = imagefontheight($font);
1074       $fw = imagefontwidth($font);
1075       $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
1076       $lines = count($txt);
1077       $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
1078       $bg = imagecolorallocate($im, 255, 255, 255);
1079       $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
1080       $y = 0;
1081
1082       foreach ($txt as $text) {
1083          $x = (($w - ($fw * strlen($text))) / 2);
1084          imagestring($im, $font, $x, $y, $text, $color);
1085          $y += ($h + $space);
1086       }
1087
1088       Header("Content-type: image/png");
1089       ImagePng($im);
1090
1091    } // showTextImage()
1092
1093    private function checkRequirements()
1094    {
1095       if(!function_exists("imagecreatefromjpeg")) {
1096          print "PHP GD library extension is missing<br />\n";
1097          $missing = true;
1098       }
1099
1100       if(!function_exists("sqlite3_open")) {
1101          print "PHP SQLite3 library extension is missing<br />\n";
1102          $missing = true;
1103       }
1104
1105       /* Check for HTML_AJAX PEAR package, lent from Horde project */
1106       ini_set('track_errors', 1);
1107       @include_once 'HTML/AJAX/Server.php';
1108       if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1109          print "PEAR HTML_AJAX package is missing<br />\n";
1110          $missing = true;
1111       }
1112       @include_once 'Calendar/Calendar.php';
1113       if(isset($php_errormsg) && preg_match('/Failed opening.*for inclusion/i', $php_errormsg)) {
1114          print "PEAR Calendar package is missing<br />\n";
1115          $missing = true;
1116       }
1117       ini_restore('track_errors');
1118
1119       if(isset($missing))
1120          return false;
1121
1122       return true;
1123
1124    } // checkRequirements()
1125
1126    private function _debug($text)
1127    {
1128       if($this->fromcmd) {
1129          print $text;
1130       }
1131
1132    } // _debug()
1133
1134    public function checkifImageSupported($mime)
1135    {
1136       if(in_array($mime, Array("image/jpeg")))
1137          return true;
1138
1139       return false;
1140
1141    } // checkifImageSupported()
1142
1143    public function _warning($text)
1144    {
1145       print "<img src=\"resources/green_info.png\" alt=\"warning\" />\n";
1146       print $text;
1147
1148    } // _warning()
1149
1150    private function get_calendar($mode)
1151    {
1152       $year = $_SESSION[$mode .'_date'] ? date("Y", strtotime($_SESSION[$mode .'_date'])) : date("Y");
1153       $month = $_SESSION[$mode .'_date'] ? date("m", strtotime($_SESSION[$mode .'_date'])) : date("m");
1154       $day = $_SESSION[$mode .'_date'] ? date("d", strtotime($_SESSION[$mode .'_date'])) : date("d");
1155
1156       $output = "<input type=\"text\" size=\"3\" id=\"". $mode ."year\" value=\"". $year ."\" />\n";
1157       $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."month\" value=\"". $month ."\" />\n";
1158       $output.= "<input type=\"text\" size=\"1\" id=\"". $mode ."day\" value=\"". $day ."\" />\n";
1159       return $output;
1160
1161    } // get_calendar()
1162
1163    public function get_calendar_matrix($year = 0, $month = 0, $day = 0)
1164    {
1165       if (!isset($year)) $year = date('Y');
1166       if (!isset($month)) $month = date('m');
1167       if (!isset($day)) $day = date('d');
1168       $rows = 1;
1169       $cols = 1;
1170       $matrix = Array();
1171
1172       require_once CALENDAR_ROOT.'Month/Weekdays.php';
1173       require_once CALENDAR_ROOT.'Day.php';
1174
1175
1176       // Build the month
1177       $month = new Calendar_Month_Weekdays($year,$month);
1178
1179       // Create links
1180       $prevStamp = $month->prevMonth(true);
1181       $prev = "javascript:setMonth(". date('Y',$prevStamp) .", ". date('n',$prevStamp) .", ". date('j',$prevStamp) .");";
1182       $nextStamp = $month->nextMonth(true);
1183       $next = "javascript:setMonth(". date('Y',$nextStamp) .", ". date('n',$nextStamp) .", ". date('j',$nextStamp) .");";
1184
1185       $selectedDays = array (
1186          new Calendar_Day($year,$month,$day),
1187          new Calendar_Day($year,12,25),
1188       );
1189
1190       // Build the days in the month
1191       $month->build($selectedDays);
1192
1193       $this->tmpl->assign('current_month', date('F Y',$month->getTimeStamp()));
1194       $this->tmpl->assign('prev_month', $prev);
1195       $this->tmpl->assign('next_month', $next);
1196
1197       while ( $day = $month->fetch() ) {
1198    
1199          if(!isset($matrix[$rows]))
1200             $matrix[$rows] = Array();
1201
1202          $string = "";
1203
1204          $dayStamp = $day->thisDay(true);
1205          $link = "javascript:setCalendarDate(". date('Y',$dayStamp) .", ". date('n',$dayStamp).", ". date('j',$dayStamp) .");";
1206
1207          // isFirst() to find start of week
1208          if ( $day->isFirst() )
1209             $string.= "<tr>\n";
1210
1211          if ( $day->isSelected() ) {
1212             $string.= "<td class=\"selected\">".$day->thisDay()."</td>\n";
1213          } else if ( $day->isEmpty() ) {
1214             $string.= "<td>&nbsp;</td>\n";
1215          } else {
1216             $string.= "<td><a class=\"calendar\" href=\"".$link."\">".$day->thisDay()."</a></td>\n";
1217          }
1218
1219          // isLast() to find end of week
1220          if ( $day->isLast() )
1221             $string.= "</tr>\n";
1222
1223          $matrix[$rows][$cols] = $string;
1224
1225          $cols++;
1226
1227          if($cols > 7) {
1228             $cols = 1;
1229             $rows++;
1230          }
1231       }
1232
1233       $this->tmpl->assign('matrix', $matrix);
1234       $this->tmpl->assign('rows', $rows);
1235       $this->tmpl->show("calendar.tpl");
1236
1237    } // get_calendar_matrix()
1238
1239    public function getExport($mode)
1240    {
1241       $pictures = $this->getPhotoSelection();
1242       $current_tags = $this->getCurrentTags();  
1243
1244       if(!isset($_SERVER['HTTPS'])) $protocol = "http";
1245       else $protocol = "https";
1246
1247       $server_name = $_SERVER['SERVER_NAME'];
1248
1249       foreach($pictures as $picture) {
1250
1251          $orig_url = $protocol ."://". $server_name . $this->cfg->web_path ."index.php?mode=showp&id=". $picture;
1252          if($current_tags != "") {
1253             $orig_url.= "&tags=". $current_tags;
1254          } 
1255          if(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
1256             $orig_url.= "&from_date=". $_SESSION['from_date'] ."&to_date=". $_SESSION['to_date'];
1257          }
1258
1259          $thumb_url = $protocol ."://". $server_name . $this->cfg->web_path ."phpfspot_img.php?idx=". $picture ."&width=". $this->cfg->thumb_width;
1260
1261          switch($mode) {
1262
1263             case 'HTML':
1264                // <a href="%pictureurl%"><img src="%thumbnailurl%" ></a>
1265                print htmlspecialchars("<a href=\"". $orig_url ."\"><img src=\"". $thumb_url ."\" /></a>") ."<br />\n";
1266                break;
1267                
1268             case 'MoinMoin':
1269                // [%pictureurl% %thumbnailurl%]
1270                print htmlspecialchars(" * [".$orig_url." ".$thumb_url."&fake=1.jpg]") ."<br />\n";
1271                break;
1272          }
1273
1274       }
1275
1276    } // getExport()
1277
1278    private function getCurrentTags()
1279    {
1280       $current_tags = "";
1281       if($_SESSION['selected_tags'] != "") {
1282          foreach($_SESSION['selected_tags'] as $tag)
1283             $current_tags.= $tag .",";
1284          $current_tags = substr($current_tags, 0, strlen($current_tags)-1);
1285       }
1286       return $current_tags;
1287
1288    } // getCurrentTags()
1289
1290    public function getCurrentPhoto()
1291    {
1292       if(isset($_SESSION['current_photo'])) {
1293          print $_SESSION['current_photo'];
1294       }
1295    } // getCurrentPhoto()
1296
1297    public function whatToDo()
1298    {
1299       if(isset($_SESSION['selected_tags']) && !empty($_SESSION['selected_tags'])) {
1300          return "showpi_tags";
1301       }
1302       elseif(isset($_SESSION['from_date']) && isset($_SESSION['to_date'])) {
1303          return "showpi_date";
1304       }
1305       elseif(isset($_SESSION['current_photo'])) {
1306          return "show_photo";
1307       }
1308       elseif(isset($_SESSION['start_action']) && $_SESSION['start_action'] == 'showpi') {
1309          return "showpi";
1310       }
1311
1312       return "nothing special";
1313
1314    } // whatToDo()
1315
1316 }
1317
1318 ?>