SQLStore.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. <?php
  2. /**
  3. * SQL-backed OpenID stores.
  4. *
  5. * PHP versions 4 and 5
  6. *
  7. * LICENSE: See the COPYING file included in this distribution.
  8. *
  9. * @package OpenID
  10. * @author JanRain, Inc. <openid@janrain.com>
  11. * @copyright 2005-2008 Janrain, Inc.
  12. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
  13. */
  14. /**
  15. * @access private
  16. */
  17. require_once 'Auth/OpenID/Interface.php';
  18. require_once 'Auth/OpenID/Nonce.php';
  19. /**
  20. * @access private
  21. */
  22. require_once 'Auth/OpenID.php';
  23. /**
  24. * @access private
  25. */
  26. require_once 'Auth/OpenID/Nonce.php';
  27. /**
  28. * This is the parent class for the SQL stores, which contains the
  29. * logic common to all of the SQL stores.
  30. *
  31. * The table names used are determined by the class variables
  32. * associations_table_name and nonces_table_name. To change the name
  33. * of the tables used, pass new table names into the constructor.
  34. *
  35. * To create the tables with the proper schema, see the createTables
  36. * method.
  37. *
  38. * This class shouldn't be used directly. Use one of its subclasses
  39. * instead, as those contain the code necessary to use a specific
  40. * database. If you're an OpenID integrator and you'd like to create
  41. * an SQL-driven store that wraps an application's database
  42. * abstraction, be sure to create a subclass of
  43. * {@link Auth_OpenID_DatabaseConnection} that calls the application's
  44. * database abstraction calls. Then, pass an instance of your new
  45. * database connection class to your SQLStore subclass constructor.
  46. *
  47. * All methods other than the constructor and createTables should be
  48. * considered implementation details.
  49. *
  50. * @package OpenID
  51. */
  52. class Auth_OpenID_SQLStore extends Auth_OpenID_OpenIDStore {
  53. /**
  54. * This creates a new SQLStore instance. It requires an
  55. * established database connection be given to it, and it allows
  56. * overriding the default table names.
  57. *
  58. * @param connection $connection This must be an established
  59. * connection to a database of the correct type for the SQLStore
  60. * subclass you're using. This must either be an PEAR DB
  61. * connection handle or an instance of a subclass of
  62. * Auth_OpenID_DatabaseConnection.
  63. *
  64. * @param associations_table: This is an optional parameter to
  65. * specify the name of the table used for storing associations.
  66. * The default value is 'oid_associations'.
  67. *
  68. * @param nonces_table: This is an optional parameter to specify
  69. * the name of the table used for storing nonces. The default
  70. * value is 'oid_nonces'.
  71. */
  72. function Auth_OpenID_SQLStore($connection,
  73. $associations_table = null,
  74. $nonces_table = null)
  75. {
  76. $this->associations_table_name = "oid_associations";
  77. $this->nonces_table_name = "oid_nonces";
  78. // Check the connection object type to be sure it's a PEAR
  79. // database connection.
  80. if (!(is_object($connection) &&
  81. (is_subclass_of($connection, 'db_common') ||
  82. is_subclass_of($connection,
  83. 'auth_openid_databaseconnection')))) {
  84. trigger_error("Auth_OpenID_SQLStore expected PEAR connection " .
  85. "object (got ".get_class($connection).")",
  86. E_USER_ERROR);
  87. return;
  88. }
  89. $this->connection = $connection;
  90. // Be sure to set the fetch mode so the results are keyed on
  91. // column name instead of column index. This is a PEAR
  92. // constant, so only try to use it if PEAR is present. Note
  93. // that Auth_Openid_Databaseconnection instances need not
  94. // implement ::setFetchMode for this reason.
  95. if (is_subclass_of($this->connection, 'db_common')) {
  96. $this->connection->setFetchMode(DB_FETCHMODE_ASSOC);
  97. }
  98. if ($associations_table) {
  99. $this->associations_table_name = $associations_table;
  100. }
  101. if ($nonces_table) {
  102. $this->nonces_table_name = $nonces_table;
  103. }
  104. $this->max_nonce_age = 6 * 60 * 60;
  105. // Be sure to run the database queries with auto-commit mode
  106. // turned OFF, because we want every function to run in a
  107. // transaction, implicitly. As a rule, methods named with a
  108. // leading underscore will NOT control transaction behavior.
  109. // Callers of these methods will worry about transactions.
  110. $this->connection->autoCommit(false);
  111. // Create an empty SQL strings array.
  112. $this->sql = array();
  113. // Call this method (which should be overridden by subclasses)
  114. // to populate the $this->sql array with SQL strings.
  115. $this->setSQL();
  116. // Verify that all required SQL statements have been set, and
  117. // raise an error if any expected SQL strings were either
  118. // absent or empty.
  119. list($missing, $empty) = $this->_verifySQL();
  120. if ($missing) {
  121. trigger_error("Expected keys in SQL query list: " .
  122. implode(", ", $missing),
  123. E_USER_ERROR);
  124. return;
  125. }
  126. if ($empty) {
  127. trigger_error("SQL list keys have no SQL strings: " .
  128. implode(", ", $empty),
  129. E_USER_ERROR);
  130. return;
  131. }
  132. // Add table names to queries.
  133. $this->_fixSQL();
  134. }
  135. function tableExists($table_name)
  136. {
  137. return !$this->isError(
  138. $this->connection->query(
  139. sprintf("SELECT * FROM %s LIMIT 0",
  140. $table_name)));
  141. }
  142. /**
  143. * Returns true if $value constitutes a database error; returns
  144. * false otherwise.
  145. */
  146. function isError($value)
  147. {
  148. return @PEAR::isError($value);
  149. }
  150. /**
  151. * Converts a query result to a boolean. If the result is a
  152. * database error according to $this->isError(), this returns
  153. * false; otherwise, this returns true.
  154. */
  155. function resultToBool($obj)
  156. {
  157. if ($this->isError($obj)) {
  158. return false;
  159. } else {
  160. return true;
  161. }
  162. }
  163. /**
  164. * This method should be overridden by subclasses. This method is
  165. * called by the constructor to set values in $this->sql, which is
  166. * an array keyed on sql name.
  167. */
  168. function setSQL()
  169. {
  170. }
  171. /**
  172. * Resets the store by removing all records from the store's
  173. * tables.
  174. */
  175. function reset()
  176. {
  177. $this->connection->query(sprintf("DELETE FROM %s",
  178. $this->associations_table_name));
  179. $this->connection->query(sprintf("DELETE FROM %s",
  180. $this->nonces_table_name));
  181. }
  182. /**
  183. * @access private
  184. */
  185. function _verifySQL()
  186. {
  187. $missing = array();
  188. $empty = array();
  189. $required_sql_keys = array(
  190. 'nonce_table',
  191. 'assoc_table',
  192. 'set_assoc',
  193. 'get_assoc',
  194. 'get_assocs',
  195. 'remove_assoc'
  196. );
  197. foreach ($required_sql_keys as $key) {
  198. if (!array_key_exists($key, $this->sql)) {
  199. $missing[] = $key;
  200. } else if (!$this->sql[$key]) {
  201. $empty[] = $key;
  202. }
  203. }
  204. return array($missing, $empty);
  205. }
  206. /**
  207. * @access private
  208. */
  209. function _fixSQL()
  210. {
  211. $replacements = array(
  212. array(
  213. 'value' => $this->nonces_table_name,
  214. 'keys' => array('nonce_table',
  215. 'add_nonce',
  216. 'clean_nonce')
  217. ),
  218. array(
  219. 'value' => $this->associations_table_name,
  220. 'keys' => array('assoc_table',
  221. 'set_assoc',
  222. 'get_assoc',
  223. 'get_assocs',
  224. 'remove_assoc',
  225. 'clean_assoc')
  226. )
  227. );
  228. foreach ($replacements as $item) {
  229. $value = $item['value'];
  230. $keys = $item['keys'];
  231. foreach ($keys as $k) {
  232. if (is_array($this->sql[$k])) {
  233. foreach ($this->sql[$k] as $part_key => $part_value) {
  234. $this->sql[$k][$part_key] = sprintf($part_value,
  235. $value);
  236. }
  237. } else {
  238. $this->sql[$k] = sprintf($this->sql[$k], $value);
  239. }
  240. }
  241. }
  242. }
  243. function blobDecode($blob)
  244. {
  245. return $blob;
  246. }
  247. function blobEncode($str)
  248. {
  249. return $str;
  250. }
  251. function createTables()
  252. {
  253. $this->connection->autoCommit(true);
  254. $n = $this->create_nonce_table();
  255. $a = $this->create_assoc_table();
  256. $this->connection->autoCommit(false);
  257. if ($n && $a) {
  258. return true;
  259. } else {
  260. return false;
  261. }
  262. }
  263. function create_nonce_table()
  264. {
  265. if (!$this->tableExists($this->nonces_table_name)) {
  266. $r = $this->connection->query($this->sql['nonce_table']);
  267. return $this->resultToBool($r);
  268. }
  269. return true;
  270. }
  271. function create_assoc_table()
  272. {
  273. if (!$this->tableExists($this->associations_table_name)) {
  274. $r = $this->connection->query($this->sql['assoc_table']);
  275. return $this->resultToBool($r);
  276. }
  277. return true;
  278. }
  279. /**
  280. * @access private
  281. */
  282. function _set_assoc($server_url, $handle, $secret, $issued,
  283. $lifetime, $assoc_type)
  284. {
  285. return $this->connection->query($this->sql['set_assoc'],
  286. array(
  287. $server_url,
  288. $handle,
  289. $secret,
  290. $issued,
  291. $lifetime,
  292. $assoc_type));
  293. }
  294. function storeAssociation($server_url, $association)
  295. {
  296. if ($this->resultToBool($this->_set_assoc(
  297. $server_url,
  298. $association->handle,
  299. $this->blobEncode(
  300. $association->secret),
  301. $association->issued,
  302. $association->lifetime,
  303. $association->assoc_type
  304. ))) {
  305. $this->connection->commit();
  306. } else {
  307. $this->connection->rollback();
  308. }
  309. }
  310. /**
  311. * @access private
  312. */
  313. function _get_assoc($server_url, $handle)
  314. {
  315. $result = $this->connection->getRow($this->sql['get_assoc'],
  316. array($server_url, $handle));
  317. if ($this->isError($result)) {
  318. return null;
  319. } else {
  320. return $result;
  321. }
  322. }
  323. /**
  324. * @access private
  325. */
  326. function _get_assocs($server_url)
  327. {
  328. $result = $this->connection->getAll($this->sql['get_assocs'],
  329. array($server_url));
  330. if ($this->isError($result)) {
  331. return array();
  332. } else {
  333. return $result;
  334. }
  335. }
  336. function removeAssociation($server_url, $handle)
  337. {
  338. if ($this->_get_assoc($server_url, $handle) == null) {
  339. return false;
  340. }
  341. if ($this->resultToBool($this->connection->query(
  342. $this->sql['remove_assoc'],
  343. array($server_url, $handle)))) {
  344. $this->connection->commit();
  345. } else {
  346. $this->connection->rollback();
  347. }
  348. return true;
  349. }
  350. function getAssociation($server_url, $handle = null)
  351. {
  352. if ($handle !== null) {
  353. $assoc = $this->_get_assoc($server_url, $handle);
  354. $assocs = array();
  355. if ($assoc) {
  356. $assocs[] = $assoc;
  357. }
  358. } else {
  359. $assocs = $this->_get_assocs($server_url);
  360. }
  361. if (!$assocs || (count($assocs) == 0)) {
  362. return null;
  363. } else {
  364. $associations = array();
  365. foreach ($assocs as $assoc_row) {
  366. $assoc = new Auth_OpenID_Association($assoc_row['handle'],
  367. $assoc_row['secret'],
  368. $assoc_row['issued'],
  369. $assoc_row['lifetime'],
  370. $assoc_row['assoc_type']);
  371. $assoc->secret = $this->blobDecode($assoc->secret);
  372. if ($assoc->getExpiresIn() == 0) {
  373. $this->removeAssociation($server_url, $assoc->handle);
  374. } else {
  375. $associations[] = array($assoc->issued, $assoc);
  376. }
  377. }
  378. if ($associations) {
  379. $issued = array();
  380. $assocs = array();
  381. foreach ($associations as $key => $assoc) {
  382. $issued[$key] = $assoc[0];
  383. $assocs[$key] = $assoc[1];
  384. }
  385. array_multisort($issued, SORT_DESC, $assocs, SORT_DESC,
  386. $associations);
  387. // return the most recently issued one.
  388. list($issued, $assoc) = $associations[0];
  389. return $assoc;
  390. } else {
  391. return null;
  392. }
  393. }
  394. }
  395. /**
  396. * @access private
  397. */
  398. function _add_nonce($server_url, $timestamp, $salt)
  399. {
  400. $sql = $this->sql['add_nonce'];
  401. $result = $this->connection->query($sql, array($server_url,
  402. $timestamp,
  403. $salt));
  404. if ($this->isError($result)) {
  405. $this->connection->rollback();
  406. } else {
  407. $this->connection->commit();
  408. }
  409. return $this->resultToBool($result);
  410. }
  411. function useNonce($server_url, $timestamp, $salt)
  412. {
  413. global $Auth_OpenID_SKEW;
  414. if ( abs($timestamp - time()) > $Auth_OpenID_SKEW ) {
  415. return false;
  416. }
  417. return $this->_add_nonce($server_url, $timestamp, $salt);
  418. }
  419. /**
  420. * "Octifies" a binary string by returning a string with escaped
  421. * octal bytes. This is used for preparing binary data for
  422. * PostgreSQL BYTEA fields.
  423. *
  424. * @access private
  425. */
  426. function _octify($str)
  427. {
  428. $result = "";
  429. for ($i = 0; $i < Auth_OpenID::bytes($str); $i++) {
  430. $ch = substr($str, $i, 1);
  431. if ($ch == "\\") {
  432. $result .= "\\\\\\\\";
  433. } else if (ord($ch) == 0) {
  434. $result .= "\\\\000";
  435. } else {
  436. $result .= "\\" . strval(decoct(ord($ch)));
  437. }
  438. }
  439. return $result;
  440. }
  441. /**
  442. * "Unoctifies" octal-escaped data from PostgreSQL and returns the
  443. * resulting ASCII (possibly binary) string.
  444. *
  445. * @access private
  446. */
  447. function _unoctify($str)
  448. {
  449. $result = "";
  450. $i = 0;
  451. while ($i < strlen($str)) {
  452. $char = $str[$i];
  453. if ($char == "\\") {
  454. // Look to see if the next char is a backslash and
  455. // append it.
  456. if ($str[$i + 1] != "\\") {
  457. $octal_digits = substr($str, $i + 1, 3);
  458. $dec = octdec($octal_digits);
  459. $char = chr($dec);
  460. $i += 4;
  461. } else {
  462. $char = "\\";
  463. $i += 2;
  464. }
  465. } else {
  466. $i += 1;
  467. }
  468. $result .= $char;
  469. }
  470. return $result;
  471. }
  472. function cleanupNonces()
  473. {
  474. global $Auth_OpenID_SKEW;
  475. $v = time() - $Auth_OpenID_SKEW;
  476. $this->connection->query($this->sql['clean_nonce'], array($v));
  477. $num = $this->connection->affectedRows();
  478. $this->connection->commit();
  479. return $num;
  480. }
  481. function cleanupAssociations()
  482. {
  483. $this->connection->query($this->sql['clean_assoc'],
  484. array(time()));
  485. $num = $this->connection->affectedRows();
  486. $this->connection->commit();
  487. return $num;
  488. }
  489. }