source: trunk/phpgwapi/inc/adodb/pear/Auth/Container/ADOdb.php @ 2

Revision 2, 12.7 KB checked in by niltonneto, 17 years ago (diff)

Removida todas as tags usadas pelo CVS ($Id, $Source).
Primeira versão no CVS externo.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2//
3// +----------------------------------------------------------------------+
4// | PHP Version 4                                                        |
5// +----------------------------------------------------------------------+
6// |                                                                      |
7// +----------------------------------------------------------------------+
8// | This source file is subject to version 2.02 of the PHP license,      |
9// | that is bundled with this package in the file LICENSE, and is        |
10// | available at through the world-wide-web at                           |
11// | http://www.php.net/license/2_02.txt.                                 |
12// | If you did not receive a copy of the PHP license and are unable to   |
13// | obtain it through the world-wide-web, please send a note to          |
14// | license@php.net so we can mail you a copy immediately.               |
15// +----------------------------------------------------------------------+
16// | Authors: Martin Jansen <mj@php.net>
17// |    Richard Tango-Lowy <richtl@arscognita.com>                                  |
18// +----------------------------------------------------------------------+
19//
20//
21
22require_once 'Auth/Container.php';
23require_once 'adodb.inc.php';
24require_once 'adodb-pear.inc.php';
25require_once 'adodb-errorpear.inc.php';
26
27/**
28 * Storage driver for fetching login data from a database using ADOdb-PHP.
29 *
30 * This storage driver can use all databases which are supported
31 * by the ADBdb DB abstraction layer to fetch login data.
32 * See http://php.weblogs.com/adodb for information on ADOdb.
33 * NOTE: The ADOdb directory MUST be in your PHP include_path!
34 *
35 * @author   Richard Tango-Lowy <richtl@arscognita.com>
36 * @package  Auth
37 */
38class Auth_Container_ADOdb extends Auth_Container
39{
40
41    /**
42     * Additional options for the storage container
43     * @var array
44     */
45    var $options = array();
46
47    /**
48     * DB object
49     * @var object
50     */
51    var $db = null;
52    var $dsn = '';
53       
54    /**
55     * User that is currently selected from the DB.
56     * @var string
57     */
58    var $activeUser = '';
59
60    // {{{ Constructor
61
62    /**
63     * Constructor of the container class
64     *
65     * Initate connection to the database via PEAR::ADOdb
66     *
67     * @param  string Connection data or DB object
68     * @return object Returns an error object if something went wrong
69     */
70    function Auth_Container_ADOdb($dsn)
71    {
72        $this->_setDefaults();
73               
74        if (is_array($dsn)) {
75            $this->_parseOptions($dsn);
76
77            if (empty($this->options['dsn'])) {
78                PEAR::raiseError('No connection parameters specified!');
79            }
80        } else {
81                // Extract db_type from dsn string.
82            $this->options['dsn'] = $dsn;
83            $this->_parseDsn( $dsn );
84        }
85    }
86
87    // }}}
88    // {{{ _connect()
89
90    /**
91     * Connect to database by using the given DSN string
92     *
93     * @access private
94     * @param  string DSN string
95     * @return mixed  Object on error, otherwise bool
96     */
97     function _connect($dsn)
98    {
99        if (is_string($dsn) || is_array($dsn)) {
100                if(!$this->db) {
101                        $this->db = &ADONewConnection($this->options['db_type']);
102                       
103                        if( $err = ADODB_Pear_error() ) {
104                                return PEAR::raiseError($err);
105                        }
106                }
107               
108                $dbconnected = $this->db->Connect(
109                        $this->options['db_host'],
110                        $this->options['db_user'],
111                        $this->options['db_pass'],
112                        $this->options['db_name'] );
113                if( !$dbconnected ) {
114                        PEAR::raiseError('Unable to connect to database' );
115                }
116               
117        } else {
118            return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__,
119                                    41,
120                                    PEAR_ERROR_RETURN,
121                                    null,
122                                    null
123                                    );
124        }
125       
126        if(!$this->db) {
127                return PEAR::raiseError(ADODB_Pear_error());
128        } else {
129                return true;
130        }
131    }
132
133    // }}}
134    // {{{ _prepare()
135
136    /**
137     * Prepare database connection
138     *
139     * This function checks if we have already opened a connection to
140     * the database. If that's not the case, a new connection is opened.
141     *
142     * @access private
143     * @return mixed True or a DB error object.
144     */
145    function _prepare()
146    {
147        if(!$this->db) {
148                $res = $this->_connect($this->options['dsn']);                 
149        }
150        return true;
151    }
152
153    // }}}
154    // {{{ query()
155
156    /**
157     * Prepare query to the database
158     *
159     * This function checks if we have already opened a connection to
160     * the database. If that's not the case, a new connection is opened.
161     * After that the query is passed to the database.
162     *
163     * @access public
164     * @param  string Query string
165     * @return mixed  a DB_result object or DB_OK on success, a DB
166     *                or PEAR error on failure
167     */
168    function query($query)
169    {
170        $err = $this->_prepare();
171        if ($err !== true) {
172            return $err;
173        }
174        return $this->db->query($query);
175    }
176
177    // }}}
178    // {{{ _setDefaults()
179
180    /**
181     * Set some default options
182     *
183     * @access private
184     * @return void
185     */
186    function _setDefaults()
187    {
188        $this->options['db_type']       = 'mysql';
189        $this->options['table']       = 'auth';
190        $this->options['usernamecol'] = 'username';
191        $this->options['passwordcol'] = 'password';
192        $this->options['dsn']         = '';
193        $this->options['db_fields']   = '';
194        $this->options['cryptType']   = 'md5';
195    }
196
197    // }}}
198    // {{{ _parseOptions()
199
200    /**
201     * Parse options passed to the container class
202     *
203     * @access private
204     * @param  array
205     */
206    function _parseOptions($array)
207    {
208        foreach ($array as $key => $value) {
209            if (isset($this->options[$key])) {
210                $this->options[$key] = $value;
211            }
212        }
213
214        /* Include additional fields if they exist */
215        if(!empty($this->options['db_fields'])){
216            if(is_array($this->options['db_fields'])){
217                $this->options['db_fields'] = join($this->options['db_fields'], ', ');
218            }
219            $this->options['db_fields'] = ', '.$this->options['db_fields'];
220        }
221    }
222
223    // }}}
224    // {{{ fetchData()
225
226    /**
227     * Get user information from database
228     *
229     * This function uses the given username to fetch
230     * the corresponding login data from the database
231     * table. If an account that matches the passed username
232     * and password is found, the function returns true.
233     * Otherwise it returns false.
234     *
235     * @param   string Username
236     * @param   string Password
237     * @return  mixed  Error object or boolean
238     */
239    function fetchData($username, $password)
240    {
241        // Prepare for a database query
242        $err = $this->_prepare();
243        if ($err !== true) {
244            return PEAR::raiseError($err->getMessage(), $err->getCode());
245        }
246
247        // Find if db_fields contains a *, i so assume all col are selected
248        if(strstr($this->options['db_fields'], '*')){
249            $sql_from = "*";
250        }
251        else{
252            $sql_from = $this->options['usernamecol'] . ", ".$this->options['passwordcol'].$this->options['db_fields'];
253        }
254       
255        $query = "SELECT ".$sql_from.
256                " FROM ".$this->options['table'].
257                " WHERE ".$this->options['usernamecol']." = " . $this->db->Quote($username);
258       
259        $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
260        $rset = $this->db->Execute( $query );
261        $res = $rset->fetchRow();
262
263        if (DB::isError($res)) {
264            return PEAR::raiseError($res->getMessage(), $res->getCode());
265        }
266        if (!is_array($res)) {
267            $this->activeUser = '';
268            return false;
269        }
270        if ($this->verifyPassword(trim($password, "\r\n"),
271                                  trim($res[$this->options['passwordcol']], "\r\n"),
272                                  $this->options['cryptType'])) {
273            // Store additional field values in the session
274            foreach ($res as $key => $value) {
275                if ($key == $this->options['passwordcol'] ||
276                    $key == $this->options['usernamecol']) {
277                    continue;
278                }
279                // Use reference to the auth object if exists
280                // This is because the auth session variable can change so a static call to setAuthData does not make sence
281                if(is_object($this->_auth_obj)){
282                    $this->_auth_obj->setAuthData($key, $value);
283                } else {
284                    Auth::setAuthData($key, $value);
285                }
286            }
287
288            return true;
289        }
290
291        $this->activeUser = $res[$this->options['usernamecol']];
292        return false;
293    }
294
295    // }}}
296    // {{{ listUsers()
297
298    function listUsers()
299    {
300        $err = $this->_prepare();
301        if ($err !== true) {
302            return PEAR::raiseError($err->getMessage(), $err->getCode());
303        }
304
305        $retVal = array();
306
307        // Find if db_fileds contains a *, i so assume all col are selected
308        if(strstr($this->options['db_fields'], '*')){
309            $sql_from = "*";
310        }
311        else{
312            $sql_from = $this->options['usernamecol'] . ", ".$this->options['passwordcol'].$this->options['db_fields'];
313        }
314
315        $query = sprintf("SELECT %s FROM %s",
316                         $sql_from,
317                         $this->options['table']
318                         );
319        $res = $this->db->getAll($query, null, DB_FETCHMODE_ASSOC);
320
321        if (DB::isError($res)) {
322            return PEAR::raiseError($res->getMessage(), $res->getCode());
323        } else {
324            foreach ($res as $user) {
325                $user['username'] = $user[$this->options['usernamecol']];
326                $retVal[] = $user;
327            }
328        }
329        return $retVal;
330    }
331
332    // }}}
333    // {{{ addUser()
334
335    /**
336     * Add user to the storage container
337     *
338     * @access public
339     * @param  string Username
340     * @param  string Password
341     * @param  mixed  Additional information that are stored in the DB
342     *
343     * @return mixed True on success, otherwise error object
344     */
345    function addUser($username, $password, $additional = "")
346    {
347        if (function_exists($this->options['cryptType'])) {
348            $cryptFunction = $this->options['cryptType'];
349        } else {
350            $cryptFunction = 'md5';
351        }
352
353        $additional_key   = '';
354        $additional_value = '';
355
356        if (is_array($additional)) {
357            foreach ($additional as $key => $value) {
358                $additional_key .= ', ' . $key;
359                $additional_value .= ", '" . $value . "'";
360            }
361        }
362
363        $query = sprintf("INSERT INTO %s (%s, %s%s) VALUES ('%s', '%s'%s)",
364                         $this->options['table'],
365                         $this->options['usernamecol'],
366                         $this->options['passwordcol'],
367                         $additional_key,
368                         $username,
369                         $cryptFunction($password),
370                         $additional_value
371                         );
372
373        $res = $this->query($query);
374
375        if (DB::isError($res)) {
376           return PEAR::raiseError($res->getMessage(), $res->getCode());
377        } else {
378          return true;
379        }
380    }
381
382    // }}}
383    // {{{ removeUser()
384
385    /**
386     * Remove user from the storage container
387     *
388     * @access public
389     * @param  string Username
390     *
391     * @return mixed True on success, otherwise error object
392     */
393    function removeUser($username)
394    {
395        $query = sprintf("DELETE FROM %s WHERE %s = '%s'",
396                         $this->options['table'],
397                         $this->options['usernamecol'],
398                         $username
399                         );
400
401        $res = $this->query($query);
402
403        if (DB::isError($res)) {
404           return PEAR::raiseError($res->getMessage(), $res->getCode());
405        } else {
406          return true;
407        }
408    }
409
410    // }}}
411
412        function _parseDsn( $dsn )
413        {
414                if( is_string( $dsn )) {
415                        preg_match( '/^(\w*):\/\/(\w*)(:(\w*))?@(\w*)\/(\w*)$/', $dsn, $match );
416                       
417                        $this->options['db_type'] = $match[1];
418                        $this->options['db_user'] = $match[2];
419                        $this->options['db_pass'] = $match[3];
420                        $this->options['db_host'] = $match[5];
421                        $this->options['db_name'] = $match[6];
422                }       
423        }
424}
425
426function showDbg( $string ) {
427        print "<P>$string</P>";
428}
429function dump( $var, $str, $vardump = false ) {
430        print "<H4>$str</H4><pre>";
431        ( !$vardump ) ? ( print_r( $var )) : ( var_dump( $var ));
432        print "</pre>";
433}
434?>
Note: See TracBrowser for help on using the repository browser.