Esempio n. 1
0
 public static function checkPassword($entitySignature, $loginKey, $passwdKey, $login, $passwd)
 {
     $tag = "Login::checkPassword()";
     Log::notice("{$tag}: <{$login}>");
     try {
         $blueprint = BlueprintReader::read($entitySignature);
         $authTable = $blueprint->getKey();
         $passwdField = $blueprint->get($passwdKey);
         $encType = $passwdField->getEncType();
         if ($encType != "plain") {
             $passwd = hash($encType, $passwd);
         }
     } catch (Exception $e) {
         Log::error("{$tag}: " . $e->getMessage());
         return false;
     }
     $query = "SELECT {$passwdKey} FROM {$authTable} WHERE {$loginKey}='{$login}'";
     $sql = new DatabaseQuery($query);
     try {
         $sql->doQuery();
         if ($sql->get_num_rows() == 0) {
             Log::notice("{$tag}: Login not found.");
             return false;
         } else {
             if ($sql->get_num_rows() == 1) {
                 $row = $sql->get_next_row();
                 $_passwd = $row->{$passwdKey};
                 if ($_passwd == $passwd) {
                     Log::notice("{$tag}: Password Correct");
                     return true;
                 } else {
                     Log::notice("{$tag}: Password INCORRECT");
                     return false;
                 }
             } else {
                 if ($sql->get_num_rows() > 1) {
                     Log::warning("{$tag}: Multiple matches for login.");
                     return false;
                 }
             }
         }
     } catch (Exception $e) {
         Log::error("{$tag}: " . $e->getMessage());
         return false;
     }
 }
 public static function getString($blueprint, $field, $id)
 {
     $tag = "Binary::getString()";
     Log::debug("{$tag}: {$blueprint}, {$field}, {$id}");
     $query = "SELECT {$field} FROM {$blueprint} WHERE id={$id}";
     $sql = new DatabaseQuery($query);
     try {
         $sql->doQuery();
         if ($sql->get_num_rows() == 1) {
             $row = $sql->get_next_row();
             $binaryString = $row->{$field};
             return $binaryString;
         } else {
             Log::warning("{$tag}: {$blueprint}.{$field}.{$id} not found");
             throw new Exception("{$tag}: {$blueprint}.{$field}.{$id} not found");
         }
     } catch (Exception $e) {
         Log::error("{$tag}: [{$sql->err_code}] {$sql->err_message}");
         throw $e;
     }
 }
	public function render()
	{
		$tag = "FormDrafter: render()";
		Log::debug("$tag");
		
		// convenience pointers
		$id = $this->id;
		$entityId = $this->entityId;
		$entityBP = $this->entityBlueprint;
		$formBP = $this->formBlueprint;
		$fields = $this->formFields;
		$params = $this->params;
		
		// encode params for inclusion in html
		$encodedParams = ParamEncoder::encode($params);
		
		// translate buttonPlacement into html element
		$buttonContainer = "tfoot";
		if( array_key_exists("buttonPlacement", $params) )
		{
			if($params["buttonPlacement"] == "thead")
				$buttonContainer = "thead";
			else
				$buttonContainer = "tfoot";
		}
		
		// turn on output buffering
		@ob_end_flush();
		ob_start();
		
		?>
		<div class="bp-draft-rendering" id="<?= $id ?>" type="form" renderer="FormDrafter" entitySignature="<?= $entityBP->signature(); ?>" formSignature="<?= ($formBP) ? $formBP->signature() : ""; ?>" entityId="<?= $entityId ?>" params="<?= $encodedParams ?>">
			<form class="bp-form" method="POST" <?= (array_key_exists("action", $params)) ? "action='" . $params["action"] . "'" : "" ?>>
				<table class="bp-form-table">
					<?
					if( array_key_exists("buttons", $params) )
					{
						echo "<" . $buttonContainer . ">"; // OPEN: <thead> or <tfoot>
							?>
							<tr>
								<td colspan="2" align="<?= $params["buttonAlignment"] ?>" class="bp-form-buttons">
									<?
									$buttonKeys = array_keys($params["buttons"]);
									foreach($buttonKeys as $b)
									{
										?>
										<input type="button" class="bp-form-button" value="<?= $b ?>" onClick="<?= $params["buttons"]["$b"] ?>" />
										<?
									}
									?>
								</td>
							</tr>
							<?
						echo "</" . $buttonContainer. ">";	// CLOSE: </thead> or </tfoot>
					}
					?>
					<tbody>
						<?
						foreach($fields as $f)
						{
							$key = $f->getKey();
							$entityField = $entityBP->get($key);
							
							if($f->display != "hidden")
							{
								?>
								<tr>
									<td class="bp-form-label"><?= $f->displayName; ?></td>
									<td class="bp-form-input">
										<?
										if(!$entityField->isForeignKey())
										{
											switch($f->dataType)
											{
												case "string":
													if($entityField->getEncType() == "plain")
													{
														?><input type="text" name="<?= $key ?>" value="<?= $f->value; ?>" class="<?= ($f->err) ? "bp-validation-error" : "" ?>" <?= ($f->err) ? "title='" . $f->err . "'" : "" ?> /><?
													}
													else
													{
														?>
														<input type="password" name="<?= $key ?>" value="********" class="<?= ($f->err) ? "bp-validation-error" : "" ?>" <?= ($f->err) ? "title='" . $f->err . "'" : "" ?> disabled="true" size="10" />&nbsp;
														<button class="bp-form-encoded-clear" href="<?= $key ?>">Edit</button>
														<?
													}
													break;
												case "text":
													?><textarea name="<?= $key ?>" class="<?= ($f->err) ? "bp-validation-error" : "" ?>" <?= ($f->err) ? "title='" . $f->err . "'" : "" ?>><?= $f->value; ?></textarea><?
													break;
												case "int":
												case "decimal":
													?><input type="text" name="<?= $key ?>" value="<?= $f->value ?>" class="<?= ($f->err) ? "bp-validation-error" : "" ?>" /><?
													break;
												case "date":
													?><input type="text" name="<?= $key ?>" value="<?= $f->value ?>" class="bp-form-input-date <?= ($f->err) ? "bp-validation-error" : "" ?>" /><?
													break;
												case "datetime":
													?><input type="text" name="<?= $key ?>" value="<?= $f->value ?>" class="bp-form-input-datetime <?= ($f->err) ? "bp-validation-error" : "" ?>" /><?
													break;
												case "time":
													?><input type="text" name="<?= $key ?>" value="<?= $f->value ?>" class="bp-form-input-time <?= ($f->err) ? "bp-validation-error" : "" ?>" /><?
													break;
												case "enum":
													$enumOptions = $entityField->getEnumOptions();
													if(count($enumOptions) <= 2)
													{
														?><div class="<?= ($f->err) ? "bp-validation-error" : "" ?>" <?= ($f->err) ? "title='" . $f->err . "'" : "" ?>><?		
															foreach($enumOptions as $e)
															{
																?><input type="radio" name="<?= $key ?>" value="<?= $e ?>" <?= ($f->value==$e) ? "CHECKED" : "" ?>><?= $e ?><?
															}
														?></div><?
													}
													else
													{
														?>
														<select name="<?= $key ?>" class="<?= ($f->err) ? "bp-validation-error" : "" ?>">
															<option value=""></option>
															<?
															foreach($enumOptions as $e)
															{
															?><option value="<?= $e ?>" <?= ($f->value==$e) ? "SELECTED" : "" ?>><?= $e ?></option><?
															}
														?>
														</select>
														<?
													}
													break;
												case "binary":
													?><span class="bp-form-binary"><?
													if(empty($f->value))
													{
														?>
														<input type="file" name="<?= $key ?>" />
														<?
													}
													else
													{
														?>
														<a href="/blueprints/binary/<?= $entityBP->getKey() ?>/<?= $key ?>/<?= $entityId ?>"><?= $entityField->getMimeType(); ?></a>
														<button class="bp-form-binary-clear"  href="<?= $key ?>">Clear</button>
														<?
													}
													?></span><?
													break;
											}
										} // END: if(!$f->isForeignKey())
										else
										{
											$foreignKey = substr($entityField->getForeignKey(), strpos($entityField->getForeignKey(), ".")+1);
											$foreignValue = substr($entityField->getForeignValue(), strpos($entityField->getForeignValue(), ".")+1);
											$foreignTable = substr($entityField->getForeignKey(), 0, strpos($entityField->getForeignKey(), "."));
											
											$query = "SELECT $foreignKey, $foreignValue FROM $foreignTable ORDER BY $foreignValue";
											// TODO: include WHERE cluase from formBlueprint->field:where
											$sql = new DatabaseQuery($query);
											
											try
											{
												$sql->doQuery();
												?>
												<select name="<?= $key ?>" class="<?= ($f->err) ? "bp-validation-error" : "" ?>">
													<option value=""></option>
													<?
													$num_rows = $sql->get_num_rows();
													for($i=0; $i<$num_rows; $i++)
													{
														$row = $sql->get_next_row();
														$foreignKeyResult = $row->$foreignKey;
														$foreignValueResult = $row->$foreignValue;
														?>
														<option value="<?= $foreignKeyResult ?>" <?= ($f->value==$foreignKeyResult) ? "SELECTED" : ""; ?>><?= $foreignValueResult ?></option>
														<?
													}
													?>
												</select>
												<?
											}
											catch(Exception $e)
											{
												Log::error("Caught Exception: " . $e->getMessage());
											}									
										}
										?>
									</td>
								</tr>
								<?
							} // END: if($f->display != "hidden")
							else
							{
								?>
								<input type="hidden" name="<?= $key ?>" value="<?= $f->value ?>" />
								<?
							}							
						} // END: foreach($fields as $f)
						?>
					</tbody>
				</table>
			</form>
		</div>
		<?
		
		// return contents of output buffer
		$html = ob_get_contents();
		ob_end_clean();
		return $html;
	}
	protected function initReportRows()
	{
		$tag = "ReportDrafter: initReportRows()";
		Log::debug("$tag");
		
		/*
		// Build the results table
		*/
		$reportColumnNames = array();
		$reportRows = array();
		
		// convenience pointers
		$query = $this->query;
		$reportBP = $this->reportBlueprint;
		$rowIdKey = $reportBP->getRowIdKey();
		
		try
		{
			$sql = new DatabaseQuery($query->toString());
			$sql->doQuery();
			
			// determine which fields to render
			$fields = $reportBP->fields();
			if(count($fields) == 0)
			{
				// use sql result meta data for fields
				Log::debug("$tag: Using meta data to determine fields");
				$fields = array();
				$num_cols = $sql->get_num_columns();
				for($i=0; $i<$num_cols; $i++)
				{
					$col_name = $sql->get_column_name($i);
					
					// create a new ListField for this column
					$f = new Field($col_name);
					$f->setDisplayName($col_name);
					$fields[] = $f;
				}
			}
			
			$num_rows = $sql->get_num_rows();
			if($num_rows > 0)
			{
				for($i=0; $i<$num_rows; $i++)
				{
					$row = $sql->get_next_row();
					$id = $row->$rowIdKey;
					
					$reportRow = new ListRow($id);
					
					foreach($fields as $f)
					{
						// NOTE: treat "f" as a generic Field
						$key = $f->getKey();
						
						// add to list of column names
						$reportColumnNames["$key"] = $f->getDisplayName();
						
						// retrieve value for field
						$value = $row->$key;
						
						/*
						// FORMAT VALUES
						*/
						
						if( (!empty($value)) || ($value=="0") )
						{
							// format by report blueprint format string
							if(count($reportBP->fields()) > 0)
							{
								try
								{
									$reportField = $reportBP->get($key);
									$format = $reportField->getFormat();
									
									if(!empty($format))
									{
										if("password" == strtolower($format))
										{
											$value = "********";
										}
									} // END: if(!empty($format))
								}
								catch(Exception $e)
								{
									// Report Blueprint does not contain a field for current key
									// Continue...
								}
							}
						
						} // END: if( (!empty($value) || ($value=="0") )
						
						// Look for additional column attributes from report blueprint
						$href = null;
						if(count($reportBP->fields()) > 0)
						{
							try
							{
								$reportField = $reportBP->get($key);
								$href = $reportField->getHref();
								
								// replace references to report fields with their values
								if(!empty($href)) { $href = $this->replaceKeys($href, $row); }
								
							}
							catch(Exception $e)
							{
								// Report Blueprint does not contain a field for current key
								// Continue...
							}						
						}
						
						// add a new report column to the report row
						$reportRow->addColumn($key, $value, $href);
						
					} // END: foreach($fields as $f)
					
					$reportRows[$i] = $reportRow;
					
				} // END: for($i=0; $i<$num_rows; $i++)
				
				$this->reportColumnNames = $reportColumnNames;
				$this->reportRows = $reportRows;
			
			} // END: if($num_rows > 0)
			
		}
		catch(Exception $e)
		{
			throw($e);
		}
	} // END: protected function initReportRows()
 public static function validateField(Entity $entity, $key)
 {
     $tag = "EntityValidator::validateField({$key})";
     Log::debug("{$tag}");
     try {
         $value = $entity->get($key);
         $blueprint = $entity->blueprint();
         $field = $blueprint->get($key);
         $displayName = $field->getDisplayName();
         $dataType = $field->getDataType();
         if ($field->isRequired()) {
             if (empty($value) && $value != "0") {
                 return "Missing required value '{$displayName}'";
             }
         }
         if (!empty($value) || $value == "0") {
             switch ($dataType) {
                 case "string":
                     $max = $field->getMax();
                     if (!empty($max) && strlen($value) > $max) {
                         return "'{$displayName}' exceeds maximum character limit ({$max})";
                     }
                     $regexp = $field->getRegexp();
                     if (!empty($regexp)) {
                         if (!ereg($regexp, $value)) {
                             $example = $field->getExample();
                             return "'{$displayName}' does not match the required pattern '{$example}'";
                         }
                     }
                     break;
                 case "int":
                     if (!is_numeric($value) || strpos($value, ".")) {
                         return "'{$displayName}' must be an integer";
                     }
                     $min = $field->getMin();
                     if ((!empty($min) || $min == "0") && $value < $min) {
                         return "'{$displayName}' less than minimum required ({$min})";
                     }
                     $max = $field->getMax();
                     if ((!empty($max) || $max == "0") && $value > $max) {
                         return "'{$displayName}' greater than maximum allowed ({$max})";
                     }
                     break;
                 case "decimal":
                     if (!is_numeric($value)) {
                         return "'{$displayName}' must be a number";
                     }
                     $min = $field->getMin();
                     if ((!empty($min) || $min == "0") && $value < $min) {
                         return "'{$displayName}' less than minimum required ({$min})";
                     }
                     $max = $field->getMax();
                     if ((!empty($max) || $max == "0") && $value > $max) {
                         return "'{$displayName}' greater than maximum allowed ({$max})";
                     }
                     $precision = $field->getPrecision();
                     if ($decimalPosition = strpos($value, ".")) {
                         $decimals = substr($value, $decimalPosition + 1);
                         if (!empty($precision) && strlen($decimals) > $precision) {
                             return "'{$displayName}' has more than {$precision} allowed digits after decimal point";
                         }
                     }
                     break;
                 case "date":
                     $regexp = "^([0-9]{4})\\-([0-9]{2})\\-([0-9]{2})\$";
                     $example = $field->getExample();
                     if (!ereg($regexp, $value, $regs)) {
                         return "'{$displayName}' does not match required pattern '{$example}'";
                     }
                     $year = $regs[1];
                     $month = $regs[2];
                     $day = $regs[3];
                     if (!checkdate($month, $day, $year)) {
                         return "'{$displayName}' is not a valid date";
                     }
                     break;
                 case "datetime":
                     $regexp = "^([0-9]{4})\\-([0-9]{2})\\-([0-9]{2}) ([0-9]{2})\\:([0-9]{2})\\:([0-9]{2})\$";
                     $example = $field->getExample();
                     if (!ereg($regexp, $value, $regs)) {
                         return "'{$displayName}' does not match required pattern '{$example}'";
                     }
                     $year = $regs[1];
                     $month = $regs[2];
                     $day = $regs[3];
                     $hour = $regs[4];
                     $minute = $regs[5];
                     $seconds = $regs[6];
                     if (!checkdate($month, $day, $year)) {
                         return "'{$displayName}' contains an valid date";
                     }
                     if ($hour > 23 || $minute > 59 || $seconds > 59) {
                         return "'{$displayName}' contains an invalid time";
                     }
                     break;
                 case "time":
                     $regexp = "^([0-9]{2})\\:([0-9]{2})(\\:([0-9]{2}))?\$";
                     $example = $field->getExample();
                     if (!ereg($regexp, $value, $regs)) {
                         return "'{$displayName}' does not match required pattern '{$example}'";
                     }
                     $hour = $regs[1];
                     $minute = $regs[2];
                     $seconds = $regs[4];
                     if ($hour > 23 || $minute > 59 || $seconds > 59) {
                         return "'{$displayName}' contains an invalid time";
                     }
                     break;
                 case "enum":
                     $enumOptions = $field->getEnumOptions();
                     if (!in_array($value, $enumOptions)) {
                         return "'{$value}' is not a valid selection for '{$displayName}'";
                     }
                     break;
                 case "text":
                     $min = $field->getMin();
                     $max = $field->getMax();
                     $mimeType = $field->getMimeType();
                     break;
                 case "binary":
                     $min = $field->getMin();
                     $max = $field->getMax();
                     $mimeType = $field->getMimeType();
                     break;
             }
             // END: switch($dataType)
             if ($field->isUnique()) {
                 if ($dataType == "int") {
                     $query = "SELECT id FROM " . $blueprint->getKey() . " WHERE " . $field->getKey() . "={$value}";
                 } else {
                     $query = "SELECT id FROM " . $blueprint->getKey() . " WHERE " . $field->getKey() . "='{$value}'";
                 }
                 try {
                     $sql = new DatabaseQuery($query);
                     $sql->doQuery();
                     if ($sql->get_num_rows() > 0) {
                         $row = $sql->get_next_row();
                         $id = $row->id;
                         if ($id == $entity->getId()) {
                             // this entity is simply using its own pre-existing unique value for key
                         } else {
                             // unique value is already in use for this key
                             return "'{$value}' is already in use for '{$displayName}'";
                         }
                     }
                 } catch (Exception $e) {
                     // query failed
                     Log::error("{$tag}: " . $e->getMessage());
                     return "Unable to validate uniqueness of '{$displayName}'";
                 }
             }
         }
         // END: if((!empty($value)) || ($value==0))
     } catch (Exception $e) {
         // blueprint does not contain a field for $key
         Log::warning("{$tag}: No field defined for '{$key}'");
         // do not report an error
         return false;
     }
     return false;
 }
 public function findWhere($keys, $values)
 {
     $tag = "EntityDAO: findWhere()";
     Log::notice("{$tag}: ({$keys}, {$values})");
     $blueprint = $this->blueprint;
     $timezone_offset = $this->timezone_offset_select;
     $blueprintKey = $this->tableName();
     $query = new EntityQuery($blueprint, $timezone_offset);
     if (!is_array($keys) && !is_array($values)) {
         // convert non-array arguments into single element arrays
         $keys = array($keys);
         $values = array($values);
     } else {
         if (is_array($keys) && !is_array($values) || count($keys) != count($values)) {
             throw new Exception("Length of (key,value) arguments do not match");
         }
     }
     try {
         for ($i = 0; $i < count($keys); $i++) {
             $key = $keys[$i];
             $value = $values[$i];
             $field = $blueprint->get($key);
             switch ($field->getDataType()) {
                 case "int":
                     $query->where("{$blueprintKey}.{$key}={$value}");
                     break;
                 case "datetime":
                 case "time":
                     $query->where("{$blueprintKey}.{$key}=CONVERT_TZ('{$value}', '{$timezone_offset}', '" . BPTimezone::UTC . "')");
                     break;
                 default:
                     $query->where("{$blueprintKey}.{$key}='{$value}'");
                     break;
             }
         }
     } catch (Exception $e) {
         Log::error("{$tag}: Field [{$key}] is not defined by [" . $blueprint->getKey() . "]");
         throw $e;
     }
     try {
         $sql = new DatabaseQuery($query->toString());
         $sql->doQuery();
         $matches = array();
         $num_rows = $sql->get_num_rows();
         Log::debug("{$tag}: Found {$num_rows} matches");
         for ($i = 0; $i < $sql->get_num_rows(); $i++) {
             $row = $sql->get_next_row();
             $entity = new Entity($blueprint);
             $entity->setId($row->id);
             $entity->setModified($row->modified);
             foreach ($blueprint->fields() as $field) {
                 $key = $field->getKey();
                 $value = $row->{$key};
                 if ($field->isForeignKey()) {
                     $foreignValueColumn = str_replace(".", "_", $field->getForeignValue());
                     $foreignValue = $row->{$foreignValueColumn};
                     $entity->setForeignValue($key, $foreignValue);
                 }
                 switch ($field->getDataType()) {
                     case "binary":
                         if (get_magic_quotes_gpc()) {
                             $value = stripslashes($str);
                         }
                         $lengthKey = $key . "_length";
                         $length = $row->{$lengthKey};
                         $entity->length($key, $length);
                         break;
                 }
                 $entity->set($key, $value);
             }
             $matches[] = $entity;
         }
         return $matches;
     } catch (Exception $e) {
         Log::error("{$tag}: [" . $sql->err_code . "] " . $sql->err_message);
         throw $e;
     }
 }
 public static function session_handler_read($session_id)
 {
     $tag = "Session::session_handler_read({$session_id})";
     Log::debug($tag);
     try {
         // For maximum performace, query the database directly (do not use EntityDAO)
         $session_table_name = substr(BPConfig::$session_blueprint, 0, strpos(BPConfig::$session_blueprint, "."));
         $session_field_id = BPConfig::$session_field_id;
         $session_field_data = BPConfig::$session_field_data;
         $query = "SELECT {$session_field_data} FROM {$session_table_name} WHERE {$session_field_id}='" . DatabaseSanitizer::sanitize($session_id) . "'";
         $sql = new DatabaseQuery($query);
         $sql->doQuery();
         if ($sql->get_num_rows() == 1) {
             $row = $sql->get_next_row();
             $data = $row->{$session_field_data};
             // Decode session data
             $data = base64_decode($data);
             $data = stripslashes($data);
             // DEBUG
             Log::debug("{$data}");
             return $data;
         } else {
             Log::warning("{$tag}: session_id was not found");
             return "";
             // empty string
         }
     } catch (Exception $e) {
         Log::error("{$tag}: Caught: " . $e->getMessage());
         return "";
         // empty string
     }
 }
	public function render()
	{
		$tag = "FilterDrafter: render()";
		Log::debug("$tag");
		
		// convenience pointers
		$id = $this->id;
		$entityBP = $this->entityBlueprint;
		$filterBP = $this->filterBlueprint;
		$filters = $this->filters;
		$params = $this->params;
		
		// encode params for inclusion in html
		$encodedParams = ParamEncoder::encode($params);
		
		// translate buttonPlacement into html element
		$buttonContainer = "tfoot";
		if( array_key_exists("buttonPlacement", $params) )
		{
			if($params["buttonPlacement"] == "thead")
				$buttonContainer = "thead";
			else
				$buttonContainer = "tfoot";
		}
		
		// turn on output buffering
		@ob_end_flush();
		ob_start();
		
		?>
		<div class="bp-draft-rendering" id="<?= $id ?>" type="filter" renderer="FilterDrafter" entitySignature="<?= $entityBP->signature(); ?>" filterSignature="<?= ($filterBP) ? $filterBP->signature() : ""; ?>" params="<?= $encodedParams ?>">
			<form class="bp-filter-form">
				<table class="bp-filter-table">
					<?
					if( array_key_exists("buttons", $params) )
					{
						echo "<" . $buttonContainer . ">"; // OPEN: <thead> or <tfoot>
							?>
							<tr>
								<td colspan="2" align="<?= $params["buttonAlignment"] ?>" class="bp-form-buttons">
									<?
									$buttonKeys = array_keys($params["buttons"]);
									foreach($buttonKeys as $b)
									{
										?>
										<input type="button" class="bp-form-button" value="<?= $b ?>" onClick="<?= $params["buttons"]["$b"] ?>" />
										<?
									}
									?>
								</td>
							</tr>
							<?
						echo "</" . $buttonContainer. ">";	// CLOSE: </thead> or </tfoot>
					}
					?>
					<tbody>
						<?
						foreach($filters as $f)
						{
							$key = $f->getKey();
							$type = $f->type;
							
							?>
							<tr>
								<td class="bp-filter-label"><?= $f->displayName; ?></td>
								<td class="bp-filter-input">
									<?
									if(!$f->isForeignKey())
									{
										switch($f->dataType)
										{
											case "string":
											case "text":
												?><input type="text" key="<?= $key ?>" name="<?= $key . "_" . $type ?>" value="<?= $f->value["$type"]; ?>" /><?
												break;
											case "int":
											case "decimal":
											case "date":
											case "datetime":
												switch($type)
												{
													case "min":
													case "max":
													case "equals":
														?><input type="text" key="<?= $key ?>" name="<?= $key . "_" . $type ?>" value="<?= $f->value["$type"]; ?>" /><?
														break;
													case "range":
														?><input type="text" key="<?= $key ?>" name="<?= $key . "_min" ?>" value="<?= $f->value["min"]; ?>" />&nbsp;to&nbsp;<input type="text" key="<?= $key ?>" name="<?= $key . "_max" ?>" value="<?= $f->value["max"]; ?>" /><?
														break;
												}
												break;
											case "enum":
												$entityField = $entityBP->get($key);
												$enumOptions = $entityField->getEnumOptions();
																				
												?>
												<select key="<?= $key ?>" name="<?= $key . "_" . $type ?>">
													<option value=""></option>
													<?
													foreach($enumOptions as $e)
													{
													?><option value="<?= $e ?>" <?= ($f->value["$type"]==$e) ? "SELECTED" : "" ?>><?= $e ?></option><?
													}
												?>
												</select>
												<?								
												break;
											case "binary":
												// TODO: render; type=not null|size
												break;
										} // END: switch($f->dataType)
									} // END: if(!$f->isForeignKey())
									else
									{
										$foreignKey = substr($f->foreignKey, strpos($f->foreignKey, ".")+1);
										$foreignValue = substr($f->foreignValue, strpos($f->foreignValue, ".")+1);
										$foreignTable = substr($f->foreignKey, 0, strpos($f->foreignKey, "."));
										
										$query = "SELECT $foreignKey, $foreignValue FROM $foreignTable";
										// TODO: include WHERE cluase from filterBlueprint->field:where
										$sql = new DatabaseQuery($query);
										
										try
										{
											$sql->doQuery();
											?>
											<select key="<?= $key ?>" name="<?= $key . "_equals" ?>">
												<option value=""></option>
												<?
												$num_rows = $sql->get_num_rows();
												for($i=0; $i<$num_rows; $i++)
												{
													$row = $sql->get_next_row();
													$foreignKeyResult = $row->$foreignKey;
													$foreignValueResult = $row->$foreignValue;
													?>
													<option value="<?= $foreignKeyResult ?>" <?= ($f->value["equals"]==$foreignKeyResult) ? "SELECTED" : ""; ?>><?= $foreignValueResult ?></option>
													<?
												}
												?>
											</select>
											<?
										}
										catch(Exception $e)
										{
											Log::error("Caught Exception: " . $e->getMessage());
										}
									}
									?>
								</td>
							</tr>
							<?
						}
						?>
					</tbody>
				</table>
			</form>
		</div>
		<?
		
		// return contents of output buffer
		$html = ob_get_contents();
		ob_end_clean();
		return $html;
	}
 public function render()
 {
     $tag = "FilterXMLDrafter: render()";
     Log::debug("{$tag}");
     // convenience pointers
     $id = $this->id;
     $entityBP = $this->entityBlueprint;
     $filterBP = $this->filterBlueprint;
     $filters = $this->filters;
     $params = $this->params;
     // encode params for inclusion in html
     $encodedParams = ParamEncoder::encode($params);
     // init xml respose
     $xml = new SimpleXmlElement("<bpXmlDraftRendering />");
     $rendering = $xml;
     $rendering->addAttribute("id", $id);
     $rendering->addAttribute("type", "filter");
     $rendering->addAttribute("entitySignature", $entityBP->signature());
     if ($filterBP) {
         $rendering->addAttribute("filterSignature", $filterBP->signature());
     }
     $rendering->addAttribute("params", $encodedParams);
     foreach ($filters as $f) {
         // collect data for this field
         $key = $f->getKey();
         $type = $f->type;
         // add new <field> to xml response
         $fieldPtr = $rendering->addChild("field");
         $fieldPtr->addAttribute("key", $key);
         $fieldPtr->addChild("type", $type);
         $fieldPtr->addChild("dataType", $f->dataType);
         $fieldPtr->addChild("displayName", $f->displayName);
         // enum options
         if ($f->dataType == "enum") {
             $enumPtr = $fieldPtr->addChild("enumOptions");
             $entityField = $entityBP->get($key);
             $enumOptions = $entityField->getEnumOptions();
             foreach ($enumOptions as $e) {
                 $enumPtr->addChild("option", $e);
             }
         }
         // value
         if (!$f->isForeignKey()) {
             if ($f->hasValue()) {
                 $filterValue = $f->value;
                 // an array
                 $valuePtr = $fieldPtr->addChild("value");
                 if (array_key_exists("equals", $filterValue)) {
                     $ptr = $valuePtr->addChild("equals", $filterValue["equals"]);
                     $ptr->addAttribute("name", $key . "_equals");
                 }
                 if (array_key_exists("like", $filterValue)) {
                     $ptr = $valuePtr->addChild("like", $filterValue["like"]);
                     $ptr->addAttribute("name", $key . "_like");
                 }
                 if (array_key_exists("min", $filterValue)) {
                     $ptr = $valuePtr->addChild("min", $filterValue["min"]);
                     $ptr->addAttribute("name", $key . "_min");
                 }
                 if (array_key_exists("max", $filterValue)) {
                     $ptr = $valuePtr->addChild("max", $filterValue["max"]);
                     $ptr->addAttribute("name", $key . "_max");
                 }
             }
         } else {
             $enumPtr = $fieldPtr->addChild("foreignOptions");
             $foreignKey = substr($f->foreignKey, strpos($f->foreignKey, ".") + 1);
             $foreignValue = substr($f->foreignValue, strpos($f->foreignValue, ".") + 1);
             $foreignTable = substr($f->foreignKey, 0, strpos($f->foreignKey, "."));
             $query = "SELECT {$foreignKey}, {$foreignValue} FROM {$foreignTable}";
             // TODO: include WHERE clause from filterBlueprint->field:where
             $sql = new DatabaseQuery($query);
             try {
                 $sql->doQuery();
                 $num_rows = $sql->get_num_rows();
                 for ($i = 0; $i < $num_rows; $i++) {
                     $row = $sql->get_next_row();
                     $foreignKeyResult = $row->{$foreignKey};
                     $foreignValueResult = $row->{$foreignValue};
                     $optionPtr = $enumPtr->addChild("option");
                     $optionPtr->addAttribute("key", $foreignKeyResult);
                     $optionPtr->addChild("value", $foreignValueResult);
                 }
             } catch (Exception $e) {
                 Log::error("Caught Exception: " . $e->getMessage());
             }
         }
     }
     // END: foreach($filters as $f)
     // Return XML string
     // NOTE: using DomDocument provides more flexibility (supressing empty tags, and removing xml declaration)
     // This xml cannot contain an xml declaration, because we plan on embedding it in another xml document
     $dom = new DomDocument();
     $dom->loadXML($xml->asXML());
     $node = $dom->getElementsByTagName("bpXmlDraftRendering")->item(0);
     return $dom->saveXML($node, LIBXML_NOEMPTYTAG);
 }
    echo "time = " . $access->get("time") . "<br/>";
    echo "<br/>";
    echo "<strong>Forcing update in session timezone: {$session_timezone_offset}</strong><br/><br/>";
    // Update the Access (force Session timezone)
    unset($accessDAO);
    $accessDAO = new EntityDAO($accessBP, $session_timezone_offset);
    $access->set("time", date("Y-m-d H:i:s"));
    $access->set("description", "Updated Timezone (with forced session timezone) Test");
    $accessDAO->update($access);
    echo "Updated Access with id {$access_id}<br/>";
    echo "<br/>";
    unset($access);
    // Load Access with EntityQuery
    $accessQuery = new EntityQuery($accessBP);
    $accessQuery->where("Access.id={$access_id}");
    echo "QUERY:<br/>" . $accessQuery->toString() . "<br/><br/>";
    $sql = new DatabaseQuery($accessQuery->toString());
    $sql->doQuery();
    echo "Selected Access with id {$access_id}<br/>";
    $row = $sql->get_next_row();
    $modified = $row->modified;
    $time = $row->time;
    echo "modified = {$modified}<br/>";
    echo "time = {$time}<br/>";
    echo "<br/>";
    unset($row);
    unset($sql);
    unset($accessQuery);
} catch (Exception $e) {
    echo "Caught: " . $e->getMessage() . "<br/><br/>";
}
 private function test_access_rule_ownership($rule, $identity, $entityId)
 {
     $tag = "Guardian: test_access_rule_ownership()";
     Log::debug("{$tag}");
     $ownerIdentifier = (string) $rule;
     $keyPath = $rule["keyPath"];
     $identityKeyPath = $rule["identityKeyPath"];
     list($ownershipTable, $ownershipField) = explode(".", $keyPath);
     list($identityTable, $identityField) = explode(".", $identityKeyPath);
     @(list($ownerIdentifierTable, $ownerIdentifierField) = explode(".", $ownerIdentifier));
     Log::debug("{$tag}: Rule requires ownership of '{$entityId}' from keyPath '{$keyPath}'");
     if ($ownershipTable == $identityTable) {
         // TEST FOR DIRECT OWNERSHIP BY IDENTITY
         try {
             $query = "SELECT {$ownershipField} FROM {$ownershipTable} WHERE id={$entityId}";
             $sql = new DatabaseQuery($query);
             $sql->doQuery();
             if ($sql->get_num_rows() == 1) {
                 $row = $sql->get_next_row();
                 $owner_id = $row->{$ownershipField};
                 if ($owner_id == $identity) {
                     Log::debug("{$tag}: {$ownershipTable} with ID {$entityId} is owned by requestor");
                     return true;
                 } else {
                     Log::debug("{$tag}: {$ownershipTable} with ID {$entityId} is not owned by requestor");
                     return false;
                 }
             } else {
                 Log::warning("{$tag}: {$ownershipTable} with ID {$entityId} was not found");
                 return false;
             }
         } catch (Exception $e) {
             Log::error("{$tag}: Caught: " . $e->getMessage());
             return false;
         }
     } else {
         if (!empty($ownerIdentifier)) {
             // TEST FOR INDIRECT OWNERSHIP BY AFFILIATION
             // Lookup the "group" that owns this record (in $keyPath)
             // Verify that the requestor is Affiliated with this group
             try {
                 $query = "SELECT {$ownershipField} FROM {$ownershipTable} WHERE id={$entityId}";
                 $sql = new DatabaseQuery($query);
                 $sql->doQuery();
                 if ($sql->get_num_rows() == 1) {
                     $row = $sql->get_next_row();
                     $owner_id = $row->{$ownershipField};
                     Log::debug("Rule requires ownership through affiliation with '{$owner_id}' from keyPath '{$ownerIdentifier}'");
                     $query = "SELECT {$ownerIdentifierField} FROM {$ownerIdentifierTable} WHERE {$identityField}={$identity}";
                     $sql = new DatabaseQuery($query);
                     $sql->doQuery();
                     // NOTE:
                     // "affiliations" may be defined in such a way that each identity has multiple affiliations
                     // check each matching affiliation for this identity
                     if ($sql->get_num_rows() > 0) {
                         for ($i = 0; $i < $sql->get_num_rows(); $i++) {
                             $row = $sql->get_next_row();
                             $_affiliation = $row->{$ownerIdentifierField};
                             if ($_affiliation == $owner_id) {
                                 Log::debug("{$tag}: Found matching affiliation '{$_affiliation}'");
                                 return true;
                             }
                         }
                         Log::debug("{$tag}: No records with matching affiliation '{$owner_id}'");
                         return false;
                     } else {
                         Log::debug("{$tag}: No affiliation records matching this identity");
                         return false;
                     }
                 } else {
                     Log::warning("{$tag}: {$ownershipTable} with ID {$entityId} was not found");
                     return false;
                 }
             } catch (Exception $e) {
                 Log::error("{$tag}: Caught: " . $e->getMessage());
                 return false;
             }
         } else {
             Log::error("{$tag}: Invalid <Ownership> rule");
             return false;
         }
     }
 }
 public function render()
 {
     $tag = "FormXMLDrafter: render()";
     Log::debug("{$tag}");
     // convenience pointers
     $id = $this->id;
     $entityId = $this->entityId;
     $entityBP = $this->entityBlueprint;
     $formBP = $this->formBlueprint;
     $fields = $this->formFields;
     $params = $this->params;
     // encode params for inclusion in html
     $encodedParams = ParamEncoder::encode($params);
     // init xml respose
     $xml = new SimpleXmlElement("<bpXmlDraftRendering></bpXmlDraftRendering>");
     $rendering = $xml;
     $rendering->addAttribute("id", $id);
     $rendering->addAttribute("type", "form");
     $rendering->addAttribute("entitySignature", $entityBP->signature());
     if ($formBP) {
         $rendering->addAttribute("formSignature", $formBP->signature());
     }
     $rendering->addAttribute("entityId", $entityId);
     $rendering->addAttribute("params", $encodedParams);
     foreach ($fields as $f) {
         // collect data for this field
         $key = $f->getKey();
         $entityField = $entityBP->get($key);
         // add new <field> to xml response
         $fieldPtr = $rendering->addChild("field");
         $fieldPtr->addAttribute("key", $key);
         /*
         // add details for this <field>
         */
         // displayName
         $fieldPtr->addChild("displayName", $f->displayName);
         // dataType
         $fieldPtr->addChild("dataType", $f->dataType);
         // value
         // replace "&" with "&amp;" to prevent xml errors
         $f->value = str_replace("&", "&amp;", $f->value);
         switch ($f->dataType) {
             case "string":
                 if ($entityField->getEncType() != "plain") {
                     $fieldPtr->addChild("value", "********");
                 } else {
                     $fieldPtr->addChild("value", $f->value);
                 }
                 break;
             case "binary":
                 $binaryValue = !empty($f->value) ? "/blueprints/binary/" . $entityBP->getKey() . "/" . $key . "/" . $entityId : "";
                 $binaryValuePtr = $fieldPtr->addChild("value", $binaryValue);
                 $binaryValuePtr->addAttribute("mimeType", $entityField->getMimeType());
                 break;
             default:
                 $fieldPtr->addChild("value", $f->value);
         }
         // foreign value options
         if ($entityField->isForeignKey()) {
             $enumPtr = $fieldPtr->addChild("foreignOptions");
             $foreignKey = substr($entityField->getForeignKey(), strpos($entityField->getForeignKey(), ".") + 1);
             $foreignValue = substr($entityField->getForeignValue(), strpos($entityField->getForeignValue(), ".") + 1);
             $foreignTable = substr($entityField->getForeignKey(), 0, strpos($entityField->getForeignKey(), "."));
             $query = "SELECT {$foreignKey}, {$foreignValue} FROM {$foreignTable} ORDER BY {$foreignValue}";
             // TODO: include WHERE cluase from formBlueprint->field:where
             $sql = new DatabaseQuery($query);
             try {
                 $sql->doQuery();
                 $num_rows = $sql->get_num_rows();
                 for ($i = 0; $i < $num_rows; $i++) {
                     $row = $sql->get_next_row();
                     $foreignKeyResult = $row->{$foreignKey};
                     $foreignValueResult = $row->{$foreignValue};
                     // clean
                     $foreignValueResult = htmlentities($foreignValueResult);
                     $optionPtr = $enumPtr->addChild("foreignOption", $foreignValueResult);
                     $optionPtr->addAttribute("key", $foreignKeyResult);
                 }
             } catch (Exception $e) {
                 Log::error("Caught Exception: " . $e->getMessage());
             }
         }
         // enumOptions
         if ($f->dataType == "enum") {
             $enumPtr = $fieldPtr->addChild("enumOptions");
             $enumOptions = $entityField->getEnumOptions();
             foreach ($enumOptions as $e) {
                 $enumPtr->addChild("enumOption", $e);
             }
         }
         // validation errors
         if ($f->err) {
             $errPtr = $fieldPtr->addChild("validationError");
             $errPtr->addChild("message", $f->err);
         }
     }
     // END: foreach($fields as $f)
     // Return XML string
     // NOTE: using DomDocument provides more flexibility (supressing empty tags, and removing xml declaration)
     // This xml cannot contain an xml declaration, because we plan on embedding it in another xml document
     $dom = new DomDocument();
     $dom->loadXML($xml->asXML());
     $node = $dom->getElementsByTagName("bpXmlDraftRendering")->item(0);
     return $dom->saveXML($node, LIBXML_NOEMPTYTAG);
 }
	protected function initListRows()
	{
		$tag = "ListDrafter: initListRows()";
		Log::debug("$tag");
		
		/*
		// Build the results table
		*/
		$listColumnNames = array();
		$listRows = array();
		
		// convenience pointers
		$query = $this->entityQuery;
		$entityBP = $this->entityBlueprint;
		$listBP = $this->listBlueprint;
		
		// determine which fields to render
		if($listBP) {$fields = $listBP->fields(); } else { $fields = $entityBP->fields(); }
		
		try
		{
			$sql = new DatabaseQuery($query->toString());
			$sql->doQuery();
			$num_rows = $sql->get_num_rows();
			
			if($num_rows > 0)
			{
				for($i=0; $i<$num_rows; $i++)
				{
					$row = $sql->get_next_row();
					$id = $row->id;
					
					$listRow = new ListRow($id);			
			
					foreach($fields as $f)
					{
						// NOTE: treat "f" as a generic Field
						$key = $f->getKey();
						
						// add to list of column names
						$listColumnNames["$key"] = $f->getDisplayName();
						
						// get field definition from entityBlueprint
						$entityField = $entityBP->get($key);
					
						// retrieve value for field
						if($entityField->isForeignKey())
						{
							$foreignValue = str_replace(".", "_", $entityField->getForeignValue());
							$value = $row->$foreignValue;
						}
						else
						{
							$value = $row->$key;
						}
						
						/*
						// Format Values
						*/
						
						if( (!empty($value)) || ($value=="0") )
						{
							// first by datatype
							switch($entityField->getDataType())
							{
								case "string":
									if($entityField->getEncType() != "plain") { $value = "********"; }
									break;
								case "text":
									break;
								case "binary":
									$lengthKey = $key . "_length";
									$bytes = $row->$lengthKey;
									$value = "<a href='/blueprints/binary.php?action=file&blueprint=" . $entityBP->getKey() . "&field=$key&id=$id'>" . Binary::formatLength($bytes) . "</a>";
									break;
							}
							
							// then, by list blueprint format string
							if($listBP)
							{
								$listField = $listBP->get($key);
								$format = $listField->getFormat();
								
								if(!empty($format))
								{
									switch($entityField->getDataType())
									{
										case "string":
										case "text":
											// formatter string specifies truncation length
											if(strlen($value) > $format) { $value = substr($value, 0, $format) . "..."; }
											break;
										case "enum":
											// formatter string specifies truncation length
											if(strlen($value) > $format) { $value = substr($value, 0, $format); }
											break;
										case "date":
										case "datetime":
											// formatter string specifies php date format
											$time = strtotime($value);
											$value = date($format, $time);
											break;									
										case "binary":
											break;
									}
								}
							}
							
							// look for additional column attributes from listBlueprint
							$href = null;
							if($listBP)
							{
								$listField = $listBP->get($key);
								$href = $listField->getHref();
								
								// replace references to entity fields with their values
								if(!empty($href)) { $href = $this->replaceKeys($href, $row); }
							}
						}

						// add a new list column to the list row
						$listRow->addColumn($key, $value, @$href);
						
					} // END: foreach($field as $f)
					
					$listRows[$i] = $listRow;
					
				} // END: for($i=0; $i<$num_rows; $i++)
				
				$this->listColumnNames = $listColumnNames;
				$this->listRows = $listRows;
				
			} // END: if($num_rows > 0)
		}
		catch(Exception $e)
		{
			// ? can we throw exceptions from a / to a constructor?
			throw($e);
		}
	
	} // END: protected function initListRows()