<?php
/**
 * NoNumber! Extension Manager Model
 *
 * @package     NoNumber! Extension Manager
 * @version     1.4.0
 *
 * @author      Peter van Westen <peter@nonumber.nl>
 * @link        http://www.nonumber.nl
 * @copyright   Copyright (C) 2010 NoNumber! All Rights Reserved
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

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

// Import MODEL object class
jimport( 'joomla.application.component.model' );

/**
 * NoNumber! Extension Manager Model
 */
class NoNumberManagerModelModel extends JModel
{
	/**
	 * Extensions data
	 *
	 * @var array
	 */
	var $_extensions = null;

	/**
	 * Host
	 *
	 * @var string
	 */
	var $_host = null;

	/**
	 * table_prefix - table prefix for all component table
	 *
	 * @var string
	 */
	var $_table_prefix = null;

	/**
	 * Custom Constructor
	 */
	function __construct()
	{
		parent::__construct();

		// initialize class property
		$this->_table_prefix = '#__';

		$xmlfile = JPATH_COMPONENT.DS.'extensions.xml';
		$xml =& JFactory::getXMLParser( 'Simple' );
		// Load the file
		if ( !$xml || !$xml->loadFile( $xmlfile ) ) {
			return null;
		}

		$host = parse_url( JURI::root(false) );
		$this->_host = strtolower( $host['host'] );
		if ( $this->_host == '127.0.0.1' ) {
			$this->_host = 'localhost';
		}

		$this->extensions = array();

		$ext = $this->initItem();
		$ext->name = JText::_( 'All extensions' );
		$ext->id = 'all';
		$ext->alias = 'all';
		$this->extensions[$ext->id] = $ext;

		foreach ( $xml->document->children() as $item ) {
			$item = $item->_attributes;
			$ext = $this->initItem();
			if ( isset( $item['name'] ) ) {
				$ext->name = $item['name'];
				$ext->id = isset( $item['id'] ) ? $item['id'] : preg_replace( '#[^a-z\-]#', '', str_replace( '?', '-', strtolower( $ext->name ) ) );
				$ext->alias = isset( $item['alias'] ) ? $item['alias'] : $ext->id;
				$this->extensions[$ext->alias] = $ext;
			}
		}
	}

	/**
	 * Get the extensions data
	 */
	function getData()
	{
		require_once JPATH_PLUGINS.DS.'system'.DS.'nonumberelements'.DS.'helpers'.DS.'licenses.php';
		$licenses = NNLicenses::instance();

		$db =& JFactory::getDBO();
		$sql = "SELECT * FROM #__nonumber_licenses GROUP BY extension";
		$db->setQuery( $sql );
		$licensecodes = $db->loadObjectList( 'extension' );

		foreach ( $licensecodes as $licensecode ) {
			if ( isset( $this->extensions[$licensecode->extension] ) ) {
				$this->extensions[$licensecode->extension]->code = $licensecode->code;
			}
		}
	}

	/**
	 * Return an empty extension item
	 */
	function initItem()
	{
		$item = '';
		$item->name = '';
		$item->id = '';
		$item->alias = '';
		$item->code = '';
		return $item;
	}
}