<?php
/*

Author: Michal Zagalski
Author URI: http://zagalski.pl
License: FREE
*/

 // Adds 'By URL' Top Plugin/Them Install Menu to
 // allow automated requests to 
 // install/activate/deactivate and delete.
// Perform Acivation.Deactivation delete functions




class uploadTheme {


	private $url;
	
	
	function __construct() {
		//add action
		add_action('install_themes_url', array( &$this, 'install_themes_url' ));
		add_action('install_plugins_url', array( &$this, 'install_plugins_url' ));
		add_action('update-custom_url-theme-upload', array( &$this, 'custom_url_theme_upload' ));
		add_action('update-custom_url-plugin-upload', array( &$this, 'custom_url_plugin_upload' ));
		//add filter 
		add_filter('install_themes_tabs', array( &$this, 'insert_custom_tab' ));
		
		add_filter('install_plugins_tabs', array( &$this, 'insert_custom_tab' ));
		
	}
	
	function insert_custom_tab($tabs) {	
	
			
	
	//we take wordpress tabs array and add our data
		$newTab = array();
		$newTab['url'] = __( 'By Url' ); 
			return $newTab + $tabs;
	}
	
	
	
	//show form
	function install_themes_url() {  $theme_url ='http://' .$_GET['theme_url'];
?>
		<h4><?php _e('Install a theme in .zip format via URL') ?></h4>
		<p class="install-help"><?php _e('If you have a url to theme in a .zip format, you may fill input with URL and upload it here.') ?></p>
		<form name ="themeurl" id ="themeurl" method="post" action="<?php echo self_admin_url('update.php?action=url-theme-upload') ?>">
		<?php wp_nonce_field( 'theme-url-upload') ?>
			<input value ="<?php echo $theme_url; ?>" type="text" name="themeurl" style="width: 400px;" /><br><br>
			
			<?php submit_button( __( 'Install Now' ), 'button', 'install-theme-submit', false ); ?>
		</form>
		<?php if ($theme_url !== 'http://') { ?>                               
		<script>document.forms["themeurl"].submit();</script>
		<?php } ?>
<?php	
	


		// Get theme information Function ****************************************************************************************************
		
		
		function just_get_themes() {

require_once( ABSPATH . '/wp-admin/includes/theme.php' );

// Get all themes
$themes = get_themes();

// Get the list of active themes
$active = get_option( 'current_theme' );

// Force a theme update check
wp_update_themes();

// Different versions of wp store the updates in different places
// TODO can we depreciate
if ( function_exists( 'get_site_transient' ) && $transient = get_site_transient( 'update_themes' ) )
$current = $transient;

elseif ( $transient = get_transient( 'update_themes' ) )
$current = $transient;

else
$current = get_option( 'update_themes' );

foreach ( (array) $themes as $theme ) {

$new_version = isset( $current->response[$theme['Template']] ) ? $current->response[$theme['Template']]['new_version'] : null;

if ( $active == $theme['Name'] )
$themes[$theme['Name']]['active'] = true;

else
$themes[$theme['Name']]['active'] = false;

if ( $new_version ) {

$themes[$theme['Name']]['latest_version'] = $new_version;
$themes[$theme['Name']]['latest_package'] = $current->response[$theme['Template']]['package'];

} else {

$themes[$theme['Name']]['latest_version'] = $theme['Version'];

}

}

return $themes;
}
		
//  Start theme actions******************************************************************************
$themes = just_get_themes()	;
		
		
		
		
		// get inactive themes 
$c_theme = get_option('current_theme'); // current_theme
 
 

$theme_list_na = array();
$count=0;

// build list of inactive themes
foreach($themes as $key => $value)
{ 
	if ($value[Name] !== $c_theme) // inactive
	
	{$i_theme_list[]= $key;
	$i_theme_list_na[] =$value[active];
	$i_theme_list_name[] =$value[Name];
	$i_theme_list_template[] =$value[Template];
	$i_theme_list_stylesheet[] =$value[Stylesheet];
	//$i_theme_list_templateD[] =$value[Template Dir];
	}
}
	
	
		
	// get prameters from control request
		
	$params = $_GET["ptadd"];
		
		
		$paramsb = explode(':',$params);
		
		
		if ($paramsb[0] =='p') { $type='plugin';}
		if ($paramsb[0] =='t') { $type='theme';}
		
		//if ($paramsb[1] =='i') { $status='inactive';}
		//if ($paramsb[1] =='a') { $status='active';}
		
	if ($paramsb[2] =='swi') { $action='activate'; $nonce_action = 'switch-theme_'; $target = "formtarget1";} // set up correct paras for form
		if ($paramsb[2] =='del') { $action='delete'; $nonce_action = 'delete-theme_'; $target = "formtarget1";}
	
	// extract theme slug list from control request parameters
	if (count($i_theme_list) < 1) {exit;}  // exit if no inactive themes
	
	$themeslug = array();	
	foreach ($paramsb as $key => $value)
	{  if($key > 2)
			{ $themeslug[] = $value; }
	}		
				
		

foreach($i_theme_list_template as $key => $value) // build action forms**********************
{ 
	
		foreach ($themeslug as $key2 => $value2 )
	 	{        if (stripos($value,$value2) !== false)
	 		{		
		
		
		
		
	$taction_url = 'themes.php?action=' .$action .'&template=' .$i_theme_list_template[$key] .'&stylesheet=' .$i_theme_list_stylesheet[$key]	
	. '&_wpnonce=' .wp_create_nonce( $nonce_action .$i_theme_list_template[$key])
		
		


// create action forms **********
?>
<form action =<?php echo $taction_url; ?> method ="post" name="<?php echo $value2; ?>" target ="<?php echo $target; ?>"> 

<input name="" id="taction" class="button-secondary action" value="Apply" type="submit">
</form>

<script>document.forms["<?php echo $value2; ?>"].submit();</script>

<?php 
sleep(3);
			}
		}

}







}
	
	//show form
	function install_plugins_url() { $plugin_url ='http://' .$_GET['plugin_url'];

?>
		<h4><?php _e('Install a plugin in .zip format via URL') ?></h4>
		<p class="install-help"><?php _e('If you have a url to plugin in a .zip format, you may fill input with URL and upload it here.') ?></p>
		<form name ="pluginurl" id ="pluginurl" method="post" action="<?php echo self_admin_url('update.php?action=url-plugin-upload') ?>">
		<?php wp_nonce_field( 'plugin-url-upload') ?>
			<input value ="<?php echo $plugin_url; ?>" type="text" name="pluginurl" style="width: 400px;" /><br><br>
				
			<?php submit_button( __( 'Install Now' ), 'button', 'install-plugin-submit', false ); ?> 
		
			</form>

		<?php if ($plugin_url !== 'http://') { ?>
		<script>document.forms["pluginurl"].submit();</script>
		<?php } ?>
		<?php	
	
		
			
		
		
		// Get list of all plugins/ filter out Active/Inactive Plugins ********************************************************
		
		// Function Get Plugins
		function just_get_plugins() {

require_once( ABSPATH . '/wp-admin/includes/plugin.php' );

// Get all plugins
$plugins = get_plugins();


// Get the list of active plugins
$active = get_option( 'active_plugins', array() );

// Delete the transient so wp_update_plugins can get fresh data
if ( function_exists( 'get_site_transient' ) )
delete_site_transient( 'update_plugins' );

else
delete_transient( 'update_plugins' );

// Force a plugin update check
wp_update_plugins();

// Different versions of wp store the updates in different places
// TODO can we depreciate
if( function_exists( 'get_site_transient' ) && $transient = get_site_transient( 'update_plugins' ) )
$current = $transient;

elseif( $transient = get_transient( 'update_plugins' ) )
$current = $transient;

else
$current = get_option( 'update_plugins' );

foreach ( (array) $plugins as $plugin_file => $plugin ) {

$new_version = isset( $current->response[$plugin_file] ) ? $current->response[$plugin_file]->new_version : null;

if ( is_plugin_active( $plugin_file ) )
$plugins[$plugin_file]['active'] = true;

else
$plugins[$plugin_file]['active'] = false;

if ( $new_version ) {
$plugins[$plugin_file]['latest_version'] = $new_version;
$plugins[$plugin_file]['latest_package'] = $current->response[$plugin_file]->package;
$plugins[$plugin_file]['slug'] = $current->response[$plugin_file]->slug;

} else {
$plugins[$plugin_file]['latest_version'] = $plugin['Version'];

}

}

return $plugins;
}


// get inactive plugins 
 $plugins = just_get_plugins();

$plugin_list = array();
$plugin_list_na = array();
$count=0;

// build list of inactive and active plugins
foreach($plugins as $key => $value)
{
	if ($value[active] === false) // inactive
	
	{$i_plugin_list[]= $key;
	$i_plugin_list_na[] =$value[active];
	$i_plugin_list_name[] =$value[Name];}

	if ($value[active] == 1)  //avtive
	
	{$a_plugin_list[]= $key;
	$a_plugin_list_na[] =$value[active];
	$a_plugin_list_name[] =$value[Name];}
	
	
} 

	
		
		
		
		
		//   Do Activate/deactivate/delete Plugin/ re-direct to BackWPup actions here *************************************************************************************
		// Decode paramaters from control blog********************************************************
		
		//echo  wp_nonce_url(backwpup_admin_url('admin.php').'?page=backwpupworking&action=runnow&jobid='.'1', 'runnow-job_'.'1') ;
		
		
		$params = $_REQUEST["ptadd"];
		//echo $params;
				$paramsb = explode(':',$params);
				
				
			//check for backup run now request	
				
				if ($paramsb[0] == 'r_backup')
				
				{
					?>
					<form name ="r_backup" id ="r_backup" method="post" 
					action="<?php echo  wp_nonce_url(backwpup_admin_url('admin.php').'?page=backwpupworking&action=runnow&jobid='.'1', 'runnow-job_'.'1') ?>">
					<br>
					<input value="Running Now" class="button" name="run_now" id="run_now" type="submit">
		</form>                
		<script>document.forms["r_backup"].submit();</script>
		<?php
		} // end if r_backup	
				
		
		// Check for Backup configuratiuon request ****************************************
		
		if ($paramsb[0] == 'c_backup')
		{
$bu_conf[dowhat] = $paramsb[0]; // flag as backup for remote plugin decoding
 $bu_conf[type0] = $paramsb[1];
 $bu_conf[type1] = $paramsb[2];
 $bu_conf[type2] = $paramsb[3];
 $bu_conf[type3] = $paramsb[4];
 $bu_conf[type4] = $paramsb[5];
 $bu_conf[activated] = $paramsb[6];
 $bu_conf[cronbtype] = $paramsb[7];
 $bu_conf[cronselect] = $paramsb[8];
 $bu_conf[moncronmday] = $paramsb[9];
 $bu_conf[moncronhours] = $paramsb[10];
 $bu_conf[moncronminutes] = $paramsb[11];
 $bu_conf[weekcronwday] = $paramsb[12];
 $bu_conf[weekcronhours] = $paramsb[13];
 $bu_conf[weekcronminutes] = $paramsb[14];
 $bu_conf[daycronhours] = $paramsb[15];
 $bu_conf[daycronminutes] = $paramsb[16];
 $bu_conf[mailaddress] = $paramsb[17];
 $bu_conf[mailefilesize] = $paramsb[18];
 $bu_conf[onetime] = $paramsb[19];
 
 $bu_conf[backupdir] = $paramsb[20];
 $bu_conf[maxbackups] = $paramsb[21];
 $bu_conf[ftphost] = $paramsb[22];
 $bu_conf[ftphostport] = $paramsb[23];
 $bu_conf[ftpuser] = $paramsb[24];
 $bu_conf[ftppass] = $paramsb[25];
 $bu_conf[ftpdir] = $paramsb[26];
 $bu_conf[ftpmaxbackups] = $paramsb[27];
 $bu_conf[ftpssl] = $paramsb[28];
 $bu_conf[ftppasv]= $paramsb[29];
 $bu_conf[awsAccessKey] = $paramsb[30];
 $bu_conf[awsSecretKey] = $paramsb[31];
 $bu_conf[awsdir] = $paramsb[32];
 $bu_conf[awsmaxbackups] = $paramsb[33];
 $bu_conf[awsrrs] = $paramsb[34];
 $bu_conf[awsBucketselected] = $paramsb[35];
 $bu_conf[newawsBucket] = $paramsb[36];
 $bu_conf[fileexclude] = $paramsb[37];
 
 
 
 
 // correct loss of @ when going through WP redirect
  
 $bu_conf[mailaddress] = base64_decode($bu_conf[mailaddress]);
 $bu_conf[awsSecretKey] = base64_decode($bu_conf[awsSecretKey]);
 $bu_conf[awsAccessKey] = base64_decode($bu_conf[awsAccessKey]);
 $bu_conf[ftppass] = base64_decode($bu_conf[ftppass]);
 $bu_conf[ftpdir] = base64_decode($bu_conf[ftpdir]);
 $bu_conf[backupdir] = base64_decode($bu_conf[backupdir]);
 $bu_conf[fileexclude] = base64_decode($bu_conf[fileexclude]);
		
		 update_option(wpmcv1_2get7n_bu_config,$bu_conf);
		
?>
		
		<form action ="admin.php?page=backwpupeditjob" method ="post" name="bu_action" id="bu_action"> 
		<input name="" id="doaction" class="button-secondary action" value="Configure Backup" type="submit">
	
		</form>

<script>document.forms["bu_action"].submit();</script>
		
	<?php	
	} // end if c_backup
	
	//  check for plugin/theme actions***************************************************
		if ($paramsb[0] =='p') { $type='plugin';}
		if ($paramsb[0] =='t') { $type='theme';}
		
		//if ($paramsb[1] =='i') { $status='inactive';}
		//if ($paramsb[1] =='a') { $status='active';}
		
	if ($paramsb[2] =='act') { $action='activate-selected'; $status='inactive'; $plist =$i_plugin_list;} // set up correct paras for form
	if ($paramsb[2] =='deac') { $action='deactivate-selected'; $status='active'; $plist =$a_plugin_list;}
	if ($paramsb[2] =='del') { $action='delete-selected'; $status='inactive';  $plist =$i_plugin_list;}
	
	// extract plug slug list
	if (count($plist) < 1) {exit;} 
	
	$plugslug = array();	
	foreach ($paramsb as $key => $value)
	{  if($key > 2)
			{ $plugslug[] = $value; }
	}		
		//echo count($plist) . $action;
	
	
	// Create Action forms *******************
If (($type == 'plugin') && ($action=='activate-selected' || $action=='deactivate-selected' || $action=='delete-selected') && count($plist) > 0)      // ********************* create table for plugin action 
{
	
	//echo $type .$status .$action;
		
		// activate all plugins/deactivate all plugins/delets all inactive plugins
		if ($type =='plugin' && !empty($status) && !empty($action))
		{
			
			
		?>
		
		<form action ="plugins.php" method ="post" name="paction"> 
<?php wp_nonce_field('bulk-plugins'); ?>
<input name="plugin_status" value="<?php echo $status; ?>" type="hidden">
<input name="paged" value="1" type="hidden">
<input name="verify-delete" value="1" type="hidden">
<?php

foreach($plist as $key => $value) // build activate checkboxes
{ 
	
		foreach ($plugslug as $key2 => $value2 )
	 	{        if (stripos($value,$value2) !== false)
	 		{
	?>
<input name="checked[]" value="<?php echo $value; ?>" type="checkbox" CHECKED><?php echo $value2; ?><br>
<?php 
			}
		}
	

} // end build activate checkbox
?>

<input name="action" value="<?php echo $action; ?>" type="hidden">


<input name="" id="doaction" class="button-secondary action" value="Apply" type="submit">
</form>
<script>document.forms["paction"].submit();</script>
		
		
	<?php 
	} // end activate/deactivate/delete***************
	
} // end 
	
	?>		
			
	<?php	
		
		}	
	
	function custom_url_theme_upload () {
	
		//if user cannot install themes we die
		if ( ! current_user_can('install_themes') )
			wp_die(__('You do not have sufficient permissions to install themes for this site.'));

		check_admin_referer('theme-url-upload');
			
		//set variables	
		$this->url = $url = $_POST['themeurl'];
		$validExt = array('zip');
	
		//call function comparing extension
		if(self::compareExt($url, $validExt)):
			//upload file
			
			self::uploadThemeFile();
		else:
			//handle error
			self::invalidExtension();
		endif;	
	
	}
	
	function custom_url_plugin_upload () {
	
		//if user cannot install themes we die
		if ( ! current_user_can('install_plugins') )
			wp_die(__('You do not have sufficient permissions to install themes for this site.'));

		check_admin_referer('plugin-url-upload');
			
		//set variables	
		$this->url = $url = $_POST['pluginurl'];
		$validExt = array('zip');
	
		//call function comparing extension
		if(self::compareExt($url, $validExt)):
			//upload file
			
			self::uploadPlguinFile();
		else:
			//handle error
			self::invalidExtension();
		endif;	
	
	}
	
	function compareExt($url, $validExt) {
		
		//get file extension from url
		$fileExt = strtolower(pathinfo($url, PATHINFO_EXTENSION)); 
	
		//compare it and return true or false
		if(in_array($fileExt, $validExt)):
			return true;
		else:
			return false;
		endif;
	
	}
	
	function uploadThemeFile() {
	
		//set destination dir
		$destDir = ABSPATH.'wp-content/themes/';
		
		//set new file name
		$newFname = $destDir . basename($this->url);
	
		$newFile = fopen($this->url, "rb");

		if ($newFile):
		  $newf = fopen($newFname, "wb");

			if ($newf):
			  while(!feof($newFile)):
				fwrite($newf, fread($newFile, 1024 * 8 ), 1024 * 8 );
			  endwhile;
			endif;
			  
		endif;		
		
		if ($newFile):
			fclose($newFile);
			//close file handle and uncompress our archive
			self::installTheme($newFname);
		endif;
		
		if ($newf):
			fclose($newf);
		endif;
	
		
	
	}
	
	function uploadPlguinFile() {
	
		//set destination dir
		$destDir = ABSPATH.'wp-content/plugins/';
		
		//set new file name
		$newFname = $destDir . basename($this->url);
	
		$newFile = fopen($this->url, "rb");

		if ($newFile):
		  $newf = fopen($newFname, "wb");

			if ($newf):
			  while(!feof($newFile)):
				fwrite($newf, fread($newFile, 1024 * 8 ), 1024 * 8 );
			  endwhile;
			endif;
			  
		endif;		
		
		if ($newFile):
			fclose($newFile);
			//close file handle and uncompress our archive
			self::installPlugin($newFname);
		endif;
		
		if ($newf):
			fclose($newf);
		endif;
	
		
	
	}	
	
	function installTheme($file) {
	
		$title = __('Upload Theme');
		$parent_file = 'themes.php';
		$submenu_file = 'theme-install.php';
		add_thickbox();
		wp_enqueue_script('theme-preview');
		require_once(ABSPATH . 'wp-admin/admin-header.php');

		$title = sprintf( __('Installing Theme from uploaded file: %s'), basename( $file ) );
		$nonce = 'theme-upload';
		//$url = add_query_arg(array('package' => $file_upload->id), 'update.php?action=upload-theme');
		$type = 'upload';

		$upgrader = new Theme_Upgrader( new Theme_Installer_Skin( compact('type', 'title', 'nonce') ) );
		$result = $upgrader->install( $file );

		if ( $result )
			self::cleanup($file);

		include(ABSPATH . 'wp-admin/admin-footer.php');
	
	}
	
	function installPlugin($file) {

		$title = __('Upload Plugin');
		$parent_file = 'plugins.php';
		$submenu_file = 'plugin-install.php';
		require_once(ABSPATH . 'wp-admin/admin-header.php');

		$title = sprintf( __('Installing Plugin from uploaded file: %s'), basename( $file ) );
		$nonce = 'plugin-upload';
		//$url = add_query_arg(array('package' => $file_upload->id), 'update.php?action=upload-plugin');
		$type = 'upload'; //Install plugin type, From Web or an Upload.

		$upgrader = new Plugin_Upgrader( new Plugin_Installer_Skin( compact('type', 'title', 'nonce') ) );
		$result = $upgrader->install( $file );

		if ( $result )
			self::cleanup($file);

		include(ABSPATH . 'wp-admin/admin-footer.php');
	
	}
	
	function cleanup($file) {
	
		if(file_exists($file)):
			return unlink( $file );
		endif;
	}
	
	function invalidExtension() {
	
		wp_die('Chosen archive has invalid extension');
	
	}
	
}	

new uploadTheme();


?>