Beispiel #1
0
	/**
	 * Attempts to authenticate the specified user with the specified password.
	 * Returns the result of the authentication process (either the user's
	 * unique ID, or a failure code on failure).
	 *
	 * @return mixed the result of the authentication process, on success the user's unique ID
	 */
	public function authenticate() {
		try {
			// Query Database
			$db = \Bedrock\Common\Registry::get('database')->getConnection();
			$statement = $db->prepare('SELECT ' . $this->_fieldUsername . ', ' . $this->_fieldPassword . ' FROM ' . $this->_table . ' WHERE ' . $this->_fieldUsername . '=:username');
			$statement->execute(array('username' => $this->_username));
			$res = $statement->fetchAll();

			if(count($res) == 0) {
				$this->_id = \Bedrock\Common\Auth::RESULT_FAILED_USERNAME;
			}
			else {
				$res = $res[0];

				if($res['password'] != $this->_password) {
					$this->_id = \Bedrock\Common\Auth::RESULT_FAILED_PASSWORD;
				}
				else {
					$this->_id = $res['id'];
				}
			}

			return $this->_id;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\Auth\Exception('Authentication could not be completed.');
		}
	}
Beispiel #2
0
	/**
	 * Sends an email using the specified details.
	 * 
	 * @param string $from the "from" address
	 * @param string $to the recipient
	 * @param string $subject the subject of the email
	 * @param string $body the body of the email
	 * @return integer the result of the process
	 */
	public static function send($from, $to, $subject, $body) {
		try {
			// Setup
			$config = \Bedrock\Common\Registry::get('config');
			
			$headers = array('From' => $from,
							'To' => $to,
							'Subject' => $subject,
							'Date' => date("r", time()));
			
			$smtpConfig = array('host' => $config->email->smtp,
								'port' => $config->email->port,
								'auth' => true,
								'username' => $config->email->username,
								'password' => $config->email->password);
		
			$smtp = \Mail::factory('smtp', $smtpConfig);
			
			\Bedrock\Common\Logger::info('Attempting to send an email to "' . $to . '" ...');
			$mail = $smtp->send($to, $headers, $body);
			
			if(\PEAR::isError($mail)) {
				throw new \Bedrock\Common\Email\Exception($mail->getMessage());
			}
		}
		catch(\Bedrock\Common\Email\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw $ex;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\Email\Exception('The email could not be sent.');
		}
	}
Beispiel #3
0
	/**
	 * Initializes the object.
	 */
	public function __construct(\Bedrock\Common\Config $options = null) {
		$this->defaults();
		$this->_config = \Bedrock\Common\Registry::get('config');
		
		if($options instanceof \Bedrock\Common\Config) {
			$this->_properties->unlock($this->_propertiesKey);
			$this->_properties->merge($options);
			$this->_propertiesKey = $this->_properties->lock();
		}
	}
Beispiel #4
0
	/**
	 * Initializes the object.
	 *
	 * @param $database \Bedrock\Model\Database the database object to use
	 */
	public function __construct($database = null) {
		if($database) {
			$this->_database = $database;
		}
		else {
			$this->_database = \Bedrock\Common\Registry::get('database');
		}

		$this->_connection = $this->_database->getConnection();

		parent::__construct();
	}
Beispiel #5
0
	/**
	 * Applies the default delegation queue to the router, setting the router to
	 * first search for a controller within the application's namespace, and
	 * within Bedrock's controller classes.
	 */
	public function defaultDelegationQueue() {
		$config = \Bedrock\Common\Registry::get('config');

        // TODO: Update to properly handle namespace refactored code.
		$this->addToDelegationQueue(array(
				'class' => $config->meta->namespace . '\\Control',
				'path' => $config->root->lib . $config->meta->namespace . DIRECTORY_SEPARATOR . 'Control' . DIRECTORY_SEPARATOR
		));

		$this->addToDelegationQueue(array(
				'class' => 'Bedrock\\Control',
				'path' => $config->root->lib . 'Bedrock' . DIRECTORY_SEPARATOR . 'Control' . DIRECTORY_SEPARATOR
		));
	}
Beispiel #6
0
	protected static function call($function, $params = array()) {
		$config = \Bedrock\Common\Registry::get('config');
		
		switch($config->system->os) {
			case 'darwin':
				\Bedrock\Common\Command\Darwin::$function();
				break;
				
			case 'linux':
				// \Bedrock\Common\Command\Linux::$$function();
				break;
				
			case 'win32':
				// \Bedrock\Common\Command\Win32::$$function();
				break;
		}
	}
Beispiel #7
0
	/**
	 * Attempts to load missing dependencies remotely using the specified
	 * source, or Bedrock's default package sources if a source is not
	 * specified.
	 *
	 * @param string $source a valid Bedrock package source with the required dependencies
	 *
	 * @throws Plugin\Exception if the target save directory isn't writable
	 * @return boolean whether or not the process was successful
	 */
	public static function loadDependencies($source = '') {
		try {
			// Setup
			$result = false;
			$config = \Bedrock\Common\Registry::get('config');

			// Verify library directory is writeable.
			if(!is_writeable($config->root->lib)) {
				throw new \Bedrock\Plugin\Exception('The target save directory "' . $config->root->lib . '" is not writeable, no external dependencies can be loaded.');
			}

			// Verify source is valid.

			// Download/save files.

			// Verify all dependencies were loaded.
			
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
	/**
	 * Retrieves the names for all tables associated with the specified table.
	 *
	 * @param string $tableName the table to find associations with
	 * @return array an array of associated tables and the type of association
	 */
	public static function getAssociatedTableNames($tableName) {
		try {
			// Setup
			$result = array();
			$connection = \Bedrock\Common\Registry::get('database')->getConnection();
			
			// Query for Associations
			$sql = 'SHOW TABLE STATUS WHERE Comment LIKE \'table|%\' AND ' .
					'(Comment LIKE \'%:' . self::sanitize($tableName) . '(%\' OR ' .
					'Comment LIKE \'%,' . self::sanitize($tableName) . '(%\')';
			
			\Bedrock\Common\Logger::info('Querying for associated tables: "' . $sql . '"');
			
			$res = $connection->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
			
			foreach($res as $row) {
				// Parse Association Type
				$mappings = explode(',', substr($row['Comment'], 15));
				$type = '';
				
				foreach($mappings as $mapping) {
					if(substr($mapping, 0, strpos($mapping, '(')) == $tableName) {
						$matches = array();
						preg_match('#\((.*?)\)#', $mapping, $matches);
						$type = $matches[1];
					}
				}
				
				$result[$row['Name']] = $type;
			}
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
	/**
	 * @param string $id the unique identifier to associate with the value
	 * @param mixed $value the value to be stored
	 *
	 * @return void
	 */
	protected function _addToRegistry($id, $value) {
		\Bedrock\Common\Registry::set($id, $value);
	}
Beispiel #10
0
 * Initializes the application environment, setting up an autoload function,
 * include paths, and loads any needed configuration files.
 *
 * @package Bedrock
 * @author Nick Williams
 * @version 1.0.0
 * @created 04/08/2009
 * @updated 04/08/2009
 */

use Bedrock\Common;

// Imports
require_once '../lib/Bedrock.php';
require_once '../lib/Bedrock/Common.php';

try {
	// Initialize Environment
	Common::init('../cfg/application.xml');
	Common\Logger::logEntry();

	// Start Router
	Common\Registry::get('router')->delegate();

	Common\Logger::logExit();
}
catch(Common\Exception $ex) {
	Common\Logger::exception($ex);
	Common\Logger::logExit();
}
Beispiel #11
0
	/**
	 * Initializes the application environment.
	 *
	 * @param string $configPath absolute path to the application's main configuration file
	 * @param string $env the configuration environment to use
	 * @param string $callback an optional callback function to execute uplon completion
	 * @param boolean $session whether or not to start a session
	 */
	public static function init($configPath = '', $env = 'main', $callback = '', $session = true) {
		// Load Configuration
		require_once 'Common/Config.php';
		require_once 'Common/Config/Xml.php';

		if(!is_file($configPath)) {
			header('Location: install/');
		}

		$config = new \Bedrock\Common\Config\Xml($configPath, $env);

		// Setup
		define('ROOT', $config->root->system);

		switch($config->env->os) {
			default:
			case 'unix':
				define('DELIMITER', self::DELIM_UNIX);
				break;

			case 'windows':
				define('DELIMITER', self::DELIM_WIN);
				break;
		}

		// Autoload Function
		spl_autoload_register(function($className) {
			// Imports
			require_once ROOT . '/lib/Bedrock.php';
			require_once ROOT . '/lib/Bedrock/Common.php';
			\Bedrock\Common::autoload($className, ROOT);
		});

		// Register Configuration
		\Bedrock\Common\Registry::set('config', $config);

		// Include Paths
		ini_set('include_path', ini_get('include_path') . DELIMITER .
			ROOT . DELIMITER .
			$config->root->cfg . DELIMITER .
			$config->root->lib . DELIMITER .
			$config->root->pub);

		// Error Reporting/Handling
		eval('error_reporting(' . $config->env->error . ');');
		set_error_handler('\\Bedrock\\Common::error', E_ALL - E_NOTICE);

		// Initialize: Logger
		\Bedrock\Common\Logger::init(\Bedrock\Common\Logger::LEVEL_INFO, $config->meta->title, $config->meta->version->application, $config->meta->status);

		// Add built-in targets that are enabled...
		if($config->logger->targets->system->active) {
			\Bedrock\Common\Logger::addTarget(new \Bedrock\Common\Logger\Target\System(), $config->logger->targets->system->level);
		}

		if($config->logger->targets->file->active) {
			\Bedrock\Common\Logger::addTarget(new \Bedrock\Common\Logger\Target\File($config->root->log . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log'), $config->logger->targets->file->level);
		}

		if($config->logger->targets->firephp->active) {
			\Bedrock\Common\Logger::addTarget(new \Bedrock\Common\Logger\Target\FirePHP(), $config->logger->targets->firephp->level);
		}

		if($config->logger->targets->growl->active) {
			\Bedrock\Common\Logger::addTarget(new \Bedrock\Common\Logger\Target\Growl(array($config->growl->host, $config->growl->password, $config->meta->title)), $config->logger->targets->growl->level);
		}

		// Initialize: Session
		if($session) {
			\Bedrock\Common\Session::start();
		}

		$router = new \Bedrock\Common\Router();
		\Bedrock\Common\Registry::set('router', $router);

		// Execute Callback
		if($callback) {
			call_user_func($callback);
		}
	}
Beispiel #12
0
	/**
	 * Opens a connection to the system logger.
	 *
	 * @param array $args the Growl initialization arguments
	 */
	public function open($args = array()) {
		openlog(\Bedrock\Common\Registry::get('config')->meta->title, LOG_PID | LOG_PERROR, LOG_USER);
	}
Beispiel #13
0
	/**
	 * Queries for all records from the target table that are associated with
	 * the specified record.
	 *
	 * @param \Bedrock\Model\Record $record the record to find associations with
	 * @param string $targetTableName the name of the target table from which to retrieve associated Records
	 * @param array $limit
	 *
	 * @throws \Bedrock\Model\Query\Exception if the query fails
	 * @return \Bedrock\Model\ResultSet the corresponding ResultSet
	 */
	public function associated($record, $targetTableName, $limit = array()) {
		try {
			if($this->_target == self::TARGET_PROCEDURE) {
				throw new \Bedrock\Model\Query\Exception('Stored procedure queries cannot have associated records.');
			}
			
			// Setup
			$result = new \Bedrock\Model\ResultSet();
			$connection = \Bedrock\Common\Registry::get('database')->getConnection();
			$recordTable = $record->getTable();
			$recordTableName = $recordTable->getProperty('name');
			$targetTable = new \Bedrock\Model\Table(array('name' => $targetTableName));
			
			$targetTable->load();
			
			// Verify Table Association
			$mappings = $recordTable->getMappings();
			
			if(array_key_exists($targetTableName, $mappings)) {
				// Query for Associated Records
				switch($mappings[$targetTableName]) {
					default:
					case \Bedrock\Model\Table::MAP_TYPE_ONE_ONE:
					case \Bedrock\Model\Table::MAP_TYPE_ONE_MANY:
						$foreignKeys = $targetTable->getForeignKeys();
						$query = \Bedrock\Model\Query::from($targetTableName)->where($foreignKeys[$recordTableName]->name, '=', $record->{$record->getPrimaryKey()});
						
						if(count($limit)) {
							$query = $query->limit($limit['start'], $limit['count']);
						}
						
						$result = $query->execute();
						
						break;
						
					case \Bedrock\Model\Table::MAP_TYPE_MANY_ONE:
						$foreignKeys = $recordTable->getForeignKeys();
						$query = \Bedrock\Model\Query::from($targetTableName)->where($targetTable->getPrimaryKey()->name, '=', $record->{$foreignKeys[$targetTableName]->name});
						
						if(count($limit)) {
							$query = $query->limit($limit['start'], $limit['count']);
						}
						
						$result = $query->execute();
						
						break;
						
					case \Bedrock\Model\Table::MAP_TYPE_MANY_MANY:
						$mappingTableName = \Bedrock\Model\Utilities::getMappingTableName($recordTableName, $targetTableName);
						$query = 'SELECT t.* FROM ' . $targetTableName . ' t LEFT JOIN ' . $mappingTableName . ' m ON t.' . $targetTable->getPrimaryKey()->name . ' = m.' . $targetTable->getPrimaryKey()->name . '_' . $targetTableName . ' WHERE m.' . $recordTable->getPrimaryKey()->name . '_' . $recordTableName . ' = :recordPrimaryKey';
						
						if(count($limit)) {
							$query .= ' LIMIT ' . $limit['start'] . ', ' . $limit['count'];
						}
						
						$statement = $connection->prepare($query);
						$statement->execute(array(':recordPrimaryKey' => $record->{$record->getPrimaryKey()}));
						$results = $statement->fetchAll(\PDO::FETCH_ASSOC);
						$records = array();
						
						if($results) {
							foreach($results as $result) {
								$records[] = new \Bedrock\Model\Record($targetTableName, $result);
							}
						}
						
						$result = new \Bedrock\Model\ResultSet($records);
						$result->setCountAll(count($records));
						break;
				}
			}
			return $result;
		}
		catch(\PDOException $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Model\Query\Exception('There was a problem with the database connection, associated records could not be retrieved.');
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Model\Query\Exception('Could not retrieve associated records for the specified Record object.');
		}
	}
	/**
	 * Tears down the fixture, for example, closes a network connection.
	 * This method is called after a test is executed.
	 *
	 * @return void
	 */
	protected function tearDown() {
		\Bedrock\Common\Registry::clear();
	}
Beispiel #15
0
	/**
	 * Executes the specified method with the specified parameters.
	 * 
	 * @param string $method a valid ImageMagick command-line utility
	 * @param array $params an array of key-value pairs to use as parameters
	 */
	public static function exec($method, $params) {
		try {
			// Setup
			$command = '';

			if(!self::$_methods[$method]) {
				throw new \Bedrock\Common\Image\Exception('Unknown method "' . $method . '" specified.');
			}

			// Load Paths
			if(self::$_methods === null) {
				$root = \Bedrock\Common\Registry::get('config')->root->image;
				self::$_methods = array(
					'animate' => $root . 'animate',
					'compare' => $root . 'compare',
					'composite' => $root . 'composite',
					'conjure' => $root . 'conjure',
					'convert' => $root . 'convert',
					'display' => $root . 'display',
					'identify' => $root . 'identify',
					'import' => $root . 'import',
					'mogrify' => $root . 'mogrify',
					'montage' => $root . 'montage',
					'stream' => $root . 'stream'
				);
			}

			// Build Command
			$command = self::$_methods[$method];

			foreach($params as $key => $value) {
				if(is_numeric($key)) {
					$command .= ' ' . $value;
				}
				else {
					$command .= ' -' . $key . ' ' . $value;
				}
			}

			$command = escapeshellcmd($command);

			\Bedrock\Common\Logger::info('Executing command: ' . $command);

			exec($command);
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\Image\Exception('The method "' . $method . '" could not be executed.');
		}
	}