summaryrefslogtreecommitdiff
path: root/lib/VNDB/Handler/VNEdit.pm
blob: d5fa1060f8c9d69e2e689a2e30f2d108c333407b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352

package VNDB::Handler::VNEdit;

use strict;
use warnings;
use YAWF ':html', ':xml';
use VNDB::Func;


YAWF::register(
  qr{v(?:([1-9]\d*)(?:\.([1-9]\d*))?/edit|/new)}
    => \&edit,
  qr{xml/vn\.xml}          => \&vnxml,
  qr{xml/screenshots\.xml} => \&scrxml,
);


sub edit {
  my($self, $vid, $rev) = @_;

  my $v = $vid && $self->dbVNGet(id => $vid, what => 'extended screenshots relations anime changes', $rev ? (rev => $rev) : ())->[0];
  return 404 if $vid && !$v->{id};
  $rev = undef if !$vid || $v->{cid} == $v->{latest};

  return $self->htmlDenied if !$self->authCan('edit')
    || $vid && ($v->{locked} && !$self->authCan('lock') || $v->{hidden} && !$self->authCan('del'));

  my %b4 = !$vid ? () : (
    (map { $_ => $v->{$_} } qw|title original desc alias length l_wp l_encubed l_renai l_vnn img_nsfw ihid ilock|),
    anime => join(' ', sort { $a <=> $b } map $_->{id}, @{$v->{anime}}),
    vnrelations => join('|||', map $_->{relation}.','.$_->{id}.','.$_->{title}, sort { $a->{id} <=> $b->{id} } @{$v->{relations}}),
    screenshots => join(' ', map sprintf('%d,%d,%d', $_->{id}, $_->{nsfw}?1:0, $_->{rid}), @{$v->{screenshots}}),
  );

  my $frm;
  if($self->reqMethod eq 'POST') {
    $frm = $self->formValidate(
      { name => 'title',       maxlength => 250 },
      { name => 'original',    required => 0, maxlength => 250, default => '' },
      { name => 'alias',       required => 0, maxlength => 500, default => '' },
      { name => 'desc',        required => 0, default => '', maxlength => 10240 },
      { name => 'length',      required => 0, default => 0,  enum => $self->{vn_lengths} },
      { name => 'l_wp',        required => 0, default => '', maxlength => 150 },
      { name => 'l_encubed',   required => 0, default => '', maxlength => 100 },
      { name => 'l_renai',     required => 0, default => '', maxlength => 100 },
      { name => 'l_vnn',       required => 0, default => $b4{l_vnn}||0,  template => 'int' },
      { name => 'anime',       required => 0, default => '' },
      { name => 'img_nsfw',    required => 0, default => 0 },
      { name => 'vnrelations', required => 0, default => '', maxlength => 5000 },
      { name => 'screenshots', required => 0, default => '', maxlength => 1000 },
      { name => 'editsum',     maxlength => 5000 },
      { name => 'ihid',        required  => 0 },
      { name => 'ilock',       required  => 0 },
    );

    # handle image upload
    my $image = _uploadimage($self, $v, $frm);

    if(!$frm->{_err}) {
      # parse and re-sort fields that have multiple representations of the same information
      my $anime = { map +($_=>1), grep /^[0-9]+$/, split /[ ,]+/, $frm->{anime} };
      my $relations = [ map { /^([a-z]+),([0-9]+),(.+)$/ && (!$vid || $2 != $vid) ? [ $1, $2, $3 ] : () } split /\|\|\|/, $frm->{vnrelations} ];
      my $screenshots = [ map /^[0-9]+,[01],[0-9]+$/ ? [split /,/] : (), split / +/, $frm->{screenshots} ];

      $frm->{ihid} = $frm->{ihid}?1:0;
      $frm->{ilock} = $frm->{ilock}?1:0;
      $relations = [] if $frm->{ihid};
      $frm->{anime} = join ' ', sort { $a <=> $b } keys %$anime;
      $frm->{vnrelations} = join '|||', map $_->[0].','.$_->[1].','.$_->[2], sort { $a->[1] <=> $b->[1]} @{$relations};
      $frm->{img_nsfw} = $frm->{img_nsfw} ? 1 : 0;
      $frm->{screenshots} = join ' ', map sprintf('%d,%d,%d', $_->[0], $_->[1]?1:0, $_->[2]), sort { $a->[0] <=> $b->[0] } @$screenshots;

      # nothing changed? just redirect
      return $self->resRedirect("/v$vid", 'post')
        if $vid && !$self->reqUploadFileName('img') && !grep $frm->{$_} ne $b4{$_}, keys %b4;

      # perform the edit/add
      my $nrev = $self->dbItemEdit(v => $vid ? $v->{cid} : undef,
        (map { $_ => $frm->{$_} } qw|title original alias desc length l_wp l_encubed l_renai l_vnn editsum img_nsfw ihid ilock|),
        anime => [ keys %$anime ],
        relations => $relations,
        image => $image,
        screenshots => $screenshots,
      );

      # update reverse relations & relation graph
      if(!$vid && $#$relations >= 0 || $vid && $frm->{vnrelations} ne $b4{vnrelations}) {
        my %old = $vid ? (map { $_->{id} => $_->{relation} } @{$v->{relations}}) : ();
        my %new = map { $_->[1] => $_->[0] } @$relations;
        _updreverse($self, \%old, \%new, $nrev->{iid}, $nrev->{rev});
      }

      return $self->resRedirect("/v$nrev->{iid}.$nrev->{rev}", 'post');
    }
  }

  !exists $frm->{$_} && ($frm->{$_} = $b4{$_}) for (keys %b4);
  $frm->{editsum} = sprintf 'Reverted to revision v%d.%d', $vid, $rev if $rev && !defined $frm->{editsum};

  my $title = $vid ? mt('_vnedit_title_edit', $v->{title}) : mt '_vnedit_title_add';
  $self->htmlHeader(title => $title, noindex => 1);
  $self->htmlMainTabs('v', $v, 'edit') if $vid;
  $self->htmlEditMessage('v', $v, $title);
  _form($self, $v, $frm);
  $self->htmlFooter;
}


sub _uploadimage {
  my($self, $v, $frm) = @_;
  return $v ? $v->{image} : 0 if $frm->{_err} || !$self->reqUploadFileName('img');

  # save to temporary location
  my $tmp = sprintf '%s/static/cv/00/tmp.%d.jpg', $VNDB::ROOT, $$*int(rand(1000)+1);
  $self->reqSaveUpload('img', $tmp);

  # perform some checks
  my $l;
  open(my $T, '<:raw:bytes', $tmp) || die $1;
  read $T, $l, 2;
  close($T);

  $frm->{_err} = [ 'noimage' ] if $l ne pack('H*', 'ffd8') && $l ne pack('H*', '8950');
  $frm->{_err} = [ 'toolarge' ] if -s $tmp > 512*1024;

  if($frm->{_err}) {
    unlink $tmp;
    return undef;
  }

  # get image ID and move it to the correct location
  my $imgid = $self->dbVNImageId;
  my $new = sprintf '%s/static/cv/%02d/%d.jpg', $VNDB::ROOT, $imgid%100, $imgid;
  rename $tmp, $new or die $!;
  chmod 0666, $new;

  return -1*$imgid;
}


sub _form {
  my($self, $v, $frm) = @_;
  my $r = $v ? $self->dbReleaseGet(vid => $v->{id}) : [];
  $self->htmlForm({ frm => $frm, action => $v ? "/v$v->{id}/edit" : '/v/new', editsum => 1, upload => 1 },
  vn_geninfo => [ mt('_vnedit_geninfo'),
    [ input    => short => 'title',     name => mt '_vnedit_frm_title' ],
    [ input    => short => 'original',  name => mt '_vnedit_original' ],
    [ static   => content => mt '_vnedit_original_msg' ],
    [ textarea => short => 'alias',     name => mt('_vnedit_alias'), rows => 4 ],
    [ static   => content => mt '_vnedit_alias_msg' ],
    [ textarea => short => 'desc',      name => mt('_vnedit_desc').'<br /><b class="standout">'.mt('_inenglish').'</b>', rows => 10 ],
    [ static   => content => mt '_vnedit_desc_msg' ],
    [ select   => short => 'length',    name => mt('_vnedit_length'), width => 300, options =>
      [ map [ $_ => mt '_vnlength_'.$_, 2 ], @{$self->{vn_lengths}} ] ],

    [ input    => short => 'l_wp',      name => mt('_vnedit_links'), pre => 'http://en.wikipedia.org/wiki/' ],
    [ input    => short => 'l_encubed', pre => 'http://novelnews.net/tag/', post => '/' ],
    [ input    => short => 'l_renai',   pre => 'http://renai.us/game/', post => '.shtml' ],

    [ input    => short => 'anime',     name => mt '_vnedit_anime' ],
    [ static   => content => mt '_vnedit_anime_msg' ],
  ],

  vn_img => [ mt('_vnedit_image'),
    [ static => nolabel => 1, content => sub {
      div class => 'img';
       p mt '_vnedit_image_none' if !$v || !$v->{image};
       p mt '_vnedit_image_processing' if $v && $v->{image} < 0;
       img src => sprintf("%s/cv/%02d/%d.jpg", $self->{url_static}, $v->{image}%100, $v->{image}), alt => $v->{title} if $v && $v->{image} > 0;
      end;
      div;

       h2 mt '_vnedit_image_upload';
       input type => 'file', class => 'text', name => 'img', id => 'img';
       p mt('_vnedit_image_upload_msg')."\n\n\n";

       h2 mt '_vnedit_image_nsfw';
       input type => 'checkbox', class => 'checkbox', id => 'img_nsfw', name => 'img_nsfw',
         $frm->{img_nsfw} ? (checked => 'checked') : ();
       label class => 'checkbox', for => 'img_nsfw', mt '_vnedit_image_nsfw_check';
       p mt '_vnedit_image_nsfw_msg';
      end;
    }],
  ],

  vn_rel => [ mt('_vnedit_rel'),
    [ hidden   => short => 'vnrelations' ],
    [ static   => nolabel => 1, content => sub {
      h2 mt '_vnedit_rel_sel';
      table;
       tbody id => 'relation_tbl';
        # to be filled using javascript
       end;
      end;

      h2 mt '_vnedit_rel_add';
      table;
       Tr id => 'relation_new';
        td class => 'tc_vn';
         input type => 'text', class => 'text';
        end;
        td class => 'tc_rel';
         txt mt('_vnedit_rel_isa').' ';
         Select;
          option value => $_, mt "_vnrel_$_"
            for (sort { $self->{vn_relations}{$a}[0] <=> $self->{vn_relations}{$b}[0] } keys %{$self->{vn_relations}});
         end;
         txt ' '.mt '_vnedit_rel_of';
        end;
        td class => 'tc_title', $v ? $v->{title} : '';
        td class => 'tc_add';
         a href => '#', mt '_vnedit_rel_addbut';
        end;
       end;
      end;
    }],
  ],

  vn_scr => [ mt('_vnedit_scr'), !@$r ? (
    [ static => nolabel => 1, content => mt '_vnedit_scrnorel' ],
  ) : (
    [ hidden => short => 'screenshots' ],
    [ static => nolabel => 1, content => sub {
      div class => 'warning';
       lit mt '_vnedit_scrmsg';
      end;
      br;
      table;
       tbody id => 'scr_table', '';
      end;
      Select id => 'scr_rel', class => $self->{url_static};
       option value => $_->{id}, sprintf '[%s] %s (r%d)', join(',', @{$_->{languages}}), $_->{title}, $_->{id} for (@$r);
      end;
    }],
  )]

  );
}


# Update reverse relations and regenerate relation graph
# Arguments: %old. %new, vid, rev
#  %old,%new -> { vid2 => relation, .. }
#    from the perspective of vid
#  rev is of the related edit
sub _updreverse {
  my($self, $old, $new, $vid, $rev) = @_;
  my %upd;

  # compare %old and %new
  for (keys %$old, keys %$new) {
    if(exists $$old{$_} and !exists $$new{$_}) {
      $upd{$_} = undef;
    } elsif((!exists $$old{$_} and exists $$new{$_}) || ($$old{$_} ne $$new{$_})) {
      $upd{$_} = $self->{vn_relations}{$$new{$_}}[1];
    }
  }
  return if !keys %upd;

  # edit all related VNs
  for my $i (keys %upd) {
    my $r = $self->dbVNGet(id => $i, what => 'relations')->[0];
    my @newrel = map $_->{id} != $vid ? [ $_->{relation}, $_->{id} ] : (), @{$r->{relations}};
    push @newrel, [ $upd{$i}, $vid ] if $upd{$i};
    $self->dbItemEdit(v => $r->{cid},
      relations => \@newrel,
      editsum => "Reverse relation update caused by revision v$vid.$rev",
      uid => 1, # Multi
    );
  }
}


# peforms a (simple) search and returns the results in XML format
sub vnxml {
  my $self = shift;

  my $q = $self->formValidate({ name => 'q', maxlength => 500 });
  return 404 if $q->{_err};
  $q = $q->{q};

  my($list, $np) = $self->dbVNGet(
    $q =~ /^v([1-9]\d*)/ ? (id => $1) : (search => $q),
    results => 10,
    page => 1,
  );

  $self->resHeader('Content-type' => 'text/xml; charset=UTF-8');
  xml;
  tag 'vns', more => $np ? 'yes' : 'no', query => $q;
   for(@$list) {
     tag 'item', id => $_->{id}, $_->{title};
   }
  end;
}


# handles uploading screenshots and fetching information about them
sub scrxml {
  my $self = shift;
  return $self->htmlDenied if !$self->authCan('edit');
  $self->resHeader('Content-type' => 'text/xml; charset=UTF-8');

  # fetch information about screenshots
  if($self->reqMethod ne 'POST') {
    my $ids = $self->formValidate(
      { name => 'id', required => 1, template => 'int', multi => 1 }
    );
    return 404 if $ids->{_err};
    my $r = $self->dbScreenshotGet($ids->{id});

    xml;
    tag 'screenshots';
     tag 'item', %$_, undef for (@$r);
    end;
    return;
  }

  # upload new screenshot
  my $num = $self->formValidate({name => 'upload', template => 'int'});
  return 404 if $num->{_err};
  my $tmp = sprintf '%s/static/sf/00/tmp.%d.jpg', $VNDB::ROOT, $$*int(rand(1000)+1);
  $self->reqSaveUpload("scr_upl_file_$num->{upload}", $tmp);

  my $id = 0;
  $id = -2 if !-s $tmp;
  if(!$id) {
    my $l;
    open(my $T, '<:raw:bytes', $tmp) || die $1;
    read $T, $l, 2;
    close($T);
    $id = -1 if $l ne pack('H*', 'ffd8') && $l ne pack('H*', '8950');
  }

  if($id) {
    unlink $tmp;
  } else {
    $id = $self->dbScreenshotAdd;
    my $new = sprintf '%s/static/sf/%02d/%d.jpg', $VNDB::ROOT, $id%100, $id;
    rename $tmp, $new or die $!;
    chmod 0666, $new;
  }

  xml;
  # blank stylesheet because some browsers don't allow JS access otherwise
  lit qq|<?xml-stylesheet href="$self->{url_static}/f/blank.css" type="text/css" ?>|;
  tag 'image', id => $id, undef;
}


1;