source: trunk/lib/Vote/DB/common.pm @ 193

Last change on this file since 193 was 190, checked in by nanardon, 15 years ago
  • check dates coherencies in poll settings
  • Property svn:keywords set to Id Rev
File size: 2.3 KB
Line 
1package Vote::DB::common;
2
3# $Id$
4
5use strict;
6use warnings;
7use Vote;
8use DBI;
9use vars qw(@EXPORT);
10use base 'Exporter';
11@EXPORT = qw(gen_uid);
12
13=head1 NAME
14
15Vote::Model::Vote - Catalyst Model
16
17=head1 DESCRIPTION
18
19Catalyst Model.
20
21=cut
22
23sub _newdb {
24    my ($dbstring) = @_;
25    my $db = DBI->connect_cached(
26        'dbi:Pg:' . $dbstring,
27        undef, undef,
28        {
29            RaiseError => 0,
30            AutoCommit => 0,
31            PrintWarn => 0,
32            PrintError => 1,
33        }
34    ) or return;
35    $db->do(q{set DATESTYLE to 'DMY'});
36    return $db;
37}
38
39sub db {
40    my ($self) = @_;
41    return $_[0]->{db} && $_[0]->{db}->ping
42        ? $_[0]->{db}
43        : $_[0]->_newdb($self->{dbstring});
44}
45
46sub mail_header {
47    return(
48        'Content-Type' => 'text/plain; charset=UTF-8; format=flowed',
49        'Content-Transfer-Encoding' => '8bit',
50        'X-Epoll-version' => $Vote::VERSION,
51    );
52}
53
54sub random_string {
55    my $lenght = $_[-1] || 8;
56
57    return join('', map { ('a'..'z', 'A'..'Z', 0..9)[rand 62] } (1..$lenght));
58}
59
60sub gen_enc_passwd {
61    my ($self, $passwd) = @_;
62
63    $passwd ||= random_string(8);
64    return(crypt($passwd, '$1$' . random_string(8) . '$'));
65}
66
67sub dbtime {
68    my ($self) = @_;
69    my $sth = $self->db->prepare(
70        q{select to_char(now(), 'DD/MM/YYYY HH24:MI:SS') as d}
71    );
72
73    $sth->execute();
74    my $res = $sth->fetchrow_hashref;
75    $sth->finish;
76    $res->{d};
77}
78
79sub valid_date {
80    my ($self, $date) = @_;
81    my $res = $self->db->do(
82        sprintf(
83            q{ select %s::timestamp },
84            $self->db->quote($date),
85        )
86    );
87    $res or $self->db->rollback;
88}
89
90sub check_date_max {
91    my ($self, $maxdate, $mindate) = @_;
92    my $sth = $self->db->prepare(
93        sprintf(
94            q{ select %s::timestamp > %s::timestamp as res },
95            $self->db->quote($maxdate),
96            $mindate ? $self->db->quote($mindate) : 'now()',
97        )
98    );
99    $sth->execute or do {
100        $self->db->rollback;
101        return;
102    };
103    my $res = $sth->fetchrow_hashref;
104    $sth->finish;
105    $res->{res}
106}
107
108sub gen_uid {
109    unpack("H*", join("", map { chr(rand(256)) } (0..15)))
110}
111
112=head1 AUTHOR
113
114Thauvin Olivier
115
116=head1 LICENSE
117
118This library is free software, you can redistribute it and/or modify
119it under the same terms as Perl itself or CeCILL.
120
121=cut
122
1231;
Note: See TracBrowser for help on using the repository browser.