<?xml version="1.0" encoding="UTF-8"?>
<maxdQL version="0.1" name="ListATableWithAttributesPHPed" >
	<description>List the entries for a given table and their attributes</description>
	
	<pfunction id="formatBrowseSimple" comment="formats a list of entries from a browse output" method="xml" >
	   <![CDATA[	
			/*
			* 2 magic variables here: $input and $output
			* $input is the DOM xml object that needs parsing
			* $output is the string that will be read by the engine at the end
			*/
			
			// import into simplexml from dom for easy parsing
			$simpleXML = simplexml_import_dom($input);
			
			// create a new dom
			$domNew = new DOMDocument();
			$root = $domNew->createElement("result");
			$rootDom = $domNew->appendChild($root);
			
			// cycle through the simplexml and make a new DOM xml for output
			foreach ($simpleXML as $nodeName => $node) {        
				foreach ($node as $subNodeName => $subNode) {
						
					$item = $domNew->createElement("item");
					$itemDom = $rootDom->appendChild($item);
					
					$name = (string)$subNode["Name"];
					$value = (string)$subNode;
					
					$newAttribute = $item->setAttribute("Name", $name);
						
					$links = array();
					foreach ($subNode as $subSubNodeName => $subSubNode) {
						$sname = (string)$subSubNode["Name"];
						$svalue = (string)$subSubNode;

						if ($subSubNodeName == "attribute") {
								$sname = str_replace(".", "_", $sname);
								$sname = str_replace(" ", "", $sname);
								$newAttribute = $item->setAttribute($sname, $svalue);
							} else {
							$links[$subSubNodeName][] = $sname;
						}
					}
					foreach ($links as $tableName => $linkArray) {
						$val = "";
						$comma = "";
						foreach ($linkArray as $link) {
							$val .= $comma . $link;
							$comma = ",";
						}
						
						$newAttribute = $item->setAttribute($tableName, $val);
					}
				}
			}
			/*
			* the pfunction's attribute method="xml", so it's expecting a DOM back 
			* (not a string)
			*/
			$output = $domNew;
		]]>
	</pfunction>
	
	<arguments type="user">  
		<var name="TableName" comment="the table name you wish to retrieve entries for" />
	</arguments>
	
	<query id="1" name="ListTable" comment="list entries in a table" type="maxdBrowse" >
		<table uref="user" name="TableName" />
		<action>browse</action>
		<ids>*</ids>
		<attributes>yes</attributes>
	</query>
	
	<query id="2" name="DisplayResults" type="export" >
		<table pref="formatBrowseSimple" processResultID="1" >
			<var uref="user" name="TableName" />
		</table>
	</query>

</maxdQL>
