<?php
/**
 * @version $Id: bfChecks.php 139 2010-01-03 20:45:41Z  $
 * @package Blue Flame Framework (bfFramework)
 * @copyright Copyright (C) 2003,2004,2005,2006,2007,2008,2009 Blue Flame IT Ltd. All rights reserved.
 * @license GNU General Public License
 * @link http://www.blueflameit.ltd.uk
 * @author Phil Taylor / Blue Flame IT Ltd.
 *
 * bfFramework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * bfFramework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this package.  If not, see http://www.gnu.org/licenses/
 */
defined ( '_JEXEC' ) or die ( 'Restricted access' );

final class bfChecks {
	
	private $warnings = 0;
	private $warningsHTML = array ();
	
	private $errors = 0;
	private $errorHTML = array ();
	
	/**
	 * I run the checks
	 */
	public function runchecks() {
		
		$popup = bfRequest::getVar ( 'pop', null );
		if ($popup)
			return;
		
		$this->_setPermissions ();
		
		/* checks likely to error */
		$this->_checkXajaxPlubished ();
		$this->_checkValidDomain ();
		$this->_checkJPromoter ();
		$this->_checkFireboard ();
		$this->_checkSMFBridge ();
		$this->_checkJoomlaVersion ();
		$this->_checkDBTables ();
		$this->_check_OLD_XAJAX ();
		
		$this->_checkSPLAvailable ();
		
		/* checks likely to warn */
		$this->_checkIE ();
		$this->_checkLatestVersion ();
		$this->_checkFish ();
		$this->_checkTagsMambot ();
		$this->_checkKBSearchMambot ();
		
		/* clean up environment */
		$this->_cleanUpOldStuff ();
		
		if ($this->errors !== 0) {
			return $this->_displayErrors ();
		}
		
		if ($this->warnings !== 0) {
			$this->_displayWarnings ();
		}
	}
	
	/**
	 * Class 'DirectoryIterator' not found
	 */
	private function _checkSPLAvailable() {
		
		if (! class_exists ( 'DirectoryIterator' )) {
			$this->errors ++;
			$this->errorHTML [] = bfText::_ ( 'Your PHP Installation is missing the SPL which is normally a standard and default in an installation of PHP.  More details can be found here: http://docs.php.net/manual/en/book.spl.php - until SPL is available you cannot use our extensions (remember: SPL is free and NORMALLY part of EVERY PHP5 installation)' );
		}
	}
	
	private function _checkXajaxPlubished() {
		$refreshNeeded = false;
		/* Pull in the bfFramework - or install framework! */
		if (_BF_PLATFORM == 'JOOMLA1.5') {
			$db = & JFactory::getDBO ();
			$db->setQuery ( "update `#__plugins` set published = 1 WHERE `name` = 'Blue Flame Framework inc. xAJAX'" );
			$db->query ();
			$db->setQuery ( "SELECT count(*) FROM `#__plugins` WHERE `name` = 'Blue Flame Framework inc. xAJAX'" );
			$sqlok = $db->loadResult ();
			if (! $sqlok) {
				$db->setQuery ( "INSERT INTO `#__plugins` (
`id` ,
`name` ,
`element` ,
`folder` ,
`access` ,
`ordering` ,
`published` ,
`iscore` ,
`client_id` ,
`checked_out` ,
`checked_out_time` ,
`params`
)
VALUES (
NULL , 'Blue Flame Framework inc. xAJAX', 'xajax', 'system', '0', '0', '1', '1', '0', '0', '0000-00-00 00:00:00', ''
);
" );
				$db->query ();
				$db->setQuery ( "SELECT count(*) FROM `#__plugins`WHERE `name` = 'Blue Flame Framework inc. xAJAX'" );
				$sqlok = $db->loadResult ();
				if ($sqlok)
					$refreshNeeded = true;
			}
		} else {
			global $database;
			$database->setQuery ( "update `#__mambots` set published = 1 WHERE `name` = 'Blue Flame Framework inc. xAJAX'" );
			$database->query ();
			$database->setQuery ( "SELECT count(*) FROM `#__mambots`WHERE `name` = 'Blue Flame Framework inc. xAJAX'" );
			$sqlok = $database->loadResult ();
			if (! $sqlok) {
				$database->setQuery ( "INSERT INTO `#__mambots` VALUES ('', 'Blue Flame Framework inc. xAJAX', 'xajax.system', 'system', 0, 0, 1, 0, 0, 0, '0000-00-00 00:00:00', '');" );
				$database->query ();
				$database->setQuery ( "SELECT count(*) FROM `#__mambots`WHERE `name` = 'Blue Flame Framework inc. xAJAX'" );
				$sqlok = $database->loadResult ();
				if ($sqlok)
					$refreshNeeded = true;
			}
		}
		if ($refreshNeeded) {
			$this->errors ++;
			$this->errorHTML [] = '<span style="color: red; font-weight: bolder;">' . bfText::_ ( 'Maintenance tasks complete (xajax plugin reinstatement - AUTO HEAL) - Please refresh the page' ) . '</span>';
			return false;
		}
		if (! $sqlok) {
			$this->errors ++;
			$this->errorHTML [] = '<span style="color: red; font-weight: bolder;">' . bfText::_ ( 'Could not set the xAJAX plugin to published - cant get it to work - contact support!' ) . '</span>';
		
		}
	}
	
	/**
	 * I set the correct permissions to run this application
	 *
	 */
	private function _setPermissions() {
		
		if (__BF_SKIP_PERMSCHECK === false) {
			clearstatcache ();
			$filesPerm = octdec ( substr ( sprintf ( '%o', fileperms ( bfCompat::getAbsolutePath () . '/index.php' ) ), - 4 ) );
			$folderPerm = octdec ( substr ( sprintf ( '%o', fileperms ( bfCompat::getAbsolutePath () . '/components' ) ), - 4 ) );
			
			@chmod ( bfCompat::getAbsolutePath () . DS . bfCompat::mambotsfoldername () . DS . 'system', 0755 );
			@chmod ( bfCompat::getAbsolutePath () . DS . bfCompat::mambotsfoldername () . DS . 'system' . DS . 'blueflame', $folderPerm );
			@chmod ( bfCompat::getAbsolutePath () . DS . bfCompat::mambotsfoldername () . DS . 'system' . DS . 'blueflame' . DS . 'bfCombine.php', $filesPerm );
			@chmod ( bfCompat::getAbsolutePath () . DS . bfCompat::mambotsfoldername () . DS . 'system' . DS . 'blueflame' . DS . 'xajax_0.5_beta_4' . DS . 'adminentry.php', $filesPerm );
			@chmod ( bfCompat::getAbsolutePath () . DS . bfCompat::mambotsfoldername () . DS . 'system' . DS . 'blueflame' . DS . 'xajax_0.5_beta_4' . DS . 'entry.php', $filesPerm );
			@chmod ( bfCompat::getAbsolutePath () . DS . bfCompat::mambotsfoldername () . DS . 'system' . DS . 'blueflame' . DS . 'cache', $folderPerm );
			@chmod ( bfCompat::getAbsolutePath () . DS . bfCompat::mambotsfoldername () . DS . 'system' . DS . 'blueflame' . DS . 'libs' . DS . 'smarty' . DS . 'templates_c', $folderPerm );
			@chmod ( bfCompat::getAbsolutePath () . DS . 'components' . DS . 'com_form' . DS . 'plugins' . DS . 'layouts' . DS . 'custom', $folderPerm );
		}
	}
	
	private function _checkFish() {
		
		/*
		 * depreciated at the moment
		 */
		return;
		
		$registry = & bfRegistry::getInstance ();
		if ($registry->getValue ( 'joomfish_compatible' ) === false)
			return;
		$fish = _BF_JPATH_BASE . DS . bfCompat::mambotsfoldername () . DS . 'system' . DS . 'jfdatabase.systembot.php';
		if (@file_exists ( $fish )) {
			$this->warnings ++;
			$this->warningsHTML [] = '<img src="components/com_joomfish/images/fish.png" align="right" style="padding:20px;padding-bottom:50px;"><h2 style="color: orange; font-weight: bolder;">You have Joom!fish installed</h2>
							<span>

				' . $registry->getValue ( 'Component.Title' ) . ' has a content element xml for that, <a href="#" onclick="killTinyMCE();jQuery(\'div.col85\').fadeOut(\'fast\');bfHandler(\'xplugins\')">click here</a> for instructions for installing it</span><br /><br />';
		}
	}
	
	private function _checkJPromoter() {
		global $mainframe;
		$filename = _BF_JPATH_BASE . DS . bfCompat::mambotsfoldername () . DS . 'system' . DS . 'jpromoter.metaedit.php';
		if (@file_exists ( $filename )) {
			$contents = file_get_contents ( $filename );
			if (preg_match ( '/session_name/i', $contents )) {
				return;
			}
			
			$this->errors ++;
			$this->errorHTML [] = bfText::_ ( 'You have the JPromoter System Mambot installed. The JPromoter System Mambot doesnt handle Joomla Session Management correctly.' ) . '<br /><br />' . bfText::_ ( ' We can help you with that though :-) -' ) . '<a href="index2.php?option=' . $mainframe->get ( 'component' ) . '&entry_task=jpromoter">' . bfText::_ ( 'Click here' ) . '</a>' . ' ' . bfText::_ ( 'to make a small 1 line change to the JPromoter System Mambot to ensure compatibility' );
			if (! file_exists ( $filename ) or ! is_writeable ( $filename )) {
				$this->errorHTML [] = '<br/><br/><b>The file is not writeable - fix this and then refresh this page<br />
					' . $filename . '</b>';
			}
		}
	}
	
	private function _checkFireboard() {
		global $mainframe;
		$filename = _BF_JPATH_BASE . DS . 'components' . DS . 'com_fireboard' . DS . 'fireboard.php';
		if (@file_exists ( $filename )) {
			$contents = file_get_contents ( $filename );
			if (preg_match ( '/session_name/i', $contents )) {
				return;
			}
			
			$this->warnings ++;
			$this->warningsHTML [] = bfText::_ ( 'You have the Fireboard Forum Extension installed. If you have problems with fireboard please read this <a href="http://blog.phil-taylor.com/2008/01/30/fireboard-conflict-with-joomlakb-and-joomlatags/">FAQ Blog Article</a>' );
		}
	}
	
	private function _checkSMFBridge() {
		global $mainframe;
		
		$filename = _BF_JPATH_BASE . DS . bfCompat::mambotsfoldername () . DS . 'system' . DS . 'SMF_header_include.php';
		if (@file_exists ( $filename )) {
			$contents = file_get_contents ( $filename );
			if (preg_match ( '/_IS_XAJAX_CALL/i', $contents )) {
				return;
			}
			
			$this->errors ++;
			$this->errorHTML [] = bfText::_ ( 'You have the SMF Forum Bridge installed.  The SMFBridge uses complex system plugins the same way this component does and therefore there is a conflict' ) . '<br /><br />' . bfText::_ ( ' We can help you with that though :-) -' ) . '<a href="index2.php?option=' . $mainframe->get ( 'component' ) . '&entry_task=smfbridge">' . bfText::_ ( 'Click here' ) . '</a>' . ' ' . bfText::_ ( 'to make a small 1 line change to the SMF bridge to ensure compatibility' );
			if (! file_exists ( $filename ) or ! is_writeable ( $filename )) {
				$this->errorHTML [] = '<br/><br/><b>The file is not writeable - fix this and then refresh this page<br />
					' . $filename . '</b>';
			}
		}
	}
	
	private function _checkLatestVersion() {
		
		if (_SKIP_UPDATE_CHECK === true)
			return;
		
		global $mainframe;
		
		/* not in popup view */
		$tmpl = bfRequest::getVar ( 'tmpl' );
		if ($tmpl == 'component')
			return;
		
		if (function_exists ( 'file_get_contents' )) {
			
			$versions = @file_get_contents ( 'http://www.phil-taylor.com/versions.php' );
			
			if (@$versions) {
				$registry = & bfRegistry::getInstance ( $mainframe->get ( 'component' ) );
				/* check my component version */
				$xml = new bfXml ( );
				$arr = $xml->parse ( $versions, null );
				
				foreach ( $arr ['component'] as $component ) {
					
					if ($component ['name'] == $registry->getValue ( 'Component.Title' )) {
						
						//						if ($component ['version'] > $registry->getValue ( 'Component.Version' )) {
						if (version_compare ( $component ['version'], $registry->getValue ( 'Component.Version' ), '>' )) {
							$txt = 'There is a new version of ' . $registry->getValue ( 'Component.Title' ) . ' available!';
							echo "<script>bfversioncheck = \"jQuery.jGrowl('" . $txt . "', { theme:  'red',	speed:  'slow', sticky: true, header: 'New Version Available'})\";</script>";
						}
						
						//						if ($component ['version'] < $registry->getValue ( 'Component.Version' )) {
						if (version_compare ( $component ['version'], $registry->getValue ( 'Component.Version' ), '<' )) {
							$txt = 'This version of ' . $registry->getValue ( 'Component.Title' ) . ' has not yet been released - SVN Rev ' . $registry->getValue ( 'Component.Version' );
							echo "<script>bfversioncheck = \"jQuery.jGrowl('" . $txt . "', {  theme:  'yellow',	speed:  'slow', header: 'Version Check' , life: 5000 });\";</script>";
						}
						//						if ($component ['version'] == $registry->getValue ( 'Component.Version' )) {
						if (version_compare ( $component ['version'], $registry->getValue ( 'Component.Version' ), '=' )) {
							$txt = 'This version of ' . $registry->getValue ( 'Component.Title' ) . ' is the latest version - we just checked :-)';
							echo "<script>bfversioncheck = \"jQuery.jGrowl('" . $txt . "', { theme:  'green',	speed:  'slow', header: 'Version Check' , life: 5000 });\";</script>";
						
						}
					}
				
				}
			}
		
		}
	}
	
	/**
	 * Check the Joomla version
	 */
	private function _checkJoomlaVersion() {
		if (class_exists ( 'JVersion' ) && _BF_PLATFORM == 'JOOMLA1.5') {
			$version = new JVersion ( );
			if ($version->RELEASE != '1.5') {
				$this->errors ++;
				$this->errorHTML [] = '<span style="color: red; font-weight: bolder;">' . bfText::_ ( 'You must upgrade to the latest Joomla 1.5.x version in order to run this component' ) . '</span>';
			} else {
				if ($version->RELEASE == '1.5' && $version->DEV_LEVEL < '14') {
					$this->errors ++;
					$this->errorHTML [] = '<span style="color: red; font-size: 14px; font-weight: bolder;">' . bfText::_ ( 'You must upgrade to the latest Joomla 1.5.14 version in order to run this component - This is for your own good, for your own stability and security, and also to ensure that our applications environment is secure - the last thing you need right now is to get hacked though an old version of Joomla! right?<br/><br/><br/>If you need help upgrading please <a href="https://secure.phil-taylor.com/contact">contact us using the form here </a>' ) . '</span>';
				}
			}
		} else {
			global $_VERSION;
			if ($_VERSION->DEV_LEVEL < 15) {
				$this->errors ++;
				$this->errorHTML [] = '<span style="color: red; font-weight: bolder;">' . bfText::_ ( 'You must upgrade to the latest Joomla 1.0.x in order to run this component' ) . '</span>';
			}
		}
	}
	
	/**
	 * Clean up dust form old things
	 *
	 */
	private function _cleanUpOldStuff() {
		
		/* Remove tags component mambot */
		$filename = _BF_JPATH_BASE . DS . bfCompat::mambotsfoldername () . DS . 'content' . DS . 'tag.php';
		if (file_exists ( $filename )) {
			@chmod ( $filename, 0777 );
			@unlink ( $filename );
		}
		
		/* remove duplicate plugins */
		$db = bfCompat::getDBO ();
		$db->setQuery ( "SELECT count(*) FROM `#__" . bfCompat::mambotsfoldername () . "` WHERE `name` = 'Blue Flame Framework inc. xAJAX'" );
		$num = $db->loadResult ();
		if ($num >= "2") {
			$db->setQuery ( "DELETE FROM `#__" . bfCompat::mambotsfoldername () . "` WHERE `name` = 'Blue Flame Framework inc. xAJAX' LIMIT " . ($num - 1) );
			$db->query ();
		}
	
	}
	
	/**
	 * make sure we have the correct tables for this component - if not install them!
	 *
	 */
	private function _checkDBTables() {
		bfLoad ( 'bfDBUtils' );
		$check = new bfDBUtils ( );
		$check->checktables ();
		$check->checkComponentLink ();
	}
	
	/**
	 * I am interested in the version of the xAJAX Mambot installed.
	 * I need to be the blue flame one!!
	 */
	private function _check_OLD_XAJAX() {
		$db = bfCompat::getDBO ();
		$db->setQuery ( "SELECT count(*) FROM `#__" . bfCompat::mambotsfoldername () . "` WHERE `name` = 'XAJAX System Mambot For Joomla'" );
		$installed = $db->loadResult ();
		
		if ($installed) {
			$this->errors ++;
			$this->errorHTML [] = '<span style="color: red; font-weight: bolder;">' . bfText::_ ( 'You must remove the xAJAX system mambot that is currently installed.  Then return here and this component will help you install the updated version of xAJAX Plugin.' ) . '</span>';
		}
	}
	
	/**
	 * I display the results to the user
	 *
	 */
	private function _displayErrors() {
		$registry = bfRegistry::getInstance ();
		$pre = '<div style="text-align: left;width: 500px;background-color: #fff;border: 5px solid red;  margin: 0 auto;padding: 15px; font-weight: bolder;">
		<h1>' . $registry->getValue ( 'Component.Title' ) . ' ' . bfText::_ ( 'System Check' ) . '</h1>';
		$post = '</div>';
		
		echo $pre . implode ( '<br /><br />', $this->errorHTML ) . $post;
		return false;
	}
	
	private function _displayWarnings() {
		
		$pre = '<div onClick="jQuery(this).hide();" id="warnings" style="margin-bottom: 20px; margin: 0 auto; text-align: left;width: 500px;background-color: #fff;border: 5px solid orange; padding: 15px; font-weight: bolder;">';
		$post = ' <span style="float:right"><a href="#" onClick="jQuery(\'#warnings\').hide();">Dismiss</a></span></div>';
		echo $pre . implode ( '<br /><br />', $this->warningsHTML ) . $post;
	}
	
	private function _checkValidDomain() {
		$parts = explode ( '/', bfCompat::getLiveSite () );
		if (! preg_match ( '/'.$parts [2].'/i', $_SERVER ['HTTP_HOST'] )) {
			$info = file_get_contents ( dirname ( __FILE__ ) . DS . 'view' . DS . 'sameorignpolicy.php' );
			$info = str_replace ( '###HOST###', $_SERVER ['HTTP_HOST'], $info );
			$info = str_replace ( '###LIVESITE###', bfCompat::getLiveSite (), $info );
			$this->errors ++;
			$this->errorHTML [] = $info;
		}
	}
	
	/**
	 * @depreciated December 2009
	 */
	private function _checkSiteOnline() {
		$registry = & bfRegistry::getInstance ();
		$offline = bfCompat::isOffline ();
		if ($offline == true) {
			$this->errors ++;
			$this->errorHTML [] = bfText::_ ( "Your site needs to be set to online in the Joomla global configuration for" ) . $registry->getValue ( 'Component.Title' ) . bfText::_ ( "to work <br/><br/>This is required for XAJAX mambot, which powers the" ) . $registry->getValue ( 'Component.Title' ) . bfText::_ ( "admin console" );
		}
	}
	
	private function _checkIE() {
		if ($this->_detect_ie () === true) {
			define ( '_BF_IS_IE', true );
		} else {
			define ( '_BF_IS_IE', false );
		}
	}
	
	private function _detect_ie() {
		if (isset ( $_SERVER ['HTTP_USER_AGENT'] ) && (strpos ( $_SERVER ['HTTP_USER_AGENT'], 'MSIE' ) !== false))
			return true;
		else
			return false;
	}
	
	private function _checkTagsMambot() {
		$registry = & bfRegistry::getInstance ();
		if ($registry->getValue ( 'Component.Title' ) == "Joomla Tags") {
			if (! file_exists ( bfCompat::getAbsolutePath () . "/mambots/content/content.tag.php" )) {
				$this->warnings ++;
				$this->warningsHTML [] = '
				<h2>Tags Content Mambot</h2><br />
				<span style="color: red; font-weight: bolder;">
				' . bfText::_ ( 'You currently do not have the JoomlaTags Content mambot installed.' ) . '<br /><br />' . bfText::_ ( 'If you wish to add/view tags via the front end, please install the mambot by visiting the addons section of the admin control panel' ) . '</span>';
			}
		}
	}
	
	private function _checkKBSearchMambot() {
		$registry = & bfRegistry::getInstance ();
		if (preg_match ( "/Joomla Knowledgebase/i", $registry->getValue ( 'Component.Title' ) )) {
			if (_BF_PLATFORM == 'JOOMLA1.5') {
				$file = bfCompat::getAbsolutePath () . "/" . bfCompat::mambotsfoldername () . "/search/searchkb.php";
			} else {
				$file = bfCompat::getAbsolutePath () . "/" . bfCompat::mambotsfoldername () . "/search/search.kb.php";
			}
			if (! file_exists ( $file )) {
				$this->warnings ++;
				$this->warningsHTML [] = '
				<h2 style="color: orange; font-weight: bolder;">Search Mambot</h2><br />
				<span>
				<img src="../' . bfCompat::mambotsfoldername () . '/system/blueflame/view/images/warning.png" align="left" style="padding:20px;padding-bottom:50px;">
				' . bfText::_ ( 'You currently do not have the Joomla Knowledgebase Search mambot installed.' ) . '<br /><br />' . bfText::_ ( 'If you wish to search for Joomla Knowledgebase articles on the front end, please install the mambot by visiting the addons section of the admin control panel' ) . '</span>';
			}
		}
	
	}
}