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 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;
     }
 }
 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;
 }
             $status = "error";
             $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":
		}

		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>
<?php

require_once "Config.php";
require_once "Blueprint.php";
require_once "BlueprintReader.php";
require_once "EntityExporter.php";
?>
<h1>EntityExporter Test</h1>
<?

// extract config variables
$path_blueprints = BPConfig::$path_blueprints;

$blueprint = $_GET["blueprint"];
$path = $path_blueprints . $blueprint . ".xml";

echo "Path = $path<br>";

$bp = BlueprintReader::read($path);

$csv = EntityExporter::exportCsv($bp);
$csv = nl2br($csv);

echo "<pre>";
echo "$csv";
echo "</pre>";

?>
echo "using ListDrafter<br/>";
DraftingDesk::renderList("ListDrafter", "Member.entity.xml");
echo "using ListUlDrafter<br/>";
echo "using ListUlDrafter with a ListBlueprint<br/>";
DraftingDesk::renderList("ListUlDrafter", "Member.entity.xml", "Member.Directory.list.xml");
$params = array();
$params["order"] = "lname DESC";
$params["filters"] = array();
$params["filters"]["filter_fname_like"] = "Be";
DraftingDesk::renderList("ListTableDrafter", "Member.entity.xml", null, $params);
echo "<br/><br/><hr/><br/><br/>";
echo "Test FilterDrafter<br/><br/>";
$drafter = new FilterDrafter($entityBP);
$html = $drafter->render();
echo $html;
echo "<br/><br/>";
echo "Test Reading a Filter Blueprint<br/><br/>";
$filterBP = BlueprintReader::read("Member.Name.filter.xml");
echo "Test class instance..<br>";
if ($filterBP instanceof FilterBlueprint) {
    echo "filterBP is an instance of FilterBlueprint<br><br>";
} else {
    echo "filterBP is not an instance of FilterBlueprint<br><br>";
}
echo "Test FilterDrafter with a FilterBlueprint<br/><br/>";
$drafter = new FilterDrafter($entityBP, $filterBP);
$html = $drafter->render();
echo $html;
echo "<br/><br/><hr/><br/><br/>";
echo "Testing DraftingDesk, renderFilter()...<br/>";
DraftingDesk::renderFilter("FilterDrafter", "Member.entity.xml", "Member.Name.filter.xml");
 // Decode params
 $params = ParamEncoder::decode($params);
 /*
 // Read Blueprints
 */
 // Read Entity Blueprint
 try {
     $entityBP = BlueprintReader::read($entitySignature);
 } catch (Exception $e) {
     Log::error("{$tag}: Caught Exception reading entity blueprint " . $entitySignature);
     // TODO: return error response; do not continue
 }
 // Read Filter Blueprint
 if ($filterSignature != null) {
     try {
         $filterBP = BlueprintReader::read($filterSignature);
     } catch (Exception $e) {
         Log::error("{$tag}: Caught Exception reading filter blueprint " . $filterSignature);
     }
 } else {
     $filterBP = null;
 }
 /*
 // Use a FilterDrafter to initialize filters from Blueprints
 // Note: FilterPostDrafter overrides FilterDrafter.initFilterValues()
 // 				to read filter values from $_POST array
 */
 $filterPostDrafter = new FilterPostDrafter($entityBP, $filterBP);
 $filters = $filterPostDrafter->filters();
 $filterKeys = array_keys($filters);
 Log::debug(count($filters) . " returned from FilterPostDrafter");
$config_timezone_offset = BPConfig::$timezone_offset;
echo "Config timezone offset: ";
if (!empty($config_timezone_offset)) {
    echo "{$config_timezone_offset}";
} else {
    echo "EMPTY";
}
echo "<br/><br/>";
$default_timezone_offset = BPTimezone::UTC;
echo "Default timezone offset: {$default_timezone_offset}";
echo "<br/><br/>";
echo "<hr/>";
echo "<h1>Timezone Conversion</h1>";
echo "<strong>Using BPConfig::\$timezone_offset of " . BPConfig::$timezone_offset . "</strong><br/><br/>";
try {
    $accessBP = BlueprintReader::read("Access.entity.xml");
    $accessDAO = new EntityDAO($accessBP);
    // Debug
    echo "Local time is " . date("Y-m-d H:i:s") . "<br/>";
    echo "Universal time is " . gmdate("Y-m-d H:i:s") . "<br/>";
    echo "<br/>";
    // Build new Access
    $access = $accessBP->build();
    $access->set("member_id", 1);
    $access->set("time", date("Y-m-d H:i:s"));
    $access->set("resource_id", 1);
    $access->set("description", "Timezone Test");
    // Insert new Access
    $access_id = $accessDAO->insert($access);
    echo "Inserted new Access with id {$access_id}<br/>";
    unset($access);
 public static function renderReport($renderer, $reportBlueprintSignature, $params = null)
 {
     $tag = "DraftingDesk::renderReport()";
     Log::debug("{$tag} <{$renderer}, {$reportBlueprintSignature}>");
     // Read Report Blueprint
     try {
         $reportBlueprint = BlueprintReader::read($reportBlueprintSignature);
     } catch (Exception $e) {
         Log::error("{$tag}: Caught Exception reading report blueprint " . $reportBlueprintSignature);
         throw $e;
     }
     // create an instance of the requested ReportDrafter class
     loadClass($renderer);
     $reportDrafter = new $renderer($reportBlueprint, $params);
     // send render message
     return $reportDrafter->render();
 }
 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/>");
 public static function blueprints($blueprintType = "entity", $entityBlueprintSignature = null)
 {
     $tag = "BlueprintEnumerator::blueprints()";
     Log::debug("{$tag}: <{$blueprintType}, {$entityBlueprintSignature}>");
     try {
         $signatures = self::signatures($blueprintType, $entityBlueprintSignature);
         $blueprints = array();
         foreach ($signatures as $s) {
             try {
                 $bp = BlueprintReader::read($s);
                 $blueprints["{$s}"] = $bp;
             } catch (Exception $e) {
                 Log::error("{$tag}: Caught Exception");
                 throw $e;
             }
         }
         return $blueprints;
     } catch (Exception $e) {
         Log::error("{$tag}: Caught Exception");
         throw $e;
     }
 }
$type = @$_GET["type"];
if (empty($type)) {
    $type = "csv";
}
if (empty($blueprint)) {
    echo "ERROR: Missing required input \"blueprint\"";
    exit;
} else {
    $blueprintSignature = $blueprint;
    // extract filters from Session
    // NOTE: requires enhancement to Session.php to allow retrieval from a named page
    // $filters = Session::namedPage($page, "filters");
    $filters = array();
    try {
        // read blueprint
        $bp = BlueprintReader::read($blueprintSignature);
        $bpKey = $bp->getKey();
        // get export data
        $tar = EntityExporter::export($bp, $type, $where, $filters);
    } catch (Exception $e) {
        // return err to ajax client
        echo "Caught Exception: " . $e->getMessage();
        exit;
    }
    // create filename
    $filename = $bpKey . ".{$type}";
    // set headers
    header("Content-Type: application/x-gzip");
    header("Content-Disposition: attachment; filename={$filename}");
    header("Content-Transfer-Encoding: binary");
    echo "{$tar}";
$entityId = @$_POST["entityId"];
// 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}");
$blueprint = $_GET["blueprint"];
$field = $_GET["field"];
$id = $_GET["id"];
if (empty($action)) {
    $action = "file";
}
if (empty($blueprint) || empty($field) || empty($id)) {
    Log::error("Missing a required input");
    echo "ERROR: Missing a required input.";
    exit;
} else {
    Log::debug("... " . $blueprint . "." . $field . ": " . $id);
    try {
        // load the blueprint
        $blueprint_file_name = $blueprint . ".entity.xml";
        $bp = BlueprintReader::read($blueprint_file_name);
        // lookup the field
        $f = $bp->get($field);
        // retrieve meta data for file creation
        $mimeType = $f->getMimeType();
        // retrieve the binary as a string
        $binaryString = Binary::getString($blueprint, $field, $id);
    } catch (Exception $e) {
        Log::error($e->getMessage());
        echo "EXCEPTION: " . $e->getMessage();
        exit;
    }
    switch ($action) {
        case "file":
            // create filename
            $ext = Binary::extension($mimeType);