-
Notifications
You must be signed in to change notification settings - Fork 0
/
Core.pm
402 lines (316 loc) · 10.8 KB
/
Core.pm
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# Plugin for Foswiki - The Free and Open Source Wiki, http://foswiki.org/
#
# Copyright (C) 2009-2016 Michael Daum http://michaeldaumconsulting.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details, published at
# http://www.gnu.org/copyleft/gpl.html
package Foswiki::Plugins::SqlPlugin::Core;
use strict;
use warnings;
use Foswiki::Plugins::SqlPlugin::Connection ();
use Error qw( :try );
use Foswiki::Sandbox ();
use Text::ParseWords ();
use constant TRACE => 0; # toggle me
##############################################################################
sub new {
my $class = shift;
my $this = {
connections => undef,
accessControls => $Foswiki::cfg{SqlPlugin}{AccessControl},
cache => undef,
defaultDatabase => undef,
@_
};
bless($this, $class);
foreach my $desc (@{$Foswiki::cfg{SqlPlugin}{Databases}}) {
my $connection = new Foswiki::Plugins::SqlPlugin::Connection(%$desc);
$this->connection($desc->{id}, $connection);
$this->{defaultDatabase} = $desc->{id} unless defined $this->{defaultDatabase};
}
return $this;
}
##############################################################################
sub connection {
my ($this, $id, $connection) = @_;
if (defined $connection) {
$this->{connections}{$id} = $connection;
} else {
$connection = $this->{connections}{$id};
throw Error::Simple("unknown database '$id'") unless defined $connection;
}
return $connection;
}
##############################################################################
sub finish {
my $this = shift;
foreach my $id (keys %{$this->{connections}}) {
$this->connection($id)->disconnect;
}
undef $this->{connections};
undef $this->{cache};
}
##############################################################################
sub execute {
my ($this, $theDatabase, $theQuery, @thePlaceHolders) = @_;
$theDatabase = $this->{defaultDatabase} unless defined $theDatabase;
throw Error::Simple("No Query provided") unless defined $theQuery;
$this->checkAccess($theDatabase, $theQuery);
my $connection = $this->connection($theDatabase);
$connection->connect();
my $sth = $connection->{db}->prepare_cached($theQuery)
or throw Error::Simple("Can't prepare cmd '$theQuery': " . $connection->{db}->errstr);
$sth->execute(@thePlaceHolders)
or throw Error::Simple("Can't execute cmd '$theQuery': " . $connection->{db}->errstr);
return $sth;
}
##############################################################################
sub handleSQL {
my ($this, $session, $params, $theTopic, $theWeb) = @_;
my $theDatabase = $params->{database} || $this->{defaultDatabase};
my $theId = $params->{id};
my $theQuery = $params->{_DEFAULT} || $params->{query};
my $theParams = $params->{params} || '';
my $theDecode = $params->{decode} || '';
return inlineError("no query") unless defined $theQuery;
if ($theDecode eq 'url') {
$theQuery = urlDecode($theQuery);
} elsif ($theDecode eq 'entity') {
$theQuery = entityDecode($theQuery);
}
#writeDebug("called handleSQL() - " . $theQuery);
my @bindVals = Text::ParseWords::parse_line('\s*,\s*', 0, $theParams);
my $result = '';
try {
my $connection = $this->connection($theDatabase);
$this->checkAccess($theDatabase, $theQuery);
$connection->connect();
my $sth = $connection->{db}->prepare_cached($theQuery) or
throw Error::Simple("Can't prepare cmd '$theQuery': ".$connection->{db}->errstr);
$sth->execute(@bindVals) or
throw Error::Simple("Can't execute cmd '$theQuery': ".$connection->{db}->errstr);
# cache this statement under the given id
$this->{cache}{$theId} = {
sth => $sth,
connection => $connection,
bindVals => \@bindVals,
} if $theId;
if($sth->{NUM_OF_FIELDS}) {
# select statement
$result = $this->formatResult($params, $sth);
} else {
# non-select statement
$result = $sth->rows();
}
} catch Error::Simple with {
my $msg = shift->{-text};
$msg =~ s/ at .*?$//gs;
#$msg .= "<br />for query $theQuery";
$result = inlineError($msg);
};
#writeDebug("result=$result");
return $result;
}
##############################################################################
sub handleSQLFORMAT {
my ($this, $session, $params, $theTopic, $theWeb) = @_;
my $theId = $params->{_DEFAULT} || $params->{id};
my $theContinue = $params->{'continue'} || 'off';
$theContinue = ($theContinue eq 'on') ? 1 : 0;
my $entry = $this->{cache}{$theId};
return inlineError("unknown statement '$theId'") unless defined $entry;
my $sth = $entry->{sth};
my $connection = $entry->{connection};
my $bindVals = $entry->{bindVals};
my $result = '';
try {
unless ($theContinue) {
($bindVals ? $sth->execute(@{$bindVals}) : $sth->execute)
or throw Error::Simple("Can't execute again: " . $connection->{db}->errstr);
}
$result = $this->formatResult($params, $sth);
}
catch Error::Simple with {
my $msg = shift->{-text};
$msg =~ s/ at .*?$//gs;
$result = inlineError($msg);
};
return $result;
}
##############################################################################
sub handleSQLINFO {
my ($this, $session, $params, $theTopic, $theWeb) = @_;
my $theDatabase = $params->{_DEFAULT} || $params->{database};
my $theFormat = $params->{format} || '$id';
my $theSeparator = $params->{separator};
my $theHeader = $params->{header} || '';
my $theFooter = $params->{footer} || '';
$theSeparator = ', ' unless defined $theSeparator;
my @selectedIds = ();
if ($theDatabase) {
push @selectedIds, split(/\s*,\s*/, $theDatabase);
} else {
push @selectedIds, keys %{$this->{connections}};
}
my @result = ();
foreach my $id (sort @selectedIds) {
my $connection = $this->connection($id);
next unless $connection;# ignore
my $line = $theFormat;
$line =~ s/\$id/$id/g;
$line =~ s/\$dsn/$connection->{dsn}/g;
$line =~ s/\$nop//go;
$line =~ s/\$n/\n/go;
$line =~ s/\$perce?nt/\%/go;
$line =~ s/\$dollar/\$/go;
push @result, $line;
}
return '' unless @result;
return $theHeader.join($theSeparator, @result).$theFooter;
}
##############################################################################
sub formatResult {
my ($this, $params, $sth) = @_;
my $theFormat = $params->{format};
my $theHeader = $params->{header};
my $theFooter = $params->{footer};
my $theSeparator = $params->{separator};
my $theHidenull = $params->{hidenull} || 'off';
$theHidenull = ($theHidenull eq 'on')?1:0;
my $theLimit = $params->{limit} || 0;
my $theSkip = $params->{skip} || 0;
if (!defined($theFormat) && !defined($theHeader) && !defined($theFooter)) {
$theHeader = '<table class="foswikiTable"><tr>';
foreach my $key (@{$sth->{NAME}}) {
$theHeader .= "<th> $key </th>";
}
$theHeader .= '</tr>';
$theFormat = '<tr>';
foreach my $key (@{$sth->{NAME}}) {
$key ||= '';
$theFormat .= "<td> \$$key </td>";
}
$theFormat .= '</tr>';
$theFooter = '</table>'
}
my @lines = ();
if ($theFormat) {
my $index = 0;
while (my $res = $sth->fetchrow_hashref() ) {
$index++;
next if $theSkip && $index <= $theSkip;
my $line = $theFormat;
foreach my $key (keys %$res) {
my $val = $res->{$key} || '';
$line =~ s/\$index/$index/g;
$line =~ s/\$\Q$key/$val/g;
}
push @lines, $line;
last if $theLimit && $index >= $theLimit;
}
}
my $result = '';
if (!$theHidenull || @lines) {
$theHeader ||= '';
$theFooter ||= '';
$theSeparator ||= '';
$result = $theHeader.join($theSeparator, @lines).$theFooter;
$result =~ s/\$nop//go;
$result =~ s/\$n/\n/go;
$result =~ s/\$perce?nt/\%/go;
$result =~ s/\$dollar/\$/go;
}
return $result;
}
##############################################################################
# Check if the currently logged in user has permission to run
# $theQuery on $theDatabase. Throws Error::Simple on access failure.
##############################################################################
sub checkAccess {
my ($this, $theDatabase, $theQuery) = @_;
my $isAllowed = 1;
if ($this->{accessControls}) {
my $user = Foswiki::Func::getWikiName();
foreach my $access (@{$this->{accessControls}}) {
next unless $access->{id} eq $theDatabase;
$isAllowed = 0;
my $whoPasses = 0;
my $who = $access->{who};
if (!defined($who)) {
$whoPasses = 1;
} else {
if ($who eq $user) {
$whoPasses = 1;
} elsif (Foswiki::Func::isGroup($who) && Foswiki::Func::isGroupMember($who, $user)) {
$whoPasses = 1;
}
}
my $queryPasses = 0;
if (!defined($access->{queries})) {
$queryPasses = 1;
} else {
my $searchQuery = uc $theQuery;
# convert multiple lines into one
$searchQuery = join ' ', ($searchQuery =~ /^(.*)$/gm);
$searchQuery =~ s/\s+/ /g;
for my $query (@{$access->{queries}}) {
if ($searchQuery eq $query) {
$queryPasses = 1;
last;
}
# Trap regexp compilation errors - we don't care.
eval {
if ($searchQuery =~ /^\s*$query\s*$/) {
$queryPasses = 1;
last;
}
};
}
}
if ($whoPasses && $queryPasses) {
$isAllowed = 1;
last;
}
}
}
my $message = $theQuery;
$message =~ s/\n/ /g; # remove newlines
$message .= " [ACCESS DENIED]" unless $isAllowed;
Foswiki::Func::writeEvent("sql", $message) if $Foswiki::cfg{Log}{Action}{sql};
unless ($isAllowed) {
$message = "Access control check failed on database '$theDatabase' for query '$theQuery'";
Foswiki::Func::writeWarning("SqlPlugin", $message);
throw Error::Simple($message);
}
return $isAllowed;
}
################################################################################
# static helpers
sub urlDecode {
my $text = shift;
$text =~ s/%([\da-f]{2})/chr(hex($1))/gei;
return $text;
}
sub entityDecode {
my $text = shift;
$text =~ s/&#(\d+);/chr($1)/ge;
return $text;
}
sub writeDebug {
print STDERR "- SqlPlugin::Core - $_[0]\n" if TRACE;
# Foswiki::Func::writeDebug("SqlPlugin::Core", $_[0]);
}
sub inlineError {
my $msg = shift;
$msg =~ s/\%/%/g;
return "<noautolink><span class='foswikiAlert'>ERROR: $msg </span></noautolink>";
}
1;