<?php
/*
Plugin Name: Typo3 to Wordpress
Plugin URI: http://www.fjordinterative.com/
Description: Migrates the tt_news/timtab posts from Typo3 to Wordpress.
Version: 0.1
Author: Brad Touesnard
Author URI: http://bradt.ca/
*/

// Typo3's container ids for each language mapped to the language parent category in WP
$lang_map = array(
    '105' => '1', // English
    '221' => '2', // Spanish
    '234' => '3' // French
);

// Typo3 to WP cat ids
// typo3 => wp
$cat_map = array(
    '10' => '9',
    '9' => '8',
    '8' => '7',
    '7' => '6',
    '6' => '5',
    '4' => '4',
    '3' => '3',
    '11' => '10',
    '12' => '11',
    '13' => '12',
    '14' => '13',
    '15' => '14',
    '16' => '15',
    '17' => '16',
    '18' => '17',
    '19' => '18',
    '21' => '19',
    '22' => '21',
    '23' => '22',
    '24' => '23',
    '25' => '25',
    '26' => '8',
    '27' => '24',
    '28' => '26'
);


$db_typo3 = mysql_connect('localhost', 'mcdcrew1', 'fad45$%dafd', true);
mysql_selectdb('mcdcrew1', $db_typo3);

$db_wp = mysql_connect('localhost', 'mcdcrew_wpmu', 'fad45$%dafd', true);
mysql_selectdb('mcdcrew_wpmu', $db_wp);

function ttw_migrate_data() {
    global $db_typo3, $db_wp, $cat_map, $lang_map;

    foreach ($lang_map as $typo3_uid => $wp_blog_id) {
        $table_prefix = 'wp_' . $wp_blog_id . '_';

        $sql = "TRUNCATE TABLE {$table_prefix}posts";
        mysql_query($sql, $db_wp);

        $sql = "TRUNCATE TABLE {$table_prefix}term_relationships";
        mysql_query($sql, $db_wp);

        $sql = "TRUNCATE TABLE {$table_prefix}postmeta";
        mysql_query($sql, $db_wp);
    }

    $sql = "
        SELECT uid, pid, hidden, datetime, title, bodytext, tstamp, short
        FROM tt_news
        WHERE type = '3'
            AND deleted = 0
        ORDER BY datetime DESC
    ";
    $result = mysql_query($sql, $db_typo3);

    while ($row = mysql_fetch_assoc($result)) {
        $style = '';
        if ($row['hidden']) {
            $style .= 'color: #999;';
        }
        if ($style) {
            $style = ' style="' . $style . '"';
        }

        $catids = ttw_get_typo3_post_cats($row['uid']);
        ?>
        <p<?php echo $style ?>>
            <?php echo $row['uid'] . ' ' . utf8_encode($row['title']) ?>
        </p>
        <?php

        $date_format = 'Y-m-d H:i:s';
        $post_date = date($date_format, $row['datetime']);
        $post_date_gmt = gmdate($date_format, $row['datetime']);
        $post_modified = date($date_format, $row['tstamp']);
        $post_modified_gmt = gmdate($date_format, $row['tstamp']);

        if ($row['hidden'] == '1') {
            $post_status = 'draft';
        }
        else {
            $post_status = 'publish';
        }

        $post_name = sanitize_title_with_dashes($row['title']);

        $lang_id = $row['pid'];
        $table_prefix = 'wp_' . $lang_map[$lang_id] . '_';

        $sql = sprintf("
            INSERT INTO `{$table_prefix}posts` ( `ID` , `post_author` , `post_date` ,
                `post_date_gmt` , `post_content` , `post_title` , `post_category` ,
                `post_excerpt` , `post_status` , `comment_status` , `ping_status` ,
                `post_password` , `post_name` , `to_ping` , `pinged` , `post_modified` ,
                `post_modified_gmt` , `post_content_filtered` , `post_parent` , `guid` ,
                `menu_order` , `post_type` , `post_mime_type` , `comment_count` )
            VALUES
                ( NULL , '1', '%s', '%s', '%s', '%s', '0',
                '%s', '%s', 'open', 'open', '', '%s', '', '', '%s',
                '%s', '', '0', '', '0', 'post', '', '0')
        ",
        $post_date, $post_date_gmt, mysql_real_escape_string($row['bodytext']), mysql_real_escape_string($row['title']),
        mysql_real_escape_string($row['short']), $post_status, $post_name, $post_modified, $post_modified_gmt);
        //echo '<p>', utf8_encode($sql), '</p>';
        mysql_query($sql, $db_wp);

        $post_id = mysql_insert_id($db_wp);

        // Link each category to this post
        foreach ($catids as $cat_id) {
            $term_taxonomy_id = ttw_get_term_taxonomy_id($cat_map[$cat_id], $lang_map[$lang_id]);

            $sql = sprintf("
                INSERT INTO {$table_prefix}term_relationships (object_id, term_taxonomy_id, term_order)
                VALUES (%s, %s, 0)
            ", $post_id, $term_taxonomy_id);
            mysql_query($sql, $db_wp);
        }

        $sql = sprintf("
            UPDATE {$table_prefix}posts SET guid = 'http://%s/wpmu/?p=%d'
            WHERE ID = %d
        ", $_SERVER['HTTP_HOST'], $post_id, $post_id);
        mysql_query($sql, $db_wp);

        $sql = sprintf("
            INSERT INTO `{$table_prefix}postmeta` ( `post_id` , `meta_key` , `meta_value` )
            VALUES (%s, '_typo3_uid', '%s')
        ", $post_id, $row['uid']);
        mysql_query($sql, $db_wp);

    }

    exit;
}

function ttw_save_post($post_ID, $post) {
    global $db_typo3, $db_wp, $cat_map, $lang_map, $blog_id;

    if ($post->post_type == 'post') {
        // Flip the arrays so that the Wordpress ids are the keys
        $cat_map_flip = array_flip($cat_map);
        $lang_map_flip = array_flip($lang_map);

        $custom = get_post_custom($post->ID);
        $cats = get_the_category($post->ID);

        if (isset($custom['_typo3_uid'])) {
            $typo3_uid = $custom['_typo3_uid'][0];
        }

        $pid = $lang_map_flip[$blog_id];
        $table_prefix = 'wp_' . $blog_id . '_';

        if ($post->post_status == 'publish' || $post->post_status == 'future') {
            $hidden = 0;
        }
        else {
            $hidden = 1;
        }

        $tstamp = strtotime($post->post_modified_gmt . ' GMT');
        $datetime = strtotime($post->post_date_gmt . ' GMT');

        // If it's a schedule post
        if ($post->post_status == 'future') {
            $starttime = $datetime;
        }
        else {
            $starttime = 0;
        }

        $bodytext = apply_filters('the_content', $post->post_content);
        if ($post->post_excerpt) {
            $short = apply_filters('the_content', $post->post_excerpt);
        }
        else {
            $short = '';
        }

        $title = mysql_real_escape_string(ttw_iso_encode($post->post_title), $db_typo3);
        $bodytext = mysql_real_escape_string(ttw_iso_encode($bodytext), $db_typo3);
        $short = mysql_real_escape_string(ttw_iso_encode($short), $db_typo3);

        // If the post doesn't exist on the Typo3 side yet, we're inserting
        if (!isset($typo3_uid)) {
            $sql = sprintf("
                INSERT INTO `tt_news` ( `pid` , `tstamp` , `crdate` ,
                    `cruser_id` , `editlock` , `deleted` , `hidden` , `starttime` ,
                    `endtime` , `fe_group` , `title` , `datetime` , `image` ,
                    `imagecaption` , `imagealttext` , `imagetitletext` , `related` ,
                    `short` , `bodytext` , `author` , `author_email` , `category` ,
                    `news_files` , `links` , `type` , `page` , `keywords` ,
                    `archivedate` , `ext_url` , `sys_language_uid` , `l18n_parent` ,
                    `l18n_diffsource` , `no_auto_pb` , `t3ver_oid` , `t3ver_id` ,
                    `t3ver_wsid` , `t3ver_label` , `t3ver_state` , `t3ver_stage` ,
                    `t3ver_count` , `t3ver_tstamp` , `t3_origuid` ,
                    `tx_timtab_trackbacks` , `tx_timtab_comments_allowed` ,
                    `tx_timtab_ping_allowed` , `tx_timtab_rating` , `tx_timtab_votes` )
                VALUES
                    ( '%d', '%d', '%d', '6', '0', '0', '%d', '%d', '0', '', '%s',
                    '%d', '', '', '', '', '0', '%s', '%s', '', '', '1', '', '', '3', '0', '',
                    '0', '', '0', '0', '', '0', '0', '0', '0', '', '0', '0', '0', '0',
                    '0', '', '1', '1', '0', '0' )
            ", $pid, $tstamp, $tstamp, $hidden, $starttime, $title, $datetime, $short, $bodytext);
            mysql_query($sql, $db_typo3);

            $typo3_uid = mysql_insert_id($db_typo3);

            $sql = sprintf("
                INSERT INTO `{$table_prefix}postmeta` ( `post_id` , `meta_key` , `meta_value` )
                VALUES (%s, '_typo3_uid', '%s')
            ", $post->ID, $typo3_uid);
            mysql_query($sql, $db_wp);
        }
        else {
            $sql = sprintf("
                UPDATE `tt_news` SET `pid` = %d, `hidden` = %d, `datetime` = %s,
                    `title` = '%s', `bodytext` = '%s', `tstamp` = %d, `starttime` = %d, `short` = '%s'
                WHERE `uid` = %d
            ", $pid, $hidden, $datetime, $title, $bodytext, $tstamp, $starttime, $short, $typo3_uid);
            mysql_query($sql, $db_typo3);

            // Remove all the category relations
            $sql = sprintf("
                DELETE FROM `tt_news_cat_mm` WHERE `uid_local` = %d
            ", $typo3_uid);
            mysql_query($sql, $db_typo3);
        }

        // Add the new category relations
        foreach ($cats as $cat) {
            $sql = sprintf("
                INSERT INTO `tt_news_cat_mm` (`uid_local`, `uid_foreign`, `tablenames`, `sorting`)
                VALUES (%d, %d, '', 1)
            ", $typo3_uid, $cat_map_flip[$cat->cat_ID]);
            mysql_query($sql, $db_typo3);
        }
    }
}

function ttw_delete_post($post_id) {
    global $db_typo3, $db_wp;

    $custom = get_post_custom($post_id);
    $uid = $custom['_typo3_uid'][0];

    // Remove all the category relations
    $sql = sprintf("
        DELETE FROM `tt_news_cat_mm` WHERE `uid_local` = %d
    ", $uid);
    mysql_query($sql, $db_typo3);

    $sql = sprintf("
        DELETE FROM `tt_news` WHERE `uid` = %d
    ", $uid);
    mysql_query($sql, $db_typo3);
}

function ttw_iso_encode($str) {
    return iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $str);
}

function ttw_get_term_taxonomy_id($cat_id, $lang_id) {
    global $db_wp;

    $table_prefix = 'wp_' . $lang_id . '_';

    $sql = sprintf("
        SELECT term_taxonomy_id
        FROM {$table_prefix}term_taxonomy
        WHERE term_id = %d
    ", $cat_id);
    $result2 = mysql_query($sql, $db_wp);

    return mysql_result($result2, 0, 0);
}

function ttw_get_typo3_post_cats($uid) {
    global $db_typo3;

    $sql = sprintf("
        SELECT uid_foreign
        FROM tt_news_cat_mm
        WHERE uid_local = %s
    ", $uid);
    $result = mysql_query($sql, $db_typo3);

    $cats = array();
    while ($row = mysql_fetch_row($result)) {
        $cats[] = $row[0];
    }

    return $cats;
}

function ttw_meta_boxes($page, $context, $object) {
    global $userdata;

    // Don't cripple the interface, if 'admin' user
    if ($userdata->ID == 1) { return; }

    if ($page == 'post' && $context == 'normal') {
        remove_meta_box('tagsdiv', $page, $context);
    }
    elseif ($page == 'post' && $context == 'advanced') {
        remove_meta_box('trackbacksdiv', $page, $context);
        remove_meta_box('postcustom', $page, $context);
        remove_meta_box('commentstatusdiv', $page, $context);
        remove_meta_box('passworddiv', $page, $context);
    }
}

function ttw_admin_menu() {
    global $menu, $submenu, $userdata;

    // Don't cripple the interface, if 'admin' user
    if ($userdata->ID == 1) { return; }

    $menu[0] = array(__('&laquo; Back to Task Center'), 'read', '/typo3/sysext/taskcenter/task/index.php');

    // Remove unneeded "Write" subtabs
    unset($submenu['post-new.php'][15]); // Link
    unset($submenu['post-new.php'][10]); // Page

    // Remove unneeded "Manage" subtabs
    unset($submenu['edit.php'][10]); // Pages
    unset($submenu['edit.php'][15]); // Links
    unset($submenu['edit.php'][20]); // Categories
    unset($submenu['edit.php'][25]); // Tags
    unset($submenu['edit.php'][30]); // Link Categories

    // Remove "Comments" tab
    unset($menu[20]);
}

function ttw_request_url() {
    // Need to redirect now, so the cookie can take effect
    if ( is_ssl() )
        $proto = 'https://';
    else
        $proto = 'http://';

    return $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

function ttw_logout() {
    wp_clear_auth_cookie();
    wp_redirect('https://' . $_SERVER['HTTP_HOST'] . '/typo3/index.php');
    exit;
}

function ttw_seamless_login() {
    global $db_typo3;

    if (!defined('WP_ADMIN')) {
        return;
    }

    if (!WP_ADMIN) {
        return;
    }

    // If Typo3 session doesn't exist, we abort auto login
    if (!isset($_COOKIE['be_typo_user'])) {
        ttw_logout();
    }

    $sql = sprintf("
        SELECT `ses_tstamp` FROM `be_sessions` WHERE `ses_id` = '%s'
    ", mysql_real_escape_string($_COOKIE['be_typo_user']));
    $result = mysql_query($sql, $db_typo3);

    if (mysql_num_rows($result) <= 0) {
        ttw_logout();
    }

    $tstamp = mysql_result($result, 0, 0);

    // If the Typo3 session is expired, we abort auto login
    if (time() - $tstamp > 1800) {
        ttw_logout();
    }

    // If we're already logged in to WP, just refresh the Typo3 session
	if (wp_validate_auth_cookie()) {
        $sql = sprintf("
            UPDATE `be_sessions` SET `ses_tstamp` = '%d' WHERE `ses_id` = '%s'
        ", time(), mysql_real_escape_string($_COOKIE['be_typo_user']));
        mysql_query($sql, $db_typo3);
    }
    // If we're not logged in to WP, create the WP cookie automatically
    else {
        wp_set_auth_cookie(2); // Hardcoded ID: 'blogger' user
        $request_url = ttw_request_url();
        wp_redirect($request_url);
        exit;
    }
}

add_filter('save_post', 'ttw_save_post', 10, 2);
add_filter('delete_post', 'ttw_delete_post', 10, 1);

add_filter('do_meta_boxes', 'ttw_meta_boxes', 10, 3);
add_action('_admin_menu', 'ttw_admin_menu');

add_action('init', 'ttw_seamless_login');

if (stristr($_SERVER['REQUEST_URI'], 'migrate-typo3-to-wp')) {
	add_action('init', 'ttw_migrate_data');
}

if (!CUSTOM_TAGS) {
    $allowedposttags['a']['onclick'] = array();

	$allowedposttags['embed'] = array(
		'style' => array(),
		'type' => array (),
		'id' => array (),
		'height' => array (),
		'width' => array (),
		'src' => array (),
		'object' => array(
			'height' => array (),
			'width' => array (),
			'param' => array (
				'name' => array (),
				'value' => array ()
			)
		)
	);
	$allowedposttags['object'] = array(
	        'style' => array (),
		'height' => array (),
		'width' => array (),
		'param' => array (
			'name' => array (),
			'value' => array ()
		),
		'embed' => array(
			'style' => array(),
			'type' => array (),
			'id' => array (),
			'height' => array (),
			'width' => array (),
			'src' => array (),
			'allowfullscreen' => array (),
			'allowscriptaccess' => array ()
		)
	);
	$allowedposttags['param'] = array (
	        'name' => array (),
		'value' => array ()
	);
}
?>
