<?php
/**
 * Dashboard functionality
 * @since Cryout 0.5.1
 */
 
// generic functions
 
function cryout_export_options(){

    if (ob_get_contents()) ob_clean();

	/* Check authorisation */
	$authorised = true;
	// Check nonce
	if ( ! wp_verify_nonce( $_POST[_CRYOUT_THEME_NAME.'-export'], _CRYOUT_THEME_NAME.'-export' ) ) {
		$authorised = false;
	}
	// Check permissions
	if ( ! current_user_can( 'edit_theme_options' ) ){
		$authorised = false;
	}

	if ( $authorised) {
        
        date_default_timezone_set('UTC');
        $name = _CRYOUT_THEME_NAME.'settings-'.preg_replace("/[^a-z0-9-_]/i",'',preg_replace("/https?\:\/\//","",get_option('siteurl'))).'-'.date('Ymd-His').'.xml';
		$data = cryout_get_theme_options();
		$data[_CRYOUT_THEME_NAME . '_version'] = _CRYOUT_THEME_VERSION;
		//$data = json_encode( $data );
		//$size = strlen( $data );
		$xml = Cryout_Array2XML::createXML(_CRYOUT_THEME_NAME . '-settings', $data);

		header( 'Content-Type: text/xml' );
		header( 'Content-Disposition: attachment; filename="'.$name.'"' );
		header( "Content-Transfer-Encoding: binary" );
		header( 'Accept-Ranges: bytes' );

		/* The three lines below basically make the download non-cacheable */
		header( "Cache-control: private" );
		header( 'Pragma: private' );
		header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );

		//header( "Content-Length: " . sizeof($xml) );
		print ( $xml->saveXML() );
}
die();
} // cryout_export_options()

/**
 * This file manages the theme settings uploading and import operations.
 * Uses the theme page to create a new form for uplaoding the settings
 * Uses WP_Filesystem
*/
function cryout_import_form(){

    $bytes = apply_filters( 'import_upload_size_limit', wp_max_upload_size() );
    $size = size_format( $bytes );
    $upload_dir = wp_upload_dir();
    if ( ! empty( $upload_dir['error'] ) ) :
        ?><div class="error"><p><?php _e('Before you can upload your import file, you will need to fix the following error:', 'cryout'); ?></p>
            <p><strong><?php echo $upload_dir['error']; ?></strong></p></div><?php
    else :
    ?>
	<style>.notice, div.error, div.updated {max-width: 400px;padding: 1em; margin: 2em 2em 0 2em;}</style>
    <div class="wrap">
		<div style="display: inline-block; margin: 2em; padding: 2em; background: #fff;">
        <div id="icon-tools" class="icon32"><br></div>
        <h2><?php echo __( 'Import Customizer Theme Settings', 'cryout' );?></h2>
        <form enctype="multipart/form-data" id="import-upload-form" method="post" action="">
        	<p><?php _e('<em> Please remember that this is still an experimental feature.</em>', 'cryout'); ?></p>
            <p>
                <label for="upload"><strong><?php _e('Choose an XML file:', 'cryout'); ?> </strong><i>(<?php echo _CRYOUT_THEME_NAME; ?>-settings.xml)</i></label><br><br>
		       <input type="file" id="upload" name="import" size="25"  />
				<span style="font-size:11px;">(<?php  printf( __( 'Maximum size: %s', 'cryout' ), $size ); ?> )</span>
                <input type="hidden" name="action" value="save" />
                <input type="hidden" name="max_file_size" value="<?php echo $bytes; ?>" />
                <?php wp_nonce_field(_CRYOUT_THEME_NAME.'-import', _CRYOUT_THEME_NAME.'-import'); ?>
                <input type="hidden" name="cryout_import_confirmed" value="true" />
            </p><br>
            <input type="submit" class="button" value="<?php _e('Import', 'cryout'); ?>" style="display: table; margin: 0 auto;"/>
        </form>
	</div>
    </div> <!-- end wrap -->
    <?php
    endif;
} // cryout_import_form()

/**
 * This actual import of the options from the file to the settings array.
*/
function cryout_import_file() {

	$theme_settings = cryout_get_theme_options();

    /* Check authorisation */
    $authorised = true;
    // Check nonce
    if (!wp_verify_nonce($_POST[_CRYOUT_THEME_NAME.'-import'], _CRYOUT_THEME_NAME.'-import')) {$authorised = false;}
    // Check permissions
    if (!current_user_can('edit_theme_options')){ $authorised = false; }

    // If the user is authorised, import the theme's options to the database
    if ($authorised) {?>
        <?php
        // make sure there is an import file uploaded
        if ( (isset($_FILES["import"]["size"]) &&  ($_FILES["import"]["size"] > 0) ) ) {

			$form_fields = array('import');
			$method = '';

			$url = wp_nonce_url('themes.php?page='._CRYOUT_THEME_NAME.'-page', _CRYOUT_THEME_NAME.'-import');

			// Get file writing credentials
			if (false === ($creds = request_filesystem_credentials($url, $method, false, false, $form_fields) ) ) {
				return true;
			}

			if ( ! WP_Filesystem($creds) ) {
				// our credentials were no good, ask the user for them again
				request_filesystem_credentials($url, $method, true, false, $form_fields);
				return true;
			}

			// Write the file if credentials are good
			$upload_dir = wp_upload_dir();
			$filename = trailingslashit($upload_dir['path'])._CRYOUT_THEME_NAME.'-settings-import-'.date('Ymd-His').'.xml';

			// by this point, the $wp_filesystem global should be working, so let's use it to create a file
			global $wp_filesystem;
			if ( ! $wp_filesystem->move($_FILES['import']['tmp_name'], $filename, true) ) {
				echo 'Error saving file!';
				return;
			}

			$file = $_FILES['import'];

			if ($file['type'] == 'text/xml') {

				$data = $wp_filesystem->get_contents($filename);
				// try to read the file
				if ($data !== FALSE){
					//$settings = json_decode($data, true);
					$settings = Cryout_XML2Array::createArray($data);
					$settings = $settings[_CRYOUT_THEME_NAME."-settings"];
					// try to read the settings array
					if (isset($settings[_CRYOUT_THEME_NAME . '_db'])){ ?>
        <div class="wrap">
        <div id="icon-tools" class="icon32"><br></div>
        <h2><?php echo __( 'Import Theme Options ', 'cryout' );?></h2> <?php
						$settings = array_merge($theme_settings, $settings);
						update_option(_CRYOUT_THEME_NAME.'_settings', $settings);
						echo '<div class="updated fade"><p>'. __('Great! The options have been imported!', 'cryout').'<br />';
						echo '<a href="themes.php?page=about-'._CRYOUT_THEME_NAME.'-theme">'.__('Go back to the theme settings page and check them out!', 'cryout').'<a></p></div>';
					}
					else { // else: try to read the settings array
						echo '<div class="error"><p><strong>'.__('Oops, there\'s a small problem.', 'cryout').'</strong><br />';
						echo __('The uploaded file does not contain valid theme options. Make sure the file is exported from the theme options page.', 'cryout').'</p></div>';
						cryout_import_form();
					}
				}
				else { // else: try to read the file
					echo '<div class="error"><p><strong>'.__('Oops, there\'s a small problem.', 'cryout').'</strong><br />';
					echo __('The uploaded file could not be read.', 'cryout').'</p></div>';
					cryout_import_form();
				}
			}
			else { // else: make sure the file uploaded was a plain text file
				echo '<div class="error"><p><strong>'.__('Oops, there\'s a small problem.', 'cryout').'</strong><br />';
				echo __('The uploaded file is not supported. Make sure the file was exported from the theme settings page and that it is an XML file.', 'cryout').'</p></div>';
				cryout_import_form();
			}

			// Delete the file after we're done
			$wp_filesystem->delete($filename);

        }
        else { // else: make sure there is an import file uploaded
            echo '<div class="error"><p>'.__( 'Oops! The file is empty or there was no file. 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.', 'cryout' ).'</p></div>';
			cryout_import_form();
        }
        echo '</div> <!-- end wrap -->';
    }
    else {
        wp_die(__('ERROR: You are not authorised to perform that operation', 'cryout'));
    }
} // cryout_import_file()

// Truncate function for use in the Admin RSS feed
function cryout_truncate_words($string,$words=20, $ellipsis=' ...') {
 $new = preg_replace('/((\w+\W+\'*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
 return $new.$ellipsis;
}

add_action('wp_ajax_feed_action', 'cryout_fetch_feed');
function cryout_fetch_feed() {
	
	$theme_news = fetch_feed( array( 'http://www.cryoutcreations.eu/cat/'._CRYOUT_THEME_NAME.'/feed/') );
	$maxitems = 0;
	if ( ! is_wp_error( $theme_news ) ) {
			$maxitems = $theme_news->get_item_quantity( 10 );
			$news_items = $theme_news->get_items( 0, $maxitems );
	}
	?>
         <ul class="news-list">
            <?php if ( $maxitems == 0 ) : echo '<li>' . __( 'No news items.', 'cryout' ) . '</li>'; else :
						foreach( $news_items as $news_item ) : ?>
                    	<li>
                        	<a class="news-header" target="_blank" href='<?php echo esc_url( $news_item->get_permalink() ); ?>'><?php echo esc_html( $news_item->get_title() ); ?></a>
							<span class="news-item-date"><?php _e('Posted on','cryout'); echo $news_item->get_date(' j F Y'); ?></span>
							<a class="news-more" target="_blank" href='<?php echo esc_url( $news_item->get_permalink() ); ?>'><?php _e('Read the full post','cryout');?> &#8594;</a>
                        </li>
						<?php endforeach; 
				endif; ?>
          </ul>
<?php 
die();
} // cryout_fetch_feed()

// Gather sys info for debug 
/* Inspired by Easy Digital Download plugin by Pippin Williamson */
function cryout_sysinfo($echo=true) { 
	ob_start();
	?>
	<div class="wrap">
	<h3><?php _e( 'Debug Information', 'cryout' ); ?></h3>
	<p><?php _e( 'Please include the debug information when creating a support request or posting to the forum.' , 'cryout' ) ?></p>
	
	<textarea readonly="readonly" onclick="this.focus();" id="cryout-sysinfo" name="cryout-sysinfo" title="" rows="10">
General Information
-------------------
Website URL            : <?php echo site_url() . "\n"; ?>
Home URL               : <?php echo home_url() . "\n"; ?>
Multisite              : <?php echo ( is_multisite() ? 'Yes' : 'No' ) . "\n" ?>

Theme                  : <?php printf( '%1$s v%2$s', _CRYOUT_THEME_NAME, _CRYOUT_THEME_VERSION ); echo "\n"; ?>
<?php if ( get_stylesheet_directory() != get_template_directory() ) { $child_theme = wp_get_theme(); ?>
Child Theme            : <?php printf( '%1$s v%2$s', $child_theme->get('Name'), $child_theme->get('Version') ); echo "\n" ?>
<?php }; ?>
WordPress              : <?php echo get_bloginfo( 'version' ) . "\n"; ?>
Language               : <?php echo get_bloginfo( 'language' ) . (is_RTL() ? ' (RTL)' : '') . "\n" ; ?>
jQuery                 : jQuery not detected
Permalinks             : <?php echo get_option( 'permalink_structure' ) . "\n"; ?>
WP_DEBUG               : <?php echo defined( 'WP_DEBUG' ) ? WP_DEBUG ? 'On' . "\n" : 'Off' . "\n" : 'Undefined' . "\n" ?>

Show On Front          : <?php echo get_option( 'show_on_front' ) . "\n" ?>
Page On Front          : <?php $id = get_option( 'page_on_front' ); echo get_the_title( $id ) . ' ID=' . $id . '' . "\n" ?>
Page For Posts         : <?php $id = get_option( 'page_for_posts' ); echo get_the_title( $id ) . ' ID=' . $id . '' . "\n" ?>

PHP                    : <?php echo PHP_VERSION . "\n"; ?>
MySQL                  : <?php echo @mysql_get_server_info() . "\n"; ?>
Server                 : <?php echo $_SERVER['SERVER_SOFTWARE'] . "\n"; ?>

WordPress Memory Limit : <?php echo WP_MEMORY_LIMIT; echo "\n"; ?>
PHP Safe Mode          : <?php echo ini_get( 'safe_mode' ) ? "Yes" : "No\n"; ?>
PHP Memory Limit       : <?php echo ini_get( 'memory_limit' ) . "\n"; ?>
PHP Upload Max Size    : <?php echo ini_get( 'upload_max_filesize' ) . "\n"; ?>
PHP Post Max Size      : <?php echo ini_get( 'post_max_size' ) . "\n"; ?>
PHP Time Limit         : <?php echo ini_get( 'max_execution_time' ) . "\n"; ?>
PHP Max Input Vars     : <?php echo ini_get( 'max_input_vars' ) . "\n"; ?>
PHP Allow URL FOpen    : <?php echo ini_get( 'allow_url_fopen' ) ? "Yes\n" : "No\n"; ?>

Currently active plugins
------------------------
<?php
	$plugins = get_plugins();
	$active_plugins = get_option( 'active_plugins', array() );

	foreach ( $plugins as $plugin_path => $plugin ) {
	  // If the plugin isn't active, don't show it.
	  if ( ! in_array( $plugin_path, $active_plugins ) )
		continue;

	  echo $plugin['Name'] . ': ' . $plugin['Version'] ."\n";
	}

	if ( is_multisite() ) :
	$plugins = wp_get_active_network_plugins();
	$active_plugins = get_site_option( 'active_sitewide_plugins', array() );

	foreach ( $plugins as $plugin_path ) {
	  $plugin_base = plugin_basename( $plugin_path );

	  // If the plugin isn't active, don't show it.
	  if ( ! array_key_exists( $plugin_base, $active_plugins ) )
		continue;

	  $plugin = get_plugin_data( $plugin_path );

	  echo $plugin['Name'] . ' :' . $plugin['Version'] . " (multisite)\n";
	}

	endif;
?>
--
	</textarea>
	</div> <?php
	$output = ob_get_contents();
	ob_end_clean();
	if ($echo) echo $output; else return $output;
} // cryout_sysinfo()
