4 * SQL-backed OpenID stores.
8 * LICENSE: See the COPYING file included in this distribution.
11 * @author JanRain, Inc. <openid@janrain.com>
12 * @copyright 2005-2008 Janrain, Inc.
13 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
19 require_once 'Auth/OpenID/Interface.php';
20 require_once 'Auth/OpenID/Nonce.php';
25 require_once 'Auth/OpenID.php';
30 require_once 'Auth/OpenID/Nonce.php';
33 * This is the parent class for the SQL stores, which contains the
34 * logic common to all of the SQL stores.
36 * The table names used are determined by the class variables
37 * associations_table_name and nonces_table_name. To change the name
38 * of the tables used, pass new table names into the constructor.
40 * To create the tables with the proper schema, see the createTables
43 * This class shouldn't be used directly. Use one of its subclasses
44 * instead, as those contain the code necessary to use a specific
45 * database. If you're an OpenID integrator and you'd like to create
46 * an SQL-driven store that wraps an application's database
47 * abstraction, be sure to create a subclass of
48 * {@link Auth_OpenID_DatabaseConnection} that calls the application's
49 * database abstraction calls. Then, pass an instance of your new
50 * database connection class to your SQLStore subclass constructor.
52 * All methods other than the constructor and createTables should be
53 * considered implementation details.
57 class Auth_OpenID_SQLStore extends Auth_OpenID_OpenIDStore {
60 * This creates a new SQLStore instance. It requires an
61 * established database connection be given to it, and it allows
62 * overriding the default table names.
64 * @param connection $connection This must be an established
65 * connection to a database of the correct type for the SQLStore
66 * subclass you're using. This must either be an PEAR DB
67 * connection handle or an instance of a subclass of
68 * Auth_OpenID_DatabaseConnection.
70 * @param associations_table: This is an optional parameter to
71 * specify the name of the table used for storing associations.
72 * The default value is 'oid_associations'.
74 * @param nonces_table: This is an optional parameter to specify
75 * the name of the table used for storing nonces. The default
76 * value is 'oid_nonces'.
78 function Auth_OpenID_SQLStore($connection,
79 $associations_table = null,
82 $this->associations_table_name = "oid_associations";
83 $this->nonces_table_name = "oid_nonces";
85 // Check the connection object type to be sure it's a PEAR
86 // database connection.
87 if (!(is_object($connection) &&
88 (is_subclass_of($connection, 'db_common') ||
89 is_subclass_of($connection,
90 'auth_openid_databaseconnection')))) {
91 trigger_error("Auth_OpenID_SQLStore expected PEAR connection " .
92 "object (got ".get_class($connection).")",
97 $this->connection = $connection;
99 // Be sure to set the fetch mode so the results are keyed on
100 // column name instead of column index. This is a PEAR
101 // constant, so only try to use it if PEAR is present. Note
102 // that Auth_Openid_Databaseconnection instances need not
103 // implement ::setFetchMode for this reason.
104 if (is_subclass_of($this->connection, 'db_common')) {
105 $this->connection->setFetchMode(DB_FETCHMODE_ASSOC);
108 if ($associations_table) {
109 $this->associations_table_name = $associations_table;
113 $this->nonces_table_name = $nonces_table;
116 $this->max_nonce_age = 6 * 60 * 60;
118 // Be sure to run the database queries with auto-commit mode
119 // turned OFF, because we want every function to run in a
120 // transaction, implicitly. As a rule, methods named with a
121 // leading underscore will NOT control transaction behavior.
122 // Callers of these methods will worry about transactions.
123 $this->connection->autoCommit(false);
125 // Create an empty SQL strings array.
126 $this->sql = array();
128 // Call this method (which should be overridden by subclasses)
129 // to populate the $this->sql array with SQL strings.
132 // Verify that all required SQL statements have been set, and
133 // raise an error if any expected SQL strings were either
135 list($missing, $empty) = $this->_verifySQL();
138 trigger_error("Expected keys in SQL query list: " .
139 implode(", ", $missing),
145 trigger_error("SQL list keys have no SQL strings: " .
146 implode(", ", $empty),
151 // Add table names to queries.
155 function tableExists($table_name)
157 return !$this->isError(
158 $this->connection->query(
159 sprintf("SELECT * FROM %s LIMIT 0",
164 * Returns true if $value constitutes a database error; returns
167 function isError($value)
169 return PEAR::isError($value);
173 * Converts a query result to a boolean. If the result is a
174 * database error according to $this->isError(), this returns
175 * false; otherwise, this returns true.
177 function resultToBool($obj)
179 if ($this->isError($obj)) {
187 * This method should be overridden by subclasses. This method is
188 * called by the constructor to set values in $this->sql, which is
189 * an array keyed on sql name.
196 * Resets the store by removing all records from the store's
201 $this->connection->query(sprintf("DELETE FROM %s",
202 $this->associations_table_name));
204 $this->connection->query(sprintf("DELETE FROM %s",
205 $this->nonces_table_name));
211 function _verifySQL()
216 $required_sql_keys = array(
225 foreach ($required_sql_keys as $key) {
226 if (!array_key_exists($key, $this->sql)) {
228 } else if (!$this->sql[$key]) {
233 return array($missing, $empty);
241 $replacements = array(
243 'value' => $this->nonces_table_name,
244 'keys' => array('nonce_table',
249 'value' => $this->associations_table_name,
250 'keys' => array('assoc_table',
259 foreach ($replacements as $item) {
260 $value = $item['value'];
261 $keys = $item['keys'];
263 foreach ($keys as $k) {
264 if (is_array($this->sql[$k])) {
265 foreach ($this->sql[$k] as $part_key => $part_value) {
266 $this->sql[$k][$part_key] = sprintf($part_value,
270 $this->sql[$k] = sprintf($this->sql[$k], $value);
276 function blobDecode($blob)
281 function blobEncode($str)
286 function createTables()
288 $this->connection->autoCommit(true);
289 $n = $this->create_nonce_table();
290 $a = $this->create_assoc_table();
291 $this->connection->autoCommit(false);
300 function create_nonce_table()
302 if (!$this->tableExists($this->nonces_table_name)) {
303 $r = $this->connection->query($this->sql['nonce_table']);
304 return $this->resultToBool($r);
309 function create_assoc_table()
311 if (!$this->tableExists($this->associations_table_name)) {
312 $r = $this->connection->query($this->sql['assoc_table']);
313 return $this->resultToBool($r);
321 function _set_assoc($server_url, $handle, $secret, $issued,
322 $lifetime, $assoc_type)
324 return $this->connection->query($this->sql['set_assoc'],
334 function storeAssociation($server_url, $association)
336 if ($this->resultToBool($this->_set_assoc(
338 $association->handle,
340 $association->secret),
341 $association->issued,
342 $association->lifetime,
343 $association->assoc_type
345 $this->connection->commit();
347 $this->connection->rollback();
354 function _get_assoc($server_url, $handle)
356 $result = $this->connection->getRow($this->sql['get_assoc'],
357 array($server_url, $handle));
358 if ($this->isError($result)) {
368 function _get_assocs($server_url)
370 $result = $this->connection->getAll($this->sql['get_assocs'],
373 if ($this->isError($result)) {
380 function removeAssociation($server_url, $handle)
382 if ($this->_get_assoc($server_url, $handle) == null) {
386 if ($this->resultToBool($this->connection->query(
387 $this->sql['remove_assoc'],
388 array($server_url, $handle)))) {
389 $this->connection->commit();
391 $this->connection->rollback();
397 function getAssociation($server_url, $handle = null)
399 if ($handle !== null) {
400 $assoc = $this->_get_assoc($server_url, $handle);
407 $assocs = $this->_get_assocs($server_url);
410 if (!$assocs || (count($assocs) == 0)) {
413 $associations = array();
415 foreach ($assocs as $assoc_row) {
416 $assoc = new Auth_OpenID_Association($assoc_row['handle'],
417 $assoc_row['secret'],
418 $assoc_row['issued'],
419 $assoc_row['lifetime'],
420 $assoc_row['assoc_type']);
422 $assoc->secret = $this->blobDecode($assoc->secret);
424 if ($assoc->getExpiresIn() == 0) {
425 $this->removeAssociation($server_url, $assoc->handle);
427 $associations[] = array($assoc->issued, $assoc);
434 foreach ($associations as $key => $assoc) {
435 $issued[$key] = $assoc[0];
436 $assocs[$key] = $assoc[1];
439 array_multisort($issued, SORT_DESC, $assocs, SORT_DESC,
442 // return the most recently issued one.
443 list($issued, $assoc) = $associations[0];
454 function _add_nonce($server_url, $timestamp, $salt)
456 $sql = $this->sql['add_nonce'];
457 $result = $this->connection->query($sql, array($server_url,
460 if ($this->isError($result)) {
461 $this->connection->rollback();
463 $this->connection->commit();
465 return $this->resultToBool($result);
468 function useNonce($server_url, $timestamp, $salt)
470 global $Auth_OpenID_SKEW;
472 if ( abs($timestamp - time()) > $Auth_OpenID_SKEW ) {
476 return $this->_add_nonce($server_url, $timestamp, $salt);
480 * "Octifies" a binary string by returning a string with escaped
481 * octal bytes. This is used for preparing binary data for
482 * PostgreSQL BYTEA fields.
486 function _octify($str)
489 for ($i = 0; $i < Auth_OpenID::bytes($str); $i++) {
490 $ch = substr($str, $i, 1);
492 $result .= "\\\\\\\\";
493 } else if (ord($ch) == 0) {
494 $result .= "\\\\000";
496 $result .= "\\" . strval(decoct(ord($ch)));
503 * "Unoctifies" octal-escaped data from PostgreSQL and returns the
504 * resulting ASCII (possibly binary) string.
508 function _unoctify($str)
512 while ($i < strlen($str)) {
515 // Look to see if the next char is a backslash and
517 if ($str[$i + 1] != "\\") {
518 $octal_digits = substr($str, $i + 1, 3);
519 $dec = octdec($octal_digits);
536 function cleanupNonces()
538 global $Auth_OpenID_SKEW;
539 $v = time() - $Auth_OpenID_SKEW;
541 $this->connection->query($this->sql['clean_nonce'], array($v));
542 $num = $this->connection->affectedRows();
543 $this->connection->commit();
547 function cleanupAssociations()
549 $this->connection->query($this->sql['clean_assoc'],
551 $num = $this->connection->affectedRows();
552 $this->connection->commit();