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 loved => "rating/(1+rated)",
18 interesting => INTERESTINGNESS_ALGORITHM,
22 while (my($label, $how) = each %order_by) {
23 __PACKAGE__->set_sql($label => qq{
32 $self->view_paged_ordered($r, "$how desc");
34 __PACKAGE__->MODIFY_CODE_ATTRIBUTES(*{$label}{CODE}, "Exported"); # Hack
37 __PACKAGE__->has_many(comments => "Memories::Comment");
38 __PACKAGE__->has_a(uploader => "Memories::User");
39 __PACKAGE__->has_a(uploaded => "Time::Piece",
40 inflate => sub { Time::Piece->strptime(shift, "%Y-%m-%d %H:%M:%S") },
41 deflate => 'datetime',
44 sub do_upload :Exported {
46 my %upload = $r->upload("photo");
48 my $photo = $self->create({
50 uploaded => Time::Piece->new(),
51 title => $r->params->{title},
54 rated => 0, # Oh, the potential for divide by zero errors...
58 if (!open OUT, ">". $photo->path("file")) {
59 die "Can't write ".$photo->path("file")." because $!";
61 # XXX Check it's a JPEG, etc.
63 print OUT $upload{content};
65 my ($x, $y) = dim(image_info($photo->path));
66 $photo->x($x); $photo->y($y);
71 $photo->title($photo->title_exif || $upload{filename});
75 $r->{params}{tags} ||= join " ", map { qq{"$_"} } $photo->tags_exif;
76 $photo->add_tags($r->{params}{tags});
77 $photo->add_to_imageseek_library;
78 Memories->zap_cache();
80 # Add system tags here
81 my $tag = "date:".$photo->shot->ymd;
82 $photo->add_to_system_tags({tag => Memories::SystemTag->find_or_create({name =>$tag}) });
84 # Set it up to go again
85 $r->objects([$photo]);
87 $r->message("Thanks for the upload! ".
88 ($r->{params}{tags} ? ""
89 : "Don't forget to <a href=\"?".$r->config->uri_base."photo/view/".$photo->id."?active=tagedit\">tag your photo</a>"
96 $self->rated or return 0;
97 int($self->rating/$self->rated*10)/10;
100 sub add_rating :Exported {
102 my $photo = $r->{objects}[0];
103 my $delta = $r->{params}{rating};
104 if ($delta < 0 or $delta > 5) { return; } # Scammer
106 $photo->rating($photo->rating() + $delta);
107 $photo->rated($photo->rated() + 1);
108 $r->output(""); # Only used by ajax
113 my $photo = $r->{objects}[0];
114 $photo->hit_count($photo->hit_count()+1);
115 if ($r->{session}{last_search}) {
116 # This is slightly inefficient
117 my @search = split/,/, $r->{session}{last_search};
119 for my $i (0..$#search) {
120 next unless $photo->id == $search[$i];
123 return unless $found > -1;
124 $r->{template_args}{next} = $self->retrieve($search[$found+1])
125 if $found+1 <= $#search;
126 $r->{template_args}{prev} = $self->retrieve($search[$found-1])
130 sub upload :Exported {}
131 sub exif :Exported {}
132 sub comment :Exported {}
133 sub tagedit :Exported {}
134 sub similar :Exported {}
136 use Class::DBI::Plugin::Pager;
137 use Class::DBI::Plugin::AbstractCount;
139 sub view_paged_ordered {
140 my ($self, $r, $how) = @_;
141 my $page = $r->params->{page} || 1;
142 my $pager = $self->pager(
143 per_page => Memories->config->{photos_per_page},
145 syntax => PAGER_SYNTAX,
148 $r->objects([$pager->retrieve_all ]);
149 $r->{template_args}{pager} = $pager;
151 $r->template("paged"); # Set the what using the action name
154 sub add_comment :Exported {
155 my ($self, $r, $photo) = @_;
156 $r->template("view");
157 $r->objects->[0]->add_to_comments({
158 name => $r->params->{name},
159 content => $r->params->{content}
167 use Cache::MemoryCache;
168 use Image::Info qw(dim image_info);
170 my $cache = new Cache::MemoryCache( { 'namespace' => 'MemoriesInfo' });
172 sub add_to_imageseek_library {
174 Image::Seek::cleardb();
175 my $img = Image::Imlib2->load($self->path("file"));
177 Image::Seek::add_image($img, $self->id);
178 # Merge this new one into the main database; there is a bit of a
179 # race condition here. XXX
180 Image::Seek::loaddb(Memories->config->{image_seek});
181 Image::Seek::savedb(Memories->config->{image_seek});
184 sub recommended_tags {
186 my %tags = map { $_->name => $_ }
188 $self->find_similar(3);
193 my ($self, $count) = @_;
194 Image::Seek::cleardb();
195 Image::Seek::loaddb(Memories->config->{image_seek});
196 my @res = map {$_->[0] } Image::Seek::query_id($self->id, $count);
198 map { $self->retrieve($_) } @res;
203 my $orient = $self->exif_info->{EXIF}->{Orientation};
204 return if $orient !~/Rotate (\d+)/i;
206 my $img = Image::Imlib2->load($self->path("file"));
207 $img->image_orientate($steps);
208 $img->save($self->path("file"));
213 my $info = $self->exif_object;
214 return $info if $info;
215 # Get it from the Cache
216 if (!($info = $cache->get($self->id))) {
218 $info = $self->_exif_info;
219 $cache->set($self->id, $info);
221 $self->exif_object($info);
225 my %banned_tags = map { $_ => 1 }
226 qw( CodedCharacterSet ApplicationRecordVersion );
229 my $exifTool = new Image::ExifTool;
230 $exifTool->Options(Group0 => ['IPTC', 'EXIF', 'XMP', 'MakerNotes', 'Composite']);
231 my $info = $exifTool->ImageInfo(shift->path);
233 foreach my $tag ($exifTool->GetFoundTags('Group0')) {
234 next if $banned_tags{$tag};
235 my $group = $exifTool->GetGroup($tag);
236 my $val = $info->{$tag};
237 next if ref $val eq 'SCALAR';
238 next if $val =~ /^[0\s]*$/ or $val =~ /^nil$/;
239 $hash->{$group}->{$exifTool->GetDescription($tag)} = $val;
245 sub dimensions { join "x", $_[0]->x, $_[0]->y }
248 my ($self, $size) = @_;
249 return 1 if $size eq "full";
250 my ($w, $h) = ($self->x, $self->y);
251 my ($w2, $h2) = split /x/, $size;
252 return 1 if $w > $w2 or $h > $h2;
256 sub sized_url { # Use this rather than ->path from TT
257 my ($self, $size) = @_;
258 my $url = Memories->config->{data_store_external};
259 my $resized = Memories->config->{sizes}->[$size];
260 if (!$resized) { cluck "Asked for crazy size $size"; return; }
261 if ($resized eq "full") { return $self->path("url") }
262 $self->scale($resized)
263 unless -e $self->path( file => $resized );
264 return $self->path(url => $resized);
268 my ($self, $is_url, $scale) = @_;
270 Memories->config->{$is_url eq "url" ? "data_store_external" : "data_store" };
271 if ($scale) { $path .= "$scale/" }
272 # Make dir if it doesn't exist, save trouble later
274 if ($is_url ne "url") {mkpath($path);}
275 $path .= $self->id.".".$self->format;
279 sub thumb_url { shift->path(url => Memories->config->{thumb_size}); }
280 sub make_thumb { shift->scale(Memories->config->{thumb_size}, 1); }
284 my ($self, $scale, $swap) = @_;
285 my ($x, $y) = split /x/, $scale;
286 # Find out smaller axis
287 my ($cur_x, $cur_y) = ($self->x, $self->y);
289 if ($cur_x < $cur_y) { $y = 0 } else { $x = 0 }
291 if ($cur_x > $cur_y) { $y = 0 } else { $x = 0 }
293 my $img = Image::Imlib2->load($self->path("file"));
295 cluck "Couldn't open image file ".$self->path("file");
298 $img = $img->create_scaled_image($x, $y);
299 $img->image_set_format("jpeg");
300 my $file = $self->path( file => $scale );
303 cluck "Couldn't write image file $file ($!)";
308 sub edit_tags :Exported {
310 my $photo = $r->objects->[0];
311 my %params = %{$r->params};
313 next unless /delete_(\d+)/;
314 my $tagging = Memories::Tagging->retrieve($1) or next;
315 next unless $tagging->photo->id == $photo->id;
318 $photo->add_tags($params{newtags});
319 $r->template("view");
323 my ($photo, $tagstring) = @_;
325 for my $tag (Tagtools->separate_tags($tagstring)) {
326 $photo->add_to_tags({tag => Memories::Tag->find_or_create({name =>$tag}) })
330 # Work out some common properties from a set of potential photo metadata
332 sub _grovel_metadata {
333 my ($self, @tags) = @_;
334 my %md = map {%$_} values %{$self->exif_info};
336 if ($md{$_} and $md{$_} =~/[^ 0:]/) { return $md{$_} }
343 my $dt = $self->_grovel_metadata(
344 'Shooting Date/Time',
345 'Date/Time Of Digitization',
346 'Date/Time Of Last Modification'
348 if (!$dt) { return $self->uploaded }
349 return Time::Piece->strptime($dt, "%Y:%m:%d %T") || $self->uploaded;
353 shift->_grovel_metadata(
354 'Description', 'Image Description', 'Caption-Abstract'
358 sub title_exif { shift->_grovel_metadata( 'Headline', 'Title'); }
359 sub license { shift->_grovel_metadata( 'Rights Usage Terms', 'Usage Terms' ) }
360 sub copyright { shift->_grovel_metadata( 'Rights', 'Copyright', 'Copyright Notice') }
362 # This one's slightly different since we want everything we can get...
365 my %md = map {%$_} values %{$self->exif_info};
367 map { s/\s+/-/g; lc $_ => 1 }
368 map { split /\s*,\s*/, $md{$_}}
369 grep {$md{$_} and $md{$_} =~/[^ 0:]/}
370 (qw(Keywords Subject City State Location Country Province-State),
371 'Transmission Reference', 'Intellectual Genre',
372 'Country-Primary Location Name'