<?php
/**
 * @package BILLETS
 * @link 	http://www.dioscouri.com
 * @license GNU/GPLv2
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport( 'joomla.application.component.model' );

/**
 * Billets Model
 *
 * @package BILLETS
 */
class BilletsModelAddons extends JModel {

	var $_data;
	var $_total;
	var $_pagination;
	var $_types;
	var $_type;

	/**
	 * constructor
	 * @return array Array of objects containing the data from the database
	 */	
	function __construct() {
		parent::__construct();
		global $mainframe;
		$config = JFactory::getConfig();

		// Get the pagination request variables
		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( 'billets.limitstart', 'limitstart', 0, 'int' );

		// In case limit has been changed, adjust limitstart accordingly
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);		
		$this->setState( 'order', strval( htmlspecialchars( $mainframe->getUserStateFromRequest( "order", 'order', 'id' ) ) ) );
		$this->setState( 'order_dir', strval( htmlspecialchars( $mainframe->getUserStateFromRequest( "order_dir", 'order_dir', 'asc' ) ) ) );

		// set the type
		$this->_type = strval( htmlspecialchars( $mainframe->getUserStateFromRequest( "type", 'type', 'lang' ) ) );
	}
	
	/**
	 * Returns the query
	 * @return string The query to be used to retrieve the rows from the database
	 */
	function _buildQuery() {
		global $mainframe;
		$database = &JFactory::getDBO();
		// ************************************** //
		//	RECORDS
		// ************************************** //
		$where = array();
		$lists = array();

		$search				= $mainframe->getUserStateFromRequest( 'search', 'search', '',	'string' );
		$search				= JString::strtolower($search);
		$limit				= $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart			= $mainframe->getUserStateFromRequest('limitstart', 'limitstart', 0, 'int');
			
		$type			= strval( htmlspecialchars( $mainframe->getUserStateFromRequest( 'type', 'type', ' ' ) ) );
		if ($type) {
			$type_query = " AND LOWER(r.type) LIKE '%" . $database->getEscaped( trim( strtolower( $type ) ) ) . "%'";
		}
	
		$status					= strval( htmlspecialchars( $mainframe->getUserStateFromRequest( "status", 'status', ' ' ) ) );	
		$status_query = "";	
		switch ($status) {
			case "published":
				$status_query = " AND r.published = '1' ";
			  break;
			case "unpublished":
				$status_query = " AND r.published = '0' ";
			  break;
		}
		
		if ($search) {
			$where[] = " LOWER(r.id) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
			$where[] = " LOWER(r.title) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
			$where[] = " LOWER(r.type) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
			$where[] = " LOWER(r.description) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
			$where[] = " LOWER(r.author_name) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
			$where[] = " LOWER(r.author_email) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
			$where[] = " LOWER(r.author_url) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
		}
	
		$order_query = "";
		$order = $this->getState( 'order' );
		$order_dir = $this->getState( 'order_dir' );
		switch ($order) {
			case "id":
				$order_query = " ORDER BY r.id ".strtoupper( $order_dir )." ";
			  break;
			case "title":
				$order_query = " ORDER BY r.title ".strtoupper( $order_dir )." ";
			  break;
			case "type":
				$order_query = " ORDER BY r.type ".strtoupper( $order_dir )." ";
			  break;
			case "published":
				$order_query = " ORDER BY r.published ".strtoupper( $order_dir )." ";
			  break;
			case "iscore":
				$order_query = " ORDER BY r.iscore ".strtoupper( $order_dir )." ";
			  break;
			case "author":
				$order_query = " ORDER BY r.author_name ".strtoupper( $order_dir )." ";
			  break;
			case "version":
				$order_query = " ORDER BY r.version ".strtoupper( $order_dir )." ";
			  break;
			default:
				$order_query = " ORDER BY r.title ".strtoupper( $order_dir )." ";
			  break;
		}
	
		// grab all records
		$query = "SELECT r.* FROM #__billets_addons as r "
		. " WHERE 1 "
		. $type_query 
		. (count( $where ) ? "\n HAVING " . implode( ' OR ', $where ) : "")
		. $order_query
		;
		
		return $query;
	}
	
	/**
	 * Retrieves the data
	 * @return array Array of objects containing the data from the database
	 */
	function getData() {
		// load the data if it doesn't already exist
		if (empty( $this->_data )) {
			$query = $this->_buildQuery();
			$this->_data = $this->_getList( $query, $this->getState('limitstart'), $this->getState('limit') );
		}
		return $this->_data;
	}

	/**
	 * Paginates the data
	 * @return array Array of objects containing the data from the database
	 */
	function getPagination() {
		if (empty($this->_pagination)) {
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}
		return $this->_pagination;
	}

	/**
	 * Retrieves the count 
	 * @return array Array of objects containing the data from the database
	 */
	function getTotal() {
		if (empty($this->_total)) {
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
	}
	
	/**
	 * Retrieves the types
	 * @return array Array of objects containing the data from the database
	 */
	function getTypes() {
		if (empty($this->_types)) {
			$database = &JFactory::getDBO();
			// types
			$types = array();
			$query = "SELECT DISTINCT(r.type) FROM #__billets_addons as r"
			. " WHERE 1 "
			. " ORDER BY r.type ASC "
			;
			$database->setQuery( $query );
			$allrows = $database->loadObjectList();
			$types[] = JHTML::_('select.option', ' ', "- "._BILLETS_SELECTTYPE." -" );
			if ($allrows) { foreach ($allrows as $a) {
				$types[] = JHTML::_('select.option', $a->type, $a->type );
			} }	
			$javascript 	= 'onchange="document.adminForm.submit();"';	
			$this->_types = JHTML::_('select.genericlist', $types, "type", "size='1' $javascript", "value", "text", $this->_type );
		}

		return $this->_types;
	}

	/**
	 * Retrieves the type
	 * @return array Array of objects containing the data from the database
	 */
	function getType() {
		if (empty($this->_type)) {
			global $mainframe;
			// set the type
			$this->_type = strval( htmlspecialchars( $mainframe->getUserStateFromRequest( "type", 'type', 'lang' ) ) );

		}

		return $this->_type;
	}
	
	/**
	* uploadAddon
	*/
	// ************************************************************************	
	function uploadAddon( ) {
		global $mainframe;
		$database = &JFactory::getDBO();
			
		$installer = new billetsAddon();
	
		// Check if file uploads are enabled
		if (!(bool)ini_get('file_uploads')) {
			$this->setError( _BILLETS_UPLOADSDISABLED );
			return false;
		}
	
		// Check that the zlib is available
		if(!extension_loaded('zlib')) {
			$this->setError( _BILLETS_ZLIBUNAVAILABLE );
			return false;
		}
	
		// check that filetype selected
		if (!$this->_type) {
			$this->setError( _BILLETS_NOFILETYPESELECTED );
			return false;
		}
		
		// check that userfile exists
		// $userfile = mosGetParam( $_FILES, 'userfile', null );
		$userfile = JArrayHelper::getValue( $_FILES, 'userfile', '', '' );		
		if (!$userfile) {
			$this->setError( _BILLETS_NOFILESELECTED );		
			return false;
		}
	
		$userfile_name = $userfile['name'];
		$msg = '';
		$resultdir = $installer->uploadAddonFile( $userfile['tmp_name'], $userfile['name'], $this->_type, $msg );
	
		$RetVal = explode ( '.', $userfile_name);
		$addon_filename = "";
		for ($p=0; $p <= count($RetVal)-2; $p++) {
			$addon_filename .= strtolower($RetVal[$p]);
		}
	
		if ($resultdir !== false) {
			// install billetsAddon		
			$ret = $installer->installAddon( $addon_filename, $this->_type );
			if ($ret) {
				$this->setError( _BILLETS_ADDONINSTALLED );
				// cleanupInstall( $userfile['name'], $installer->unpackDir() );
				return true;
			} else {
				$this->setError( _BILLETS_ADDONINSTALLFAILED." - ".$installer->getError() );
				// cleanupInstall( $userfile['name'], $installer->unpackDir() );
				return false;				
			}			
		} else {
				$this->setError( _BILLETS_UPLOADERROR." - ".$installer->getError() );
				return false;				
		}
	} // end uploadAddon
	// ************************************************************************	
	
	/**
	* uninstallAddon
	*/
	// ************************************************************************
	function uninstallAddon( ) {
		global $mainframe;
		$database = &JFactory::getDBO();
		
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );		
	
		if (!is_array( $cids ) || count( $cids ) < 1) {
			echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
			exit;
		}
		
		if (count( $cids )) {
			foreach ($cids as $id) {
				$row = new billetsAddonEntry( $database );
				// load the row from the db table
				$row->load( (int)$id );
				if ($row->id > 0 && $row->iscore != '1') {
				
					$type = $row->type;
					$filename = $row->filename;
					
					// change folder
					switch ($type) {
							case "mod":
								$baseDir = JPATH_COMPONENT_ADMINISTRATOR.DS.'modules';
								$dirname = "modules";
							  break;
							case "lang":
								$baseDir = JPATH_COMPONENT_SITE.DS.'languages';
								$dirname = "languages";
							  break;
							default:
								$link = 'index.php?option='._THISCOMPONENT.'&controller=addons&type='.$this->_type;
								$msg = _BILLETS_NOFILETYPESELECTED;
								$mainframe->redirect( $link, $msg, 'notice' );
								return false;
							  break;
					} // end switch type

					// if file not writable, fail and give notice
					if ( !is_writable( $baseDir . DS . $filename . ".php" ) ) {
						$link = 'index.php?option='._THISCOMPONENT.'&controller=addons&type='.$this->_type;
						$msg = _BILLETS_NOTWRITEABLEFILE;
						$mainframe->redirect( $link, $msg, 'notice' );
						return false;
					}
								
					// if file not exists, fail and notify
					if (!file_exists( $baseDir . DS . $filename . ".php" )) { 
						$link = 'index.php?option='._THISCOMPONENT.'&controller=addons&type='.$this->_type;
						$msg = _BILLETS_NOFILE;
						$mainframe->redirect( $link, $msg, 'notice' );
						return false;
					}
		
				
					// if file exists, delete it
					if (file_exists( $baseDir . DS . $filename . ".php" )) { 
						// delete the file
						unlink( $baseDir . DS . $filename . ".php" );
					} else {
						$link = 'index.php?option='._THISCOMPONENT.'&controller=addons&type='.$this->_type;
						$msg = _BILLETS_NOFILE;
						$mainframe->redirect( $link, $msg, 'notice' );
						return false;
					}
					
					// delete the database records
					$query = "DELETE FROM #__billets_addons "
					. "\n WHERE `filename` = '".$row->filename."' "
					. " AND `iscore` != '1' "
					;
					$database->setQuery( $query );
					$database->query();
					if ($database->getErrorNum()) {
						echo $database->stderr();
						return false;
					}

					$link = 'index.php?option='._THISCOMPONENT.'&controller=addons&type='.$this->_type;
					$msg = _BILLETS_ADDONUNINSTALLED;
					$mainframe->redirect( $link, $msg, 'message' );
					return true;
				}

				$link = 'index.php?option='._THISCOMPONENT.'&controller=addons&type='.$this->_type;
				$msg = _BILLETS_ADDONUNINSTALLFAILED;
				$mainframe->redirect( $link, $msg, 'notice' );
				return false;

			}
		}
		
	} // end uninstallAddon
	// ************************************************************************
	
		
}
// ************************************************************************
