1 package Memories::Photo;
5 use File::Temp qw(tempdir);
6 use File::Path qw(rmtree);
10 use Carp qw(cluck confess);
11 use base qw(Memories::DBI Maypole::Model::CDBI::Plain);
12 use constant INTERESTINGNESS_ALGORITHM => '((rating+3)/(rated+1))*(1+rated/hit_count)*(1+hit_count/(select max(hit_count) from photo))';
15 use constant PAGER_SYNTAX => "LimitXY";
16 __PACKAGE__->columns(Essential => qw(id title uploader uploaded x y rating rated hit_count));
17 __PACKAGE__->untaint_columns(printable => [qw/title/]);
18 __PACKAGE__->columns(TEMP => qw/exif_object/);
23 popular => "hit_count",
24 loved => "rating/(1+rated)",
25 interesting => INTERESTINGNESS_ALGORITHM,
29 while (my($label, $how) = each %order_by) {
30 __PACKAGE__->set_sql($label => qq{
39 $self->view_paged_ordered($r, "$how desc");
41 __PACKAGE__->MODIFY_CODE_ATTRIBUTES(*{$label}{CODE}, "Exported"); # Hack
44 __PACKAGE__->has_many(comments => "Memories::Comment");
45 __PACKAGE__->has_a(uploader => "Memories::User");
46 __PACKAGE__->has_a(uploaded => "Time::Piece",
47 inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d %H:%M:%S") },
48 deflate => 'datetime',
51 sub do_upload :Exported {
53 my $upload = $r->{ar}->upload("photo");
55 my @photos = ($self->upload_file($r, $upload->tempname, $upload->filename));
56 my @quarantined = grep { !$_->tags } @photos;
57 # Set it up to go again
59 $r->{session}{quarantined} = join ",", sort map { $_->id} @quarantined;
60 $r->objects(\@quarantined);
61 $r->template("quarantine");
64 $r->objects(\@photos);
65 if (@photos == 0) { $r->template("upload"); return }
66 if (@photos > 1) { $r->template("list") }
67 else { $r->template("view"); }
68 $r->message("Thanks for the upload!");
71 sub quarantine :Exported {
73 my @quarantined = split /,/, $r->{session}{quarantined};
74 my %q = map { $_ => 1 } @quarantined;
75 for (map /(\d+)/,grep /tags\d+/, keys %{$r->{params}}) {
76 my $tags = $r->{params}{"tags$_"};
78 if (my $photo = $self->retrieve($_)) {
79 $photo->add_tags($tags);
83 $r->{session}{quarantined} = join ",", sort keys %q;
84 if (!$r->{session}{quarantined}) {
86 $r->objects([ map { $self->retrieve($_) } @quarantined ]);
88 $r->objects([ map { $self->retrieve($_) } sort keys %q ]);
93 my ($self, $r, $filename, $offered_name) = @_;
94 my $mm = File::MMagic->new;
95 my $res = $mm->checktype_filename($filename);
96 warn "$filename is a $res\n";
97 if ($res =~ m{/x-zip} or $offered_name =~ /t(ar\.)?gz/i) {
98 return $self->upload_archive($r, $filename);
99 } elsif ($res =~ m{image/jpeg}) {
100 return $self->upload_jpeg($r, $filename, $offered_name);
102 $r->message(basename($offered_name).": I can't handle $res files yet");
108 my ($self, $r, $filename, $tags) = @_;
109 $r->{params}{title} = ""; # Kill that dead.
110 my $archive = Archive::Any->new($filename);
112 $archive->extract($dir);
114 find({ wanted => sub { return unless -f $_;
115 push @results, $self->upload_file($r, $_, $_) },
116 no_chdir => 1}, $dir);
122 my ($self, $r, $filename, $offered_name) = @_;
123 my $photo = $self->create({
124 uploader => $r->user,
125 uploaded => Time::Piece->new(),
126 title => ($r->{params}{title} || basename($offered_name)),
131 if (!copy($filename, $photo->path("file"))) {
132 $photo->delete(); die "Couldn't copy photo: $!";
134 my ($x, $y) = dim(image_info($photo->path));
135 $photo->x($x); $photo->y($y);
140 $photo->title($photo->title_exif || basename($filename));
144 my $tags = $r->{params}{tags}.join " ", map { qq{"$_"} } $photo->tags_exif;
145 $photo->add_tags($tags);
146 $photo->add_to_imageseek_library;
147 Memories->zap_cache();
149 # Add system tags here
150 my $tag = "date:".$photo->shot->ymd;
151 $photo->add_to_system_tags({tag => Memories::SystemTag->find_or_create({name =>$tag}) });
157 $self->rated or return 0;
158 int($self->rating/$self->rated*10)/10;
161 sub add_rating :Exported {
163 my $photo = $r->{objects}[0];
164 my $delta = $r->{params}{rating};
165 if ($delta < 0 or $delta > 5) { return; } # Scammer
167 $photo->rating($photo->rating() + $delta);
168 $photo->rated($photo->rated() + 1);
169 $r->output(""); # Only used by ajax
174 my $photo = $r->{objects}[0];
175 $photo->hit_count($photo->hit_count()+1);
176 if ($r->{session}{last_search}) {
177 # This is slightly inefficient
178 my @search = split/,/, $r->{session}{last_search};
180 for my $i (0..$#search) {
181 next unless $photo->id == $search[$i];
184 return unless $found > -1;
185 $r->{template_args}{next} = $self->retrieve($search[$found+1])
186 if $found+1 <= $#search;
187 $r->{template_args}{prev} = $self->retrieve($search[$found-1])
191 sub upload :Exported {}
192 sub exif :Exported {}
193 sub comment :Exported {}
194 sub tagedit :Exported {}
195 sub similar :Exported {}
196 sub sized :Exported {}
198 use Class::DBI::Plugin::Pager;
199 use Class::DBI::Plugin::AbstractCount;
201 sub view_paged_ordered {
202 my ($self, $r, $how) = @_;
203 my $page = $r->params->{page} || 1;
204 my $pager = $self->pager(
205 per_page => Memories->config->{photos_per_page},
207 syntax => PAGER_SYNTAX,
210 $r->objects([$pager->retrieve_all ]);
211 $r->{template_args}{pager} = $pager;
213 $r->template("paged"); # Set the what using the action name
216 sub add_comment :Exported {
217 my ($self, $r, $photo) = @_;
218 $r->template("view");
219 $r->objects->[0]->add_to_comments({
220 name => $r->params->{name},
221 content => $r->params->{content}
229 use Cache::MemoryCache;
230 use Image::Info qw(dim image_info);
232 my $cache = new Cache::MemoryCache( { 'namespace' => 'MemoriesInfo' });
234 sub add_to_imageseek_library {
236 Image::Seek::cleardb();
237 my $img = Image::Imlib2->load($self->path("file"));
239 Image::Seek::add_image($img, $self->id);
240 # Merge this new one into the main database; there is a bit of a
241 # race condition here. XXX
242 Image::Seek::loaddb(Memories->config->{image_seek});
243 Image::Seek::savedb(Memories->config->{image_seek});
246 sub recommended_tags {
248 my %tags = map { $_->name => $_ }
250 $self->find_similar(3);
255 my ($self, $count) = @_;
256 Image::Seek::cleardb();
257 Image::Seek::loaddb(Memories->config->{image_seek});
258 my @res = map {$_->[0] } Image::Seek::query_id($self->id, $count);
260 map { $self->retrieve($_) } @res;
265 my $orient = $self->exif_info->{EXIF}->{Orientation};
266 return if $orient !~/Rotate (\d+)/i;
268 my $img = Image::Imlib2->load($self->path("file"));
269 $img->image_orientate($steps);
270 $img->save($self->path("file"));
275 my $info = $self->exif_object;
276 return $info if $info;
277 # Get it from the Cache
278 if (!($info = $cache->get($self->id))) {
280 $info = $self->_exif_info;
281 $cache->set($self->id, $info);
283 $self->exif_object($info);
287 my %banned_tags = map { $_ => 1 }
288 qw( CodedCharacterSet ApplicationRecordVersion );
291 my $exifTool = new Image::ExifTool;
292 $exifTool->Options(Group0 => ['IPTC', 'EXIF', 'XMP', 'MakerNotes', 'Composite']);
293 my $info = $exifTool->ImageInfo(shift->path);
295 foreach my $tag ($exifTool->GetFoundTags('Group0')) {
296 next if $banned_tags{$tag};
297 my $group = $exifTool->GetGroup($tag);
298 my $val = $info->{$tag};
299 next if ref $val eq 'SCALAR';
300 next if $val =~ /^[0\s]*$/ or $val =~ /^nil$/;
301 $hash->{$group}->{$exifTool->GetDescription($tag)} = $val;
307 sub dimensions { join "x", $_[0]->x, $_[0]->y }
310 my ($self, $size) = @_;
311 return 1 if $size eq "full";
312 my ($w, $h) = ($self->x, $self->y);
313 my ($w2, $h2) = split /x/, $size;
314 return 1 if $w > $w2 or $h > $h2;
318 sub sized_url { # Use this rather than ->path from TT
319 my ($self, $size) = @_;
320 my $url = Memories->config->{data_store_external};
321 my $resized = Memories->config->{sizes}->[$size];
322 if (!$resized) { cluck "Asked for crazy size $size"; return; }
323 if ($resized eq "full") { return $self->path("url") }
324 warn "Looking for path ".$self->path(file => $resized);
325 $self->scale($resized)
326 unless -e $self->path( file => $resized );
327 return $self->path(url => $resized);
331 my ($self, $is_url, $scale) = @_;
333 Memories->config->{$is_url eq "url" ? "data_store_external" : "data_store" };
334 if ($scale) { $path .= "$scale/" }
335 # Make dir if it doesn't exist, save trouble later
337 if ($is_url ne "url") {mkpath($path);}
338 $path .= $self->id.".".$self->format;
342 sub thumb_url { shift->path(url => Memories->config->{thumb_size}); }
343 sub make_thumb { shift->scale(Memories->config->{thumb_size}, 1); }
347 my ($self, $scale, $swap) = @_;
348 my ($x, $y) = split /x/, $scale;
349 # Find out smaller axis
350 my ($cur_x, $cur_y) = ($self->x, $self->y);
352 if ($cur_x < $cur_y) { $y = 0 } else { $x = 0 }
354 if ($cur_x > $cur_y) { $y = 0 } else { $x = 0 }
356 my $img = Image::Imlib2->load($self->path("file"));
358 cluck "Couldn't open image file ".$self->path("file");
361 $img = $img->create_scaled_image($x, $y);
362 $img->image_set_format("jpeg");
363 my $file = $self->path( file => $scale );
366 cluck "Couldn't write image file $file ($!)";
371 sub edit_tags :Exported {
373 my $photo = $r->objects->[0];
374 my %params = %{$r->params};
375 my $exifTool = new Image::ExifTool;
377 next unless /delete_(\d+)/;
378 my $tagging = Memories::Tagging->retrieve($1) or next;
379 next unless $tagging->photo->id == $photo->id;
380 $exifTool->SetNewValue(Keywords => $1, DelValue => 1);
383 $exifTool->WriteInfo($photo->path);
384 $photo->add_tags($params{newtags});
385 $r->template("view");
389 my ($photo, $tagstring) = @_;
390 my $exifTool = new Image::ExifTool;
392 for my $tag (Tagtools->separate_tags($tagstring)) {
393 $photo->add_to_tags({tag => Memories::Tag->find_or_create({name =>$tag}) });
394 $exifTool->SetNewValue(Keywords => $tag, AddValue => 1);
396 $exifTool->WriteInfo($photo->path);
399 # Work out some common properties from a set of potential photo metadata
401 sub _grovel_metadata {
402 my ($self, @tags) = @_;
403 my %md = map {%$_} values %{$self->exif_info};
405 if ($md{$_} and $md{$_} =~/[^ 0:]/) { return $md{$_} }
412 my $dt = $self->_grovel_metadata(
413 'Shooting Date/Time',
414 'Date/Time Of Digitization',
415 'Date/Time Of Last Modification'
417 if (!$dt) { return $self->uploaded }
418 return Time::Piece->strptime($dt, "%Y:%m:%d %T") || $self->uploaded;
422 shift->_grovel_metadata(
423 'Description', 'Image Description', 'Caption-Abstract'
427 sub title_exif { shift->_grovel_metadata( 'Headline', 'Title'); }
428 sub license { shift->_grovel_metadata( 'Rights Usage Terms', 'Usage Terms' ) }
429 sub copyright { shift->_grovel_metadata( 'Rights', 'Copyright', 'Copyright Notice') }
431 # This one's slightly different since we want everything we can get...
434 my %md = map {%$_} values %{$self->exif_info};
436 map { s/\s+/-/g; lc $_ => 1 }
437 map { split /\s*,\s*/, $md{$_}}
438 grep {$md{$_} and $md{$_} =~/[^ 0:]/}
439 (qw(Keywords Subject City State Location Country Province-State),
440 'Transmission Reference', 'Intellectual Genre',
441 'Country-Primary Location Name'