<?php
/**
 * @version $Id: mi_mysql_query.php 16 2007-07-02 13:29:29Z mic $
 * @package AEC - Account Control Expiration - Subscription component for Joomla! OS CMS
 * @subpackage Micro Integrations - MySQL Query
 * @copyright 2006/2007 Copyright (C) David Deutsch
 * @author David Deutsch <skore@skore.de> & Team AEC - http://www.globalnerd.org
 * @license GNU/GPL v.2 http://www.gnu.org/copyleft/gpl.html
 */

/***
 * This version copyright (c) 2008 by Martin Brampton
 * martin@remository.com
 * http://www.remository.com
 * Modified to correctly integrate with Remository
 */

defined( '_VALID_MOS' ) OR defined('_JEXEC') OR die( 'Direct Access to this location is not allowed.' );

// Temporary definitions so this file can be used with earlier Remository releases
if (!defined('_DOWN_AEC_OPTION_A')) DEFINE ('_DOWN_AEC_OPTION_A', 'Just apply group(s) below.');
if (!defined('_DOWN_AEC_OPTION_B')) DEFINE ('_DOWN_AEC_OPTION_B', 'Delete ALL, then apply group(s) below.');
if (!defined('_DOWN_AEC_OPTION_C')) DEFINE ('_DOWN_AEC_OPTION_C', 'Delete Group Set on Application, then apply group(s) below.');

class mi_remository {
	public $settings = array();
	private $absolute_path = '';
	private $interface = null;
	private $database = null;
	private $authoriser = null;
	private $dbprefix = '';
	
	// This needs review for compatibility with Joomla 1.5 native or Aliro
	// Other methods should be safe
	public function __construct () {
		if (!defined('_JLEGACY') AND method_exists('mosMainFrame', 'getInstance')) $mainframe = mosMainFrame::getInstance();
		else global $mainframe;
		$this->absolute_path = $mainframe->getCfg('absolute_path');
		require_once($this->absolute_path.'/components/com_remository/remository.interface.php');
		$this->interface = remositoryInterface::getInstance();
		$this->database = $this->interface->getDB();
	}
	
	public function Info() {
		return array ('name' => _AEC_MI_NAME_REMOS, 'desc' => _AEC_MI_DESC_REMOS);
	}

	public function checkInstallation() {
		$this->database->setQuery("SHOW TABLES LIKE '#__acctexp_mi_remository'");
		$results = $this->database->loadObjectList();
		return empty($results) ? false : true;
	}

	public function install() {
		$query = 'CREATE TABLE IF NOT EXISTS `#__acctexp_mi_remository` ('
		. '`id` int(11) NOT NULL auto_increment,'
		. '`userid` int(11) NOT NULL,'
		. '`active` int(4) NOT NULL default 1,'
		. '`granted_downloads` int(11) NOT NULL default 0,'
		. '`unlimited_downloads` int(3) NOT NULL default 0,'
		. '`used_downloads` int(11) NOT NULL default 0,'
		. '`params` text NOT NULL,'
		. ' PRIMARY KEY (`id`)'
		. ')'
		;
		$this->database->setQuery( $query );
		$this->database->query();
	}

	public function Settings () {
		$this->includeRemCore();
		foreach ($this->authoriser->getAllRoles() as $role) {
			$sg[] = mosHTML::makeOption( $role, $role);
		}

		$del_opts[0] = mosHTML::makeOption ( "No", _DOWN_AEC_OPTION_A );
		$del_opts[1] = mosHTML::makeOption ( "All", _DOWN_AEC_OPTION_B );
		$del_opts[2] = mosHTML::makeOption ( "Set", _DOWN_AEC_OPTION_C );

		$settings['add_downloads'] = array( 'inputA' );
		$settings['set_downloads'] = array( 'inputA' );
		$settings['set_unlimited'] = array( 'list_yesno' );

		$current_groups = explode(';', $this->settings['group']);
		$settings['lists']['group']	= mosHTML::selectList($sg, 'group[]', 'size="4" multiple="multiple"', 'value', 'text', $current_groups);
		$current_groups_exp = explode(';', $this->settings['group_exp']);
		$settings['lists']['group_exp']	= mosHTML::selectList($sg, 'group_exp[]', 'size="4" multiple="multiple"', 'value', 'text', $current_groups_exp);

		$settings['set_group'] = array( 'list_yesno' );
		$settings['group'] = array( 'list' );
		$settings['lists']['delete_on_exp'] = mosHTML::selectList( $del_opts, 'delete_on_exp', 'size="3"', 'value', 'text', $this->settings['delete_on_exp'] );
		$settings['delete_on_exp'] = array( 'list' );
		$settings['set_group_exp'] = array( 'list_yesno' );
		$settings['group_exp'] = array( 'list' );

		return $settings;
	}

	// ??????
	public function saveparams( $params ) {
		$params['group'] = implode(';', $params['group']);
		$params['group_exp'] = implode(';', $params['group_exp']);
		return $params;
	}

	public function detect_application() {
		return is_dir( $this->absolute_path.'/components/com_remository/c-classes' );
	}

	public function hacks() {
		return array();
	}

	public function expiration_action ($request) {
		$this->includeRemCore();
		if ( 'Set' == $this->settings['delete_on_exp'] ) {
			$roles = explode(';', $this->settings['group']);
			foreach ($roles as $role) $this->authoriser->unassign($role, 'aUser', $request->metaUser->userid);
		}

		if ( 'All' == $this->settings['delete_on_exp'] ) {
			$this->authoriser->dropAccess('aUser', $request->metaUser->userid);
		}

		if ($this->settings['set_group_exp']) {
			$roles = explode(';', $this->settings['group_exp']);
			foreach ($roles as $role) $this->authoriser->assign($role, 'aUser', $request->metaUser->userid);
		}

		$mi_remositoryhandler = new remository_restriction( $this->database );
		$mi_id = $mi_remositoryhandler->getIDbyUserID( $request->metaUser->userid );
		$mi_remositoryhandler->load( $mi_id );

		if ( $mi_id ) $mi_remositoryhandler->deactivateAndStore();

		return true;
	}

	public function action ($request) {
		$this->includeRemCore();
		if ( !empty($this->settings['set_group']) ) {
			$roles = explode(';', $this->settings['group']);
			foreach ($roles as $role) $this->authoriser->assign($role, 'aUser', $request->metaUser->userid);
		}

		$mi_remositoryhandler = new remository_restriction( $this->database );
		$mi_id = $mi_remositoryhandler->getIDbyUserID( $request->metaUser->userid );
		$mi_remositoryhandler->load( $mi_id );

		if ( !$mi_id ) $mi_remositoryhandler->activate($request->metaUser->userid);

		if ( $this->settings['set_downloads'] ) {
			$mi_remositoryhandler->setDownloads( $this->settings['set_downloads'] );
		} 
		elseif ( $this->settings['add_downloads'] ) {
			$mi_remositoryhandler->addDownloads( $this->settings['add_downloads'] );
		}

		$mi_remositoryhandler->checkAndStore();

		return true;
	}
	
	private function includeRemCore () {
		require_once($this->absolute_path.'/components/com_remository/remository.class.php');
		$this->authoriser = aliroAuthorisationAdmin::getInstance();
		$lang = $this->interface->getCfg('lang');
		$langdir = $this->absolute_path.'/components/com_remository/language/';
		$Small_Text_Len = $Large_Text_Len = 100;
		if (file_exists($langdir.$lang.'.php')) require_once($langdir.$lang.'.php');
		require_once($langdir.'english.php');
	}
}

class remository_restriction extends mosDBTable {
	/** @var int Primary key */
	private $id					= null;
	/** @var int */
	private $userid 			= null;
	/** @var int */
	private $active				= null;
	/** @var int */
	private $granted_downloads	= null;
	/** @var int */
	private $unlimited_downloads	= null;
	/** @var text */
	private $used_downloads		= null;
	/** @var text */
	private $params				= null;

	// Constructor
	public function __construct ($db) {
		parent::__construct( '#__acctexp_mi_remository', 'id', $db );
	}

	public function getIDbyUserID ($userid) {
		$userid = intval($userid);
		$query = "SELECT `id` FROM #__acctexp_mi_remository WHERE `userid` = $userid";
		$this->_db->setQuery( $query );
		$result = $this->_db->loadResult();
		return $result ? $result : 0;
	}


	public function is_active() {
		return $this->active ? true : false;
	}

	public function getDownloadsLeft() {
		return empty( $this->unlimited_downloads ) ? ($this->granted_downloads - $this->used_downloads) : 9999;
	}

	public function hasDownloadsLeft() {
		return $this->getDownloadsLeft() > 0 ? true : false;
	}

	public function useDownload() {
		return ( $this->is_active() AND $this->hasDownloadsLeft() ) ? ($this->incrementDownloadStore() OR true) : false;
	}
	
	public function activate ($userid=0) {
		if ($userid) $this->userid = $userid;
		$this->active = 1;
	}
	
	public function deactivateAndStore () {
		$this->active = 0;
		$this->checkAndStore();
	}
	
	public function incrementDownloadStore () {
		$this->used_downloads++;
		$this->checkAndStore();
	}
	
	public function checkAndStore () {
		$this->check();
		$this->store();
	}

	public function setDownloads ($set) {
		$this->granted_downloads = $set;
	}

	public function addDownloads ($add) {
		$this->granted_downloads += $add;
	}
}