1 package Memories::Photo;
5 use Carp qw(cluck confess);
6 use base qw(Memories::DBI Maypole::Model::CDBI::Plain);
7 use constant INTERESTINGNESS_ALGORITHM => '((rating+3)/(rated+1))*(1+rated/hit_count)*(1+hit_count/(select max(hit_count) from photo))';
10 use constant PAGER_SYNTAX => "LimitXY";
11 __PACKAGE__->columns(Essential => qw(id title uploader uploaded x y rating rated hit_count));
12 __PACKAGE__->untaint_columns(printable => [qw/title/]);
13 __PACKAGE__->columns(TEMP => qw/exif_object/);
18 popular => "hit_count",
19 loved => "rating/(1+rated)",
20 interesting => INTERESTINGNESS_ALGORITHM,
24 while (my($label, $how) = each %order_by) {
25 __PACKAGE__->set_sql($label => qq{
34 $self->view_paged_ordered($r, "$how desc");
36 __PACKAGE__->MODIFY_CODE_ATTRIBUTES(*{$label}{CODE}, "Exported"); # Hack
39 __PACKAGE__->has_many(comments => "Memories::Comment");
40 __PACKAGE__->has_a(uploader => "Memories::User");
41 __PACKAGE__->has_a(uploaded => "Time::Piece",
42 inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d %H:%M:%S") },
43 deflate => 'datetime',
46 sub do_upload :Exported {
48 my $upload = $r->{ar}->upload("photo");
50 my @photos = ($self->upload_jpeg($upload->tempname, ($r->params->{title}||basename($upload->filename)), $r->params->{tags}, $r));
51 my @quarantined = grep { !$_->tags } @photos;
52 warn "Quarantined these photos: ".join(",", map {$_->id} @quarantined);
53 # Set it up to go again
55 $r->{session}{quarantined} = join ",", sort map { $_->id} @quarantined;
56 warn "Setting quarantineined to: ".( join ",", sort map { $_->id} @quarantined);
57 $r->objects(\@quarantined);
58 $r->template("quarantine");
61 $r->objects(\@photos);
62 if (@photos > 1) { $r->template("list") }
63 else { $r->template("view"); }
64 $r->message("Thanks for the upload!");
67 sub quarantine :Exported {
69 my @quarantined = split /,/, $r->{session}{quarantined};
70 my %q = map { $_ => 1 } @quarantined;
71 warn "Before we had these quarantined: @{[ keys %q ]}";
72 for (map /(\d+)/,grep /tags\d+/, keys %{$r->{params}}) {
73 my $tags = $r->{params}{"tags$_"};
74 warn "Got tags for $_: <$tags>";
76 if (my $photo = $self->retrieve($_)) {
77 $photo->add_tags($tags);
81 $r->{session}{quarantined} = join ",", sort keys %q;
82 warn "After, we have these quarantined: @{[ keys %q ]}";
83 warn "And we set session to $r->{session}{quarantined}";
84 if (!$r->{session}{quarantined}) {
86 $r->objects([ map { $self->retrieve($_) } @quarantined ]);
88 $r->objects([ map { $self->retrieve($_) } sort keys %q ]);
93 my ($self, $filename, $title, $tags, $r) = @_;
94 my $photo = $self->create({
96 uploaded => Time::Piece->new(),
102 if (!copy($filename, $photo->path("file"))) {
103 $photo->delete(); die "Couldn't copy photo: $!";
105 my ($x, $y) = dim(image_info($photo->path));
106 $photo->x($x); $photo->y($y);
111 $photo->title($photo->title_exif || basename($filename));
115 $tags ||= join " ", map { qq{"$_"} } $photo->tags_exif;
116 $photo->add_tags($tags);
117 $photo->add_to_imageseek_library;
118 Memories->zap_cache();
120 # Add system tags here
121 my $tag = "date:".$photo->shot->ymd;
122 $photo->add_to_system_tags({tag => Memories::SystemTag->find_or_create({name =>$tag}) });
128 $self->rated or return 0;
129 int($self->rating/$self->rated*10)/10;
132 sub add_rating :Exported {
134 my $photo = $r->{objects}[0];
135 my $delta = $r->{params}{rating};
136 if ($delta < 0 or $delta > 5) { return; } # Scammer
138 $photo->rating($photo->rating() + $delta);
139 $photo->rated($photo->rated() + 1);
140 $r->output(""); # Only used by ajax
145 my $photo = $r->{objects}[0];
146 $photo->hit_count($photo->hit_count()+1);
147 if ($r->{session}{last_search}) {
148 # This is slightly inefficient
149 my @search = split/,/, $r->{session}{last_search};
151 for my $i (0..$#search) {
152 next unless $photo->id == $search[$i];
155 return unless $found > -1;
156 $r->{template_args}{next} = $self->retrieve($search[$found+1])
157 if $found+1 <= $#search;
158 $r->{template_args}{prev} = $self->retrieve($search[$found-1])
162 sub upload :Exported {}
163 sub exif :Exported {}
164 sub comment :Exported {}
165 sub tagedit :Exported {}
166 sub similar :Exported {}
167 sub sized :Exported {}
169 use Class::DBI::Plugin::Pager;
170 use Class::DBI::Plugin::AbstractCount;
172 sub view_paged_ordered {
173 my ($self, $r, $how) = @_;
174 my $page = $r->params->{page} || 1;
175 my $pager = $self->pager(
176 per_page => Memories->config->{photos_per_page},
178 syntax => PAGER_SYNTAX,
181 $r->objects([$pager->retrieve_all ]);
182 $r->{template_args}{pager} = $pager;
184 $r->template("paged"); # Set the what using the action name
187 sub add_comment :Exported {
188 my ($self, $r, $photo) = @_;
189 $r->template("view");
190 $r->objects->[0]->add_to_comments({
191 name => $r->params->{name},
192 content => $r->params->{content}
200 use Cache::MemoryCache;
201 use Image::Info qw(dim image_info);
203 my $cache = new Cache::MemoryCache( { 'namespace' => 'MemoriesInfo' });
205 sub add_to_imageseek_library {
207 Image::Seek::cleardb();
208 my $img = Image::Imlib2->load($self->path("file"));
210 Image::Seek::add_image($img, $self->id);
211 # Merge this new one into the main database; there is a bit of a
212 # race condition here. XXX
213 Image::Seek::loaddb(Memories->config->{image_seek});
214 Image::Seek::savedb(Memories->config->{image_seek});
217 sub recommended_tags {
219 my %tags = map { $_->name => $_ }
221 $self->find_similar(3);
226 my ($self, $count) = @_;
227 Image::Seek::cleardb();
228 Image::Seek::loaddb(Memories->config->{image_seek});
229 my @res = map {$_->[0] } Image::Seek::query_id($self->id, $count);
231 map { $self->retrieve($_) } @res;
236 my $orient = $self->exif_info->{EXIF}->{Orientation};
237 return if $orient !~/Rotate (\d+)/i;
239 my $img = Image::Imlib2->load($self->path("file"));
240 $img->image_orientate($steps);
241 $img->save($self->path("file"));
246 my $info = $self->exif_object;
247 return $info if $info;
248 # Get it from the Cache
249 if (!($info = $cache->get($self->id))) {
251 $info = $self->_exif_info;
252 $cache->set($self->id, $info);
254 $self->exif_object($info);
258 my %banned_tags = map { $_ => 1 }
259 qw( CodedCharacterSet ApplicationRecordVersion );
262 my $exifTool = new Image::ExifTool;
263 $exifTool->Options(Group0 => ['IPTC', 'EXIF', 'XMP', 'MakerNotes', 'Composite']);
264 my $info = $exifTool->ImageInfo(shift->path);
266 foreach my $tag ($exifTool->GetFoundTags('Group0')) {
267 next if $banned_tags{$tag};
268 my $group = $exifTool->GetGroup($tag);
269 my $val = $info->{$tag};
270 next if ref $val eq 'SCALAR';
271 next if $val =~ /^[0\s]*$/ or $val =~ /^nil$/;
272 $hash->{$group}->{$exifTool->GetDescription($tag)} = $val;
278 sub dimensions { join "x", $_[0]->x, $_[0]->y }
281 my ($self, $size) = @_;
282 return 1 if $size eq "full";
283 my ($w, $h) = ($self->x, $self->y);
284 my ($w2, $h2) = split /x/, $size;
285 return 1 if $w > $w2 or $h > $h2;
289 sub sized_url { # Use this rather than ->path from TT
290 my ($self, $size) = @_;
291 my $url = Memories->config->{data_store_external};
292 my $resized = Memories->config->{sizes}->[$size];
293 if (!$resized) { cluck "Asked for crazy size $size"; return; }
294 if ($resized eq "full") { return $self->path("url") }
295 $self->scale($resized)
296 unless -e $self->path( file => $resized );
297 return $self->path(url => $resized);
301 my ($self, $is_url, $scale) = @_;
303 Memories->config->{$is_url eq "url" ? "data_store_external" : "data_store" };
304 if ($scale) { $path .= "$scale/" }
305 # Make dir if it doesn't exist, save trouble later
307 if ($is_url ne "url") {mkpath($path);}
308 $path .= $self->id.".".$self->format;
312 sub thumb_url { shift->path(url => Memories->config->{thumb_size}); }
313 sub make_thumb { shift->scale(Memories->config->{thumb_size}, 1); }
317 my ($self, $scale, $swap) = @_;
318 my ($x, $y) = split /x/, $scale;
319 # Find out smaller axis
320 my ($cur_x, $cur_y) = ($self->x, $self->y);
322 if ($cur_x < $cur_y) { $y = 0 } else { $x = 0 }
324 if ($cur_x > $cur_y) { $y = 0 } else { $x = 0 }
326 my $img = Image::Imlib2->load($self->path("file"));
328 cluck "Couldn't open image file ".$self->path("file");
331 $img = $img->create_scaled_image($x, $y);
332 $img->image_set_format("jpeg");
333 my $file = $self->path( file => $scale );
336 cluck "Couldn't write image file $file ($!)";
341 sub edit_tags :Exported {
343 my $photo = $r->objects->[0];
344 my %params = %{$r->params};
346 next unless /delete_(\d+)/;
347 my $tagging = Memories::Tagging->retrieve($1) or next;
348 next unless $tagging->photo->id == $photo->id;
351 $photo->add_tags($params{newtags});
352 $r->template("view");
356 my ($photo, $tagstring) = @_;
358 for my $tag (Tagtools->separate_tags($tagstring)) {
359 $photo->add_to_tags({tag => Memories::Tag->find_or_create({name =>$tag}) })
363 # Work out some common properties from a set of potential photo metadata
365 sub _grovel_metadata {
366 my ($self, @tags) = @_;
367 my %md = map {%$_} values %{$self->exif_info};
369 if ($md{$_} and $md{$_} =~/[^ 0:]/) { return $md{$_} }
376 my $dt = $self->_grovel_metadata(
377 'Shooting Date/Time',
378 'Date/Time Of Digitization',
379 'Date/Time Of Last Modification'
381 if (!$dt) { return $self->uploaded }
382 return Time::Piece->strptime($dt, "%Y:%m:%d %T") || $self->uploaded;
386 shift->_grovel_metadata(
387 'Description', 'Image Description', 'Caption-Abstract'
391 sub title_exif { shift->_grovel_metadata( 'Headline', 'Title'); }
392 sub license { shift->_grovel_metadata( 'Rights Usage Terms', 'Usage Terms' ) }
393 sub copyright { shift->_grovel_metadata( 'Rights', 'Copyright', 'Copyright Notice') }
395 # This one's slightly different since we want everything we can get...
398 my %md = map {%$_} values %{$self->exif_info};
400 map { s/\s+/-/g; lc $_ => 1 }
401 map { split /\s*,\s*/, $md{$_}}
402 grep {$md{$_} and $md{$_} =~/[^ 0:]/}
403 (qw(Keywords Subject City State Location Country Province-State),
404 'Transmission Reference', 'Intellectual Genre',
405 'Country-Primary Location Name'