first tag search functionality
[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    var $current_tags;
16
17    public function __construct()
18    {
19       $this->cfg = new PHPFSPOT_CFG;
20
21       $this->db = new PHPFSPOT_DB(&$this, $this->cfg->fspot_db);
22
23       $this->cfg_db = new PHPFSPOT_DB(&$this, $this->cfg->phpfspot_db);
24       $this->check_config_table();
25
26       $this->tmpl = new PHPFSPOT_TMPL($this);
27
28       $this->get_tags();
29
30       session_start();
31
32       if(!isset($_SESSION['tag_condition']))
33          $_SESSION['tag_condition'] = 'or';
34
35       if(!isset($_SESSION['searchfor']))
36          $_SESSION['searchfor'] = '';
37
38    } // __construct()
39
40    public function __destruct()
41    {
42
43    } // __destruct()
44
45    public function show()
46    {
47       $this->tmpl->assign('searchfor', $_SESSION['searchfor']);
48       $this->tmpl->assign('page_title', $this->cfg->page_title);
49       $this->tmpl->assign('current_condition', $_SESSION['tag_condition']);
50       $this->tmpl->show("index.tpl");
51
52    } // show()
53
54    private function get_tags()
55    {
56       $this->avail_tags = Array();
57       $count = 0;
58    
59       $result = $this->db->db_query("
60          SELECT id,name
61          FROM tags
62          ORDER BY sort_priority ASC
63       ");
64       
65       while($row = $this->db->db_fetch_object($result)) {
66
67          $tag_id = $row['id'];
68          $tag_name = $row['name'];
69
70          /* check if config requests to ignore this tag */
71          if(in_array($row['name'], $this->cfg->hide_tags))
72             continue;
73
74          $this->tags[$tag_id] = $tag_name; 
75          $this->avail_tags[$count] = $tag_id;
76
77          $count++;
78
79       }
80
81    } // get_tags()
82
83    public function get_photo_details($idx)
84    {
85       $result = $this->db->db_query("
86          SELECT *
87          FROM photos
88          WHERE id='". $idx ."'
89       ");
90       
91       return $this->db->db_fetch_object($result);
92
93    } // get_photo_details
94
95    public function translate_path($path, $width = 0)
96    {  
97       return str_replace($this->cfg->path_replace_from, $this->cfg->path_replace_to, $path);
98
99    } // translate_path
100
101    public function showPhoto($photo)
102    {
103       $all_photos = $this->getAllTagPhotos();
104
105       foreach($all_photos as $all_photo) {
106          
107          if($get_next) {
108             $next_img = $all_photo;
109             break;
110          }
111
112          if($all_photo == $photo) {
113             $get_next = 1;
114          }
115          else {
116             $previous_img = $all_photo;
117          }
118       }
119
120
121       $details = $this->get_photo_details($photo);
122       $meta = $this->get_meta_informations($this->translate_path($details['directory_path']) ."/". $details['name']);
123       $info = getimagesize($this->translate_path($details['directory_path']) ."/thumbs/". $this->cfg->photo_width ."_". $details['name']);
124
125       $this->tmpl->assign('width', $info[0]);
126       $this->tmpl->assign('height', $info[1]);
127       $this->tmpl->assign('c_date', $meta['DateTime']);
128       $this->tmpl->assign('madewith', $meta['Make'] ." ". $meta['Model']);
129       $this->tmpl->assign('image_name', $details['name']);
130       $this->tmpl->assign('image_url', 'phpfspot_img.php?idx='. $photo ."&amp;width=". $this->cfg->photo_width);
131       $this->tmpl->assign('image_url_full', 'phpfspot_img.php?idx='. $photo);
132
133       if($previous_img) {
134          $this->tmpl->assign('previous_url', "javascript:showImage(". $previous_img .");");
135       }
136
137       if($next_img) {
138          $this->tmpl->assign('next_url', "javascript:showImage(". $next_img .");");
139       }
140
141       $this->tmpl->show("single_photo.tpl");
142
143    } // showPhoto()
144
145    public function getAvailableTags()
146    {
147       foreach($this->avail_tags as $tag)
148       {
149          if(isset($_SESSION['selected_tags']) && in_array($tag, $_SESSION['selected_tags']))
150             continue;
151
152          // return all available (= not selected) tags
153          print "<a href=\"javascript:Tags('add', ". $tag .");\">". $this->tags[$tag] ."</a>&nbsp;";
154
155       }
156
157    } // getAvailableTags()
158
159    public function getSelectedTags()
160    {
161       foreach($this->avail_tags as $tag)
162       {
163          // return all selected tags
164          if(isset($_SESSION['selected_tags']) && in_array($tag, $_SESSION['selected_tags'])) {
165             print "<a href=\"javascript:Tags('del', ". $tag .");\">". $this->tags[$tag] ."</a>&nbsp;";
166          }
167
168       }
169
170    } // getSelectedTags()
171
172    public function addTag($tag)
173    {
174       if(!isset($_SESSION['selected_tags']))
175          $_SESSION['selected_tags'] = Array();
176
177       array_push($_SESSION['selected_tags'], $tag);
178    
179    } // addTag()
180
181    public function delTag($tag)
182    {
183       if(isset($_SESSION['selected_tags'])) {
184          $key = array_search($tag, $_SESSION['selected_tags']);
185          unset($_SESSION['selected_tags'][$key]);
186       }
187
188    } // delTag()
189
190    public function resetTags()
191    {
192       unset($_SESSION['selected_tags']);
193
194    } // resetTags()
195
196    public function getAllTagPhotos()
197    {  
198       $tagged_photos = Array();
199
200       if(isset($_SESSION['selected_tags'])) {
201          $selected = "";
202          foreach($_SESSION['selected_tags'] as $tag)
203             $selected.= $tag .",";
204          $selected = substr($selected, 0, strlen($selected)-1);
205
206          if($_SESSION['tag_condition'] == 'or') {
207             $result = $this->db->db_query("
208                SELECT DISTINCT photo_id
209                   FROM photo_tags pt
210                INNER JOIN photos p
211                   ON p.id=pt.photo_id
212                WHERE pt.tag_id IN (". $selected .")
213                ORDER BY p.time ASC
214             ");
215             while($row = $this->db->db_fetch_object($result)) {
216                array_push($tagged_photos, $row['photo_id']);
217             }
218          }
219          elseif($_SESSION['tag_condition'] == 'and') {
220             $result = $this->db->db_query("
221                SELECT DISTINCT photo_id, tag_id
222                   FROM photo_tags pt
223                INNER JOIN photos p
224                   on p.id=pt.photo_id
225                WHERE pt.tag_id IN (". $selected .")
226                ORDER BY p.time ASC
227             ");
228
229             /* now we need to check if each object fulfills the condition
230                and has all the selected tags assigned
231             */
232             $match_object = Array();
233             $matches_needed = count($_SESSION['selected_tags']);
234             while($row = $this->db->db_fetch_object($result)) {
235                /* set the counter for this object */
236                if(!isset($match_object[$row['photo_id']]))
237                   $match_object[$row['photo_id']] = $matches_needed;
238                
239                /* we have a match? decrement the counter */
240                if(in_array($row['tag_id'], $_SESSION['selected_tags']))
241                   $match_object[$row['photo_id']]--;
242
243                /* if the object has all necessary tags, add it to the result */
244                if($match_object[$row['photo_id']] == 0)
245                   array_push($tagged_photos, $row['photo_id']);
246             }
247          }
248       }
249       else {
250          $result = $this->db->db_query("
251             SELECT DISTINCT photo_id
252                FROM photo_tags pt
253             INNER JOIN photos p
254                ON p.id=pt.photo_id
255             ORDER BY p.time ASC
256          ");
257          while($row = $this->db->db_fetch_object($result)) {
258             array_push($tagged_photos, $row['photo_id']);
259          }
260       }
261
262       return $tagged_photos;
263
264    } // getAllTagPhotos()
265
266    public function showPhotoIndex()
267    {
268       if($_SESSION['searchfor'] == '')
269          $photos = $this->getAllTagPhotos();
270       else
271          $photos = $this->getSearchResult($_SESSION['searchfor']);
272
273       $count = count($photos);
274
275       $rows = 0;
276       $cols = 0;
277       $images[$rows] = Array();
278
279       for($i = 0; $i < $count; $i++) {
280
281          $images[$rows][$cols] = $photos[$i];
282
283          if($cols == $this->cfg->thumbs_per_row-1) {
284             $cols = 0;
285             $rows++;
286             $images[$rows] = Array();
287          }
288          else {
289             $cols++;
290          }
291       } 
292
293       // +1 for for smarty's selection iteration
294       $rows++;
295
296          //$images.= "<img src=\"phpfspot_img.php?idx=". $photo ."&amp;width=". $this->cfg->thumb_width ."\" /><br />\n";
297
298       $this->tmpl->assign('count', $count);
299       $this->tmpl->assign('width', $this->cfg->thumb_width);
300       $this->tmpl->assign('images', $images);
301       $this->tmpl->assign('rows', $rows);
302       $this->tmpl->assign('columns', $this->cfg->thumbs_per_row);
303       $this->tmpl->show("photo_index.tpl");
304
305
306    } // showPhotoIndex()
307
308    public function showBubbleDetails($photo, $direction)
309    {
310       if($direction == "up")
311          $direction = "bubbleimg_up";
312       else
313          $direction = "bubbleimg_down";
314
315       $details = $this->get_photo_details($photo);
316
317       $image_url = "phpfspot_img.php?idx=". $photo ."&amp;width=". $this->cfg->bubble_width;
318
319       $filesize = filesize($this->translate_path($details['directory_path'])  ."/". $details['name']);
320       $filesize = rand($filesize/1024, 2);
321
322       $img = getimagesize($this->translate_path($details['directory_path'])  ."/". $details['name']);
323
324       $this->tmpl->assign('file_size', $filesize);
325       $this->tmpl->assign('width', $img[0]);
326       $this->tmpl->assign('height', $img[1]);
327       $this->tmpl->assign('file_name', $details['name']);
328       $this->tmpl->assign('image_id', $direction);
329       $this->tmpl->assign('image_url', $image_url);
330       $this->tmpl->show("bubble_details.tpl");
331
332    } // showBubbleDetails()
333
334    public function showCredits()
335    {
336       $this->tmpl->assign('version', $this->cfg->version);
337       $this->tmpl->assign('product', $this->cfg->product);
338       $this->tmpl->show("credits.tpl");
339
340    } // showCredits()
341
342    public function create_thumbnail($image, $width)
343    {  
344       // if thumbnail already exists, don't recreate it
345       if(file_exists(dirname($image) ."/thumbs/". $width ."_". basename($image)))
346          return;
347
348       $src_img = @imagecreatefromjpeg($image);
349
350       if($src_img)
351       {  
352          /* grabs the height and width */
353          $new_w = imagesx($src_img);
354          $new_h = imagesy($src_img);
355
356          // If requested width is more then the actual image width,
357          // do not generate a thumbnail
358
359          if($width >= $new_w) {
360             imagedestroy($src_img);
361             return;
362          }
363
364          /* calculates aspect ratio */
365          $aspect_ratio = $new_h / $new_w;
366
367          /* sets new size */
368          $new_w = $width;
369          $new_h = abs($new_w * $aspect_ratio);
370
371          /* creates new image of that size */
372          $dst_img = imagecreatetruecolor($new_w,$new_h);
373
374          imagefill($dst_img, 0, 0, ImageColorAllocate($dst_img, 255, 255, 255));
375
376          /* copies resized portion of original image into new image */
377          imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
378
379          /* write down new generated file */
380
381          if(!file_exists(dirname($image) ."/thumbs"))
382             mkdir(dirname($image) ."/thumbs");
383
384          $newfile = dirname($image) ."/thumbs/". $width ."_". basename($image);
385          imagejpeg($dst_img, $newfile, 75);
386
387          /* free your mind */
388          imagedestroy($dst_img);
389          imagedestroy($src_img);
390       }
391
392    } // create_thumbnail()
393
394    public function get_meta_informations($file)
395    {
396
397       return exif_read_data($file);
398
399    } // get_meta_informations()
400
401    public function check_config_table()
402    {
403       // if the config table doesn't exist yet, create it
404       if(!$this->cfg_db->db_check_table_exists("images")) {
405          $this->cfg_db->db_exec("
406             CREATE TABLE images (
407                img_idx int primary key,
408                img_md5 varchar(32)
409             )
410             ");
411       }
412
413    } // check_config_table
414
415    public function gen_thumbs($idx = 0, $fromcmd = 0)
416    {
417       if(!$idx) {
418          /* get all available photos */
419          $all = $this->getAllTagPhotos();
420       }
421       else
422          $all = Array($idx);
423       
424       foreach($all as $photo) {
425
426          $details = $this->get_photo_details($photo);
427
428          $full_path = $this->translate_path($details['directory_path'])  ."/". $details['name'];
429          $file_md5 = md5_file($full_path);
430
431          if($fromcmd) print "Image ". $details['name'] ." Thumbnails:";
432
433          /* if the file hasn't changed there is no need to regen the thumb */
434          if($file_md5 == $this->getMD5($photo)) {
435             if($fromcmd) print " file has not changed - skipping\n";
436             continue;
437          }
438
439          /* set the new/changed MD5 sum for the current photo */
440          $this->setMD5($photo, $file_md5);
441
442          $resolutions = Array(
443                            $this->cfg->thumb_width,
444                            $this->cfg->bubble_width,
445                            $this->cfg->photo_width
446                         );
447
448          /* create thumbnails for the requested resolutions */
449          foreach($resolutions as $resolution) {
450             if($fromcmd) print " ". $resolution ."px";
451             $this->create_thumbnail($full_path, $resolution);
452          }
453
454          if($fromcmd) print "\n";
455
456       }
457
458    } // gen_thumbs()
459
460    private function getMD5($idx)
461    {
462       $result = $this->cfg_db->db_query("
463          SELECT img_md5 
464          FROM images
465          WHERE img_idx='". $idx ."'
466       ");
467
468       if(!$result)
469          return 0;
470
471       $img = $this->cfg_db->db_fetch_object($result);
472       return $img['img_md5'];
473       
474    } // getMD5()
475
476    private function setMD5($idx, $md5)
477    {
478       $result = $this->cfg_db->db_exec("
479          REPLACE INTO images (img_idx, img_md5)
480          VALUES ('". $idx ."', '". $md5 ."')
481       ");
482
483    } // setMD5()
484
485    public function setTagCondition($mode)
486    {
487       $_SESSION['tag_condition'] = $mode;
488
489    } // setTagCondition()
490
491    public function startSearch($searchfor)
492    {
493       $_SESSION['searchfor'] = $searchfor;
494
495    } // showSearchResult()
496
497    public function getSearchResult($for)
498    {
499       $tagged_photos = Array();
500
501       $result = $this->db->db_query("
502          SELECT DISTINCT photo_id
503             FROM photo_tags pt
504          INNER JOIN photos p
505             ON p.id=pt.photo_id
506          INNER JOIN tags t
507             ON pt.tag_id=t.id
508          WHERE t.name LIKE '%". $for ."%'
509             ORDER BY p.time ASC
510       ");
511
512       while($row = $this->db->db_fetch_object($result)) {
513          array_push($tagged_photos, $row['photo_id']);
514       }
515
516       return $tagged_photos;
517
518    } // getSearchResult()
519
520 }
521
522 ?>