<?php
if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) {
    die(__("Sorry, but you can't access this page directly.", "cloudfw"));
} 

global $pagenow;

/*
 *	CloudFw check whether the server supports cURL extension
 *
 *	@since 1.0
**/
if ( ! is_support_curl()) {
    echo "Your server doesn't support php cURL extension. You have to activate it to run Positive Theme on your server.";
    exit;
}

/*
 *	CloudFw check whether the upload directories is writable or not
 *
 *	@since 1.0
**/

if (is_admin())
    cloudfw_check_upload_folders();


//////////////////////////////////////////////////////////
//	GOOGLE ANALYTICS CONFIGURATION WITHOUT DATABASE		//
//////////////////////////////////////////////////////////

//define( 'GA_ID', 		'YOUR_GA_ID_HERE' );		 // Google Analytics Username - 	/	if you don't want to store your GA id and password in the database, you can set them here lines.
//define( 'GA_PASS', 	'YOUR_GA_PASSWORD_HERE' );   // Google Password - 				/	And don't forget delete comment slashes (//) where in head of this line and above line.

function parseQueryString($str) {
    $op = array();
    $pairs = explode("&", $str);
    foreach ($pairs as $pair) {
        list($k, $v) = array_map("urldecode", explode("=", $pair));
        $op[$k] = $v;
    }
    return $op;
} 

/*
 *	CloudFw check whether the theme has a new version
 *
 *	@since 1.0
**/
if (is_admin())
	lastupdates_news(TRUE);
	
/*
 *	The Trigger of Save Settings
 *
 *	@since 1.0
**/
if (isset($_POST[PFIX . '_update'])) {
    $form_selector = $_POST['form_selector'];
    if (!empty($form_selector)) {
        $_opt = getCO();
        cloudfw_form_register($form_selector);
    } 
    global $message, $jump_tab, $_id;
    $comeback = $_POST['comeback'];
    
    if (empty($comeback)) {
		
        $ref = $_SERVER['HTTP_REFERER'];
		if ($ref) {
            $ref_result = parseQueryString( $ref );
            $msg_ = isset( $ref_result['m'] ) ? $ref_result['m'] : FALSE;
        	$comeback = str_replace("&m={$msg_}", '', $ref);
		}
		
		if (isset($jump_tab)):
            $comeback_result = parseQueryString( $comeback );
            $d = isset( $comeback_result['jump'] ) ? $comeback_result['jump'] : FALSE;

            if ( $d )
               $comeback = str_replace("&jump={$d}", '', $comeback);
            $comeback .= '&jump='. $jump_tab; 
		endif;
		
		if (isset($_id)):
            $comeback_result = parseQueryString( $comeback );
            $d = isset( $comeback_result['_id'] ) ? $comeback_result['_id'] : FALSE;

            if ( $d )
               $comeback = str_replace("&id={$d}", '', $comeback);
            $comeback .= '&id='. $jump_tab; 
		endif;
		
    } 
    else
        $comeback = admin_url($comeback);
    
    if (!$message) {
        wp_redirect($comeback . '&m=1000');
    } 
    else {
        wp_redirect($comeback . '&m=' . $message);
    }
    
    exit;
    
}

/*
 *	CloudFw Quick Actions
 *
 *	@since 1.0
**/
if (isset($_GET['q'])) {
    require_once(TMP_ADMIN_PATH . '/inc/fn.q.process.php');
}


/*
 *	Register CloudFw Menus For WP Admin
 *
 *	@since 1.0
**/
function cloudfw_setup_menu(){
    global $theme_setting_slug, $slider_slug, $theme_doc_slug, $_opt;
	$last_version = is_need_update();

    $who_can_see =  get_cOption('framework', 'who_can_see');
    $menu_title =  get_cOption('framework', 'title');
    

    if ( $who_can_see == get_current_user_id() || $who_can_see == 0 || !isset($who_can_see ) ) {
        
        add_menu_page($menu_title . ' - ' . __('Settings', 'cloudfw') . ' - CloudFW', $menu_title . _isso($last_version, '<span class="update-plugins cloudfw-notify"><span class="plugin-count">'.$last_version.'</span></span>'), 'administrator', $theme_setting_slug, 'cloudfw_setup_setting', '', 701);
    }
    if ( current_user_can('administrator') ) {
        add_menu_page($menu_title . ' - Slider Manager - CloudFW', __("Slider Manager", "cloudfw"), 'administrator', $slider_slug, 'cloudfw_setup_slider', '', 702);        
    }
    
}
add_action('admin_menu', 'cloudfw_setup_menu');


/*
 *	Set CloudFW Panel Scheme
 *
 *	@since 1.0
**/
function cloudfw_setup_setting(){
    global $_opt, $_params, $theme_setting_slug, $nav_pages;
    
    $tab    = isset($_GET['tab']) ? $_GET['tab'] : NULL;
    $lastID = get_option("cloud_created_att_page");
	$map 	= cloudfw_get_schemes('theme');
    
		

	foreach ($map as $page_number => $page):
		if ($page['type'] == 'page'){
			if (!$page['page'])
				$page['page'] = 'dashboard';
				
			$nav_pages[$page_number] = $page[$page['page']];
			if ( $tab == $nav_pages[$page_number]['page_slug'] )
				$current_page_number = $page_number;
		}
	endforeach;
	
	//echo $current_page_number;
	
	$current_page = $map[$current_page_number];
	$current_page_data = $current_page[$current_page['page']];
	$the_data = $current_page['data'];
	
	require(TMP_ADMIN_PATH . '/inc/theme_settings_render.php');

}

/*
 *	Set CloudFW Panel Scheme
 *
 *	@since 1.0
**/
function cloudfw_setup_slider(){
    global $_opt, $_params, $theme_setting_slug, $nav_pages;
	
    $id     = $_GET['id'];
    $lastID = get_option("cloud_created_att_page");
    
    if (!isset($id)):
        require(TMP_ADMIN_PATH . '/inc/theme_sliders.php');
    else:

		
		$cloudfw_sliders = cloudfw_sliders();
        $type = cloudfw_get_slider_type($id);
		
		if (file_exists(TMP_ADMIN_PATH . "/inc/core/core.slider.items.php"))
			require(TMP_ADMIN_PATH . "/inc/core/core.slider.items.php");
		else
			exit ('File Cannot Found:'. TMP_ADMIN_PATH . "/inc/core/core.slider.items.php");
			
    endif;
}

/*
 *	Load JS Files For Admin Panel
 *
 *	@since 1.0
**/
add_action('admin_print_scripts', 'cloudfw_admmin_scripts');
function cloudfw_admmin_scripts(){
    global $theme_setting_slug, $slider_slug;
    
    if (is_admin()) {
        wp_enqueue_script('cloudfw-ui', TMP_ADMIN . '/js/ui.js', array(
            'jquery',
            'jquery-ui-core',
            'jquery-ui-tabs',
            'jquery-ui-sortable',
            'jquery-ui-draggable',
            'jquery-ui-droppable',
            'jquery-ui-selectable',
            'jquery-ui-dialog'
        ), '1.8.7');
        
        if (get_bloginfo('version') >= 3.1)
            wp_enqueue_script('cloudfw-ui-slider', TMP_ADMIN . '/js/ui_187.js');
		else
            wp_enqueue_script('cloudfw-ui-slider', TMP_ADMIN . '/js/ui_173.js');
		
        wp_enqueue_script('cloudfw-fg', TMP_ADMIN . '/js/fg/fg.menu.js', array('jquery'), '1.0.0');
        
        wp_enqueue_script('cloudfw-script', TMP_ADMIN . '/js/script.js');
        wp_enqueue_script('media-upload');
        wp_enqueue_script('thickbox');
        
        wp_enqueue_script('cloudfw-picker', TMP_ADMIN . '/js/colorpicker/js/colorpicker.js', array('jquery'), '1.0.0');
        wp_enqueue_script('cloudfw-picker-eye', TMP_ADMIN . '/js/colorpicker/js/eye.js', array('jquery'), '1.0.0');
        wp_enqueue_script('cloudfw-picker-utils', TMP_ADMIN . '/js/colorpicker/js/utils.js', array('jquery'), '1.0.0');
        wp_enqueue_script('cloudfw-fileinput', TMP_ADMIN . '/js/fileinput.js', array('jquery'), '1.0.0');
        wp_enqueue_script('cloudfw-fileuploader', TMP_ADMIN . '/js/fileuploader.js', array('jquery'), '1.0.0');
        
        if (is_theme_setting_page()) {
            wp_enqueue_script('cloudfw-shortcodes-script', TMP_ADMIN . '/js/shortcodes_tinymce.js', array(
                'jquery'
            ), '1.0.0');
        }
        
        if (is_theme_setting_page('menu')) {
            wp_enqueue_script('cloudfw-nav-menu', TMP_ADMIN . '/js/nav_menu.js', array(
                'jquery'
            ), '1.0.0');
        }
        
    }
    
}

/*
 *	Load CSS Files For Admin Panel
 *
 *	@since 1.0
**/
add_action('admin_print_styles', 'cloudfw_admin_styles');
function cloudfw_admin_styles()
{
    wp_enqueue_style('thickbox');
    if (is_theme_setting_page() || is_theme_setting_page("menu"))
        wp_enqueue_style('cloudfw-main-style', TMP_ADMIN . '/style.admin.css', false, '1.0.0', 'screen');
    wp_enqueue_style('cloudfw-colorpicker-style', TMP_ADMIN . '/js/colorpicker/css/colorpicker.css', false, '1.0.0', 'screen');
    wp_enqueue_style('cloudfw-fg', TMP_ADMIN . '/js/fg/fg.menu.css', false, '1.0.0', 'screen');
}


/*
 *	CloudFw Installing Actions
 *
 *	@since 1.0
**/
function cloudfw_installer()
{
    global $theme_setting_slug;
    $_already_installed = get_option(PFIX . '_already_installed');
    
    # Create The System Page   
    $sys_page_1_init['post_title']   = '[System Page] - Don\'t Delete This Page';
    $sys_page_1_init['post_content'] = 'Important - Don\'t Delete This Page';
    $sys_page_1_init['post_status']  = 'publish';
    $sys_page_1_init['post_author']  = 1;
    $sys_page_1_init['post_type']    = 'page';
    
    $sys_page_1 = cloudfw_create_a_page($sys_page_1_init);
    if ($sys_page_1 !== false) {
        update_option('cloud_created_att_page', $sys_page_1["id"]);
    } //$sys_page_1 !== false
    
    /*if (!$_already_installed) {*/
		if (file_exists(TMP_ADMIN_PATH . "/inc/core/core.installation.php"))
			require(TMP_ADMIN_PATH . "/inc/core/core.installation.php");
		else {
			echo 'File Cannot Found:'. TMP_ADMIN_PATH . '/inc/core/core.installation.php'; 
			exit;
		}
			
   /* } //$is_first_install == false*/
    
    wp_redirect(admin_url('admin.php?page=' . $theme_setting_slug . '&w=cloudfwActivated'));
	//exit;

}

if ( !get_option(PFIX . '_already_installed') ) {
    cloudfw_installer();
}

/*
 *	CloudFw Uninstalling Actions
 *
 *	@since 1.0
**/
add_action('switch_theme', 'cloudfw_uninstalling');
function cloudfw_uninstalling(){
    wp_clear_scheduled_hook('remove_cache_files');
    $array_created_pages = get_option('cloud_created_att_page');
    
    if ($array_created_pages && !is_array($array_created_pages)) {
        wp_delete_post($array_created_pages, true);
    } 
    elseif ($array_created_pages && is_array($array_created_pages)) {
        foreach ((array) $array_created_pages as $array_created_pages__) {
            wp_delete_post($array_created_pages__, true);
        } 
    }
    delete_option('cloud_created_att_page');
}

/*
 *	CloudFw Register Custom Post Types & Taxonomies
 *
 *	@since 1.0
**/
add_action('init', 'cloudfw_custom_types', 1);
function cloudfw_custom_types() {
	
    register_post_type('portfolio', array(
        'label' => __('Portfolio Post', 'cloudfw'),
        'public' => true,
        'show_ui' => true,
        'rewrite' => true,
        'query_var' => 'portfolio',
        //'capability_type' => 'post',
        'supports' => array(
            'title',
            'editor',
            'thumbnail'
        ),
        'rewrite' => true,
        'menu_position' => 29,
        'hierarchical' => false,
        'labels' => array(
            'name' => __('Portfolio', 'cloudfw'),
            'singular_name' => __('Portfolio', 'cloudfw'),
            'add_new' => __('Add New', 'cloudfw'),
            'add_new_item' => __('Add New Portfolio Post', 'cloudfw'),
            'edit' => __('Edit Portolio Post', 'cloudfw'),
            'edit_item' => __('Edit Portolio Post', 'cloudfw'),
            'new_item' => __('New Portolio Post', 'cloudfw'),
            'view' => __('View The Post', 'cloudfw'),
            'view_item' => __('View The Portolio Post', 'cloudfw'),
            'not_found' => __('There Is No Any Portolio Post', 'cloudfw'),
            'not_found_in_trash' => __('There Is No Any Portolio Post In Trash', 'cloudfw')
        )
    )); // register portfolio
	
    $portfolio_category_labels = array(
        'name' => __('Categories', 'cloudfw'),
        'singular_name' => 'cat-portfolio',
        'search_items' => __('Search Category', 'cloudfw'),
        'all_items' => __('All Categories', 'cloudfw'),
        'parent_item' => __('Parent Category', 'cloudfw'),
        'parent_item_colon' => __('Parent Category', 'cloudfw'),
        'edit_item' => __('Edit Category', 'cloudfw'),
        'update_item' => __('Update Category', 'cloudfw'),
        'add_new_item' => __('Add New Category', 'cloudfw'),
        'new_item_name' => __('New Category Name', 'cloudfw'),
        'menu_name' => __('Categories', 'cloudfw')
    );
    
    register_taxonomy('cat-portfolio', array(
        'portfolio'
    ), array(
        'hierarchical' => true,
        'labels' => $portfolio_category_labels,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => array(
            'slug' => 'cat-portfolio'
        )
    )); // regsiter taxonomy
}

/*
 *	Menu Icons On Admin Panel
 *
 *	@since 1.0
**/
add_action('admin_head', 'cloudfw_admin_icons');
function cloudfw_admin_icons(){
?> <style type="text/css" media="screen">
   		#toplevel_page_CloudFW .wp-menu-image a img,
		#toplevel_page_CloudFW_Slider .wp-menu-image a img{
			display:none !important;
        }
   
        #toplevel_page_CloudFW .wp-menu-image {
            background: url('<?php echo TMP_ADMIN_SRC; ?>/cloud_icons/cloud.png') no-repeat -2px -2px !important;
        }
		#toplevel_page_CloudFW:hover .wp-menu-image, #toplevel_page_CloudFW.current .wp-menu-image {
            background-position:-2px -34px !important;
        }
		#menu-posts-slider .wp-menu-image,
		#toplevel_page_CloudFW_Slider .wp-menu-image {
            background: url('<?php echo TMP_ADMIN_SRC; ?>/cloud_icons/monitor_.png') no-repeat -2px -2px !important;
        }
        #menu-posts-slider:hover .wp-menu-image, #menu-posts-slider.wp-menu-open .wp-menu-image,
		#toplevel_page_CloudFW_Slider.current .wp-menu-image,
        #toplevel_page_CloudFW_Slider:hover .wp-menu-image, #toplevel_page_CloudFW_Slider.wp-menu-open .wp-menu-image {
            background-position:-2px -34px !important;
        }
		#menu-posts-portfolio .wp-menu-image {
            background: url('<?php echo TMP_ADMIN_SRC; ?>/cloud_icons/portfolio_.png') no-repeat -2px -2px !important;
        }
		#menu-posts-portfolio:hover .wp-menu-image, #menu-posts-portfolio.wp-menu-open .wp-menu-image,
		#toplevel_page_CloudFW_Slider:hover .wp-menu-image, #toplevel_page_CloudFW_Slider.wp-menu-open .wp-menu-image {
            background-position:-2px -34px !important;
        }
		#favorite-actions {
			min-width: 200px !important;
		}
    </style>
<?php
}

/*
 *	CloudFw JavaScript Definitions
 *
 *	@since 1.0
**/
add_action('admin_head', 'cloudfw_admin_path');
function cloudfw_admin_path(){
    echo '
        <meta name="_wpnonce" content="' .  wp_create_nonce() . '" />
   		<meta name="cloudfw_nonce" content="' .  wp_create_nonce('cloudfw') . '" />
        <meta name="tmpurl" content="' . TMP_ADMIN . '" />
   		<meta name="pfix" content="' . PFIX . '" />
   		<meta name="textSending" content="' . __('Saving...', 'cloudfw') . '" />
   		<meta name="textSaved" content="' . __('Saved', 'cloudfw') . '" />
	';
    global $blog_id, $current_site;
    
    //$image_path_exploded = explode($_SERVER['SERVER_NAME'], $src);
    $image_path = $_SERVER['DOCUMENT_ROOT'];
    if (isset($image_path_exploded[1]))
         $image_path .= $image_path_exploded[1];
    
    echo '
       <meta name="cloudfw_multisite" content="', (defined('MULTISITE')) && (MULTISITE == true) ? TRUE : FALSE, '" />
       <meta name="cloudfw_image_path" content="' . $image_path . '" />
       <meta name="cloudfw_blogid" content="' . $blog_id . '" />
   ';
}

/*
 *	CloudFw Favorite Actions
 *
 *	@since 1.0
**/
add_filter('favorite_actions', 'cloudfw_custom_favorites');
function cloudfw_custom_favorites($actions)
{
    global $slider_slug, $theme_setting_slug, $nav_pages;
    
    //$actions = NULL;
    $actions["admin.php?page=" . $theme_setting_slug] = array(
        '&bull; CloudFW',
        'unfiltered_html'
    );
    $actions["admin.php?page=" . $slider_slug]        = array(
        '&bull; ' . __('Slider Management', 'cloudfw') . '',
        'unfiltered_html'
    );
    
    if ($nav_pages) {
        foreach ($nav_pages as $nav_page) {
            $actions["admin.php?page=" . $theme_setting_slug . "&amp;tab=" . $nav_page["page_slug"] . ""] = array(
                '&mdash; ' . ucwords($nav_page["page_title"]),
                'unfiltered_html'
            );
            
        } //$nav_pages as $nav_page
        
    } //$nav_pages
    
    ksort($actions);
    
    return $actions;
}

/*
 *	CloudFw Quick Tags
 *
 *	@since 1.0
**/
function cloudfw_add_quicktags(){
    require(TEMPLATEPATH . '/cloudfw/inc/fn.quicktags.php');
}
if (is_theme_setting_page('editor'))
    add_filter('admin_footer', 'cloudfw_add_quicktags');


/*
 *	CloudFw Clean Old Cache Files Every 3 Days
 *
 *	@since 1.0
**/
add_action('remove_cache_files', 'remove_old_cache_files');
wp_schedule_single_event(time() + 259200, 'remove_cache_files'); //  259200 = 3 Days, it runs every 3 days
//date("Y-m-d H:i:s",wp_next_scheduled( 'remove_cache_files' ));


/*
 *	Show A Message Function If The Theme Has A New Update
 *
 *	@since 1.0
**/
if (is_admin()) {
    add_action( 'network_admin_notices', 'cloudfw_update_theme_message', 4 );
    add_action( 'admin_notices', 'cloudfw_update_theme_message', 4 );
}
  
    
function cloudfw_update_theme_message(){


    if ($the_version = is_need_update()){
        printf ("<div id=\"version-message\" class='cloudfw-update-messages updated'>%s</div>",
            sprintf ("<div style='padding:15px;'>%s</div>", 
                sprintf ("".__("There is a new update for the theme. (version: %s)","cloudfw")." | <a target='_new' href='http://go.cloudfw.net/?theme=positive'>".__('View Details','cloudfw')."</a> <a style='float:right;' href='javascript:void(0);' onclick='cloudfw_dismiss_update_notification();'>".__("Dismiss",'cloudfw')."</a>",$the_version)
                 
            )
        
        );
        
?>
        
<script type="text/javascript">
        
        function cloudfw_dismiss_update_notification() {
            var url = url = jQuery("meta[name=tmpurl]").attr('content');
            
            jQuery("#version-message").slideUp();
            
            jQuery.ajax({
              type: 'POST',
              url: url + '/ajax/lastupdates.php',
              data: {x: 'dissmiss', version:'<?php echo $the_version ?>', nonce: '<?php echo wp_create_nonce('cloudfw');?>'},
            });
            
            jQuery(document).trigger('click');
            jQuery(document).trigger('destroyTheFG');
            cloudfw_get_icon_list_close();
        }
        
</script>
        
<?php
    }
}	
