File: amavisd_sql.php

package info (click to toggle)
horde-sam 0.1-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,292 kB
  • ctags: 363
  • sloc: php: 1,449; xml: 646; makefile: 64; sql: 60; sh: 30
file content (783 lines) | stat: -rw-r--r-- 31,841 bytes parent folder | download
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
<?php
/**
 * SAM storage implementation for PHP's PEAR database abstraction layer.
 *
 * Required parameters:<pre>
 *   'phptype'       The database type (ie. 'pgsql', 'mysql', etc.).</pre>
 *
  * Optional preferences:<pre>
 *   'table'         The name of the SAM options table in 'database'.
 *                   DEFAULT: 'userpref'</pre>
 *
 * Required by some database implementations:<pre>
 *   'hostspec'      The hostname of the database server.
 *   'protocol'      The communication protocol ('tcp', 'unix', etc.).
 *   'database'      The name of the database.
 *   'username'      The username with which to connect to the database.
 *   'password'      The password associated with 'username'.
 *   'options '      Additional options to pass to the database.
 *   'port'          The port on which to connect to the database.
 *   'tty'           The TTY on which to connect to the database.</pre>
 *
 * The table structure can be created by the scripts/sql/amavisd_*.sql
 * script appropriate for your database, or modified from one that is
 * available.
 *
 * $Horde: sam/lib/Driver/amavisd_sql.php,v 1.20 2006/01/18 17:49:02 ben Exp $
 *
 * @author  Max Kalika <max@horde.org>
 * @since   SAM 0.0.1
 * @package Sam
 */

/**
 * Backend-specific 'false' value.
 */
define('_SAM_OPTION_OFF', 'N');

/**
 * Backend-specific 'true' value.
 */
define('_SAM_OPTION_ON',  'Y');

class SAM_Driver_amavisd_sql extends SAM_Driver {

    /**
     * Handle for the current database connection.
     *
     * @var DB
     */
    var $_db;

    /**
     * Boolean indicating whether or not we're connected to the SQL server.
     *
     * @var boolean
     */
    var $_connected = false;

    /**
     * List of the capabilities supported by this driver.
     *
     * @var array
     */
    var $_capabilities = array('tag_level',
                               'hit_level',
                               'kill_level',
                               'rewrite_sub',
                               'spam_extension',
                               'virus_extension',
                               'banned_extension',
                               'spam_quarantine',
                               'allow_virus',
                               'allow_spam',
                               'allow_banned',
                               'allow_header',
                               'skip_virus',
                               'skip_spam',
                               'skip_banned',
                               'skip_header',
                               'whitelist_from',
                               'blacklist_from');

    /**
     * Constructs a new SQL storage object.
     *
     * @param string $user   The user who owns these SPAM options.
     * @param array $params  A hash containing connection parameters.
     */
    function SAM_Driver_amavisd_sql($user, $params = array())
    {
        global $conf;

        $this->_user = $user;
        $this->_params = array_merge($conf['sql'], $params);
    }

    /**
     * Converts a SAM table name to a table name that Amavisd-new will use.
     *
     * @access private
     *
     * @param string $table  The SAM table to lookup.
     *
     * @return string  The converted Amavisd-new table or the original name if
     *                 no match is found.
     */
    function _mapNameToTable($table)
    {
        return isset($this->_params['table_map'][$table]['name'])
               ? $this->_params['table_map'][$table]['name'] : $table;
    }

    /**
     * Converts a SAM attribute from a specific table to a field that
     * Amavisd-new will use.
     *
     * @access private
     *
     * @param string $table      The SAM table to lookup.
     * @param string $attribute  The SAM attribute to convert.
     *
     * @return string  The converted Amavisd-new field or the original
     *                 attribute if no match is found.
     */
    function _mapAttributeToField($table, $attribute)
    {
        return isset($this->_params['table_map'][$table]['field_map'][$attribute])
               ? $this->_params['table_map'][$table]['field_map'][$attribute] : $attribute;
    }

    /**
     * Converts a Amavisd-new field from a specific table to a SAM attribute.
     *
     * @access private
     *
     * @param string $table  The SAM table to lookup.
     * @param string $field  The Amavisd-new field to convert.
     *
     * @return string  The converted SAM attribute or the original field if no
     *                 match is found.
     */
    function _mapFieldToAttribute($table, $field)
    {
        $attribute_map = array();
        if (isset($this->_params['table_map'][$table]['field_map'])) {
            $attribute_map = array_flip($this->_params['table_map'][$table]['field_map']);
        }

        return isset($attribute_map[$field]) ? $attribute_map[$field] : $field;
    }

    /*
     * Create an Amavisd-new recipient for policy, whitelist and blacklist
     * storage and retrieval.
     *
     * @access private
     *
     * @return mixed  The id of the newly created recipient or a PEAR_Error
     *                object on failure.
     */
    function _createUserID()
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the recipient creation query. */
        $query = sprintf('INSERT INTO %s (%s) VALUES (?)',
                         $this->_mapNameToTable('recipients'),
                         $this->_mapAttributeToField('recipients', 'email'));
        $values = array($this->_user);

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_createUserID(): %s', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        $result = $this->_db->query($query, $values);
        if (is_a($result, 'PEAR_Error')) {
            return PEAR::raiseError(sprintf(_("Cannot create recipient %s: %s"),
                                            $this->_user, $result->getMessage()));
        } else {
            $GLOBALS['notification']->push(sprintf(_("Recipient created: %s"),
                                                   $this->_user), 'horde.success');
            return $this->_lookupUserID();
        }
    }

    /*
     * Lookup an Amavisd-new recipient for policy, whitelist and blacklist
     * storage and retrieval.
     *
     * This function will cache the found ID for quicker lookup on subsequent
     * calls.
     *
     * @access private
     *
     * @return mixed  The ID of the found or newly created recipient or a
     *                PEAR_Error object on failure.
     */
    function _lookupUserID()
    {
        static $_userID;

        if (!empty($_userID)) {
            return $_userID;
        }

        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the recipient lookup query. */
        $query = sprintf('SELECT %s FROM %s WHERE %s = ?',
                         $this->_mapAttributeToField('recipients', 'id'),
                         $this->_mapNameToTable('recipients'),
                         $this->_mapAttributeToField('recipients', 'email'));
        $values = array($this->_user);

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_lookupUserID(): %s', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $result = $this->_db->getOne($query, $values);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
            return $result;
        } elseif (is_null($result)) {
            $_userID = $this->_createUserID();
        } else {
            $_userID = $result;
        }

        return $_userID;
    }

    /*
     * Lookup an Amavisd-new policy for storage and retrieval.
     *
     * @access private
     *
     * @return mixed  The results of the of the policy lookup. Can be the ID of
     *                the policy, null if not found, or a PEAR_Error object on
     *                failure.
     */
    function _lookupPolicyID()
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the policy lookup query. */
        $query = sprintf('SELECT %s FROM %s WHERE %s = ?',
                         $this->_mapAttributeToField('policies', 'id'),
                         $this->_mapNameToTable('policies'),
                         $this->_mapAttributeToField('policies', 'name'));
        $values = array($this->_user);

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_lookupPolicyID(): %s', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $result = $this->_db->getOne($query, $values);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
        }

        return $result;
    }

    /**
     * Retrieve an option set from the storage backend.
     *
     * @access private
     *
     * @return mixed  Array of field-value pairs or a PEAR_Error object on
     *                failure.
     */
    function _retrieve()
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Find the user id. */
        $userID = $this->_lookupUserID();
        if (is_a($userID, 'PEAR_Error')) {
            return $userID;
        }

        /* Find the policy id. */
        $policyID = $this->_lookupPolicyID();
        if (is_a($policyID, 'PEAR_Error')) {
            return $policyID;
        }

        $return = array();

        /* Build the SQL query for SPAM policy. */
        $query = sprintf('SELECT * FROM %s WHERE %s = ?',
                         $this->_mapNameToTable('policies'),
                         $this->_mapAttributeToField('policies', 'id'));
        $values = array($policyID);

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_retrieve(): %s', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $result = $this->_db->getRow($query, $values, DB_FETCHMODE_ASSOC);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
            return $result;
        }

        /* Loop through elements of the result, retrieving options. */
        if (!is_null($result)) {
            foreach ($result as $field => $value) {
                $attribute = $this->_mapFieldToAttribute('policies', $field);
                if ($this->hasCapability($attribute) && !is_null($value)) {
                    $return[$attribute] = $value;
                }
            }
        }

        /* Build the SQL query for whitelists and blacklists. */
        $query = sprintf('SELECT %s, %s FROM %s WHERE %s = ?',
                         $this->_mapAttributeToField('wblists', 'sender'),
                         $this->_mapAttributeToField('wblists', 'type'),
                         $this->_mapNameToTable('wblists'),
                         $this->_mapAttributeToField('wblists', 'recipient'));
        $values = array($userID);

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_retrieve(): %s', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        $result = $this->_db->query($query, $values);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
            return $result;
        }

        /* Loop through results, retrieving whitelists and blacklists. */
        while (($row = $result->fetchRow(DB_FETCHMODE_ASSOC)) &&
               !is_a($row, 'PEAR_Error')) {
            $type = $row[$this->_mapAttributeToField('wblists', 'type')];
            $senderID = $row[$this->_mapAttributeToField('wblists', 'sender')];

            /* Only proceed if sender is listed white or black. */
            if (preg_match('/[WYBN]/i', $type)) {
                $query = sprintf('SELECT %s FROM %s WHERE %s = ?',
                                 $this->_mapAttributeToField('senders', 'email'),
                                 $this->_mapNameToTable('senders'),
                                 $this->_mapAttributeToField('senders', 'id'));
                $values = array($senderID);

                /* Log the query at a DEBUG log level. */
                Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_retrieve(): %s', $query),
                                  __FILE__, __LINE__, PEAR_LOG_DEBUG);

                $sender = $this->_db->getOne($query, $values);
                if (is_a($sender, 'PEAR_Error')) {
                    Horde::logMessage($sender, __FILE__, __LINE__, PEAR_LOG_ERR);
                    return $sender;
                } else {
                    $list = preg_match('/[WY]/i', $type) ? 'whitelist_from' : 'blacklist_from';
                    if (isset($return[$list])) {
                        if (!in_array($sender, $return[$list])) {
                            $return[$list][] = $sender;
                        }
                    } else {
                        $return[$list] = array($sender);
                    }
                }
            }
        }
        $result->free();

        if (is_a($row, 'PEAR_Error')) {
            Horde::logMessage($row, __FILE__, __LINE__, PEAR_LOG_ERR);
            return $row;
        }

        return $return;
    }

    /**
     * Retrieves the user options and stores them in the member array.
     *
     * @return mixed  True on success or a PEAR_Error object on failure.
     */
    function retrieve()
    {
        $options = $this->_retrieve();
        if (!is_a($options, 'PEAR_Error')) {
            $this->_options = $options;
        } else {
            return $options;
        }

        return true;
    }

    /**
     * Store an option set from the member array to the storage backend.
     *
     * @access private
     *
     * @return mixed  True on success or a PEAR_Error object on failure.
     */
    function _store()
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Check if the policy already exists. */
        $policyID = $this->_lookupPolicyID();
        if (is_a($policyID, 'PEAR_Error')) {
            return $policyID;
        }

        /* Delete existing policy. */
        if (!is_null($policyID)) {
            $query = sprintf('DELETE FROM %s WHERE %s = ?',
                             $this->_mapNameToTable('policies'),
                             $this->_mapAttributeToField('policies', 'name'));
            $values = array($this->_user);

            /* Log the query at a DEBUG log level. */
            Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                              __FILE__, __LINE__, PEAR_LOG_DEBUG);

            $result = $this->_db->query($query, $values);
            if (is_a($result, 'PEAR_Error')) {
                Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
                return $result;
            }
        }

        /* Insert new policy (everything but whitelists and blacklists). */
        $insertKeys = $insertVals = array();
        foreach ($this->_options as $attribute => $value) {
            if ($attribute != 'whitelist_from' && $attribute != 'blacklist_from') {
                $insertKeys[] = $this->_mapAttributeToField('policies', $attribute);
                $insertVals[] = $value;
            }
        }
        if (count($insertKeys)) {
            $query = sprintf('INSERT INTO %s (%s, %s) VALUES (%s)',
                             $this->_mapNameToTable('policies'),
                             $this->_mapAttributeToField('policies', 'name'),
                             implode(', ', $insertKeys),
                             implode(', ', array_fill(0, count($insertVals) + 1, '?')));
            $values = array_merge(array($this->_user), $insertVals);

            /* Log the query at a DEBUG log level. */
            Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                              __FILE__, __LINE__, PEAR_LOG_DEBUG);

            $result = $this->_db->query($query, $values);
            if (is_a($result, 'PEAR_Error')) {
                Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
                return $result;
            }
        }

        /* Get the new policy id for the recipients table. */
        $policyID = $this->_lookupPolicyID();
        if (is_a($policyID, 'PEAR_Error')) {
            return $policyID;
        }

        /* Update recipients with new policy id. */
        $query = sprintf('UPDATE %s SET %s = ? WHERE %s = ?',
                         $this->_mapNameToTable('recipients'),
                         $this->_mapAttributeToField('recipients', 'policy_id'),
                         $this->_mapAttributeToField('recipients', 'email'));
        $values = array($policyID, $this->_user);

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        $result = $this->_db->query($query, $values);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
            return $result;
        }

        /* Find the user id. */
        $userID = $this->_lookupUserID();
        if (is_a($userID, 'PEAR_Error')) {
            return $userID;
        }

        $existing = array('whitelist_from' => array(), 'blacklist_from' => array());

        /* Build the SQL query for whitelists and blacklists. */
        $query = sprintf('SELECT %s, %s FROM %s WHERE %s = ?',
                         $this->_mapAttributeToField('wblists', 'sender'),
                         $this->_mapAttributeToField('wblists', 'type'),
                         $this->_mapNameToTable('wblists'),
                         $this->_mapAttributeToField('wblists', 'recipient'));
        $values = array($userID);

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        $result = $this->_db->query($query, $values);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
            return $result;
        }

        /* Loop through results, retrieving whitelists and blacklists. */
        while (($row = $result->fetchRow(DB_FETCHMODE_ASSOC)) &&
               !is_a($row, 'PEAR_Error')) {
            $type = $row[$this->_mapAttributeToField('wblists', 'type')];
            $senderID = $row[$this->_mapAttributeToField('wblists', 'sender')];

            /* Only proceed if sender is listed white or black. */
            if (preg_match('/[WYBN]/i', $type)) {
                $query = sprintf('SELECT %s FROM %s WHERE %s = ?',
                                 $this->_mapAttributeToField('senders', 'email'),
                                 $this->_mapNameToTable('senders'),
                                 $this->_mapAttributeToField('senders', 'id'));
                $values = array($senderID);

                /* Log the query at a DEBUG log level. */
                Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                                  __FILE__, __LINE__, PEAR_LOG_DEBUG);

                $sender = $this->_db->getOne($query, $values);
                if (is_a($sender, 'PEAR_Error')) {
                    Horde::logMessage($sender, __FILE__, __LINE__, PEAR_LOG_ERR);
                    return $sender;
                } else {
                    $list = preg_match('/[WY]/i', $type) ? 'whitelist_from' : 'blacklist_from';
                    /* User removed an address from a list. */
                    if (!isset($this->_options[$list]) || !in_array($sender, $this->_options[$list])) {
                        $query = sprintf('DELETE FROM %s WHERE %s = ? AND %s = ?',
                                         $this->_mapNameToTable('wblists'),
                                         $this->_mapAttributeToField('wblists', 'sender'),
                                         $this->_mapAttributeToField('wblists', 'recipient'));
                        $values = array($senderID, $userID);

                        /* Log the query at a DEBUG log level. */
                        Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

                        $deleted = $this->_db->query($query, $values);
                        if (is_a($deleted, 'PEAR_Error')) {
                            Horde::logMessage($deleted, __FILE__, __LINE__, PEAR_LOG_ERR);
                            return $deleted;
                        }

                        /* Check if there is anyone else using this sender
                         * address. */
                        $query = sprintf('SELECT 1 FROM %s WHERE %s = ?',
                                         $this->_mapNameToTable('wblists'),
                                         $this->_mapAttributeToField('wblists', 'sender'));
                        $values = array($senderID);

                        /* Log the query at a DEBUG log level. */
                        Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

                        /* No one else needs this sender address, delete it
                         * from senders table. */
                        if (is_null($this->_db->getOne($query, $values))) {
                            $query = sprintf('DELETE FROM %s WHERE %s = ?',
                                             $this->_mapNameToTable('senders'),
                                             $this->_mapAttributeToField('senders', 'id'));
                            $values = array($senderID);

                            /* Log the query at a DEBUG log level. */
                            Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                                              __FILE__, __LINE__, PEAR_LOG_DEBUG);

                            $deleted = $this->_db->query($query, $values);
                            if (is_a($deleted, 'PEAR_Error')) {
                                Horde::logMessage($deleted, __FILE__, __LINE__, PEAR_LOG_ERR);
                                return $deleted;
                            }
                        }
                    } else {
                        $existing[$list][] = $sender;
                    }
                }
            }
        }
        $result->free();

        if (is_a($row, 'PEAR_Error')) {
            Horde::logMessage($row, __FILE__, __LINE__, PEAR_LOG_ERR);
            return $row;
        }

        /* Check any additions to the lists. */
        foreach (array('whitelist_from' => 'W', 'blacklist_from' => 'B') as $list => $type) {
            if (isset($this->_options[$list])) {
                foreach ($this->_options[$list] as $sender) {
                    if (!in_array($sender, $existing[$list])) {

                        /* Check if this sender address exists already. */
                        $query = sprintf('SELECT %s FROM %s WHERE %s = ?',
                                         $this->_mapAttributeToField('senders', 'id'),
                                         $this->_mapNameToTable('senders'),
                                         $this->_mapAttributeToField('senders', 'email'));
                        $values = array($sender);

                        /* Log the query at a DEBUG log level. */
                        Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

                        $wb_result = $this->_db->getOne($query, $values);
                        if (is_null($wb_result)) {
                            /* Address doesn't exist, add it. */
                            $query = sprintf('INSERT INTO %s (%s) VALUES (?)',
                                             $this->_mapNameToTable('senders'),
                                             $this->_mapAttributeToField('senders', 'email'));
                            $values = array($sender);

                            /* Log the query at a DEBUG log level. */
                            Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                                              __FILE__, __LINE__, PEAR_LOG_DEBUG);

                            $result = $this->_db->query($query, $values);
                            if (is_a($result, 'PEAR_Error')) {
                                Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
                                return $result;
                            }

                            $query = sprintf('SELECT %s FROM %s WHERE %s = ?',
                                             $this->_mapAttributeToField('senders', 'id'),
                                             $this->_mapNameToTable('senders'),
                                             $this->_mapAttributeToField('senders', 'email'));
                            $values = array($sender);

                            /* Log the query at a DEBUG log level. */
                            Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                                              __FILE__, __LINE__, PEAR_LOG_DEBUG);

                            $senderID = $this->_db->getOne($query, $values);
                            if (is_a($senderID, 'PEAR_Error')) {
                                Horde::logMessage($senderID, __FILE__, __LINE__, PEAR_LOG_ERR);
                                return $senderID;
                            }

                            $query = sprintf('INSERT INTO %s (%s, %s, %s) VALUES (?, ?, ?)',
                                             $this->_mapNameToTable('wblists'),
                                             $this->_mapAttributeToField('wblists', 'recipient'),
                                             $this->_mapAttributeToField('wblists', 'sender'),
                                             $this->_mapAttributeToField('wblists', 'type'));
                            $values = array($userID, $senderID, $type);

                            /* Log the query at a DEBUG log level. */
                            Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                                              __FILE__, __LINE__, PEAR_LOG_DEBUG);

                            $result = $this->_db->query($query, $values);
                            if (is_a($result, 'PEAR_Error')) {
                                Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
                                return $result;
                            }
                        } else {
                            /* Address exists, use it's ID */
                            $query = sprintf('INSERT INTO %s (%s, %s, %s) VALUES (?, ?, ?)',
                                             $this->_mapNameToTable('wblists'),
                                             $this->_mapAttributeToField('wblists', 'recipient'),
                                             $this->_mapAttributeToField('wblists', 'sender'),
                                             $this->_mapAttributeToField('wblists', 'type'));
                            $values = array($userID, $wb_result, $type);

                            /* Log the query at a DEBUG log level. */
                            Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                                              __FILE__, __LINE__, PEAR_LOG_DEBUG);

                            $result = $this->_db->query($query, $values);
                            if (is_a($result, 'PEAR_Error')) {
                                Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
                                return $result;
                            }
                        }
                    }
                }
            }
        }

        /* Remove any disjoined sender IDs. */
        $query = sprintf('DELETE FROM %s WHERE %s = ?',
                         $this->_mapNameToTable('wblists'),
                         $this->_mapAttributeToField('wblists', 'recipient'));
        $values = array('');

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SAM_Driver_amavisd_sql::_store(): %s', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        $result = $this->_db->query($query, $values);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
            return $result;
        }

        return true;
    }

    /**
     * Stores the user options from the member array.
     *
     * @return mixed  True on success or a PEAR_Error object on failure.
     */
    function store()
    {
        return $this->_store();
    }

    /**
     * Attempts to open a persistent connection to the SQL server.
     *
     * @access private
     *
     * @return mixed    True on success or a PEAR_Error object on failure.
     */
    function _connect()
    {
        if (!$this->_connected) {
            Horde::assertDriverConfig($this->_params, 'amavisd_sql',
                array('phptype'),
                'SAM backend', 'backends.php', '$backends');
            if (!isset($this->_params['table'])) {
                $this->_params['table'] = 'userpref';
            }

            if (!isset($this->_params['database'])) {
                $this->_params['database'] = '';
            }
            if (!isset($this->_params['username'])) {
                $this->_params['username'] = '';
            }
            if (!isset($this->_params['hostspec'])) {
                $this->_params['hostspec'] = '';
            }

            /* Connect to the SQL server using the supplied parameters. */
            require_once 'DB.php';
            $this->_db = &DB::connect($this->_params,
                                      array('persistent' => !empty($this->_params['persistent'])));
            if (is_a($this->_db, 'PEAR_Error')) {
                Horde::fatal($this->_db, __FILE__, __LINE__);
            }

            // Set DB portability options.
            switch ($this->_db->phptype) {
            case 'mssql':
                $this->_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS | DB_PORTABILITY_RTRIM);
                break;
            default:
                $this->_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS);
            }

            $this->_connected = true;
        }

        return true;
    }

    /**
     * Disconnect from the SQL server and clean up the connection.
     *
     * @return boolean  True on success, false on failure.
     */
    function _disconnect()
    {
        if ($this->_connected) {
            $this->_connected = false;
            return $this->_db->disconnect();
        }

        return true;
    }

}