<?php

	include_once( PLOG_CLASS_PATH."class/dao/model.class.php" );

	/**
	 * schema of the table, so that we can tell ADOdb to create it
	 * automatically for us
	 */
	define( "ATOM_PASSWORDS_DB_SCHEMA", 
                "user_id I(10) NOTNULL,
                 password C(32) NOTNULL DEFAULT ''" );
	
	/**
	 * The WSSE authentication needs to know the plain version of the password so that
	 * we can calculate the digest. Unfortunatley plog does not have such password as
	 * we only store an md5 hash... Therefore, we need a separate table to hold a plain
	 * password that will be different from our site password
	 */
	class AtomPasswords extends Model
	{
		
		function AtomPasswords()
		{
			$this->Model();
			
			// initialize the db and check the tables
			$this->_initializeDb();			
		}

		/**
		 * @private
		 * Makes sure that the plog_atom_password table is there
		 */
		function checkTables()
		{
			$dbPrefix = $this->getPrefix();
			$tableName = $dbPrefix."atom_passwords";
			
			$dict = NewPDbDataDictionary( $this->_db );
			$sqlArray = $dict->ChangeTableSQL( $tableName, ATOM_PASSWORDS_DB_SCHEMA );
			$result = $dict->ExecuteSQLArray( $sqlArray );
		}

		/**
		 * retrieves a password
		 *
		 * @param userId
		 * @return A password string, or false otherwise
		 */
		function getPassword( $userId )
		{
			$query = "SELECT * FROM ".$this->getPrefix()."atom_passwords
				  WHERE user_id = $userId";
			$result = $this->Execute( $query );

			if( !$result )
				return false;
			if( $result->RecordCount() == 0 )
				return false;

			$row = $result->FetchRow();
			$password = $row["password"];

			return $password;
		}

		/**
		 * sets a password. It will create it if it does not exist or it will 
		 * update it if it already exists in the db
		 *
		 * @param userId
		 * @param password
		 * @return True if successful or false otherwise
		 */
		function setPassword( $userId, $password )
		{
			if( !$this->getPassword( $userId )) {
				// does not exist, let's create it
				$query = "INSERT INTO ".$this->getPrefix()."atom_passwords
					  VALUES( $userId, '".Db::qstr( $password )."' );";
			}
			else {
				$query = "UPDATE ".$this->getPrefix()."atom_passwords
					  SET password = '".Db::qstr( $password )."'
					  WHERE user_id = $userId";
			}

			return( $this->Execute( $query ));
		}
	}
?>
