<?php
/**
 * Plugin element to render text area
 * @package fabrikar
 * @author Rob Clayburn
 * @copyright (C) Rob Clayburn
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

require_once(JPATH_SITE.DS.'components'.DS.'com_fabrik'.DS.'models'.DS.'element.php');

class FabrikModelFabrikTextarea extends FabrikModelElement {

	var $_pluginName = 'textarea';

	/**
	 * Constructor
	 */

	function __construct()
	{
		parent::__construct();
	}

	/**
	 * tagify a string
	 * @param string to tagify
	 * @return string tagified string
	 */

	protected function tagify($data)
	{
		$name = $this->getFullName(false, true, false);
		$params =& $this->getParams();
		$tableModel =& $this->getTableModel();
		$filters = $tableModel->getFilterArray();
		$fkeys = JArrayHelper::getValue($filters, 'key', array());

		$data = explode(",", strip_tags($data));
		$tags = array();
		$url = $params->get('textarea_tagifyurl');
		if ($url == '') {
			$url = $_SERVER['REQUEST_URI'];
			$bits = explode('?', $url);
			$bits = JArrayHelper::getValue($bits, 1, '', 'string');
			$bits = explode("&", $bits);
			foreach ($bits as $bit) {
				$parts = explode("=", $bit);
				if (count($parts) > 1) {
					$key = FabrikString::ltrimword(FabrikString::safeColNameToArrayKey($parts[0]), '&');
					if ($key == $this->getFullName(false, true, false)) {
						$url = str_replace($key.'='.$parts[1], '', $url);
					}
				}
			}
		}
		foreach ($data as $d) {
			$d = trim($d);
			if ($d != '') {
				if (trim($params->get('textarea_tagifyurl')) == '') {
					$qs = strstr($url, '?');
					if (substr($url, -1) === '?') {
						$thisurl = "$url$name=$d";
					} else {
						$thisurl = strstr($url, '?') ? "$url&$name=".urlencode($d) : "$url?$name=".urlencode($d);
					}
				} else {
					$thisurl = str_replace('{tag}', urlencode($d), $url);
				}
				$tags[] = "<a href=\"$thisurl\" class=\"fabrikTag\">$d</a>";
			}
		}
		return implode(" ", $tags);
	}

	/**
	 * shows the data formatted for the table view
	 * @param string data
	 * @param object all the data in the tables current row
	 * @return string formatted value
	 */

	function renderTableData($data, $oAllRowsData)
	{
		$data = parent::renderTableData($data, $oAllRowsData);
		$params =& $this->getParams();

		if ($params->get('textarea-tagify') == true) {
			$data = $this->tagify( $data);
		}
		//$$$rob dont strip slashes here - this is done when saving to db now

		if ($params->get('use_wysiwyg', 0) == 0) {
			if (is_array($data)) {
				for ($i=0; $i<count($data); $i++) {
					$data[$i] = nl2br($data[$i]);
				}
			} else {
				$data = nl2br($data);
			}
		}
		if (!$params->get('textarea-tagify') && $data !== '' && (int)$params->get('textarea-truncate', 0) !== 0) {
			$opts = array();
			$opts['wordcount'] = (int)$params->get('textarea-truncate', 0);
			$opts['tip'] = $params->get('textarea-hover');
			$data = fabrikString::truncate( $data, $opts);
		}
		return $data;
	}

	/**
	 * state if the element uses a wysiwyg editor
	 */

	function useEditor()
	{
		$params =& $this->getParams();
		$element =& $this->getElement();
		if ($params->get('use_wysiwyg', 0)) {
			return preg_replace("/[^A-Za-z0-9]/", "_", $element->name);
		} else {
			return false;
		}
	}

	/**
	 * determines if the element can contain data used in sending receipts, e.g. fabrikfield returns true
	 */

	function isReceiptElement()
	{
		return true;
	}

	/**
	 * draws the form element
	 * @param int repeat group counter
	 * @return string returns element html
	 */

	function render($data, $repeatCounter = 0)
	{
		$name		 	= $this->getHTMLName($repeatCounter);
		$id 			= $this->getHTMLId($repeatCounter);
		$element	=& $this->getElement();
		if ($element->hidden == '1') {
			return $this->getHiddenField($name, $data[$name], $id);
		}
		$params 		=& $this->getParams();
		$cols 			= $element->width;
		$rows 			= $element->height;
		$value 			= $this->getValue($data, $repeatCounter);
		if (!$this->_editable) {
			if ($params->get('use_wysiwyg', 0) == 0) {
				$value = nl2br($value);
			}
			if ($params->get('textarea-tagify') == true) {
				$value = $this->tagify( $value);
			}
			return $value;
		}
		$errorCSS  = '';
		if (isset($this->_elementError) && $this->_elementError != '') {
			$errorCSS = " elementErrorHighlight";
		}
		if ($params->get('use_wysiwyg')) {
			$str = FabrikHelperHTML::getEditorArea($name, $value, $name, $cols, $rows, $cols, $rows);
		} else {
			$str = "<textarea class=\"fabrikinput inputbox$errorCSS\" name=\"$name\" id=\"". $id. "\" cols=\"$cols\" rows=\"$rows\">".$value."</textarea>\n";
		}
		if ($params->get('textarea-showmax')) {
			$charsLeft = $params->get('textarea-maxlength') - strlen($value);
			$str .= "<div class=\"fabrik_characters_left\"><span>" . $charsLeft . "</span> " . JText::_('Characters left') . "</div>";
		}

		return $str;
	}

	/**
	 * used to format the data when shown in the form's email
	 * @param mixed element's data
	 * @param array form records data
	 * @param int repeat group counter
	 * @return string formatted value
	 */

	protected function _getEmailValue($value, $data = array(), $repeatCounter = 0)
	{
		return $this->renderTableData($value, new stdClass());
	}

	/**
	 * get db field description
	 * @return string db field description
	 */

	function getFieldDescription()
	{
		$p = $this->getParams();
		if ($this->encryptMe()) {
			return 'BLOB';
		}
		return "TEXT";
	}

	/**
	 * return tehe javascript to create an instance of the class defined in formJavascriptClass
	 * @param int repeat group counter
	 * @return string javascript to create instance. Instance name must be 'el'
	 */

	function elementJavascript($repeatCounter)
	{
		$version = new JVersion();
		$params =& $this->getParams();
		if ($params->get('use_wysiwyg')) {
			// $$$ rob need to use the NAME as the ID when wysiwyg end in joined group
			$id		 	= $this->getHTMLName($repeatCounter);
			if ($this->_inDetailedView) {
				$id .= "_ro";
			}
		} else {
			$id = $this->getHTMLId($repeatCounter);
		}
		$opts =& $this->getElementJSOptions($repeatCounter);
		//tinymce version changed in J 1.5.12 - all of its methods have changed!
		$opts->tinymce = ($version->RELEASE == '1.5' && $version->DEV_LEVEL >= 12) ? 3: 2;
		$opts->max = $params->get('textarea-maxlength');
		$opts->wysiwyg = $params->get('use_wysiwyg') ? true: false;
		$opts->deleteOverflow = $params->get('delete_overflow', true) ? true : false;
		$opts = FastJSON::encode($opts);
		return "new fbTextarea('$id', $opts)";
	}

		/**
	 * can be overwritten in adddon class
	 *
	 * checks the posted form data against elements INTERNAL validataion rule - e.g. file upload size / type
	 * @param string elements data
	 * @param int repeat group counter
	 * @return bol true if passes / false if falise validation
	 */

	function validate( $data, $repeatCounter = 0  )
	{
		$params 		=& $this->getParams();
		if (!$params->get('textarea-showmax', false)) {
			return true;
		}
		if ($params->get('delete_overflow', true)) {
			return true;
		}
		if (JString::strlen($data) > (int)$params->get('textarea-maxlength')) {
			return false;
		}
		return true;
	}

	/**
	 * @return string error message raised from failed validation
	 */

	function getValidationErr()
	{
		return JText::_('PLG_ELEMENT_TEXTAREA_CONTENT_TOO_LONG');
	}


	/**
	 * load the javascript class that manages interaction with the form element
	 * should only be called once
	 * @return string javascript class file
	 */

	function formJavascriptClass()
	{
		FabrikHelperHTML::script('javascript.js', 'components/com_fabrik/plugins/element/fabriktextarea/', false);
	}

	/**
	 * @return string joomfish translation type e.g. text/textarea/referenceid/titletext
	 */

	function getJoomfishTranslationType()
	{
		return 'textarea';
	}

	/**
	 * @return array key=>value options
	 */

	function getJoomfishOptions()
	{
		$params = $this->getParams();
		$return  = array();
		if ($params->get('textarea-showmax')) {
			$return['maxlength'] = $params->get('textarea-maxlength');
		}
		return $return;
	}

	/**
	 * can the element's data be encrypted
	 */

	public function canEncrypt()
	{
		return true;
	}
}
?>