1 package Memories::Photo;
3 use Carp qw(cluck confess);
4 use base qw(Memories::DBI Maypole::Model::CDBI::Plain);
5 use constant INTERESTINGNESS_ALGORITHM => '((rating+3)/(rated+1))*(1+rated/hit_count)*(1+hit_count/(select max(hit_count) from photo))';
8 use constant PAGER_SYNTAX => "LimitXY";
9 __PACKAGE__->columns(Essential => qw(id title uploader uploaded x y rating rated hit_count));
10 __PACKAGE__->untaint_columns(printable => [qw/title/]);
11 __PACKAGE__->columns(TEMP => qw/exif_object/);
16 popular => "hit_count",
17 interesting => INTERESTINGNESS_ALGORITHM
20 while (my($label, $how) = each %order_by) {
21 __PACKAGE__->set_sql($label => qq{
30 $self->view_paged_ordered($r, "$how desc");
32 __PACKAGE__->MODIFY_CODE_ATTRIBUTES(*{$label}{CODE}, "Exported"); # Hack
35 __PACKAGE__->has_many(comments => "Memories::Comment");
36 __PACKAGE__->has_a(uploader => "Memories::User");
37 __PACKAGE__->has_a(uploaded => "Time::Piece",
38 inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d %H:%M:%S") },
39 deflate => 'datetime',
42 sub do_upload :Exported {
44 my %upload = $r->upload("photo");
46 # XXX Stop anonymous uploads!
47 my $photo = $self->create({
49 uploaded => Time::Piece->new(),
50 title => $r->params->{title},
53 rated => 0, # Oh, the potential for divide by zero errors...
57 if (!open OUT, ">". $photo->path("file")) {
58 die "Can't write ".$photo->path("file")." because $!";
60 # XXX Check it's a JPEG, etc.
62 print OUT $upload{content};
64 my ($x, $y) = dim(image_info($photo->path));
65 $photo->x($x); $photo->y($y);
70 $photo->title($photo->title_exif || $upload{filename});
74 $r->{params}{tags} ||= join " ", map { qq{"$_"} } $photo->tags_exif;
75 $photo->add_tags($r->{params}{tags});
76 $photo->add_to_imageseek_library;
77 Memories->zap_cache();
79 # Add system tags here
80 my $tag = "date:".$photo->shot->ymd;
81 $photo->add_to_system_tags({tag => Memories::SystemTag->find_or_create({name =>$tag}) });
83 # Set it up to go again
84 $r->objects([$photo]);
86 $r->message("Thanks for the upload! ".
87 ($r->{params}{tags} ? ""
88 : "Don't forget to <a href=\"?".$r->config->uri_base."photo/view/".$photo->id."?active=tagedit\">tag your photo</a>"
95 $self->rated or return 0;
96 int($self->rating/$self->rated*10)/10;
99 sub add_rating :Exported {
101 my $photo = $r->{objects}[0];
102 my $delta = $r->{params}{rating};
103 if ($delta < 0 or $delta > 5) { return; } # Scammer
105 $photo->rating($photo->rating() + $delta);
106 $photo->rated($photo->rated() + 1);
107 $r->output(""); # Only used by ajax
112 my $photo = $r->{objects}[0];
113 $photo->hit_count($photo->hit_count()+1);
114 if ($r->{session}{last_search}) {
115 # This is slightly inefficient
116 my @search = split/,/, $r->{session}{last_search};
118 for my $i (0..$#search) {
119 next unless $photo->id == $search[$i];
122 return unless $found > -1;
123 $r->{template_args}{next} = $self->retrieve($search[$found+1])
124 if $found+1 <= $#search;
125 $r->{template_args}{prev} = $self->retrieve($search[$found-1])
129 sub upload :Exported {}
130 sub exif :Exported {}
131 sub comment :Exported {}
132 sub tagedit :Exported {}
133 sub similar :Exported {}
135 use Class::DBI::Plugin::Pager;
136 use Class::DBI::Plugin::AbstractCount;
138 sub view_paged_ordered {
139 my ($self, $r, $how) = @_;
140 my $page = $r->params->{page} || 1;
141 my $pager = $self->pager(
142 per_page => Memories->config->{photos_per_page},
144 syntax => PAGER_SYNTAX,
147 $r->objects([$pager->retrieve_all ]);
148 $r->{template_args}{pager} = $pager;
150 $r->template("paged"); # Set the what using the action name
153 sub add_comment :Exported {
154 my ($self, $r, $photo) = @_;
155 $r->template("view");
156 $r->objects->[0]->add_to_comments({
157 name => $r->params->{name},
158 content => $r->params->{content}
166 use Cache::MemoryCache;
167 use Image::Info qw(dim image_info);
169 my $cache = new Cache::MemoryCache( { 'namespace' => 'MemoriesInfo' });
171 sub add_to_imageseek_library {
173 Image::Seek::cleardb();
174 my $img = Image::Imlib2->load($self->path("file"));
176 Image::Seek::add_image($img, $self->id);
177 # Merge this new one into the main database; there is a bit of a
178 # race condition here. XXX
179 Image::Seek::loaddb(Memories->config->{image_seek});
180 Image::Seek::savedb(Memories->config->{image_seek});
183 sub recommended_tags {
185 my %tags = map { $_->name => $_ }
187 $self->find_similar(3);
192 my ($self, $count) = @_;
193 Image::Seek::cleardb();
194 Image::Seek::loaddb(Memories->config->{image_seek});
195 my @res = map {$_->[0] } Image::Seek::query_id($self->id, $count);
197 map { $self->retrieve($_) } @res;
202 my $orient = $self->exif_info->{EXIF}->{Orientation};
203 return if $orient !~/Rotate (\d+)/i;
205 my $img = Image::Imlib2->load($self->path("file"));
206 $img->image_orientate($steps);
207 $img->save($self->path("file"));
212 my $info = $self->exif_object;
213 return $info if $info;
214 # Get it from the Cache
215 if (!($info = $cache->get($self->id))) {
217 $info = $self->_exif_info;
218 $cache->set($self->id, $info);
220 $self->exif_object($info);
224 my %banned_tags = map { $_ => 1 }
225 qw( CodedCharacterSet ApplicationRecordVersion );
228 my $exifTool = new Image::ExifTool;
229 $exifTool->Options(Group0 => ['IPTC', 'EXIF', 'XMP', 'MakerNotes', 'Composite']);
230 my $info = $exifTool->ImageInfo(shift->path);
232 foreach my $tag ($exifTool->GetFoundTags('Group0')) {
233 next if $banned_tags{$tag};
234 my $group = $exifTool->GetGroup($tag);
235 my $val = $info->{$tag};
236 next if ref $val eq 'SCALAR';
237 next if $val =~ /^[0\s]*$/ or $val =~ /^nil$/;
238 $hash->{$group}->{$exifTool->GetDescription($tag)} = $val;
244 sub dimensions { join "x", $_[0]->x, $_[0]->y }
247 my ($self, $size) = @_;
248 return 1 if $size eq "full";
249 my ($w, $h) = ($self->x, $self->y);
250 my ($w2, $h2) = split /x/, $size;
251 return 1 if $w > $w2 or $h > $h2;
255 sub sized_url { # Use this rather than ->path from TT
256 my ($self, $size) = @_;
257 my $url = Memories->config->{data_store_external};
258 my $resized = Memories->config->{sizes}->[$size];
259 if (!$resized) { cluck "Asked for crazy size $size"; return; }
260 if ($resized eq "full") { return $self->path("url") }
261 $self->scale($resized)
262 unless -e $self->path( file => $resized );
263 return $self->path(url => $resized);
267 my ($self, $is_url, $scale) = @_;
269 Memories->config->{$is_url eq "url" ? "data_store_external" : "data_store" };
270 if ($scale) { $path .= "$scale/" }
271 # Make dir if it doesn't exist, save trouble later
273 if ($is_url ne "url") {mkpath($path);}
274 $path .= $self->id.".".$self->format;
278 sub thumb_url { shift->path(url => Memories->config->{thumb_size}); }
279 sub make_thumb { shift->scale(Memories->config->{thumb_size}, 1); }
283 my ($self, $scale, $swap) = @_;
284 my ($x, $y) = split /x/, $scale;
285 # Find out smaller axis
286 my ($cur_x, $cur_y) = ($self->x, $self->y);
288 if ($cur_x < $cur_y) { $y = 0 } else { $x = 0 }
290 if ($cur_x > $cur_y) { $y = 0 } else { $x = 0 }
292 my $img = Image::Imlib2->load($self->path("file"));
294 cluck "Couldn't open image file ".$self->path("file");
297 $img = $img->create_scaled_image($x, $y);
298 $img->image_set_format("jpeg");
299 my $file = $self->path( file => $scale );
302 cluck "Couldn't write image file $file ($!)";
307 sub edit_tags :Exported {
309 my $photo = $r->objects->[0];
310 my %params = %{$r->params};
312 next unless /delete_(\d+)/;
313 my $tagging = Memories::Tagging->retrieve($1) or next;
314 next unless $tagging->photo->id == $photo->id;
317 $photo->add_tags($params{newtags});
318 $r->template("view");
322 my ($photo, $tagstring) = @_;
324 for my $tag (Tagtools->separate_tags($tagstring)) {
325 $photo->add_to_tags({tag => Memories::Tag->find_or_create({name =>$tag}) })
329 # Work out some common properties from a set of potential photo metadata
331 sub _grovel_metadata {
332 my ($self, @tags) = @_;
333 my %md = map {%$_} values %{$self->exif_info};
335 if ($md{$_} and $md{$_} =~/[^ 0:]/) { return $md{$_} }
342 my $dt = $self->_grovel_metadata(
343 'Shooting Date/Time',
344 'Date/Time Of Digitization',
345 'Date/Time Of Last Modification'
347 if (!$dt) { return $self->uploaded }
348 return Time::Piece->strptime($dt, "%Y:%m:%d %T") || $self->uploaded;
352 shift->_grovel_metadata(
353 'Description', 'Image Description', 'Caption-Abstract'
357 sub title_exif { shift->_grovel_metadata( 'Headline', 'Title'); }
358 sub license { shift->_grovel_metadata( 'Rights Usage Terms', 'Usage Terms' ) }
359 sub copyright { shift->_grovel_metadata( 'Rights', 'Copyright', 'Copyright Notice') }
361 # This one's slightly different since we want everything we can get...
364 my %md = map {%$_} values %{$self->exif_info};
366 map { s/\s+/-/g; lc $_ => 1 }
367 map { split /\s*,\s*/, $md{$_}}
368 grep {$md{$_} and $md{$_} =~/[^ 0:]/}
369 (qw(Keywords Subject City State Location Country Province-State),
370 'Transmission Reference', 'Intellectual Genre',
371 'Country-Primary Location Name'