<?php
function fn_relatedi_arc($aql)
{
	$list = $aql->Consume(3);
	
	//echo 'Related To It';
	
	$ids = $list[2]->value;
	$rel = $list[1]->value;
	$dir = $list[0]->value;
		
	if (!is_array($rel))
	{
		$rel = array($rel);
	}
	//print_r($list);
	
	global $db;
	//$rel = $rel;	
	$existing = array();
	
	$mt = microtime(true);
		
	$extra = "";
	if (count($existing) > 0) 
	{
		$extra = " AND childasset IN (".implode(",",$existing).')';
	}
	
	$apool = array();
	
	foreach($ids as $id)
	{
		$apool[] = $id;
	}
	
    if ($dir == 'down')
	{
		$query = $db->query("SELECT childasset FROM assetrelclosures WHERE relationship IN (".implode(',',$rel).") AND parentasset IN (".implode(',',$ids).")".$extra);
		
		while($row = $query->fetch(PDO::FETCH_ASSOC)) 
		{
			$apool[] = $row['childasset'];
		}
	}
	else
	{
		$query = $db->query("SELECT parentasset FROM assetrelclosures WHERE relationship IN (".implode(',',$rel).") AND childasset IN (".implode(',',$ids).")".$extra);
		
		while($row = $query->fetch(PDO::FETCH_ASSOC)) 
		{
			$apool[] = $row['parentasset'];
		}
	}

	
	$a = new AQLStackElement();
	$a->typename = "assetlist";
	$a->islist = true;
	$a->value = $apool;
	array_push($aql->stack,$a);

}
?>