<?php
$mydirpath = dirname(dirname(__FILE__));
$mydirname = basename($mydirpath);
$lang = @$GLOBALS["xoopsConfig"]['language'];
global $wp_db_version;
include_once $mydirpath .'/wp-includes/version.php' ;

// language file (modinfo.php)

if( file_exists( $mydirpath .'/language/'.$lang.'/modinfo.php' ) ) {
	include_once $mydirpath .'/language/'.$lang.'/modinfo.php' ;
} else if( file_exists(  $mydirpath .'/language/english/modinfo.php' ) ) {
	include_once $mydirpath .'/language/english/modinfo.php' ;
}


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


if( ! function_exists( 'xpress_oninstall_base' ) ) :
function xpress_oninstall_base( $module , $mydirname )
{
	// transations on module install

	global $ret ; // TODO :-D

	// for Cube 2.1
	if( defined( 'XOOPS_CUBE_LEGACY' ) ) {
		$root =& XCube_Root::getSingleton();
		$root->mDelegateManager->add( 'Legacy.Admin.Event.ModuleInstall.' . ucfirst($mydirname) . '.Success' , 'xpress_message_append_oninstall' ) ;
		$ret = array() ;
	} else {
		if( ! is_array( $ret ) ) $ret = array() ;
	}

	$db =& Database::getInstance() ;
	$mid = $module->getVar('mid') ;

//xpress
	global $wpdb,$wp_rewrite, $wp_queries, $table_prefix, $wp_db_version, $wp_roles, $wp_query;
	define("WP_INSTALLING", true);
	$site_url= XOOPS_URL."/modules/".$mydirname;
	$mydirpath = XOOPS_ROOT_PATH . '/modules/' . $mydirname;
	$path = $mydirpath . '/';
	if (file_exists($path . 'wp-load.php')) {
		require_once $path . 'wp-load.php';
	} else {
		require_once $path . 'wp-config.php';
	}
	include_once($mydirpath . '/wp-admin/upgrade-functions.php');
	wp_cache_flush();
	make_db_current_silent();
	
	$option_desc = __('WordPress web address');
	$wpdb->query("INSERT INTO $wpdb->options (option_id, blog_id, option_name,option_value, autoload) VALUES ('1', '0', 'siteurl','$site_url', 'yes')");	
	$wpdb->query("INSERT INTO $wpdb->options (option_id, blog_id, option_name,option_value, autoload) VALUES ('1', '0', 'home','$site_url', 'yes')");

	populate_options();
	populate_roles();
	
// Rewrite Option for Xpress
//	update_option("blog_charset", wp_blog_charset());
	update_option('blogname', ucfirst($mydirname) . ' ' . _MI_XPRESS_NAME );	
	update_option('blogdescription', 'WordPress for XOOPS');
	update_option("admin_email", $GLOBALS["xoopsConfig"]['adminmail']);
	update_option("ping_sites", "http://rpc.pingomatic.com/\nhttp://ping.xoopsforge.com/");
	update_option("home", $site_url);
	update_option("siteurl", $site_url);
	update_option("template", "xpress_default");
	update_option("stylesheet", "xpress_default");
	update_option("what_to_show", "posts");

	/* add new option for uploads */
//	update_option('uploads_use_yearmonth_folders', 1);
//	update_option('upload_path', $module->getVar("dirname"));
	
	/* activate the XPressME plugin */
	$plugin_current = "xpressme/xpressme.php";
	update_option('active_plugins', array($plugin_current));
	include_once(dirname(__FILE__) . '/../wp-content/plugins/'.$plugin_current);
	do_action('activate_'.$plugin_current);
		
// Admin User Data write
	// Change uid field
	$wpdb->query("ALTER TABLE $wpdb->posts CHANGE `post_author` `post_author` mediumint(8) NOT NULL DEFAULT '0'");
	$ID = is_object($GLOBALS["xoopsUser"])?$GLOBALS["xoopsUser"]->getVar("uid"):1;
//   	require_once($mydirpath . '/include/user_sync.php');
	$sync_messg = '';
//	user_sync_to_wordpress($ID,$sync_messg);		//this function in XPressME plugin 

	// Set Default data
		wp_install_defaults($ID);
//	    generate_page_uri_index();

	        
	// create views table
	$xp_prefix = $mydirname;
	if ($xp_prefix == 'wordpress'){
 		$xp_prefix = 'wp';
	}
	$views_table = XOOPS_DB_PREFIX . '_' . $xp_prefix .'_views' ;

	$charset_collate = '';
	if ( version_compare(mysql_get_server_info(), '4.1.0', '>=') ) {
		if ( ! empty($wpdb->charset) )
			$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
		if ( ! empty($wpdb->collate) )
			$charset_collate .= " COLLATE $wpdb->collate";
	}
	$views_queries ="CREATE TABLE $views_table (
  		post_id bigint(20) unsigned NOT NULL default '0',
  		post_views bigint(20) unsigned NOT NULL default '0',
  		KEY post_id (post_id)
		)$charset_collate;";

	dbDelta($views_queries);
	
	$d3forum_link = XOOPS_DB_PREFIX . '_' . $xp_prefix .'_d3forum_link' ;
	$views_queries ="CREATE TABLE $d3forum_link (
  		comment_ID bigint(20) unsigned NOT NULL default '0',
  		post_id int(10) unsigned NOT NULL default '0' ,
  		wp_post_ID bigint(20) unsigned NOT NULL default '0',
  		KEY post_id (post_id)
		)$charset_collate;";
	dbDelta($views_queries);
	
	$group_role = XOOPS_DB_PREFIX . '_' . $xp_prefix .'_group_role' ;
	$views_queries ="CREATE TABLE $group_role (
  		groupid smallint(5) unsigned NOT NULL default '0',
  		name varchar(50)  NOT NULL default '' ,
  		description text  NOT NULL default '',
  		group_type varchar(10)  NOT NULL default '' ,
		role varchar(20)  NOT NULL default '' ,
		login_all smallint(5) unsigned NOT NULL default '0' ,
  		KEY groupid (groupid)
		)$charset_collate;";
	dbDelta($views_queries);
	$sql = "INSERT INTO $group_role (groupid, role) VALUES (1, 'administrator')";
	$wpdb->query($sql);
	
	// TEMPLATES
	$tplfile_handler =& xoops_gethandler( 'tplfile' ) ;
	$tpl_path = dirname( dirname( __FILE__ ) ).'/templates/source' ;
	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 ) ) {
				$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' , 'block' ) ;
				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
					include_once XOOPS_ROOT_PATH.'/class/xoopsblock.php' ;
					include_once XOOPS_ROOT_PATH.'/class/template.php' ;
					if( ! xoops_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' ;
	xoops_template_clear_module_cache( $mid ) ;

	return true ;
}
endif;

if( ! function_exists( 'xpress_message_append_oninstall' ) ) :
function xpress_message_append_oninstall( &$module_obj , &$log )
{
	if( is_array( @$GLOBALS['ret'] ) ) {
		foreach( $GLOBALS['ret'] as $message ) {
			$log->add( strip_tags( $message ) ) ;
		}
	}

	// use mLog->addWarning() or mLog->addError() if necessary
}
endif;

?>