package CMTD::Helpers; use strict; use warnings; use utf8; use Mojo::Base 'Mojolicious::Plugin'; use Mojo::Util qw(b64_encode); sub register { my ($self, $app) = @_; $app->helper(referrer => sub { my ($c) = @_; my $url = $c->req->headers->referrer || $c->req->param('url'); return $url; }); $app->helper(pageid => sub { my ($c, $url) = @_; return unless $url; my $u = Mojo::URL->new($url); my $site = $u->host; my $path = $u->path; $path =~ s{^/+}{}o; $path =~ s{/+$}{}o; $path =~ y{/.}{-}s; $path =~ s<\.[a-z0-9]{2,4}$><>io; my $md5 = md5_sum($path); return {site => $site, pid => $md5, path => $path}; }); $app->helper(maintenance => sub { my ($c) = @_; eval { my $table = $c->app->config->{captcha}->{table}; my $tries = $c->app->config->{captcha}->{tries}; my $limit = $c->app->config->{captcha}->{limit}; $c->app->db->delete($table, {tries => {'>=' => $tries}}); my $count = $c->app->db->select($table, 'count(id)')->list; if ($count < $limit) { $c->app->db->begin; foreach my $n ($count + 1 .. $limit) { $c->app->log->info("generating captcha's: $n of $limit"); my ($code, $data) = $c->app->captcha->create; next unless $code and $data; my $b64 = 'data:image/jpeg;base64,' . b64_encode($data, ''); $c->app->db->insert($table, { code => $code, data => $b64 }); } $c->app->db->commit; } 1; } or do { chomp $@; $c->app->log->error($@); }; }); $app->helper(sid_by_name => sub { my ($c, $site) = @_; return $self->app->db->select('sites', 'id', {site => $site})->list; }); $app->helper(pid_by_hash => sub { my ($c, $sid, $hash) = @_; return $self->app->db->select('pages', 'id', {sid => $sid, hash => $hash})->list; }); $app->helper(comments_by_pid => sub { my ($c, $pid) = @_; return $self->app->db->select('comments', '*', {pid => $pid}, 'seq')->hashes; }); $app->helper(captcha_by_id => sub { my ($c, $cid) = @_; return $self->app->db->select('captcha', '*', {cid => $cid})->hash; }); $app->helper(add_page => sub { my ($c, $sid, $page) = @_; $self->app->db->insert('pages', { sid => $sid, hash => $page->{hash}, path => $page->{path}, }); }); $app->helper(add_comment => sub { my ($c, $pid, $cm) = @_; my $table = 'comments'; $self->app->db->begin; my $seq = $self->app->db->select($table, 'max(seq)', {pid => $pid})->list; $self->app->db->insert($table, { pid => $pid, seq => $seq, date => time(), name => $cm->{name}, reply => $cm->{reply}, email => $cm->{email}, text => b64_encode($cm->{text}), }); $self->app->db->commit; }); } 1;