<?php
/**
 * @version		$Id: ckforms.php 10714 2009-07-24 09:00:00Z pierrerevest$
 * @package		CKForms
 * @subpackage	Content
 * @copyright	Copyright (C) 2008 - 2009 Open Source Matters. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * CKForms! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * See COPYRIGHT.php for copyright notices and details.
 */

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

jimport( 'joomla.plugin.plugin' );

/**
 * CKforms Content Plugin
 *
 * @package		CKforms
 * @subpackage	Content
 * @since 		1.3.4
 */
class plgContentCkFormsData extends JPlugin
{

	/**
	 * Constructor
	 *
	 * For php4 compatability we must not use the __constructor as a constructor for plugins
	 * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
	 * This causes problems with cross-referencing necessary for the observer design pattern.
	 *
	 * @param object $subject The object to observe
	 * @param object $params  The object that holds the plugin parameters
	 * @since 1.3.4
	 */
	function plgContentCkFormsData( &$subject, $params )
	{
		parent::__construct( $subject, $params );
		JPlugin::loadLanguage( 'plg_content_ckformsdata' );
		
	}

	/**
	 * CKForms prepare content method
	 *
	 * Method is called by the view
	 *
	 * @param 	object		The article object.  Note $article->text is also available
	 * @param 	object		The article params
	 * @param 	int			The 'page' number
	 */
	 
	function onPrepareContent( &$article, &$params, $limitstart )
    {
        $regex = '/{ckdata\s*(.*?)}/i';
		
        // find all instances of plugin and put in $matches
        preg_match_all( $regex, $article->text, $matches );

        // Number of plugins
        $count = count( $matches[0] );

		$j = 0;
        if ($count > 0) {
            foreach ($matches[1] as $i => $textFound) 
			{
				$start = 1;
				$number = 20;
				
				$plugin	=& JPluginHelper::getPlugin('content', 'ckformsdata');
				$pluginParams = new JParameter( $plugin->params );
				
				$displayBorders = $pluginParams->get( 'show_tableborder', '1');
				$displayColumnHeader = $pluginParams->get( 'show_columnheader', '1');
				$displayNavigation = $pluginParams->get( 'show_navigation', '1');

				$optregex = '/\[\s*(.*?)\]/i';
				preg_match_all( $optregex, $textFound, $optmatches);
				
				$opt = explode(" ", $textFound);
				$formname = $opt[0];

				$sortfield = JRequest::getVar($formname.'_sortf','created');
				$sortdirection = JRequest::getVar($formname.'_sortd','-1');
				$ckstart = JRequest::getVar($formname.'_ckstart','-1');
								
				if (count($optmatches[1]) > 0)
				{
					$optlist = explode(",", $optmatches[1][0]);
					
					foreach ($optlist as $k => $optFound) 
					{
						$opts = explode(":", $optFound);
						
						if (count($opts) == 2)
						{
							if (strcmp($opts[0],'start') == 0)
							{
								$start = $opts[1];
							} else if (strcmp($opts[0],'number') == 0)
							{
								$number = $opts[1];
							} else if (strcmp($opts[0],'showborder') == 0)
							{
								$displayBorders = $opts[1];
							} else if (strcmp($opts[0],'showheader') == 0)
							{
								$displayColumnHeader = $opts[1];
							} else if (strcmp($opts[0],'shownavigation') == 0)
							{
								$displayNavigation = $opts[1];
							}
						}
						
					}
				}
				if (strcmp($ckstart,'-1') != 0)
				{
					$start = $ckstart;
				}
				
            	// Load Selected form
                $form = $this->loadCkForm($formname);
				if ($form == null)
				{
				   $html = "<span style='color: #FF0000'>CKForms Error Message : <br />Form  '".$formname . "' not found !!!</span>";
				   $article->text = str_replace($matches[0][$j], $html, $article->text);
				   
				   return;
				}
								
 				$fields = $this->loadCkFormFields($form->id);
    
				$realSortfield = $sortfield;
				if (strcmp($sortfield,'created') != 0 && strcmp($sortfield,'ipaddress') != 0)
				{
					for ($j=0; $j < count( $fields ); $j++)
					{
						$rowField = $fields[$j];
						if (strcmp($sortfield,$rowField->name) == 0)
						{
							$realSortfield = 'F'.$rowField->id;
						}
					}
				}
				
                $data = $this->loadCkFormData($form->id,intval($start-1),$number,$realSortfield,$sortdirection);
				$total = $this->getFormDataTotal($form->id);
				
                $_SESSION['ck_send_once'.$form->id] = "1";

                $this->formLink = "index.php?option=com_ckforms&view=ckforms&task=send&id=".$form->id;
				
                $html = $this->generateCkFormHTML( $form, $fields, $data, $start, $number, $total, $sortfield,$sortdirection,$displayBorders,$displayColumnHeader,$displayNavigation);

                $article->text = str_replace($matches[0][$i], $html, $article->text);
				$j++;
            }
        }
	}

	/**
	 * CKForms load form data method
	 *
	 * Method is called by onPrepareContent method
	 *
	 * @param 	object		The form name
	 * @return	object
	 */
	function loadCkForm($name)
	{
		$db =& JFactory::getDBO();
		$query = "SELECT * FROM #__ckforms where name='".$name."'";
						
		$db->setQuery( $query );
		$data = $db->loadObject();

		return $data;
	}

	/**
	 * CKForms load fields data method
	 *
	 * Method is called by onPrepareContent method
	 *
	 * @param 	int		The form id
	 * @return	object
	 */
	function loadCkFormData($id,$start,$number,$sortfield,$sortdirection)
	{
		$db =& JFactory::getDBO();
		
		$tn = "#__ckforms_".$id;	
		$query = ' SELECT c.* from '.$tn.' c where c.published = 1 ';
		$query = $query .' order by '.$sortfield.' '.$sortdirection.' ';
		
		$db->setQuery($query,$start*$number, $number);
		$data = $db->loadObjectList();
		//echo "*".$db->getErrorMsg()."*";
		
		return $data;
	}

	/**
	 * CKForms load fields data method
	 *
	 * Method is called by onPrepareContent method
	 *
	 * @param 	int		The form id
	 * @return	object
	 */
	function getFormDataTotal($id)
	{
		$db =& JFactory::getDBO();
		
		$tn = "#__ckforms_".$id;	
		$query = ' SELECT count(*) as nb from '.$tn.' c where c.published = 1 ';

		$db->setQuery($query);
		$data = $db->loadObject();
		
		return $data->nb;
	}
	
	/**
	 * CKForms load fields data method
	 *
	 * Method is called by onPrepareContent method
	 *
	 * @param 	int		The form id
	 * @return	object
	 */
	function loadCkFormFields($id)
	{
		$db =& JFactory::getDBO();
		$query = ' SELECT * from #__ckfields c where c.fid='.$id." and (c.frontdisplay is null or c.frontdisplay = '1') and published=1  order by ordering asc";	

		$db->setQuery($query);
		$fields = $db->loadObjectList();
				
		return $fields;
	}

	/**
	 * CKForms generate form HTML method
	 *
	 * Method is called by onPrepareContent method
	 *
	 * @param 	object				The form data
	 * @param 	array of objects	The fields data
	 * @return	String
	 */
	function generateCkFormHTML($form, $fields, $data, $start, $number, $total, $sortfield, $sortdirection,$displayBorders,$displayColumnHeader,$displayNavigation)
	{
		global $mainframe;

		if ($form->published != '1') return '';
		
		$plugin	=& JPluginHelper::getPlugin('content', 'ckformsdata');
		$pluginParams = new JParameter( $plugin->params );
		
		$pageclass_sfx = $pluginParams->get( 'pageclass_sfx', '');
		
		$itemid = JRequest::getVar('Itemid','-1');
		$id = JRequest::getVar('id','-1');
		$lang = JRequest::getVar('lang');
		
		$html = '<style type="text/css">'."\n";
		$html = $html.'<!--'."\n";
		$html = $html.'#maincolumn  {'."\n";
		$html = $html.'	overflow:auto !important;'."\n";
		$html = $html.'}'."\n";
		$html = $html.'-->'."\n";
		$html = $html.'</style>'."\n";

		$html = $html.'<link rel="stylesheet" href="'.JURI::root(true).'/components/com_ckforms/css/ckforms.css" type="text/css" />'."\n";

		$html = $html.'<div class="componentheading'.$pageclass_sfx.'">'."\n";

		if (isset($form->fronttitle) == false || strcmp ($form->fronttitle, "") == 0)
		{
			$html = $html.$form->title."\n";
		} else {
			$html = $html.$form->fronttitle."\n";
		}

		$html = $html.'</div>'."\n";

		if (isset($form->frontdescription) == false || strcmp($form->frontdescription, "") == 0) 
		{ 
			$html = $html.'<p>'.$form->description."</p>"."\n";
		} else {
			$html = $html."<p>".$form->frontdescription."</p>"."\n";
		}

		$html = $html."<table class=\"ckdatatable ";
		if (isset($displayBorders) == false || strcmp($displayBorders,"1") == 0) 
		{
			$html = $html.'ckdatatableborder';
		}
		$html = $html.'">'."\n";

		if (isset($displayColumnHeader) == false || strcmp($displayColumnHeader,"1") == 0)
		{
			$link = 'index.php?option=com_content&view=article&id='.$id.'&Itemid='.$itemid.'&'.$form->name.'_ckstart='.$start;
			$navLink = 'index.php?option=com_content&view=article&id='.$id.'&Itemid='.$itemid;
			if (isset($lang)) 
			{
				$link = $link . '&lang='.$lang;
				$navLink = $navLink . '&lang='.$navLink;
			}
			
			$sortLink = JRoute::_($link);
			$navLink = JRoute::_($navLink);

			$html = $html.'<thead>'."\n";
			$html = $html.'    <tr>'."\n";
	
			$k = 0;
			$n=count( $fields );
			for ($i=0; $i < $n; $i++)
			{
				$rowField = $fields[$i];
		
				$t_texttype = "";		
				if ($rowField->typefield == 'text')
				{
					$opt = explode("[--]", $rowField->defaultvalue);
					$key1 = explode("===", $opt[0]);
					$key2 = explode("===", $opt[1]);
					$key3 = explode("===", $opt[2]);
					$t_texttype = $key3[1];
				}
				
				if (($rowField->typefield != 'text' && $rowField->typefield != 'button' && $rowField->typefield != 'fieldsep')
					 || ($rowField->typefield == 'text' && $t_texttype != 'password'))
				{			
	
					$html = $html.'    <td class="sectiontableheader">'."\n";
	
					$sortLinkURL = JRoute::_($sortLink."&".$form->name."_sortf=".$rowField->name);
					$navLinkURL = JRoute::_($navLink."&".$form->name."_sortf=".$rowField->name);
					$sortimg = '';
					if ($rowField->name == $sortfield)
					{
						if ($sortdirection == "asc")
						{
							$sortLinkURL = JRoute::_($sortLinkURL."&".$form->name."_sortd=desc");
							$navLinkURL = JRoute::_($navLinkURL."&".$form->name."_sortd=desc");
							$sortimg = ' <img src="images/sort_asc.png" />';
						} else {
							$sortLinkURL = JRoute::_($sortLinkURL."&".$form->name."_sortd=asc");
							$navLinkURL = JRoute::_($navLinkURL."&".$form->name."_sortd=asc");
							$sortimg = ' <img src="images/sort_desc.png" />';
						}
					} else {
						$sortLinkURL = JRoute::_($sortLinkURL."&".$form->name."_sortd=asc");
						$navLinkURL = JRoute::_($navLinkURL."&".$form->name."_sortd=asc");
					}
	
					$html = $html.'<a href="'.$sortLinkURL.'">'."\n";
					$html = $html.$rowField->label.$sortimg;
			
					$html = $html.'</a>'."\n";
					$html = $html.'</td>'."\n";
				}
			}
 	
			if ($form->displayip == '1') 
			{
	 
				$html = $html.'<td class="sectiontableheader">'."\n";
				$sortLinkURL = JRoute::_($sortLink."&".$form->name."_sortf=ipaddress");
				$navLinkURL = JRoute::_($navLink."&".$form->name."_sortf=ipaddress");
				$sortimg = '';
				if ($sortfield == 'ipaddress')
				{
					if ($sortdirection == "asc")
					{
						$sortLinkURL = JRoute::_($sortLinkURL."&".$form->name."_sortd=desc");
						$navLinkURL = JRoute::_($navLinkURL."&".$form->name."_sortd=desc");
						$sortimg = ' <img src="images/sort_asc.png" />';
					} else {
						$sortLinkURL = JRoute::_($sortLinkURL."&".$form->name."_sortd=asc");
						$navLinkURL = JRoute::_($navLinkURL."&".$form->name."_sortd=asc");
						$sortimg = ' <img src="images/sort_desc.png" />';
					}
				} else {
					$sortLinkURL = JRoute::_($sortLinkURL."&".$form->name."_sortd=asc");
					$navLinkURL = JRoute::_($navLinkURL."&".$form->name."_sortd=asc");
				}
			 
				$html = $html.'<a href="'.$sortLinkURL.'">'."\n";
				$html = $html.JText::_( 'IP Address' ).$sortimg;
			
				$html = $html.'</a>'."\n";
	
				$html = $html.'</td>'."\n";
			} 

			$html = $html.'</tr>'."\n";		
			$html = $html.'</thead>'."\n";
		}

		$k = 0;
		$n=count( $data );
		for ($i=0; $i < $n; $i++)
		{	
		
			$row = &$data[$i];
			$link = JRoute::_( 'index.php?option=com_content&view=article&id='.$id.'&Itemid='.$itemid);
	
			$html = $html.'<tr class="sectiontableentry1">'."\n";
			 
			$z=count( $fields );
			for ($j=0; $j < $z; $j++)
			{
			
				$rowField = $fields[$j];
		
				$t_texttype = "";		
				if ($rowField->typefield == 'text')
				{
					$opt = explode("[--]", $rowField->defaultvalue);
					$key1 = explode("===", $opt[0]);
					$key2 = explode("===", $opt[1]);
					$key3 = explode("===", $opt[2]);
					$t_texttype = $key3[1];
				}
				
				if (($rowField->typefield != 'text' && $rowField->typefield != 'button' && $rowField->typefield != 'fieldsep')
					 || ($rowField->typefield == 'text' && $t_texttype != 'password'))
				{			
					$prop="F".$rowField->id;
					if (isset($row->$prop) == false)
					{
						$prop=$rowField->name;
					}
					if (isset($row->$prop))
					{
						$texte = $row->$prop;
					} else {
						$texte = "&nbsp;";
					}
					
					if (strlen($texte) > 255) {
						$texte = substr($texte,0,255)."...";
					}
					
					if ($rowField->typefield == 'fileupload' && isset($row->$prop))
					{
						$texte = basename($row->$prop);
					}
					
					$isEmail = false;
					if ($rowField->typefield == 'text') {
						
						if ($t_texttype == 'email') {
							$isEmail = true;
						}
						
					}
				
					if ($isEmail == true) 
					{
						$linkfield = "mailto:".$texte;
					} 
					else 
					{
						$linkfield = $link;
					}
	 
					$html = $html.'<td>'."\n";
	 
					if (isset($row->$prop))
					{
						if (isset($form->displaydetail) == false || $form->displaydetail == true)
						{
							$html = $html.'<a href="'.$linkfield."\">".$texte.'</a>'."\n";
						} else {
							$html = $html.$texte; 
						}
					} else { 
						$html = $html.'&nbsp;'."\n";
					}
					
					$html = $html.'</td> '."\n";
		
				}
			}
	
			if ($form->displayip == '1') 
			{
				if (isset($form->displaydetail) == false || $form->displaydetail == true)
				{
					$html = $html.'<td><a href="'.$linkfield."\">".$row->ipaddress.'</a></td>'."\n";
				} else {
					$html = $html.'<td>'.$row->ipaddress.'</td>'."\n";
				}
			}
			$html = $html.'</tr>'."\n";
			
			$k = 1 - $k;
		}

		$html = $html.'</table> '."\n";
	
		if (strcmp($displayNavigation,'1') == 0 && $total > $number)
	   	{
			$nbpage = ceil($total / $number);
			
			$html = $html.'<div class="ckpagination">'."\n";
			$html = $html.'	<span class="pagination">'."\n";
			if (intval($start) > 1)
			{
				$html = $html.'		<span>&laquo;</span>'."\n";
				$LinkURL = JRoute::_($navLinkURL."&".$form->name."_ckstart=1");
				$html = $html.'		<a href="'.$LinkURL.'" title="'.JText::_('Start').'">'.JText::_('Start').'</a>'."\n";
				$LinkURL = JRoute::_($navLinkURL."&".$form->name."_ckstart=".(intval($start)-1));
				$html = $html.'		<a href="'.$LinkURL.'" title="'.JText::_('Prev').'">'.JText::_('Prev').'</a>'."\n";			
			}
			
			for ($i = 1; $i <= $nbpage; $i++) {
				if (intval($start) == $i)
				{
					$html = $html.'		<strong><span>'.$i.'</span></strong>'."\n";
				} else {
					$LinkURL = JRoute::_($navLinkURL."&".$form->name."_ckstart=".$i);
					$html = $html.'		<a href="'.$LinkURL.'" title="'.$i.'">'.$i.'</a>'."\n";
				}
			}
			
			if (intval($start) < (intval($nbpage)))
			{			
				$start = intval($start)+1;
				$LinkURL = JRoute::_($navLinkURL."&".$form->name."_ckstart=".$start);
				$html = $html.'		<a href="'.$LinkURL.'" title="'.JText::_('Next').'">'.JText::_('Next').'</a>'."\n";
				$LinkURL = JRoute::_($navLinkURL."&".$form->name."_ckstart=".$nbpage);
				$html = $html.'		<a href="'.$LinkURL.'" title="'.JText::_('End').'">'.JText::_('End').'</a>'."\n";
				$html = $html.'		<span>&raquo;</span>'."\n";
			}
			
			$html = $html.'	</span>'."\n";
			$html = $html.'</div>'."\n";
	   	}
		
		return $html;
	
	}

}
