<?php
/**
* @version	$Id: prerequisites.php 16432 2016-11-18 09:30:26Z alex $
* @package	In-Portal
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license      GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* 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 http://www.in-portal.org/license for copyright notices and details.
*/

	defined('FULL_PATH') or die('restricted access!');

	$prerequisite_class = 'InPortalPrerequisites';

	/**
	 * Class, that holds all prerequisite scripts for "In-Portal" module
	 *
	 */
	class InPortalPrerequisites {

		/**
		 * Install toolkit instance
		 *
		 * @var kInstallToolkit
		 */
		var $_toolkit = null;

		/**
		* Connection to database
		*
		* @var IDBConnection
		* @access protected
		*/
		protected $Conn = null;

		/**
		 * Version upgrade rules
		 *
		 * @var array
		 * @access private
		 */
		private $upgradeRules = Array (
			'5.0.0' => Array ('from' => '5.0.0-B1', 'to' => '5.1.0-B1'),
			'5.1.0' => Array ('from' => '5.1.0-B1', 'to' => '5.2.0-B1'),
			'5.2.0' => Array ('from' => '5.2.0-B1', 'to' => '5.3.0-B1'),
		);

		/**
		 * Sets common instance of installator toolkit
		 *
		 * @param kInstallToolkit $instance
		 */
		function setToolkit(&$instance)
		{
			$this->_toolkit =& $instance;
		}

		/**
		 * Checks minimal version, that could be upgradeable
		 *
		 * @return IDBConnection
		 */
		function getConnection()
		{
			return $this->_toolkit->Conn;
		}

		/**
		 * Checks minimal version, that could be upgradeable
		 *
		 * @param Array $versions
		 * @param string $mode when called mode {install, upgrade, standalone)
		 * @return Array
		 */
		function CheckPrerequisites($versions, $mode)
		{
			$errors = Array ();

			if ( $mode == 'upgrade' ) {
				$sql = 'SELECT Version
						FROM ' . TABLE_PREFIX . 'Modules
						WHERE Name = "In-Portal"';
				$inportal_version = $this->getConnection()->GetOne($sql);

				if ( $inportal_version === false ) {
					// only, when In-Portal was installed (below 4.3.x)
					return $errors;
				}

				$min_version = '4.3.1'; // K4-based installator was created, that no longer maintained old upgrade scripts

				if ( version_compare($inportal_version, $min_version, '<') ) {
					$errors[] = 'Please upgrade "In-Portal" to version ' . $min_version . ' first';
				}

				// example: to upgrade to 5.1.0-B1 or more you at least need to have 5.0.0 installed
				foreach ($this->upgradeRules as $min_version => $version_rules) {
					if ( version_compare($versions[0], $version_rules['from'], '<') && version_compare($versions[1], $version_rules['to'], '>=') ) {
						$errors[] = 'Please upgrade "In-Portal" to version ' . $min_version . ' first';
						break;
					}
				}
			}

			return $errors;
		}

		/**
		 * Returns information about system requirements
		 *
		 * @return array
		 */
		function CheckSystemRequirements()
		{
			$ret = Array ();
			$ret['php_version'] = version_compare(PHP_VERSION, '5.3.2', '>=');

			if ( function_exists('apache_get_modules') ) {
				$mod_rewrite = in_array('mod_rewrite', apache_get_modules());
			}
			else {
				$mod_rewrite = getenv('HTTP_MOD_REWRITE') == 'On';
			}

			$ret['url_rewriting'] = $mod_rewrite;
			$ret['memcache'] = class_exists('Memcache');
			$ret['curl'] = function_exists('curl_init');
			$ret['simplexml'] = function_exists('simplexml_load_string');
			$ret['spl'] = function_exists('spl_autoload_register');
			$ret['freetype'] = function_exists('imagettfbbox');

			$ret['gd_version'] = false;

			if ( function_exists('gd_info') ) {
				$gd_info = gd_info();
				$gd_version = preg_replace('/[^\d.]/', '', $gd_info['GD Version']);
				$ret['gd_version'] = version_compare($gd_version, '1.8', '>=');
			}

			$ret['jpeg'] = function_exists('imagecreatefromjpeg');
			$ret['mysql'] = function_exists('mysqli_connect');
			$ret['json'] = function_exists('json_encode');

			$output = shell_exec('java -version 2>&1');
			$ret['java'] = stripos($output, 'java version') !== false;

			$ret['composer'] = file_exists(FULL_PATH . '/vendor/autoload.php');

			$ret['memory_limit'] = $this->isPhpSettingChangeable('memory_limit', '33M');
			$ret['display_errors'] = $this->isPhpSettingChangeable('display_errors', '1');
			$ret['error_reporting'] = $this->canChangeErrorReporting();
			$ret['date.timezone'] = ini_get('date.timezone') != '';
			$ret['variables_order'] = $this->_hasLetters(ini_get('variables_order'), Array ('G', 'P', 'C', 'S'));

			$output_buffering = strtolower(ini_get('output_buffering'));
			$ret['output_buffering'] = $output_buffering == 'on' || $output_buffering > 0;

			return $ret;
		}

		/**
		 * Determines of a setting string has all given letters (ignoring order) in it
		 *
		 * @param string $setting
		 * @param Array $search_letters
		 * @return bool
		 * @access protected
		 */
		protected function _hasLetters($setting, $search_letters)
		{
			$setting = preg_replace('/(' . implode('|', $search_letters) . ')/', '*', $setting);

			return substr_count($setting, '*') == count($search_letters);
		}

		/**
		 * Detects if error reporting can be changed at runtime
		 *
		 * @return bool
		 * @access protected
		 */
		protected function canChangeErrorReporting()
		{
			$old_value = error_reporting(E_PARSE);
			$new_value = error_reporting();

			if ( $new_value == E_PARSE ) {
				error_reporting($old_value);

				return true;
			}

			return false;
		}

		/**
		 * Detects if setting of php.ini can be changed
		 *
		 * @param string $setting_name
		 * @param string $new_value
		 * @return bool
		 */
		protected function isPhpSettingChangeable($setting_name, $new_value)
		{
			$old_value = ini_get($setting_name);

			if ( ini_set($setting_name, $new_value) === false ) {
				return false;
			}

			ini_set($setting_name, $old_value);

			return true;
		}

		/**
		 * Returns information about DB requirements
		 *
		 * @return array
		 */
		function CheckDBRequirements()
		{
			// check PHP version 5.2+
			$ret = Array();

			$sql = 'SELECT VERSION()';
			$conn = $this->getConnection();

			$db_version = preg_replace('/[^\d.]/', '', $conn->GetOne($sql));
			$ret['version'] = version_compare($db_version, '5.0', '>=');

			$sql = 'SHOW VARIABLES LIKE "max_allowed_packet"';
			$db_variables = $conn->Query($sql, 'Variable_name');

			$ret['packet_size'] = $db_variables['max_allowed_packet']['Value'] >= 1048576;

			return $ret;
		}
	}
