3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20 use DateTime::Format::MySQL;
21 use DBI qw(:sql_types);
24 use Koha::DateUtils qw(dt_from_string);
26 use base qw(Koha::Object);
30 Koha::Quote - Koha Quote object class
38 =head2 get_daily_quote($opts)
40 Takes a hashref of options
42 Currently supported options are:
44 'id' An exact quote id
45 'random' Select a random quote
46 noop When no option is passed in, this sub will return the quote timestamped for the current day
48 The function returns an anonymous hash following this format:
51 'source' => 'source-of-quote',
52 'timestamp' => 'timestamp-value',
53 'text' => 'text-of-quote',
59 # This is definitely a candidate for some sort of caching once we finally settle caching/persistence issues...
60 # at least for default option
63 my ($self, %opts) = @_;
64 my $dbh = C4::Context->dbh;
69 $query = 'SELECT * FROM quotes WHERE id = ?';
70 $sth = $dbh->prepare($query);
71 $sth->execute($opts{'id'});
72 $quote = $sth->fetchrow_hashref();
74 elsif ($opts{'random'}) {
75 # Fall through... we also return a random quote as a catch-all if all else fails
78 $query = 'SELECT * FROM quotes WHERE timestamp LIKE CONCAT(CURRENT_DATE,\'%\') ORDER BY timestamp DESC LIMIT 0,1';
79 $sth = $dbh->prepare($query);
81 $quote = $sth->fetchrow_hashref();
83 unless ($quote) { # if there are not matches, choose a random quote
84 # get a list of all available quote ids
85 $sth = C4::Context->dbh->prepare('SELECT count(*) FROM quotes;');
87 my $range = ($sth->fetchrow_array)[0];
88 # chose a random id within that range if there is more than one quote
89 my $offset = int(rand($range));
91 $query = 'SELECT * FROM quotes ORDER BY id LIMIT 1 OFFSET ?';
92 $sth = C4::Context->dbh->prepare($query);
93 # see http://www.perlmonks.org/?node_id=837422 for why
94 # we're being verbose and using bind_param
95 $sth->bind_param(1, $offset, SQL_INTEGER);
97 $quote = $sth->fetchrow_hashref();
98 # update the timestamp for that quote
99 $query = 'UPDATE quotes SET timestamp = ? WHERE id = ?';
100 $sth = C4::Context->dbh->prepare($query);
102 DateTime::Format::MySQL->format_datetime( dt_from_string() ),