<?php
/**
 * Mobile Joomla! Pro
 * http://www.mobilejoomla.com
 *
 * @version		1.2.13.pro
 * @license		GNU/GPL v2 - http://www.gnu.org/licenses/gpl-2.0.html
 * @copyright	(C) 2008-2015 Kuneri Ltd.
 * @date		February 2015
 */
defined('_JEXEC') or die('Restricted access');

function isDowngrade()
{
	static $downgrade;
	if(!isset($downgrade))
		$downgrade = !preg_match('#\.pro$#', MjInstaller::MJ_version());
	return $downgrade;
}

function MJAddonLoadLanguageOverrides()
{
	if(isDowngrade())
		return;

	$lang = JFactory::getLanguage();

	// a trick to get user's language
	$lang_tag = $lang->setLanguage('en-GB');
	$lang->setLanguage($lang_tag);

	$path = $lang->getLanguagePath(dirname(__FILE__), $lang_tag);
	if(!JFile::exists($path))
		$lang_tag = 'en-GB';

	$lang->load('mjpro', dirname(__FILE__), $lang_tag);
}

function MJAddonUpdateConfig(&$MobileJoomla_Settings)
{
	if(isDowngrade())
	{
		// Uninstall MJPro plugin on downgrade
		MJAddonUninstallPlugins();
		JFile::delete(JPATH_ADMINISTRATOR.'/components/com_mobilejoomla/packages/install.addons.php');
		return;
	}

	MJAddonLoadLanguageOverrides();

	$defValues = array(
		'hiresimages'=>1, 'hijpegquality'=>80,
		'tablet.template'=>'', 'tablet.homepage'=>'', 'tablet.gzip'=>'', 'tablet.domain'=>'', 'tablet.buffer_width'=>30,
		'tablet.header1'=>'mj_tablet_header', 'tablet.header2'=>'mj_tablet_header2', 'tablet.header3'=>'mj_all_header',
		'tablet.middle1'=>'mj_tablet_middle', 'tablet.middle2'=>'mj_tablet_middle2', 'tablet.middle3'=>'mj_all_middle',
		'tablet.componenthome'=>'', 'tablet.removetags'=>'',
		'tablet.footer1'=>'mj_tablet_footer', 'tablet.footer2'=>'mj_tablet_footer2', 'tablet.footer3'=>'mj_all_footer',
		'tablet.jfooter'=>1, 'tablet.img'=>'', 'tablet.img_addstyles'=>''
	);
	foreach($defValues as $key=>$val)
		if(!isset($MobileJoomla_Settings[$key]))
			$MobileJoomla_Settings[$key] = $val;
}

//function MJAddonInstallTemplates($TemplateSource){}

//function MJAddonInstallModules($ModuleSource){}

function MJAddonInstallPlugins($PluginSource)
{
	if(isDowngrade())
		return true;

	//install mjpro plugin
	$status = true;
	if(!MjInstaller::InstallPlugin('mobile', $PluginSource, 'mjpro', 1, -1))
	{
		JError::raiseError(0, JText::_('COM_MJ__CANNOT_INSTALL').' Mobile Joomla Pro');
		$status = false;
	}

	//uninstall terawurfl
	if(MjInstaller::getExtensionId('plugin', 'terawurfl', 'mobile') !== null)
	{
		if(!MjInstaller::UninstallPlugin('mobile', 'terawurfl'))
		{
			JError::raiseError(0, JText::_('COM_MJ__CANNOT_UNINSTALL').' Mobile - TeraWURFL.');
			$status = false;
		}
		MjInstaller::clear_terawurfl_db();
	}

	return $status;
}

function MJAddonUninstallPlugins()
{
	MJAddonLoadLanguageOverrides();

	$status = true;
	if(!MjInstaller::UninstallPlugin('mobile', 'mjpro'))
	{
		JError::raiseError(0, JText::_('COM_MJ__CANNOT_UNINSTALL').' Mobile Joomla Pro');
		$status = false;
	}

	return $status;
}

//function MJAddonUninstallTemplates(){}

//function MJAddonUninstallModules(){}

function MJAddonPostInstall(&$postInstallActions)
{
	if(isDowngrade())
		return;

	$postInstallActions['installScientia'] = false;

	$ok = MJAddonRemoteCheck::activateRemote();

	$db = JFactory::getDBO();
	$ok = $ok ? '1' : '0';
	if(!MjInstaller::isJoomla15())
		$query = "UPDATE #__extensions SET enabled = $ok WHERE element = 'amdd' AND folder = 'mobile'";
	else
		$query = "UPDATE #__plugins SET published = $ok WHERE element = 'amdd' AND folder = 'mobile'";
	$db->setQuery($query);
	$db->query();
}

class MJAddonRemoteCheck
{
	static $timeout = 2;

	public static function activateRemote()
	{
		jimport('joomla.registry.format');
		$db = JFactory::getDBO();

		$table = MjInstaller::isJoomla15() ? '#__plugins' : '#__extensions';
		$db->setQuery("SELECT params FROM $table WHERE element = 'mjpro' AND folder = 'mobile'");
		$data = $db->loadResult();
		$parser = JRegistryFormat::getInstance(isJoomla15() ? 'ini' : 'json');
		$data = $parser->stringToObject($data);
		if(!isset($data))
			$data = new stdClass;

		if(isset($data->contype) && $data->contype=='')
			return false;

		$data->contype   = isset($data->contype)   ? $data->contype   : '';
		$data->timeout   = isset($data->timeout)   ? $data->timeout   : 10;
		$data->cachetime = isset($data->cachetime) ? $data->cachetime : 60;

		$data->contype = MJAddonRemoteCheck::check($data->contype);
		$ok = ($data->contype!='');
		if(!$ok)
			JError::raiseWarning(0, 'Connection to api.mobilejoomla.com is blocked.');
		$data = $parser->objectToString($data, array());
		$db->setQuery("UPDATE $table SET params = ".$db->Quote($data)." WHERE element = 'mjpro' AND folder = 'mobile'");
		$db->query();

		return $ok;
	}

	public static function check($mode)
	{
		$checked = array('fsock'=>0, 'curl'=>0, 'stream'=>0);
		if($mode)
		{
			if(self::doCheck($mode))
				return $mode;
			$checked[$mode]=1;
		}
		foreach($checked as $mode=>$status)
			if(!$status && self::doCheck($mode))
				return $mode;
		return '';
	}

	private static function doCheck($mode)
	{
		$method = 'check'.$mode;
		return self::$method();
	}

	private static function checkFsock()
	{
		if(!function_exists('fsockopen'))
			return false;
		$fp = @fsockopen('api.mobilejoomla.com', 80, $errno, $errstr, self::$timeout);
		if(!$fp)
			return false;

		$request = "GET /ping.txt HTTP/1.0\r\n";
		$request.= "Host: api.mobilejoomla.com\r\n";
		$request.= "Connection: close\r\n\r\n";
		if(!fwrite($fp, $request))
			return false;

		while(!feof($fp))
			fread($fp, 32768);

		$info = stream_get_meta_data($fp);
		fclose($fp);
		if($info['timed_out'])
			return false;
		return true;
	}

	private static function checkCurl()
	{
		if(!function_exists('curl_init'))
			return false;
		$c = curl_init('http://api.mobilejoomla.com/ping.txt');
		curl_setopt($c, CURLOPT_HEADER, 0);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($c, CURLOPT_NOBODY, 1);
		curl_setopt($c, CURLOPT_TIMEOUT, self::$timeout);
		$content = curl_exec($c);
		curl_close($c);
		return ($content != false);
	}

	private static function checkStream()
	{
		if(!ini_get('allow_url_fopen'))
			return false;
		$opts = array('http' => array('timeout' => self::$timeout, 'ignore_errors' => true) );
		$context = stream_context_create($opts);
		$content = file_get_contents('http://api.mobilejoomla.com/ping.txt', false, $context);
		return ($content != false);
	}
}