1 package Memories::Photo;
6 use Carp qw(cluck confess);
7 use base qw(Memories::DBI Maypole::Model::CDBI::Plain);
8 use constant INTERESTINGNESS_ALGORITHM => '((rating+3)/(rated+1))*(1+rated/hit_count)*(1+hit_count/(select max(hit_count) from photo))';
11 use constant PAGER_SYNTAX => "LimitXY";
12 __PACKAGE__->columns(Essential => qw(id title uploader uploaded x y rating rated hit_count));
13 __PACKAGE__->untaint_columns(printable => [qw/title/]);
14 __PACKAGE__->columns(TEMP => qw/exif_object/);
19 popular => "hit_count",
20 loved => "rating/(1+rated)",
21 interesting => INTERESTINGNESS_ALGORITHM,
25 while (my($label, $how) = each %order_by) {
26 __PACKAGE__->set_sql($label => qq{
35 $self->view_paged_ordered($r, "$how desc");
37 __PACKAGE__->MODIFY_CODE_ATTRIBUTES(*{$label}{CODE}, "Exported"); # Hack
40 __PACKAGE__->has_many(comments => "Memories::Comment");
41 __PACKAGE__->has_a(uploader => "Memories::User");
42 __PACKAGE__->has_a(uploaded => "Time::Piece",
43 inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d %H:%M:%S") },
44 deflate => 'datetime',
47 sub do_upload :Exported {
49 my $upload = $r->{ar}->upload("photo");
51 my @photos = ($self->upload_jpeg($upload->tempname, ($r->params->{title}||basename($upload->filename)), $r->params->{tags}, $r));
52 my @quarantined = grep { !$_->tags } @photos;
53 warn "Quarantined these photos: ".join(",", map {$_->id} @quarantined);
54 # Set it up to go again
56 $r->{session}{quarantined} = join ",", sort map { $_->id} @quarantined;
57 warn "Setting quarantineined to: ".( join ",", sort map { $_->id} @quarantined);
58 $r->objects(\@quarantined);
59 $r->template("quarantine");
62 $r->objects(\@photos);
63 if (@photos > 1) { $r->template("list") }
64 else { $r->template("view"); }
65 $r->message("Thanks for the upload!");
68 sub quarantine :Exported {
70 my @quarantined = split /,/, $r->{session}{quarantined};
71 my %q = map { $_ => 1 } @quarantined;
72 warn "Before we had these quarantined: @{[ keys %q ]}";
73 for (map /(\d+)/,grep /tags\d+/, keys %{$r->{params}}) {
74 my $tags = $r->{params}{"tags$_"};
75 warn "Got tags for $_: <$tags>";
77 if (my $photo = $self->retrieve($_)) {
78 $photo->add_tags($tags);
82 $r->{session}{quarantined} = join ",", sort keys %q;
83 warn "After, we have these quarantined: @{[ keys %q ]}";
84 warn "And we set session to $r->{session}{quarantined}";
85 if (!$r->{session}{quarantined}) {
87 $r->objects([ map { $self->retrieve($_) } @quarantined ]);
89 $r->objects([ map { $self->retrieve($_) } sort keys %q ]);
94 my ($self, $filename, $title, $tags, $r) = @_;
95 my $photo = $self->create({
97 uploaded => Time::Piece->new(),
103 if (!copy($filename, $photo->path("file"))) {
104 $photo->delete(); die "Couldn't copy photo: $!";
106 my ($x, $y) = dim(image_info($photo->path));
107 $photo->x($x); $photo->y($y);
112 $photo->title($photo->title_exif || basename($filename));
116 $tags ||= join " ", map { qq{"$_"} } $photo->tags_exif;
117 $photo->add_tags($tags);
118 $photo->add_to_imageseek_library;
119 Memories->zap_cache();
121 # Add system tags here
122 my $tag = "date:".$photo->shot->ymd;
123 $photo->add_to_system_tags({tag => Memories::SystemTag->find_or_create({name =>$tag}) });
129 $self->rated or return 0;
130 int($self->rating/$self->rated*10)/10;
133 sub add_rating :Exported {
135 my $photo = $r->{objects}[0];
136 my $delta = $r->{params}{rating};
137 if ($delta < 0 or $delta > 5) { return; } # Scammer
139 $photo->rating($photo->rating() + $delta);
140 $photo->rated($photo->rated() + 1);
141 $r->output(""); # Only used by ajax
146 my $photo = $r->{objects}[0];
147 $photo->hit_count($photo->hit_count()+1);
148 if ($r->{session}{last_search}) {
149 # This is slightly inefficient
150 my @search = split/,/, $r->{session}{last_search};
152 for my $i (0..$#search) {
153 next unless $photo->id == $search[$i];
156 return unless $found > -1;
157 $r->{template_args}{next} = $self->retrieve($search[$found+1])
158 if $found+1 <= $#search;
159 $r->{template_args}{prev} = $self->retrieve($search[$found-1])
163 sub upload :Exported {}
164 sub exif :Exported {}
165 sub comment :Exported {}
166 sub tagedit :Exported {}
167 sub similar :Exported {}
168 sub sized :Exported {}
170 use Class::DBI::Plugin::Pager;
171 use Class::DBI::Plugin::AbstractCount;
173 sub view_paged_ordered {
174 my ($self, $r, $how) = @_;
175 my $page = $r->params->{page} || 1;
176 my $pager = $self->pager(
177 per_page => Memories->config->{photos_per_page},
179 syntax => PAGER_SYNTAX,
182 $r->objects([$pager->retrieve_all ]);
183 $r->{template_args}{pager} = $pager;
185 $r->template("paged"); # Set the what using the action name
188 sub add_comment :Exported {
189 my ($self, $r, $photo) = @_;
190 $r->template("view");
191 $r->objects->[0]->add_to_comments({
192 name => $r->params->{name},
193 content => $r->params->{content}
201 use Cache::MemoryCache;
202 use Image::Info qw(dim image_info);
204 my $cache = new Cache::MemoryCache( { 'namespace' => 'MemoriesInfo' });
206 sub add_to_imageseek_library {
208 Image::Seek::cleardb();
209 my $img = Image::Imlib2->load($self->path("file"));
211 Image::Seek::add_image($img, $self->id);
212 # Merge this new one into the main database; there is a bit of a
213 # race condition here. XXX
214 Image::Seek::loaddb(Memories->config->{image_seek});
215 Image::Seek::savedb(Memories->config->{image_seek});
218 sub recommended_tags {
220 my %tags = map { $_->name => $_ }
222 $self->find_similar(3);
227 my ($self, $count) = @_;
228 Image::Seek::cleardb();
229 Image::Seek::loaddb(Memories->config->{image_seek});
230 my @res = map {$_->[0] } Image::Seek::query_id($self->id, $count);
232 map { $self->retrieve($_) } @res;
237 my $orient = $self->exif_info->{EXIF}->{Orientation};
238 return if $orient !~/Rotate (\d+)/i;
240 my $img = Image::Imlib2->load($self->path("file"));
241 $img->image_orientate($steps);
242 $img->save($self->path("file"));
247 my $info = $self->exif_object;
248 return $info if $info;
249 # Get it from the Cache
250 if (!($info = $cache->get($self->id))) {
252 $info = $self->_exif_info;
253 $cache->set($self->id, $info);
255 $self->exif_object($info);
259 my %banned_tags = map { $_ => 1 }
260 qw( CodedCharacterSet ApplicationRecordVersion );
263 my $exifTool = new Image::ExifTool;
264 $exifTool->Options(Group0 => ['IPTC', 'EXIF', 'XMP', 'MakerNotes', 'Composite']);
265 my $info = $exifTool->ImageInfo(shift->path);
267 foreach my $tag ($exifTool->GetFoundTags('Group0')) {
268 next if $banned_tags{$tag};
269 my $group = $exifTool->GetGroup($tag);
270 my $val = $info->{$tag};
271 next if ref $val eq 'SCALAR';
272 next if $val =~ /^[0\s]*$/ or $val =~ /^nil$/;
273 $hash->{$group}->{$exifTool->GetDescription($tag)} = $val;
279 sub dimensions { join "x", $_[0]->x, $_[0]->y }
282 my ($self, $size) = @_;
283 return 1 if $size eq "full";
284 my ($w, $h) = ($self->x, $self->y);
285 my ($w2, $h2) = split /x/, $size;
286 return 1 if $w > $w2 or $h > $h2;
290 sub sized_url { # Use this rather than ->path from TT
291 my ($self, $size) = @_;
292 my $url = Memories->config->{data_store_external};
293 my $resized = Memories->config->{sizes}->[$size];
294 if (!$resized) { cluck "Asked for crazy size $size"; return; }
295 if ($resized eq "full") { return $self->path("url") }
296 $self->scale($resized)
297 unless -e $self->path( file => $resized );
298 return $self->path(url => $resized);
302 my ($self, $is_url, $scale) = @_;
304 Memories->config->{$is_url eq "url" ? "data_store_external" : "data_store" };
305 if ($scale) { $path .= "$scale/" }
306 # Make dir if it doesn't exist, save trouble later
308 if ($is_url ne "url") {mkpath($path);}
309 $path .= $self->id.".".$self->format;
313 sub thumb_url { shift->path(url => Memories->config->{thumb_size}); }
314 sub make_thumb { shift->scale(Memories->config->{thumb_size}, 1); }
318 my ($self, $scale, $swap) = @_;
319 my ($x, $y) = split /x/, $scale;
320 # Find out smaller axis
321 my ($cur_x, $cur_y) = ($self->x, $self->y);
323 if ($cur_x < $cur_y) { $y = 0 } else { $x = 0 }
325 if ($cur_x > $cur_y) { $y = 0 } else { $x = 0 }
327 my $img = Image::Imlib2->load($self->path("file"));
329 cluck "Couldn't open image file ".$self->path("file");
332 $img = $img->create_scaled_image($x, $y);
333 $img->image_set_format("jpeg");
334 my $file = $self->path( file => $scale );
337 cluck "Couldn't write image file $file ($!)";
342 sub edit_tags :Exported {
344 my $photo = $r->objects->[0];
345 my %params = %{$r->params};
347 next unless /delete_(\d+)/;
348 my $tagging = Memories::Tagging->retrieve($1) or next;
349 next unless $tagging->photo->id == $photo->id;
352 $photo->add_tags($params{newtags});
353 $r->template("view");
357 my ($photo, $tagstring) = @_;
359 for my $tag (Tagtools->separate_tags($tagstring)) {
360 $photo->add_to_tags({tag => Memories::Tag->find_or_create({name =>$tag}) })
364 # Work out some common properties from a set of potential photo metadata
366 sub _grovel_metadata {
367 my ($self, @tags) = @_;
368 my %md = map {%$_} values %{$self->exif_info};
370 if ($md{$_} and $md{$_} =~/[^ 0:]/) { return $md{$_} }
377 my $dt = $self->_grovel_metadata(
378 'Shooting Date/Time',
379 'Date/Time Of Digitization',
380 'Date/Time Of Last Modification'
382 if (!$dt) { return $self->uploaded }
383 return Time::Piece->strptime($dt, "%Y:%m:%d %T") || $self->uploaded;
387 shift->_grovel_metadata(
388 'Description', 'Image Description', 'Caption-Abstract'
392 sub title_exif { shift->_grovel_metadata( 'Headline', 'Title'); }
393 sub license { shift->_grovel_metadata( 'Rights Usage Terms', 'Usage Terms' ) }
394 sub copyright { shift->_grovel_metadata( 'Rights', 'Copyright', 'Copyright Notice') }
396 # This one's slightly different since we want everything we can get...
399 my %md = map {%$_} values %{$self->exif_info};
401 map { s/\s+/-/g; lc $_ => 1 }
402 map { split /\s*,\s*/, $md{$_}}
403 grep {$md{$_} and $md{$_} =~/[^ 0:]/}
404 (qw(Keywords Subject City State Location Country Province-State),
405 'Transmission Reference', 'Intellectual Genre',
406 'Country-Primary Location Name'