public static function authenticate($entitySignature, $identityKey, $resourceKey, $authKey, $identity, $resource)
 {
     $tag = "Sentry::authenticate()";
     Log::notice("{$tag}: <entitySignature={$entitySignature}, {$identityKey}={$identity}, {$resourceKey}={$resource}>");
     // TODO: (?) check users session for cached permissions
     try {
         $sentryBP = BlueprintReader::read($entitySignature);
         $entityDAO = new EntityDAO($sentryBP);
         $keys = array("{$identityKey}", "{$resourceKey}");
         $values = array("{$identity}", "{$resource}");
         $matches = $entityDAO->findWhere($keys, $values);
         if (0 == count($matches)) {
             Log::debug("{$tag}: No permission record was found.");
             return false;
         } else {
             if (1 == count($matches)) {
                 // found a matching permission record
                 $entity = $matches[0];
                 // extract value of $authKey field
                 $authValue = $entity->get($authKey);
                 // test for boolean values
                 if (empty($authValue) || $authValue == 0 || $authValue == "0" || strtoupper($authValue) == "NO" || strtoupper($authValue) == "FALSE") {
                     Log::debug("{$tag}: {$identityKey} {$identity} does not have permission to access {$resourceKey} {$resource}");
                     return false;
                 } else {
                     if ($authValue == 1 || $authValue == "1" || strtoupper($authValue) == "YES" || strtoupper($authValue) == "TRUE") {
                         Log::debug("{$tag}: {$identityKey} {$identity} has permission to access {$resourceKey} {$resource}");
                         return true;
                     }
                 }
             } else {
                 if (1 < count($matches)) {
                     Log::warning("{$tag}: ! More than one permission record was found.");
                     return false;
                 }
             }
         }
     } catch (Exception $e) {
         Log::error("{$tag}: " . $e->getMessage());
         return false;
     }
 }
	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();
			}
		}
	}
// either a single id or an array of ids
if (!empty($entitySignature) && !empty($entityId)) {
    Log::debug("* entitySignature = {$entitySignature}");
    Log::debug("* entityId = {$entityId}");
    if (is_array($entityId)) {
        $ids = implode(", ", $entityId);
        Log::debug("* entityId[] = {$ids}");
    } else {
        // force single entityId into an array
        $array = array($entityId);
        // update pointer
        $entityId = $array;
    }
    try {
        $bp = BlueprintReader::read($entitySignature);
        $dao = new EntityDAO($bp);
        $failures = 0;
        foreach ($entityId as $id) {
            $xmlDelete = $xmlAttempts->addChild("delete");
            $xmlDelete->addAttribute("signature", $entitySignature);
            $xmlDelete->addAttribute("id", $id);
            try {
                // Make sure the user has permission to perform this action
                if (BPConfig::$guardian_enable !== true || Guardian::authorize(Session::user(BPConfig::$guardian_identity_session_key), "DELETE", $bp->getKey(), $id)) {
                    $dao->delete($id);
                    $xmlDelete->addChild("status", "success");
                    $xmlDelete->addChild("message", "Entity was deleted successfully.");
                    $xmlDelete->addChild("html", "Deleted " . $entitySignature . " with ID#" . $id);
                } else {
                    Log::warning("* Guardian denied access to delete " . $bp->getKey() . " with ID {$id}");
                    $failures++;
 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;
 }
             $message = "Login throttle has prevented another attempt.";
         } else {
             // Check Password
             if (Login::checkPassword($entity_blueprint, $login_key, $passwd_key, $login, $passwd)) {
                 Login::start($login, $domain);
                 // ! TODO: inject BPConfig::$guardian_identity_session_key into the users session
                 $status = "success";
                 $message = "Login Successful.";
             } else {
                 $status = "error";
                 $message = "Username or password is incorrect.";
                 Log::warning("* Failed login attempt");
                 if (BPConfig::$login_throttle_enabled) {
                     // Record a failed login attempt
                     $failedLoginAttemptBP = BlueprintReader::read(BPConfig::$login_throttle_blueprint);
                     $failedLoginAttemptDAO = new EntityDAO($failedLoginAttemptBP, "+0:00");
                     $fla = $failedLoginAttemptBP->build();
                     $fla->set(BPConfig::$login_throttle_field_id, $member_id);
                     $fla->set("time", gmdate("Y-m-d H:i:s"));
                     $failedLoginAttemptDAO->insert($fla);
                 }
             }
         }
     } else {
         // Login not found
         $status = "error";
         $message = "Username or password is incorrect.";
     }
     break;
 case "logout":
     $domain = @$_POST["domain"];
		}

		try
		{
			echo "Creating Session database.<br/>";
			$sessionBP = BlueprintReader::read("Session.entity.xml");
			$sessionDAO = new EntityDAO($sessionBP);
			$sessionDAO->create();
		}
		catch(Exception $e)
		{
			echo "Exception: " . $e->getMessage() . "<br>";
		}
		
		try
		{
			echo "Creating AuthFailedLoginAttempts database.<br/>";
			$loginBP = BlueprintReader::read("AuthFailedLoginAttempts.entity.xml");
			$loginDAO = new EntityDAO($loginBP);
			$loginDAO->create();
		}
		catch(Exception $e)
		{
			echo "Exception: " . $e->getMessage() . "<br>";
		}
		
		?>
	
	</body>
</html>
if (!empty($renderer) && !empty($entitySignature)) {
    Log::debug("* view = {$view}");
    Log::debug("* renderer = {$renderer}");
    Log::debug("* entitySignature = {$entitySignature}");
    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);
             $action = "edit";
         }
         $content[] = array("type" => "file", "data" => "alter.frm");
     }
     break;
 case "delete":
     $blueprintSignature = $_REQUEST["blueprint"];
     $content[] = array("type" => "html", "data" => "<h1>Blueprints</h1>");
     if (empty($blueprintSignature)) {
         // do nothing
     } else {
         $blueprint_file_path = BPConfig::$path_blueprints . $blueprintSignature;
         try {
             $bp = BlueprintReader::read($blueprintSignature);
             // drop database table
             $sqlDAO = new EntityDAO($bp);
             $sqlDAO->drop();
             // delete blueprint file
             unlink($blueprint_file_path);
             $html = "<div class='notice'>Blueprint \"{$blueprintSignature}\" was deleted.</div>";
             $content[] = array("type" => "html", "data" => "{$html}");
         } catch (Exception $e) {
             $html = "An error occured deleting blueprint: " . $e->getMessage();
             $content[] = array("type" => "html", "data" => "{$html}");
         }
         $content[] = array("type" => "file", "data" => "index.inc");
     }
     break;
 case "xml":
     $blueprintSignature = $_REQUEST["blueprint"];
     if (empty($blueprintSignature)) {
 $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/>";
 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;
 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;
         }
     }
 }
 // Retrieve request parameters
 $domain = @$_GET["domain"];
 $destination = @$_GET["destination"];
 // Init Defaults
 if (empty($destination)) {
     $destination = "/";
 }
 // Debug
 Log::debug("* domain = {$domain}");
 Log::debug("* destination = {$destination}");
 if (Login::loggedIn($domain)) {
     // Retrieve 'login' from users Login Session
     $login = Login::who($domain);
     // Retrieve member data
     $memberBP = BlueprintReader::read("Member.entity.xml");
     $memberDAO = new EntityDAO($memberBP);
     $matches = $memberDAO->findWhere("login", $login);
     if (count($matches) > 0) {
         $member = $matches[0];
         // Add data to the users session
         Session::user("member_id", $member->getId());
         // Required by Guardian
         // Forward user
         Log::debug("* REDIRECTING TO: {$destination}\n");
         header("location: {$destination}");
         exit;
     } else {
         // Should never happen, since users password was just checked
         Log::error("* Member with login '{$login}' was not found.");
         $content->addHtml("<strong>Login Error</strong><br/>");
         $content->addHtml("Message: Member with login '{$login}' was not found.");