protected function initEntity()
	{
		$tag = "FormDrafter: initEntity()";
		Log::debug("$tag");
		
		if($this->entity == null)
		{	
			// convenience pointers
			$entityId = $this->entityId;
			$entityBP = $this->entityBlueprint;
			
			if($entityId > 0)
			{
				try
				{
					$entityDAO = new EntityDAO($entityBP);
					if($entity = $entityDAO->load($entityId))
					{
						$this->entity = $entity;
					}
					else
					{
						Log::warning("$tag: Entity with id $entityId was not found");
						$this->entity = $entityBP->build();
					}
				}
				catch(Exception $e)
				{
					Log::erorr("$tag: Caught: " . $e->getMessage());
					$this->entity = $entityBP->build();
				}
			}
			else
			{
				$this->entity = $entityBP->build();
			}
		}
	}
 public static function get($blueprintSignature, $id, $field, $timezone_offset = NULL)
 {
     $tag = "EntityDAO: get()";
     Log::debug("{$tag}: <blueprintSignature={$blueprintSignature}, id={$id}, field={$field}, timezone_offset={$timezone_offset}>");
     // Init timezone offsets
     if (empty($timezone_offset)) {
         $timezone_offset = BPTimezone::getOffset();
     }
     try {
         $blueprint = BlueprintReader::read($blueprintSignature);
         $dao = new EntityDAO($blueprint, $timezone_offset);
         if ($entity = $dao->load($id)) {
             $value = $entity->get($field);
             Log::debug("{$tag}: {$field} = {$value}");
             return $value;
         } else {
             // entity with "id" not found
             Log::warning("{$tag}: {$blueprintSignature} with id {$id} not found.");
             return false;
         }
     } catch (Exception $e) {
         Log::error("{$tag}: Caught: " . $e->getMessage());
         throw $e;
     }
 }
 public static function import($path_csv, $path_resources = null, $mapping = array())
 {
     $tag = "EntityImporter:import()";
     Log::notice("{$tag}: <{$path_csv}, {$path_resources}, {$mapping}>");
     // pseudo contants
     $IMPORT_MODE_INSERT = 0;
     $IMPORT_MODE_UPDATE = 1;
     // init results array
     $stat = array();
     $stat["attempts"] = 0;
     $stat["inserts"] = 0;
     $stat["updates"] = 0;
     $stat["warnings"] = 0;
     $stat["errors"] = 0;
     // TODO: include sub-arrays for warning messages and error messages
     // eg: $stat["warning_messages"] = array(); where array indecies reference csv row numbers
     if (!is_readable($path_csv)) {
         Log::error("{$tag}: Unable to read from path {$path_csv}");
         throw new Exception("{$tag}: Unable to read from path {$path_csv}");
     }
     if ($path_resources != null && !is_readable($path_resources)) {
         Log::error("{$tag}: Unable to read from path {$path_resources}");
         throw new Exception("{$tag}: Unable to read from path {$path_resources}");
     }
     $csv_filename = basename($path_csv);
     $blueprint_key = substr($csv_filename, 0, strpos($csv_filename, "."));
     $blueprint_signature = $blueprint_key . ".entity.xml";
     Log::debug("{$tag}: Blueprint Signature: {$blueprint_signature}");
     /*
     // Compare CSV Header with Blueprint
     // determine if mapping is required
     */
     // read blueprint (on server)
     $bp = BlueprintReader::read($blueprint_signature);
     // init csv file for parsing
     $csv = new Csv($path_csv);
     // read csv header row
     $csv_header_row = $csv->nextRow();
     // apply mappings
     for ($i = 0; $i < count($csv_header_row); $i++) {
         $import_field = $csv_header_row[$i];
         $mapping_key = "mapping_" . $bp->getKey() . "_" . str_replace(".", "_", $import_field);
         // skip <id> columns
         if ($import_field == "id") {
             continue;
         }
         // skip columns where mapping is _DROP
         if (array_key_exists($mapping_key, $mapping) && $mapping[$mapping_key] == "_DROP") {
             continue;
         }
         if (array_key_exists($mapping_key, $mapping)) {
             // replace csv column header with mapped value
             $csv_header_row[$i] = $mapping["{$mapping_key}"];
         }
     }
     foreach ($csv_header_row as $import_field) {
         // skip <id> columns
         if ($import_field == "id") {
             continue;
         }
         // skip columns where mapping is _DROP
         $mapping_key = "mapping_" . $bp->getKey() . "_" . str_replace(".", "_", $import_field);
         if (array_key_exists($mapping_key, $mapping) && $mapping[$mapping_key] == "_DROP") {
             continue;
         }
         if (!$bp->keyExists($import_field)) {
             throw new EntityImporterException($bp, $csv_header_row);
         }
     }
     // check for id column
     $with_ids = false;
     if (in_array("id", $csv_header_row)) {
         $with_ids = true;
         Log::debug("{$tag}: Importing with ids");
     }
     // init Entity DAO
     $entityDAO = new EntityDAO($bp);
     // Import rows from Csv
     while (($row = $csv->nextRow()) !== FALSE) {
         $stat["attempts"]++;
         // init an entity to import
         unset($entity);
         // clear previous
         $entity = null;
         // flag an import mode (insert, update)
         $import_mode = EntityImporter::$IMPORT_MODE_INSERT;
         // check <id> to see if this csv row references an existing entity
         if ($with_ids) {
             $import_id = $row[0];
             if (!empty($import_id) && $import_id != 0) {
                 // check that an entity with this id exists
                 try {
                     if ($match = $entityDAO->load($import_id)) {
                         $entity = $match;
                         $import_mode = EntityImporter::$IMPORT_MODE_UPDATE;
                         Log::debug("{$tag}: Updating an existing {$blueprint_signature} with id {$import_id}");
                     } else {
                         $entity = $bp->build();
                         $entity->setId($import_id);
                         Log::debug("{$tag}: Creating a new {$blueprint_signature} with id {$import_id}");
                     }
                 } catch (Exception $e) {
                     $stat["warnings"]++;
                     Log::warning("{$tag}: Caught Exception: " . $e->getMessage());
                     $entity = $bp->build();
                     $entity->setId($import_id);
                     Log::debug("{$tag}: Creating a new {$blueprint_signature} with id {$import_id}");
                 }
             }
             // END: if( (!empty($import_id)) && ($import_id!=0) )
         }
         // END: if($with_ids)
         // if we are not working with an existing entity, build a new one
         if ($entity == null) {
             $entity = $bp->build();
             Log::debug("{$tag}: Creating a new {$blueprint_signature} without an id");
         }
         for ($i = 0; $i < count($csv_header_row); $i++) {
             // extract data from csv
             $import_field_key = $csv_header_row[$i];
             $import_field_value = $row[$i];
             // skid <id> column
             if ($import_field_key == "id") {
                 continue;
             }
             // skip columns where mapping is _DROP
             $mapping_key = "mapping_" . $bp->getKey() . "_" . str_replace(".", "_", $import_field_key);
             if (array_key_exists($mapping_key, $mapping) && $mapping[$mapping_key] == "_DROP") {
                 continue;
             }
             // extract field information from blueprint
             $field = $bp->get($import_field_key);
             switch ($field->getDataType()) {
                 case "date":
                     // reformat dates for mysql
                     $time = strtotime($import_field_value);
                     $import_field_value = date("Y-m-d", $time);
                     $entity->set($import_field_key, $import_field_value);
                     break;
                 case "binary":
                     $path_binary = $path_resources . $import_field_value;
                     Log::debug("{$tag}: Searching for binary at path {$path_binary}");
                     if (is_readable($path_binary)) {
                         Log::debug("{$tag}: Found readable binary at path {$path_binary}");
                         $binaryString = file_get_contents($path_binary);
                         $entity->set($import_field_key, $binaryString);
                     } else {
                         Log::debug("{$tag}: No readable binary at path {$path_binary}");
                     }
                     break;
                 default:
                     $entity->set($import_field_key, $import_field_value);
                     break;
             }
             // END: switch($field->getType())
         }
         // END: for($i=0; $i<count($csv_header_row); $i++)
         switch ($import_mode) {
             case EntityImporter::$IMPORT_MODE_UPDATE:
                 try {
                     $entityDAO->update($entity);
                     $stat["updates"]++;
                 } catch (Exception $e) {
                     Log::warning("{$tag}: Caught Exception: " . $e->getMessage());
                     $stat["errors"]++;
                 }
                 break;
             case EntityImporter::$IMPORT_MODE_INSERT:
                 try {
                     $entityDAO->insert($entity);
                     $stat["inserts"]++;
                 } catch (Exception $e) {
                     Log::warning("{$tag}: Caught Exception: " . $e->getMessage());
                     $stat["errors"]++;
                 }
                 break;
         }
     }
     // END: while( ($row = $csv->nextRow()) !== FALSE )
     return $stat;
 }
 Log::debug("* formSignature = {$formSignature}");
 Log::debug("* entityId = {$entityId}");
 // Decode parameters submitted with request
 if (!empty($params)) {
     $params = ParamEncoder::decode($params);
 } else {
     $params = array();
 }
 try {
     // Create a Data Access Object for the Entity
     $entityBP = BlueprintReader::read($entitySignature);
     $dao = new EntityDAO($entityBP);
     // Create an Entity
     if ($entityId != 0) {
         // Update an existing entity
         $entity = $dao->load($entityId);
     } else {
         // Create a new Entity
         $entity = $entityBP->build();
     }
     // Initialize Entity with User Inputs
     $entity->init($_POST);
     // Note: (at this point in execution)
     // If the entity contains binary fields, their values have been initialized from the $_POST array; and not the $_FILES array
     // Even if an existing entity was loaded with a binary value, that value could have been overriden with a value from $_POST
     // Validate
     $errs = EntityValidator::validate($entity);
     // Process file uploads for binary types
     foreach ($entityBP->fields() as $field) {
         if ($field->getDataType() == "binary") {
             $key = $field->getKey();
 $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);
 echo "<strong>Using session supplied timezone (-07:00)</strong><br/><br/>";
 Session::user("_TIMEZONE_OFFSET", "-07:00");
 unset($accessDAO);
 $accessDAO = new EntityDAO($accessBP);
 $session_timezone_offset = Session::user("_TIMEZONE_OFFSET");
 // Load updated Access
 $access = $accessDAO->load($access_id);
 echo "Loaded updated Access with description '" . $access->get("description") . "'<br/>";
 echo "modified = " . $access->getModified() . "<br/>";
 echo "time = " . $access->get("time") . "<br/>";
 echo "<br/>";
 // Update the Access
 $access->set("time", date("Y-m-d H:i:s"));
 $access->set("description", "Updated Timezone (Session Based) Test");
 $accessDAO->update($access);
 echo "Updated Access with id {$access_id}<br/>";
 echo "<br/>";
 unset($access);
 // Load updated Access
 $access = $accessDAO->load($access_id);
 echo "Loaded updated Access with description '" . $access->get("description") . "'<br/>";
 echo "modified = " . $access->getModified() . "<br/>";
 private function test_access_list_rule_ownership($rule, $identity, $listRows)
 {
     $tag = "Guardian: test_access_list_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 " . count($listRows) . " list item(s) from keyPath '{$keyPath}'");
     if ($ownershipTable == $identityTable) {
         // TEST FOR DIRECT OWNERSHIP BY IDENTITY (of each listRow)
         foreach ($listRows as $row) {
             $entityId = $row->id;
             $owner_id = $row->columns["{$ownershipField}"];
             Log::debug("{$tag}: Testing list rows {$entityId} with {$ownershipField}={$owner_id}");
             if ($owner_id == $identity) {
                 Log::debug("{$tag}: {$ownershipTable} with ID {$entityId} is owned by requestor");
                 // Continue testing next row
             } else {
                 Log::debug("{$tag}: {$ownershipTable} with ID {$entityId} is not owned by requestor");
                 return false;
             }
         }
         // If processing has reached this point, all rows are owned by the requestor
         Log::debug("{$tag}: All {$ownershipTable} rows are owned by requestor");
         return true;
     } else {
         if (!empty($ownerIdentifier)) {
             // TEST FOR INDIRECT OWNERSHIP BY AFFILIATION (of each listRow)
             // Lookup the "group" that owns this record (in $keyPath)
             // Verify that the requestor is Affiliated with this group
             try {
                 // Query for the "affiliations" of "identity" from "ownerIdentifierTable"
                 // The results from this query can be reused to test ownership of each listRow
                 $ownerIdentifierBP = BlueprintReader::read($ownerIdentifierTable . ".entity.xml");
                 $ownerIdentifierDAO = new EntityDAO($ownerIdentifierBP);
                 // "id's" are not defined as "fields" in a blueprint; therefore if "identityField" references an "id", we should do a direct load
                 if ($identityField == "id") {
                     $affiliationObj = $ownerIdentifierDAO->load($identity);
                     $affiliations = array($affiliationObj);
                 } else {
                     $affilations = $ownerIdentifierDAO->findWhere("{$identityField}", "{$identity}");
                 }
                 foreach ($listRows as $row) {
                     $entityId = $row->id;
                     $owner_id = $row->columns["{$ownershipField}"]->value;
                     Log::debug("Rule requires ownership through affiliation with '{$owner_id}' from keyPath '{$ownerIdentifier}'");
                     // NOTE:
                     // "affiliations" may be defined in such a way that each identity has multiple affiliations
                     // check each matching affiliation for this identity
                     if (count($affiliations > 0)) {
                         for ($i = 0; $i < count($affiliations); $i++) {
                             $affiliationObj = $affiliations[0];
                             $_affiliation = $affiliationObj->get($ownerIdentifierField);
                             if ($_affiliation == $owner_id) {
                                 Log::debug("{$tag}: Found matching affiliation '{$_affiliation}' for entityId={$entityId}");
                                 // Continue checking the next listRow
                             }
                         }
                     } else {
                         Log::debug("{$tag}: No affiliation records matching this identity");
                         return false;
                     }
                 }
                 // END: foreach($listRow as $row)
                 // If processing has reached this point, all rows are owned by the requestor
                 Log::debug("{$tag}: All {$ownershipTable} rows are owned by the requestor");
                 return true;
             } catch (Exception $e) {
                 Log::error("{$tag}: Caught: " . $e->getMessage());
                 return false;
             }
         } else {
             Log::error("{$tag}: Invalid <Ownership> rule");
             return false;
         }
     }
 }