<?php

eval( ' function xoops_module_install_'.$mydirname.'( $module ) { return d3news_oninstall_base( $module , "'.$mydirname.'" ) ; } ' ) ;


if( ! function_exists( 'd3news_oninstall_base' ) ) {

function d3news_oninstall_base( $module , $mydirname )
{
	// transations on module install

	$isCube = false ;
	if( ! is_array( $ret ) ) $ret = array() ;

	$db =& icms_db_Factory::instance() ;
	$mid = $module->getVar('mid') ;


	// transations on module installation
	$d3news_posting_permissions = array( 1 , 2 , 3 , 4, 7 ) ;
	$gperm_handler = xoops_gethandler('groupperm') ;
	foreach( $d3news_posting_permissions as $itemid ) {
		$gperm =& $gperm_handler->create() ;
		$gperm->setVar( 'gperm_groupid' , 1 ) ;
		$gperm->setVar( 'gperm_name' , 'd3news_permit' );
		$gperm->setVar( 'gperm_modid' , $mid ) ;
		$gperm->setVar( 'gperm_itemid' , $itemid ) ;
		$gperm_handler->insert( $gperm ) ;
	}

	// TABLES (loading mysql.sql)
	$sql_file_path = dirname(__FILE__).'/sql/mysql.sql' ;
	$prefix_mod = $db->prefix() . '_' . $mydirname ;
	if( file_exists( $sql_file_path ) ) {
		$ret[] = "SQL file found at <b>".htmlspecialchars($sql_file_path)."</b>.<br  /> Creating tables...<br />";

		$sqlutil = new icms_db_legacy_mysql_Utility();
		$sql_query = trim( file_get_contents( $sql_file_path ) ) ;
		$sqlutil->splitMySqlFile( $pieces , $sql_query ) ;
		$created_tables = array() ;
		foreach( $pieces as $piece ) {
			$prefixed_query = $sqlutil->prefixQuery( $piece , $prefix_mod ) ;
			if( ! $prefixed_query ) {
				$ret[] = "Invalid SQL <b>".htmlspecialchars($piece)."</b><br />";
				return false ;
			}
			if( ! $db->query( $prefixed_query[0] ) ) {
				$ret[] = '<b>'.htmlspecialchars( $db->error() ).'</b><br />' ;
				//var_dump( $db->error() ) ;
				return false ;
			} else {
				if( ! in_array( $prefixed_query[4] , $created_tables ) ) {
					$ret[] = 'Table <b>'.htmlspecialchars($prefix_mod.'_'.$prefixed_query[4]).'</b> created.<br />';
					$created_tables[] = $prefixed_query[4];
				} else {
					$ret[] = 'Data inserted to table <b>'.htmlspecialchars($prefix_mod.'_'.$prefixed_query[4]).'</b>.</br />';
				}
			}
		}
	}



	// TEMPLATES
	$tplfile_handler =& icms::handler('icms_view_template_file');
	$tpl_path = dirname(__FILE__).'/templates' ;
	if( $handler = @opendir( $tpl_path . '/' ) ) {
		while( ( $file = readdir( $handler ) ) !== false ) {
			if( substr( $file , 0 , 1 ) == '.' ) continue ;
			$file_path = $tpl_path . '/' . $file ;
			if( is_file( $file_path ) && substr( $file , -5 ) == '.html' ) {
				$mtime = intval( @filemtime( $file_path ) ) ;
				$tplfile =& $tplfile_handler->create() ;
				$tplfile->setVar( 'tpl_source' , file_get_contents( $file_path ) , true ) ;
				$tplfile->setVar( 'tpl_refid' , $mid ) ;
				$tplfile->setVar( 'tpl_tplset' , 'default' ) ;
				$tplfile->setVar( 'tpl_file' , $mydirname . '_' . $file ) ;
				$tplfile->setVar( 'tpl_desc' , '' , true ) ;
				$tplfile->setVar( 'tpl_module' , $mydirname ) ;
				$tplfile->setVar( 'tpl_lastmodified' , $mtime ) ;
				$tplfile->setVar( 'tpl_lastimported' , 0 ) ;
				$tplfile->setVar( 'tpl_type' , 'module' ) ;
				if( ! $tplfile_handler->insert( $tplfile ) ) {
					$ret[] = '<span style="color:#ff0000;">ERROR: Could not insert template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b> to the database.</span><br />';
				} else {
					$tplid = $tplfile->getVar( 'tpl_id' ) ;
					$ret[] = 'Template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b> added to the database. (ID: <b>'.$tplid.'</b>)<br />';
					// generate compiled file
					if( !icms_view_Tpl::template_touch( $tplid ) ) {
						$ret[] = '<span style="color:#ff0000;">ERROR: Failed compiling template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b>.</span><br />';
					} else {
						$ret[] = 'Template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b> compiled.</span><br />';
					}
				}
			}
		}
		closedir( $handler ) ;
	}

	include_once XOOPS_ROOT_PATH.'/class/xoopsblock.php' ;
//	include_once XOOPS_ROOT_PATH.'/class/template.php' ;
	icms_view_Tpl::template_clear_module_cache( $mid ) ;

	// BLOCKS
	$tpl_path = dirname(__FILE__).'/templates/blocks' ;
	if( $handler = @opendir( $tpl_path . '/' ) ) {
		while( ( $file = readdir( $handler ) ) !== false ) {
			if( substr( $file , 0 , 1 ) == '.' ) continue ;
			$file_path = $tpl_path . '/' . $file ;
			$tpl_source = file_get_contents( $file_path );
			if( is_file( $file_path ) && substr( $file , -5 ) == '.html' ) {
				$mtime = intval( @filemtime( $file_path ) ) ;
				$tpl_file = $mydirname . '_' . $file;
				$sql = "SELECT tpl_id, tpl_refid FROM ".$db->prefix('tplfile')." WHERE tpl_module='$mydirname' AND tpl_file='".$db->quoteString($tpl_file)."'";
				list($tpl_id, $block_id) = $db->fetchRow($db->query($sql));
				if( empty($tpl_id) && empty($block_id)){
					$blocks_info = $module->getInfo('blocks');
					$show_func = '';
					foreach($blocks_info as $oneblock){
						if($tpl_file == $oneblock['template']){
							$show_func = $oneblock['show_func'];
							break;
						}
					}
					if( $show_func != ''){
						$sql = sprintf("SELECT bid FROM %s WHERE dirname=%s AND show_func=%s", $db->prefix("newblocks"), $db->quoteString($mydirname), $db->quoteString($show_func) ) ;
						list($block_id) = $db->fetchRow($db->query($sql));
						if($block_id){
							$tplfile =& $tplfile_handler->create();
							$tplfile->setVar('tpl_module', $mydirname);
							$tplfile->setVar('tpl_refid', $block_id);
							$tplfile->setVar('tpl_source', $tpl_source, true);
							$tplfile->setVar('tpl_tplset', 'default');
							$tplfile->setVar('tpl_file', $tpl_file, true);
							$tplfile->setVar('tpl_type', 'block');
							$tplfile->setVar('tpl_lastimported', 0);
							$tplfile->setVar('tpl_lastmodified', time());
							$tplfile->setVar('tpl_desc', '', true);
							if (!$tplfile_handler->insert($tplfile)) {
								$ret[] = '&nbsp;&nbsp;<span style="color:#ff0000;">ERROR: Could not insert template <b>'.$tpl_file.'</b> to the database.</span><br />';
							} else {
								$newid = $tplfile->getVar('tpl_id');
								$ret[] = '&nbsp;&nbsp;Template <b>'.$tpl_file.'</b> added to the database.<br />';
								if ($xoopsConfig['template_set'] == 'default') {
									if (!icms_view_Tpl::template_touch($block_id)) {
										$ret[] = '&nbsp;&nbsp;<span style="color:#ff0000;">ERROR: Template <b>'.$tpl_file.'</b> recompile failed.</span><br />';
									} else {
										$ret[] = '&nbsp;&nbsp;Template <b>'.$tpl_file.'</b> recompiled.<br />';
									}
								}
							}
							$sql = "UPDATE ".$db->prefix("newblocks")." SET template='".$db->quoteString($tpl_file)."', last_modified=".time()." WHERE bid=".$block_id;
							if( !$result = $db->query($sql) ) {
								$ret[] = '<span style="color:#ff0000;">ERROR: Could not insert template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b> to the database.</span><br />';
							}else{
								$ret[] = 'Template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b> added to the database. (ID: <b>'.$newid.'</b>)<br />';
							}
						}
					}
				}
				elseif (!empty($tpl_id) && isset($tpl_source) && $tpl_source != '') {
					$sql = "SELECT COUNT(*) FROM ".$db->prefix('tplsource')." WHERE tpl_id='$tpl_id'";
					list($count) = $$db->fetchRow($xoopsDB->query($sql));
					if($count==0){
						$sql = sprintf("INSERT INTO %s (tpl_id, tpl_source) VALUES (%u, %s)", $db->prefix('tplsource'), $tpl_id, $db->quoteString($tpl_source));
					}else{
						$sql = "UPDATE ".$db->prefix("tplsource")." SET tpl_source='".$db->quoteString($tpl_source)."' WHERE tpl_id=".$tpl_id;
					}
					if( !$result = $db->query($sql) ) {
						$ret[] = '<span style="color:#ff0000;">ERROR: Could not insert template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b> to the database.</span><br />';
					} else {
						$ret[] = 'Template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b> added to the database. (ID: <b>'.$tpl_id.'</b>)<br />';
						// generate compiled file
						include_once XOOPS_ROOT_PATH.'/class/xoopsblock.php';
//						include_once XOOPS_ROOT_PATH.'/class/template.php';
						if( ! icms_view_Tpl::template_touch( $tpl_id ) ) {
							$ret[] = '<span style="color:#ff0000;">ERROR: Failed compiling template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b>.</span><br />';
						} else {
							$ret[] = 'Template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b> compiled.</span><br />';
						}
					}
					$sql = "UPDATE ".$db->prefix("newblocks")." SET template='".$db->quoteString($tpl_file)."', last_modified=".time()." WHERE bid=".$block_id;
					if( !$result = $db->query($sql) ) {
						$ret[] = '<span style="color:#ff0000;">ERROR: Could not insert template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b> to the database.</span><br />';
					}else{
						$ret[] = 'Template <b>'.htmlspecialchars($mydirname.'_'.$file).'</b> added to the database. (ID: <b>'.$tpl_id.'</b>)<br />';
					}
				}
			}
		}
		closedir( $handler ) ;
	$ret[] = 'Now end block template area' . '<br />';
	}

	return true ;
}

function d3news_message_append_oninstall( &$controller , &$eventArgs )
{
	if( is_array( @$GLOBALS['ret'] ) ) {
		foreach( $GLOBALS['ret'] as $message ) {
			$controller->mLog->add( $message ) ;
		}
	}
}

}
