summaryrefslogtreecommitdiff
path: root/platform/www/lib/plugins/authpdo/auth.php
blob: 9c0968e30dafc1bf6babaa8ebaa9d5107212fff4 (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
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
<?php
/**
 * DokuWiki Plugin authpdo (Auth Component)
 *
 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
 * @author  Andreas Gohr <andi@splitbrain.org>
 */

/**
 * Class auth_plugin_authpdo
 */
class auth_plugin_authpdo extends DokuWiki_Auth_Plugin
{

    /** @var PDO */
    protected $pdo;

    /** @var null|array The list of all groups */
    protected $groupcache = null;

    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct(); // for compatibility

        if (!class_exists('PDO')) {
            $this->debugMsg('PDO extension for PHP not found.', -1, __LINE__);
            $this->success = false;
            return;
        }

        if (!$this->getConf('dsn')) {
            $this->debugMsg('No DSN specified', -1, __LINE__);
            $this->success = false;
            return;
        }

        try {
            $this->pdo = new PDO(
                $this->getConf('dsn'),
                $this->getConf('user'),
                conf_decodeString($this->getConf('pass')),
                array(
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // always fetch as array
                    PDO::ATTR_EMULATE_PREPARES => true, // emulating prepares allows us to reuse param names
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // we want exceptions, not error codes
                )
            );
        } catch (PDOException $e) {
            $this->debugMsg($e);
            msg($this->getLang('connectfail'), -1);
            $this->success = false;
            return;
        }

        // can Users be created?
        $this->cando['addUser'] = $this->checkConfig(
            array(
                'select-user',
                'select-user-groups',
                'select-groups',
                'insert-user',
                'insert-group',
                'join-group'
            )
        );

        // can Users be deleted?
        $this->cando['delUser'] = $this->checkConfig(
            array(
                'select-user',
                'select-user-groups',
                'select-groups',
                'leave-group',
                'delete-user'
            )
        );

        // can login names be changed?
        $this->cando['modLogin'] = $this->checkConfig(
            array(
                'select-user',
                'select-user-groups',
                'update-user-login'
            )
        );

        // can passwords be changed?
        $this->cando['modPass'] = $this->checkConfig(
            array(
                'select-user',
                'select-user-groups',
                'update-user-pass'
            )
        );

        // can real names be changed?
        $this->cando['modName'] = $this->checkConfig(
            array(
                'select-user',
                'select-user-groups',
                'update-user-info:name'
            )
        );

        // can real email be changed?
        $this->cando['modMail'] = $this->checkConfig(
            array(
                'select-user',
                'select-user-groups',
                'update-user-info:mail'
            )
        );

        // can groups be changed?
        $this->cando['modGroups'] = $this->checkConfig(
            array(
                'select-user',
                'select-user-groups',
                'select-groups',
                'leave-group',
                'join-group',
                'insert-group'
            )
        );

        // can a filtered list of users be retrieved?
        $this->cando['getUsers'] = $this->checkConfig(
            array(
                'list-users'
            )
        );

        // can the number of users be retrieved?
        $this->cando['getUserCount'] = $this->checkConfig(
            array(
                'count-users'
            )
        );

        // can a list of available groups be retrieved?
        $this->cando['getGroups'] = $this->checkConfig(
            array(
                'select-groups'
            )
        );

        $this->success = true;
    }

    /**
     * Check user+password
     *
     * @param string $user the user name
     * @param string $pass the clear text password
     * @return  bool
     */
    public function checkPass($user, $pass)
    {

        $userdata = $this->selectUser($user);
        if ($userdata == false) return false;

        // password checking done in SQL?
        if ($this->checkConfig(array('check-pass'))) {
            $userdata['clear'] = $pass;
            $userdata['hash'] = auth_cryptPassword($pass);
            $result = $this->query($this->getConf('check-pass'), $userdata);
            if ($result === false) return false;
            return (count($result) == 1);
        }

        // we do password checking on our own
        if (isset($userdata['hash'])) {
            // hashed password
            $passhash = new \dokuwiki\PassHash();
            return $passhash->verify_hash($pass, $userdata['hash']);
        } else {
            // clear text password in the database O_o
            return ($pass === $userdata['clear']);
        }
    }

    /**
     * Return user info
     *
     * Returns info about the given user needs to contain
     * at least these fields:
     *
     * name string  full name of the user
     * mail string  email addres of the user
     * grps array   list of groups the user is in
     *
     * @param string $user the user name
     * @param bool $requireGroups whether or not the returned data must include groups
     * @return array|bool containing user data or false
     */
    public function getUserData($user, $requireGroups = true)
    {
        $data = $this->selectUser($user);
        if ($data == false) return false;

        if (isset($data['hash'])) unset($data['hash']);
        if (isset($data['clean'])) unset($data['clean']);

        if ($requireGroups) {
            $data['grps'] = $this->selectUserGroups($data);
            if ($data['grps'] === false) return false;
        }

        return $data;
    }

    /**
     * Create a new User [implement only where required/possible]
     *
     * Returns false if the user already exists, null when an error
     * occurred and true if everything went well.
     *
     * The new user HAS TO be added to the default group by this
     * function!
     *
     * Set addUser capability when implemented
     *
     * @param string $user
     * @param string $clear
     * @param string $name
     * @param string $mail
     * @param null|array $grps
     * @return bool|null
     */
    public function createUser($user, $clear, $name, $mail, $grps = null)
    {
        global $conf;

        if (($info = $this->getUserData($user, false)) !== false) {
            msg($this->getLang('userexists'), -1);
            return false; // user already exists
        }

        // prepare data
        if ($grps == null) $grps = array();
        array_unshift($grps, $conf['defaultgroup']);
        $grps = array_unique($grps);
        $hash = auth_cryptPassword($clear);
        $userdata = compact('user', 'clear', 'hash', 'name', 'mail');

        // action protected by transaction
        $this->pdo->beginTransaction();
        {
            // insert the user
            $ok = $this->query($this->getConf('insert-user'), $userdata);
            if ($ok === false) goto FAIL;
            $userdata = $this->getUserData($user, false);
            if ($userdata === false) goto FAIL;

            // create all groups that do not exist, the refetch the groups
            $allgroups = $this->selectGroups();
            foreach ($grps as $group) {
                if (!isset($allgroups[$group])) {
                    $ok = $this->addGroup($group);
                    if ($ok === false) goto FAIL;
                }
            }
            $allgroups = $this->selectGroups();

            // add user to the groups
            foreach ($grps as $group) {
                $ok = $this->joinGroup($userdata, $allgroups[$group]);
                if ($ok === false) goto FAIL;
            }
        }
        $this->pdo->commit();
        return true;

        // something went wrong, rollback
        FAIL:
        $this->pdo->rollBack();
        $this->debugMsg('Transaction rolled back', 0, __LINE__);
        msg($this->getLang('writefail'), -1);
        return null; // return error
    }

    /**
     * Modify user data
     *
     * @param string $user nick of the user to be changed
     * @param array $changes array of field/value pairs to be changed (password will be clear text)
     * @return  bool
     */
    public function modifyUser($user, $changes)
    {
        // secure everything in transaction
        $this->pdo->beginTransaction();
        {
            $olddata = $this->getUserData($user);
            $oldgroups = $olddata['grps'];
            unset($olddata['grps']);

            // changing the user name?
            if (isset($changes['user'])) {
                if ($this->getUserData($changes['user'], false)) goto FAIL;
                $params = $olddata;
                $params['newlogin'] = $changes['user'];

                $ok = $this->query($this->getConf('update-user-login'), $params);
                if ($ok === false) goto FAIL;
            }

            // changing the password?
            if (isset($changes['pass'])) {
                $params = $olddata;
                $params['clear'] = $changes['pass'];
                $params['hash'] = auth_cryptPassword($changes['pass']);

                $ok = $this->query($this->getConf('update-user-pass'), $params);
                if ($ok === false) goto FAIL;
            }

            // changing info?
            if (isset($changes['mail']) || isset($changes['name'])) {
                $params = $olddata;
                if (isset($changes['mail'])) $params['mail'] = $changes['mail'];
                if (isset($changes['name'])) $params['name'] = $changes['name'];

                $ok = $this->query($this->getConf('update-user-info'), $params);
                if ($ok === false) goto FAIL;
            }

            // changing groups?
            if (isset($changes['grps'])) {
                $allgroups = $this->selectGroups();

                // remove membership for previous groups
                foreach ($oldgroups as $group) {
                    if (!in_array($group, $changes['grps']) && isset($allgroups[$group])) {
                        $ok = $this->leaveGroup($olddata, $allgroups[$group]);
                        if ($ok === false) goto FAIL;
                    }
                }

                // create all new groups that are missing
                $added = 0;
                foreach ($changes['grps'] as $group) {
                    if (!isset($allgroups[$group])) {
                        $ok = $this->addGroup($group);
                        if ($ok === false) goto FAIL;
                        $added++;
                    }
                }
                // reload group info
                if ($added > 0) $allgroups = $this->selectGroups();

                // add membership for new groups
                foreach ($changes['grps'] as $group) {
                    if (!in_array($group, $oldgroups)) {
                        $ok = $this->joinGroup($olddata, $allgroups[$group]);
                        if ($ok === false) goto FAIL;
                    }
                }
            }

        }
        $this->pdo->commit();
        return true;

        // something went wrong, rollback
        FAIL:
        $this->pdo->rollBack();
        $this->debugMsg('Transaction rolled back', 0, __LINE__);
        msg($this->getLang('writefail'), -1);
        return false; // return error
    }

    /**
     * Delete one or more users
     *
     * Set delUser capability when implemented
     *
     * @param array $users
     * @return  int    number of users deleted
     */
    public function deleteUsers($users)
    {
        $count = 0;
        foreach ($users as $user) {
            if ($this->deleteUser($user)) $count++;
        }
        return $count;
    }

    /**
     * Bulk retrieval of user data [implement only where required/possible]
     *
     * Set getUsers capability when implemented
     *
     * @param int $start index of first user to be returned
     * @param int $limit max number of users to be returned
     * @param array $filter array of field/pattern pairs, null for no filter
     * @return  array list of userinfo (refer getUserData for internal userinfo details)
     */
    public function retrieveUsers($start = 0, $limit = -1, $filter = null)
    {
        if ($limit < 0) $limit = 10000; // we don't support no limit
        if (is_null($filter)) $filter = array();

        if (isset($filter['grps'])) $filter['group'] = $filter['grps'];
        foreach (array('user', 'name', 'mail', 'group') as $key) {
            if (!isset($filter[$key])) {
                $filter[$key] = '%';
            } else {
                $filter[$key] = '%' . $filter[$key] . '%';
            }
        }
        $filter['start'] = (int)$start;
        $filter['end'] = (int)$start + $limit;
        $filter['limit'] = (int)$limit;

        $result = $this->query($this->getConf('list-users'), $filter);
        if (!$result) return array();
        $users = array();
        if (is_array($result)) {
            foreach ($result as $row) {
                if (!isset($row['user'])) {
                    $this->debugMsg("list-users statement did not return 'user' attribute", -1, __LINE__);
                    return array();
                }
                $users[] = $this->getUserData($row['user']);
            }
        } else {
            $this->debugMsg("list-users statement did not return a list of result", -1, __LINE__);
        }
        return $users;
    }

    /**
     * Return a count of the number of user which meet $filter criteria
     *
     * @param array $filter array of field/pattern pairs, empty array for no filter
     * @return int
     */
    public function getUserCount($filter = array())
    {
        if (is_null($filter)) $filter = array();

        if (isset($filter['grps'])) $filter['group'] = $filter['grps'];
        foreach (array('user', 'name', 'mail', 'group') as $key) {
            if (!isset($filter[$key])) {
                $filter[$key] = '%';
            } else {
                $filter[$key] = '%' . $filter[$key] . '%';
            }
        }

        $result = $this->query($this->getConf('count-users'), $filter);
        if (!$result || !isset($result[0]['count'])) {
            $this->debugMsg("Statement did not return 'count' attribute", -1, __LINE__);
        }
        return (int)$result[0]['count'];
    }

    /**
     * Create a new group with the given name
     *
     * @param string $group
     * @return bool
     */
    public function addGroup($group)
    {
        $sql = $this->getConf('insert-group');

        $result = $this->query($sql, array(':group' => $group));
        $this->clearGroupCache();
        if ($result === false) return false;
        return true;
    }

    /**
     * Retrieve groups
     *
     * Set getGroups capability when implemented
     *
     * @param int $start
     * @param int $limit
     * @return  array
     */
    public function retrieveGroups($start = 0, $limit = 0)
    {
        $groups = array_keys($this->selectGroups());
        if ($groups === false) return array();

        if (!$limit) {
            return array_splice($groups, $start);
        } else {
            return array_splice($groups, $start, $limit);
        }
    }

    /**
     * Select data of a specified user
     *
     * @param string $user the user name
     * @return bool|array user data, false on error
     */
    protected function selectUser($user)
    {
        $sql = $this->getConf('select-user');

        $result = $this->query($sql, array(':user' => $user));
        if (!$result) return false;

        if (count($result) > 1) {
            $this->debugMsg('Found more than one matching user', -1, __LINE__);
            return false;
        }

        $data = array_shift($result);
        $dataok = true;

        if (!isset($data['user'])) {
            $this->debugMsg("Statement did not return 'user' attribute", -1, __LINE__);
            $dataok = false;
        }
        if (!isset($data['hash']) && !isset($data['clear']) && !$this->checkConfig(array('check-pass'))) {
            $this->debugMsg("Statement did not return 'clear' or 'hash' attribute", -1, __LINE__);
            $dataok = false;
        }
        if (!isset($data['name'])) {
            $this->debugMsg("Statement did not return 'name' attribute", -1, __LINE__);
            $dataok = false;
        }
        if (!isset($data['mail'])) {
            $this->debugMsg("Statement did not return 'mail' attribute", -1, __LINE__);
            $dataok = false;
        }

        if (!$dataok) return false;
        return $data;
    }

    /**
     * Delete a user after removing all their group memberships
     *
     * @param string $user
     * @return bool true when the user was deleted
     */
    protected function deleteUser($user)
    {
        $this->pdo->beginTransaction();
        {
            $userdata = $this->getUserData($user);
            if ($userdata === false) goto FAIL;
            $allgroups = $this->selectGroups();

            // remove group memberships (ignore errors)
            foreach ($userdata['grps'] as $group) {
                if (isset($allgroups[$group])) {
                    $this->leaveGroup($userdata, $allgroups[$group]);
                }
            }

            $ok = $this->query($this->getConf('delete-user'), $userdata);
            if ($ok === false) goto FAIL;
        }
        $this->pdo->commit();
        return true;

        FAIL:
        $this->pdo->rollBack();
        return false;
    }

    /**
     * Select all groups of a user
     *
     * @param array $userdata The userdata as returned by _selectUser()
     * @return array|bool list of group names, false on error
     */
    protected function selectUserGroups($userdata)
    {
        global $conf;
        $sql = $this->getConf('select-user-groups');
        $result = $this->query($sql, $userdata);
        if ($result === false) return false;

        $groups = array($conf['defaultgroup']); // always add default config
        if (is_array($result)) {
            foreach ($result as $row) {
                if (!isset($row['group'])) {
                    $this->debugMsg("No 'group' field returned in select-user-groups statement", -1, __LINE__);
                    return false;
                }
                $groups[] = $row['group'];
            }
        } else {
            $this->debugMsg("select-user-groups statement did not return a list of result", -1, __LINE__);
        }

        $groups = array_unique($groups);
        sort($groups);
        return $groups;
    }

    /**
     * Select all available groups
     *
     * @return array|bool list of all available groups and their properties
     */
    protected function selectGroups()
    {
        if ($this->groupcache) return $this->groupcache;

        $sql = $this->getConf('select-groups');
        $result = $this->query($sql);
        if ($result === false) return false;

        $groups = array();
        if (is_array($result)) {
            foreach ($result as $row) {
                if (!isset($row['group'])) {
                    $this->debugMsg("No 'group' field returned from select-groups statement", -1, __LINE__);
                    return false;
                }

                // relayout result with group name as key
                $group = $row['group'];
                $groups[$group] = $row;
            }
        } else {
            $this->debugMsg("select-groups statement did not return a list of result", -1, __LINE__);
        }

        ksort($groups);
        return $groups;
    }

    /**
     * Remove all entries from the group cache
     */
    protected function clearGroupCache()
    {
        $this->groupcache = null;
    }

    /**
     * Adds the user to the group
     *
     * @param array $userdata all the user data
     * @param array $groupdata all the group data
     * @return bool
     */
    protected function joinGroup($userdata, $groupdata)
    {
        $data = array_merge($userdata, $groupdata);
        $sql = $this->getConf('join-group');
        $result = $this->query($sql, $data);
        if ($result === false) return false;
        return true;
    }

    /**
     * Removes the user from the group
     *
     * @param array $userdata all the user data
     * @param array $groupdata all the group data
     * @return bool
     */
    protected function leaveGroup($userdata, $groupdata)
    {
        $data = array_merge($userdata, $groupdata);
        $sql = $this->getConf('leave-group');
        $result = $this->query($sql, $data);
        if ($result === false) return false;
        return true;
    }

    /**
     * Executes a query
     *
     * @param string $sql The SQL statement to execute
     * @param array $arguments Named parameters to be used in the statement
     * @return array|int|bool The result as associative array for SELECTs, affected rows for others, false on error
     */
    protected function query($sql, $arguments = array())
    {
        $sql = trim($sql);
        if (empty($sql)) {
            $this->debugMsg('No SQL query given', -1, __LINE__);
            return false;
        }

        // execute
        $params = array();
        $sth = $this->pdo->prepare($sql);
        $result = false;
        try {
            // prepare parameters - we only use those that exist in the SQL
            foreach ($arguments as $key => $value) {
                if (is_array($value)) continue;
                if (is_object($value)) continue;
                if ($key[0] != ':') $key = ":$key"; // prefix with colon if needed
                if (strpos($sql, $key) === false) continue; // skip if parameter is missing

                if (is_int($value)) {
                    $sth->bindValue($key, $value, PDO::PARAM_INT);
                } else {
                    $sth->bindValue($key, $value);
                }
                $params[$key] = $value; //remember for debugging
            }

            $sth->execute();
            // only report last line's result
            $hasnextrowset = true;
            $currentsql = $sql;
            while ($hasnextrowset) {
                if (strtolower(substr($currentsql, 0, 6)) == 'select') {
                    $result = $sth->fetchAll();
                } else {
                    $result = $sth->rowCount();
                }
                $semi_pos = strpos($currentsql, ';');
                if ($semi_pos) {
                    $currentsql = trim(substr($currentsql, $semi_pos + 1));
                }
                try {
                    $hasnextrowset = $sth->nextRowset(); // run next rowset
                } catch (PDOException $rowset_e) {
                    $hasnextrowset = false; // driver does not support multi-rowset, should be executed in one time
                }
            }
        } catch (Exception $e) {
            // report the caller's line
            $trace = debug_backtrace();
            $line = $trace[0]['line'];
            $dsql = $this->debugSQL($sql, $params, !defined('DOKU_UNITTEST'));
            $this->debugMsg($e, -1, $line);
            $this->debugMsg("SQL: <pre>$dsql</pre>", -1, $line);
        }
        $sth->closeCursor();
        $sth = null;

        return $result;
    }

    /**
     * Wrapper around msg() but outputs only when debug is enabled
     *
     * @param string|Exception $message
     * @param int $err
     * @param int $line
     */
    protected function debugMsg($message, $err = 0, $line = 0)
    {
        if (!$this->getConf('debug')) return;
        if (is_a($message, 'Exception')) {
            $err = -1;
            $msg = $message->getMessage();
            if (!$line) $line = $message->getLine();
        } else {
            $msg = $message;
        }

        if (defined('DOKU_UNITTEST')) {
            printf("\n%s, %s:%d\n", $msg, __FILE__, $line);
        } else {
            msg('authpdo: ' . $msg, $err, $line, __FILE__);
        }
    }

    /**
     * Check if the given config strings are set
     *
     * @param string[] $keys
     * @return  bool
     * @author  Matthias Grimm <matthiasgrimm@users.sourceforge.net>
     *
     */
    protected function checkConfig($keys)
    {
        foreach ($keys as $key) {
            $params = explode(':', $key);
            $key = array_shift($params);
            $sql = trim($this->getConf($key));

            // check if sql is set
            if (!$sql) return false;
            // check if needed params are there
            foreach ($params as $param) {
                if (strpos($sql, ":$param") === false) return false;
            }
        }

        return true;
    }

    /**
     * create an approximation of the SQL string with parameters replaced
     *
     * @param string $sql
     * @param array $params
     * @param bool $htmlescape Should the result be escaped for output in HTML?
     * @return string
     */
    protected function debugSQL($sql, $params, $htmlescape = true)
    {
        foreach ($params as $key => $val) {
            if (is_int($val)) {
                $val = $this->pdo->quote($val, PDO::PARAM_INT);
            } elseif (is_bool($val)) {
                $val = $this->pdo->quote($val, PDO::PARAM_BOOL);
            } elseif (is_null($val)) {
                $val = 'NULL';
            } else {
                $val = $this->pdo->quote($val);
            }
            $sql = str_replace($key, $val, $sql);
        }
        if ($htmlescape) $sql = hsc($sql);
        return $sql;
    }
}

// vim:ts=4:sw=4:et: