<?php
/*
Plugin Name: WP Twitter Importer
Plugin URI: http://wordpress.org/extend/plugins/wp-twitter-importer/
Description:
Author: wordpressdotorg
Author URI: http://wordpress.org/
Version: 0.1
Text Domain: wp-twitter-importer
License: GPL version 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/

if ( ! defined( 'WP_LOAD_IMPORTERS' ) )
	return;

// Load Importer API
require_once ABSPATH . 'wp-admin/includes/import.php';

if ( ! class_exists( 'WP_Importer' ) ) {
	$class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
	if ( file_exists( $class_wp_importer ) )
		require $class_wp_importer;
}

class WP_Twitter_Import extends WP_Importer {

	/**
	 * Display import page title
	 */
	function header() {
		echo '<div class="wrap">';
		screen_icon();
		echo '<h2>' . __( 'Import Twitter', 'wp-twitter-importer' ) . '</h2>';

		$updates = get_plugin_updates();
		$basename = plugin_basename( __FILE__ );
		if ( isset( $updates[$basename] ) ) {
			$update = $updates[$basename];
			echo '<div class="error"><p><strong>';
			printf( __( 'A new version of this importer is available. Please update to version %s to ensure compatibility with newer export files.', 'wp-twitter-importer' ), $update->update->new_version );
			echo '</strong></p></div>';
		}
	}

	/**
	 * Close div.wrap
	 */
	function footer() {
		echo '</div>';
	}

	/**
	 * Display introductory text and file upload form
	 */
	function greet() {
		echo '<div class="narrow">';
		echo '<p>'.__( 'Howdy! Upload your Twitter archive data file and we&#8217;ll import the status updates into this site.', 'wp-twitter-importer' ).'</p>';
		echo '<p>'.__( 'Choose a Twitter archive data (.zip) file to upload, then click Upload file and import.', 'wp-twitter-importer' ).'</p>';
		wp_import_upload_form( 'admin.php?import=twitter&amp;step=1' );
		echo '</div>';
	}

	/**
	 * Registered callback function for the WordPress Importer
	 *
	 * Manages the three separate stages of the WXR import process
	 */
	function dispatch() {
		$this->header();

		$step = empty( $_GET['step'] ) ? 0 : (int) $_GET['step'];
		switch ( $step ) {
			case 0:
				$this->greet();
				break;
			case 1:
				//check_admin_referer( 'import-upload' );
				$working_dir = $this->handle_upload();
				$this->parse_files( $working_dir );
				break;
		}

		$this->footer();
	}

	/**
	 * Handles the zip upload and initial parsing of the file
	 *
	 * @return bool False if error uploading or invalid file, true otherwise
	 */
	function handle_upload() {
		global $wp_filesystem;

		if ( ! isset( $_FILES['import'] ) ) {
			$file['error'] = __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.' );
			return $file;
		}

		$url = 'admin.php?import=twitter';

		if ( false === ($credentials = request_filesystem_credentials($url, '', false, ABSPATH)) )
			return false;

		if ( ! WP_Filesystem($credentials, ABSPATH) ) {
			request_filesystem_credentials($url, '', true, ABSPATH); //Failed to connect, Error and request again
			return false;
		}

		$import_folder = $wp_filesystem->wp_content_dir() . 'import/';

		//Clean up contents of upgrade directory beforehand.
		$import_files = $wp_filesystem->dirlist( $import_folder );
		if ( ! empty( $import_files ) ) {
			foreach ( $import_files as $file )
				$wp_filesystem->delete( $import_folder . $file['name'], true );
		}

		//We need a working directory
		$working_dir = $import_folder . basename( $_FILES['import']['name'], '.zip' );

		// Clean up working directory
		if ( $wp_filesystem->is_dir( $working_dir ) )
			$wp_filesystem->delete( $working_dir, true );

		// Unzip package to working directory
		$result = unzip_file( $_FILES['import']['tmp_name'], $working_dir ); //TODO optimizations, Copy when Move/Rename would suffice?

		// Once extracted, delete the import file.
		unlink( $_FILES['import']['tmp_name'] );

		if ( is_wp_error($result) ) {
			$wp_filesystem->delete($working_dir, true);
			if ( 'incompatible_archive' == $result->get_error_code() ) {
				return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], $result->get_error_data() );
			}
			return $result;
		}

		return $working_dir;

	}

	public function parse_files( $working_dir ) {
		global $wp_filesystem;
		$tweets_dir = $working_dir . '/data/js/tweets/';

		$tweet_files = $wp_filesystem->dirlist( $tweets_dir );
		$tweets = array();
		if ( ! empty( $tweet_files ) ) {
			foreach ( $tweet_files as $file ) {
				$tweet_json = file_get_contents( $tweets_dir . $file['name'] );
				$tweet_json = preg_replace( '/^[^\[]*/', '', $tweet_json );
				$tweet_json = json_decode( $tweet_json );
				if ( is_array( $tweet_json ) )
					$tweets = array_merge( $tweet_json, $tweets );
			}
		}
		echo '<pre>', var_dump( $tweets ), '</pre>';
	}

}

function wp_twitter_importer_init() {
	load_plugin_textdomain( 'wp-twitter-importer', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );

	/**
	 * WordPress Importer object for registering the import callback
	 * @global WP_Twittter_Import $wp_twitter_import
	 */
	$GLOBALS['wp_twitter_import'] = new WP_Twitter_Import();
	register_importer( 'twitter', 'Twitter', __( 'Import your twitter status udpates.', 'wp-twitter-importer' ), array( $GLOBALS['wp_twitter_import'], 'dispatch' ) );
}
add_action( 'admin_init', 'wp_twitter_importer_init' );
