File: spamd_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 (360 lines) | stat: -rw-r--r-- 13,018 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
<?php

require_once dirname(__FILE__) . '/spamd.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/spamd_*.sql
 * script appropriate for your database, or modified from one that is
 * available.
 *
 * $Horde: sam/lib/Driver/spamd_sql.php,v 1.50 2006/01/18 17:49:02 ben Exp $
 *
 * Copyright 2003-2006 Chris Bowlby <excalibur@hub.org>
 * Copyright 2003-2006 Max Kalika <max@horde.org>
 * Copyright 2004-2006 Jan Schneider <jan@horde.org>
 *
 * See the enclosed file COPYING for license information (GPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/gpl.html.
 *
 * @author  Chris Bowlby <excalibur@hub.org>
 * @author  Max Kalika <max@horde.org>
 * @author  Jan Schneider <jan@horde.org>
 * @since   SAM 0.0.1
 * @package Sam
 */
class SAM_Driver_spamd_sql extends SAM_Driver_spamd {

    /**
     * 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;

    /**
     * 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_spamd_sql($user, $params = array())
    {
        global $conf;

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

    /**
     * Retrieve an option set from the storage backend.
     *
     * @access private
     *
     * @param boolean $defaults  Whether to retrieve the global defaults
     *                           instead of user options.
     *
     * @return mixed    Array of option-value pairs or a PEAR_Error object
     *                  on failure.
     */
    function _retrieve($defaults = false)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        if ($defaults) {
            $user = isset($this->_params['global_user'])
                    ? $this->_params['global_user'] : '@GLOBAL';
        } else {
            $user = $this->_user;
        }

        /* Build the SQL query. */
        $query = 'SELECT * FROM ' . $this->_params['table'] .
                 ' WHERE username = ?';
        $values = array($user);

        $return = array();

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

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

        /* Loop through rows, retrieving options. */
        while (($row = $result->fetchRow(DB_FETCHMODE_ASSOC)) && !is_a($row, 'PEAR_Error')) {
            $attribute = $this->_mapOptionToAttribute($row['preference']);

            if (isset($return[$attribute])) {
                if (!is_array($return[$attribute])) {
                    $return[$attribute] = array($return[$attribute]);
                }
                if (!in_array($row['value'], $return[$attribute])) {
                    $return[$attribute][] = $row['value'];
                }
            } else {
                $return[$attribute] = $row['value'];
            }
        }
        $result->free();

        if (is_a($row, 'PEAR_Error')) {
            return $row;
        }

        return $return;
    }

    /**
     * Retrieves the global defaults and user options and stores them in the
     * appropriate member array (options or defaults).
     *
     * @return mixed    True on success or a PEAR_Error object on failure.
     */
    function retrieve()
    {
        /* Load defaults for any options the user hasn't already overridden. */
        $defaults = $this->_retrieve(true);
        if (!is_a($defaults, 'PEAR_Error')) {
            $this->_defaults = $defaults;
        } else {
            return $defaults;
        }

        $this->_options = $this->_defaults;
        $options = $this->_retrieve();
        if (!is_a($options, 'PEAR_Error')) {
            $this->_options = array_merge($this->_options, $options);
        } else {
            return $options;
        }

        return true;
    }

    /**
     * Store an option set from the appropriate member array (options or
     * defaults) to the storage backend.
     *
     * @access private
     *
     * @param boolean $defaults  Whether to store the global defaults instead
     *                           of user options.
     *
     * @return mixed  True on success or a PEAR_Error object on failure.
     */
    function _store($defaults = false)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        if ($defaults) {
            $store = $this->_defaults;
            $user = isset($this->_params['global_user'])
                        ? $this->_params['global_user'] : '@GLOBAL';
        } else {
            $store = $this->_options;
            $user = $this->_user;
        }

        foreach ($store as $attribute => $value) {
            $option = $this->_mapAttributeToOption($attribute);

            /* Delete the option if it is the same as the default */
            if (!$defaults && isset($this->_defaults[$attribute]) &&
                $this->_defaults[$attribute] === $value) {
                $query = 'DELETE FROM ' . $this->_params['table'] .
                         ' WHERE username = ? AND preference = ?';
                $values = array($user, $option);
                /* Log the query at a DEBUG log level. */
                Horde::logMessage(sprintf('SAM_Driver_spamd_sql::_store(): %s', $query),
                                  __FILE__, __LINE__, PEAR_LOG_DEBUG);
                $this->_db->query($query, $values);
                continue;
            }

            if (is_array($value)) {
                $query = 'DELETE FROM ' . $this->_params['table'] .
                         ' WHERE username = ? AND preference = ?';
                $values = array($user, $option);
                /* Log the query at a DEBUG log level. */
                Horde::logMessage(sprintf('SAM_Driver_spamd_sql::_store(): %s', $query),
                                  __FILE__, __LINE__, PEAR_LOG_DEBUG);
                $this->_db->query($query, $values);

                foreach ($value as $address) {
                    /* Don't save email addresses already in defaults. */
                    if (!$defaults && isset($this->_defaults[$attribute]) &&
                        ((is_array($this->_defaults[$attribute]) &&
                          in_array($address, $this->_defaults[$attribute])) ||
                         $this->_defaults[$attribute] === $address)) {
                        continue;
                    }

                    $query = 'INSERT INTO ' . $this->_params['table'] .
                             ' (username, preference, value)' .
                             ' VALUES (?, ?, ?)';
                    $values = array($user, $option, $address);
                    /* Log the query at a DEBUG log level. */
                    Horde::logMessage(sprintf('SAM_Driver_spamd_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 {
                $query = 'SELECT 1 FROM ' . $this->_params['table'] .
                         ' WHERE username = ? AND preference = ?';
                $values = array($user, $option);

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

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

                if (is_null($result)) {
                    $query = 'INSERT INTO ' . $this->_params['table'] .
                             ' (username, preference, value)' .
                             ' VALUES (?, ?, ?)';
                    $values = array($user, $option, $value);
                } else {
                    $query = 'UPDATE ' . $this->_params['table'] .
                             ' SET value = ?' .
                             ' WHERE username = ? AND preference = ?';
                    $values = array($value, $user, $option);
                }

                /* Log the query at a DEBUG log level. */
                Horde::logMessage(sprintf('SAM_Driver_spamd_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 global defaults or user options from the appropriate
     * member array (options or defaults).
     *
     * @param boolean $defaults  Whether to store the global defaults instead
     *                           of user options.
     *
     * @return mixed  True on success or a PEAR_Error object on failure.
     */
    function store($defaults = false)
    {
        return $this->_store($defaults);
    }

    /**
     * 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, 'spamd_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;
    }

}