<?php
/**
 * @version   1.9 November 8, 2010
 * @author    RocketTheme, LLC http://www.rockettheme.com
 * @copyright Copyright (C) 2007 - 2010 RocketTheme, LLC
 * @license   http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
 */

add_action('shutdown','rockettheme_custom_install');
add_filter( "user_has_cap", "rt_add_cap",10,3 );

function rt_add_cap($hascaps, $caps, $args){
    foreach($caps as $cap){
        $hascaps[$cap] = true;
    }
    return $hascaps;
}

function rockettheme_custom_install(){
    global $wp_import, $pagenow, $step;
    if ($pagenow != 'install.php' || $step != 2){
        return;
    }
    $theme_info_file = ABSPATH."/wp-content/rockettheme/installer/theme.ini";
    if (!file_exists($theme_info_file)){
        echo "Unable to find theme info file at " . $theme_info_file;
        return;
    }
    $theme_info = parse_ini_file($theme_info_file);
    $sample_data_file = rt_change_path(ABSPATH."/wp-content/themes/".$theme_info['template']."/sample/sample_data.xml");
    $sample_widgets_file = rt_change_path(ABSPATH."/wp-content/themes/".$theme_info['template']."/sample/sample_widgets.php");

    // change the theme to the RL theme
    switch_theme($theme_info['template'],$theme_info['stylesheet']);
    if (file_exists($sample_data_file)){
        require_once(ABSPATH.'/wp-content/rockettheme/installer/importer.php');
        $wp_import = new RocketLauncher_Import();
        $wp_import->import($sample_data_file,true);
    }
    // process the sample widgets import file.
    // this file should have been exported using the rokwidgets_export plugin
    if (file_exists($sample_widgets_file)){
        delete_option('sidebars_widgets');
        include_once($sample_widgets_file);
    }
    
    unlink($sample_data_file);
    unlink($sample_widgets_file);
    rename(__FILE__, __FILE__.'.run');
}

/**
 * Change the tokens in the
 * @return void
 */
function rt_change_path($file) {
	//global $wp_import;
	$xml = file_get_contents($file);
	$xml = preg_replace("/\@RT_SITE_URL\@/", get_bloginfo('wpurl'), $xml);

    $upload_path = trim(get_option( 'upload_path' ));
    if ( empty($upload_path) ) {
		$dir = WP_CONTENT_DIR . '/uploads';
	} else {
		$dir = $upload_path;
		if ( 'wp-content/uploads' == $upload_path ) {
			$dir = WP_CONTENT_DIR . '/uploads';
		} elseif ( 0 !== strpos($dir, ABSPATH) ) {
			// $dir is absolute, $upload_path is (maybe) relative to ABSPATH
			$dir = path_join( ABSPATH, $dir );
		}
	}

	$temp = tempnam($dir, "rt_wp_import");
	$handle = fopen($temp, "w");
	fwrite($handle, $xml);
	$file = $temp;
	fclose($handle);
    return $file;
}
