<?php
/**
 * Smarty Open Source Billing Plugin
 * -------------------------------------------------------------
 * File:	block.osb.php
 * Type:	block
 * Name:	osb
 * Purpose:	Hooks into OSB
 * -------------------------------------------------------------
 */
function smarty_function_osb($params,&$smarty) {
	if (! isset($params['f']) || ! ($f=$params['f'])) {
		echo 'NO Function name used in call?';
		return;
	}

	unset($params['f']);

	$f = 'osb_'.$f;

	if (! function_exists($f)) {
		printf('Unknown Function [%s]?',$f);
		return;
	}

	eval(sprintf('%s($params,$smarty);',$f));
}

function osb_html_select($val,$id,$name,$default,$module) {
	if (! $val) {
		printf('<input type="hidden" id="%s_hidden" name="id" value="%s"/>',$id,$default);
		printf('<input type="text" id="%s" name="%s_search" size="35" value="%s" autocomplete="off"/>',$name,'account',$val);
		printf('<div class="auto_complete" id="%s_auto_complete"></div>',$id);
		printf('<script type="text/javascript">new Ajax.Autocompleter("%s","%s_auto_complete","ajax.php?do[]=%s:autoselect",{});</script>',$name,$id,$module);

	} else {
		printf('<div style="text-decoration: underline;"><a href="#" onclick="window.open(\'?_page=%s:view&amp;id=%s\',\'mainFrame\',\'\')">%s</a></div>',$module,$default,$val);
		printf('<input type="hidden" id="%s" name="%s" value="%s"/>',$id,$name,$default);
	}
}

/**
 * HTML Account Selector
 *
 * If passed a default ID (and it exists), that will be rendered, otherwise a javascript selection box is rendered.
 */
function osb_html_select_account($params,&$smarty) {
	if (! $params['name']) {
		printf('MISSING name:%s',__METHOD__);
		return;
	}

	$module = isset($params['module']) ? $params['module'] : 'account';
	$default = isset($params['default']) ? $params['default'] : '';
	$id = isset($params['id']) ? $params['id'] : sprintf('%s_id',$params['name']);
	$val = '';

	if ($default) {
		$db = &DB();
		$result = $db->Execute(sqlSelect($db,'account','first_name,last_name',array('id'=>$default)));

		if ($result->RecordCount() > 0)
			$val = sprintf('%s %s',$result->fields['first_name'],$result->fields['last_name']);
	}

	return osb_html_select($val,$id,$params['name'],$default,$module);
}

/**
 * HTML Affiliate Selector
 *
 * If passed a default ID (and it exists), that will be rendered, otherwise a javascript selection box is rendered.
 * @todo need to create autoselect();
 */
function osb_html_select_affiliate($params,&$smarty) {
	if (! $params['name']) {
		printf('MISSING name:%s',__METHOD__);
		return;
	}

	$module = isset($params['module']) ? $params['module'] : 'affiliate';
	$default = isset($params['default']) ? $params['default'] : '';
	$id = isset($params['id']) ? $params['id'] : sprintf('%s_id',$params['name']);
	$val = '';

	if ($default) {
		$db = &DB();
		$sql = sprintf('SELECT DISTINCT {p}affiliate.id,{p}account.first_name,{p}account.last_name,{p}account.username
			FROM {p}account LEFT JOIN {p}affiliate ON {p}account.id={p}affiliate.account_id
			WHERE {p}affiliate.id=%s AND {p}affiliate.site_id=%s AND {p}account.site_id=%s',$db->qstr($default),DEFAULT_SITE,DEFAULT_SITE);

		$result = $db->Execute(str_replace('{p}',AGILE_DB_PREFIX,$sql));

		if ($result->RecordCount() > 0)
			$val = sprintf('%s %s',$result->fields['first_name'],$result->fields['last_name']);
	}

	return osb_html_select($val,$id,$params['name'],$default,$module);
}

function osb_html_select_name($params,&$smarty) {
	if (! $params['name']) {
		printf('MISSING name:%s',__METHOD__);
		return;
	}

	$module = isset($params['module']) ? $params['module'] : '';
	$table = isset($params['table']) ? $params['table'] : '';
	$default = isset($params['default']) ? $params['default'] : '';
	$id = isset($params['id']) ? $params['id'] : sprintf('%s_id',$params['name']);
	$val = '';

	if ($default) {
		$db = &DB();
		$result = $db->Execute($q=sqlSelect($db,$table,'name',array('id'=>$default)));

		if ($result && $result->RecordCount() > 0)
			$val = $result->fields['name'];
	}

	return osb_html_select($val,$id,$params['name'],$default,$module);
}

function osb_autoselect($params,&$smarty) {
	$module = isset($params['module']) ? $params['module'] : (isset($smarty->_tpl_vars['meth'][0]) ? $smarty->_tpl_vars['meth'][0] : '');
	$field = isset($params['field']) ? $params['field'] : '';
	$return = isset($params['return']) ? $params['return'] : '';
	$default = isset($params['default']) ? $params['default'] : '';
	$val = '';

	if (! $module || ! $field || ! $return) {
		printf('MISSING module (%s),field (%s) OR return (%s):%s',$module,$field,$return,__METHOD__);
		return;
	}

	if ($default) {
		$db = &DB();
		$result = $db->Execute($q=sqlSelect($db,$module,$return.',first_name,last_name',array($return=>$default)));

		if ($result && $result->RecordCount() == 1)
			$val = sprintf('%s %s',$result->fields['first_name'],$result->fields['last_name']);
	}

	printf('<input type="hidden" id="autoselect_%s_hidden" name="%s" size="35" value="%s"/>',$field,$field,$default);
	printf('<input type="text" id="autoselect_%s" name="autosearch_%s" size="35" value="%s" autocomplete="off"/>',$field,$field,$val);
	printf('<div class="auto_complete" id="%s_auto_complete"></div>',$field);
	echo '<script type="text/javascript"><!--'."\n";
	printf('new Ajax.Autocompleter("autoselect_%s","%s_auto_complete","ajax.php?do[]=%s:autoselect&return=%s&field=%s",{});',$field,$field,$module,$return,$field);
	echo "\n";
	echo '//--></script>'."\n";
}

/**
 * Get list of files from the filesystem, and present in a select list
 */
function osb_html_menu_files($params,&$smarty) {
	if (! $params['name'] || ! $params['path']) {
		printf('MISSING name OR path:%s',__METHOD__);
		return;
	}

	$id = isset($params['id']) ? $params['id'] : $params['name'];
	$ext = '';

	switch ($params['path']) {
		case 'affiliate_plugin': $path = sprintf('%s/affiliate/',PATH_PLUGINS); break;
		case 'checkout_plugin': $path = sprintf('%s/checkout/',PATH_PLUGINS); break;
		case 'invoice_pdf': $path = sprintf('%s/invoice/PDF/',PATH_MODULES); $ext = '.inc.php'; $pre = 'pdf_invoice_'; break;
		case 'invoice_pagetype': $path = sprintf('%s%s/invoice/',PATH_THEMES,DEF_THEME_N); $ext = '.pdf'; $pre = 'invoice-'; break;
		case 'language': $path = sprintf('%s/core/',PATH_LANGUAGE); $ext = '_core.xml'; $cap=1; break;
		case 'product' : $path = sprintf('%s/product',PATH_PLUGINS); break;
		case 'product_cat' : $path = sprintf('%s%s/blocks/product_cat',PATH_THEMES,DEF_THEME_N); break;
		case 'provision_plugin': $path = sprintf('%s/provision/',PATH_PLUGINS); break;
		case 'static_template':	$path = sprintf('%s/default/blocks/static_page/',PATH_THEMES); $ext = '_template.tpl'; $cap=1; break;
		case 'theme' : $path = PATH_THEMES; break;
		case 'whois_plugin': $path = sprintf('%s/whois/',PATH_PLUGINS); break;

		default:
			printf('Unkonwn path: %s',$params['path']);
			return;
	}

	$count = 0;
	$arr = array();
	$dir = opendir($path);
	while ($file_name = readdir($dir)) {
		$display = true;

		if (! in_array($file_name,array('.','..'))) {
			if ($ext) {
				$cute = preg_replace("/{$ext}$/",'',$file_name);

				if (! preg_match("/{$ext}$/",$file_name))
					$display = false;
			}

			if ($pre) {
				$cute = preg_replace("/^{$pre}/",'',$cute);

				if (! preg_match("/^{$pre}/",$file_name))
					$display = false;

			}

			if ($display) {
				$value = str_replace('_',' ',str_replace('-',' ',$cute));

				if ($cap==1)
					$value = ucfirst(strtolower($value));
				elseif ($cap==2)
					$value = ucwords(strtolower($value));
				elseif($cap)
					$value = strtoupper($value);

				$arr[$cute] = $value;
			}
		}
	}

	$return = sprintf('<select id="%s" name="%s">',$id,$params['name']);

	if ($params['default'] == 'all')
		$return .= '<option value="" selected>&nbsp;</option>';

	if (count($arr))
		foreach ($arr as $index => $value)
			$return .= sprintf('<option value="%s"%s>%s</option>',$index,($params['default'] == $index) ? ' selected' : '',$value);

	$return .= '</select>';

	echo $return;
}

function osb_html_link($params,&$smarty) {
	$name = 'submit';
	$module = 'CORE';

	$_ignore['show'] = true;
	$_ignore['hide'] = true;
	$_ignore['name'] = true;

	# Get the values passed...
	$vals = '';
	foreach ($params as $_key => $_val)
		if (empty($_ignore[$_key]))
			$vals .= sprintf(' %s="%s"',$_key,$_val);
		else
			$$_key = $_val;

		foreach ($params as $_key => $_val)
			$$_key = $_val;

		# Change state(s) (hide)
		$t = 0;
		if ($hide) {
			if (preg_match('/,/',$hide))
				$hides = explode(',',$hide);
			else
				$hides = array($hide);

			foreach ($hides as $element)
				if (preg_match('/\|/',$element)) {
					$el = explode('|',$element);
					$action .= sprintf("new Effect.%s('%s',{duration: %s});",$el[2],$el[0],$el[1]);
				} else {
					$action .= sprintf("$('%s').style.display='none';",$element);
				}
		}

		# Change state(s) (show)
		if ($show) {
			if (preg_match('/,/',$show))
				$shows = explode(',',$show);
			else
				$shows = array($show);

			foreach ($shows as $element) {
				if (preg_match('/\|/',$element)) {
					$el = explode('|',$element);
					$action .= sprintf("new Effect.%s('%s',{duration: %s});",$el[2],$el[0],$el[1]);
				} else {
					$action .= sprintf("$('%s').style.display='block';",$element);
				}
			}
		}

		# translate name
		global $C_translate;
		$trans = $C_translate->translate($name,$module);
		if (! empty($trans))
			$name = $trans;

		if (empty($link))
			$link = '#';

		return sprintf('<a href="%s"%s%s>%s</a>',$link,$vals,$action ? sprintf(' onclick="%s"',$action) : '',$name);
}

/**
 * Hides a div/span element without disabling the view
 */
function osb_style_hide($params,&$smarty) {
	echo 'style="display:none;"';
}

/**
 * Displays & Populates an Plug In template
 * @todo change this to be dynmaic, ie: defined by the instalation of a module and calling a method.
 */
function osb_plugin($params,&$smarty) {
	# Some Validation
	if ((! isset($params['type']) || ! trim($params['type'])) || (! isset($params['name']) || ! trim($params['name'])))
		return;

	if (! isset($params['name_prefix']))
		$params['name_prefix'] = '';

	if (! isset($params['data']) && $params['data'])
		$smarty->assign('plugin',unserialize($params['data']));

	# Pass any other vars to smarty
	foreach ($params as $var=>$val)
		$smarty->assign($var,$val);

	# Get full template file-path:
	switch ($params['type']) {
		case 'affiliate':
			$meth = 'affiliate:plugin';
			break;

		case 'checkout':
			$meth = 'checkout_plugin:plugin';
			break;

		case 'import':
			$meth = '';	// @todo
			break;

		case 'product':
			$meth = 'product_plugin:plugin';
			break;

		case 'provision':
			$meth = 'host_provision_plugin:plugin';
			break;

		case 'registrar':
			$meth = 'host_registrar_plugin:plugin';
			break;

		case 'whois':
			$meth = 'host_whois_plugin:plugin';
			break;

		case 'voip_did':
			$meth = 'voip_did_plugin:config';
			break;
	}

	$_tpl = sprintf('%s_%s%s',$meth,$params['name_prefix'],$params['name']);

	# Check if file exists:
	$_template_full = sprintf('%s%s/blocks/%s.tpl',PATH_THEMES,DEF_THEME_N,str_replace(':','/',$_tpl));

	if (! is_file($_template_full)) {
		$_template_full = sprintf('%s%s/blocks/%s.tpl',PATH_THEMES,'default',str_replace(':','/',$_tpl));

		if (! is_file($_template_full)) {
			if ($debug)
				printf('Error loading plugin template: %s',$_template_full);

			return;
		}
	}

	// Load file
	$smarty->display(sprintf('file:%s',$_template_full));
}

/**
 * Translate a table title
 */
function osb_tt($params,&$smarty) {
	require_once(PATH_CORE.'translate.inc.php');
	$C_translate = new CORE_translate;

	echo $C_translate->tt($params,$smarty);
}

/**
 * Translate a table field
 */
function osb_tf($params,&$smarty) {
	require_once(PATH_CORE.'translate.inc.php');
	$C_translate = new CORE_translate;

	echo $C_translate->tf($params,$smarty);
}

function osb_html_menu_product_host($params,&$smarty) {
	$id = $params['id'];
	$default = unserialize($params['default']);
	if (empty($id))
		$id = $params['name'];

	$db = &DB();
	$result = $db->Execute(sqlSelect($db,'product','id,sku',sprintf('host=1 AND active=1 AND price_type=1 AND id!%s',$params['exclude'])));
	if ($result && $result->RecordCount()) {
		printf('<select id="%s" name="%s[]" size="%s" multiple="multiple">',$id,$params['name'],$params['size']);
		while(!$result->EOF) {
			$sel = '';
			foreach ($default as $cur)
				if ($cur == $result->fields['id'])
					$sel = ' selected="selected"';

			printf('<option value="%s"%s>%s</option>',$result->fields['id'],$sel,$result->fields['sku']);
			$result->MoveNext();
		}
		echo '</select>';
	}
}

function osb_html_menu_product_subscription($params,&$smarty) {
	$id = $params['id'];
	$default = unserialize($params['default']);
	if (empty($id))
		$id = $params['name'];

	$db = &DB();
	$result = $db->Execute(sqlSelect($db,'product','id,sku',sprintf('(host=0 OR host IS NULL) AND active=1 AND price_type=1 AND id!=%s',$params['exclude']),'sku'));
	if ($result && $result->RecordCount()) {
		printf('<select id="%s" name="%s[]" size="%s" multiple="multiple">',$id,$params['name'],$params['size']);
		while (! $result->EOF) {
			$sel = '';
			foreach ($default as $cur)
				if ($cur == $result->fields['id'])
					$sel = ' selected="selected"';

			printf('<option value="%s"%s>%s</option>',$result->fields['id'],$sel,$result->fields['sku']);
			$result->MoveNext();
		}
		echo '</select>';
	}
}
?>