<?php
/**
* @version $Id: index2.php 6022 2006-12-18 22:30:07Z friesengeist $
* @package Joomla
* @copyright Copyright (C) 2005 Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to 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 COPYRIGHT.php for copyright notices and details.
*/
define ('_JA_NEWSFLASH_CACHE_ENABLE', 0);

function setToCache ($order, $html) {
	if (!_JA_NEWSFLASH_CACHE_ENABLE) return '';
	$filename = JPATH_CACHE.'/cache_'.md5("ja-newsflashloader-$order");
	$f = fopen($filename, 'w');
	if($f) {
		fwrite ($f, $html);
		fclose ($f);
	}
	return;
}

function getFromCache ($order) {
	if (!_JA_NEWSFLASH_CACHE_ENABLE) return '';
	$filename = JPATH_CACHE.'/cache_'.md5("ja-newsflashloader-$order");
	if (is_file($filename))
		return file_get_contents ($filename);
	return '';
}

if (!defined ('_JEXEC')) {
	header('Content-Type: text/html; charset=utf-8');

	define( '_JEXEC', 1 );
	$path = dirname(dirname(dirname(dirname(__FILE__))));
	define('JPATH_BASE', $path );

	if (strpos(php_sapi_name(), 'cgi') !== false && !empty($_SERVER['REQUEST_URI'])) {
		//Apache CGI
		$_SERVER['PHP_SELF'] =  rtrim(dirname(dirname(dirname($_SERVER['PHP_SELF']))), '/\\');
	} else {
		//Others
		$_SERVER['SCRIPT_NAME'] =  rtrim(dirname(dirname(dirname($_SERVER['SCRIPT_NAME']))), '/\\');
	}
	
	define( 'DS', DIRECTORY_SEPARATOR );
	require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
	require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
	JDEBUG ? $_PROFILER->mark( 'afterLoad' ) : null;

	$mainframe =& JFactory::getApplication('site');
	
	// set the language
	$mainframe->initialise();
	// SSL check - $http_host returns <live site url>:<port number if it is 443>
	JPluginHelper::importPlugin('system', null, false);
	// trigger the onStart events
	$mainframe->triggerEvent( 'onStart' );

  $numrows = isset($_REQUEST['total'])?intval($_REQUEST['total']):0;
	$curnews = isset($_REQUEST['curnews'])?intval($_REQUEST['curnews']):0;
	$flashnum = $curnews;
	$html = getFromCache($flashnum);
	if ($html) {
		echo $html;
		return;
	}

	$splitter = md5("JA Flashnews");
	// SSL check - $http_host returns <live site url>:<port number if it is 443>

	// retrieve some expected url (or form) arguments
	$modid 	= intval( JArrayHelper::getValue( $_REQUEST, 'modid' , 0) ) ;
	$news 	= intval( JArrayHelper::getValue( $_REQUEST, 'news' , 0) ) ;
	$total 	= intval( JArrayHelper::getValue( $_REQUEST, 'total', 0 ) );
	$option = strval( strtolower( JArrayHelper::getValue( $_REQUEST, 'option' ) ) );

  $database = &JFactory::getDBO( );
	$my =  &JFactory::getUser();
	$gid = intval( $my->gid );

	$query = "SELECT params FROM #__modules WHERE id=$modid;";
	$database->setQuery($query);
	$params = $database->loadResult();
	$params = new JParameter ($params);

	function textprocess($string) {
		return $string;
	}

} else {
	global $mainframe;
	$database = &JFactory::getDBO( );
	$my =  &JFactory::getUser();
	//$query = "SELECT params FROM #__modules WHERE module = 'mod_janewsflash';";
	//$database->setQuery($query);
	//$params = $database->loadResult();
	//$params = new JParameter ($params);
	$splitter = "";

	function textprocess($string) {
		return $string;
	}
}

if (!defined( '_JA_NEWSFLASH' )) {
	/** ensure that functions are declared only once */
	define( '_JA_NEWSFLASH', 1 );

	function ja_output_newsflash( &$row, &$params, &$access ) {
		global $mainframe;

		$row->text 		= $row->introtext;
		$row->groups 	= '';
		$row->readmore 	= (trim( $row->fulltext ) != '') && ($params->get( 'readmore' ));
		$row->metadesc 	= '';
		$row->metakey 	= '';
		$row->access 	= '';
		$row->created 	= '';
		$row->modified 	= '';

		$params->set('image', 1);

		JPluginHelper::importPlugin('content', null, false);
		$results = $mainframe->triggerEvent( 'onPrepareContent', array( &$row, &$params, null ), true );

		$html = "";
		ja_linkInfo ($row, $params);

		$newTitle = "";
		if ($params->get('link_titles')) $newTitle .= "<a href=\"".$row->link_on."\" title=\"".$row->title."\">".$row->title."</a>";
		else $newTitle .= "".$row->title."";

		//Get image
		$regex = "/\<img.*\/\>/";

		preg_match ($regex, $row->text, $matches);
		$row->text = preg_replace ($regex, '', $row->text);

		$newReadmore 	=	"<a href=\"".$row->link_on."\" title=\"".$row->link_text."\">".$row->link_text."</a>";
		$html = str_replace("##TITLE##",$newTitle,$params->get("templates"));
		$html = str_replace("##CONTENT##",$row->text,$html);
		$img  = count($matches) ? $matches[0] : "";
		$html = str_replace("##IMAGE##", $img, $html);
		$html =	str_replace("##READMORE##",$newReadmore,$html);
		return $html;
	}

	function ja_linkInfo( &$row, &$params ) {
	require_once (JPATH_SITE . '/components/com_content/helpers/route.php');

		$my =  &JFactory::getUser();
		
		$row->link_on 	= '';
		$row->link_text	= '';

		if ($params->get( 'readmore' ) || $params->get( 'link_titles' )) {
			if ( $params->get( 'intro_only' ) ) {
				// checks if the item is a public or registered/special item
				if ( $row->access <= $my->get('aid', 0)) {
					
					$row->link_on =		JRoute::_(ContentHelperRoute::getArticleRoute($row->slug, $row->catslug, $row->sectionid));
					if ( isset($row->readmore) && @$row->readmore) {
						// text for the readmore link
						$row->link_text = _READ_MORE;
					}
				} else {
					$row->link_on = JRoute::_( 'index.php?option=com_user&amp;task=register' );

					if ( isset($row->readmore) && @$row->readmore ) {
						// text for the readmore link if accessible only if registered
						$row->link_text	= _READ_MORE_REGISTER;
					}
				}
			}
		}
	}
}

// Disable edit ability icon
$access = new stdClass();
$access->canEdit 	= 0;
$access->canEditOwn = 0;
$access->canPublish = 0;

$now 				= date( 'Y-m-d H:i' );
$noauth 			= !$mainframe->getCfg( 'shownoauth' );
$nullDate 			= $database->getNullDate();
$aid	= $my->get('aid', 0);
$catid 				= intval( $params->get( 'catid' ) );
$delaytime 		= intval( $params->get( 'delaytime', 0 ) );
$moduleclass_sfx    = $params->get( 'moduleclass_sfx' );
$link_titles		= $params->get( 'link_titles' );

$params->set( 'intro_only', 		1 );
$params->set( 'hide_author', 		1 );
$params->set( 'hide_createdate', 	0 );
$params->set( 'hide_modifydate', 	1 );
$params->set( 'link_titles', 		$link_titles );


$query = 'SELECT a.*,cc.description as catdesc, cc.title as cattitle,s.description as secdesc, s.title as sectitle,' .
			' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,'.
			' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":",cc.id,cc.alias) ELSE cc.id END as catslug,'.
			' CASE WHEN CHAR_LENGTH(s.alias) THEN CONCAT_WS(":", s.id, s.alias) ELSE s.id END as secslug'.
			' FROM #__content AS a' .
			' INNER JOIN #__categories AS cc ON cc.id = a.catid' .
			' INNER JOIN #__sections AS s ON s.id = a.sectionid';
			$query .=	' WHERE a.state = 1 ' .
			
			( $noauth ? "\n AND a.access <= " . (int) $aid . " AND cc.access <= " . (int) $aid . " AND s.access <= " . (int) $aid : '' ).
			' AND (a.publish_up = '.$database->Quote($nullDate).' OR a.publish_up <= '.$database->Quote($now).' ) ' .
			' AND (a.publish_down = '.$database->Quote($nullDate).' OR a.publish_down >= '.$database->Quote($now).' )' .
			
			' AND a.catid =' . (int) $catid.
			' AND cc.section = s.id' .
			' AND cc.published = 1' .
			' AND s.published = 1'.
			' ORDER BY a.ordering';
			
$database->setQuery( $query );
$rows = $database->loadObjectList();

$numrows = count( $rows );

// check if any results returned
if ( $numrows ) {
	if (!JArrayHelper::getValue($_GET,'loadajax',0)) {
		$flashnum = 0;
		srand ((double) microtime() * 1000000);
		$flashnum = rand( 0, $numrows-1 );
	}
	$row = $rows[$flashnum];
} else {
	echo "Please select a category for JA Newsflash!";	
	return;
}

$row->introtext = textprocess($row->introtext);
$row->fulltext = textprocess($row->fulltext);
$xheight = $params->get('xheight');

if (!JArrayHelper::getValue($_GET,'loadajax',0)) {

?>
	<script type="text/javascript">
	if (!self.jaNewsflash) {
		jaNewsflash = new Object();
	}
		jaNewsflash.animation = '<?php echo $params->get('animation'); ?>';
		jaNewsflash.livesite = '<?php echo JURI::base(); ?>';
		jaNewsflash.delaytime = <?php echo $delaytime; ?>;
		jaNewsflash.splitter = "97c8730aa693f60439cf3cf4558ce5ea";
		jaNewsflash.interval= <?php echo $params->get('animationtime'); ?>;
		jaNewsflash.currentItem = <?php echo $flashnum;?>;
		jaNewsflash.totalItem = <?php echo $numrows;?>;
		jaNewsflash.modid = <?php echo $module->id;?>;
	</script>
	<div style="position:relative; width:100%;height:<?php echo $xheight; ?>px; overflow:hidden;">
		<div id="ja-scroll_1" style="position:absolute; top:0;  left:0; width: 100%; display:block;">
	<?php
		$html = ja_output_newsflash( $row, $params, $access );
		setToCache ($flashnum, $html.$splitter.$flashnum);
		echo $html;
	?>
		</div>
		<div id="ja-scroll_2" style="position: absolute; top:0; left:0; width: 100%; display:none;">
		</div>
	</div>
	<?php
}
else{
	$html = ja_output_newsflash( $row, $params, $access );
	$html .= $splitter.$flashnum;

	setToCache ($flashnum, $html);
	echo $html;
	return;
}
?>
