Exemple #1
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.');
		}
	}
	/**
	 * Shuts down the system.
	 */
	public static function shutdown() {
		try {
			self::exec('sudo -S halt');
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
Exemple #3
0
	/**
	 * Reverts a sanitized value after being retrieved from the database.
	 *
	 * @param mixed $value the value being desanitized
	 *
	 * @throws Model\Exception if the specified value could not be dezanitized
	 * @return mixed the desanitized value
	 */
	public static function desanitize($value) {
		try {
			return stripslashes($value);
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Model\Exception('There was a problem desanitizing the specified data.');
		}
	}
	/**
	 * Simplifies a string, replacing spaces with underscores, removing
	 * punctuation, etc.
	 *
	 * @param string $string the string to simplify
	 * @return string the simplified string
	 */
	public static function simplify($string) {
		try {
			// Setup
			$result = $string;

			// Simplify String
			$result = trim($result);
			$result = str_replace(' ', '_', $result);
			$result = strtolower($result);
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
	/**
	 * Returns the current ResultSet as an array.
	 *
	 * @return array an array of rows/values
	 */
	public function toArray() {
		try {
			// Setup
			$result = array();
			
			if($this->count()) {
				foreach($this->_records as $record) {
					$result[] = $record->toArray();
				}
			}
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Model\ResultSet\Exception('There was a problem converting the ResultSet to an array.');
		}
	}
	/**
	 * Outputs the data to the browser.
	 */
	public function printData() {
		try {
			switch(get_class($this)) {
				default:
					header('Content-Type: text/plain; charset=ISO-8859-1');
					break;
					
				case 'Bedrock\\Common\\DataFormat\\XML':
					header('Content-Type: application/xml; charset=ISO-8859-1');
					echo '<?xml version="1.0" encoding="ISO-8859-1"?>' . \Bedrock\Common::TXT_NEWLINE;
					break;
			}
			
			echo $this->toString();
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
Exemple #7
0
	/**
	 * Returns the current data as an CSV string.
	 * 
	 * @return string the data assembled into an CSV string
	 */
	public function toString() {
		try {
			// Setup
			$result = '';
			
			foreach($this->_data as $key => $value) {
				if(get_class($value) == 'Bedrock\\Common\\DataFormat\\CSV') {
					$result .= $value->toString();
				}
				else {
					$result .= $value;
				}
			}
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\DataFormat\Exception('A problem was encountered while attempting to generate a CSV string.');
		}
	}
Exemple #8
0
 /**
  * Converts the specified value to the desired unit of measure (for data).
  * 
  * @param float $value the numeric value to convert
  * @param string $sourceUnits the numeric value's current units
  * @param string $destUnits the desired units to convert to
  * @return float the converted value
  */
 public function convertDataUnits($value, $sourceUnits, $destUnits) {
     try {
         $units['bytes'] = 0;
         $units['kilobytes'] = 1;
         $units['megabytes'] = 2;
         $units['gigabytes'] = 3;
         $units['terabytes'] = 4;
         $units['petabytes'] = 5;
         
         $exp = $units[$sourceUnits] - $units[$destUnits];
         
         $result = $value*pow(1024, $exp);
         return $result;
     }
     catch(\Exception $ex) {
         \Bedrock\Common\Logger::exception($ex);
     }
 }
	/**
	 * Returns extended information of a given user, specified by ID or screen
	 * name as per the required id parameter.  The author's most recent status
	 * will be returned inline.
	 *
	 * Formats: xml, json, rss, atom
	 * HTTP Method: GET
	 * Requires Authentication: false, unless the user is protected
	 * API Rate Limited: 1 call per request
	 *
	 * @param mixed $id the ID or screen name of a user
	 * @param integer $userId specifies the ID of the user to return (helpful for disambiguating when a valid user ID is also a valid screen name)
	 * @param <type> $screenName specifies the screen name of the user to return (helpful for disambiguating when a valid screen name is also a user ID)
	 * @param string $format the format with which the response should use
	 * @return string the formatted response
	 */
	protected function usersShow($id = null, $userId = null, $screenName = null, $format = 'xml') {
		try {
			// Setup
			$url = $this->_searchUrl . 'users/show';
			$params = array();

			if(!empty($id)) {
				$url .= '/' . $id . '.' . $format;
			}
			elseif(!empty($userId)) {
				$url .= '.' . $format;
				$params['user_id'] = $userId;
			}
			elseif(!empty($screenName)) {
				$url .= '.' . $format;
				$params['screen_name'] = $screenName;
			}
			else {
				throw new \Bedrock\Common\Service\Exception('No user identifier specified, cannot complete query.');
			}

			$result = self::exec($url, 'GET', $this->_username, $this->_password, $params);
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\Service\Exception('A problem was encountered while attempting to make the request "users/show".');
		}
	}
Exemple #10
0
	/**
	 * Renders the specified property or input field.
	 *
	 * @param string $property the property to render
	 */
	public function render($property = 'input') {
		try {
			// Setup
			$namespace = '';
			$type = '';
			$html = '';
			
			if($property != 'input') {
				parent::render($property);
			}
			else {
				list($namespace, $type) = explode(':', $this->__get('type'));
				
				if($namespace != 'std') {
					throw new \Bedrock\Common\Form\Exception('The specified type namespace "' . $namespace . '" does not match the field instance type.');
				}
				
				switch($type) {
					// =========================================================
					// Type: Unsupported
					// =========================================================
					default:
						throw new \Bedrock\Common\Form\Exception('The specified field type "' . $type . '" is not a recognized field type.');
						break;
						
					// =========================================================
					// Type: Basic Input Types
					// =========================================================
					case 'text':
					case 'password':
					case 'hidden':
					case 'checkbox':
					case 'radio':
					case 'button':
					case 'submit':
					case 'reset':
						$html = '<input type="' . $type .
									'" name="' . $this->__get('name') .
									'" id="' . $this->__get('id') . '" ' .
									$this->attributeToString('value', $this->_value) .
									$this->attributeToString('tabindex', $this->__get('tabindex')) .
									$this->attributeToString('size', $this->__get('size')) .
									$this->attributeToString('maxlength', $this->__get('maxlength')) .
									$this->attributeToString('class', $this->__get('class')) .
									$this->attributeToString('style', $this->__get('style')) . 
									$this->attributeToString('disabled', ($this->__get('disabled') ? 'disabled' : '')) . '/>' . "\n";
						
						if($type == 'checkbox' || $type == 'radio') {
							$html .= '<label for="' . $this->__get('id') . '">' . $this->__get('text') . '</label>' . "\n";
						}
						break;
						
					// =========================================================
					// Type: New Password (Passwor Field + Confirmation Field)
					// =========================================================
					case 'newpassword':
						$html = '<input type="password" name="' . $this->__get('name') . '_a' .
									'" id="' . $this->__get('id') . '_a" ' .
									$this->attributeToString('value', $this->_value) .
									$this->attributeToString('tabindex', $this->__get('tabindex')) .
									$this->attributeToString('size', $this->__get('size')) .
									$this->attributeToString('maxlength', $this->__get('maxlength')) .
									$this->attributeToString('class', $this->__get('class')) .
									$this->attributeToString('style', $this->__get('style')) . 
									$this->attributeToString('disabled', ($this->__get('disabled') ? 'disabled' : '')) . '/>' . "\n";
						
						$html .= '<br />';
						
						$html .= '<input type="password" name="' . $this->__get('name') . '_b' .
									'" id="' . $this->__get('id') . '_b" ' .
									$this->attributeToString('value', $this->_value) .
									$this->attributeToString('tabindex', $this->__get('tabindex') + 1) .
									$this->attributeToString('size', $this->__get('size')) .
									$this->attributeToString('maxlength', $this->__get('maxlength')) .
									$this->attributeToString('class', $this->__get('class')) .
									$this->attributeToString('style', $this->__get('style')) . 
									$this->attributeToString('disabled', ($this->__get('disabled') ? 'disabled' : '')) . '/>' . "\n";
						break;
						
					// =========================================================
					// Type: Textarea Box
					// =========================================================
					case 'textarea':
						$html = '<textarea name="' . $this->__get('name') . '" id="' . $this->__get('id') . '" >' . $this->_value . '</textarea>' . "\n";
						break;
						
					// =========================================================
					// Type: File Selection
					// =========================================================
					case 'file':
						$html = '<input type="file" name="' . $this->__get('name') .
									'" id="' . $this->__get('id') . '" ' .
									$this->attributeToString('value', $this->_value) .
									$this->attributeToString('tabindex', $this->__get('tabindex')) .
									$this->attributeToString('class', $this->__get('class')) .
									$this->attributeToString('style', $this->__get('style')) .
									$this->attributeToString('accept', $this->__get('accept')) .
									$this->attributeToString('disabled', ($this->__get('disabled') ? 'disabled' : '')) . '/>' . "\n";
						break;
						
					// =========================================================
					// Type: Select Dropdown
					// =========================================================
					case 'select':
						$html = '<select name="' . $this->__get('name') .
									'" id="' . $this->__get('id') . '" ' .
									$this->attributeToString('tabindex', $this->__get('tabindex')) .
									$this->attributeToString('size', $this->__get('size')) .
									$this->attributeToString('multiple', ($this->__get('multiple') ? 'multiple' : '')) .
									$this->attributeToString('class', $this->__get('class')) .
									$this->attributeToString('style', $this->__get('style')) . 
									$this->attributeToString('disabled', ($this->__get('disabled') ? 'disabled' : '')) . '>' . "\n";
									
						if(count($this->__get('options'))) {
							foreach($this->__get('options') as $option) {
								$html .= '<option value="' . $option->value . '"' . ($this->_value == $option->value ? ' selected="selected"' : '') . '>' . $option->label . '</option>' . "\n";
							}
						}
									
						$html .= '</select>' . "\n";
						
						break;
						
					// =========================================================
					// Type: Multi-Checkbox List
					// =========================================================
					case 'multicheck':
						if(count($this->__get('options'))) {
							foreach($this->__get('options') as $key => $option) {
								$html .= '<input type="checkbox" name="' . $this->__get('name') .
											'" id="' . $this->__get('id') . '_' . $key . '" ' .
											'" value="' . $option->value . '" ' .
											$this->attributeToString('checked', in_array($option->value, explode(',', $this->_value)) ? 'checked' : '') .
											$this->attributeToString('class', $this->__get('class')) .
											$this->attributeToString('style', $this->__get('style')) .
											$this->attributeToString('disabled', ($this->__get('disabled') ? 'disabled' : '')) . '/>' .
											'<label for="' . $this->__get('id') . '_' . $key . '">' . $option->label . '</label><br />' . "\n";
							}
						}
						break;
						
					// =========================================================
					// Type: Multi-Radio List
					// =========================================================
					case 'multiradio':
						if(count($this->__get('options'))) {
							foreach($this->__get('options') as $key => $option) {
								$html .= '<input type="radio" name="' . $this->__get('name') .
											'" id="' . $this->__get('id') . '_' . $key . '" ' .
											'" value="' . $option->value . '" ' .
											$this->attributeToString('checked', $option->value == $this->_value ? 'checked' : '') .
											$this->attributeToString('class', $this->__get('class')) .
											$this->attributeToString('style', $this->__get('style')) .
											$this->attributeToString('disabled', ($this->__get('disabled') ? 'disabled' : '')) . '/>' .
											'<label for="' . $this->__get('id') . '_' . $key . '">' . $option->label . '</label><br />' . "\n";
							}
						}
						break;
				}
				
				echo $html;
			}
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
Exemple #11
0
	/**
	 * Returns the current data as a YAML string.
	 * 
	 * @param string $indent an optional indent string to prepend to each line
	 * @return string the data assembled into a YAML string
	 */
	public function toString($indent = '') {
		try {
			// Setup
			$result = '';
			$t = \Bedrock\Common::TXT_TAB;
			$n = \Bedrock\Common::TXT_NEWLINE;
			
			// Build YAML
			if($indent == '') {
				$result .= '---' . $n;
			}
			
			foreach($this->_data as $entry) {
				foreach($entry as $key => $value) {
					if(get_class($value) == 'Bedrock\\Common\\DataFormat\\YAML') {
						$result .=
							$indent . $key . ':' . $n . 
							$value->toString($indent . $t);
					}
					else {
						$result .= $indent . $key . ': ' . $value . $n;
					}
				}
			}
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\DataFormat\Exception('A problem was encountered while attempting to generate a YAML string.');
		}
	}
Exemple #12
0
	/**
	 * Sets the protocol to use for authentication.
	 *
	 * @param string $protocol a valid authentication protocol
	 */
	public static function setProtocol($protocol) {
		try {
			\Bedrock\Common\Logger::info('Protocol set to: ' . $protocol);
			self::$_protocol = $protocol;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\Auth\Exception('The protocol could not be set.');
		}
	}
Exemple #13
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();
}
	/**
	 * 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);
		}
	}
Exemple #15
0
	/**
	 * Returns the current data as a JSON string.
	 * 
	 * @param string $indent an optional indent string to prepend to each line
	 * @return string the data assembled into a JSON string
	 */
	public function toString($indent = '', $isArray = false) {
		try {
			// Setup
			$result = '';
			$t = \Bedrock\Common::TXT_TAB;
			$n = \Bedrock\Common::TXT_NEWLINE;
			
			// Build JSON
			if($indent == '') {
				$ind = $t;
				$result .= '{' . $n;
			}
			else {
				$ind = $indent . $indent;
				$result .= $indent . '{' . $n;
			}
			
			foreach($this->_data as $entry) {
				foreach($entry as $key => $value) {
					if(get_class($value) == 'Bedrock\\Common\\DataFormat\\JSON') {
						$result .=
							$ind . $key . ':' . $n . 
							$value->toString($indent . $t) . ',';
					}
					elseif(is_object($value) && get_class($value) == 'Bedrock\\Model\\ResultSet') {
						$result .= $ind . $key . ': [' . $n;
						
						foreach($value as $record) {
							$result .= $ind . $t . '{' . $record->getPrimaryKey() . ': ' . $record->{$record->getPrimaryKey()} . ', cell: [';
							
							foreach($record as $column => $val) {
								$result .= $this->formatValue($val) . ', ';
							}
							
							$result = substr($result, 0, strlen($result)-2) . ']';
							
							$result .= '},' . $n;
						}
						
						$result = substr($result, 0, strlen($result)-2) . $n;
						$result .= $ind . ']' . $n;
					}
					else {
						$result .= $ind . $key . ': ' . $this->formatValue($value) . ',' . $n;
					}
				}
			}
			
			$result = substr($result, 0, strlen($result)-2) . $n;
			
			if($indent == '') {
				$result .= '}' . $n;
			}
			else {
				$result .= $indent . '}' . $n;
			}
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\DataFormat\Exception('A problem was encountered while attempting to generate a JSON string.');
		}
	}
Exemple #16
0
	/**
	 * Prints the specified attribute if a value is specified.
	 *
	 * @param string $attribute the attribute to print
	 * @param string $value the value to associate with the attribute
	 *
	 * @return string the resulting attribute string
	 */
	protected function attributeToString($attribute, $value) {
		try {
			// Setup
			$result = '';
			
			if($value != '') {
				$result = $attribute . '="' . $value . '" ';
			}
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
Exemple #17
0
	/**
	 * Stores the specified switch block with the current instance.
	 *
	 * @param mixed $switch the switch data to store
	 */
	private function storeSwitch($switch) {
		try {
			// Setup
			$data = array();
			
			// =================================================================
			// Source Data: SimpleXMLElement
			// =================================================================
			if($switch instanceof \SimpleXMLElement) {
				// Setup
				$data = array(
					'depends' => $switch->attributes()->depends,
					'cases' => array()
				);
				
				// Store Cases
				foreach($switch->case as $case) {
					foreach($case->field as $field) {
						// Store Field
						$this->storeField($field);
						
						// Store Case Details
						$data['cases'][] = array(
							'target' => $case->attributes()->target,
							'field' => $field->attributes()->id
						);
					}
				}
			}
			
			// =================================================================
			// Source Data: Config
			// =================================================================
			elseif($switch instanceof \Bedrock\Common\Config) {
				// Setup
				$data = array(
					'depends' => $switch->depends,
					'cases' => array()
				);
				
				// Store Cases
				foreach($switch->cases as $case) {
					foreach($case->fields as $field) {
						// Store Field
						$this->storeField($field);
						
						// Store Case Details
						$data['cases'][] = array(
							'target' => $case->target,
							'field' => $field->id
						);
					}
				}
			}
			
			// =================================================================
			// Source Data: Array
			// =================================================================
			elseif(is_array($switch)) {
				// Setup
				$data = array(
					'depends' => $switch['depends'],
					'cases' => array()
				);
				
				// Store Cases
				foreach($switch['cases'] as $case) {
					foreach($case['fields'] as $field) {
						// Store Field
						$this->storeField($field);
						
						// Store Case Details
						$data['cases'][] = array(
							'target' => $case->target,
							'field' => $field->id
						);
					}
				}
			}
			
			// =================================================================
			// Source Data: Unsupported
			// =================================================================
			else {
				throw new \Bedrock\Common\Form\Exception('Invalid data provided, switch block could not be stored.');
			}
			
			$this->_switches[] = new \Bedrock\Common\Config($data, true);
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
	/**
	 * Exports all table data from the database to the specified location.
	 *
	 * @param integer $exportType the data type to use
	 * @param string $exportLocation the location to which to export
	 */
	public function exportTableData($exportLocation, $exportType) {
		try {
			// Load Tables
			$this->load();
			
			\Bedrock\Common\Logger::info('Exporting all table data for database "' . $this->_name . '" to location "' . $exportLocation . '" ...');
			
			// Export Data
			foreach($this->_tables as $name => $table) {
				\Bedrock\Common\Logger::info('Exporting table "' . $name . '" ...');
				$table->exportData($exportLocation, $exportType);
			}
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
Exemple #19
0
	/**
	 * Encodes the specified data into a string.
	 *
	 * @param mixed $data the data to encode
	 * @return string the encoded data
	 */
	public static function encode($data, $root = true, $prepend = '', $strictTyping = false) {
		try {
			// Setup
			$result = '';
			$valueIndent = '';

			// Mark start of document.
			if($root) {
				$result = '---' . \Bedrock\Common::TXT_NEWLINE;
			}

			if($data instanceof \Bedrock\Common\Data) {
				$data = $data->toArray();
			}

			// Build YAML
			if(is_array($data) || $data instanceof \Bedrock\Common\Data) {
				$keys = array_keys($data);
				$length = 0;

				foreach($keys as $key) {
					if(strlen($key) > $length) {
						$length = strlen($key);
					}
				}

				$valueIndent = ''; // @todo finish this

				foreach($data as $name => $value) {
					if(is_numeric($name)) {
						// Type: List
						if(is_array($value) || $value instanceof \Bedrock\Common\Data) {
							$result .= substr($prepend, 0, -2) . '- ' . substr(self::encode($value, false, $prepend, $strictTyping), strlen($prepend)) . \Bedrock\Common::TXT_NEWLINE;
						}
						// Type: Hash Member
						else {
							$result .= self::formatValue($value, $strictTyping) . ', ';
							//$result .= substr($prepend, -2) . '- ' . $value . \Bedrock\Common::TXT_NEWLINE;
						}
					}
					else {
						// Type: Complex Value
						if(is_array($value) || $value instanceof \Bedrock\Common\Data) {
							$isHash = false;
							$hasArray = false;
							$isAssoc = false;

							foreach($value as $key => $item) {
								if(!is_numeric($key)) {
									$isAssoc = true;
								}

								if(is_array($item)) {
									$hasArray = true;
								}

								if(!$isAssoc && !$hasArray) {
									$isHash = true;
									break;
								}
							}

							// Type: Hash Container
							if($isHash) {
								$result .= $prepend . $name . ': ' . '[' . substr(self::encode($value, false, $prepend . self::INDENT_CHAR, $strictTyping), 0, -2) . ']' . \Bedrock\Common::TXT_NEWLINE;
							}
							// Type: List Container
							else {
								$result .= $prepend . $name . ': ' . \Bedrock\Common::TXT_NEWLINE . self::encode($value, false, $prepend . self::INDENT_CHAR, $strictTyping) . \Bedrock\Common::TXT_NEWLINE;
							}
						}
						// Type: Primitive Value
						else {
							$result .= $prepend . $name . ': ' . self::formatValue($value, $strictTyping) . \Bedrock\Common::TXT_NEWLINE;
						}
					}
				}
			}
			else {
				throw new \Bedrock\Common\Data\Exception('The specified data is not in a supported format, please provide a valid array or Data descendant.');
			}

			// Mark end of document.
			if($root) {
				$result = str_replace(\Bedrock\Common::TXT_NEWLINE . \Bedrock\Common::TXT_NEWLINE . \Bedrock\Common::TXT_NEWLINE, /*\Bedrock\Common::TXT_NEWLINE .*/ \Bedrock\Common::TXT_NEWLINE, $result);
				$result = str_replace(\Bedrock\Common::TXT_NEWLINE . \Bedrock\Common::TXT_NEWLINE, \Bedrock\Common::TXT_NEWLINE, $result);

				$result .= '...';
			}
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\Data\Exception('Could not encode the specified data into a string: ' . $ex->getTrace());
		}
	}
	/**
	 * Clears all currently stored errors.
	 */
	public function clearErrors() {
		try {
			$this->_errors = array();
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
	/**
	 * Unlocks the current namespace, allowing for changes to be made.
	 */
	public function unlock() {
		try {
			$this->_locked = false;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
Exemple #22
0
	/**
	 * Converts the specified value into a string usable in SQL queries.
	 *
	 * @param mixed $value the value to convert
	 * @return string the resulting string
	 */
	public static function valueToString($value) {
		try {
			// Setup
			$result = '';
			
			switch(gettype($value)) {
				case 'array':
					foreach($value as $element) {
						$result .= self::valueToString($element) . ', ';
					}
					
					$result = substr($result, 0, strlen($result)-2);
					break;
					
				case 'boolean':
					$result = $value ? '1' : '0';
					break;
					
				case 'double':
				case 'integer':
					$result = $value + 0;
					break;
					
				case 'NULL':
					$result = 'null';
					break;
					
				default:
				case 'string':
					$result = '\'' . self::sanitize($value) . '\'';
					break;
			}
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
Exemple #23
0
	/**
	 * Retrieves all Records in the specified table associated with the current
	 * Record.
	 *
	 * @param string $tableName the name of the table to use
	 * @return \Bedrock\Model\ResultSet any associated records in the table
	 */
	public function associated($tableName, $limit = array()) {
		try {
			$result = \Bedrock\Model\Query::associated($this, $tableName, $limit);
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Model\Record\Exception('A problem was encountered while checking for associated records.');
		}
	}
	/**
	 * Sets or gets the current session ID. If an ID is specified, the session
	 * ID will be set to that value. If no ID is specified, the current ID will
	 * be returned.
	 *
	 * @param string $newSessionId a new session ID to use, leave blank to retrieve the current ID
	 *
	 * @throws \Bedrock\Common\Session\Exception if a session ID cannot be set and/or retrieved
	 * @return string the current session ID
	 */
	public static function id($newSessionId = NULL) {
		try {
			if(!self::started()) {
				throw new \Bedrock\Common\Session\Exception('A session ID could not be retrieved, no session has been started.');
			}
			return session_id($newSessionId);
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\Session\Exception('The session ID could not be set and/or retrieved.');
		}
	}
Exemple #25
0
	/**
	 * Retrieves the current server's operating system.
	 *
	 * @return string the current server's operating system
	 */
	public function getOperatingSystem() {
		try {
			// Setup
			$result = '';
			$cmd = 'sw_vers';
			
			// Execute Command/Parse Results
			self::execute($cmd, $output);
			
			$name = explode(':', $output[0]);
			$name = trim($name[1]);
			
			$version = explode(':', $output[1]);
			$version = trim($version[1]);
			
			$result = $name . ' (' . $version . ')';
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
Exemple #26
0
	/**
	 * Converts the supplied array into a valid JSON string.
	 *
	 * @param array $array the array to convert
	 * @param integer $format whether or not to apply indentation/newlines
	 * @param string $indentPrefix a string to prefix to every new line for nested calls
	 * @return string the assembled JSON string
	 */
	public static function encode($array, $format = self::FORMAT_INDENT, $indentPrefix = '') {
		try {
			// Setup
			$t = \Bedrock\Common::TXT_TAB;
			$n = \Bedrock\Common::TXT_NEWLINE;
			$json = '';
			
			if($format === self::FORMAT_NONE) {
				$t = '';
				$n = '';
			}
			
			// Build JSON String
			if(count($array)) {
				if(self::isAssoc($array)) {
					$json .=  '{' . $n;
					
					foreach($array as $key => $value) {
						if(gettype($value) == 'array') {
							if($format === self::FORMAT_ROWS && $key == 'rows') {
								$json .= $indentPrefix . $t . $key  . ': ' . self::encode($value, self::FORMAT_ROW) . ', ' . $n;
							}
							else {
								$json .= $indentPrefix . $t . $key . ': ' . self::encode($value, $format, $indentPrefix . $t) . ', ' . $n;
							}
						}
						else {
							$json .= $indentPrefix . $t . $key . ': ' . self::formatValue($value) . ', ' . $n;
						}
					}
					
					if(!$n) {
						$json = substr($json, 0, strlen($json)-2);
					}
					else {
						$json = substr($json, 0, strlen($json)-3) . $n;
					}
					
					$json .= $indentPrefix . '}';
					
				}
				else {
					$json .= '[' . $n;
					
					foreach($array as $key => $value) {
						if(gettype($value) == 'array') {
							if($format === self::FORMAT_ROW) {
								$json .= $indentPrefix . $t . self::encode($value, self::FORMAT_NONE) . ', ' . $n;
							}
							else {
								$json .= $indentPrefix . $t . self::encode($value, $format, $indentPrefix . $t) . ', ' . $n;
							}
						}
						else {
							$json .= $indentPrefix . $t . self::formatValue($value) . ', ' . $n;
						}
					}
					
					if(!$n) {
						$json = substr($json, 0, strlen($json)-2);
					}
					else {
						$json = substr($json, 0, strlen($json)-3) . $n;
					}
					
					
					$json .= $indentPrefix . ']';
				}
			}
			return $json;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\Exception('A problem was encountered while attempting to encode the data to JSON.');
		}
	}
Exemple #27
0
	/**
	 * Sends an alert to the user.
	 *
	 * @param string $message a message for the alert
	 * @param string $title an optional title for the alert
	 * @param string $type the type of alert to send
	 */
	public static function alert($message, $title = '', $type = \Bedrock\Common\Alert::TYPE_BASE) {
		try {
			self::getInstance()->addAlert(array('message' => $message, 'title' => $title, 'type' => $type));
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
Exemple #28
0
	/**
	 * Processes a successful authentication request.
	 */
	public function authSuccess() {
		try {
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Common\Auth\Exception('Authentication was successful, but the response could not be processed.');
		}
	}
Exemple #29
0
	/**
	 * Validates the current form and returns the result of the validation process.
	 *
	 * @return boolean whether or not the form passed validation
	 */
	public function validate() {
		try {
			// Setup
			$result = false;
			
			// Validate the Form
			
			return $result;
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
		}
	}
Exemple #30
0
	/**
	 * Exports the table's data to the specified location using the specified
	 * format.
	 *
	 * @param string $exportLocation the file to which exported data will be saved
	 * @param integer $exportType the export format to use
	 */
	public function exportData($exportLocation, $exportType = \Bedrock\Model::FORMAT_SQL) {
		try {
			\Bedrock\Common\Logger::info('Exporting data in table "' . $this->_name . '" as ' . strtoupper(self::formatToString($exportType)) . '...');
			$fileContents = $this->dataToString($exportType);
			self::writeFile($exportLocation, $fileContents);
		}
		catch(\Exception $ex) {
			\Bedrock\Common\Logger::exception($ex);
			throw new \Bedrock\Model\Exception('Data export failed.');
		}
	}