<?php

// Includes
require_once 'class.stdModule.php';

// Defines
define('REG_ATT_TYPE_NORMAL', 0);
define('REG_ATT_TYPE_EMAIL', 1);
define('REG_ATT_TYPE_NAME', 2);

define('REG_HANDLE_TYPE_EMAIL', 1);
define('REG_HANDLE_TYPE_DATABASE', 2);
define('REG_HANDLE_TYPE_BOTH', 3);

define('REG_RDR_HEADER', 1);
define('REG_RDR_JAVASCRIPT', 2);
define('REG_RDR_TEMPLATE', 3);

define('REG_ERROR_INVALID_CODE', 100);
define('REG_ERROR_ORG_ID', 101);
define('REG_ERROR_NO_TCC', 110);
define('REG_ERROR_CALLER', 111);
define('REG_ERROR_NO_XSL', 115);
define('REG_ERROR_MBR_AUTHORIZATION', 120);
define('REG_ERROR_GRP_AUTHORIZATION', 121);

// Presentation settings
define('REG_PUBLISH_NOT', 		0);
define('REG_PUBLISH_LIST', 		1);
define('REG_PUBLISH_DETAIL', 	2);
define('REG_PUBLISH_BOTH', 		3);

// XSL Publish Types
define('REG_XSL_PUBLISH_LIST', 	1);
define('REG_XSL_PUBLISH_DETAIL',2);




class Register extends stdModule {

	var $_ctrl;


	/*
	 * Constructor
	 */
	function Register() {

		// Init
		$this->stdModule('creg0100');

		// Default templates
		$this->_settings->templates->registers		= 'registers.tpl';
		$this->_settings->templates->register		= 'register.tpl';
		$this->_settings->templates->reaction		= 'reaction.tpl';
		$this->_settings->templates->screen			= 'screen.tpl';
		$this->_settings->templates->form			= 'form.tpl';

		$this->_variables->public->checkvalues		= array('Y','');

		// HTML Controls
		require_once 'htmlcontrols-1.0/class.htmlcontrols.php';
		$this->_ctrl = new htmlControls ($this->_variables->public->lng_code, $this->_settings->general->paths->virtual->style.'controls.css');

	}


	/*
	 * Print a bunch of attributes as defined in the manager
	 *
	 * @param $code		Defines which form to print.
	 */
	function printNewMessage($code) {

		global $globalSettings;

		// Initial checks
		if (empty($code)) {
			$this->triggerError(REG_ERROR_INVALID_CODE);
			return false;
		}

		if (!is_numeric($this->_variables->public->org_id)) {
			$this->triggerError(REG_ERROR_ORG_ID);
			return false;
		}

		// NOTE:
		// frm_auth_members defines if the form is public(0) of private(1)
		// frm_auth_groups == 1 means that this form has active authorization on groups

		// Get form record
		$rst = $this->_db->Query("
			select
				frm_id as id,
				frm_title as title,
				frm_uri as uri,
				frm_uli as uli,
				frm_auth_members as private,
				frm_auth_groups as uses_authorization,
				frm_eml_email,
				frm_eml_confirm,
				frm_verification,
				frm_uploads as uploads
			from
				tbl_reg_forms
			where
				".(is_numeric($code) ? "frm_id = '".$code."'" : "frm_code = '".$this->_db->db_escape_string($code)."'")." and
				frm_org_id = ".$this->_variables->public->org_id." and
				frm_lng_code = '".$this->_variables->public->lng_code."'");

		$frm_id = $rst->Row('id');
		$uploads = $rst->Row('uploads');
		$frm_row = $rst->Row();
		$rst->Close();

		// Form doesn't exist
		if (!is_numeric($frm_id)) {
			$this->triggerError(REG_ERROR_INVALID_CODE);
			return false;
		}

		// Private form called from public area
		if (!is_numeric($this->_variables->public->usr_id) && ($frm_row['private'] == 1 || $frm_row['uses_authorization'] == 1)) {
			$this->triggerError(REG_ERROR_MBR_AUTHORIZATION);
			return false;
		}

		// Check form authorization
		if ($frm_row['uses_authorization'] == 1 && !$this->_isAuthorizedForGroup($frm_id)) {
			$this->triggerError(REG_ERROR_GRP_AUTHORIZATION);
			return false;
		}

		// Clear previous results
		$this->_smrt->clear_all_assign();

		// Assign global template variables
		$this->assignTemplateGlobals();

		// Send form
		if ($_POST['frm_send'] == 'pressed' && is_numeric($_POST['frm_id'])) {

			// Get rea_id
			$loop = true;
			while($loop) {

				// Create def id
				$rea_id = rand(1, 9999999999);

				// Check if def id is unique
				$rs = $this->_db->Query("SELECT rea_id FROM tbl_reg_reactions WHERE rea_id=".$rea_id);
				$loop = (!$rs->EOF());
				$rs->Close();

			}

			// Get form (XML format)
			$form = &$this->_getAttributeForm($_POST['frm_id'], $rea_id);

			// Save reaction
			$this->_db->Execute("
				insert into tbl_reg_reactions (
					rea_id,
					rea_frm_id,
					rea_usr_id,
					rea_usr_name,
					rea_usr_email,
					rea_form,
					rea_status
				) values (
					".$rea_id.",
					".$_POST['frm_id'].",
					".(is_numeric($this->_variables->public->usr_id) ? $this->_variables->public->usr_id : "NULL").",
					".(isset($_POST['rea_name']) ? "'".$this->_db->db_escape_string($_POST['rea_att'][$_POST['rea_name']])."'" : "NULL").",
					".(isset($_POST['rea_email']) ? "'".$this->_db->db_escape_string($_POST['rea_att'][$_POST['rea_email']])."'" : "NULL").",
					'".$this->_db->db_escape_string($form)."',
					".$frm_row['frm_verification']."
					)");

			// Save files
			if (is_array($_FILES['ufiles'])) {

				foreach($_FILES['ufiles']["error"] as $id => $err) {

					if (!$err) {

	                	// Read the temp file
	                	$this->_db->Execute("INSERT INTO tbl_reg_rea_uploads (
												upl_rea_id,
												upl_mimetype,
												upl_name,
												upl_size,
												upl_content,
												upl_changedate,
												upl_createdate
												) VALUES (
												".$rea_id.",
												'".addslashes($_FILES['ufiles']["type"][$id])."',
												'".addslashes($_FILES['ufiles']["name"][$id])."',
												".$_FILES['ufiles']["size"][$id].",
												'".addslashes(file_get_contents($_FILES['ufiles']["tmp_name"][$id]))."',
												now(),
												now())");

					}

				}

			}


			// Send email
			if ($frm_row['frm_eml_email'] != '' || $frm_row['eml_eml_confirm'] != '') {

				// Transform xml form to html
				$xh = xslt_create();
				xslt_set_encoding($xh, "ISO-8859-1");
				$form = xslt_process($xh, 'arg:xmldata', $this->_settings->paths->absolute.'style/reaction_html.xsl', NULL, array('xmldata' => "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>\n".$form));
				xslt_free($xh);

				// Get posted user name and address
				if (isset($_POST['rea_email']) && !empty($_POST['rea_att'][$_POST['rea_email']])) {

					$email_address = $_POST['rea_att'][$_POST['rea_email']];
					$email_name = $_POST['rea_att'][$_POST['rea_name']];

				}


				// Send normal email
				if ($frm_row['frm_eml_email']) {

					$err = $this->_tcc->doCall("SEND_EMAIL", array(
																$frm_row['frm_eml_email'],
																$this->_variables->public->org_id,
																$this->_variables->public->usr_id,
																array(
																	'FORM'			=> $form
																),
																'debug'		=> false,
																'address'	=> array(
																					'replyto' 		=> $email_address,
																					'replytoname'	=> $email_name,
																					'from' 			=> $email_address,
																					'fromname'		=> $email_name
																				)
															), $call_result);

				}

				// Send confirmation email
				if ($frm_row['eml_eml_confirm']) {

					$err = $this->_tcc->doCall("SEND_EMAIL", array(
																$frm_row['eml_eml_confirm'],
																$this->_variables->public->org_id,
																$this->_variables->public->usr_id,
																array(
																	'FORM'			=> $form
																),
																'debug'		=> false,
																'address'	=> array(
																					'to' 		=> $email_address,
																					'toname'	=> $email_name
																				)
															), $call_result);

				}

			}

			// Log a form is sent (module use because the pageview is done by the redirecting module)
			$this->logThis('FORM_SENT', $frm_id);

			// Redirect
			if (!empty($frm_row['uli'])) {

				// Get ULI
				$frm_row['uli'] = $this->_tcc->getFormattedHyperLink($frm_row['uli']);

				// Redirect using javascript
				if ($this->_settings->redirectmethod == REG_RDR_JAVASCRIPT) {

					echo "<script language=\"javascript\" type=\"text/javascript\">window.location.href='".$frm_row['uli']['location']."';</script>";

				// Redirect using a template
				} elseif ($this->_settings->redirectmethod == REG_RDR_TEMPLATE) {

					$this->_smrt->assign('form', $frm_row);
					$this->_smrt->display($this->_settings->templates->sent);

				// Redirect using headers
				} else {

					header('Location: '.$frm_row['uli']['location']);

				}

			// Redirect using a template
			} else {

				header('Location: /reg/'.$frm_id.'/');

			}

			return true;

		}

		// Get article and assign form to template
		$frm_row['data'] 		= &$this->_getAttributeForm($frm_id);
		$frm_row['uri']			= $this->_tcc->getResourceByURI($frm_row['uri']);
		$frm_row['open']		= '<form name="frm_'.$frm_id.'" action="" method="POST" enctype="multipart/form-data">';
		$frm_row['close']		= '<input type="hidden" id="frm_send" name="frm_send" value=""><input type="hidden" id="frm_id" name="frm_id" value="'.$frm_id.'"></form>';
		$frm_row['javascript']	= '<script language="javascript" type="text/javascript" src="'.$globalSettings->general->paths->virtual->js.'creg0100.js"></script><script language="javascript">var upload_max = '.($uploads - 1).'; window.setTimeout(\'addrow();\', 100);</script>';
//mail('ted.koch@amgate.com', 'lhv', $globalSettings->general->paths->virtual->js);
		$frm_row['submit']		= 'submitForm(document.forms[\'frm_'.$frm_id.'\'], \'frm_send\');';

		// Log a form is opened
		$this->logThis('REGISTER_FORM', $frm_id);

		// Assign some form functionality
		$this->_smrt->assign_by_ref('form', $frm_row);

		// Display
		$this->_smrt->display($this->_settings->templates->screen);
		return true;

	}


	/*
	 * Fetches an attribute form using templates
	 * @param $frm_id	The form's id.
	 * @param $rea_id	If the id is given it's indicates the form has been sent. If it has we don't need controls or personalization but we do need to include the posted variables.
	 */
	function &_getAttributeForm($frm_id, $rea_id = false) {

		$return = false;

		if (is_numeric($rea_id)) {

			// Get form values
			$rsd = $this->_db->Query("SELECT frm_title FROM tbl_reg_forms WHERE frm_id=".$frm_id);
			$return = "<reaction>\n\t<date>".date("Y-m-d H:i:s")."</date>\n\t<form><![CDATA[".$rsd->Row('frm_title')."]]></form>\n\t<id>".$rea_id."</id>\n\t<attributes>\n";
			$rsd->Close();

		}

		// Get attributes
		$rsa = $this->_db->Query("
			select
				att_id as id,
				att_fieldlabel as label,
				att_fieldlength as length,
				att_fieldtype as type,
				att_mandatory as mandatory,
				att_help as help,
				att_prs_type as ptype,
				att_prs_field as pfield
			from
				tbl_reg_attributes
			where
				att_frm_id = ".$frm_id."
			order by
				att_order, att_fieldlabel");

		while($att_row = $rsa->Row()) {

			$flags = 0;
			$argv = array();
			$options = false;
			$nodes = array();
			$att_name = 'rea_att['.$rsa->Row('id').']';

			// Get attribute options
			$opt = $this->_db->Query("
				select
					opt_id,
					opt_label,
					opt_default
				from
					tbl_reg_att_options
				where
					opt_att_id = '".$rsa->Row('id')."'
				order by
					opt_order, opt_label");

			while($opt->Row()) {

				if ($rsa->Row('type') == 'olv') {

					$nodes[$opt->Row('opt_id')]->label = $opt->Row('opt_label');
					$nodes[$opt->Row('opt_id')]->name = 'rea_att['.$rsa->Row('id').']['.$opt->Row('opt_id').']';
					$nodes[$opt->Row('opt_id')]->parent = 'root';
					if ($opt->Row('opt_default')) $nodes[$opt->Row('opt_id')]->checked = true;
					if ($_POST['rea_olv_'.$rsa->Row('id')][$opt->Row('opt_id')] == $this->_variables->public->checkvalues[0]) $att_row['value'][] = $opt->Row('opt_label');

				} elseif ($rsa->Row('type') != 'dsp') {

					$argv['options'][$opt->Row('opt_id')] = $opt->Row('opt_label');

					if ($opt->Row('opt_default')) {
						if ($rsa->Row('type') == 'chk2') $argv['default'][$opt->Row('opt_id')] = $this->_variables->public->checkvalues[0];
						else $argv['default'] = $opt->Row('opt_id');
					}

					if (is_array($_POST['rea_att'][$rsa->Row('id')])) {
						if ($_POST['rea_att'][$rsa->Row('id')][$opt->Row('opt_id')] == $this->_variables->public->checkvalues[0]) $att_row['value'][] = $opt->Row('opt_label');
					} else  {

						if ($_POST['rea_att'][$rsa->Row('id')] == $opt->Row('opt_id') || $_POST['rea_att'][$rsa->Row('id')] == 'Y') $att_row['value'] = $opt->Row('opt_label');

					}

				}

				$opt->MoveNext();

			}
			$opt->Close();

			if (!is_numeric($rea_id)) {

				// Set special control type values
				switch ($rsa->Row('type')) {

					case 'chk': case 'chk2': case 'lst2':
						$argv['checkvalues'] = $this->_variables->public->checkvalues;
						break;

					case 'cmb':
						$flags = CTRL_READONLY;
						break;

					case 'tme':
						$argv['showhours'] = true;
						$argv['showminutes'] = true;
						$argv['showseconds'] = true;
						break;

					case 'olv':
						$att_name = 'rea_olv_'.$rsa->Row('id');
						$nodes['root']->label = $rsa->Row('label');
						$nodes['root']->name = 'olv_opt_root';
						$nodes['root']->parent = 0;

						$argv = new stdClass();
						$argv->indent = 15;
						$argv->checkable = true;
						$argv->checkvalues[0] = $this->_variables->public->checkvalues[1];
						$argv->checkvalues[1] = $this->_variables->public->checkvalues[0];
						$argv->autoexpand = true;
						$argv->nodes = $nodes;
						break;

				}

				// Create control
				$att_row['control'] = $this->_ctrl->{$rsa->Row('type')}($rsa->Row('label'), $att_name, $rsa->Row('pfield'), $rsa->Row('length'), $argv, '', ($rsa->Row('mandatory') ? CTRL_MANDATORY | $flags : $flags));

				// If the field should contain the user's name of email address add an additional hidden field to indicate this.
				if ($rsa->Row('ptype') == REG_ATT_TYPE_NAME) {
					$att_row['control'] .= "<input type=\"hidden\" name=\"rea_name\" value=\"".$rsa->Row('id')."\">";
				} elseif ($rsa->Row('ptype') == REG_ATT_TYPE_EMAIL) {
					$att_row['control'] .= "<input type=\"hidden\" name=\"rea_email\" value=\"".$rsa->Row('id')."\">";
				}

			}

			// Get POSTed value
			if (!isset($att_row['value']) && $rsa->Row('type') != 'dsp') $att_row['value'] = (is_string($_POST['rea_att'][$rsa->Row('id')]) ? stripslashes($_POST['rea_att'][$rsa->Row('id')]) : $_POST['rea_att'][$rsa->Row('id')]);

			// Append values
			if (is_numeric($rea_id)) {

				$return .= "\t\t<attribute>\n\t\t\t<id>".$att_row['id']."</id>\n\t\t\t<type>".$att_row['type']."</type>\n\t\t\t<ptype>".$att_row['ptype']."</ptype>\n\t\t\t<mandatory>".$att_row['mandatory']."</mandatory>\n\t\t\t<label><![CDATA[".$att_row['label']."]]></label>\n";

				if (is_array($att_row['value'])) {
					$return .= "\t\t\t<answers>\n";
					foreach ($att_row['value'] as $value) if ($value) $return .= "\t\t\t\t<answer><![CDATA[".$value."]]></answer>\n";
					$return .= "\t\t\t</answers>\n";
				} else {
					if ($att_row['type'] != 'dsp') $return .= "\t\t\t<answer><![CDATA[".$att_row['value']."]]></answer>\n";
				}

				$return .= "\t\t</attribute>\n";

			} else {

				$this->_smrt->append('attributes', $att_row);

			}


			$rsa->MoveNext();

		}

		$rsa->Close();

		// Close XML data
		$return .= "\t</attributes>\n</reaction>\n";

		// Personalize fields
		if (!is_numeric($rea_id)) {

			// Fetch form template
			$this->_smrt->assign('sent', is_numeric($rea_id));
			$return = $this->_smrt->fetch($this->_settings->templates->form);

			if (!is_numeric($rea_id)) {
				$err = $this->_tcc->doCall('PERSONALIZE', array('text' => $return, 'variables' => array('org_id' => $this->_variables->public->org_id, 'usr_id' => $this->_variables->public->usr_id, 'mod_code' => $this->_moduleCode, 'frm_id' => $frm_id)), $tmp_data);
				if ($err->id == ICH_RESPONSE_OK) $return = &$tmp_data;
				$return = preg_replace('/\[PTC.*?\]/i', "", $return);
			}

			$this->_smrt->clear_assign('definition');
			$this->_smrt->clear_assign('attributes');
			$this->_smrt->clear_assign('sent');

		}

		return $return;

	}


	// Checks if an interchange object is available
	function _checkTCC() {

		if (!is_object($this->_tcc)) {
			$this->triggerError(REG_ERROR_NO_TCC, null, null, null, null, E_WARNING);
			return false;
		}

		return true;

	}

	// Get user groups
	function &_getUserGroups($usr_id) {

		$groups = false;
		if (is_numeric($usr_id)) {

			// No interchange object, return
			if (!$this->_checkTCC()) return false;

			// Get usergroups
			$err = $this->_tcc->doCall('GET_USERGROUPS', array('org_id' => $this->_variables->public->org_id, 'usr_id' => $usr_id, 'codes' => false), $groups);

			// Interchange error, return
			if ($err->id != ICH_RESPONSE_OK) {
				$this->triggerError(REG_ERROR_CALLER, $err->msg, null, null, null, E_WARNING);
				return false;
			}

		}

		return $groups;

	}


	// Check authorization
	function _isAuthorized($membership_check, $group_membership_check, $frm_id) {

		if (!$membership_check) {

			return true;

		} else {

			if (is_numeric($this->_variables->public->usr_id)) {

				if (!$group_membership_check) {

					return true;

				} else {

					return $this->_isAuthorizedForGroup($frm_id);

				}

			} else {

				return false;

			}

		}

	}

	// Check group authorization
	function _isAuthorizedForGroup($frm_id) {

		// No interchange object, return
		if (!$this->_checkTCC()) return false;

		// Get authorization
		$return = false;
		$err = $this->_tcc->doCall('GET_AUTH', array($this->_variables->public->org_id, 'GRP', 'tbl_reg_forms', $frm_id), $auth);

		// Interchange error, return
		if ($err->id != ICH_RESPONSE_OK) {
			$this->triggerError(REG_ERROR_CALLER, $err->msg, null, null, null, E_WARNING);
			return false;
		}

		// Get usergroups
		$groups = &$this->_getUserGroups($this->_variables->public->usr_id);

		// Both return values are OK
		if (is_array($auth) && is_array($groups)) {

			// Equalize the arrays
			$auth = array_keys($auth);
			$groups = array_keys($groups);

			// Check by intersecting the group and auth arrays
			$chk = array_intersect($auth, $groups);
			$return = (is_array($chk) && count($chk) > 0);

		}

		return $return;

	}


	function printMessage($rea_id) {

		// Form doesn't exist
		if (!is_numeric($rea_id)) {
			$this->triggerError(REG_ERROR_INVALID_CODE);
			return false;
		}

		// Get the attribute id that should be shown in the list
		$rs = $this->_db->Query("SELECT att_id FROM tbl_reg_attributes INNER JOIN tbl_reg_forms ON att_frm_id=frm_id AND att_publish IN (".REG_PUBLISH_DETAIL.", ".REG_PUBLISH_BOTH.") INNER JOIN tbl_reg_reactions ON rea_frm_id=frm_id AND rea_id=".$rea_id);
		while (!$rs->EOF()) {
			$ids .= '|'.$rs->Row('att_id');
			$rs->MoveNext();
		}
		$rs->Close();

		// Get and assign register info
		$rs = $this->_db->Query("SELECT * FROM tbl_reg_reactions INNER JOIN tbl_reg_forms ON rea_frm_id=frm_id AND rea_id=".$rea_id." LEFT JOIN tbl_reg_xsls ON frm_xsl_id_detail=xsl_id AND xsl_publish_type=".REG_XSL_PUBLISH_DETAIL);

		// Assign some variables to template
		$register['frm_id'] = $rs->Row('frm_id');
		$register['frm_title'] = $rs->Row('frm_title');
		$this->_smrt->assign('register', $register);

		// Check if there is a xsl connected
		if (!$rs->Row('xsl_id')) {
			$this->triggerError(REG_ERROR_NO_XSL);
			$rs->Close();
			return false;
		}

		// Create xslt object
		$xh = xslt_create();
		xslt_set_encoding($xh, "ISO-8859-1");
		$table = xslt_process($xh, 'arg:xmldata', 'arg:xsldata', NULL, array('xmldata' => $rs->Row('rea_form'), 'xsldata' => $rs->Row('xsl_text')), array('ids' => $ids));
		xslt_free($xh);

		$rs->Close();

		// Assign table to template
		$this->_smrt->assign('table', $table);

		// Get the files connected to the message
		$rs = $this->_db->Query("SELECT upl_id as id, upl_mimetype as type, upl_name as name FROM tbl_reg_rea_uploads WHERE upl_rea_id=".$rea_id);
		while (!$rs->EOF()) {

			$this->_smrt->append('files', $rs->Row());
			$rs->MoveNext();

		}
		$rs->Close();

		// Log a register is opened
		$this->logThis('REACTION', $rea_id);

		// Assign globals to template
		$this->assignTemplateGlobals();

		// Parse template
		$this->_smrt->display($this->_settings->templates->reaction);
		$this->_smrt->clear_all_assign();


	}

	function printRegister($frm_id) {

		// Form doesn't exist
		if (!is_numeric($frm_id)) {
			$this->triggerError(REG_ERROR_INVALID_CODE);
			return false;
		}

		// Get and assign register info
		$rs = $this->_db->Query("SELECT * FROM tbl_reg_forms LEFT JOIN tbl_reg_xsls ON frm_xsl_id_list=xsl_id AND  xsl_publish_type=".REG_XSL_PUBLISH_LIST." WHERE frm_id=".$frm_id);

		// Private form called from public area
		if (!is_numeric($this->_variables->public->usr_id) && ($rs->row('frm_auth_members') == 1 || $rs->row('frm_auth_groups') == 1)) {
			$this->triggerError(REG_ERROR_MBR_AUTHORIZATION);
			$rs->Close();
			return false;
		}

		// Check form authorization
		if ($frm_row['uses_authorization'] == 1 && !$this->_isAuthorizedForGroup($frm_id)) {
			$this->triggerError(REG_ERROR_GRP_AUTHORIZATION);
			$rs->Close();
			return false;
		}

		// Check if there is a xsl connected
		if (!$rs->Row('xsl_id')) {
			$this->triggerError(REG_ERROR_NO_XSL);
			$rs->Close();
			return false;
		}

		$xsl = $rs->Row('xsl_text');
		$register['frm_id'] = $rs->Row('frm_id');
		$register['frm_title'] = $rs->Row('frm_title');
		$this->_smrt->assign('register', $register);
		$rs->Close();

		// Get the reactions
		$reactions = "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>\n<reactions>\n";
		$rs = $this->_db->Query("SELECT * FROM tbl_reg_reactions WHERE rea_frm_id=".$frm_id." AND rea_status=0 ORDER BY rea_createdate DESC");
		while (!$rs->EOF()) {
			$reactions .= $rs->Row('rea_form');
			$rs->MoveNext();
		}
		$reactions .= "</reactions>";
		$rs->Close();


		// Get the attribute id that should be shown in the list
		$rs = $this->_db->Query("SELECT att_id FROM tbl_reg_attributes WHERE att_publish IN (".REG_PUBLISH_LIST.", ".REG_PUBLISH_BOTH.") AND att_frm_id=".$frm_id);
		while (!$rs->EOF()) {
			$ids .= '|'.$rs->Row('att_id');
			$rs->MoveNext();
		}
		$rs->Close();

		// Create xslt object
		$xh = xslt_create();
		xslt_set_encoding($xh, "ISO-8859-1");

		$table = xslt_process($xh, 'arg:xmldata', 'arg:xsldata', NULL, array('xmldata' => $reactions, 'xsldata' => $xsl), array('ids' => $ids));

		xslt_free($xh);

		// Assign table to template
		$this->_smrt->assign('table', $table);

		// Log a register is opened
		$this->logThis('REGISTER', $frm_id);

		// Assign globals to template
		$this->assignTemplateGlobals();

		// Parse template
		$this->_smrt->display($this->_settings->templates->register);
		$this->_smrt->clear_all_assign();

	}


	function printRegisters() {

		$rs = $this->_db->Query("SELECT * FROM tbl_reg_forms ORDER BY frm_title ASC");
		while (!$rs->EOF()) {

			if ($this->_isAuthorized($rs->Row('frm_auth_members'), $rs->Row('frm_auth_groups'), $rs->Row('frm_id'))) $this->_smrt->append('registers', $rs->Row());
			$rs->MoveNext();

		}
		$rs->Close();

		// Log register list is opened
		$this->logThis('REGISTER_LIST', 0);

		// Assign globals to template
		$this->assignTemplateGlobals();

		// Parse template
		$this->_smrt->display($this->_settings->templates->registers);
		$this->_smrt->clear_all_assign();

	}


	function downloadFile($upl_id) {

		// Download doesn't exist
		if (!is_numeric($upl_id)) {
			$this->triggerError(REG_ERROR_INVALID_CODE);
			return false;
		}


		$rs = $this->_db->Query("SELECT * FROM tbl_reg_rea_uploads WHERE upl_id=".$upl_id);
		Header("Pragma: public");
		Header("Expires: ".gmdate("D, d M Y H:i:s", mktime() + 2678400));
		Header("Cache-Control: max-age=3600, must-revalidate, post-check=0, pre-check=0");
		Header('Accept-Ranges: bytes');
      	Header("Content-type: ".$rs->Row('upl_mimetype'));
  		Header("Content-Length: ".$rs->Row('upl_size'));
  		Header("Content-Disposition: filename=".$rs->Row('upl_name'));
		Header("Connection: close");
        echo $rs->Row('upl_content');
		$rs->Close();

		die();

	}

}

?>