AlkantarClanX12

Your IP : 18.116.20.108


Current Path : /proc/self/root/var/softaculous/sitepad/editor/site-data/plugins/sitepad/
Upload File :
Current File : //proc/self/root/var/softaculous/sitepad/editor/site-data/plugins/sitepad/sitepad.php

<?php
/*
Plugin Name: SitePad
Plugin URI: http://sitepad.com/
Description: PageLayer is a WordPress page builder plugin. Its very easy to use and very light on the browser.
Version: 1.0.0
Author: SitePad Team
Author URI: https://sitepad.com/
License: Proprietary
License URI: https://sitepad.com/license
*/

// We need the ABSPATH
if (!defined('ABSPATH')) exit;

if(!function_exists('add_action')){
	echo 'You are not allowed to access this page directly.';
	exit;
}

define('SITEPAD_VERSION', '1.8.8');
define('SITEPAD_DIR', dirname(__FILE__));
define('SITEPAD_FILE', __FILE__);
define('SITEPAD_URL', plugins_url('', SITEPAD_FILE));
define('SITEPAD_CSS', SITEPAD_URL.'/css');
define('SITEPAD_JS', SITEPAD_URL.'/js');
define('SITEPAD_DOCS', 'https://sitepad.com/docs/');
define('SITEPAD_API', empty($sitepad['dev']) ? 'https://api.sitepad.com/' : 'http://127.0.0.1/website/api/sitepad/');
define('SITEPAD_SC_PREFIX', 'pl');

$_tmp_plugins = get_option('active_plugins');

add_action( 'send_headers', 'add_header_sitepad' );
function add_header_sitepad() {
    header('X-Powered-By: SitePad');// Always will be SitePad
}

// Check the license
function sitepad_license_check($force = 0){ // $force applies only to enduser license
	
	global $l, $args, $sitepad;
	
	$sitepad['buy_link'] = empty($sitepad['dev']) ? 'https://softaculous.com/clients?ca=sitepad_enduser_buy' : 'http://127.0.0.1/website/www/clients?ca=sitepad_enduser_buy';
	
	$sitepad['features']['pages'] = 3;
	$sitepad['features']['themes'] = 0;// Theme level 0 = free, 1 = pro, 2 = premium
	
	if(file_exists($sitepad['editor_path'].'/license.php')){
	
		$license = @file_get_contents($sitepad['editor_path'].'/license.php');		
		$license = @trim(sm_decode($license));
		$license = json_decode($license, true);
		
		// Is it an active license
		if(!empty($license['status'])){
			$sitepad['server_license'] = $license;
		}
		
		// Allowed features
		$sitepad['features']['pages'] = 0;
		$sitepad['features']['themes'] = 1;
		
	}
	
	// Any Webuzo license ?
	$webuzo_license = get_option('webuzo_license');
	
	// Check webuzo license
	if(!empty($webuzo_license)){
		
		//$webuzo_license = json_decode($webuzo_license, true);
		
		if((time() - @$webuzo_license['last_update']) >= 86400 || $force){
		
			$resp = wp_remote_get('https://api.webuzo.com/license2.php?license='.$webuzo_license['license'].'&sitepad='.rawurlencode($sitepad['serving_url']));
			
			// Did we get a response ?
			if(is_array($resp)){
				
				// Decode
				$tosave = @json_decode(trim(sm_decode($resp['body'])), true);
				
				// Is it the license ?
				if(!empty($tosave['license'])){
					$tosave['last_update'] = time();
					update_option('webuzo_license', $tosave);
					$webuzo_license = $tosave;
				}
				
			}
			
		}
		
		// Is a premium license ?
		if(!empty($webuzo_license['license']) && !empty($webuzo_license['status']) && !empty($webuzo_license['sitepad_bundle'])){
			
			$sitepad['server_license'] = $webuzo_license;
			
			// Allowed features
			$sitepad['features']['pages'] = 0;
			$sitepad['features']['themes'] = 1;
			
		}
		
	}
	
	// Any Enduser license ?
	$enduser_license = get_option('sitepad_license');
	
	// Update license details as well
	if(!empty($enduser_license)){
		
		$sitepad['license'] = $enduser_license;
		//r_print($sitepad['license']);
		
		if((time() - @$enduser_license['last_update']) >= 86400 || $force){
		
			$resp = wp_remote_get(SITEPAD_API.'license_enduser.php?eu_license='.$enduser_license['license'].'&siteurl='.rawurlencode($sitepad['serving_url']));
			
			// Did we get a response ?
			if(is_array($resp)){
				
				$tosave = json_decode($resp['body'], true);
				
				// Is it the license ?
				if(!empty($tosave['license'])){
					$tosave['last_update'] = time();
					update_option('sitepad_license', $tosave);
					$sitepad['license'] = $tosave;
				}
				
			}
			
		}
		
		// Is a premium license ?
		if(!empty($sitepad['license']) && !empty($sitepad['license']['status'])){
			
			// Allowed features
			$sitepad['features']['pages'] = 0;
			$sitepad['features']['themes'] = 1;
			
		}
		
	}
	
	// Do we have a license ?
	if(is_admin() && is_user_logged_in() && current_user_can('manage_options')){
		
		// If there is a license is it active ?
		if(!empty($sitepad['license']) && empty($sitepad['license']['status']) && $GLOBALS['pagenow'] != 'plans.php'){
			
			// Redirect and exit
			wp_redirect(admin_url('/plans.php'));
			exit;
			
		}
		
	}
	
}

// Checks if we are to update ?
function sitepad_update_check(){
	
	global $l, $args, $sitepad;

	$sql = array();
	$current_version = get_option('sitepad_version');
	$version = (int) str_replace('.', '', $current_version);

	// No update required
	if($current_version == SITEPAD_VERSION){
		return true;
	}
	
	// Is it first run ?
	if($version < 123){
	
		$editor_themes_path = $sitepad['editor_path'].'/site-data/themes';

		// Update template root
		update_option( 'template_root', $editor_themes_path );

	}
	
	// Flush rewite rule
	if($version < 181){
		add_action( 'init', 'flush_rewrite_rules' );
	}

	// Save the new Version
	update_option('sitepad_version', SITEPAD_VERSION);

}

// Disable rest API
add_filter( 'rest_authentication_errors', 'sitepad_disable_rest_api' );
function sitepad_disable_rest_api($access) {
	
	$rest_api = get_option('sitepad_rest_api');
	
	if(empty($rest_api)){
		$error_message = __('The REST API has been disabled on this site.');
		return new WP_Error('rest_disabled', $error_message, array('status' => 401));
	}
	
	return $access;
}

// Automatic Login
add_action('plugins_loaded', 'sitepad_login_admin');
function sitepad_login_admin(){
	
	global $l, $args, $sitepad, $pagelayer;
	
	// Lets fool the Client !
	if(!headers_sent()){
		header('Server: SitePad');
	}
	
	// Load certain variables
	$tmp = (array)get_option('sitepad_vars');
	
	register_theme_directory($sitepad['editor_path'].'/site-data/themes');
	
	// Check if the installed version is outdated
	sitepad_update_check();
	
	// Check which license are you using ?
	sitepad_license_check();
	
	//print_r($GLOBALS['wp_theme_directories']);
	
	foreach($tmp as $k => $v){
		$sitepad[$k] = $v;
	}
	
	//print_r($sitepad);
	
	// Branding related
	define('BRAND_SM', (!empty($sitepad['sm_brand']) ? $sitepad['sm_brand'] : 'SitePad'));
	define('BRAND_SM_URL', (!empty($sitepad['sm_brand_url']) ? $sitepad['sm_brand_url'] : 'https://sitepad.com'));
	define('BRAND_SM_LOGO', (!empty($sitepad['sm_brand_logo']) ? $sitepad['sm_brand_logo'] : sitepad_assets_url().'/images/logo-40.png'));
	define('BRAND_SM_APP', (!empty($sitepad['sm_brand_app']) ? $sitepad['sm_brand_app'] : BRAND_SM.' Website Builder'));
	define('BRAND_SM_EDITOR', (!empty($sitepad['sm_brand_editor']) ? $sitepad['sm_brand_editor'] : BRAND_SM.' Editor'));
	define('BRAND_SM_DEMOS', (!empty($sitepad['sm_brand_demos']) ? $sitepad['sm_brand_demos'] : 'https://demos.sitepad.com/'));
	
	if(strtolower(BRAND_SM) != 'sitepad'){
		define('BRAND_SM_CUSTOM', 1);
	}
	
	$pagelayer->BRAND_TEXT = BRAND_SM;
	$pagelayer->LOGO = BRAND_SM_LOGO;
	
	if(!empty($args['export'])){
		return true;
	}
		
	if(!empty($_REQUEST['sp-login'])){
	
		// Are we logged in WP ?
		if(!is_user_logged_in()){
			
			$key = get_option('sp-login');
			
			if( !empty($key['sp-login']) && md5($key['sp-login']) === $_REQUEST['sp-login'] && 
				(time() - $key['time']) < 60 ){
				
				// Create the session as the admin
				wp_set_auth_cookie(1);
			
			}else{
				
				die('YOUR HACKING ATTEMPT HAS BEEN NOTED. WE WILL NOW TAKE NECESSARY ACTION.');
				
			}
		
		}
		
		// Are we to redirect to editor ?
		if(!empty($_REQUEST['edit'])){
			
			$home = get_page_by_path('home');
			$link = pagelayer_livelink($home->ID);
			
		}else{
			
			$link = admin_url();
			
		}
		
		// Redirect and exit
		wp_redirect($link);
		exit;

	}

}

// Has setup completed
add_action('setup_theme', 'sitepad_setup_check');
function sitepad_setup_check(){

	//////////////////////////////////////////////////
	/* If setup is not done go to show=initial */
	//////////////////////////////////////////////////
	$setup_done = get_option('sp_setup_done');
	
	if(empty($setup_done)){
		
		// Is there an automated call to setup ? 2 calls are needed
		if(!empty($_REQUEST['sitepad_setup_start']) || !empty($_REQUEST['sitepad_setup_final'])){
			$key = get_option('sitepad_setup_key');
			
			// First step
			if($_REQUEST['sitepad_setup_start'] == $key){
				sitepad_setup_start($_REQUEST['theme']);
				die('DONE');
			}
			
			// Final step
			if($_REQUEST['sitepad_setup_final'] == $key){
				sitepad_setup_final();
				die('DONE');
			}
		}
		
		if(is_user_logged_in()){
			
			$allowed_files = array('admin-ajax.php', 'options-general.php', 'options.php', 'setup.php', 'plans.php');
			
			// Ask the user to choose a theme first
			if(!in_array(SP_SERVING_FILE, $allowed_files)){
				
				$to_theme = '';
				$showtheme = optGET('theme');
				if(!empty($showtheme)){
					$to_theme = 'theme='.$showtheme;
				}
				
				wp_redirect(admin_url('setup.php?'.$to_theme));
				exit();
				
			}
		
		// Show Coming Soon
		}elseif(!is_admin() && $GLOBALS['pagenow'] !== 'login.php'){
			
			sitepad_enduser_setup_notice();
			
		}
	
	}
}

// Shows the Coming soon notice
function sitepad_enduser_setup_notice(){
	
	echo '
<html>
<head>
<link href="https://fonts.googleapis.com/css2?family=Khula:wght@300&display=swap" rel="stylesheet"> 
<style>
html,body{
font-family: Khula, Arial;
margin: 0px;
background: #d3e7f9;
}
</style>
</head>
<body>
	<div style="width:97vw; height:97vh; text-align: center; vertical-align:middle">
		<h1>Coming Soon !</h1>
		This website is almost setup. Just a theme has to be chosen from your <a href="'.admin_url('setup.php').'">'.BRAND_SM.' Admin Panel</a>. You can login with your Email or from your control panel.
	</div>
</body>
</html>';
	die();
}

// First step
function sitepad_setup_start($theme_slug){
	
	sitepad_pre_switch_theme($theme_slug);

	delete_option('_site_transient_timeout_theme_roots');
	delete_option('_site_transient_theme_roots');
	delete_option('template_root');
	delete_option('stylesheet_root');
	delete_option('current_theme');
	delete_option('theme_switched');
	
	update_option('sp_setup_selected_theme', $theme_slug);
	
}

// Final step
function sitepad_setup_final(){
	$chosen_theme = get_option('sp_setup_selected_theme');
	switch_theme($chosen_theme);	
}

// Upload Dir
add_filter('upload_dir', 'sitepad_upload_dir', 10, 1);
function sitepad_upload_dir($uploads){
	
	global $sitepad;
	
	//print_r($uploads);
	
	// Handle upload fixes
	$uploads['basedir'] = $sitepad['upload_path'];
	$uploads['baseurl'] = rtrim($sitepad['upload_url'], '/');
	$uploads['url'] = trailingslashit($uploads['baseurl']).trim($uploads['subdir'], '/');
	$uploads['path'] = trailingslashit($uploads['basedir']).trim($uploads['subdir'], '/');
	
	//print_r($uploads);die();
	
	return $uploads;

}

add_action('admin_head', 'sitepad_admin_head');
add_action('wp_head', 'sitepad_admin_head');
function sitepad_admin_head(){
?>
<script type="text/javascript">

// Make $ is jQuery
$ = jQuery;

</script>
<?php
}

// Footer Version
add_filter('update_footer', 'sitepad_admin_footer_version', 10001, 1);
function sitepad_admin_footer_version($text) {
	$text = 'Thank you for using <a href="'.BRAND_SM_URL.'">'.BRAND_SM.'</a>';
	return $text;
}
// Footer
add_filter('admin_footer_text', 'sitepad_admin_footer');
function sitepad_admin_footer($text) {
	return '';
}

// Remove Help Tab
add_filter('contextual_help', 'sitepad_remove_help_tabs', 10001, 3);
function sitepad_remove_help_tabs($old_help, $screen_id, $screen){
	$screen->remove_help_tabs();
	return $old_help;
}

// Disable Emojis
add_action( 'admin_print_styles', 'sitepad_admin_print_styles' );
function sitepad_admin_print_styles() {
	
	global $menu, $submenu;
	
	foreach($menu as $k => $v){
		if(in_array($v[2], ['pagelayer'])){
			unset($menu[$k]);
		}
	}
	
	//unset();
}

// Disable Emojis
add_action( 'init', 'disable_wp_emojicons' );
function disable_wp_emojicons() {

	// All actions related to emojis
	remove_action( 'admin_print_styles', 'print_emoji_styles' );
	remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
	remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
	remove_action( 'wp_print_styles', 'print_emoji_styles' );
	remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
	remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
	remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
	
	// Filter to remove TinyMCE emojis
	//add_filter( 'tiny_mce_plugins', 'disable_emojicons_tinymce' );
	
}

// Months Drop Down in Posts List
add_filter('disable_months_dropdown', 'sitepad_disable_dropdown_months');
function sitepad_disable_dropdown_months(){
	return true;
}

// Disable the screen options
add_filter('screen_options_show_screen', 'sitepad_disable_screen_options');
function sitepad_disable_screen_options(){
	return false;
}

add_filter('page_row_actions', 'sitepad_edit_link', 1000, 2);
add_filter('post_row_actions', 'sitepad_edit_link', 1000, 2);

// Remove actions not required in Posts Lists
function sitepad_edit_link($actions, $post){
	unset($actions['inline hide-if-no-js']);
	unset($actions['pagelayer']);
	return $actions;
}

// Handle edit link of the post type
add_filter('get_edit_post_link', 'sitepad_edit_post_link', 10, 3);
function sitepad_edit_post_link($link, $postID, $context){
	
	$post = get_post($postID);
	
	if(!pagelayer_supported_type($post->post_type)){
		return $link;
	}
	
	return pagelayer_livelink($postID);
	
}

// Remove dashboard widgets
add_action( 'admin_init', 'remove_dashboard_meta' );
function remove_dashboard_meta() {	
	remove_action( 'welcome_panel', 'wp_welcome_panel' );
}

// Always show all columns, because we remove the default cols otherwise
add_filter('hidden_columns', 'sitepad_hidden_columns', 10001, 3);
function sitepad_hidden_columns($hidden, $screen, $use_defaults){
	//r_print($use_defaults);
	return array();
}

// Always show all columns advanced options for nav-menus
add_filter('manage_nav-menus_columns', 'sitepad_manage_nav_menus_columns', 10001);
function sitepad_manage_nav_menus_columns($menus){
	//r_print($menus);
	//return $menus;
	return array();
}

// Disable Avatars
add_filter('pre_option_show_avatars', '__return_true', 10001);

// Filter the capabilities
add_filter('map_meta_cap', 'sitepad_map_meta_cap', 10001, 4);
function sitepad_map_meta_cap($caps, $cap, $user_id, $args){
	
	// Actions which are not allowed for SitePad used in current_user_can() wp-includes/capabilities.php
	$disallowed_actions = array('delete_themes', 'install_themes', 'edit_themes', 'update_themes');
	
	if(in_array($cap, $disallowed_actions)){
		return array('do_not_allow');
	}
	
	return $caps;
}

add_action('wp_mail', 'sitepad_wp_mail', 10, 1);
function sitepad_wp_mail($mail){
	$mail['subject'] = str_replace('WordPress', BRAND_SM, $mail['subject']);
	$mail['subject'] = str_replace('wordpress', strtolower(BRAND_SM), $mail['subject']);
	$mail['message'] = str_replace('WordPress', BRAND_SM, $mail['message']);
	$mail['message'] = str_replace('wordpress', strtolower(BRAND_SM), $mail['message']);
	return $mail;
}

add_action('wp_mail_from', 'sitepad_wp_mail_from', 10, 1);
function sitepad_wp_mail_from($mail_from){	
	$brand = preg_replace('/\s/is', '_', BRAND_SM);
	$mail_from = str_replace('WordPress', $brand, $mail_from);
	$mail_from = str_replace('wordpress', strtolower($brand), $mail_from);
	return $mail_from;
}

add_action('wp_mail_from_name', 'sitepad_wp_mail_from_name', 10, 1);
function sitepad_wp_mail_from_name($mail_from_name){
	$mail_from_name = str_replace('WordPress', BRAND_SM, $mail_from_name);
	$mail_from_name = str_replace('wordpress', strtolower(BRAND_SM), $mail_from_name);
	return $mail_from_name;
}

// Link to clone a post
function sitepad_clone_post_link( $id = 0, $context = 'display' ) {
	if ( ! $post = get_post( $id ) )
		return;
		
	$nonce = wp_create_nonce('pagelayer-options');
	
	if ( 'revision' === $post->post_type )
		$action = '';
	elseif ( 'display' == $context )
		$action = '&amp;action=pagelayer_clone_post&amp;_wpnonce='.$nonce;
	else
		$action = '&action=pagelayer_clone_post&_wpnonce='.$nonce;

	$post_type_object = get_post_type_object( $post->post_type );
	if ( !$post_type_object )
		return;

	if ( !current_user_can( 'edit_post', $post->ID ) )
		return;

	if ( $post_type_object->_edit_link ) {
		$link = admin_url( sprintf( $post_type_object->_edit_link . $action, $post->ID ) );
	} else {
		$link = '';
	}
	
	return apply_filters( 'sitepad_clone_post_link', $link, $post->ID, $context );
}

//Remove Pagelayer Promo
add_action( 'admin_notices', 'remove_pagelayer_show_promo', 0 );
function remove_pagelayer_show_promo(){
    remove_action( 'admin_notices', 'pagelayer_show_promo' );
}

// The publish button handler
add_action('admin_head' , 'sitepad_head_script', 0);
function sitepad_head_script(){
	
	global $l, $sitepad;
	
?>

<div class="modal" tabindex="-1" role="dialog" id="sitepad-reset-modal">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="reset_title">Reset</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<div id="reset_status_txt" style="display: none;">
					<form>
						<input type="radio" name="reset_todo" value="pages"><?php echo __('Reset all Pages');?> <br />
						<input type="radio" name="reset_todo" value="posts"><?php echo __('Reset all Blog Posts');?> <br />
						<input type="radio" name="reset_todo" value="all"><?php echo __('Reset full site');?>
					</form>
				</div>
				<div id="reset_status_txt_conf" style="display: none;">
					<div id="sitepad_reset_txt"></div>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-primary" id="reset_continue" onclick="sitepad_reset_site_continue()">Continue</button>
				<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
			</div>
		</div>
	</div>
</div>

<script>

<?php

echo '

// Reset Site Functions
function sitepad_reset_conf(){
	jQuery("#sitepad-reset-modal").modal();
	jQuery("#reset_status_txt").show();
	jQuery("#reset_status_txt_conf").hide();
	jQuery("#reset_title").html("'.__('Reset').'");
	jQuery("#reset_continue").prop("disabled", false);
}

function sitepad_reset_site_continue(){
	
	if(jQuery("#sitepad_reset_txt").is(":visible")){
		sitepad_reset_site();
		return;
	}
	
	var reset_todo = jQuery("#sitepad-reset-modal input[name=reset_todo]:checked").val();
	
	if(reset_todo == "pages"){
		var raw_reset_txt = "1. '.__('All the Pages will be deleted').' <br /> 2. '.__('Default Pages that exists in the active theme will be recreated').'";
	}
	
	if(reset_todo == "posts"){
		var raw_reset_txt = "1. '.__('All the Blog Posts will be deleted').' <br /> 2. '.__('The Default blog post will be recreated').'";
	}
	
	if(reset_todo == "all"){
		var raw_reset_txt = "1. '.__('All the Pages and Blog Posts will be deleted').' <br /> 2. '.__('You will need to start again by choosing a theme').'";
	}
	
	if(!raw_reset_txt){
		alert("'.__('Please select the appropriate option !').'");
		return true;
	}
	
	var reset_txt = "'.__('The following changes will be performed').' : <br />";
	raw_reset_txt = reset_txt+raw_reset_txt;
	jQuery("#sitepad_reset_txt").html(raw_reset_txt);
	jQuery("#reset_title").html("'.__('Are you sure you want to reset ?').'");
	
	jQuery("#reset_status_txt").hide();
	jQuery("#reset_status_txt_conf").show();
}


// Close the publish progress
function sitepad_reset_conf_close(){
	jQuery("#reset_status_txt").hide();
	jQuery("#reset_status_txt_conf").hide();
	jQuery("#sitepad-reset-prog").hide();
}

var time_left = 6000;
var sitepad_reset_siterecall = false;

function start_timer(){
	sitepad_reset_siterecall = true;
	time_left = time_left - 1000;
	jQuery("#sm-redirect-sec").html((time_left/1000).toFixed(0));
	
	if(time_left < 1000){
		sitepad_reset_siterecall = false;
		time_left = 6000;
		window.location.href = sitepad_setup_url;
	}else{
		setTimeout(function(){ start_timer() }, 1000);
	}
	
}

function sitepad_reset_site(){
	
	if(sitepad_reset_siterecall) return;
	
	var reset_todo = jQuery("#sitepad-reset-modal input[name=reset_todo]:checked").val();
	var ajaxurl = "'.admin_url('admin-ajax.php?').'&action=sitepad_reset_site&reset_todo="+reset_todo+"&sitepad_nonce="+sitepad_ajax_nonce;
	
	var reset_loading_txt = \'<br /><center><img src="'.admin_url('/images/wpspin_light-2x.gif').'" /></center>\';
	jQuery("#sitepad_reset_txt").html(reset_loading_txt);
	jQuery("#reset_continue").prop("disabled", true);
	
	jQuery.ajax({
		url: ajaxurl,
		dataType: "json",
		success: function(data){ 
			if(!("done" in data)){
				jQuery("#reset_status_txt_conf").hide();
				jQuery("#reset_status_txt").show();
				jQuery("#reset_title").html("'.__('Reset').'");
				alert(data["error"]);
			}else{
				jQuery("#sitepad_reset_txt").html(\'<div class="spe-prog-status-txt">'.__('Your site has been reset successfully. Redirecting you in ').' <b><span id="sm-redirect-sec">5</span></b> '.__('Seconds').'.</div>\');
				start_timer();
			}
		},
	});
}

sitepad_setup_url = "'.admin_url('setup.php?').'&";
sitepad_ajax_url = "'.admin_url( 'admin-ajax.php?' ).'&";
sitepad_ajax_nonce = "'.wp_create_nonce('sitepad_ajax').'";

';

?>

</script>

<?php

}

// Disable Comments
add_action('plugins_loaded', 'sitepad_disable_comments');
function sitepad_disable_comments(){
	
	global $l, $args, $sitepad;
	
	$types = get_post_types();
	
	if(get_option('default_comment_status') != 'closed'){
		update_option('default_comment_status', 'closed');
		update_option('default_ping_status', 'closed');
		update_option('default_pingback_flag', 0);
	}
	
	// Disable Comments
	foreach($types as $k => $v){
		remove_post_type_support($k, 'comments');
		remove_post_type_support($k, 'trackbacks');
	}
	
}

// Resets the site as per the given parameter
function sitepad_reset_site_fn($reset_todo = 'all'){
	
	global $pagelayer, $sitepad;
	
	if(empty($reset_todo) || !in_array($reset_todo, array('pages', 'posts', 'all'))){
		return false;
	}
	
	$theme_path = cleanpath(get_stylesheet_directory());
	
	// Delete Pages
	if(empty($_POST['maintain_ids']) && ($reset_todo == 'pages' || $reset_todo == 'all')){
	
		foreach (glob($sitepad['data_path'].'/uploads/screenshots/*') as $file) {
			unlink($file);
		}
	
		// Delete Pagelayer templates
		$args = [
			'post_type' => $pagelayer->builder['name'],
			'posts_per_page' => -1
		];
		
		$query = new WP_Query($args);
		
		foreach($query->posts as $ck => $cv){
			wp_delete_post($cv->ID, true);
		}
		
		$cur_pages = get_pages(array(
						'post_status' => 'publish,draft,trash',
						'posts_per_page' => -1)
					);
		//r_print($cur_pages);
		
		foreach($cur_pages as $ck => $cv){
			wp_delete_post($cv->ID, true);
		}
		
	}
	
	// Delete Posts
	if($reset_todo == 'posts' || $reset_todo == 'all'){
		
		$cur_posts = get_posts(
			array(
				'post_status' => 'publish,draft,trash',
				'posts_per_page' => -1
			)
		);
		
		// Delete all the blog posts
		foreach($cur_posts as $ck => $cv){
			wp_delete_post($cv->ID, true);
		}
		
		if($reset_todo == 'posts'){
			$post_types = array('post' => 'Posts');
		} else {
			$post_types = pagelayer_get_public_post_types();
		}
	
		foreach ( $post_types as $post_type => $label ) {
			$type_taxonomies = get_object_taxonomies( $post_type, 'objects' );
			$taxonomies = wp_filter_object_list( $type_taxonomies, [
				'public' => true,
				'show_in_nav_menus' => true,
			] );
			
			foreach( $taxonomies as $slug => $object ){
				$query_params = [
					'taxonomy' => $object->name,
					'hide_empty' => false,
				];
				$terms = get_terms( $query_params );		
				foreach($terms as $term){
					wp_delete_term($term->term_id,$term->taxonomy);
				}
			}
				
		}
	}
	
	if($reset_todo == 'posts'){
		// Insert Default blog post
		$new_post = array();
		$new_post['post_content'] = 'This is a default blog post. Feel free to delete it.';
		$new_post['post_title'] = 'Default Blog Post';
		$new_post['post_name'] = 'default-post';
		$new_post['post_type'] = 'post';
		$new_post['post_status'] = 'publish';
		
		// Now insert / update the post
		$ret = wp_insert_post($new_post);
	}
	
	// Restore the pages
	if($reset_todo == 'pages'){
		$_POST['create_blog_page'] = 1;
		$theme_slug = basename(get_stylesheet_directory());
		sitepad_switch_theme($theme_slug, wp_get_theme());
	}
		
	if($reset_todo == 'all'){
		if(!empty($sitepad['dev'])){
		
			//Delete Media Library
			$cur_images = get_posts(array(
				'post_type' => 'attachment',
				'posts_per_page' => -1)
			);
						
			foreach($cur_images as $ik => $iv){
				wp_delete_attachment($iv->ID, true);
			}
			
			//Delete Global Fonts
			foreach($pagelayer->css_settings as $k => $params){
				foreach($pagelayer->screens as $sk => $sv){
					$suffix = (!empty($sv) ? '_'.$sv : '');
					$setting = empty($params['key']) ? 'pagelayer_'.$k.'_css' : $params['key'];
					$tmp = $setting.$suffix;
					if(!empty($tmp)){
						delete_option($tmp);
					}
				}
			}
		}
		
		wp_delete_nav_menu('Header Menu');
		delete_option('sp_setup_done');
		update_option('stylesheet', 'sitepad');
		update_option('template', 'sitepad');
		update_option('sp_setup_clear_data', '1');
	}
	
	return true;
	
}

// Print SiteMap data
add_action( 'wp_loaded', 'sitepad_print_sitemap' );
function sitepad_print_sitemap(){
	
	if(sitepad_cur_page() != 'sitemap.xml'){
		return false;
	}
	
	// Get a list of pages
	$wp_pages = get_pages();
	
	$sitemap_todo = array();
	$sitemap_data = get_option('sitepad_sitemap');
	$sitemap_data = json_decode($sitemap_data, true);
	
	$exclude_post = false;
	
	foreach($wp_pages as $pk => $pv){
		
		if(in_array($pv->ID, array(1, 2))){
			continue;
		}
		
		// We want the sitemap only if it is enabled and it is not a blog page and not home page. Homepage we will handle it from publish-cli.php
		if($sitemap_data['enable_sitemap'] == 'on' && ($sitemap_data[$pv->ID]['include'] != 'exclude' || $sitemap_data['sitemap'] != 'manual')){
			
			// If is post blog page then print all posts
			if(get_option('page_for_posts') == $pv->ID){
				$exclude_post = true;
			}
			
			$sitemap_todo[$pv->post_name]['loc'] = get_permalink($pv->ID);
			$sitemap_todo[$pv->post_name]['lastmod'] = date('Y-m-d', strtotime($pv->post_modified));
			
			if(!empty($sitemap_data[$pv->ID]['frequency']) && $sitemap_data['sitemap'] == 'manual'){
				$sitemap_todo[$pv->post_name]['changefreq'] = $sitemap_data[$pv->ID]['frequency'];
			}else{
				if($pv->post_name == 'home'){
					$sitemap_todo[$pv->post_name]['changefreq'] = 'daily';
				}else{
					$sitemap_todo[$pv->post_name]['changefreq'] = 'monthly';
				}
			}
			
			if(!empty($sitemap_data[$pv->ID]['priority']) && $sitemap_data['sitemap'] == 'manual'){
				$sitemap_todo[$pv->post_name]['priority'] = $sitemap_data[$pv->ID]['priority'];
			}else{
				if($pv->post_name == 'home'){
					$sitemap_todo[$pv->post_name]['priority'] = '1.0';
				}else{
					$sitemap_todo[$pv->post_name]['priority'] = '0.8';
				}
			}
			
		}
	}
	
	// Free some memory
	unset($wp_pages);
	
	// Add the blog posts as well
	$wp_posts = get_posts( array( 'numberposts' => -1 ) );
	//r_print($wp_posts);
	
	if($exclude_post){
		foreach($wp_posts as $pk => $pv){
			
			$permalink = get_permalink($pv->ID);
			
			if($sitemap_data['enable_sitemap'] == 'on'){
				
				// We are not using $posts_page because blog post url always have the URL blog/
				$sitemap_todo[$pv->post_name]['loc'] = $permalink;
				$sitemap_todo[$pv->post_name]['lastmod'] = date('Y-m-d', strtotime($pv->post_modified));
				$sitemap_todo[$pv->post_name]['changefreq'] = 'weekly';
				$sitemap_todo[$pv->post_name]['priority'] = '0.6';
				
			}
		}
	}
	
	if($sitemap_data['enable_sitemap'] == 'on'){
		if($sitemap_data['ssl_secured'] == 'on'){
			$sitemap_ssl = $sitemap_data['ssl_secured'];
		}
	}
			
	$sitemap = '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
'; // Do not remove this new line. It is required
			
	$sitemap_url = home_url('/');
	//Replace plain http with https if setting is enabled.
	if(!empty($sitemap_ssl)){				
		$sitemap_url = str_replace('http://', 'https://', $sitemap_url);
	}
	
	// This is for the main site 
	// sitemap_url_tag function declare in site-inc\sitepad_functions.php
	// TODO: varify if need to change lostmod change here
	$sitemap .= sitemap_url_tag($sitemap_url, '', 'always', '1.0');
	
	foreach($sitemap_todo as $sk => $sv){
		if(!empty($sitemap_ssl)){				
			$sv['loc'] = str_replace('http://', 'https://', $sv['loc']);
		}
		$sitemap .= sitemap_url_tag($sv['loc'], $sv['lastmod'], $sv['changefreq'], $sv['priority']);
	}
	
	$sitemap .= '</urlset>';
	
	header('Content-type: text/xml');
	echo $sitemap;
	die();
}

// Show Google Analytics on Pages
add_action('wp_head', 'sitepad_show_google_analytics' , 2);
function sitepad_show_google_analytics(){
	
	$trackingID = get_option('g_analytics_tracking_id');
	
	// We do not have google analytics Tracking ID
	if(empty($trackingID)){
		return true;
	}
	
	$echo_meta = "<script async src='https://www.googletagmanager.com/gtag/js?id=".$trackingID."'></script>
	<script>
		window.dataLayer = window.dataLayer || [];
		function gtag(){dataLayer.push(arguments);}
		gtag('js', new Date());
		gtag('config', '".$trackingID."');
	</script>
	";
	
	echo $echo_meta;
}

add_action('wp_footer', 'sitepad_mailchimp', 99999);
function sitepad_mailchimp(){
	
	global $post;
	
	// If we are in the editor mode we do not need to display this
	if(pagelayer_is_live()){
		return true;
	}
	
	$mcPopUp = get_option('mail_chimp');
	
	// MailChimp not configured
	if(empty($mcPopUp)){
		return true;
	}
	
	if(!empty($mcPopUp['mailchimp_popup'])){
		if(empty($mcPopUp['option']) || (!empty($mcPopUp['option']) && in_array($post->ID, $mcPopUp['selected_page']))){
			echo '<!-- MailChimp Code starts -->'.$mcPopUp['mailchimp_popup'].'<!-- MailChimp Code ends -->';
		}		
	}

	return true;
}

// SMTP setting us
add_action( 'phpmailer_init', 'sitepad_smtp_setting' );
function sitepad_smtp_setting( $phpmailer ) {
	
	$options = get_option('sitepad_smtp_options');
	
	if(empty($options) || empty($options['enable_smtp'])){
		return false;
	}

	$phpmailer->isSMTP();

	if ( !empty($options['encryption']) && 'none' !== $options['encryption']) {
		$phpmailer->SMTPSecure = $options['encryption'];
	}

	// Set the other options
	$phpmailer->Host = $options['smtp_host'];
	$phpmailer->Port = $options['smtp_port'];

	// If we're using smtp auth, set the username & password
	if ( !empty($options['smtp_auth']) ) {
		$phpmailer->SMTPAuth = true;
		$phpmailer->Username = $options['smtp_username'];
		$phpmailer->Password = base64_decode($options['smtp_password']);
	}
	
	//PHPMailer 5.2.10 introduced this option. However, this might cause issues if the server is advertising TLS with an invalid certificate.
	$phpmailer->SMTPAutoTLS = false;

	if(isset( $options['disable_ssl_verification'] ) && false !== $options['disable_ssl_verification']) {
		// Insecure SSL option enabled
		$phpmailer->SMTPOptions = array(
			'ssl' => array(
				'verify_peer'       => false,
				'verify_peer_name'  => false,
				'allow_self_signed' => true,
			),
		);
	}

	//set reasonable timeout
	$phpmailer->Timeout = 10;
}

// Add custom text/textarea attachment field
add_filter('attachment_fields_to_edit', 'sitepad_add_custom_fields_to_attachment', null, 2); 
function sitepad_add_custom_fields_to_attachment( $form_fields, $post ){
	
    $img_source = get_post_meta($post->ID, 'sitepad_img_source', true);
    $download_url = get_post_meta($post->ID, 'sitepad_download_url', true);
    $img_lic = get_post_meta($post->ID, 'sitepad_img_lic', true);
	
    $form_fields['sitepad_img_source'] = array(
        'label' => __('Image Source'),
        'input' => 'text',
        'value' => $img_source,
    );
	 $form_fields['sitepad_download_url'] = array(
        'label' => __('Download Url'),
        'input' => 'text',
        'value' => $download_url,
    );
	 $form_fields['sitepad_img_lic'] = array(
        'label' => __('Image License'),
        'input' => 'text',
        'value' => $img_lic,
    );
	
    return $form_fields;
}
 
// Save custom text/textarea attachment field
add_filter('attachment_fields_to_save', 'sitepad_save_attachment_field', null, 2);
function sitepad_save_attachment_field($post, $attachment){
	
	$keys = array('sitepad_img_source', 'sitepad_download_url', 'sitepad_img_lic');
	
	foreach($keys as $key){
		if( !empty($attachment[$key]) ){  
			update_post_meta($post['ID'], $key, sanitize_text_field($attachment[$key]));  
		}else{
			 delete_post_meta($post['ID'], $key);
		}
	}
	
    return $post;  
}

// Find the page being accessed
function sitepad_cur_page(){
	
	$blog_url = trailingslashit(get_bloginfo('url'));
	
	// Build the Current URL
	$url = (is_ssl() ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	
	if(is_ssl() && preg_match('/^http\:/is', $blog_url)){
		$blog_url = substr_replace($blog_url, 's', 4, 0);
	}
	
	// The relative URL to the Blog URL
	$req = str_replace($blog_url, '', $url);
	$req = str_replace('index.php/', '', $req);
	
	// We dont need the args
	$parts = explode('?', $req, 2);
	$relative = basename($parts[0]);

	// Remove trailing slash
	$relative = rtrim($relative, '/');
	$tmp = explode('/', $relative, 2);
	$page = end($tmp);
	
	//echo 'Page : '.$page.'<br>';
	
	return $page;
	
}

// Site is under development mode
add_action('wp_head', 'sitepad_dev_mode');
function sitepad_dev_mode(){
	$mode = get_option('sitepad_dev_mode');
	
	if(empty($mode) || is_user_logged_in()){
		return;
	}
	
	wp_die('<h1>Under Development</h1><br />Website under development. Please check back later.');
}

add_action( 'customize_register', 'sitepad_customizer_remove_sections', 999);
function sitepad_customizer_remove_sections( $wp_customize ) {
	$wp_customize->remove_section('header_image');
	$wp_customize->remove_panel('kkart'); //Todo: Add when Kkart Complete
	$wp_customize->remove_panel('widgets');
	$wp_customize->remove_section('colors');	
	$wp_customize->remove_section('custom_css');	
}

add_action( 'user_new_form', 'sitepad_add_multiple_roles_ui', 0 );
add_action( 'show_user_profile', 'sitepad_add_multiple_roles_ui', 0 );
add_action( 'edit_user_profile', 'sitepad_add_multiple_roles_ui', 0 );
function sitepad_add_multiple_roles_ui( $user ) {

	$roles = get_editable_roles();

	$user_roles = ! empty( $user->roles ) ? array_intersect( array_values( $user->roles ), array_keys( $roles ) ) : array();

	?>
	<script>
		jQuery(document).ready(function() {
			var row = jQuery('select#role').closest('tr');
			row.html(jQuery('.sitepad-roles-container tr').html());
			jQuery('.sitepad-roles-container').remove();
		});
	</script>
	<div class="sitepad-roles-container">
		<table class="form-table">
			<tr>
				<th>
					<label><?php _e('Roles'); ?></label>
				</th>
				<td>
					<?php
						foreach ( $roles as $role_id => $role_data ) {

							if ( current_user_can( 'promote_users', get_current_user_id() ) ) {
								?>
								<label for="user_role_<?php echo esc_attr( $role_id ); ?>">
									<input type="checkbox" style = "max-width: 1rem;" id="user_role_<?php esc_attr_e( $role_id ); ?>" value="<?php esc_attr_e( $role_id ); ?>" name="sitepad_user_roles[]" <?php echo ( ! empty( $user_roles ) && in_array( $role_id, $user_roles ) ) ? ' checked="checked"' : ''; ?> />
									<?php esc_html_e( translate_user_role( $role_data['name'] ) ); ?>
								</label>
								<br />
								<?php
							} else {
								
								if ( ! empty( $user_roles ) && in_array( $role_id, $user_roles ) ) {
									echo translate_user_role( $role_data['name'] ) . ', ';
								}
							} 
						} 
					?>
					<?php wp_nonce_field( 'sitepad_set_roles', '_sitepad_roles_nonce' ); ?>
				</td>
			</tr>
		</table>
	</div>
	<?php
}

add_action('personal_options_update', 'sitepad_save_multiple_user_roles');
add_action('edit_user_profile_update', 'sitepad_save_multiple_user_roles');
add_action('user_register', 'sitepad_save_multiple_user_roles');
function sitepad_save_multiple_user_roles( $user_id ) {

	// Not allowed to edit user - bail
	if ( ! current_user_can( 'promote_users', $user_id ) || ! wp_verify_nonce( $_POST['_sitepad_roles_nonce'], 'sitepad_set_roles' ) ) {
		return;
	}

	$user = new WP_User( $user_id );

	$roles = get_editable_roles();

	if ( ! empty( $_POST['sitepad_user_roles'] ) ) {

		$new_roles = array_map( 'sanitize_text_field', wp_unslash( $_POST['sitepad_user_roles'] ) );

		// Get rid of any bogus roles
		$new_roles = array_intersect( $new_roles, array_keys( $roles ) );

		$roles_to_remove = array();

		$user_roles = array_intersect( array_values( $user->roles ), array_keys( $roles ) );

		if ( ! $new_roles ) {
			// If there are no roles, delete all of the user's roles
			$roles_to_remove = $user_roles;

		} else {

			$roles_to_remove = array_diff( $user_roles, $new_roles );
		}

		foreach ( $roles_to_remove as $_role ) {

			$user->remove_role( $_role );

		}

		if ( $new_roles ) {

			// Make sure that we don't call $user->add_role() any more than it's necessary
			$_new_roles = array_diff( $new_roles, array_intersect( array_values( $user->roles ), array_keys( $roles ) ) );

			foreach ( $_new_roles as $_role ) {
				$user->add_role( $_role );

			}
		}
	}
}

include_once(SITEPAD_DIR.'/theme.php');
include_once(SITEPAD_DIR.'/pagelayer.php');
include_once(SITEPAD_DIR.'/ajax.php');
include_once(SITEPAD_DIR.'/seo.php');