<?php
define( 'WPFRESH5_GOOGLE_FONTS_URL', '//fonts.googleapis.com');

/* Delete / Create content */
function wpfresh5_delete_posttypes( $post_types = array() ) {
	$one_deleted = 0;
	if( empty( $post_types ) )
		return array( 1, 'There are no posts types to delete' );

	foreach( $post_types as $post_type ) {
		$all_posts = wp_count_posts( $post_type ); //Total posts count before operation
		$count_posts = $all_posts->publish + $all_posts->draft;
		if ( $count_posts > 0 ) {
		    $args = array( 'post_type' => $post_type, 'posts_per_page'   => -1 );
		    $posts = get_posts( $args );
		    foreach ($posts as $post) {
		    	$one_deleted = 1;
		        wp_delete_post( $post->ID, true );
		        // echo '<p>borro: '.$post->ID.'</p>';
		    }
		}
	}
	// echo $one_deleted;
	if( $one_deleted )
		return array( 1, 'OK' );
	else
		return array( 0, 'There are no posts to delete' );
}

function wpfresh5_pages_info( $sub = false ) {
	$info = array(
		array(
			'id' => 'about',
			'title' => 'About Us'
		),
		array(
			'id' => 'contact',
			'title' => 'Contact'
		),
		array(
			'id' => 'sitemap',
			'title' => 'Sitemap'
		),
		array(
			'id' => 'privacy',
			'title' => 'Privacy Policy'
		),
		array(
			'id' => 'terms',
			'title' => 'Terms of Use'
		),
		array(
			'id' => 'earnings',
			'title' => 'Disclaimer'
		),
		array(
			'id' => 'amazon',
			'title' => 'Amazon Affiliate Disclaimer'
		),
		array(
			'id' => 'affiliate',
			'title' => 'Affiliate Disclosure'
		),
		array(
			'id' => 'copyright',
			'title' => 'Digital Millennium Copyright Act Notice'
		),
		array(
			'id' => 'antispam',
			'title' => 'Anti Spam Policy'
		),
		array(
			'id' => 'cookiepol',
			'title' => 'Cookie Policy'
		),
		array(
			'id' => 'medical',
			'title' => 'Medical Disclaimer'
		)
	);
	if( !$sub )
		return $info;

	foreach( $info as $el ) {
		if( $sub == $el['id'] )
			return $el;
	}
}

function wpfresh5_create_pages( $pages = array() ) {
	if( empty( $pages ) )
		return array( 1, 'There are no pages to delete' );
	foreach( $pages as $page ) {
		$info = wpfresh5_pages_info( $page );
		if( $page == 'amazon' ) {
			$country = isset( $_POST['wpfresh5_cg_amazoncountry'] ) ? $_POST['wpfresh5_cg_amazoncountry'] : 'us';
			$content = wpfresh5_amazon_disclaimers( $country );
		}
		else
			$content = wpfresh5_clear_file_get( $info['id'] );
		wpfresh5_create_page( $info['title'], $content );
	}

}

function wpfresh5_create_page( $title, $content ) {
	if( null == get_page_by_title( $title ) ) {
	    $page   =   array(
	    'post_type'    => 'page',
	    'post_content' => $content,
	    'post_author'  => 1,
	    'post_status'  => 'publish',
	    'post_title'   => $title,
		);
   	 	wp_insert_post ($page);
	}
}

function wpfresh5_amazon_disclaimers( $country = 'us' ) {
	$site_name = get_bloginfo('name');
	$am_ca = 'The owner of this website is a participant in the Amazon.com.ca, Inc. Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.ca.';
	$am_de = $site_name.  ' ist Teilnehmer des Partnerprogramms von Amazon EU, das zur Bereitstellung eines Mediums für Websites konzipiert wurde, mittels dessen durch die Platzierung von Werbeanzeigen und Links zu Amazon.de, Javari.de, de.BuyVIP.com Werbekostenerstattung verdient werden kann.';
	$am_es = $site_name. ' participa en el Programa de Afiliados de Amazon EU, un programa de publicidad para afiliados diseñado para ofrecer a sitios web un modo de obtener comisiones por publicidad, publicitando e incluyendo enlaces a Amazon.es, es.buyvip.com.';
	$am_fr = $site_name. ' participe au Programme Partenaires d’Amazon EU, un programme d’affiliation conçu pour permettre à des sites de percevoir une rémunération grâce à la création de liens vers Amazon.fr, Javari.fr.';
	$am_it = $site_name. ' partecipa al Programma Affiliazione Amazon EU, un programma di affiliazione che consente ai siti di percepire una commissione pubblicitaria pubblicizzando e fornendo link al sito Amazon.it, it.BuyVIP.com.';
	$am_uk = 'The owner of this website is a participant in the Amazon EU Associates Programme, an affiliate advertising programme designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.co.uk.';
	$am_us = 'The owner of this website is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon properties including, but not limited to, amazon.com, endless.com, myhabit.com, smallparts.com, or amazonwireless.com.';
	$am_in = 'The owner of this website is a participant in the Amazon India Associates Programme, an affiliate advertising programme designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.in.';
	$disclaimers = array(
		'us' => $am_us,
		'ca' => $am_ca,
		'de' => $am_de,
		'es' => $am_es,
		'fr' => $am_fr,
		'uk' => $am_uk,
		'in' => $am_in,
		'it' => $am_it
	);
	return $disclaimers[ $country ];
}
function wpfresh5_clear_file_get( $id ){
    $content = file_get_contents( WPFRESH5_URL.'/lib/pages/'.$id.'.txt' );
    if( !$content )
    	$content = file_get_contents( WPFRESH5_DIR.'/lib/pages/'.$id.'.txt' );

    $content = str_replace( '[site_name]', get_bloginfo('name'), $content );
    $content = str_replace( '[site_url]', get_bloginfo('wpurl'), $content );
    $content = str_replace( '[site_description]', get_bloginfo('description'), $content );
    $content = str_replace( '[admin_email]', get_bloginfo('admin_email'), $content );
    return $content;
}

function wpfresh5_create_blank_pages( $pages_arr, $post_type = 'page' ) {
	if ( empty ( $pages_arr ) )
		return;
	foreach ($pages_arr as $title ) {
		$title = trim( $title );
		if ( !get_page_by_title( $title ) ) {
		    $empty = array(
		        'post_title' => $title,
		        'post_type' =>  $post_type,
		        'post_content' => 'This page is created by WP FreshStart 5 WordPress plugin (remember to edit this text).',
		        'post_status' => 'publish',
		        'post_author' => 1,
		    );
		    wp_insert_post( $empty );
		}
	}
}

/* Cookie Policy */

// TO-DO

/* Categories / Tags */

function wpfresh5_create_categories( $cat_list ) {
	if( empty( $cat_list) )
		return 0;
	$category = explode(',', $cat_list);
	if( empty( $category ) )
		return 0;
	for ($i = 0; $i < count($category); $i++) {
	    if ( 0 == get_cat_ID( 'Uncategorized' ) )
	        wp_create_category( trim( $category[$i] ) );
	    else {
	        $arr = array( 'cat_ID' => get_cat_ID('Uncategorized'), 'cat_name' => trim( $category[$i] ) );
	        wp_insert_category( $arr );
	    }
	}
}

function wpfresh5_create_tags( $tag_list ) {
	if( empty( $tag_list ) )
		return;
	$tags = explode( ',', $tag_list );
	if( empty( $tags ) )
		return 0;
	for ($i = 0; $i < count( $tags ); $i++) {
		$tag = trim( $tags[$i] );
		if( !term_exists( 'fruits', 'post_tag' ) )
			wp_insert_term( $tag, 'post_tag' );
	}
}


// Sample Content

function wpfresh5_sample_content() {
	// ---------- Posts ----------
	// Multiple Paragraphs Post
	$post1 = array( 'post_title' => 'Multiple Paragraph Post', 'post_content' => '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', 'post_status' => 'publish', );

	// Image Post
	$post2 = array( 'post_title' => 'Image Post', 'post_content' => '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><img src="http://hivemindlabs.com/plugin-data/hive.jpg" width="100%" /><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>', 'post_status' => 'publish', );

	// UL and OL post
	$post3 = array( 'post_title' => 'UL and OL Post', 'post_content' => '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><ul><li>First Item</li><li>Second Item</li><li>Third Item</li><li>Fourth Item</li><li>Fifth Item</li></ul><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><ol><li>First Item</li><li>Second Item</li><li>Third Item</li><li>Fourth Item</li><li>Fifth Item</li></ol><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>', 'post_status' => 'publish', );

	// Blockquote post
	$post4 = array( 'post_title' => 'Blockquote Post', 'post_content' => '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><blockquote>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</blockquote><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>', 'post_status' => 'publish', );

	// Links Post
	$post5 = array( 'post_title' => 'Links Post', 'post_content' => '<p>Lorem ipsum dolor sit amet, <a href="#">consectetur adipisicing</a> elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. <a href="#">Duis aute irure</a> dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia <a href="#">deserunt</a> mollit anim id est laborum.</p>', 'post_status' => 'publish', );

	// Links Post
	$post6 = array( 'post_title' => 'Headers Post', 'post_content' => '<h1>This Is An H1 Tag</h1><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><h2>This Is An H2 Tag</h2><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><h3>This Is An H3 Tag</h3><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><h4>This Is An H4 Tag</h4><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><h5>This Is An H5 Tag</h5><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>', 'post_status' => 'publish', );



	// -------- Pages --------
	// Multiple Paragraphs Page
	$page1 = array( 'post_title' => 'Multiple Paragraph Page', 'post_content' => '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', 'post_type' => 'page', 'post_status' => 'publish', );

	// Image Page
	$page2 = array( 'post_title' => 'Image Page', 'post_content' => '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><img src="http://hivemindlabs.com/plugin-data/hive.jpg" width="100%" /><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>', 'post_type' => 'page', 'post_status' => 'publish', );

	// UL and OL Page
	$page3 = array( 'post_title' => 'UL and OL Page', 'post_content' => '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><ul><li>First Item</li><li>Second Item</li><li>Third Item</li><li>Fourth Item</li><li>Fifth Item</li></ul><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><ol><li>First Item</li><li>Second Item</li><li>Third Item</li><li>Fourth Item</li><li>Fifth Item</li></ol><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>', 'post_type' => 'page', 'post_status' => 'publish', );

	// Blockquote Page
	$page4 = array( 'post_title' => 'Blockquote Page', 'post_content' => '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><blockquote>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</blockquote><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>', 'post_type' => 'page', 'post_status' => 'publish', );

	// Links Page
	$page5 = array( 'post_title' => 'Links Page', 'post_content' => '<p>Lorem ipsum dolor sit amet, <a href="#">consectetur adipisicing</a> elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. <a href="#">Duis aute irure</a> dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia <a href="#">deserunt</a> mollit anim id est laborum.</p>', 'post_type' => 'page', 'post_status' => 'publish', );

	// Links Page
	$page6 = array( 'post_title' => 'Headers Page', 'post_content' => '<h1>This Is An H1 Tag</h1><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><h2>This Is An H2 Tag</h2><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><h3>This Is An H3 Tag</h3><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><h4>This Is An H4 Tag</h4><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p><h5>This Is An H5 Tag</h5><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>', 'post_type' => 'page', 'post_status' => 'publish', );

	// Child Page
	$childpage = array( 'post_title' => 'Child Page', 'post_content' => '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', 'post_type' => 'page', 'post_parent' => /*$imagepageid*/0, 'post_status' => 'publish', );

	// Grand Child Page
	$grandchildpage = array( 'post_title' => 'Grandchild Page', 'post_content' => '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', 'post_type' => 'page', 'post_parent' => /*$childpageid*/0, 'post_status' => 'publish', );

	$add_posts_array = array( $post1, $post2, $post3, $post4, $post5, $post6, $page1, $page2, $page3, $page4, $page5, $page6 );
	$remove_posts_array = array( $post1, $post2, $post3, $post4, $post5, $post6, $page1, $page2, $page3, $page4, $page5, $page6, $childpage, $grandchildpage );
	return array( 'add' => $add_posts_array, 'delete' => $remove_posts_array, 'childpage' => $childpage, 'grandchildpage' => $grandchildpage );
}

function wpfresh5_create_sample_content( ) {
	$sample = wpfresh5_sample_content();
	$add_posts_array = $sample['add'];
	$childpage = $sample['childpage'];
	$grandchildpage = $sample['grandchildpage'];
	// Add Posts -------------------------
	global $wpdb;
    // Get content for all posts and pages, then insert posts
    foreach ( $add_posts_array as $post ){
        $post_id = wp_insert_post( $post );
    	add_post_meta( $post_id, 'wpfresh5_samplec', 1, true );
    };

	// Add Child Page
	$page_name = 'Image Page';
	$page_name_id = $wpdb->get_results("SELECT ID FROM " . $wpdb->base_prefix . "posts WHERE post_title = '". $page_name ."'");
    foreach($page_name_id as $page_name_id){
    	$imagepageid = $page_name_id->ID;
    	$childpage['post_parent'] = $imagepageid;
    	$post_id = wp_insert_post( $childpage );
    	add_post_meta( $post_id, 'wpfresh5_samplec', 1, true );
    };

	// Add Grandchild Page
	$page_name = 'Child Page';
	$page_name_id = $wpdb->get_results("SELECT ID FROM " . $wpdb->base_prefix . "posts WHERE post_title = '". $page_name ."'");
    foreach($page_name_id as $page_name_id){
    	$childpageid = $page_name_id->ID;
    	$grandchildpage['post_parent'] = $childpageid;
    	$post_id = wp_insert_post( $grandchildpage );
    	add_post_meta( $post_id, 'wpfresh5_samplec', 1, true );
    };
}

function wpfresh5_delete_sample_content( ) {
	$sample = wpfresh5_sample_content();
	$remove_posts_array = $sample['delete'];
    foreach($remove_posts_array as $array){
        $page_name = $array["post_title"];
		global $wpdb;
        $page_name_id = $wpdb->get_results( "SELECT ID FROM " . $wpdb->base_prefix . "posts WHERE post_title = '". $page_name ."'" );
        foreach($page_name_id as $page_name_id){
        	$page_name_id = $page_name_id->ID;
        	wp_delete_post( $page_name_id, true );
        };
    };
}

// Comments

// Fb Comments

function wpfresh5_fb_comments_footer() {
	$fbcomments = wpfresh5_get_settings( array( 'content', 'comments', 'fb_comments' ) );
	if( $fbcomments ) {
?>
<!-- Facebook Comments Plugin for WordPress: http://peadig.com/wordpress-plugins/facebook-comments/ -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.3";
  // &appId=appid
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<?php }
}

add_action('wp_footer', 'wpfresh5_fb_comments_footer', 100);

add_filter( 'the_content', 'wpfresh5_fb_comments_content', 100 );
function wpfresh5_fb_comments_content( $content ) {
	$fbcomments = wpfresh5_get_settings( array( 'content', 'comments', 'fb_comments' ) );
	if( !$fbcomments || !is_singular( 'post' ) )
		return $content;
	$fb_comments = '<div class="fb-comments" data-href="'.get_permalink().'" data-width="100%" data-numposts="10" data-order-by="social" data-colorscheme="light"></div>';
	return $content.$fb_comments;
}

/* FE Functionality */

// Close comments on the front-end
function wpfresh5_disable_comments( $open, $post_id ) {
	$post_type = get_post_type( $post_id );
	$disabled = wpfresh5_get_comments_disabled();

	if( in_array( $post_type, $disabled ) )
		$open = false;

	$fbcomments = wpfresh5_get_settings( array( 'content', 'comments', 'fb_comments' ) );
	if( $fbcomments )
		$open = false;
	return $open;
}

add_filter('comments_open', 'wpfresh5_disable_comments', 20, 2);
add_filter('pings_open', 'wpfresh5_disable_comments', 20, 2);

function wpfresh5_get_comments_disabled() {
	$disabled = wpfresh5_get_settings( array( 'content', 'comments', 'disable_comments' ) );
	if( empty( $disabled ) )
		return array();
	return wpfresh5_get_array_keys_checked( $disabled );
}

// Lazy-load images

function wpfresh5_prepare_images( $content ) {
	$lazy_load = wpfresh5_get_settings( array( 'content', 'images', 'lazy_load' ) );
	if( !$lazy_load )
		return $content;

	/* No lazy images? */
	if ( strpos( $content, '-image' ) === false ) {
		return $content;
	}

	/* Replace images */
	return preg_replace_callback(
		'/(?P<all>                                                              (?# match the whole img tag )
			<img(?P<before>[^>]*)                                               (?# the opening of the img and some optional attributes )
			(                                                                   (?# match a class attribute followed by some optional ones and the src attribute )
				class=["\'](?P<class1>.*?(?:wp-image-|wp-post-image)[^>"\']*)["\']
				(?P<between1>[^>]*)
				src=["\'](?P<src1>[^>"\']*)["\']
				|                                                               (?# match same as before, but with the src attribute before the class attribute )
				src=["\'](?P<src2>[^>"\']*)["\']
				(?P<between2>[^>]*)
				class=["\'](?P<class2>.*?(?:wp-image-|wp-post-image)[^>"\']*)["\']
			)
			(?P<after>[^>]*)                                                    (?# match any additional optional attributes )
			(?P<closing>\/?)>                                                   (?# match the closing of the img tag with or without a self closing slash )
		)/x',
		'wpfresh5_replace_images',
		$content
	);
}

function wpfresh5_replace_images( $matches ) {
	/* Empty gif */
	$null = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
	// Return unmodified image if the "data skip" attribute was found or the image has already been processed.
	if ( false !== strpos( $matches['all'], 'data-crazy-lazy="exclude"' ) || false !== strpos( $matches['class1'] . $matches['class2'], 'wpfresh5_lazy' ) ) {
		return $matches['all'];
	} else {
        return '<img ' . $matches['before']
               . ' style="display:none" '
               . ' class="wpfresh5_lazy ' . $matches['class1'] . $matches['class2'] . '" src="' . $null . '" '
               . $matches['between1'] . $matches['between2']
               . ' data-src="' . $matches['src1'] . $matches['src2'] . '" '
               . $matches['after']
               . $matches['closing'] . '><noscript>' . $matches['all'] . '</noscript>';
	}
}

add_filter(	'the_content','wpfresh5_prepare_images', 12 );
add_filter(	'post_thumbnail_html',	'wpfresh5_prepare_images' );
add_action(	'wp_enqueue_scripts', 'wpfresh5_lazy_scripts' );

function wpfresh5_lazy_scripts() {
	$lazy_load = wpfresh5_get_settings( array( 'content', 'images', 'lazy_load' ) );
	if( !$lazy_load )
		return;

	/* Globals */
	global $wp_scripts;

	/* Check for jQuery */
	if ( ! empty( $wp_scripts ) && (bool) $wp_scripts->query( 'jquery' ) ) { /* hot fix for buggy wp_script_is() */
		wp_enqueue_script( 'fresh5-unveil.js', WPFRESH5_URL . '/js/front/jquery.unveil.min.js',	array( 'jquery' ), '', true );
	} else {
		wp_enqueue_script( 'fresh5-lazyload.js', WPFRESH5_URL . '/js/front/lazyload.min.js',	array( 'jquery' ), '', true );
	}
}

// Compress jpg

add_filter( 'jpeg_quality', 'wpfresh5_get_jpeg_quality_setting' );
add_filter( 'wp_editor_set_quality', 'wpfresh5_get_jpeg_quality_setting' );

function wpfresh5_get_jpeg_quality_setting() {
	$optimize = wpfresh5_get_settings( array( 'content', 'images', 'optimize' ) );
	if( !$optimize )
		return 90;
	$compression = wpfresh5_get_settings( array( 'content', 'images', 'compression' ) );
	if( $compression )
		return intval( $compression );
	return 90;
}

if ( is_admin() )
	add_action( 'plugins_loaded', 'wpfresh5_exif_init' );

function wpfresh5_exif_init()
{
	$optimize = wpfresh5_get_settings( array( 'content', 'images', 'optimize' ) );
	$exif = wpfresh5_get_settings( array( 'content', 'images', 'exif' ) );
	if( !( $optimize && $exif ) )
		return;

	if (!function_exists('wp_handle_upload'))
		require_once( ABSPATH . 'wp-admin/includes/file.php' );

	add_action('wp_handle_upload', 'wpfresh5_exif_set_extension' );
}

function wpfresh5_exif_set_extension( $array )
{

	if ( empty($array['file']))
		return false;

	$fileInfo = pathinfo( $array['file'] );
	$filePath = $fileInfo['dirname'] . '/'.$fileInfo['basename'];
	switch ( $fileInfo['extension'] ) {
		case 'jpg':
			$array['file'] =  wpfresh5_remove_exif($filePath, 'jpg');
			break;
		case 'png':
			$array['file'] =  wpfresh5_remove_exif($filePath, 'png');
			break;
	}

	return $array;
}

function wpfresh5_remove_exif($imagePath, $type)
{
	if (empty($imagePath) || !is_admin())
		return false;

	if ($type == 'jpg')
		$clearExif = imagecreatefromjpeg($imagePath);
	elseif ($type == 'png')
		$clearExif = imagecreatefrompng($imagePath);
	else
		return $imagePath;

	imagejpeg( $clearExif, $imagePath, wpfresh5_get_jpeg_quality_setting() ) ;
	imagedestroy($clearExif);

	return $imagePath;
}


// Image Watermark

function wpfresh5_add_watermark( $meta, $attachment_id ){
	$watermark = wpfresh5_get_settings( array( 'content', 'images', 'watermark' ) );
	$watermark_url = wpfresh5_get_settings( array( 'content', 'images', 'watermark_url' ) );
	if( !$watermark || empty( $watermark_url ) ) {
		return $meta;
	}
    $option_sizes = array( 'fullsize');
    foreach($option_sizes as $size){ // Cycle trough checked image sizes to crop
        if(isset($meta['sizes'][$size]) || $size == 'fullsize'){ // Check if given size exist

            $watermark_path = $watermark_url;
            $test = getimagesize($watermark_path);

            if($test['mime'] == 'image/png'){
                $stamp = imagecreatefrompng($watermark_path);
            }elseif($test['mime'] == 'image/jpeg'){
                $stamp = imagecreatefromjpeg($watermark_path);
            }

            // Url of processed file
            $file = wp_upload_dir();

            if ($size == 'fullsize') {
                $pos = strrpos($meta['file'], '/');
                $img_name = substr($meta['file'], $pos + 1);

                $file = trailingslashit($file['path']).$img_name;

            }
            else
            	$file = trailingslashit($file['path']).$meta['sizes'][$size]['file'];

            $file_params = getimagesize($file);
            $mime_type = $file_params['mime'];
            $im = wpfresh5_get_image_resource( $file, $mime_type );

            // Set the margins for the stamp and get the height/width of the stamp image
            $marginlr = 30;
            $margintd = 30;
            $stampw = imagesx($stamp);
            $stamph = imagesy($stamp);
            $mainw = imagesx($im);
            $mainh = imagesy($im);
            $watermark_position = 9;
            switch( $watermark_position ){
                case '1':
                    $posx = $marginlr;
                    $posy = $margintd;
                break;
                case '2':
                    $posx = ($mainw - $stampw) / 2;
                    $posy = $margintd;
                break;
                case '3':
                    $posx = $mainw - $stampw - $marginlr;
                    $posy = $margintd;
                break;
                case '4':
                    $posx = $marginlr;
                    $posy = ($mainh - $stamph) / 2;
                break;
                case '5':
                    $posx = ($mainw - $stampw) / 2;
                    $posy = ($mainh - $stamph) / 2;
                break;
                case '6':
                    $posx = $mainw - $stampw - $marginlr;
                    $posy = ($mainh - $stamph) / 2;
                break;
                case '7':
                    $posx = $marginlr;
                    $posy = $mainh - $stamph - $margintd;
                break;
                case '8':
                    $posx = ($mainw - $stampw) / 2;
                    $posy = $mainh - $stamph - $margintd;
                break;
                case '9':
                    $posx = $mainw - $stampw - $marginlr;
                    $posy = $mainh - $stamph - $margintd;
                break;

                default:
                    $posx = $marginlr;
                    $posy = $margintd;
                break;


            }

            // Copy the stamp image onto our photo using the margin offsets and the photo
            // width to calculate positioning of the stamp.
            imagecopy($im, $stamp, $posx, $posy, 0, 0, imagesx($stamp), imagesy($stamp));
            wpfresh5_save_image_file( $im, $mime_type, $file );
            imagedestroy($im);
        }
    }

    return $meta;

}


function wpfresh5_save_image_file($image, $mime_type, $filepath) {
	switch ( $mime_type ) {
		case 'image/jpeg':
			return imagejpeg($image, $filepath, 90);
		case 'image/png':
			return imagepng($image, $filepath);
		case 'image/gif':
			return imagegif($image, $filepath);
		default:
			return false;
	}
}

/**
 * Get image resource accordingly to mimetype
 *
 * @param string $filepath
 * @param string $mime_type
 * @return resource
 */
function wpfresh5_get_image_resource($filepath, $mime_type) {
	switch ( $mime_type ) {
		case 'image/jpeg':
			return imagecreatefromjpeg($filepath);
		case 'image/png':
			$image = imagecreatefrompng($filepath);
			imagealphablending($image, true);
			imagesavealpha($image, true);
			return $image;
		case 'image/gif':
			return imagecreatefromgif($filepath);
		default:
			return false;
	}
}

// if( ! ( array_key_exists( 'post_id', $_REQUEST ) && $_REQUEST['post_id'] == -1) )
add_filter('wp_generate_attachment_metadata', 'wpfresh5_add_watermark', 10, 2 );

// Under Construction

add_action('get_header', 'wpfresh5_maintenance' );
add_action('wpfresh5_before_mm', 'wpfresh5_before_maintenance_mode' );

function wpfresh5_before_maintenance_mode()
{
    // remove jetpack sharing
    remove_filter('the_content', 'sharing_display', 19);
}

function wpfresh5_maintenance()
{
	if( is_admin() )
		return false;
	$is_maintenance = wpfresh5_get_settings( array( 'content', 'underc', 'underc_enabled' ) );
	if( !$is_maintenance )
		return false;

	$text = wpfresh5_get_settings( array( 'content', 'underc', 'underc_text' ) );


    do_action( 'wpfresh5_before_mm');

    // TML Compatibility
    if ( class_exists('Theme_My_Login') ) {
        if (Theme_My_Login::is_tml_page()) {
            return;
        }
    }

    if (/*!(current_user_can('ljmm_view_site') || current_user_can( 'super admin') ) || (isset($_GET['fres4m']) && $_GET['fres4m'] == 'preview') ||*/ !is_user_logged_in() ) {
        wp_die( $text, 'Under Construction' , array( 'response' => 200 ) );
    }
}

// Members only

function wpfresh5_forcelogin() {
	$members_only = wpfresh5_get_settings( array( 'content', 'underc', 'members_only' ) );
	if( !$members_only )
		return false;

  // Exceptions for AJAX, Cron, or WP-CLI requests
  if ( ( defined( 'DOING_AJAX' ) && DOING_AJAX ) || ( defined( 'DOING_CRON' ) && DOING_CRON ) || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
    return;
  }
  // Redirect unauthorized visitors
  if ( !is_user_logged_in() ) {
    // Get URL
    $url  = isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] ? 'https' : 'http';
    $url .= '://' . $_SERVER['HTTP_HOST'];
    // port is prepopulated here sometimes
    if ( strpos( $_SERVER['HTTP_HOST'], ':' ) === FALSE ) {
      $url .= in_array( $_SERVER['SERVER_PORT'], array('80', '443') ) ? '' : ':' . $_SERVER['SERVER_PORT'];
    }
    $url .= $_SERVER['REQUEST_URI'];
    // Apply filters
    $bypass = apply_filters ( 'v_forcelogin_bypass', false );
    $whitelist = apply_filters( 'v_forcelogin_whitelist', array() );
    $redirect_url = apply_filters( 'v_forcelogin_redirect', $url );
    // Redirect visitors
    if ( preg_replace('/\?.*/', '', $url) != preg_replace('/\?.*/', '', wp_login_url()) && !in_array($url, $whitelist) && !$bypass ) {
      wp_safe_redirect( wp_login_url( $redirect_url ), 302 ); exit();
    }
  }
  else {
    // Only allow Multisite users access to their assigned sites
    if ( function_exists('is_multisite') && is_multisite() ) {
      $current_user = wp_get_current_user();
      if ( !is_user_member_of_blog( $current_user->ID ) && !is_super_admin() )
        wp_die( __( "You're not authorized to access this site.", 'wpfresh5' ), get_option('blogname') . ' &rsaquo; ' . __( "Error", 'wpfresh5' ) );
    }
  }
}
add_action('template_redirect', 'wpfresh5_forcelogin');

// Google Fonts

function wpfresh5_get_google_fonts() {
	include_once WPFRESH5_DIR.'/lib/webfonts.php';
	$fonts = $wpfresh5_google_fonts;
	$fonts = json_decode( $fonts );
	// var_dump($fonts);
	$fonts = $fonts->items;
	$font_arr = array();
	foreach( $fonts as $font ) {
		// var_dump($font);
		$name = $font->family;
		$value = $font->family;
		$font_arr[] = array( 'label' => $name, 'value' => $value );
	}
	return $font_arr;
}

function wpfresh5_editor_fontsize_filter( $options ) {
	if (!in_array('fontsizeselect', $options))
		array_unshift( $options, 'fontsizeselect');

	if (!in_array('fontselect', $options))
		array_unshift( $options, 'fontselect');

	return $options;
}

add_filter( 'mce_buttons_2', 'wpfresh5_editor_fontsize_filter', 20);
add_filter( 'tiny_mce_before_init', 'wpfresh5_editor_font_choices' );

function wpfresh5_editor_font_choices( $init ) {

	if (WPFRESH5_WPVERSION < 3.9)
		$findex = 'theme_advanced_fonts';
	else
		$findex = 'font_formats';
// var_dump($init);
    $init[$findex] =
                'Andale Mono=andale mono,times;'.
                'Arial=arial,helvetica,sans-serif;'.
                'Arial Black=arial black,avant garde;'.
                'Book Antiqua=book antiqua,palatino;'.
                'Comic Sans MS=comic sans ms,sans-serif;'.
                'Courier New=courier new,courier;'.
                'Georgia=georgia,palatino;'.
                'Helvetica=helvetica;'.
                'Impact=impact,chicago;'.
                'Tahoma=tahoma,arial,helvetica,sans-serif;'.
                'Terminal=terminal,monaco;'.
                'Times New Roman=times new roman,times;'.
                'Trebuchet MS=trebuchet ms,geneva;'.
                'Verdana=verdana,geneva'.
                '';

        $enable_fonts = wpfresh5_get_settings( array( 'content', 'fonts', 'enable_fonts' ) );
        if( !$enable_fonts )
            return $init;
        $fonts_txt = '';
        for( $i=1; $i<6;$i++ ) {
            $font = wpfresh5_get_settings( array( 'content', 'fonts', 'font'.$i ) );
            if( $font ) {
                // $fonts_txt .= str_replace( ' ', '+', $font).'|';
                 $fonts_txt .= $font.'='.$font.';';
            }
        }
        if( !empty ($fonts_txt ) ) {
        	$fonts_txt_fixed = ';'.substr( $fonts_txt, 0, -1 );
        	$init[$findex] .= $fonts_txt_fixed;
        }

	if (WPFRESH5_WPVERSION < 3.9)
		$init['theme_advanced_font_sizes'] = "10px,11px,12px,13px,14px,15px,16px,17px,18px,19px,20px,21px,22px,23px,24px,25px,26px,27px,28px,29px,30px,32px,48px,54px,60px,72px";
	else
		$init['fontsize_formats'] = "10px 11px 12px 13px 14px 15px 16px 17px 18px 19px 20px 21px 22px 23px 24px 25px 26px 27px 28px 29px 30px 32px 48px 54px 60px 72px";

    return $init;
}

function wpfresh5_add_editor_styles() {
	$enable_fonts = wpfresh5_get_settings( array( 'content', 'fonts', 'enable_fonts' ) );
	if( !$enable_fonts )
	    return;
	$fonts_txt = '';
	for( $i=1; $i<6;$i++ ) {
	    $font = wpfresh5_get_settings( array( 'content', 'fonts', 'font'.$i ) );
	    if( $font )
	        $fonts_txt .= str_replace( ' ', '+', $font).'|';
	}
	$font_url = WPFRESH5_GOOGLE_FONTS_URL.'/css?family='.$fonts_txt;

	if (!empty($font_url))
    	add_editor_style( str_replace( ',', '%2C', $font_url ) );
}
add_action( 'init', 'wpfresh5_add_editor_styles' );

// Placeholder Images

// add tab to media upload window
function wpfresh5_media_upload_tabs_handler($tabs) {
	if( wpfresh5_get_settings( array( 'content', 'images', 'placeholder' ) ) )
		$tabs['wpfresh5pltab'] = __('Placeholder Images', 'wpfresh5');

	return $tabs;
}

add_filter('media_upload_tabs', 'wpfresh5_media_upload_tabs_handler');

function media_upload_wpfresh5pltab_handler() { wp_iframe('media_wpfresh5pltab'); }
add_action('media_upload_wpfresh5pltab', 'media_upload_wpfresh5pltab_handler');


function media_wpfresh5pltab() {
    media_upload_header();
	?>
        <style scope>
            html, body { background: #fff; }
            ::-webkit-input-placeholder { color: #aaa !important; }
            ::-moz-placeholder { color: #aaa !important; }
            :-ms-input-placeholder { color: #aaa !important; }
            [placeholder] { text-overflow: ellipsis; }
        </style>
        <div style="padding:10px 15px 25px">
			<table class="form-table">
	            <tbody>
	            	<tr valign="top">
			        	<th scope="row">Image Width (px)</th>
			        	<td>
			            	<input class="small-text " type="number" value="300" id="wpfresh5-img-width">
			                <!-- <p class="description">Your WP Site Name</p> -->
                    	</td>
		            	<tr valign="top">
				        	<th scope="row">Image Height (px)</th>
				        	<td>
				            	<input class="small-text " type="number" value="200" id="wpfresh5-img-height">
				                <!-- <p class="description">Your WP Site Name</p> -->
	                    	</td>
				    	</tr>
			    	</tr>
			    </tbody>
			</table>
			<br/>
            <p><button type="button" id="wpfresh5-insert-btn" class="button button-primary">Insert Placeholder Image</button></p>
        </div>
		<script>
            jQuery(document).on('click', '#wpfresh5-insert-btn', function() {
            	// alert( 'ahora')
            	var width = jQuery('#wpfresh5-img-width').val();
            	if( !width )
            		width = 300;

            	var height = jQuery('#wpfresh5-img-height').val();
            	if( !height )
            		height = 200;

            	window.parent.send_to_editor('<img src="http://via.placeholder.com/'+width+'x'+height+'" />');
        	    window.parent.tb_remove();
                return false;
            });
        </script>
    <?php
}

/* Cookie Policy */

// HTML Sitemap

// the plugin core
if ( !function_exists( 'wpfreshstart_sitemap_shortcode' ) ) {
	function wpfreshstart_sitemap_shortcode() {

	// ==============================================================================
	// General Variables
	// $options = get_option('wpseosms');
	// $checkOptions = get_option('wpseo_xml');
	$goHtm = '<div>';

	//Hard Coded Styles
	// if( $options['css-disable'] == '' ){
	// 	echo '<link rel="stylesheet" type="text/css" href="'.plugin_dir_url( __FILE__ ) . 'style.css" media="screen" />';
	// }

	// $goHtm .= '<!-- WP SEO HTML Sitemap Plugin Start --><div id="wpseo_sitemap" class="columns_'.$options['columns'].'">';

	// ==============================================================================
	// Authors
	if ( 0 ){
		$goHtm .= '<div id="sitemap_authors"><h3>'. __('Authors') .'</h3>
		<ul>';

		$authEx = implode (", ", get_users( 'orderby=nicename&meta_key=wpseo_excludeauthorsitemap&meta_value=on') );
		$goHtm .= wp_list_authors(array( 'exclude_admin' => false, 'exclude' => $authEx, 'echo' => false ) );
		$goHtm .= '</ul></div>';
	}

	// ==============================================================================
	// Pages
	$pageCheck = get_pages(/*array( 'exclude' => $options['pageID'] )*/);
	if ( ( !empty( $pageCheck ) ) /*&& $checkOptions['post_types-page-not_in_sitemap'] !== true*/ ){
		$pageTitle = get_post_type_object( 'page' );
		$pageTitle = $pageTitle->label;
		$goHtm .= '<div id="sitemap_pages"><h3>'.$pageTitle.'</h3>
		<ul>';
		$pageInc = '';
		$getPages = get_all_page_ids();
		foreach( $getPages as $pageID ) {
			if ( $pageID !== get_the_id()/*$options['pageID']*/ ){
				if ( ( get_post_meta( $pageID, '_yoast_wpseo_meta-robots-noindex', true ) === '1' && get_post_meta( $pageID, '_yoast_wpseo_sitemap-include', true ) !== 'always' ) || ( get_post_meta( $pageID, '_yoast_wpseo_sitemap-include', true ) === 'never' ) ||  ( get_post_meta( $pageID, '_yoast_wpseo_redirect', true ) !== '' ) ) {
					continue;
				}
				if( $pageInc == ''){
					$pageInc = $pageID;
					continue;
				}
				$pageInc .= ', '.$pageID;
			}
		}
		$goHtm .= wp_list_pages( array( 'include' => $pageInc, 'title_li' => '', 'sort_column'  => 'post_title', 'sort_order' => 'ASC', 'echo' => false ) );

		$goHtm .= '</ul></div>';
	}

	// ==============================================================================
	// Posts
	$postsTest = get_posts();
	if ( ( !empty( $postsTest ) ) /*&& $checkOptions['post_types-post-not_in_sitemap'] !== true*/ ){
		$postTitle = get_post_type_object( 'post' );
		$postTitle = $postTitle->label;
		if( get_option( 'show_on_front' ) == 'page' ){
			$postsURL = get_permalink( get_option('page_for_posts') );
			$postTitle = get_the_title( get_option('page_for_posts') );
		}else{
			$postsURL = get_bloginfo('url');
		}
		$goHtm .= '<div id="sitemap_posts"><h3>';
		if ( $postsURL !== '' && $postsURL !== get_permalink( get_the_id() ) ){
			$goHtm .= '<a href="'.  $postsURL .'">'. $postTitle .'</a>';
		}else{
			$goHtm .= $postTitle;
		}
		$goHtm .= '</h3><ul>';
		//Categories
		$cateEx = '';
		$getCate = get_option('wpseo_taxonomy_meta');
		if( !empty($getCate['category']) ){
			foreach( $getCate['category'] as $cateID => $item ) {
				if( ( $item['wpseo_noindex'] == 'noindex' ) || ( $item['wpseo_sitemap_include'] == 'never' ) ){
					if( $cateEx == '' ) {
						$cateEx = $cateID;
					}
					else{
						$cateEx .= ', '.$cateID;
					}
				}
			}
		}
		$cats = get_categories('exclude='.$cateEx);
		foreach ($cats as $cat) {
			$goHtm .= "<li style='margin-top:10px;'><h4><a href='".esc_url( get_term_link( $cat ) )."'>".$cat->cat_name."</a></h4>";
			$goHtm .= "<ul>";
			query_posts('posts_per_page=-1&cat='.$cat->cat_ID);
			while(have_posts()) {
				the_post();
				if ( ( get_post_meta( get_the_ID(), '_yoast_wpseo_meta-robots-noindex', true ) === '1' && get_post_meta( get_the_ID(), '_yoast_wpseo_sitemap-include', true ) !== 'always' ) || ( get_post_meta( get_the_ID(), '_yoast_wpseo_sitemap-include', true ) === 'never' ) ||  ( get_post_meta( get_the_ID(), '_yoast_wpseo_redirect', true ) !== '' ) ) {
					continue;
				}

				$category = get_the_category();
				// Only display a post link once, even if it's in multiple categories
				if ( $category[0]->cat_ID == $cat->cat_ID ) {
					$goHtm .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
				}
			}
			wp_reset_query();
			$goHtm .= "</ul>";
			$goHtm .= "</li>";
		}
		$goHtm .= '</ul></div>';
	}

	// ==============================================================================
	// Custom Post Types

	foreach( get_post_types( array('public' => true) ) as $post_type ) {
		$postsTest = get_posts('post_type='.$post_type);
		if  ( !empty( $postsTest ) ){
			$checkSitemap = 'post_types-'.$post_type.'-not_in_sitemap';
			if ( ( in_array( $post_type, array('post','page','attachment') ) ) || ( $checkOptions[$checkSitemap] === true ) ){
				continue;
			}
			$postType = get_post_type_object( $post_type );
			$postTypeLink = get_post_type_archive_link($postType->name);
			$goHtm .= '<div id="sitemap_'.str_replace( ' ', '', strtolower( $postType->labels->name ) ).'">';
			if( !empty( $postTypeLink ) ){
				$goHtm .= '<h3><a href="'. $postTypeLink .'">'. $postType->labels->name .'</a></h3>';
			}
			else{
				$goHtm .= '<h3>'. $postType->labels->name .'</h3>';
			}
			$goHtm .= '<ul>';
				query_posts('post_type='.$post_type.'&posts_per_page=-1&orderby=title&order=ASC');
			while( have_posts() ) {
				the_post();
				if ( ( get_post_meta( get_the_ID(), '_yoast_wpseo_meta-robots-noindex', true ) === '1' && get_post_meta( get_the_ID(), '_yoast_wpseo_sitemap-include', true ) !== 'always' ) || ( get_post_meta( get_the_ID(), '_yoast_wpseo_sitemap-include', true ) === 'never' ) ||  ( get_post_meta( get_the_ID(), '_yoast_wpseo_redirect', true ) !== '' ) ) {
					continue;
				}
				$goHtm .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
			}
			wp_reset_query();
				$goHtm .= '</ul></div>';
		}
	}

	// ==============================================================================
	// Link To Sitemap
	// if($options['xml-link'] == 'yes'){
		// $goHtm .= '<div id="sitemap_xml"><h3><a rel="alternate" href="'.home_url().'/sitemap_index.xml" target="_blank">Sitemap XML</a></h3></div>';
	// }

	// ==============================================================================
	// Add Credits Link
	// if($options['credits-link'] == 'yes'){
		// $goHtm .= '<div id="credits_link">Sitemap by <a href="http://www.magnatechnology.com/" target="_blank">Magna Technology, LLC</a></div>';
	// }

	$goHtm .= '</div><div class="wpseo_clearRow"></div><!-- WP SEO HTML Sitemap Plugin END -->';

	return $goHtm;
	}
}
//End of Shortcode Function
add_shortcode( 'wpfresh5-sitemap', 'wpfreshstart_sitemap_shortcode');

// Lorem Ipsum
add_action( 'admin_head', 'wpfresh5_add_lorem_button' );

function wpfresh5_add_lorem_button() {
	global $typenow;
	// check user permissions
	if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ) {
		return;
	}
	// verify the post type
	if ( ! in_array( $typenow, array( 'post', 'page' ) ) ) {
		return;
	}
	// check if WYSIWYG is enabled
	if ( get_user_option( 'rich_editing' ) == 'true' ) {
		add_filter( "mce_external_plugins", "wpfresh5_lorem_add_tinymce_plugin" );
		add_filter( 'mce_buttons', 'wpfresh5_lorem_register_button' );
	}
}

function wpfresh5_lorem_add_tinymce_plugin($plugin_array) {
	$plugin_array['wpfresh5_lorem_button'] = WPFRESH5_URL . '/js/button-lorem.js';

	return $plugin_array;
}

function wpfresh5_lorem_register_button( $buttons ) {
	array_push( $buttons, "wpfresh5_lorem_button" );

	return $buttons;
}

// function srizon_lorem_script() {
// 	wp_enqueue_style( 'srizonlorem', WP_PLUGIN_URL . '/srizon-lorem/resources/css/button-lorem.css', null, '1.0' );
// }

// add_action( 'admin_print_scripts-post-new.php', 'srizon_lorem_script', 11 );
// add_action( 'admin_print_scripts-post.php', 'srizon_lorem_script', 11 );

/* Comments */

function wpfresh5_delete_comments() {
	$comments_count = wp_count_comments();
	$all_comments = $comments_count->total_comments;
	$comments = get_comments();
	if($all_comments>0) {
	    foreach ($comments as $comment) {
	        wp_delete_comment($comment->comment_ID, true);
	    }
	    // $delete_items[] = "<li style='color:green;'><span class='bold'>✔ </span> All comments deleted successfully!</li>";
	}
	else{
	    // $delete_items[]= "<li style='color:red;'><span class='bold'>✘ </span>There are no comment(s) to delete.</li>";
	}
}

/* Editor */

function wpfresh5_admin_head()
{
    add_filter('mce_buttons', 'wpfresh5_mce_buttons', 5 );
    add_filter('mce_buttons_2', 'wpfresh5_mce_buttons2', 5 );
}

function wpfresh5_mce_buttons( $buttons )
{
	// var_dump($buttons);
    $settings = wpfresh5_get_plugin_settings();
	$settings = isset( $settings['content']['editor'] ) ? $settings['content']['editor'] : false;
	$justify_enabled = isset( $settings['justify'] ) ? intval( $settings['justify'] ) : 0;
	$underline_enabled = isset( $settings['underline'] ) ? intval( $settings['underline'] ) : 0;
	$strike_enabled = isset( $settings['strike'] ) ? intval( $settings['strike'] ) : 0;
	$background_enabled = isset( $settings['background'] ) ? intval( $settings['background'] ) : 0;

	if( $justify_enabled ) {
	    $position = array_search('alignright', $buttons);

	    if (! is_int($position)) {
	        $buttons =  array_merge($buttons, ['alignjustify']);
	    }

	    $buttons = array_merge(
	        array_slice($buttons, 0, $position + 1),
	        ['alignjustify'],
	        array_slice($buttons, $position + 1)
	    );
	}

	if( $underline_enabled ) {
	    $position = array_search('italic', $buttons);

	    if (! is_int($position)) {
	        $buttons =  array_merge($buttons, ['underline']);
	    }

	    $buttons = array_merge(
	        array_slice($buttons, 0, $position + 1),
	        ['underline'],
	        array_slice($buttons, $position + 1)
	    );
	}

	/*if( $strike_enabled ) {
	    $position = array_search('italic', $buttons);

	    if (! is_int($position)) {
	        $buttons =  array_merge($buttons, ['strikethrough']);
	    }

	    $buttons = array_merge(
	        array_slice($buttons, 0, $position + 1),
	        ['strikethrough'],
	        array_slice($buttons, $position + 1)
	    );
	}*/

/*	if( $background_enabled ) {
	    $position = array_search('forecolor', $buttons);

	    if (! is_int($position)) {
	        $buttons =  array_merge($buttons, ['backcolor']);
	    }

	    $buttons = array_merge(
	        array_slice($buttons, 0, $position + 1),
	        ['backcolor'],
	        array_slice($buttons, $position + 1)
	    );
	}*/
    return $buttons;
}

function wpfresh5_mce_buttons2( $buttons )
{
    $settings = wpfresh5_get_plugin_settings();
	$settings = isset( $settings['content']['editor'] ) ? $settings['content']['editor'] : false;
	$background_enabled = isset( $settings['background'] ) ? intval( $settings['background'] ) : 0;


	if( $background_enabled ) {
	    $position = array_search('forecolor', $buttons);

	    if (! is_int($position)) {
	        $buttons =  array_merge($buttons, ['backcolor']);
	    }

	    $buttons = array_merge(
	        array_slice($buttons, 0, $position + 1),
	        ['backcolor'],
	        array_slice($buttons, $position + 1)
	    );
	}
    return $buttons;
}

add_action( 'admin_head', 'wpfresh5_admin_head', 5 );

?>