PageRenderTime 375ms CodeModel.GetById 120ms app.highlight 150ms RepoModel.GetById 51ms app.codeStats 3ms

/administrator/components/com_rsform/helpers/rsform.php

https://bitbucket.org/organicdevelopment/joomla-2.5
PHP | 3182 lines | 2568 code | 464 blank | 150 comment | 480 complexity | bdd0af366eb5ce7b1bb8307504cf05dd MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/**
   3* @version 1.4.0
   4* @package RSform!Pro 1.4.0
   5* @copyright (C) 2007-2011 www.rsjoomla.com
   6* @license GPL, http://www.gnu.org/copyleft/gpl.html
   7*/
   8
   9defined('_JEXEC') or die('Restricted access');
  10
  11//PRODUCT INFO - DO NOT CHANGE
  12DEFINE('_RSFORM_PRODUCT','RSform!Pro');
  13DEFINE('_RSFORM_VERSION','1.4.0');
  14DEFINE('_RSFORM_KEY','2XKJ3KS7JO');
  15DEFINE('_RSFORM_COPYRIGHT','&copy;2007-2012 www.rsjoomla.com');
  16DEFINE('_RSFORM_LICENSE','GPL Commercial License');
  17DEFINE('_RSFORM_AUTHOR','<a href="http://www.rsjoomla.com" target="_blank">www.rsjoomla.com</a>');
  18DEFINE('_RSFORM_WEBSITE','http://www.rsjoomla.com/');
  19if(!defined('_RSFORM_REVISION'))
  20	DEFINE('_RSFORM_REVISION','44');
  21
  22JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_rsform'.DS.'tables');
  23
  24$cache =& JFactory::getCache('com_rsform');
  25$cache->clean();
  26
  27$lang =& JFactory::getLanguage();
  28$lang->load('com_rsform', JPATH_ADMINISTRATOR, 'en-GB', true);
  29$lang->load('com_rsform', JPATH_ADMINISTRATOR, $lang->getDefault(), true);
  30$lang->load('com_rsform', JPATH_ADMINISTRATOR, null, true);
  31
  32// Create the Legacy adapter
  33$GLOBALS['RSadapter'] = RSFormProHelper::getLegacyAdapter();
  34
  35// Legacy function -- RSgetValidationRules()
  36function RSgetValidationRules()
  37{
  38	return RSFormProHelper::getValidationRules();
  39}
  40
  41function _modifyResponsiveTemplate()
  42{
  43	$buffer = JResponse::getBody();
  44	$buffer = trim($buffer);
  45	
  46	$line = reset(RSFormProHelper::explode($buffer));
  47	if (strtolower($line) != '<!doctype html>')
  48	{
  49		$buffer = str_replace($line, '<!doctype html>', $buffer);
  50		JResponse::setBody($buffer);
  51	}
  52}
  53
  54class RSFormProHelper
  55{
  56	function isJ16()
  57	{
  58		static $compatible = null;
  59		if (is_null($compatible))
  60		{
  61			jimport('joomla.version');
  62			$version = new JVersion();
  63			$compatible = $version->isCompatible('1.6.0');
  64		}
  65		
  66		return $compatible;
  67	}
  68	
  69	function isJ170()
  70	{
  71		static $compatible = null;
  72		if (is_null($compatible))
  73		{
  74			jimport('joomla.version');
  75			$version = new JVersion();
  76			$compatible = version_compare($version->getShortVersion(), '1.7.0', 'eq');
  77		}
  78		
  79		return $compatible;
  80	}
  81	
  82	function getDate($date)
  83	{
  84		if (RSFormProHelper::isJ16())
  85			return JHTML::_('date', $date, 'Y-m-d H:i:s');
  86		else
  87			return JHTML::_('date', $date, '%Y-%m-%d %H:%M:%S');
  88	}
  89	
  90	function getLegacyAdapter()
  91	{
  92		static $adapter;
  93		if (empty($adapter))
  94		{
  95			require_once JPATH_ADMINISTRATOR.DS.'components'.DS.'com_rsform'.DS.'helpers'.DS.'legacy.php';
  96			$adapter = new RSAdapter();
  97		}
  98		
  99		return $adapter;
 100	}
 101	
 102	function getComponentId($name, $formId=0)
 103	{
 104		static $cache;
 105		if (!is_array($cache))
 106			$cache = array();
 107			
 108		if (empty($formId))
 109		{
 110			$formId = JRequest::getInt('formId');
 111			if (empty($formId))
 112			{
 113				$post   = JRequest::getVar('form');
 114				$formId = (int) @$post['formId'];
 115			}
 116		}
 117		
 118		if (!isset($cache[$formId][$name]))
 119			$cache[$formId][$name] = RSFormProHelper::componentNameExists($name, $formId);
 120		
 121		return $cache[$formId][$name];
 122	}
 123	
 124	function checkValue($setvalue, $array)
 125	{
 126		if (!is_array($array))
 127			$array = RSFormProHelper::explode($array);
 128		
 129		if (strlen($setvalue))
 130			foreach ($array as $k => $v)
 131			{
 132				@list($value, $text) = explode("|", $v, 2);
 133				if ($value == $setvalue)
 134					$array[$k] = $v.'[c]';
 135			}
 136		
 137		return implode("\n", $array);
 138	}
 139	
 140	function createList($results, $value='value', $text='text')
 141	{
 142		$list = array();
 143		if (is_array($results))
 144			foreach ($results as $result)
 145				if (is_object($result))
 146					$list[] = $result->{$value}.'|'.$result->{$text};
 147				elseif (is_array($result))
 148					$list[] = $result[$value].'|'.$result[$text];
 149		
 150		return implode("\n", $list);
 151	}
 152	
 153	function displayForm($formId, $is_module=false)
 154	{
 155		$mainframe =& JFactory::getApplication();
 156		
 157		$db = JFactory::getDBO();
 158		$db->setQuery("SELECT Published, FormTitle, MetaTitle, MetaDesc, MetaKeywords, ShowThankyou FROM #__rsform_forms WHERE FormId='".(int) $formId."'");
 159		$form = $db->loadObject();
 160		
 161		if (empty($form) || !$form->Published)
 162		{
 163			JError::raiseWarning(500, JText::_('_NOT_EXIST'));
 164			return;
 165		}
 166		
 167		$lang 		  = RSFormProHelper::getCurrentLanguage($formId);
 168		$translations = RSFormProHelper::getTranslations('forms', $formId, $lang);
 169		if ($translations)
 170			foreach ($translations as $field => $value)
 171			{
 172				if (isset($form->$field))
 173					$form->$field = $value;
 174			}
 175		
 176		$doc =& JFactory::getDocument();
 177		if (!$is_module)
 178		{
 179			if ($form->MetaDesc)
 180				$doc->setMetaData('description', $form->MetaDesc);
 181			if ($form->MetaKeywords)
 182				$doc->setMetaData('keywords', $form->MetaKeywords);
 183			if ($form->MetaTitle)
 184				$doc->setTitle($form->FormTitle);
 185		}
 186		
 187		$session =& JFactory::getSession();
 188		$formparams = $session->get('com_rsform.formparams.'.$formId);
 189		
 190		// Form has been processed ?
 191		if ($formparams && $formparams->formProcessed)
 192		{
 193			// Must show Thank You Message
 194			if ($form->ShowThankyou)
 195			{
 196				return RSFormProHelper::showThankYouMessage($formId);
 197			}
 198			
 199			// Clear
 200			$session->clear('com_rsform.formparams.'.$formId);
 201			
 202			// Must show small message
 203			$mainframe->enqueueMessage(JText::_('RSFP_THANKYOU_SMALL'));
 204		}
 205		
 206		// Must process form
 207		$post = JRequest::getVar('form', array(), 'post', 'none', JREQUEST_ALLOWRAW);
 208		if (isset($post['formId']) && $post['formId'] == $formId)
 209		{
 210			$invalid = RSFormProHelper::processForm($formId);
 211			// Did not pass validation - show the form
 212			if ($invalid)
 213			{
 214				$mainframe->triggerEvent('rsfp_f_onBeforeShowForm');
 215				return RSFormProHelper::showForm($formId, $post, $invalid);
 216			}
 217		}
 218		
 219		// Default - show the form
 220		$mainframe->triggerEvent('rsfp_f_onBeforeShowForm');
 221		return RSFormProHelper::showForm($formId);
 222	}
 223	
 224	function WYSIWYG($name, $content, $hiddenField, $width, $height, $col, $row)
 225    {
 226    	$editor =& JFactory::getEditor();		
 227		$params = array('relative_urls' => '0', 'cleanup_save' => '0', 'cleanup_startup' => '0', 'cleanup_entities' => '0');
 228		
 229		if (!RSFormProHelper::isJ16())
 230		{
 231			$content = $editor->display($name, $content , $width, $height, $col, $row, true, $params);
 232			
 233			if (RSFormProHelper::getConfig('global.editor'))
 234			{
 235				$doc =& JFactory::getDocument();
 236				$head = $doc->getHeadData();
 237			
 238				$editor_name = $editor->get('_name');
 239				
 240				if (!empty($editor_name))
 241					switch ($editor_name)
 242					{
 243						// Hack to remove the save_callback function from TinyMCE
 244						// save_callback strips the current site URL from any href/src it finds
 245						case 'tinymce':
 246						$data['custom'] = str_replace('save_callback : "TinyMCE_Save",', '', $head['custom']);
 247						break;
 248						
 249						// Hack to automatically set relative_urls and remove_script_host to false from JCE
 250						case 'jce':
 251						if (strpos($head['script']['text/javascript'], 'relative_urls: false,') === false && strpos($head['script']['text/javascript'], 'remove_script_host: false,') === false)
 252						{
 253							preg_match('#inlinepopups_skin: "(\w+)",#i', $head['script']['text/javascript'], $matches);
 254							$head['script']['text/javascript'] = str_replace($matches[0], $matches[0]."\r\n\t\t\t".'relative_urls: false,'."\r\n\t\t\t".'remove_script_host: false,', $head['script']['text/javascript']);
 255							$data['script'] = $head['script'];
 256						}
 257						break;
 258					}
 259				
 260				if (!empty($data))
 261					$doc->setHeadData($data);
 262			}
 263		}
 264		else
 265		{
 266			$id = trim(substr($name, 4), '][');
 267			$content = $editor->display($name, $content , $width, $height, $col, $row, true, $id, null, null, $params);
 268		}
 269		
 270		return $content;
 271    }
 272	
 273	function getValidationRules()
 274	{
 275		require_once JPATH_SITE.DS.'components'.DS.'com_rsform'.DS.'helpers'.DS.'validation.php';
 276		$results = get_class_methods('RSFormProValidations');
 277		return implode("\n",$results);
 278	}
 279	
 280	function readConfig($force=false)
 281	{
 282		static $rsformpro_config;
 283		
 284		if (!is_object($rsformpro_config) || $force)
 285		{
 286			$rsformpro_config = new stdClass();
 287			
 288			$db =& JFactory::getDBO();
 289			$db->setQuery("SELECT * FROM `#__rsform_config`");
 290			$config = $db->loadObjectList();
 291			if (!empty($config))
 292				foreach ($config as $config_item)
 293					$rsformpro_config->{$config_item->SettingName} = $config_item->SettingValue;
 294		}
 295		
 296		return $rsformpro_config;
 297	}
 298	
 299	function getConfig($name = null)
 300	{
 301		$config = RSFormProHelper::readConfig();
 302		if ($name != null)
 303		{
 304			if (isset($config->$name))
 305				return $config->$name;
 306			else
 307				return false;
 308		}
 309		else
 310			return $config;
 311	}
 312	
 313	function genKeyCode()
 314	{
 315		$code = RSFormProHelper::getConfig('global.register.code');
 316		return md5($code._RSFORM_KEY);
 317	}
 318	
 319	function componentNameExists($componentName, $formId, $currentComponentId=0)
 320	{
 321		$db = JFactory::getDBO();
 322		
 323		if ($componentName == 'formId')
 324			return true;
 325		
 326		$componentName = $db->getEscaped($componentName);
 327		$formId = (int) $formId;
 328		$currentComponentId = (int) $currentComponentId;
 329		
 330		$query  = "SELECT c.ComponentId FROM #__rsform_properties p LEFT JOIN #__rsform_components c ON (p.ComponentId = c.ComponentId)";
 331		$query .= "WHERE c.FormId='".$formId."' AND p.PropertyName='NAME' AND p.PropertyValue='".$componentName."'";
 332		if ($currentComponentId)
 333			$query .= " AND c.ComponentId != '".$currentComponentId."'";
 334		
 335		$db->setQuery($query);
 336		$exists = $db->loadResult();
 337		
 338		return $exists;
 339	}
 340	
 341	function copyComponent($sourceComponentId, $toFormId)
 342	{
 343		$sourceComponentId 	= (int) $sourceComponentId;
 344		$toFormId 			= (int) $toFormId;
 345		$db 				= JFactory::getDBO();
 346		
 347		$db->setQuery("SELECT * FROM #__rsform_components WHERE ComponentId='".$sourceComponentId."'");
 348		$component = $db->loadObject();
 349		if (!$component)
 350			return false;
 351	
 352		//get max ordering
 353		$db->setQuery("SELECT MAX(`Order`)+1 FROM #__rsform_components WHERE FormId = '".$toFormId."'");
 354		$component->Order = $db->loadResult();
 355		
 356		$db->setQuery("INSERT INTO #__rsform_components SET `FormId`='".$toFormId."', `ComponentTypeId`='".$component->ComponentTypeId."', `Order`='".$component->Order."',`Published`='".$component->Published."'");
 357		$db->query();
 358		$newComponentId = $db->insertid();
 359		
 360		$db->setQuery("SELECT * FROM #__rsform_properties WHERE ComponentId='".$sourceComponentId."'");
 361		$properties = $db->loadObjectList();
 362		
 363		foreach ($properties as $property)
 364		{
 365			if ($property->PropertyName == 'NAME' && $toFormId == $component->FormId)
 366			{
 367				$property->PropertyValue .= ' copy';
 368			
 369				while (RSFormProHelper::componentNameExists($property->PropertyValue, $toFormId))
 370					$property->PropertyValue .= mt_rand(0,9);
 371			}
 372			
 373			$db->setQuery("INSERT INTO #__rsform_properties SET ComponentId='".$newComponentId."', PropertyName='".$db->getEscaped($property->PropertyName)."', PropertyValue='".$db->getEscaped($property->PropertyValue)."'");
 374			$db->query();
 375		}
 376		
 377		// copy language
 378		$db->setQuery("SELECT * FROM #__rsform_translations WHERE `reference`='properties' AND `reference_id` LIKE '".$sourceComponentId.".%'");
 379		$translations = $db->loadObjectList();
 380		foreach ($translations as $translation)
 381		{
 382			$reference_id = $newComponentId.'.'.end(explode('.', $translation->reference_id, 2));
 383			
 384			$db->setQuery("INSERT INTO #__rsform_translations SET `form_id`='".$toFormId."', `lang_code`='".$db->getEscaped($translation->lang_code)."', `reference`='properties', `reference_id`='".$db->getEscaped($reference_id)."', `value`='".$db->getEscaped($translation->value)."'");
 385			$db->query();
 386		}
 387		
 388		return $newComponentId;
 389	}
 390	
 391	function getCurrentLanguage($formId=null)
 392	{
 393		$mainframe =& JFactory::getApplication();
 394		$lang 	   = JFactory::getLanguage();
 395		
 396		$session   =& JFactory::getSession();
 397		$formId    = !$formId ? JRequest::getInt('formId') || JRequest::getInt('FormId') : $formId;
 398		
 399		// editing in backend ?
 400		if ($mainframe->isAdmin())
 401		{
 402			if (JRequest::getVar('task') == 'submissions.edit')
 403			{
 404				$cid = JRequest::getVar('cid', array());
 405				if (is_array($cid))
 406					$cid = (int) @$cid[0];
 407					
 408				$db =& JFactory::getDBO();
 409				$db->setQuery("SELECT `Lang` FROM #__rsform_submissions WHERE SubmissionId='".$cid."'");
 410				$language = $db->loadResult();
 411				
 412				return $language;
 413			}
 414			
 415			return $session->get('com_rsform.form.'.$formId.'.lang', $lang->getTag());
 416		}
 417		// frontend
 418		else
 419		{
 420			return $lang->getTag();
 421		}
 422	}
 423	
 424	function getComponentProperties($components)
 425	{
 426		$db = JFactory::getDBO();
 427		
 428		if (is_numeric($components))
 429		{
 430			$componentId = (int) $components;
 431		
 432			//load component properties
 433			$db->setQuery("SELECT `PropertyName`, `PropertyValue` FROM #__rsform_properties WHERE `ComponentId`='".$componentId."'");
 434			$properties = $db->loadObjectList();
 435		
 436			//set up data array with component properties
 437			$data = array();
 438			foreach($properties as $property)
 439				$data[$property->PropertyName] = $property->PropertyValue;
 440			$data['componentId'] = $componentId;
 441		
 442			unset($properties);
 443			
 444			$db->setQuery("SELECT FormId FROM #__rsform_components WHERE ComponentId='".$componentId."'");
 445			$formId = $db->loadResult();
 446			
 447			// language
 448			$lang 		  = RSFormProHelper::getCurrentLanguage($formId);
 449			$translations = RSFormProHelper::getTranslations('properties', $formId, $lang);
 450			foreach ($data as $property => $value)
 451			{
 452				$reference_id = $componentId.'.'.$property;
 453				if (isset($translations[$reference_id]))
 454					$data[$property] = $translations[$reference_id];
 455			}
 456			
 457			return $data;
 458		}
 459		elseif (is_array($components))
 460		{
 461			$componentIds = array();
 462			foreach ($components as $componentId)
 463			{
 464				if (is_object($componentId) && !empty($componentId->ComponentId))
 465					$componentIds[] = (int) $componentId->ComponentId;
 466				elseif (is_array($componentId) && !empty($componentId['ComponentId']))
 467					$componentIds[] = (int) $componentId['ComponentId'];
 468				else
 469					$componentIds[] = (int) $componentId;
 470			}
 471			if (!empty($componentIds))
 472			{
 473				$db->setQuery("SELECT `PropertyName`, `PropertyValue`, `ComponentId` FROM #__rsform_properties WHERE `ComponentId` IN (".implode(',', $componentIds).")");
 474				$results = $db->loadObjectList();
 475				
 476				$all_data = array();
 477				foreach ($results as $result)
 478					$all_data[$result->ComponentId][$result->PropertyName] = $result->PropertyValue;
 479				
 480				foreach ($all_data as $componentId => $properties)
 481					$all_data[$componentId]['componentId'] = $componentId;
 482				
 483				$db->setQuery("SELECT FormId FROM #__rsform_components WHERE ComponentId='".$componentIds[0]."'");
 484				$formId = $db->loadResult();
 485				
 486				// language
 487				$lang 		  = RSFormProHelper::getCurrentLanguage($formId);
 488				$translations = RSFormProHelper::getTranslations('properties', $formId, $lang);
 489				foreach ($all_data as $componentId => $properties)
 490				{
 491					foreach ($properties as $property => $value)
 492					{
 493						$reference_id = $componentId.'.'.$property;
 494						if (isset($translations[$reference_id]))
 495							$properties[$property] = $translations[$reference_id];
 496					}
 497					$all_data[$componentId] = $properties;
 498				}
 499				
 500				return $all_data;
 501			}
 502		}
 503		
 504		return false;
 505	}
 506	
 507	function isCode($value)
 508	{
 509		$RSadapter = RSFormProHelper::getLegacyAdapter();
 510		
 511		if (strpos($value, '<code>') !== false)
 512			return eval($value);
 513		
 514		return $value;
 515	}
 516	
 517	function showPreview($formId, $componentId, $data)
 518	{
 519		$mainframe =& JFactory::getApplication();
 520		
 521		$formId = (int) $formId;
 522		$componentId = (int) $componentId;
 523		
 524		// Legacy
 525		$r = array();
 526		$r['ComponentTypeName'] = $data['ComponentTypeName'];
 527		
 528		$out ='';
 529		
 530		//Trigger Event - rsfp_bk_onBeforeCreateComponentPreview
 531		$mainframe->triggerEvent('rsfp_bk_onBeforeCreateComponentPreview',array(array('out'=>&$out,'formId'=>$formId,'componentId'=>$componentId,'ComponentTypeName'=>$r['ComponentTypeName'],'data'=>$data)));
 532		
 533		static $passedPageBreak;
 534		
 535		switch($r['ComponentTypeName'])
 536		{
 537			case 'textBox':
 538			{
 539				$defaultValue = RSFormProHelper::isCode($data['DEFAULTVALUE']);
 540				
 541				$out.='<td>'.$data['CAPTION'].'</td>';
 542				$out.='<td><input type="text" value="'.RSFormProHelper::htmlEscape($defaultValue).'" size="'.$data['SIZE'].'" /></td>';
 543			}
 544			break;
 545			
 546			case 'textArea':
 547			{
 548				$defaultValue = RSFormProHelper::isCode($data['DEFAULTVALUE']);	
 549				
 550				$out.='<td>'.$data['CAPTION'].'</td>';
 551				$out.='<td><textarea cols="'.$data['COLS'].'" rows="'.$data['ROWS'].'">'.RSFormProHelper::htmlEscape($defaultValue).'</textarea></td>';
 552			}
 553			break;
 554			
 555			case 'selectList':
 556			{
 557				$out.='<td>'.$data['CAPTION'].'</td>';
 558				$out.='<td><select '.($data['MULTIPLE']=='YES' ? 'multiple="multiple"' : '').' size="'.$data['SIZE'].'">';
 559				
 560				$items = RSFormProHelper::isCode($data['ITEMS']);
 561				$items = str_replace(array("\r\n", "\r"), "\n", $items);
 562				$items = explode("\n",$items);
 563				
 564				$special = array('[c]', '[g]', '[d]');
 565				
 566				foreach ($items as $item)
 567				{
 568					@list($val, $txt) = @explode('|', str_replace($special, '', $item), 2);
 569					if (is_null($txt))
 570						$txt = $val;
 571					
 572					// <optgroup>
 573					if (strpos($item, '[g]') !== false) {
 574						$out .= '<optgroup label="'.RSFormProHelper::htmlEscape($val).'">';
 575						continue;
 576					}
 577					// </optgroup>
 578					if(strpos($item, '[/g]') !== false) {
 579						$out .= '</optgroup>';
 580						continue;
 581					}
 582					
 583					$additional = '';
 584					// selected
 585					if (strpos($item, '[c]') !== false)
 586						$additional .= 'selected="selected"';
 587					// disabled
 588					if (strpos($item, '[d]') !== false)
 589						$additional .= 'disabled="disabled"';
 590					
 591					$out .= '<option '.$additional.' value="'.RSFormProHelper::htmlEscape($val).'">'.RSFormProHelper::htmlEscape($txt).'</option>';
 592				}
 593				$out.='</select></td>';
 594			}
 595			break;
 596			
 597			case 'checkboxGroup':
 598			{
 599				$i=0;
 600				
 601				$out.='<td>'.$data['CAPTION'].'</td>';
 602				$out.='<td>';
 603				
 604				$items = RSFormProHelper::isCode($data['ITEMS']);
 605				$items = str_replace(array("\r\n", "\r"), "\n", $items);
 606				$items = explode("\n",$items);
 607				
 608				$special = array('[c]', '[d]');
 609				
 610				foreach ($items as $item)
 611				{
 612					@list($val, $txt) = @explode('|', str_replace($special, '', $item), 2);
 613					if (is_null($txt))
 614						$txt = $val;
 615					
 616					$additional = '';
 617					// checked
 618					if (strpos($item, '[c]') !== false)
 619						$additional .= 'checked="checked"';
 620					// disabled
 621					if (strpos($item, '[d]') !== false)
 622						$additional .= 'disabled="disabled"';
 623					
 624					$out.='<input type="checkbox" '.$additional.' value="'.RSFormProHelper::htmlEscape($val).'" id="'.$data['NAME'].$i.'"/><label for="'.$data['NAME'].$i.'">'.$txt.'</label>';
 625					if($data['FLOW']=='VERTICAL') $out.='<br/>';
 626					$i++;
 627				}
 628				$out.='</td>';
 629
 630			}
 631			break;
 632			
 633			case 'radioGroup':
 634			{
 635				$i=0;
 636				
 637				$out.='<td>'.$data['CAPTION'].'</td>';
 638				$out.='<td>';
 639				
 640				$items = RSFormProHelper::isCode($data['ITEMS']);
 641				$items = str_replace(array("\r\n", "\r"), "\n", $items);
 642				$items = explode("\n",$items);
 643				
 644				$special = array('[c]', '[d]');
 645				
 646				foreach ($items as $item)
 647				{
 648					@list($val, $txt) = @explode('|', str_replace($special, '', $item), 2);
 649					if (is_null($txt))
 650						$txt = $val;
 651					
 652					$additional = '';
 653					// checked
 654					if (strpos($item, '[c]') !== false)
 655						$additional .= 'checked="checked"';
 656					// disabled
 657					if (strpos($item, '[d]') !== false)
 658						$additional .= 'disabled="disabled"';
 659					
 660					$out.='<input type="radio" '.$additional.' value="'.RSFormProHelper::htmlEscape($val).'" id="'.$data['NAME'].$i.'"/><label for="'.$data['NAME'].$i.'">'.$txt.'</label>';
 661					if ($data['FLOW']=='VERTICAL') $out.='<br/>';
 662					$i++;
 663				}
 664				$out.='</td>';
 665
 666			}
 667			break;
 668			
 669			case 'calendar':
 670			{
 671				$out.='<td>'.$data['CAPTION'].'</td>';
 672				$out.='<td><img src="'.JURI::root(true).'/administrator/components/com_rsform/assets/images/icons/calendar.png" /> '.JText::_('RSFP_COMP_FVALUE_'.$data['CALENDARLAYOUT']).'</td>';
 673			}
 674			break;
 675			
 676			case 'captcha':
 677			{
 678				$out.='<td>'.$data['CAPTION'].'</td>';
 679				$out.='<td>';
 680				switch (@$data['IMAGETYPE'])
 681				{
 682					default:
 683					case 'FREETYPE':
 684					case 'NOFREETYPE':
 685						$out.='<img src="index.php?option=com_rsform&amp;task=captcha&amp;componentId='.$componentId.'&amp;tmpl=component&amp;sid='.mt_rand().'" id="captcha'.$componentId.'" alt="'.$data['CAPTION'].'"/>';
 686						$out.=($data['FLOW']=='HORIZONTAL') ? '':'<br/>';
 687						$out.='<input type="text" value="" id="captchaTxt'.$componentId.'" '.$data['ADDITIONALATTRIBUTES'].' />';
 688						$out.=($data['SHOWREFRESH']=='YES') ? '&nbsp;&nbsp;<a href="" onclick="refreshCaptcha('.$componentId.',\'index.php?option=com_rsform&amp;task=captcha&amp;componentId='.$componentId.'&amp;tmpl=component\'); return false;">'.$data['REFRESHTEXT'].'</a>':'';
 689					break;
 690					
 691					case 'INVISIBLE':
 692						$out.='{hidden captcha}';
 693					break;
 694				}
 695				$out.='</td>';
 696			}
 697			break;
 698			
 699			case 'fileUpload':
 700			{
 701				$out.='<td>'.$data['CAPTION'].'</td>';
 702				$out.='<td><input type="file" /></td>';
 703			}
 704			break;
 705			
 706			case 'freeText':
 707			{
 708				$out.='<td>&nbsp;</td>';
 709				$out.='<td>'.$data['TEXT'].'</td>';
 710			}
 711			break;
 712			
 713			case 'hidden':
 714			{
 715				$out.='<td>&nbsp;</td>';
 716				$out.='<td>{hidden field}</td>';
 717			}
 718			break;
 719			
 720			case 'imageButton':
 721			{			
 722				$out.='<td>'.$data['CAPTION'].'</td>';
 723				$out.='<td>';
 724				$out.='<input type="image" src="'.RSFormProHelper::htmlEscape($data['IMAGEBUTTON']).'"/>';
 725				if($data['RESET']=='YES')
 726					$out.='&nbsp;&nbsp;<input type="image" src="'.RSFormProHelper::htmlEscape($data['IMAGERESET']).'"/>';
 727				$out.='</td>';
 728			}
 729			break;
 730			
 731			case 'button':
 732			case 'submitButton':
 733			{				
 734				$out.='<td>'.$data['CAPTION'].'</td>';
 735				
 736				if (isset($data['BUTTONTYPE']) && $data['BUTTONTYPE'] == 'TYPEBUTTON')
 737					$out.='<td><button type="button">'.RSFormProHelper::htmlEscape($data['LABEL']).'</button>';
 738				else
 739					$out.='<td><input type="button" value="'.RSFormProHelper::htmlEscape($data['LABEL']).'" />';
 740					
 741				if($data['RESET']=='YES')
 742				{
 743					if (isset($data['BUTTONTYPE']) && $data['BUTTONTYPE'] == 'TYPEBUTTON')
 744						$out.='&nbsp;&nbsp;<button type="reset">'.RSFormProHelper::htmlEscape($data['RESETLABEL']).'</button>';
 745					else
 746						$out.='&nbsp;&nbsp;<input type="reset" value="'.RSFormProHelper::htmlEscape($data['RESETLABEL']).'"/>';
 747				}
 748				$out.='</td>';
 749			}
 750			break;
 751			
 752			case 'password':
 753			{				
 754				$out.='<td>'.$data['CAPTION'].'</td>';
 755				$out.='<td><input type="password" value="'.RSFormProHelper::htmlEscape($data['DEFAULTVALUE']).'" size="'.$data['SIZE'].'"/></td>';
 756			}
 757			break;
 758			
 759			case 'ticket':
 760			{				
 761				$out.='<td>&nbsp;</td>';
 762				$out.='<td>'.RSFormProHelper::generateString($data['LENGTH'],$data['CHARACTERS']).'</td>';
 763			}
 764			break;
 765			
 766			case 'pageBreak':
 767				$out.='<td>&nbsp;</td>';
 768				$out.='<td>'.($passedPageBreak ? '<input type="button" value="'.RSFormProHelper::htmlEscape($data['PREVBUTTON']).'" />' : '').' <input type="button" value="'.RSFormProHelper::htmlEscape($data['NEXTBUTTON']).'" /></td>';
 769				$passedPageBreak = true;
 770			break;
 771			
 772			case 'rseprotickets':
 773				$out.='<td>'.$data['CAPTION'].'</td>';
 774				$out.='<td>'.JText::_('RSFP_RSEVENTSPRO_TICKETS').'</td>';
 775			break;
 776			
 777			default:
 778				$out = '<td colspan="2" style="color:#333333"><em>'.JText::_('RSFP_COMP_PREVIEW_NOT_AVAILABLE').'</em></td>';
 779			break;
 780		}
 781		
 782		//Trigger Event - rsfp_bk_onAfterCreateComponentPreview
 783		$mainframe->triggerEvent('rsfp_bk_onAfterCreateComponentPreview',array(array('out'=>&$out, 'formId'=>$formId, 'componentId'=>$componentId, 'ComponentTypeName'=>$r['ComponentTypeName'],'data'=>$data)));
 784		
 785		return $out;
 786	}
 787	
 788	function htmlEscape($val)
 789	{
 790		return htmlentities($val, ENT_COMPAT, 'UTF-8');
 791	}
 792	
 793	function explode($value)
 794	{
 795		$value = str_replace(array("\r\n", "\r"), "\n", $value);
 796		$value = explode("\n", $value);
 797		
 798		return $value;
 799	}
 800	
 801	function readFile($file, $download_name=null)
 802	{
 803		if (empty($download_name))
 804			$download_name = basename($file);
 805			
 806		$fsize = filesize($file);
 807		
 808		header("Cache-Control: public, must-revalidate");
 809		header('Cache-Control: pre-check=0, post-check=0, max-age=0');
 810		if (!preg_match('#MSIE#', $_SERVER['HTTP_USER_AGENT']))
 811			header("Pragma: no-cache");
 812		header("Expires: 0"); 
 813		header("Content-Description: File Transfer");
 814		header("Expires: Sat, 01 Jan 2000 01:00:00 GMT");
 815		if (preg_match('#Opera#', $_SERVER['HTTP_USER_AGENT']))
 816			header("Content-Type: application/octetstream"); 
 817		else 
 818			header("Content-Type: application/octet-stream");
 819		header("Content-Length: ".(string) ($fsize));
 820		header('Content-Disposition: attachment; filename="'.$download_name.'"');
 821		header("Content-Transfer-Encoding: binary\n");
 822		ob_end_flush();
 823		RSFormProHelper::readFileChunked($file);
 824		exit();
 825	}
 826	
 827	function readFileChunked($filename, $retbytes=true)
 828	{
 829		$chunksize = 1*(1024*1024); // how many bytes per chunk
 830		$buffer = '';
 831		$cnt =0;
 832		$handle = fopen($filename, 'rb');
 833		if ($handle === false) {
 834			return false;
 835		}
 836		while (!feof($handle)) {
 837			$buffer = fread($handle, $chunksize);
 838			echo $buffer;
 839			if ($retbytes) {
 840				$cnt += strlen($buffer);
 841			}
 842		}
 843		$status = fclose($handle);
 844		if ($retbytes && $status) {
 845			return $cnt; // return num. bytes delivered like readfile() does.
 846		}
 847		return $status;
 848	}
 849	
 850	function getReplacements($SubmissionId, $skip_globals=false)
 851	{
 852		// Small hack
 853		return RSFormProHelper::sendSubmissionEmails($SubmissionId, true, $skip_globals);
 854	}
 855	
 856	function sendSubmissionEmails($SubmissionId, $only_return_replacements=false, $skip_globals=false)
 857	{
 858		$db = JFactory::getDBO();
 859		$u = JFactory::getURI();
 860		$config = JFactory::getConfig();
 861		$SubmissionId = (int) $SubmissionId;
 862		$mainframe =& JFactory::getApplication();
 863		$Itemid = JRequest::getInt('Itemid');
 864		$Itemid = $Itemid ? '&amp;Itemid='.$Itemid : '';
 865		
 866		$db->setQuery("SELECT * FROM #__rsform_submissions WHERE SubmissionId='".$SubmissionId."'");
 867		$submission = $db->loadObject();
 868		
 869		$submission->values = array();
 870		$db->setQuery("SELECT FieldName, FieldValue FROM #__rsform_submission_values WHERE SubmissionId='".$SubmissionId."'");
 871		$fields = $db->loadObjectList();
 872		foreach ($fields as $field)
 873			$submission->values[$field->FieldName] = $field->FieldValue;
 874		unset($fields);
 875		
 876		$formId = $submission->FormId;
 877		$db->setQuery("SELECT * FROM #__rsform_forms WHERE FormId='".$formId."'");
 878		$form = $db->loadObject();
 879		$form->MultipleSeparator = str_replace(array('\n', '\r', '\t'), array("\n", "\r", "\t"), $form->MultipleSeparator);
 880
 881		if (empty($submission->Lang))
 882		{
 883			if (!empty($form->Lang))
 884				$submission->Lang = $form->Lang;
 885			else
 886			{
 887				$lang =& JFactory::getLanguage();
 888				$language = $lang->getDefault();
 889				$submission->Lang = $language;
 890			}
 891			$db->setQuery("UPDATE #__rsform_submissions SET Lang='".$db->getEscaped($submission->Lang)."' WHERE SubmissionId='".$submission->SubmissionId."'");
 892			$db->query();
 893		}
 894			
 895		$translations = RSFormProHelper::getTranslations('forms', $form->FormId, $submission->Lang);
 896		if ($translations)
 897			foreach ($translations as $field => $value)
 898			{
 899				if (isset($form->$field))
 900					$form->$field = $value;
 901			}
 902		
 903		$placeholders = array();
 904		$values = array();
 905		
 906		$db->setQuery("SELECT c.ComponentTypeId, p.ComponentId, p.PropertyName, p.PropertyValue FROM #__rsform_components c LEFT JOIN #__rsform_properties p ON (c.ComponentId=p.ComponentId) WHERE c.FormId='".$formId."' AND c.Published='1' AND p.PropertyName IN ('NAME', 'CAPTION', 'EMAILATTACH', 'WYSIWYG', 'ITEMS')");
 907		$components = $db->loadObjectList();
 908		$properties 	   = array();
 909		$uploadFields 	   = array();
 910		$multipleFields    = array();
 911		$textareaFields    = array();
 912		$userEmailUploads  = array();
 913		$adminEmailUploads = array();
 914		$additionalEmailUploads = array();
 915		$additionalEmailUploadsIds = array();
 916		
 917		foreach ($components as $component)
 918		{
 919			// Upload fields - grab by NAME so that we can use it later on when checking $_FILES
 920			if ($component->ComponentTypeId == 9)
 921			{
 922				if ($component->PropertyName == 'EMAILATTACH')
 923				{
 924					$emailsvalues = $component->PropertyValue;
 925					$emailsvalues = trim($emailsvalues) != '' ? explode(',',$emailsvalues) : array();
 926					
 927					if (!empty($emailsvalues))
 928					foreach ($emailsvalues as $emailvalue)
 929					{
 930						if ($emailvalue == 'useremail' || $emailvalue == 'adminemail') continue;
 931						$additionalEmailUploadsIds[] = $emailvalue;
 932					}
 933					
 934					$additionalEmailUploadsIds = array_unique($additionalEmailUploadsIds);
 935					
 936					if (!empty($additionalEmailUploadsIds))
 937					foreach ($additionalEmailUploadsIds as $additionalEmailUploadsId)
 938					{
 939						if (in_array($additionalEmailUploadsId,$emailsvalues))
 940						$additionalEmailUploads[$additionalEmailUploadsId][] = $component->ComponentId;
 941					}
 942				}
 943				
 944				if ($component->PropertyName == 'NAME')
 945					$uploadFields[] = $component->PropertyValue;
 946				
 947				if ($component->PropertyName == 'EMAILATTACH' && !empty($component->PropertyValue))
 948				{
 949					$emailvalues = explode(',',$component->PropertyValue);
 950					
 951					if (in_array('useremail',$emailvalues))
 952					{
 953						$userEmailUploads[] = $component->ComponentId;
 954						//continue;
 955					}
 956					
 957					if (in_array('adminemail',$emailvalues))
 958					{
 959						$adminEmailUploads[] = $component->ComponentId;
 960						//continue;
 961					}				
 962				}
 963			}
 964			// Multiple fields - grab by ComponentId for performance
 965			elseif (in_array($component->ComponentTypeId, array(3, 4)))
 966			{
 967				if ($component->PropertyName == 'NAME')
 968					$multipleFields[] = $component->ComponentId;
 969			}
 970			// Textarea fields - grab by ComponentId for performance
 971			elseif ($component->ComponentTypeId == 2)
 972			{
 973				if ($component->PropertyName == 'WYSIWYG' && $component->PropertyValue == 'NO')
 974					$textareaFields[] = $component->ComponentId;
 975			}
 976			
 977			$properties[$component->ComponentId][$component->PropertyName] = $component->PropertyValue;
 978		}
 979		
 980		// language
 981		$translations = RSFormProHelper::getTranslations('properties', $formId, $submission->Lang);
 982		foreach ($properties as $componentId => $componentProperties)
 983		{
 984			foreach ($componentProperties as $property => $value)
 985			{
 986				$reference_id = $componentId.'.'.$property;
 987				if (isset($translations[$reference_id]))
 988					$componentProperties[$property] = $translations[$reference_id];
 989			}
 990			$properties[$componentId] = $componentProperties;
 991		}
 992		
 993		$secret = $config->getValue('config.secret');
 994		foreach ($properties as $ComponentId => $property)
 995		{
 996			// {component:caption}
 997			$placeholders[] = '{'.$property['NAME'].':caption}';
 998			$values[] = isset($property['CAPTION']) ? $property['CAPTION'] : '';
 999			
1000			// {component:name}
1001			$placeholders[] = '{'.$property['NAME'].':name}';
1002			$values[] = $property['NAME'];
1003			
1004			// {component:value}
1005			$placeholders[] = '{'.$property['NAME'].':value}';
1006			$value = '';
1007			if (isset($submission->values[$property['NAME']]))
1008			{
1009				$value = $submission->values[$property['NAME']];
1010				
1011				// Check if this is an upload field
1012				if (in_array($property['NAME'], $uploadFields))
1013					$value = '<a href="'.JURI::root().'index.php?option=com_rsform&amp;task=submissions.view.file&amp;hash='.md5($submission->SubmissionId.$secret.$property['NAME']).$Itemid.'">'.basename($submission->values[$property['NAME']]).'</a>';
1014				// Check if this is a multiple field
1015				elseif (in_array($ComponentId, $multipleFields))
1016					$value = str_replace("\n", $form->MultipleSeparator, $value);
1017				elseif ($form->TextareaNewLines && in_array($ComponentId, $textareaFields))
1018					$value = nl2br($value);
1019			}
1020			$values[] = $value;
1021			
1022			if (isset($property['ITEMS']) && isset($submission->values[$property['NAME']]))
1023            {
1024                $value = $submission->values[$property['NAME']];
1025                $placeholders[] = '{'.$property['NAME'].':text}';
1026				$items = RSFormProHelper::explode(RSFormProHelper::isCode($property['ITEMS']));
1027                foreach ($items as $item)
1028                {
1029                    @list($item_val, $item_text) = explode("|", $item, 2);
1030                    if ($item_text && $item_val == $value)
1031					{
1032                        $value = $item_text;
1033						break;
1034					}
1035                }
1036                $values[] = $value;
1037            }
1038			
1039			// {component:path}
1040			if (in_array($property['NAME'], $uploadFields))
1041			{
1042				$placeholders[] = '{'.$property['NAME'].':path}';
1043				if (isset($submission->values[$property['NAME']]))
1044				{
1045					$filepath = $submission->values[$property['NAME']];
1046					$filepath = str_replace(JPATH_SITE.DS, JURI::root(), $filepath);
1047					$filepath = str_replace(array('\\', '\\/', '//\\'), '/', $filepath);
1048					$values[] = $filepath;
1049				}
1050				else
1051					$values[] = '';
1052			}
1053		}
1054		$placeholders[] = '{_STATUS:value}';
1055		$values[] = isset($submission->values['_STATUS']) ? JText::_('RSFP_PAYPAL_STATUS_'.$submission->values['_STATUS']) : '';
1056		
1057		$placeholders[] = '{_ANZ_STATUS:value}';
1058		$values[] = isset($submission->values['_ANZ_STATUS']) ? JText::_('RSFP_ANZ_STATUS_'.$submission->values['_ANZ_STATUS']) : '';
1059		
1060		$user = JFactory::getUser($submission->UserId);
1061		if (empty($user->id))
1062			$user = JFactory::getUser(0);
1063		
1064		$root 				= $mainframe->isAdmin() ? JURI::root() : $u->toString(array('scheme','host', 'port'));
1065		$confirmation_hash 	= md5($submission->SubmissionId.$formId.$submission->DateSubmitted);
1066		$hash_link 			= 'index.php?option=com_rsform&task=confirm&hash='.$confirmation_hash;
1067		$confirmation 		= $root.($mainframe->isAdmin() ? $hash_link : JRoute::_($hash_link));
1068		
1069		if (!$skip_globals)
1070		{
1071			array_push($placeholders, '{global:username}', '{global:userid}', '{global:useremail}', '{global:fullname}', '{global:userip}', '{global:date_added}', '{global:sitename}', '{global:siteurl}','{global:confirmation}','{global:submissionid}', '{global:submission_id}');
1072			array_push($values, $user->username, $user->id, $user->email, $user->name, isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '', $submission->DateSubmitted, $config->getValue('config.sitename'), JURI::root(),$confirmation, $submission->SubmissionId, $submission->SubmissionId);
1073		}
1074		
1075		$mainframe->triggerEvent('rsfp_onAfterCreatePlaceholders', array(array('form' => &$form, 'placeholders' => &$placeholders, 'values' => &$values, 'submission' => $submission)));
1076		
1077		if ($only_return_replacements)
1078			return array($placeholders, $values);
1079		
1080		$userEmail = array(
1081			'to' => str_replace($placeholders, $values, $form->UserEmailTo),
1082			'cc' => str_replace($placeholders, $values, $form->UserEmailCC),
1083			'bcc' => str_replace($placeholders, $values, $form->UserEmailBCC),
1084			'from' => str_replace($placeholders, $values, $form->UserEmailFrom),
1085			'replyto' => str_replace($placeholders, $values, $form->UserEmailReplyTo),
1086			'fromName' => str_replace($placeholders, $values, $form->UserEmailFromName),
1087			'text' => str_replace($placeholders, $values, $form->UserEmailText),
1088			'subject' => str_replace($placeholders, $values, $form->UserEmailSubject),
1089			'mode' => $form->UserEmailMode,
1090			'files' => array()
1091		);
1092
1093		// user cc
1094		if (strpos($userEmail['cc'], ',') !== false)
1095			$userEmail['cc'] = explode(',', $userEmail['cc']);
1096		// user bcc
1097		if (strpos($userEmail['bcc'], ',') !== false)
1098			$userEmail['bcc'] = explode(',', $userEmail['bcc']);
1099		
1100		jimport('joomla.filesystem.file');
1101		
1102		$file = str_replace($placeholders, $values, $form->UserEmailAttachFile);
1103		if ($form->UserEmailAttach && JFile::exists($file))
1104			$userEmail['files'][] = $file;
1105		
1106		// Need to attach files
1107		// User Email
1108		foreach ($userEmailUploads as $componentId)
1109		{
1110			$name = $properties[$componentId]['NAME'];
1111			if (!empty($submission->values[$name]))
1112				$userEmail['files'][] = $submission->values[$name];
1113		}
1114		
1115		$adminEmail = array(
1116			'to' => str_replace($placeholders, $values, $form->AdminEmailTo),
1117			'cc' => str_replace($placeholders, $values, $form->AdminEmailCC),
1118			'bcc' => str_replace($placeholders, $values, $form->AdminEmailBCC),
1119			'from' => str_replace($placeholders, $values, $form->AdminEmailFrom),
1120			'replyto' => str_replace($placeholders, $values, $form->AdminEmailReplyTo),
1121			'fromName' => str_replace($placeholders, $values, $form->AdminEmailFromName),
1122			'text' => str_replace($placeholders, $values, $form->AdminEmailText),
1123			'subject' => str_replace($placeholders, $values, $form->AdminEmailSubject),
1124			'mode' => $form->AdminEmailMode,
1125			'files' => array()
1126		);
1127		
1128		// admin cc
1129		if (strpos($adminEmail['cc'], ',') !== false)
1130			$adminEmail['cc'] = explode(',', $adminEmail['cc']);
1131		// admin bcc
1132		if (strpos($adminEmail['bcc'], ',') !== false)
1133			$adminEmail['bcc'] = explode(',', $adminEmail['bcc']);
1134		
1135		// Admin Email
1136		foreach ($adminEmailUploads as $componentId)
1137		{
1138			$name = $properties[$componentId]['NAME'];
1139			if (!empty($submission->values[$name]))
1140				$adminEmail['files'][] = $submission->values[$name];
1141		}
1142		
1143		$mainframe->triggerEvent('rsfp_beforeUserEmail', array(array('form' => &$form, 'placeholders' => &$placeholders, 'values' => &$values, 'submissionId' => $SubmissionId, 'userEmail'=>&$userEmail)));
1144		
1145		// Script called before the User Email is sent.
1146		eval($form->UserEmailScript);
1147		
1148		// mail users
1149		$recipients = explode(',',$userEmail['to']);
1150		if(!empty($recipients))
1151			foreach($recipients as $recipient)
1152				if(!empty($recipient))
1153					RSFormProHelper::sendMail($userEmail['from'], $userEmail['fromName'], $recipient, $userEmail['subject'], $userEmail['text'], $userEmail['mode'], !empty($userEmail['cc']) ? $userEmail['cc'] : null, !empty($userEmail['bcc']) ? $userEmail['bcc'] : null, $userEmail['files'], !empty($userEmail['replyto']) ? $userEmail['replyto'] : '');
1154		
1155		$mainframe->triggerEvent('rsfp_beforeAdminEmail', array(array('form' => &$form, 'placeholders' => &$placeholders, 'values' => &$values, 'submissionId' => $SubmissionId, 'adminEmail'=>&$adminEmail)));
1156		
1157		// Script called before the Admin Email is sent.
1158		eval($form->AdminEmailScript);
1159		
1160		//mail admins
1161		$recipients = explode(',',$adminEmail['to']);
1162		if(!empty($recipients))
1163			foreach($recipients as $recipient)
1164				if(!empty($recipient))
1165					RSFormProHelper::sendMail($adminEmail['from'], $adminEmail['fromName'], $recipient, $adminEmail['subject'], $adminEmail['text'], $adminEmail['mode'], !empty($adminEmail['cc']) ? $adminEmail['cc'] : null, !empty($adminEmail['bcc']) ? $adminEmail['bcc'] : null, $adminEmail['files'], !empty($adminEmail['replyto']) ? $adminEmail['replyto'] : '');
1166		
1167		
1168		//additional emails
1169		$db->setQuery("SELECT * FROM #__rsform_emails WHERE formId = ".$formId." ");
1170		$emails = $db->loadObjectList();
1171		$etranslations = RSFormProHelper::getTranslations('emails', $formId, $submission->Lang);
1172		
1173		if (!empty($emails))
1174			foreach ($emails as $email)
1175			{
1176				if (empty($email->from) || empty($email->fromname) || empty($email->subject) || empty($email->message)) continue;
1177				$fromname = isset($etranslations[$email->id.'.fromname']) ? $etranslations[$email->id.'.fromname'] : $email->fromname;
1178				$subject = isset($etranslations[$email->id.'.subject']) ? $etranslations[$email->id.'.subject'] : $email->subject;
1179				$message = isset($etranslations[$email->id.'.message']) ? $etranslations[$email->id.'.message'] : $email->message;
1180				
1181				$additionalEmail = array(
1182					'to' => str_replace($placeholders, $values, $email->to),
1183					'cc' => str_replace($placeholders, $values, $email->cc),
1184					'bcc' => str_replace($placeholders, $values, $email->bcc),
1185					'from' => str_replace($placeholders, $values, $email->from),
1186					'replyto' => str_replace($placeholders, $values, $email->replyto),
1187					'fromName' => str_replace($placeholders, $values, $fromname),
1188					'text' => str_replace($placeholders, $values, $message),
1189					'subject' => str_replace($placeholders, $values, $subject),
1190					'mode' => $email->mode,
1191					'files' => array()
1192				);
1193				
1194				if (!empty($additionalEmailUploads))
1195				foreach ($additionalEmailUploads as $additionalEmailId => $additionalEmailUpload)
1196				{
1197					if ($additionalEmailId == $email->id)
1198						foreach ($additionalEmailUpload as $componentId)
1199						{
1200							$name = $properties[$componentId]['NAME'];
1201							if (!empty($submission->values[$name]))
1202								$additionalEmail['files'][] = $submission->values[$name];
1203						}
1204				}
1205				
1206				// additional cc
1207				if (strpos($additionalEmail['cc'], ',') !== false)
1208					$additionalEmail['cc'] = explode(',', $additionalEmail['cc']);
1209				// additional bcc
1210				if (strpos($additionalEmail['bcc'], ',') !== false)
1211					$additionalEmail['bcc'] = explode(',', $additionalEmail['bcc']);
1212				
1213				$mainframe->triggerEvent('rsfp_beforeAdditionalEmail', array(array('form' => &$form, 'placeholders' => &$placeholders, 'values' => &$values, 'submissionId' => $SubmissionId, 'additionalEmail'=>&$additionalEmail)));
1214				eval($form->AdditionalEmailsScript);
1215				
1216				// mail users
1217				$recipients = explode(',',$additionalEmail['to']);
1218				if(!empty($recipients))
1219					foreach($recipients as $recipient)
1220						if(!empty($recipient))
1221							RSFormProHelper::sendMail($additionalEmail['from'], $additionalEmail['fromName'], $recipient, $additionalEmail['subject'], $additionalEmail['text'], $additionalEmail['mode'], !empty($additionalEmail['cc']) ? $additionalEmail['cc'] : null, !empty($additionalEmail['bcc']) ? $additionalEmail['bcc'] : null, $additionalEmail['files'], !empty($additionalEmail['replyto']) ? $additionalEmail['replyto'] : '');
1222				
1223			}
1224		
1225		return array($placeholders, $values);
1226	}
1227	
1228	function escapeArray(&$val, &$key)
1229	{
1230		$db = JFactory::getDBO();
1231		$val = $db->getEscaped($val);
1232		$key = $db->getEscaped($key);
1233	}
1234	
1235	function componentExists($formId, $componentTypeId)
1236	{
1237		$formId = (int) $formId;
1238		$db = JFactory::getDBO();
1239		
1240		if (is_array($componentTypeId))
1241		{
1242			JArrayHelper::toInteger($componentTypeId);
1243			$db->setQuery("SELECT ComponentId FROM #__rsform_components WHERE ComponentTypeId IN (".implode(',', $componentTypeId).") AND FormId='".$formId."' AND Published='1'");
1244		}
1245		else
1246		{
1247			$componentTypeId = (int) $componentTypeId;
1248			$db->setQuery("SELECT ComponentId FROM #__rsform_components WHERE ComponentTypeId='".$componentTypeId."' AND FormId='".$formId."' AND Published='1'");
1249		}
1250		
1251		return $db->loadResultArray();
1252	}
1253	
1254	function cleanCache()
1255	{
1256		jimport('joomla.html.parameter');
1257		
1258		$config = JFactory::getConfig();
1259		$plugin = JPluginHelper::getPlugin('system', 'cache');
1260		
1261		$params = new JParameter($plugin->params);
1262		$options = array(
1263			'cachebase' 	=> JPATH_BASE.DS.'cache',
1264			'defaultgroup' 	=> 'page',
1265			'lifetime' 		=> $params->get('cachetime', 15) * 60,
1266			'browsercache'	=> $params->get('browsercache', false),
1267			'caching'		=> false,
1268			'language'		=> $config->getValue('config.language', 'en-GB')
1269		);
1270		$cache =& JCache::getInstance('page', $options);
1271		
1272		if (!RSFormProHelper::isJ16())
1273			$id = $cache->_makeId();
1274		else
1275			$id = $cache->makeId();
1276			
1277		$handler =& $cache->_getStorage();
1278		if (!JError::isError($handler))
1279			$handler->remove($id, 'page');
1280		
1281		// Test this
1282		// $cache->clean();
1283	}
1284	
1285	function loadTheme($form)
1286	{
1287		jimport('joomla.html.parameter');
1288		
1289		$doc =& JFactory::getDocument();
1290		$form->ThemeParams = new JParameter($form->ThemeParams);
1291			
1292		if ($form->ThemeParams->get('num_css', 0) > 0)
1293			for ($i=0; $i<$form->ThemeParams->get('num_css'); $i++)
1294			{
1295				$css = $form->ThemeParams->get('css'.$i);
1296				$doc->addStyleSheet(JURI::root(true).'/components/com_rsform/assets/themes/'.$form->ThemeParams->get('name').'/'.$css);
1297			}
1298		if ($form->ThemeParams->get('num_js', 0) > 0)
1299			for ($i=0; $i<$form->ThemeParams->get('num_js'); $i++)
1300			{
1301				$js = $form->ThemeParams->get('js'.$i);
1302				$doc->addScript(JURI::root(true).'/components/com_rsform/assets/themes/'.$form->ThemeParams->get('name').'/'.$js);
1303			}
1304	}
1305	
1306	// conditions
1307	function getConditions($formId, $lang=null)
1308	{
1309		$db   =& JFactory::getDBO();
1310		
1311		if (!$lang)
1312			$lang = RSFormProHelper::getCurrentLanguage();
1313		
1314		// get all conditions
1315		$db->setQuery("SELECT c.*,p.PropertyValue AS ComponentName FROM `#__rsform_conditions` c LEFT JOIN #__rsform_properties p ON (c.component_id = p.ComponentId) LEFT JOIN #__rsform_components comp ON (comp.ComponentId=p.ComponentId) WHERE c.`form_id` = ".$formId." AND c.lang_code='".$db->getEscaped($lang)."' AND comp.Published = 1 AND p.PropertyName='NAME' ORDER BY c.`id` ASC");
1316		if ($conditions = $db->loadObjectList())
1317		{
1318			// put them all in an array so we can use only one query
1319			$cids = array();
1320			foreach ($conditions as $condition)
1321				$cids[] = $condition->id;
1322			
1323			// get details
1324			$db->setQuery("SELECT d.*,p.PropertyValue AS ComponentName FROM #__rsform_condition_details d LEFT JOIN #__rsform_properties p ON (d.component_id = p.ComponentId) LEFT JOIN #__rsform_components comp ON (comp.ComponentId=p.ComponentId) WHERE d.condition_id IN (".implode(",", $cids).") AND comp.Published = 1 AND p.PropertyName='NAME'");
1325			$details = $db->loadObjectList();
1326			
1327			// arrange details within conditions
1328			foreach ($conditions as $i => $condition)
1329			{
1330				$condition->details = array();
1331				foreach ($details as $detail)
1332				{
1333					if ($detail->condition_id != $condition->id) continue;
1334					$condition->details[] = $detail;
1335				}
1336				
1337				$conditions[$i] = $condition;
1338			}
1339			// all done
1340			return $conditions;
1341		}
1342		// nothing found
1343		return false;
1344	}
1345	
1346	function showForm($formId, $val='', $validation=array())
1347	{
1348		$mainframe =& JFactory::getApplication();
1349		
1350		$formId = (int) $formId;
1351		
1352		$db = JFactory::getDBO();
1353		$doc =& JFactory::getDocument();
1354		
1355		$db->setQuery("SELECT `FormId`, `FormLayoutName`, `FormLayout`, `ScriptDisplay`, `ErrorMessage`, `FormTitle`, `CSS`, `JS`, `CSSClass`, `CSSId`, `CSSName`, `CSSAction`, `CSSAdditionalAttributes`, `AjaxValidation`, `ThemeParams` FROM #__rsform_forms WHERE FormId='".$formId."' AND `Published`='1'");
1356		$form = $db->loadObject();
1357		
1358		$lang 		  = RSFormProHelper::getCurrentLanguage();
1359		$translations = RSFormProHelper::getTranslations('forms', $form->FormId, $lang);
1360		if ($translations)
1361			foreach ($translations as $field => $value)
1362			{
1363				if (isset($form->$field))
1364					$form->$field = $value;
1365			}
1366		
1367		if ($form->JS)
1368			$doc->addCustomTag($form->JS);
1369		if ($form->CSS)
1370			$doc->addCustomTag($form->CSS);
1371		if ($form->ThemeParams)
1372			RSFormProHelper::loadTheme($form);
1373		
1374		$doc->addStyleSheet(JURI::root(true).'/components/com_rsform/assets/css/front.css');
1375		if ($doc->getDirection() == 'rtl')
1376			$doc->addStyleSheet(JURI::root(true).'/components/com_rsform/assets/css/front-rtl.css');
1377		$doc->addScript(JURI::root(true).'/components/com_rsform/assets/js/script.js');
1378		
1379		$calendars = RSFormProHelper::componentExists($formId, 6); //6 is the componentTypeId for calendar
1380		if(!empty($calendars))
1381		{
1382			$doc->addStyleSheet(JURI::root(true).'/components/com_rsform/assets/calendar/calendar.css');
1383			
1384			$hidden = JRequest::getVar('hidden');
1385			$all_data = RSFormProHelper::getComponentProperties($calendars);
1386			foreach($calendars as $i => $calendarComponentId)
1387			{
1388				$data = $all_data[$calendarComponentId];
1389				
1390				$calendars['CALENDARLAYOUT'][$i] = $data['CALENDARLAYOUT'];
1391				$calendars['DATEFORMAT'][$i] = $data['DATEFORMAT'];
1392				$calendars['VALUES'][$i] = '';
1393				$calendars['EXTRA'][$i] = array();
1394				if (!empty($hidden[$data['NAME']]))
1395					$calendars['VALUES'][$i] = preg_replace('#[^0-9\/]+#i', '', $hidden[$data['NAME']]);
1396				
1397				if (!empty($data['MINDATE']))
1398					$calendars['EXTRA'][$i][] = "'mindate': '".$data['MINDATE']."'";
1399				if (!empty($data['MAXDATE']))
1400					$calendars['EXTRA'][$i][] = "'maxdate': '".$data['MAXDATE']."'";
1401				
1402				$calendars['EXTRA'][$i] = '{'.implode(', ', $calendars['EXTRA'][$i]).'}';
1403			}
1404			unset($all_data);
1405			
1406			$calendarsLayout = "'".implode("','", $calendars['CALENDARLAYOUT'])."'";
1407			$calendarsFormat = "'".implode("','", $calendars['DATEFORMAT'])."'";
1408			$calendarsValues = "'".implode("','", $calendars['VALUES'])."'";
1409			$calendarsExtra  = implode(',', $calendars['EXTRA']);
1410		}
1411		
1412		$formLayout = $form->FormLayout;
1413		unset($form->FormLayout);
1414		$errorMessage = $form->ErrorMessage;
1415		unset($form->ErrorMessage);
1416		
1417		$db->setQuery("SELECT p.PropertyValue AS name, c.ComponentId, c.ComponentTypeId, ct.ComponentTypeName, c.Order FROM #__rsform_properties p LEFT JOIN #__rsform_components c ON (c.ComponentId=p.ComponentId) LEFT JOIN #__rsform_component_types ct ON (ct.ComponentTypeId=c.ComponentTypeId) WHERE c.FormId='".$formId."' AND p.PropertyName='NAME' AND c.Published='1' ORDER BY c.Order");
1418		$components = $db->loadObjectList();
1419		
1420		$pages			= array();
1421		$page_progress  = array();
1422		$submits		= array();
1423		foreach ($component…

Large files files are truncated, but you can click here to view the full file