<?php

/*
Plugin Name: SecretLab Installer
Plugin URI: http://www.secretlab.pw/
Description: Imports necessary data and settings for The Guard Theme
Author: SecretLab
Version: 1.0
Author URI: http://www.secretlab.pw/
*/


class secret_setup {

    public $theme_type;

	public function __construct() {
        add_filter( 'http_request_timeout', array( &$this, 'bump_request_timeout' ) );
        set_time_limit(0);

	    WP_Filesystem();
		global $wp_filesystem;

    }

	public function bump_request_timeout() {
	    return 60;
	}

	public function install_plugins() {
	
	    if($_POST['op'] == 'install_plugins') {
	
			if ($_POST['i_id'] == 0) {
				delete_transient('guard_on_click_setup');
			}
				
			$setup_opts = array( 'install_plugins' => $_POST['install_plugins'], 'activate_plugins' => $_POST['activate_plugins'],
								 'import_widgets' => $_POST['import_widgets'], 'set_theme_options_and_icons' => $_POST['set_theme_options_and_icons'], 
								 'set_sliders' => $_POST['set_sliders'], 'technical_refresh' => $_POST['technical_refresh'], 
								 'set_types' => $_POST['set_types'], 'set_post_and_menu_screens' => $_POST['set_post_and_menu_screens'],
								 'import_sample_data' => $_POST['import_sample_data'], 'i_id' => 0,
								 'install_theme' => $_POST['install_theme'], 'import_data' => $_POST['import_data'], 
								 'import_attachments' => $_POST['import_attachments']);
								 
			set_transient('guard_on_click_setup', $setup_opts, 60*10);
			$tgm_install = 1;
			$tgm_is_automatic = false;
			$msg = 'Plugins Installed';
		
		}
		else if ($_POST['op'] == 'activate_plugins') {
		    $tgm_install = 0;
			$tgm_is_automatic = true;
			$msg = 'Plugins Activated';
		}
	
		$plugins = array(
            array(
                'name' => 'SecretLab Installer',
                'slug' => 'SecretLabInstaller',
                'source' => get_template_directory().'/lib/SecretLabInstaller.zip',
                'required' => true,
            ),
            array(
                'name' => 'redux-framework',
                'slug' => 'redux-framework',
                'required' => true,
            ),
            array(
                'name' => 'Contact Form 7',
                'slug' => 'contact-form-7',
                'required' => true
            ),
            array(
                'name' => 'WooCommerce',
                'slug' => 'woocommerce',
                'required' => true
            ),
			array(
				'name' => esc_attr__('Types', 'the-repair'),
				'slug' => 'types',
				'required' => true
			),
            array(
                'name' => 'Regenerate Thumbnails',
                'slug' => 'regenerate-thumbnails',
                'required' => true
            ),
            array(
                'name' => 'MailPoet Newsletters',
                'slug' => 'wysija-newsletters',
                'required' => true
            ),
            array(
                'name' => 'WPBakery Visual Composer',
                'slug' => 'js_composer',
                'source' => get_template_directory().'/lib/js_composer.zip',
                'external_url' => 'http://wpbakery.com',
                'required' => true
            ),
            array(
                'name' => 'Ultimate Addons for Visual Composer',
                'slug' => 'Ultimate_VC_Addons',
                'source' => get_template_directory().'/lib/ultimate_vc_addons.zip',
                'external_url' => 'https://brainstormforce.com/demos/ultimate/',
                'required' => true
            ),
            array(
                'name' => 'Revolution Slider',
                'slug' => 'revslider',
                'source' => get_template_directory().'/lib/revslider.zip',
                'external_url' => 'http://www.revolution.themepunch.com/',
                'required' => true
            ),
            array(
                'name' => 'SecretLab Metabox',
                'slug' => 'SecretLabMetabox',
                'source' => get_template_directory().'/lib/SecretLabMetabox.zip',
                'external_url' => 'http://secretlab.pw',
            ),
            array(
                'name' => 'SecretLab Sidebars',
                'slug' => 'widget-areas',
                'source' => get_template_directory().'/lib/widget-areas.zip',
                'external_url' => 'http://secretlab.pw',
            ),
            array(
                'name' => 'SecretLab Shortcodes',
                'slug' => 'SecretLabShortcodes',
                'source' => get_template_directory().'/lib/SecretLabShortcodes.zip',
                'external_url' => 'http://secretlab.pw',
                'required' => true,
            ),
            array(
                'name' => 'Envato WordPress Toolkit',
                'slug' => 'envato-wordpress-toolkit-master',
                'source' => get_template_directory().'/lib/envato-wordpress-toolkit-master.zip',
                'external_url' => 'http://secretlab.pw',
                'required' => false
            ),
            array(
                'name' => 'Responsive Lightbox',
                'slug' => 'responsive-lightbox',
                'required' => true
            ),
            array(
                'name' => 'Yoast SEO',
                'slug' => 'wordpress-seo',
                'required' => false
            ),
            array(
                'name' => 'SecretLab Importer',
                'slug' => 'wordpress-importer',
                'source' => get_template_directory().'/lib/wordpress-importer.zip',
                'external_url' => 'http://secretlab.pw',
                'required' => true,
            ),
            array(
                'name' => 'Widget Importer & Exporter',
                'slug' => 'widget-importer-exporter',
                'required' => true
            ),	
            array(
                'name' => 'SecretLab Widget Areas',
                'slug' => 'widget-areas',
                'source' => get_template_directory().'/lib/widget-areas.zip',
                'external_url' => 'http://secretlab.pw',
                'required' => true
            ),			
            array(
                'name' => 'All In One Widget',
                'slug' => 'aiow_pl',
                'source' => get_template_directory().'/lib/aiow_pl.zip',
                'external_url' => 'http://codecanyon.net/user/ERROPiX/portfolio/',
                'required' => true
            )		
        );

		if ($tgm_install == 1) {
			foreach ($plugins as $plugin) {
				$_GET['plugin'] = $plugin['slug'];
				$_POST['tgm_pass'] = 1;	
				$_POST['tgm_install'] =  $tgm_install;			
				$tgma = new TGM_Plugin_Activation();
				$tgma->register($plugin);
				$tgma->is_automatic = $tgm_is_automatic;
				$tgma->do_plugin_install();
			}
        }
        else if ($tgm_install == 0) {
		    foreach ($plugins as $plugin) {
			    $_POST['tgm_pass'] = 0;
			    $tgma = new TGM_Plugin_Activation();
				$file_path = $tgma->_get_plugin_basename_from_slug( $plugin['slug'] );
				$tgma->activate_single_plugin($file_path, $plugin['slug']);
		    }
        }		
		
		echo '___<p><b>' . esc_attr__( $msg ) . '</b></p>___';
		
	}

	public function abort() {
	    delete_transient('guard_on_click_setup');
	}



	public function run() {
	
	    if (isset($_POST['theme_type'])) { 
		    $this->theme_type = $_POST['theme_type'];
            if ( $this->theme_type != 'light' ) $this->theme_prefix = 'agency_';
			else $this->theme_prefix = 'systems_'; 
		} 
		else { $this->theme_type = 'black'; $this->theme_prefix = 'agency_'; }

		$method = $_POST['op'];
		if ($method == 'activate_plugins') $method = 'install_plugins';
		if (method_exists($this, $method))
		    $this->$method();
		else {
		    $setup2 = new SL_Installer($this->theme_prefix);
			if (method_exists($setup2, $method))
			    $setup2->$method();
			else
			    $this->abort();
		}

	}

}



function guard_theme_setup() {

    $setup = new secret_setup();

	$setup->run();

}


add_action( 'wp_ajax_setup_theme', 'guard_theme_setup' );
add_action( 'wp_ajax_nopriv_setup_theme', 'guard_theme_setup' );


class SL_Installer {

    public function __construct($theme_prefix) {

	    include_once ABSPATH.'/wp-admin/includes/file.php';
	    WP_Filesystem();
		
		global $wp_filesystem;
		
		if (isset($_POST['theme_type'])) $this->theme_type = $_POST['theme_type']; else $this->theme_type = 'black';
		
		$this->theme_prefix = $theme_prefix;
		
	}
	
	public function set_sliders() {

	    global $wpdb;
	
	    $uploads_dir = wp_upload_dir(); 
		$sliders = $wpdb->get_col( "SELECT title, alias FROM ".$wpdb->prefix."revslider_sliders", 1 ); 
		$files = glob(get_template_directory() . '/'  . 'import/SEC ' . $this->theme_prefix . $this->theme_type . '/sliders/*.zip');
		var_dump(get_template_directory() . '/'  . 'import/SEC ' . $this->theme_prefix . $this->theme_type . '/sliders/*.zip');
		$names = preg_replace('/(.+sliders\/)([^\.]+)(\.zip)/', "\$2", $files); 
		$msg = $result = array();
		//ob_start();
		$i = 0;
		foreach ($names as $name) {
			if (!in_array($name, $sliders)) { 
			    $_FILES["import_file"]["tmp_name"] = $files[$i];
			    $instance = new RevSliderSlider();
			    $instance->importSliderFromPost();
				$result[] = str_ireplace('_', ' ', $name);
			}
			else {
			    $msg[] = '<i>' . str_ireplace('_', ' ', $name) . '</i>';
			}
			$i++;
		}
		//ob_end_clean();
		if (count($result) > 0) $result = 'Revolution Sliders ' . implode(', ', $result) . ' are imported';
		else $result = '';
		if (count($msg) > 0) $msg = '<br>NOTE: sliders ' . implode(', ', $msg) . ' already exists';
		else $msg = '';
		echo '___<p><b>'. $result .'</b>' . $msg . '</p>___';

	}

    public function set_icons () {
        activate_alico_icons();		
		echo '___<p><b>'.esc_attr__( 'Function ended', 'the-seo' ).'</b></p>___';
	}
	
	public function set_theme_options() {
	    global $wp_filesystem;
		    				
		$theme_options = $wp_filesystem->get_contents(get_template_directory() . '/'  . 'import/SEC ' . $this->theme_prefix . $this->theme_type . '/theme_options.json' );
		$theme_options = preg_replace('/http.....(secpl1|secpl2|secpl3).secretlab.pw/', site_url(), $theme_options);
		if (update_option('secretlab', json_decode($theme_options, true))) $msg = '___<p><b>'.esc_attr__( 'Theme Options updated', 'the-seo' ).'</b></p>___'; else $msg = '___<p><b>'.esc_attr__( 'Error occured while Theme Options importing or you are trying to save the same data', 'the-seo' ).'</b></p>___';
		
		$options = get_option('secretlab');
		if (is_array( $options ) ) theguard_change_action($options);

		echo $msg;
	}
	



	public function import_widgets($echo = true) {

		$file = glob( get_template_directory() . '/import/SEC ' . $this->theme_prefix .$this->theme_type. '/widgets.json' );
		$file = $file[0];
		$file_to_use = str_ireplace('.json', '_to_use.json', $file);
		copy( $file, $file_to_use );
		wie_process_import_file( $file_to_use );

		if ($echo)
			echo '___<p><b>'.esc_attr__( 'Widgets imported', 'the-seo' ).'</b></p>___';
	}

	public function set_post_and_menu_screens() {
		guard_set_admin_metaboxes();
		if ($_POST['data_import'] == 0) { echo '___<p class="green"><b>'.esc_attr__( 'Theme setup completed', 'the-seo' ).'</b></p>___'; }
	}		

    public function set_types() {
	
	    global $wp_filesystem;
		
			$_POST['overwrite-settings'] = 1;
			$_POST['overwrite-groups'] = 1;
			$_POST['delete-groups'] = 1;
			$_POST['delete-fields'] = 1;
			$_POST['delete-types'] = 1;
			$_POST['delete-tax'] = 1;
			$_POST['overwrite-fields'] = 1;
			$_POST['overwrite-types'] = 1;
			$_POST['overwrite-tax'] = 1;
			$_POST['post_relationship'] = 1;
			$_POST['mode'] = 'file';
			$_POST['import-final'] = 1;
			$_POST['import'] = 'Import';
			//require_once WP_PLUGIN_DIR . '/types/embedded/admin.php';
			//require_once WP_PLUGIN_DIR . '/types/embedded/types.php';
			//require_once WP_PLUGIN_DIR . '/types/embedded/includes/fields.php';
			//require_once WP_PLUGIN_DIR . '/types/embedded/includes/import-export.php';
			$data = $wp_filesystem->get_contents( get_template_directory() . '/import/types_plugin_settings.xml' );
			wpcf_admin_import_data( $data, false, 'types-auto-import' );
			
			echo '___<p><b>'.esc_attr__( 'Types Plugin Settings imported', 'the-seo' ).'</b></p>___';
				
	}
	
	public function import_sample_data() {
		global $wpdb, $wp_import, $wp_filesystem;

		if ($_POST['import_data'] == 1 || $_POST['op'] == 'import_sample_data') {

			if ( !defined('WP_LOAD_IMPORTERS') ) define('WP_LOAD_IMPORTERS', true); // we are loading importers

			if ( ! class_exists( 'WP_Importer' ) ) { // if main importer class doesn't exist
				$wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
				include $wp_importer;
			}

			if ( ! class_exists('WP_Import') ) { // if WP importer doesn't exist
				$wp_import = WP_PLUGIN_DIR . '/wordpress-importer/secretlab-importer.php';
				include $wp_import;
			}

			if ( class_exists( 'WP_Importer' ) && class_exists( 'WP_Import' ) ) {

				$_POST['imported_authors'][0] = 'admin';
				$_POST['imported_authors'][1] = 'wooteam';
				$_POST['use_map'][0] = 0;
				$_POST['use_map'][1] = 0;
				$_POST['user_new'][0] = null;
				$_POST['user_new'][1] = null;

				$importer = new WP_Import();
                $importer->fetch_attachments = false;
				
				$files = glob( get_template_directory() . '/import/SEC ' . $this->theme_prefix .$this->theme_type. '/demo_data.xml' );

				$past_files = glob( get_template_directory() . '/import/*inst.xml' );
				if (count($past_files) > 0) {
					foreach ($past_files as $pf) {
						unlink($pf);
					}
				}				
				

				
				foreach ($files as $file) {
					$nfn = str_ireplace('.xml', '_inst.xml', $file);
					if (copy($file, $nfn)) {
						$object = array(
							'post_title' => $nfn ,
							'post_content' => $nfn,
							'post_mime_type' => '',
							'guid' => $nfn,
							'context' => 'import',
							'post_status' => 'private'
						);

						$id = wp_insert_attachment( $object, $nfn );
						wp_schedule_single_event( time() + DAY_IN_SECONDS, 'importer_scheduled_cleanup', array( $id ) );

						$_POST['import_id'] = $id;
						$importer->id = $id;

						ob_start();
						$importer->import($nfn);
						if (is_file($nfn)) unlink($nfn);
						sleep(2);
						ob_end_clean();
					}
				}
				echo '___<p class="green"><b>'.esc_attr__( 'Sample data imported', 'the-seo' ).'</b></p>___';
			}
			else {
				echo '___<p class="red"><b>'.esc_attr__( 'There are problems with WP_Import classes, check if "wordpress-importer" plugin is activated', 'the-seo' ).'</b></p>___';
			}
			// Connect Nav Menus to locations
			if ($this->theme_type == 'dark') $menu_name = 'Header Menu'; else $menu_name = 'Header Menu';
			$native_menu = wp_get_nav_menu_object($menu_name);
			$locations = array('theguard_top_menu');
			$menu_set = array();
			foreach ($locations as $location) {
				$menu_set[$location] = $native_menu->term_id;
			}
			if (count($menu_set) > 0) {
				set_theme_mod('nav_menu_locations', $menu_set);
			}
			// Set Front Page
			$homepage = get_post( 549 );
			if (($homepage && $homepage->ID)) {
				update_option('show_on_front', 'page');
				update_option('page_on_front', $homepage->ID);
			}
			// change parent URI to local URI in Post Content Visual Composer data
			$site_url = site_url();
			$posts = get_posts(array('posts_per_page' => -1, 'numberposts' => -1, 'post_type' => 'any'));
			foreach ($posts as $p) {
				$post_content = preg_replace('/url.http.3A.2F.2F(secpl1|secpl2|secpl3).secretlab.pw.2F/', 'url:' . urlencode($site_url), $p->post_content);
				if ( ! wp_is_post_revision( $p->ID ) ){

					$args = array('ID' => $p->ID, 
								  'post_content' => $post_content );
					$result = wp_update_post( $args );
				}
			}
            // end of VC data correction			
			// Finish Import
			delete_transient('guard_on_click_setup');
		}
	}
	
	
	public function get_xml_file() {
	    global $wp_filesystem;
		
		$file = glob(get_template_directory() . '/' . 'import/SEC ' . $this->theme_prefix . $this->theme_type . '/demo_data.xml');
		$file = $file[0];
		$content = $wp_filesystem->get_contents($file);
		
		ob_clean();
		echo $content;
	}
	
	
	public function get_uploaded_attachments() {
	    $uploaded_attachments = get_option('guard_uploaded_attachments');
		ob_clean();
		if ($uploaded_attachments && count($uploaded_attachments) > 0) {
		    echo json_encode(array('empty' => 'no', 'content' => array_values($uploaded_attachments)));
		}
		else {
		    echo json_encode(array('empty' => 'yes', 'content' => $uploaded_attachments));
		}
	}
	
	
	public function attachment_upload() {
	    //header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
		$parameters = array(
			'url' => $_POST['url'],
			'post_title' => $_POST['title'],
			'link' => $_POST['link'],
			'pubDate' => $_POST['pubDate'],
			'post_author' => $_POST['creator'],
			'guid' => $_POST['guid'],
			'import_id' => $_POST['post_id'],
			'post_date' => $_POST['post_date'],
			'post_date_gmt' => $_POST['post_date_gmt'],
			'comment_status' => $_POST['comment_status'],
			'ping_status' => $_POST['ping_status'],
			'post_name' => $_POST['post_name'],
			'post_status' => $_POST['status'],
			'post_parent' => $_POST['post_parent'],
			'menu_order' => $_POST['menu_order'],
			'post_type' => $_POST['post_type'],
			'post_password' => $_POST['post_password'],
			'is_sticky' => $_POST['is_sticky'],
			'attribute_author1' => $_POST['author1'],
			'attribute_author2' => $_POST['author2']
		);

		function process_attachment( $post, $url ) {
			
			$pre_process = pre_process_attachment( $post, $url );
			if( is_wp_error( $pre_process ) )
				return array(
					'fatal' => false,
					'type' => 'error',
					'code' => $pre_process->get_error_code(),
					'message' => $pre_process->get_error_message(),
					'text' => sprintf( __( '%1$s was not uploaded. (<strong>%2$s</strong>: %3$s)', 'attachment-importer' ), $post['post_title'], $pre_process->get_error_code(), $pre_process->get_error_message() )
				);

			// if the URL is absolute, but does not contain address, then upload it assuming base_site_url
			if ( preg_match( '|^/[\w\W]+$|', $url ) )
				$url = rtrim( $this->base_url, '/' ) . $url;

			$upload = fetch_remote_file( $url, $post );
			if ( is_wp_error( $upload ) )
				return array(
					'fatal' => ( $upload->get_error_code() == 'upload_dir_error' && $upload->get_error_message() != 'Invalid file type' ? true : false ),
					'type' => 'error',
					'code' => $upload->get_error_code(),
					'message' => $upload->get_error_message(),
					'text' => sprintf( __( '%1$s could not be uploaded because of an error. (<strong>%2$s</strong>: %3$s)', 'attachment-importer' ), $post['post_title'], $upload->get_error_code(), $upload->get_error_message() )
				);

			if ( $info = wp_check_filetype( $upload['file'] ) )
				$post['post_mime_type'] = $info['type'];
			else {
				$upload = new WP_Error( 'attachment_processing_error', __('Invalid file type', 'attachment-importer') );
				return array(
					'fatal' => false,
					'type' => 'error',
					'code' => $upload->get_error_code(),
					'message' => $upload->get_error_message(),
					'text' => sprintf( __( '%1$s could not be uploaded because of an error. (<strong>%2$s</strong>: %3$s)', 'attachment-importer' ), $post['post_title'], $upload->get_error_code(), $upload->get_error_message() )
				);
			}

			$post['guid'] = $upload['url'];

			// Set author per user options.
			switch( $post['attribute_author1'] ){

				case 1: // Attribute to current user.
					$post['post_author'] = (int) wp_get_current_user()->ID;
					break;

				case 2: // Attribute to user in import file.
					if( !username_exists( $post['post_author'] ) )
						wp_create_user( $post['post_author'], wp_generate_password() );
					$post['post_author'] = (int) username_exists( $post['post_author'] );
					break;

				case 3: // Attribute to selected user.
					$post['post_author'] = (int) $post['attribute_author2'];
					break;

			}

			// as per wp-admin/includes/upload.php
			$post_id = wp_insert_attachment( $post, $upload['file'] );
			wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) );

			// remap image URL's
			backfill_attachment_urls( $url, $upload['url'] );

			return array(
				'fatal' => false,
				'type' => 'updated',
				'text' => sprintf( __( '%s was uploaded successfully', 'attachment-importer' ), $post['post_title'] )
			);
		}

		function pre_process_attachment( $post, $url ){
			global $wpdb;

			$imported = $wpdb->get_results(
				$wpdb->prepare(
					"
					SELECT ID, post_date_gmt, guid
					FROM $wpdb->posts
					WHERE post_type = 'attachment'
						AND post_title = %s
					",
					$post['post_title']
				)
			);

			if( $imported ){
				foreach( $imported as $attachment ){
					if( basename( $url ) == basename( $attachment->guid ) ){
						if( $post['post_date_gmt'] == $attachment->post_date_gmt ){
							$headers = wp_get_http( $url );
							if( filesize( get_attached_file( $attachment->ID ) ) == $headers['content-length'] ){
								return new WP_Error( 'duplicate_file_notice', __( 'File already exists', 'attachment-importer' ) );
							}
						}
					}
				}
			}

			return false;
		}
		
		function fetch_remote_file( $url, $post ) {
			// extract the file name and extension from the url
			$file_name = basename( $url );

			// get placeholder file in the upload dir with a unique, sanitized filename
			$upload = wp_upload_bits( $file_name, 0, '', $post['post_date'] );
			if ( $upload['error'] )
				return new WP_Error( 'upload_dir_error', $upload['error'] );

			// fetch the remote url and write it to the placeholder file
			$headers = wp_get_http( $url, $upload['file'] );
			// request failed
			if ( ! $headers ) {
				@unlink( $upload['file'] );
				return new WP_Error( 'import_file_error', __('Remote server did not respond', 'attachment-importer') );
			}

			// make sure the fetch was successful
			if ( $headers['response'] != '200' ) {
				@unlink( $upload['file'] );
				return new WP_Error( 'import_file_error', sprintf( __('Remote server returned error response %1$d %2$s', 'attachment-importer'), esc_html($headers['response']), get_status_header_desc($headers['response']) ) );
			}

			$filesize = filesize( $upload['file'] );

			if ( isset( $headers['content-length'] ) && $filesize != $headers['content-length'] ) {
				@unlink( $upload['file'] );
				return new WP_Error( 'import_file_error', __('Remote file is incorrect size', 'attachment-importer') );
			}

			if ( 0 == $filesize ) {
				@unlink( $upload['file'] );
				return new WP_Error( 'import_file_error', __('Zero size file downloaded', 'attachment-importer') );
			}

			return $upload;
		}

		function backfill_attachment_urls( $from_url, $to_url ) {
			global $wpdb;
			// remap urls in post_content
			$wpdb->query(
				$wpdb->prepare(
					"
						UPDATE {$wpdb->posts}
						SET post_content = REPLACE(post_content, %s, %s)
					",
					$from_url, $to_url
				)
			);
			// remap enclosure urls
			$result = $wpdb->query(
				$wpdb->prepare(
					"
						UPDATE {$wpdb->postmeta}
						SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key='enclosure'
					",
					$from_url, $to_url
				)
			);
		}

		$remote_url = ! empty($parameters['attachment_url']) ? $parameters['attachment_url'] : $parameters['guid'];
		
		$result = process_attachment( $parameters, $remote_url );
		ob_clean();
		echo json_encode( $result );
		
		if (!isset($result['error']) && !isset($result['fatal'])) {
		    $uploaded_attachments = get_option('guard_uploaded_attachments');
		    if (!is_array($uploaded_attachments)) {
		        $uploaded_attachments[] = array();
		    }
            $uploaded_attachments[] = $_POST['post_id'];
		    if (is_array($uploaded_attachments))
		        update_option('guard_uploaded_attachments', array_unique($uploaded_attachments));
		}
		
		die();
	}


}

function welcome_notice() {
    global $wn;
	
		$max = array( "max_execution_time"    => array(120, ini_get("max_execution_time"), " 'max_execution_time' parameter on your hosting/server is ### seconds, 120 seconds recommended"),
					  "memory_limit"          => array(256, intval(ini_get("memory_limit")), " 'memory_limit' parameter on your hosting/server is ### Mb, 256Mb recommended" ),
					  "post_max_size"         => array(32, intval(ini_get("post_max_size")), " 'post_max_size' parameter on your hosting/server is ### Mb, 32Mb recommended"),
					  "upload_max_filesize"   => array(32, intval(ini_get("upload_max_filesize")), " 'upload_max_filesize' parameter on your hosting/server is ### Mb, 32Mb recommended")
		);

		$init_msgs = array();
		foreach($max as $name => $set) {
			if ($set[1] < $set[0]) {
				$init_msgs[] = str_ireplace('###', $set[1], $set[2]);
			}
		}
		
		if (count($init_msgs) > 0) $init_msg = '<div id="init_msg">' . implode($init_msgs, '<br>') . '</div>';
		else $init_msg = '';
		
		$wn['real_capabilities'] = $init_msg;
		
		$wn['recommended_capabilities'] = '<div class="col-md-4 col-sm-12">
		                <div class="inform">
						<h3>Server Requirements</h3>
						<ul>
						<li>max_execution_time 120</li>
						<li>memory_limit 256M</li>
						<li>post_max_size 32M</li>
						<li>upload_max_filesize 32M</li>
						</ul>
						</div>
						</div>';
						
		$wn['fail_install'] = '<div class="col-md-4 col-sm-12">
		                <div class="inform">
						<h3>Fail of installation</h3>
						   If you got fail of the installation ask your hosting to check error logs
						</div>
						</div>';
					
	}
	
	add_action('delete_attachment', 'guard_correct_imported_attaches_list', 10, 2);
	
	function guard_correct_imported_attaches_list($id) {
	    $imported_attaches = get_option('guard_uploaded_attachments');
		if (is_array($imported_attaches)) {
		    $imported_attaches = array_diff($imported_attaches, array($id));
			update_option('guard_uploaded_attachments', $imported_attaches);
		}
	}

	
function activate_alico_icons() {
    $plugins = get_option('active_plugins');

    if (in_array('Ultimate_VC_Addons/Ultimate_VC_Addons.php', $plugins)) {
	    global $wp_filesystem;
		
        if( empty( $wp_filesystem ) ) {
            require_once( ABSPATH .'/wp-admin/includes/file.php' );
            WP_Filesystem();
        }

        $pathes = array ( '/import/alico*.zip', '/import/security.zip' );
		$ids = array();

		foreach ($pathes as $path) {
		
		$fp = glob( get_template_directory() . $path );
		if (!$fp) die('no available icons zip file in /import/icons directory!');
		else $fp = $fp[0];
		 
		preg_match('/\/([^\/]+)$/', $fp, $fn);
		$fn = $fn[1];
		
		$wp_upload_dir = wp_upload_dir();
		
		if (!file_exists($wp_upload_dir['path'] . '/' . $fn)) {
				 
		    $result = wp_upload_bits( $fn, null, $wp_filesystem->get_contents($fp) );
		
		    $filename = $wp_upload_dir['path'] . '/' . $fn;
		    $filetype = wp_check_filetype( basename( $filename ), null );
		 
		    $attachment = array(
			    'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
			    'post_mime_type' => $filetype['type'],
			    'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
			    'post_content'   => '',
			    'post_status'    => 'inherit'
		    );

		    $attach_id = wp_insert_attachment( $attachment, $filename );

			    require_once( ABSPATH . 'wp-admin/includes/image.php' );
			    require_once( ABSPATH . 'wp-admin/includes/file.php' );
			    require_once( ABSPATH . 'wp-admin/includes/media.php' );

		    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
		    wp_update_attachment_metadata( $attach_id, $attach_data );
		
		    $ids[] = $attach_id;
			
		}
	
		if (count($ids) > 0) {
		    update_option('guard_icons_archive_ids', $ids);
		}
		/*else {
		    update_option('guard_icons_archive_ids', 0);
		}*/
		
		}
		
        $ids = get_option('guard_icons_archive_ids');

	    foreach ($ids as $id) {
	
	    if (($id && $id != 0) || !$id) {
		
            $icon_sets = get_option('smile_fonts'); 
			$p = get_post($id);
            
            if (!isset($icon_sets[$p->post_title])) {			
			
			    if (class_exists('AIO_Icon_Manager')) {
			
	                $a = new AIO_Icon_Manager();
 
                    $path 		= realpath(get_attached_file($id));
			        $unzipped 	= $a->zip_flatten( $path , array('\.eot','\.svg','\.ttf','\.woff','\.json','\.css'));
					
				    if($unzipped) {
				        $a->create_config();
						echo "___" . $p->post_title . " Icon Set added___";
			        }
					else {
					    echo "___Error occurred with " . $p->post_title . " icons file unzipping___";
					}
					
			    }
				else {
				    echo "___class AIO_Icon_Manager is not active now___";
				}
            }
			else {
			    echo "___" . $p->post_title . " Icons Set is integrated already, to reinstall remove it via admim area ___";
			}
	    }
        else {
		    echo "___Icon Set has been integrated already, remove DB field guard_alico_archive_id in options table___";
        }

        }		
		
	}
		
	else {
	    echo "___This operation requires Ultimate_VC_Addons Plugin to be activated___";
	}

}


add_action( 'wp_ajax_activate_alico_icons', 'activate_alico_icons' );
add_action( 'wp_ajax_nopriv_activate__alico_icons', 'activate_alico_icons' );



function guard_set_admin_metaboxes() {
    $post_types_fields = array('post', 'page');
    $user = wp_get_current_user();
    foreach ($post_types_fields as $screen_id) {
        $option = get_user_option('metaboxhidden_' . $screen_id);
        if (is_array($option))
            $option = array_diff($option, array('commentstatusdiv'));
        else
            $option = array('wpb_visual_composer', 'postexcerpt', 'trackbacksdiv', 'postcustom', 'slugdiv', 'authordiv');
        $r = update_user_option($user->ID, 'metaboxhidden_' . $screen_id, $option, true);
    }
    $screen_id = 'nav-menus';
    $option = get_user_option('metaboxhidden_' . $screen_id);
    if (is_array($option))
        $option = array_diff($option, array('add-post-type-testimonial', 'add-post-type-service', 'add-post-type-teammate', 'add-post-type-portfolio'));
    else
        $option = array('add-post_format', 'add-product_cat', 'add-product_tag', 'woocommerce_endpoints_nav_link');
    $r = update_user_option($user->ID, 'metaboxhidden_' . $screen_id, $option, true);


    $option = get_user_option('manage' . $screen_id . 'columnshidden');
    if (is_array($option))
        $option = array_diff($option, array('css-classes'));
    else
        $option = array('title-attribute', 'xfn');
    $r = update_user_option($user->ID, 'manage' . $screen_id . 'columnshidden', $option, true);
    if ($r || 1 == 1) echo '___<p><b>'.esc_attr__( 'Post and Menu Screen Settings saved', 'the-guard' ).'</b></p>___'; //else echo "Error occured while Saving Screen Settings";
}	
	
	
?>
