Link to home
Start Free TrialLog in
Avatar of jonathanduane2010
jonathanduane2010

asked on

getting parse error when trying to open my website

Hi Guys,

I am having an issue with opening my website

i get the following line

http://lynx.radiocompetitions.net/

basically i tried to update the the theme, i also made a backup and when i returned to the backup the same keeps happening

Parse error: syntax error, unexpected '{' in /home/zenra937/public_html/lynx/wp-content/themes/blackfyre/themeOptions/functions.php on line 1

here is the functions.php

<?php
//translatable theme
load_theme_textdomain( 'blackfyre', get_template_directory() . '/langs');
?>
<?php

/*include important files*/
require_once ('themeOptions/functions.php');
require_once ('themeOptions/rating.php');
require_once ( 'theme-functions/page-templates.php' );
require_once ('post_templates.php');
require_once ('bootstrap-carousel.php');
require_once ('widgets/rating/popular-widget.php');
require_once ('widgets/latest_twitter/latest_twitter_widget.php');
require_once ('addons/smartmetabox/SmartMetaBox.php');
require_once ('addons/icon_addon/icon_addon.php' );
require_once ('addons/pricetable/pricetable.php');
require_once ('addons/heart/love/heart-love.php');
require_once ('addons/clan-wars/wp-clanwars.php');
require_once ('addons/multiple-post-thumbnails/multi-post-thumbnails.php');
require_once ('addons/slider/acf.php');
require_once ('addons/slider/acf-repeater/repeater.php');
require_once ('addons/image-parallax-for-vc/vc-row-parallax.php');
require_once ('addons/google-fonts/google-fonts.php');
require_once ('post_templates.php');
require_once ('js_composer/js_composer.php');
require_once ('functions_lj.php');
require_once ( ABSPATH . 'wp-admin/includes/plugin.php');
require_once dirname( __FILE__ ) . '/pluginactivation.php';


/* Custom code goes below this line. */


add_action( 'after_setup_theme', 'blackfyre_theme_setup' );

function blackfyre_theme_setup() {
    /* Add filters, actions, and theme-supported features. */

    /*****ACTIONS*****/

    /*menu*/
    add_action( 'admin_menu', 'blackfyre_create_menu' );
    add_action( 'wp_update_nav_menu_item', 'blackfyre_nav_update',10, 3);
    add_action( 'init', 'blackfyre_register_my_menus' );
	add_action( 'admin_menu', 'skywarrior_remove_menus' );

    /*styles*/
    add_action( 'wp_enqueue_scripts', 'blackfyre_style' );
    add_action( 'wp_enqueue_scripts', 'blackfyre_fonts' );
    add_action( 'wp_enqueue_scripts', 'blackfyre_external_styles' );
    add_action( 'admin_enqueue_scripts', 'blackfyre_styles_admin' );


    /*scripts*/
    add_action( 'wp_enqueue_scripts', 'blackfyre_my_scripts' );
    add_action( 'admin_enqueue_scripts', 'blackfyre_scripts_admin' );

    /*plugin activation*/
    add_action( 'tgmpa_register', 'blackfyre_register_required_plugins' );

    /*custom post type*/
    add_action( 'init', 'blackfyre_matches_register' );
    add_action( 'admin_menu', 'blackfyre_remove_matches_menu' );
    add_action( 'init', 'blackfyre_clan_create_post_type' );
    add_action( 'delete_post', 'blackfyre_onclan_delete' );
    add_action( 'publish_clan', 'blackfyre_onclan_publish' );

    /*metaboxes*/
    add_action( 'save_post', 'blackfyre_saving_my_data' );

    /*buffering*/
    add_action( 'init', 'blackfyre_do_output_buffer' );

    /*comments*/
    add_action( 'comment_post', 'blackfyre_ajaxify_comments',20, 2 );

    /*slider*/
    add_action( 'manage_slider_posts_custom_column', 'blackfyre_custom_slider_column', 10, 2 );
    add_action( 'init', 'blackfyre_register_slider' );
    add_action( 'save_post', 'blackfyre_save_slider_info' );

    /*sessions*/
    add_action( 'init', 'blackfyre_myStartSession', 1 );
    add_action( 'wp_logout', 'blackfyre_myEndSession' );
    add_action( 'wp_login', 'blackfyre_myEndSession' );

    /*user registration countries*/
    add_action( 'blackfyre_registration_clist', 'blackfyre_registration_country_list' );

    /*buddypress*/
    add_action( 'wp', 'blackfyre_remove_profile_subnav', 2 );
    add_action( 'bp_setup_nav', 'blackfyre_mb_profile_menu_tabs', 201 );
    remove_action( 'bp_init', 'bp_core_wpsignup_redirect');
	add_action( 'wp_before_admin_bar_render', 'skywarrior_bpfr_admin_bar_render' );
	add_action( 'wp_ajax_addremove_friend', 'skywarrior_bp_legacy_theme_ajax_addremove_friend',1 );
	add_action( 'wp_ajax_nopriv_addremove_friend', 'skywarrior_bp_legacy_theme_ajax_addremove_friend',1 );

    /*pricetables*/
    add_action( 'manage_pricetable_posts_custom_column', 'blackfyre_pricetable_custom_column');
    add_action( 'init', 'blackfyre_pricetable_register' );

    /*ajax calls*/
    add_action( 'wp_ajax_update_user_profile_pic', 'blackfyre_update_user_profile_pic_callback' );
    add_action( 'wp_ajax_update_user_clan_bg', 'blackfyre_update_user_clan_bg_callback' );
    add_action( 'wp_ajax_update_page_bg', 'blackfyre_update_page_bg_callback' );
    add_action( 'wp_ajax_update_user_profile_bg', 'blackfyre_update_user_profile_bg_callback' );
    add_action( 'wp_ajax_update_clan_pic', 'blackfyre_update_clan_pic_callback' );
    add_action( 'wp_ajax_nopriv_update_clan_pic', 'blackfyre_update_clan_pic_callback' );
    add_action( 'wp_ajax_nopriv_blackfyre_redirect', 'blackfyre_redirect' );
    add_action( 'wp_ajax_blackfyre_redirect', 'blackfyre_redirect' );
    add_action( 'wp_ajax_nopriv_blackfyre_delete_page_background', 'blackfyre_delete_page_background' );
    add_action( 'wp_ajax_blackfyre_delete_page_background', 'blackfyre_delete_page_background' );
    add_action( 'wp_ajax_nopriv_blackfyre_change_membership_block', 'blackfyre_change_membership_block' );
    add_action( 'wp_ajax_blackfyre_change_membership_block', 'blackfyre_change_membership_block' );
    add_action( 'wp_ajax_nopriv_blackfyre_change_membership_let_join', 'blackfyre_change_membership_let_join' );
    add_action( 'wp_ajax_blackfyre_change_membership_let_join', 'blackfyre_change_membership_let_join' );
    add_action( 'wp_ajax_nopriv_blackfyre_change_membership_remove_friend_admin', 'blackfyre_change_membership_remove_friend_admin' );
    add_action( 'wp_ajax_blackfyre_change_membership_remove_friend_admin', 'blackfyre_change_membership_remove_friend_admin' );
    add_action( 'wp_ajax_nopriv_blackfyre_change_membership_make_administrator', 'blackfyre_change_membership_make_administrator' );
    add_action( 'wp_ajax_blackfyre_change_membership_make_administrator', 'blackfyre_change_membership_make_administrator' );
    add_action( 'wp_ajax_nopriv_blackfyre_change_membership_downgrade_to_user', 'blackfyre_change_membership_downgrade_to_user' );
    add_action( 'wp_ajax_blackfyre_change_membership_downgrade_to_user', 'blackfyre_change_membership_downgrade_to_user' );
    add_action( 'wp_ajax_nopriv_blackfyre_clan_members_ajax', 'blackfyre_clan_members_ajax' );
    add_action( 'wp_ajax_blackfyre_clan_members_ajax', 'blackfyre_clan_members_ajax' );
    add_action( 'wp_ajax_nopriv_blackfyre_challenge_acc_rej', 'blackfyre_challenge_acc_rej' );
    add_action( 'wp_ajax_blackfyre_challenge_acc_rej', 'blackfyre_challenge_acc_rej' );
    add_action( 'wp_ajax_nopriv_blackfyre_challenge_acc_rej_single', 'blackfyre_challenge_acc_rej_single' );
    add_action( 'wp_ajax_blackfyre_challenge_acc_rej_single', 'blackfyre_challenge_acc_rej_single' );
    add_action( 'wp_ajax_nopriv_blackfyre_match_score_acc_rej', 'blackfyre_match_score_acc_rej' );
    add_action( 'wp_ajax_blackfyre_match_score_acc_rej', 'blackfyre_match_score_acc_rej' );
    add_action( 'wp_ajax_nopriv_blackfyre_clan_delete', 'blackfyre_clan_delete' );
    add_action( 'wp_ajax_blackfyre_clan_delete', 'blackfyre_clan_delete' );
    add_action( 'wp_ajax_nopriv_blackfyre_match_delete', 'blackfyre_match_delete' );
    add_action( 'wp_ajax_blackfyre_match_delete', 'blackfyre_match_delete' );
    add_action( 'wp_ajax_nopriv_blackfyre_match_delete_notification', 'blackfyre_match_delete_notification' );
    add_action( 'wp_ajax_blackfyre_match_delete_notification', 'blackfyre_match_delete_notification' );
    add_action( 'wp_ajax_nopriv_blackfyre_mutual_games', 'blackfyre_mutual_games' );
    add_action( 'wp_ajax_blackfyre_mutual_games', 'blackfyre_mutual_games' );
    add_action( 'wp_ajax_nopriv_blackfyre_all_clans_pagination_v2_ajax', 'blackfyre_all_clans_pagination_v2_ajax' );
    add_action( 'wp_ajax_blackfyre_all_clans_pagination_v2_ajax', 'blackfyre_all_clans_pagination_v2_ajax' );

    /*user permissions*/
    add_action( 'admin_init', 'blackfyre_change_user_permissions' );

    /*multiple thumbnails*/
    add_action( 'admin_enqueue_scripts', 'blackfyre_admin_header_scripts' );

    /*vc*/
    add_action( 'in_admin_footer', 'blakcfyre_footer_manager' );

    /*media library*/
    add_action( 'pre_get_posts','blackfyre_restrict_media_library' );
    add_action('wp_enqueue_scripts', 'blackfyre_add_media_upload_scripts');

    /*post templates*/
    add_action( 'init', 'blackfyre_post_templates_plugin_init' );
	
	/*notices*/
	add_action( 'admin_notices', 'skywarrior_update_nag', 1 );
	
	/*user profiles*/
	add_action( 'personal_options_update', 'save_skywarrior_clan_extra_user_profile_fields' );
	add_action( 'edit_user_profile_update', 'save_skywarrior_clan_extra_user_profile_fields' );
	add_action( 'show_user_profile', 'skywarrior_clan_extra_user_profile_fields' );
	add_action( 'edit_user_profile', 'skywarrior_clan_extra_user_profile_fields' );

    /*****FILTERS*****/

    /*menu*/
    add_filter( 'wp_setup_nav_menu_item','blackfyre_nav_item' );
    add_filter( 'wp_edit_nav_menu_walker', 'blackfyre_nav_edit_walker',10,2 );

    /*sidebars*/
    add_filter('dynamic_sidebar_params','blackfyre_widget_first_last_classes');

    /*excerpt*/
    add_filter( 'excerpt_length', 'blackfyre_excerpt_length', 999 );
    add_filter( 'excerpt_length', 'blackfyre_excerpt_length_pro', 999 );

    /*slider*/
    add_filter( 'the_content', 'blackfyre_remove_slider_from_home' );
    add_filter( 'manage_edit-slider_columns', 'blackfyre_set_custom_edit_slider_columns' );

    /*woocommerce*/
    add_filter( 'add_to_cart_fragments', 'blackfyre_woocommerce_header_add_to_cart_fragment' );

    /*tinymce*/
    add_filter( 'tiny_mce_before_init', 'blackfyre_change_mce_options' );

    /*social login*/
    add_filter( 'pre_user_email', 'blackfyre_skip_email_exist' );

    /*gravatar*/
    add_filter( 'get_avatar', 'blackfyre_be_gravatar_filter', 10, 5 );

    /*buddypress*/
    add_filter( 'bp_get_add_friend_button', 'blackfyre_add_friend_link_text' );
	add_filter( 'bp_core_mysteryman_src', 'skywarrior_buddypress_avatar' );

    /*role*/
    add_filter( 'pre_option_default_role', 'blackfyre_defaultrole' );

    /*comments*/
    add_filter( 'comments_open', 'blackfyre_comments_open', 10, 2 );
    add_filter( 'wp_insert_post_data', 'blackfyre_comments_on' );

    /*pricetables*/
    add_filter( 'manage_pricetable_posts_columns', 'blackfyre_pricetable_register_custom_columns');
	
	

    /*****THEME-SUPPORTED FEATURES*****/

    /*add custom menu support*/
    add_theme_support( 'menus' );
    add_theme_support( 'post-thumbnails' );
    add_theme_support( 'woocommerce' );

}

/*register sidebars*/
 add_action( 'after_setup_theme', 'blackfyre_register_sidebars' );
function blackfyre_register_sidebars() {
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => __( 'Home sidebar', 'blackfyre' ),
'id' => 'one',
'description' => __( 'Widgets in this area will be shown in the home page.' , 'blackfyre'),
'before_widget' => '<div class="widget">',
'after_widget' => '</div>',
'before_title' => '<div class="title-wrapper"><h3 class="widget-title">',
'after_title' => '</h3><div class="clear"></div></div>', ));
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => __( 'General sidebar', 'blackfyre' ),
'id' => 'two',
'description' => __( 'General sidebar for use with page builder.' , 'blackfyre'),
'before_widget' => '<div class="widget">',
'after_widget' => '</div>',
'before_title' => '<div class="title-wrapper"><h3 class="widget-title">',
'after_title' => '</h3><div class="clear"></div></div>', ));
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => __( 'Blog sidebar', 'blackfyre' ),
'id' => 'three',
'description' => __( 'Widgets in this area will be shown in the blog sidebar.' , 'blackfyre'),
'before_widget' => '<div class="widget">',
'after_widget' => '</div>',
'before_title' => '<div class="title-wrapper"><h3 class="widget-title">',
'after_title' => '</h3><div class="clear"></div></div>', ));
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => __( 'Footer area widgets', 'blackfyre' ),
'id' => 'footer',
'description' => __( 'Widgets in this area will be shown in the footer.' , 'blackfyre'),
'before_widget' => '<div class="footer_widget col-lg-4 col-md-4">',
'after_widget' => '</div>',
'before_title' => '<div class="title-wrapper"><h3 class="widget-title">',
'after_title' => '</h3><div class="clear"></div></div>', ));
}
if ( is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => 'WooCommerce Sidebar',
'id' => 'woo',
'description' => __( 'Widgets in this area will be shown in the WooCommerce sidebar.' , 'blackfyre'),
'before_widget' =>  '<div id="%1$s" class="widget widgetSidebar %2$s">',
'after_widget'  => '</div>',
'before_title' => '<div class="title-wrapper"><h3 class="widget-title">',
'after_title' => '</h3><div class="clear"></div></div>', ));
}
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => 'ClanWars Sidebar',
'id' => 'clanwars',
'description' => __( 'Widgets in this area will be shown in the Clan Wars sidebar.' , 'blackfyre'),
'before_widget' =>  '<div id="%1$s" class="widget widgetSidebar %2$s">',
'after_widget'  => '</div>',
'before_title' => '<div class="title-wrapper"><h3 class="widget-title">',
'after_title' => '</h3><div class="clear"></div></div>', ));
if ( is_plugin_active( 'buddypress/bp-loader.php' ) ) {
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => 'BuddyPress Sidebar',
'id' => 'buddypress',
'description' => __( 'Widgets in this area will be shown in the BuddyPress sidebar.' , 'blackfyre'),
'before_widget' =>  '<div id="%1$s" class="widget widgetSidebar %2$s">',
'after_widget'  => '</div>',
'before_title' => '<div class="title-wrapper"><h3 class="widget-title">',
'after_title' => '</h3><div class="clear"></div></div>', ));
}


/**
 * Dynamically sets classes on footer widgets based on number of widgets.
 *
 * @since Blackfyre 1.4
 */
function blackfyre_footer_sidebar_classes( $params ) {
    $sidebar_id = $params[0]['id'];

    if ( $sidebar_id == 'footer' ) {

        $total_widgets = wp_get_sidebars_widgets();
        $sidebar_widgets = count( $total_widgets[$sidebar_id] );
		
		if ( $sidebar_widgets == 2 ) {
			$params[0]['before_widget'] = str_replace( 'col-lg-4', 'col-lg-6', $params[0]['before_widget'] );
			$params[0]['before_widget'] = str_replace( 'col-md-4', 'col-md-6', $params[0]['before_widget'] );
		} else if ( $sidebar_widgets == 4 ) {
			$params[0]['before_widget'] = str_replace( 'col-lg-4', 'col-lg-3', $params[0]['before_widget'] );
			$params[0]['before_widget'] = str_replace( 'col-md-4', 'col-md-3', $params[0]['before_widget'] );
		}
        
    }

    return $params;
}
add_filter( 'dynamic_sidebar_params', 'blackfyre_footer_sidebar_classes' );


/*add custom menu support*/
function blackfyre_create_menu(){
$themeicon1 = get_template_directory_uri()."/img/favicon.png";
add_menu_page("Theme Options", "Theme Options", 'edit_theme_options', 'options-framework', 'optionsframework_page',$themeicon1,1800 );
}


function blackfyre_nav_update($menu_id, $menu_item_db_id, $args ) {
    if (isset($_REQUEST['menu-item-custom'])) {
        if ( is_array($_REQUEST['menu-item-custom']) ) {
            $custom_value = $_REQUEST['menu-item-custom'][$menu_item_db_id];
            update_post_meta( $menu_item_db_id, '_menu_item_custom', $custom_value );
        }
    }
    $removemegamenu = true;
    if (isset($_REQUEST['megamenu-checkbox'])) {
        if ( is_array($_REQUEST['megamenu-checkbox']) ) {
            if (isset($_REQUEST['megamenu-checkbox'][$menu_item_db_id])) {
            if ($_REQUEST['megamenu-checkbox'][$menu_item_db_id] == "on") {
                update_post_meta( $menu_item_db_id, '_uses_megamenu', "yes" );
                $removemegamenu = false;
            }
          }
        }
    }
    if ($removemegamenu == true) {
        update_post_meta( $menu_item_db_id, '_uses_megamenu', "no" );
    }
}
/*
 * Adds value of new field to $item object that will be passed to     Walker_Nav_Menu_Edit_Custom
 */

function blackfyre_nav_item($menu_item) {
    $menu_item->custom = get_post_meta( $menu_item->ID, '_menu_item_custom', true );
    return $menu_item;
}

function blackfyre_nav_edit_walker($walker,$menu_id) {
    return 'Walker_Nav_Menu_Edit_Custom';
}


add_action( 'after_setup_theme', 'blackfyre_theme_tweak' );
function blackfyre_theme_tweak(){


// When this theme is activated send the user to the theme options
if (is_admin() && isset($_GET['activated'] ) ) {
// Do redirect
header( 'Location: '.admin_url().'themes.php?page=options-framework' ) ;
}


/*register theme location menu*/
function blackfyre_register_my_menus() {
  register_nav_menus(
    array(
      'header-menu' => __( 'Header Menu' , 'blackfyre'),
      )
  );
}
}


/* Breadcrumbs */
function blackfyre_pg(){
    $pages = get_pages(array(
    'meta_key' => '_wp_page_template',
    'meta_value' => 'tmp-blog.php'
));
foreach($pages as $page){
   return $page->post_name;
}}
function blackfyre_get_page_id($name){
global $wpdb;
// get page id using custom query
$page_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE ( post_name = %s or post_title = %s )
and post_status = 'publish' and post_type='page'",
    $name));
return $page_id;
}
function blackfyre_get_page_permalink($name){
$page_id = blackfyre_get_page_id($name);
return get_permalink($page_id);
}
// Breadcrumbs
function blackfyre_breadcrumbs_inner() {
    if (!is_home()) {
        echo '<a href="';
        echo esc_url(home_url());
        echo '">';
        _e('Home', 'blackfyre ');
        echo "</a> / ";

        if(get_post_type() == 'matches' && !is_search()){

        
            _e('Matches', 'blackfyre ');
          

            if (is_single()) {
                echo " / ";
                the_title();
            }
        } elseif(is_category()) {
            _e('Category: ', 'blackfyre ');
            echo esc_attr(single_cat_title());

        } elseif(is_404()) {
            echo '404';

        } elseif(is_search()) {
            _e('Search: ', 'blackfyre ');
            echo esc_attr(get_search_query());

        } elseif(is_author()) {
            $curauth = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author')); echo esc_attr($curauth->user_nicename);
        } elseif (is_page()) {
            echo the_title();
        } elseif (is_single()) {
            echo the_title();
        }elseif(is_tag()) {
              _e('Tag: ', 'blackfyre ');
             echo blackfyre_GetTagName(get_query_var('tag_id'));
        }elseif(is_shop()){
        	 _e('Shop', 'blackfyre ');
        }elseif(is_woocommerce()){
        	
                the_title();
        } elseif(is_archive()) {
            if(get_post_type() == 'video'){}else{
               echo " / ";
              _e('Archive', 'blackfyre ');
            }
        }

     if(is_admin()){
        $current_user= wp_get_current_user();
        $level = $current_user->user_level;
        if($level == 1){
            global $wp_post_types; $obj = $wp_post_types['video'];print $obj->labels->singular_name;
        }}
    }
}

function blackfyre_breadcrumbs(){

if(function_exists('is_bbpress')){
    if(is_bbpress()){
        bbp_breadcrumb();
    }else{
        blackfyre_breadcrumbs_inner();}
}else{
        blackfyre_breadcrumbs_inner();
  }
}

/*custom excerpt lenght*/
function blackfyre_excerpt_length( $length ){
    return 55;
}
function blackfyre_excerpt_length_pro( $length ) {
    return 40;
}


/*Post templates*/
function blackfyre_post_templates_plugin_init() {
    new Blackfyre_Single_Post_Template_Plugin;
}


/*pagination*/
function blackfyre_kriesi_pagination($pages = '', $range = 1){
$showitems = ($range * 1)+1;
$general_show_page  = of_get_option('general_post_show');
global $paged;
global $paginate;
if(empty($paged)) $paged = 1;
if($pages == '')
{
global $wp_query;
$pages = $wp_query->max_num_pages;
if(!$pages)
{
$pages = 1;
}
}
if(1 != $pages){
$url= get_template_directory_uri();
$leftpager= '&laquo;';
$rightpager= '&raquo;';
if($paged > 2 && $paged > $range+1 && $showitems < $pages) $paginate.=  "";
if($paged > 1 ) $paginate.=  "<a class='page-selector' href='".get_pagenum_link($paged - 1)."'>". $leftpager. "</a>";
for ($i=1; $i <= $pages; $i++){
if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )){
$paginate.=  ($paged == $i)? "<li class='active'><a href='".get_pagenum_link($i)."'>".$i."</a></li>":"<li><a href='".get_pagenum_link($i)."' class='inactive' >".$i."</a></li>";
}
}
if ($paged < $pages ) $paginate.=  "<li><a class='page-selector' href='".get_pagenum_link($paged + 1)."' >". $rightpager. "</a></li>";
}
return $paginate;
}

/*color converter*/
function blackfyre_hex2rgb($hex) {
   $hex = str_replace("#", "", $hex);

   if(strlen($hex) == 3) {
      $r = hexdec(substr($hex,0,1).substr($hex,0,1));
      $g = hexdec(substr($hex,1,1).substr($hex,1,1));
      $b = hexdec(substr($hex,2,1).substr($hex,2,1));
   } else {
      $r = hexdec(substr($hex,0,2));
      $g = hexdec(substr($hex,2,2));
      $b = hexdec(substr($hex,4,2));
   }
   $rgb = array($r, $g, $b);
   //return implode(",", $rgb); // returns the rgb values separated by commas
   return $rgb; // returns an array with the rgb values
}

/*add featured image support*/
if ( function_exists( 'add_image_size' ) ) {
   set_post_thumbnail_size( 287, 222, true );
   set_post_thumbnail_size( 305, 305, true );
   add_image_size( 'profile-photo', 250, 250, true );
}

/*
 * Include the TGM_Plugin_Activation class.
 */

/*
 * Register the required plugins for this theme.
 *
 * In this example, we register two plugins - one included with the TGMPA library
 * and one from the .org repo.
 *
 * The variable passed to tgmpa_register_plugins() should be an array of plugin
 * arrays.
 *
 * This function is hooked into tgmpa_init, which is fired within the
 * TGM_Plugin_Activation class constructor.
 */
function blackfyre_register_required_plugins() {
    /**
     * Array of plugin arrays. Required keys are name and slug.
     * If the source is NOT from the .org repo, then source is also required.
     */
    $plugins = array(
        // This is an example of how to include a plugin pre-packaged with a theme
       array(
            'name'                  => 'BBpress', // The plugin name
            'slug'                  => 'bbpress', // The plugin slug (typically the folder name)
            'source'                => 'https://downloads.wordpress.org/plugin/bbpress.2.5.4.zip', // The plugin source
            'required'              => false, // If false, the plugin is only 'recommended' instead of required
            'version'               => '', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
            'force_activation'      => false, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
            'force_deactivation'    => false, // If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
            'external_url'          => '', // If set, overrides default API URL and points to an external URL
        ),array(
            'name'                  => 'BuddyPress', // The plugin name
            'slug'                  => 'buddypress', // The plugin slug (typically the folder name)
            'source'                => 'https://downloads.wordpress.org/plugin/buddypress.2.2.0.zip', // The plugin source
            'required'              => true, // If false, the plugin is only 'recommended' instead of required
            'version'               => '', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
            'force_activation'      => false, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
            'force_deactivation'    => false, // If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
            'external_url'          => '', // If set, overrides default API URL and points to an external URL
        ),array(
            'name'                  => 'WooCommerce', // The plugin name
            'slug'                  => 'woocommerce', // The plugin slug (typically the folder name)
            'source'                => 'https://downloads.wordpress.org/plugin/woocommerce.zip', // The plugin source
            'required'              => false, // If false, the plugin is only 'recommended' instead of required
            'version'               => '', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
            'force_activation'      => false, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
            'force_deactivation'    => false, // If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
            'external_url'          => '', // If set, overrides default API URL and points to an external URL
        ),array(
            'name'                  => 'Disqus', // The plugin name
            'slug'                  => 'disqus', // The plugin slug (typically the folder name)
            'source'                => 'https://downloads.wordpress.org/plugin/disqus-comment-system.zip', // The plugin source
            'required'              => false, // If false, the plugin is only 'recommended' instead of required
            'version'               => '', // E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
            'force_activation'      => false, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
            'force_deactivation'    => false, // If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
            'external_url'          => '', // If set, overrides default API URL and points to an external URL
        ),

    );
    // Change this to your theme text domain, used for internationalising strings
    $theme_text_domain = 'blackfyre';
    /**
     * Array of configuration settings. Amend each line as needed.
     * If you want the default strings to be available under your own theme domain,
     * leave the strings uncommented.
     * Some of the strings are added into a sprintf, so see the comments at the
     * end of each line for what each argument will be.
     */
    $config = array(
        'domain'            => $theme_text_domain,          // Text domain - likely want to be the same as your theme.
        'default_path'      => '',                          // Default absolute path to pre-packaged plugins
        'parent_menu_slug'  => 'themes.php',                // Default parent menu slug
        'parent_url_slug'   => 'themes.php',                // Default parent URL slug
        'menu'              => 'install-required-plugins',  // Menu slug
        'has_notices'       => true,                        // Show admin notices or not
        'is_automatic'      => true,                       // Automatically activate plugins after installation or not
        'message'           => '',                          // Message to output right before the plugins table
        'strings'           => array(
            'page_title'                                => __( 'Install Required Plugins', 'blackfyre' ),
            'menu_title'                                => __( 'Install Plugins', 'blackfyre' ),
            'installing'                                => __( 'Installing Plugin: %s', 'blackfyre' ), // %1$s = plugin name
            'oops'                                      => __( 'Something went wrong with the plugin API.', 'blackfyre' ),
            'notice_can_install_required'               => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.' ), // %1$s = plugin name(s)
            'notice_can_install_recommended'            => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.' ), // %1$s = plugin name(s)
            'notice_cannot_install'                     => _n_noop( 'Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', 'Sorry, but you do not have the correct permissions to install the %s plugins. Contact the administrator of this site for help on getting the plugins installed.' ), // %1$s = plugin name(s)
            'notice_can_activate_required'              => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.' ), // %1$s = plugin name(s)
            'notice_can_activate_recommended'           => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.' ), // %1$s = plugin name(s)
            'notice_cannot_activate'                    => _n_noop( 'Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.', 'Sorry, but you do not have the correct permissions to activate the %s plugins. Contact the administrator of this site for help on getting the plugins activated.' ), // %1$s = plugin name(s)
            'notice_ask_to_update'                      => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.' ), // %1$s = plugin name(s)
            'notice_cannot_update'                      => _n_noop( 'Sorry, but you do not have the correct permissions to update the %s plugin. Contact the administrator of this site for help on getting the plugin updated.', 'Sorry, but you do not have the correct permissions to update the %s plugins. Contact the administrator of this site for help on getting the plugins updated.' ), // %1$s = plugin name(s)
            'install_link'                              => _n_noop( 'Begin installing plugin', 'Begin installing plugins' ),
            'activate_link'                             => _n_noop( 'Activate installed plugin', 'Activate installed plugins' ),
            'return'                                    => __( 'Return to Required Plugins Installer', 'blackfyre' ),
            'plugin_activated'                          => __( 'Plugin activated successfully.', 'blackfyre' ),
            'complete'                                  => __( 'All plugins installed and activated successfully. %s', 'blackfyre' ), // %1$s = dashboard link
            'nag_type'                                  => 'updated' // Determines admin notice type - can only be 'updated' or 'error'
        )
    );
    tgmpa( $plugins, $config );
}

/*add media*/
 function blackfyre_add_media_upload_scripts() {
            if ( is_admin() ) {
                 return;
               }
            wp_enqueue_media();
}

/*theme styles*/
function blackfyre_style() {
  wp_enqueue_style( 'blackfyre_mytheme_style-style',  get_bloginfo( 'stylesheet_url' ), array(), '20150401' );
  wp_register_style('wp-cw-sitecss', WP_CLANWARS_URL . '/css/site.css', array(), WP_CLANWARS_VERSION);
  wp_enqueue_style( 'wp-cw-sitecss' );
  wp_register_style('wp-cw-widgetcss', WP_CLANWARS_URL . '/css/widget.css', array(), WP_CLANWARS_VERSION);
  wp_enqueue_style( 'wp-cw-widgetcss' );
   if ( is_rtl() )
    {
        wp_register_style('blackfyre-rtl',  get_template_directory_uri() . '/css/rtl.css', array(), '20150401');
        wp_enqueue_style( 'blackfyre-rtl' );
    }
}


function blackfyre_fonts() {
    $protocol = is_ssl() ? 'https' : 'http';
    wp_enqueue_style( 'blackfyre-oswald', "$protocol://fonts.googleapis.com/css?family=Oswald:400,700,300" );
    wp_enqueue_style( 'blackfyre-roboto', "$protocol://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,700,500italic,700italic,900italic,900" );
}


function blackfyre_external_styles(){
  wp_register_style( 'custom-style',  '//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800,400italic,600italic,700italic',  array(), '20150401');
  wp_enqueue_style( 'custom-style' );
  wp_register_style( 'custom-style1',  get_template_directory_uri().'/css/jquery.fancybox.css',  array(), '20150401');
  wp_enqueue_style( 'custom-style1' );
  wp_register_style( 'custom-style2',  get_template_directory_uri().'/css/jquery.bxslider.css',  array(), '20150401');
  wp_enqueue_style( 'custom-style2' );
  wp_register_style( 'pricetable1',  get_template_directory_uri().'/addons/pricetable/css/pricetable.css',  array(), '20150401');
  wp_enqueue_style( 'pricetable1' );
  wp_register_style( 'animatecss',  get_template_directory_uri().'/css/animate.css',  array(), '20150401');
  wp_enqueue_style( 'animatecss' );

}



/*theme scripts*/

function blackfyre_my_scripts(){

wp_register_script( 'bootstrap1', get_template_directory_uri().'/js/bootstrap.min.js','','',true);
wp_enqueue_script('bootstrap1');
$settingsNoty = array(
            'challenge_accepted' => __('Challenge accepted!', 'blackfyre'),
            'challenge_rejected' => __('Challenge rejected!', 'blackfyre'),
            'match_deleted' => __('Match deleted!', 'blackfyre'),
            'score_accepted' => __('Score accepted!', 'blackfyre'),
            'score_rejected' => __('Score rejected!', 'blackfyre'),
            'challenge_request_sent' => __('Challenge request sent!', 'blackfyre'),
            'submitted' => __('Score has been submitted!', 'blackfyre'),
            'already_submitted' => __('Score has already been submitted by other team!', 'blackfyre'),
            'join_clan' => __('Your request to join clan has been sent!', 'blackfyre'),
            'let_this_member_join' => __('User joined your clan!', 'blackfyre'),
            'remove_friend' => __('Removed from clan!', 'blackfyre'),
            'cancel_request' => __('Request canceled!', 'blackfyre'),
            'make_administrator' => __('Added as administrator!', 'blackfyre'),
            'downgrade_to_user' => __('Admin downgraded!', 'blackfyre'),
            'reported' => __('Match has been reported!', 'blackfyre'),
            'clan_deleted' => __('Clan has been deleted!', 'blackfyre'),
            'delete_page_background' => __('Clan page background deleted successfully!', 'blackfyre'),
             );
wp_register_script( 'noty', get_template_directory_uri().'/js/noty/packaged/jquery.noty.packaged.min.js','','',true);
wp_enqueue_script('noty');
wp_localize_script('noty', 'settingsNoty', $settingsNoty);

if(of_get_option('scrollbar') == 1){
wp_register_script( 'custom_js1',   get_template_directory_uri().'/js/theme.min.js','','',true);
wp_enqueue_script('custom_js1');
}
wp_register_script( 'easing',  get_template_directory_uri().'/js/easing.js','','',true);
wp_enqueue_script('easing');
wp_register_script( 'main',  get_template_directory_uri().'/js/main.js','','',true);
wp_enqueue_script('main');
wp_register_script( 'fancybox',  get_template_directory_uri().'/js/jquery.fancybox.js','','',true);
wp_enqueue_script('fancybox');
wp_register_script( 'custom_js3',  get_template_directory_uri().'/js/jquery-ui-1.10.3.custom.min.js','','',true);
wp_enqueue_script('custom_js3');
wp_register_script( 'custom_js4',  get_template_directory_uri().'/js/jquery.carouFredSel-6.2.1-packed.js','','',true);
wp_enqueue_script('custom_js4');
wp_register_script( 'custom_js5',   get_template_directory_uri().'/js/appear.js','','',true);
wp_enqueue_script('custom_js5');
wp_register_script( 'custom_js7',  get_template_directory_uri().'/js/jquery.webticker.js','','',true);
wp_enqueue_script('custom_js7');
wp_register_script( 'custom_js8',  get_template_directory_uri().'/js/jquery.bxslider.min.js','','',true);
wp_enqueue_script('custom_js8');
wp_register_script( 'custom_js9',   get_template_directory_uri().'/js/isotope.js','','',true);
wp_enqueue_script('custom_js9');
wp_register_script( 'custom_js10',   get_template_directory_uri().'/js/imagesloaded.min.js','','',true);
wp_enqueue_script('custom_js10');
wp_register_script( 'custom_js11',   get_template_directory_uri().'/js/jquery.validate.min.js','','',true);
wp_enqueue_script('custom_js11');
wp_register_script( 'custom_js99',   get_template_directory_uri().'/js/global.js','','',true);
wp_enqueue_script('custom_js99');
wp_register_script( 'imagescale',   get_template_directory_uri().'/js/imagescale.js','','',true);
wp_enqueue_script('imagescale');
wp_register_script( 'transit',   get_template_directory_uri().'/js/transit.js','','',true);
wp_enqueue_script('transit');

$baseurl = get_template_directory_uri() . '/include/';
$settings = array(
	'authlocation' => $baseurl,
	'ajax'         => admin_url( 'admin-ajax.php' )
);
wp_register_script( 'social_js', get_template_directory_uri() . '/js/social.js', '', '', true );
wp_localize_script( 'social_js', 'settings', $settings );
wp_enqueue_script( 'social_js' );

wp_register_script( 'cw',   get_template_directory_uri().'/addons/clan-wars/js/matches.js','','',true);
wp_enqueue_script('cw');
wp_localize_script('cw',
                'wpCWL10n',
                array(
                'plugin_url' =>  get_template_directory_uri().'/addons/clan-wars',
                'addRound' => __('Add Round', 'blackfyre'),
                'excludeMap' => __('Exclude map from match', 'blackfyre'),
                'removeRound' => __('Remove round', 'blackfyre')
                )
            );
wp_enqueue_script( 'heart-love', get_template_directory_uri() . '/addons/heart/love/js/heart-love.js', 'jquery', '1.0', TRUE );
wp_localize_script( 'heart-love', 'heartLove', array('ajaxurl' => admin_url('admin-ajax.php')));
}

/*admin sctipts*/
function blackfyre_scripts_admin(){
wp_register_script( 'custom11',   get_template_directory_uri().'/js/admin.js','','',true);
wp_enqueue_script('custom11');
wp_register_script( 'custom22',   get_template_directory_uri().'/js/jquery.elastic.source.js','','',true);
wp_enqueue_script('custom22');
wp_enqueue_script( "mpt-featured-image",  get_template_directory_uri().'/addons/multiple-post-thumbnails/js/multi-post-thumbnails-admin.js', array( 'jquery', 'set-post-thumbnail' ));
wp_enqueue_script( "mpt-featured-image-modal",  get_template_directory_uri().'/addons/multiple-post-thumbnails/js/media-modal.js', array( 'jquery', 'media-models' ));
}

/*admin styles*/
function blackfyre_styles_admin(){
wp_register_style( 'custom-style44',  get_template_directory_uri().'/css/font-awesome.css',  array(), '20130401');
wp_enqueue_style( 'custom-style44' );
wp_register_style( 'custom-style55',  get_template_directory_uri().'/css/admin.css',  array(), '20130401');
wp_enqueue_style( 'custom-style55' );
wp_register_style( 'custom-style66',  get_template_directory_uri().'/css/gf-style.css',  array(), '20130401');
wp_enqueue_style( 'custom-style66' );
}

/*post id for multipost thumbnails*/
function blackfyre_admin_header_scripts() {
    $post_id = get_the_ID();
    if(empty($post_id))$post_id=0;
    echo "<script>var post_id = $post_id;</script>";
}

/*add last item in footer sidebar class*/
function blackfyre_widget_first_last_classes($params) {
    global $my_widget_num; // Global a counter array
    $this_id = $params[0]['id']; // Get the id for the current sidebar we're processing
    $arr_registered_widgets = wp_get_sidebars_widgets(); // Get an array of ALL registered widgets
    if(!$my_widget_num) {// If the counter array doesn't exist, create it
        $my_widget_num = array();
    }
    if(!isset($arr_registered_widgets[$this_id]) || !is_array($arr_registered_widgets[$this_id])) { // Check if the current sidebar has no widgets
        return $params; // No widgets in this sidebar... bail early.
    }
    if(isset($my_widget_num[$this_id])) { // See if the counter array has an entry for this sidebar
        $my_widget_num[$this_id] ++;
    } else { // If not, create it starting with 1
        $my_widget_num[$this_id] = 1;
    }
    $class = 'class="widget-' . $my_widget_num[$this_id] . ' '; // Add a widget number class for additional styling options
    if($my_widget_num[$this_id] == 1) { // If this is the first widget
        $class .= 'first ';
    } elseif($my_widget_num[$this_id] == count($arr_registered_widgets[$this_id])) { // If this is the last widget
        $class .= 'last ';
    }
    $params[0]['before_widget'] = str_replace('class="', $class, $params[0]['before_widget']); // Insert our new classes into "before widget"
    return $params;
}


/*custom comments*/
function blackfyre_custom_comments($comment, $args, $depth) {
  $GLOBALS['comment'] = $comment;
    $GLOBALS['comment_depth'] = $depth;
  ?>
    <li class="comment">
        <div class="wcontainer"><img alt="img" class="photo avatar" src="<?php echo blackfyre_commenter_avatar($comment->user_id); ?>" />
  <?php if ($comment->comment_approved == '0'){ ?><span class='unapproved'><?php _e("Your comment is awaiting moderation.", 'blackfyre'); ?></span> <?php } ?>
          <div class="comment-body">
             <div class="comment-author"><?php blackfyre_commenter_link() ?> <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?></div>
             <i><small><?php comment_time('M j, Y @ G:i a'); ?></small> </i><br />
             <?php comment_text() ?>

        </div>
        <div class="clear"></div>
        </div>
    </li>
<?php }


/*custom pings*/
function blackfyre_custom_pings($comment, $args, $depth) {
       $GLOBALS['comment'] = $comment;
        ?>
         <div class="project-comment row">
                <div class="comment-author"><?php printf(__('By %1$s on %2$s at %3$s', 'blackfyre'),
                        get_comment_author_link(),
                        get_comment_date(),
                        get_comment_time() );
                        edit_comment_link(__('Edit', 'blackfyre'), ' <span class="meta-sep">|</span> <span class="edit-link">', '</span>'); ?></div>
    <?php if ($comment->comment_approved == '0'){ ?><span class="unapproved"><?php _e('Your trackback is awaiting moderation.', 'blackfyre');?> </span><?php } ?>
            <div class="comment-content span6">
                <?php comment_text() ?>
            </div>
            </div>
<?php
}

/*Produces an avatar image with the hCard-compliant photo class*/
function blackfyre_commenter_link() {
   $commenter = get_comment_author_link();
    if ( preg_match( '/<a[^>]* class=[^>]+>/', $commenter ) ) {
        $commenter = preg_replace( '/(<a[^>]* class=[\'"]?)/', '\\1url ' , $commenter );
    } else {
        $commenter = preg_replace( '/(<a )/', '\\1class="url "/' , $commenter );
    }
    echo ' <span class="comment-info">' . $commenter . '</span>';
}

/*Commenter avatar*/
function blackfyre_commenter_avatar($uid) {
     $url0 = get_user_meta($uid, 'profile_photo', true);
     if(!empty($url0)){
       $url1 = blackfyre_aq_resize( $url0, 100, 100, true, '', true );
       $url = $url1[0];  //resize & crop img
     }
     if(empty($url)){ $url = '//gravatar.com/avatar/ccf2e856d472e2211ace58458850aaee?d=mm&amp;s=50&amp;r=G'; }
     return $url;
}


/*register match post types*/
function blackfyre_matches_register() {
    $labels = array(
        'name' => _x('Matches', 'post type general name','blackfyre'),
        'singular_name' => _x('Match', 'post type singular name','blackfyre'),
        'add_new' => _x('Add New', 'match item' ,'blackfyre'),
        'add_new_item' => __('Add New Match','blackfyre'),
        'edit_item' => __('Edit Match','blackfyre'),
        'new_item' => __('New Match','blackfyre'),
        'view_item' => __('View Match','blackfyre'),
        'search_items' => __('Search Matches','blackfyre'),
        'not_found' =>  __('Nothing found','blackfyre'),
        'not_found_in_trash' => __('Nothing found in Trash','blackfyre'),
        'parent_item_colon' => ''
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'query_var' => true,
        'menu_icon' => get_template_directory_uri() . '/img/portfolio.png',
        'rewrite' => true,
        'capability_type' => 'post',
          'capabilities' => array(
            'create_posts' => false, // Removes support for the "Add New" function
          ),
        'map_meta_cap' => true,
        'hierarchical' => false,
        'menu_position' => null,
        'supports' => array('title','editor','thumbnail')

      );
    register_post_type( 'matches' , $args );
}
function blackfyre_remove_matches_menu() {
    remove_menu_page( 'edit.php?post_type=matches' );
}



/*add smartmetaboxes*/
function blackfyre_wp_editor( $post ) {
  $field_value = get_post_meta( $post->ID, '_smartmeta_my-awesome-field', false );
  if(!isset($field_value[0])){ wp_editor( '', '_smartmeta_my-awesome-field' );
  }else{ wp_editor( $field_value[0], '_smartmeta_my-awesome-field' );}

}


function blackfyre_saving_my_data( $post_id ) {
    if ( isset ( $_POST['_smartmeta_my-awesome-field'] ) ) {
    update_post_meta( $post_id, '_smartmeta_my-awesome-field', $_POST['_smartmeta_my-awesome-field'] );
  }
}

function blackfyre_select_meta(){
$args = array(
  'orderby' => 'name',
  'order' => 'ASC',
  'type' => 'post'
  );
$categories = get_categories($args);
$i=2;
$cat_ar = array();
$cat_ar[] = __('Do not use post slider', 'blackfyre');
foreach($categories as $category) {
    $cat_ar[] = $category->name;
    $i++;
   }

    return $cat_ar;
}

add_smart_meta_box('my-meta-box7', array(
'title' => __('Post category','blackfyre' ), // the title of the meta box
'pages' => array('slider'),  // post types on which you want the metabox to appear
'context' => 'normal', // meta box context (see above)
'priority' => 'high', // meta box priority (see above)
'fields' => array( // array describing our fields
array(
'name' => __('Select post category for the slider.','blackfyre' ),
'id' => 'my-awesome-field7',
'type' => 'select',
'default' => '1-val',
'options' => blackfyre_select_meta()
),)));

add_smart_meta_box('my-meta-box8', array(
'title' => __('Lock match','blackfyre' ), // the title of the meta box
'pages' => array('wp-clanwars-matches'),  // post types on which you want the metabox to appear
'context' => 'normal', // meta box context (see above)
'priority' => 'high', // meta box priority (see above)
'fields' => array( // array describing our fields
array(
'name' => __('Lock this match.','blackfyre' ),
'id' => 'lock_match',
'type' => 'select',
'default' => '1-val',
'options' => __('Lock', 'blackfyre')
),)));

add_smart_meta_box('my-meta-box9', array(
'title' => __('Slider shortcode (works with "Homepage" template only)','blackfyre' ), // the title of the meta box
'pages' => array('page'),  // post types on which you want the metabox to appear
'context' => 'normal', // meta box context (see above)
'priority' => 'high', // meta box priority (see above)
'fields' => array( // array describing our fields
array(
'name' => __('Paste your slider shortcode here.','blackfyre' ),
'id' => 'slider_short',
'type' => 'textarea',
'default' => ''
),)));

/*prevent headers alread sent*/
function blackfyre_do_output_buffer() {
        ob_start();
}




/*remove slider from home*/
function blackfyre_remove_slider_from_home( $content = null ){
    global $post;
    if( is_page_template('tmp-home.php') ){
        $pattern = get_shortcode_regex();
        preg_match('/'.$pattern.'/s', $content, $matches);
        if ( isset($matches[2]) && is_array($matches) && $matches[2] == 'layerslider') {
            //shortcode is being used
            $content = str_replace( $matches['0'], '', $content );
        }
    }
    return $content;
}



/*get tag name*/
function blackfyre_GetTagName($meta){
    if (is_string($meta) || (is_numeric($meta) && !is_double($meta))
            || is_int($meta)){
                if (is_numeric($meta))
                    $meta = (int)$meta;
                        if (is_int($meta))
                            $TagSlug = get_term_by('id', $meta, 'post_tag');
                        else
                            $TagSlug = get_term_by('slug', $meta, 'post_tag');
                    return $TagSlug->name;
            }
}

/*image resize*/
function blackfyre_aq_resize( $url, $width = null, $height = null, $crop = null, $single = true, $upscale = false ) {

    // Validate inputs.
    if ( ! $url || ( ! $width && ! $height ) ) return false;

    // Caipt'n, ready to hook.
    if ( true === $upscale ) add_filter( 'image_resize_dimensions', 'blackfyre_aq_upscale', 10, 6 );

    // Define upload path & dir.
    $upload_info = wp_upload_dir();
    $upload_dir = $upload_info['basedir'];
    $upload_url = $upload_info['baseurl'];

    $http_prefix = "http://";
    $https_prefix = "https://";

    /* if the $url scheme differs from $upload_url scheme, make them match
       if the schemes differe, images don't show up. */
    if(!strncmp($url,$https_prefix,strlen($https_prefix))){ //if url begins with https:// make $upload_url begin with https:// as well
        $upload_url = str_replace($http_prefix,$https_prefix,$upload_url);
    }
    elseif(!strncmp($url,$http_prefix,strlen($http_prefix))){ //if url begins with http:// make $upload_url begin with http:// as well
        $upload_url = str_replace($https_prefix,$http_prefix,$upload_url);
    }


    // Check if $img_url is local.
    if ( false === strpos( $url, $upload_url ) ) return false;

    // Define path of image.
    $rel_path = str_replace( $upload_url, '', $url );
    $img_path = $upload_dir . $rel_path;

    // Check if img path exists, and is an image indeed.
    if ( ! file_exists( $img_path ) or ! getimagesize( $img_path ) ) return false;

    // Get image info.
    $info = pathinfo( $img_path );
    $ext = $info['extension'];
    list( $orig_w, $orig_h ) = getimagesize( $img_path );

    // Get image size after cropping.
    $dims = image_resize_dimensions( $orig_w, $orig_h, $width, $height, $crop );
    $dst_w = $dims[4];
    $dst_h = $dims[5];

    // Return the original image only if it exactly fits the needed measures.
    if ( ! $dims && ( ( ( null === $height && $orig_w == $width ) xor ( null === $width && $orig_h == $height ) ) xor ( $height == $orig_h && $width == $orig_w ) ) ) {
        $img_url = $url;
        $dst_w = $orig_w;
        $dst_h = $orig_h;
    } else {
        // Use this to check if cropped image already exists, so we can return that instead.
        $suffix = "{$dst_w}x{$dst_h}";
        $dst_rel_path = str_replace( '.' . $ext, '', $rel_path );
        $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}";

        if ( ! $dims || ( true == $crop && false == $upscale && ( $dst_w < $width || $dst_h < $height ) ) ) {
            // Can't resize, so return false saying that the action to do could not be processed as planned.
            return false;
        }
        // Else check if cache exists.
        elseif ( file_exists( $destfilename ) && getimagesize( $destfilename ) ) {
            $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}";
        }
        // Else, we resize the image and return the new resized image url.
        else {

            // Note: This pre-3.5 fallback check will edited out in subsequent version.
            if ( function_exists( 'wp_get_image_editor' ) ) {

                $editor = wp_get_image_editor( $img_path );

                if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
                    return false;

                $resized_file = $editor->save();

                if ( ! is_wp_error( $resized_file ) ) {
                    $resized_rel_path = str_replace( $upload_dir, '', $resized_file['path'] );
                    $img_url = $upload_url . $resized_rel_path;
                } else {
                    return false;
                }

            } else {

                $resized_img_path = wp_get_image_editor( $img_path, $width, $height, $crop ); // Fallback foo.
                if ( ! is_wp_error( $resized_img_path ) ) {
                    $resized_rel_path = str_replace( $upload_dir, '', $resized_img_path );
                    $img_url = $upload_url . $resized_rel_path;
                } else {
                    return false;
                }

            }

        }
    }

    // Okay, leave the ship.
    if ( true === $upscale ) remove_filter( 'image_resize_dimensions', 'blackfyre_aq_upscale' );

    // Return the output.
    if ( $single ) {
        // str return.
        $image = $img_url;
    } else {
        // array return.
        $image = array (
            0 => $img_url,
            1 => $dst_w,
            2 => $dst_h
        );
    }

    return $image;
}


function blackfyre_aq_upscale( $default, $orig_w, $orig_h, $dest_w, $dest_h, $crop ) {
    if ( ! $crop ) return null; // Let the wordpress default function handle this.

    // Here is the point we allow to use larger image size than the original one.
    $aspect_ratio = $orig_w / $orig_h;
    $new_w = $dest_w;
    $new_h = $dest_h;

    if ( ! $new_w ) {
        $new_w = intval( $new_h * $aspect_ratio );
    }

    if ( ! $new_h ) {
        $new_h = intval( $new_w / $aspect_ratio );
    }

    $size_ratio = max( $new_w / $orig_w, $new_h / $orig_h );

    $crop_w = round( $new_w / $size_ratio );
    $crop_h = round( $new_h / $size_ratio );

    $s_x = floor( ( $orig_w - $crop_w ) / 2 );
    $s_y = floor( ( $orig_h - $crop_h ) / 2 );

    return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
}

//add video input field
add_smart_meta_box('my-meta-box77', array(
'title' => __('Video url', 'blackfyre'), // the title of the meta box
'pages' => array('post'),
'context' => 'normal', // meta box context (see above)
'priority' => 'high', // meta box priority (see above)
'fields' => array( // array describing our fields
array(
'name' => __('Put your embed video URL here', 'blackfyre'),
'id' => 'my-awesome-field77',
'type' => 'textarea',
),)));


//woocommerce

function blackfyre_woocommerce_header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;

    ob_start(); ?>
    <a class="cart-contents" href="<?php echo esc_url($woocommerce->cart->get_cart_url()); ?>"><div class="cart-icon-wrap"><i class="fa fa-shopping-cart"></i> <div class="cart-wrap"><span><?php echo esc_attr($woocommerce->cart->cart_contents_count); ?> </span></div> </div></a>
    <?php

    $fragments['a.cart-contents'] = ob_get_clean();

    return $fragments;
}

//ajax comments
function blackfyre_ajaxify_comments($comment_ID, $comment_status){
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
        switch($comment_status){
            case "0":
            wp_notify_moderator($comment_ID);
            case "1": //Approved comment
            _e("success","blackfyre");
            $commentdata =& get_comment($comment_ID, ARRAY_A);
            $post =& get_post($commentdata['comment_post_ID']);
            wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
            break;
            default:
            _e("error",'blackfyre');
        }
    exit;
    }
}

//multiple featured images
  if (class_exists('BlackfyreMultiPostThumbnails')) {

                 new BlackfyreMultiPostThumbnails(
                    array(
                        'label' => 'Header Image',
                        'id' => 'header-image',
                        'post_type' => 'page'
                    )
                );

                 new BlackfyreMultiPostThumbnails(
                    array(
                        'label' => 'Header Image',
                        'id' => 'header-image-post',
                        'post_type' => 'post'
                    )
                );
            }
function blackfyre_change_mce_options( $init ) {
    // Command separated string of extended elements
    $ext = 'pre[id|name|class|style]';

    // Add to extended_valid_elements if it alreay exists
    if ( isset( $init['extended_valid_elements'] ) ) {
        $init['extended_valid_elements'] .= ',' . $ext;
    } else {
        $init['extended_valid_elements'] = $ext;
    }

    // Super important: return $init!
    return $init;
}


function blackfyre_get_category_id($cat_name){
    $term = get_term_by('name', $cat_name, 'category');
    return $term->term_id;
}

add_shortcode("blackfyre_slider", "blackfyre_simple_display_slider");
function blackfyre_simple_display_slider($attr,$content) {
    global $post;
    extract(shortcode_atts(array(
            'id' => ''
            ), $attr));

     echo '
        <div class="slider-wrapper">
        <div class="slider-left-wall"></div>
        <div class="slider-right-wall"></div>
        <div class="net"></div>
        <div class="slider-text-wrapper">
            <img alt="" class="slider-pick" src="'.esc_url(get_template_directory_uri()).'/img/pick.png" />
            <div class="slider_text slantybox">
            </div>
            <div class="bx-controls-direction">
                <a class=" bx-next-out"></a>
            </div>
        </div>
        <div class="slider_text_src" style="display: none;"><ul>';

    if(get_post_meta($id, '_smartmeta_my-awesome-field7', true) == 'Do not use post slider'){

        if( get_field('field_53f5d4c019b0c', $id) )
    {

        $idc = 1;
        while( the_repeater_field('field_53f5d4c019b0c', $id) )
        {
            $img_desc = get_sub_field('image_description');
            echo '<li data-id="'.esc_attr($idc).'">'.html_entity_decode($img_desc).'</li>';
            $idc ++;
        }

    }

    }else{

        $category_ID = blackfyre_get_category_id(get_post_meta($id, '_smartmeta_my-awesome-field7', true));
        $the_query = new WP_Query( 'showposts=5&cat='.$category_ID );
        $idc = 1;
        if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
            $num_comments = get_comments_number(); // get_comments_number returns only a numeric value

            if ( comments_open() ) {
                if ( $num_comments == 0 ) {
                    $comments = __('No Comments', 'blackfyre');
                } elseif ( $num_comments > 1 ) {
                    $comments = $num_comments . __(' Comments', 'blackfyre');
                } else {
                    $comments = __('1 Comment', 'blackfyre');
                }
                $write_comments = '<a href="' . get_comments_link() .'">'. $comments.'</a>';
            } else {
                $write_comments =  __('Comments are off for this post.', 'blackfyre');
            }
             echo '<li data-id="'.$idc.'"><a href ="'.esc_url(get_the_permalink()).'">'.substr(get_the_title(), 0, 55).'...</a><div class="slider_com_wrap"><i class="fa fa-comments"></i>'.$write_comments.'</div></li>';
             $idc ++;
        endwhile; endif;
    }
    echo '</ul></div><ul class="bxslider">';

    if(get_post_meta($id, '_smartmeta_my-awesome-field7', true) == 'Do not use post slider'){

    if( get_field('field_53f5d4c019b0c', $id) )
    {

        $idc = 1;
        while( the_repeater_field('field_53f5d4c019b0c', $id) )
        {
            $img_url = get_sub_field('slider_image');
            $image = blackfyre_aq_resize( $img_url['url'], 585, 340, true, '', true );
            echo '<li data-id="'.$idc.'"><img alt="img" src="'.esc_url($image[0]).'" /></li>';
            $idc ++;
        }

    }

    }else{

        $category_ID = blackfyre_get_category_id(get_post_meta($id, '_smartmeta_my-awesome-field7', true));
        $the_query = new WP_Query( 'showposts=5&cat='.$category_ID );
        $idc = 1;
        if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
             $thumb = get_post_thumbnail_id($post->ID);
             $img_url = wp_get_attachment_url( $thumb,'full'); //get img URL
             $image = blackfyre_aq_resize( $img_url, 585, 340, true, '', true ); //resize & crop img
             echo '<li data-id="'.$idc.'"><img alt="img" src="'.esc_url($image[0]).'" /></li>';
             $idc ++;
        endwhile; endif;
    }
   echo '</ul>';
   echo '<div class="next_slide_text"><i class="fa fa-bolt"></i><strong>'.__("Next:", "blackfyre").'</strong><div class="next_slide_text_inner"> </div></div></div>';



}



function blackfyre_register_slider() {
    $labels = array(
        'name' => 'All Slide',
        'menu_name' => 'Blackfyre Sliders',
        'add_new' => 'Add New Slider',
        'add_new_item' => 'Add New Slide',
        'edit_item' => 'Edit Slide'

    );
    $args = array(

        'labels' => $labels,
        'hierarchical' => true,
        'description' => 'Slideshows',
        'supports' => array('title'),
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'show_in_nav_menus' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'has_archive' => true,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => true,
        'capability_type' => 'post'
    );
    register_post_type('slider', $args);
}


function blackfyre_set_custom_edit_slider_columns($columns) {
    return $columns
    + array('slider_shortcode' => __('Shortcode', 'blackfyre'));
}

function blackfyre_custom_slider_column($column, $post_id) {
    $slider_meta = get_post_meta($post_id, "_blackfyre_slider_meta", true);
    $slider_meta = ($slider_meta != '') ? json_decode($slider_meta) : array();

    switch ($column){
        case 'slider_shortcode':
            echo "[blackfyre_slider id=$post_id]";
        break;
    }
}

function blackfyre_save_slider_info($post_id) {
    if(isset($_POST['blackfyre_slider_box_nonce']) && $_POST['post_type'])
    {
        if (!wp_verify_nonce($_POST['blackfyre_slider_box_nonce'], basename(__FILE__))){
            return $post_id;
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
            return $post_id;
        }
        if ('slider' == $_POST['post_type'] && current_user_can('edit_post', $post_id)){
            $gallery_images = (isset($_POST['gallery_img']) ? $_POST['gallery_img'] : '');
            $gallery_images = strip_tags(json_encode($gallery_images));
            update_post_meta($post_id, "_simple_gallery_images", $gallery_images);
        }else{
            return $post_id;
        }
    }

}

/*insert slider post*/
if ( is_admin() && isset($_GET['activated'] ) && $pagenow == "themes.php" ) {

    $post = array(
      'post_content'   => '',
      'post_name'      => 'acf_image',
      'post_title'     => 'Image ',
      'post_status'    =>'publish',
      'post_type'      => 'blackfyre',
      'post_author'    => 1,
      'ping_status'    =>'closed',
      'post_parent'    => 0,
      'menu_order'     => 0,
      'comment_status' => 'closed'
    );

    $post_ID = wp_insert_post( $post );

     add_post_meta($post_ID, 'field_53f5d4c019b0c', 'a:13:{s:3:"key";s:19:"field_53f5d4c019b0c";s:5:"label";s:13:"Slider images";s:4:"name";s:13:"slider_images";s:4:"type";s:8:"repeater";s:12:"instructions";s:0:"";s:8:"required";s:1:"0";s:10:"sub_fields";a:2:{i:0;a:12:{s:3:"key";s:19:"field_53f5fbbfce05e";s:5:"label";s:12:"Slider image";s:4:"name";s:12:"slider_image";s:4:"type";s:5:"image";s:12:"instructions";s:0:"";s:8:"required";s:1:"0";s:12:"column_width";s:0:"";s:11:"save_format";s:6:"object";s:12:"preview_size";s:9:"thumbnail";s:7:"library";s:3:"all";s:17:"conditional_logic";a:3:{s:6:"status";s:1:"0";s:5:"rules";a:1:{i:0;a:3:{s:5:"field";s:4:"null";s:8:"operator";s:2:"==";s:5:"value";s:0:"";}}s:8:"allorany";s:3:"all";}s:8:"order_no";i:0;}i:1;a:14:{s:3:"key";s:19:"field_53f60a628666a";s:5:"label";s:17:"Image description";s:4:"name";s:17:"image_description";s:4:"type";s:8:"textarea";s:12:"instructions";s:0:"";s:8:"required";s:1:"0";s:12:"column_width";s:0:"";s:13:"default_value";s:0:"";s:11:"placeholder";s:0:"";s:9:"maxlength";s:0:"";s:4:"rows";s:0:"";s:10:"formatting";s:2:"br";s:17:"conditional_logic";a:3:{s:6:"status";s:1:"0";s:5:"rules";a:1:{i:0;a:2:{s:5:"field";s:4:"null";s:8:"operator";s:2:"==";}}s:8:"allorany";s:3:"all";}s:8:"order_no";i:1;}}s:7:"row_min";s:0:"";s:9:"row_limit";s:0:"";s:6:"layout";s:5:"table";s:12:"button_label";s:9:"Add Image";s:17:"conditional_logic";a:3:{s:6:"status";s:1:"0";s:5:"rules";a:1:{i:0;a:2:{s:5:"field";s:4:"null";s:8:"operator";s:2:"==";}}s:8:"allorany";s:3:"all";}s:8:"order_no";i:0;}', true);
     add_post_meta($post_ID, 'position', 'normal', true);
     add_post_meta($post_ID, 'layout', 'no_box', true);
     add_post_meta($post_ID, 'hide_on_screen', '', true);
     add_post_meta($post_ID, 'rule', 'a:5:{s:5:"param";s:9:"post_type";s:8:"operator";s:2:"==";s:5:"value";s:6:"slider";s:8:"order_no";i:0;s:8:"group_no";i:0;}', true);

}


/*****social login*****/
function blackfyre_social_createoptions() {
    $siteurl = get_site_url();
    $holdtheme = get_template_directory();
    $thetheme = explode("/", $holdtheme);
    $nametheme = $thetheme[count($thetheme) -1];
    if (substr($siteurl, -1) != "/") {
        $siteurl .= "/";
    }  //add trailing slash
        if ( !empty( $_SERVER['HTTPS'] ) ) {
            $siteurl = str_replace("http://", "https://", $siteurl);
        }

    $baseurl = $siteurl.'wp-content/themes/'.$nametheme.'/include/';
    if ( !empty( $_SERVER['HTTPS'] ) ) {
            $baseurl = str_replace("http://", "https://", $baseurl);
        }
    $redirecturl = $siteurl.'wp-content/themes/'.$nametheme.'/include/handler/index.php';

    return
      array(
        "base_url" => $baseurl,
        "redirect_url" => $redirecturl,
        "redirect_uri" => $redirecturl,
        "providers" => array (
            // openid providers
            "OpenID" => array (
                "enabled" => true
            ),
            "Facebook" => array (
                "enabled" => true,
                "keys"    => array ( "id" => of_get_option('facebook_app'), "secret" => of_get_option('facebook_secret') )
            ),

            "Twitter" => array (
                "enabled" => true,
                "keys"    => array ( "key" =>  of_get_option('twitter_app'), "secret" =>  of_get_option('twitter_secret'))
            ),

           "Google" => array (
                "enabled" => true,
                 "keys"    => array ( "id" =>  of_get_option('google_app'), "secret" =>  of_get_option('google_secret'))
            ),

            "TwitchTV" => array (
                "enabled" => true,
                 "keys"    => array ( "id" =>  of_get_option('twitch_client_id'), "secret" =>  of_get_option('twitch_secret'))
            ),
            "Steam" => array (
                "enabled" => true,
                 "keys"    => array ( "key" =>  of_get_option('steam_app'))
            ),
        ),


        // if you want to enable logging, set 'debug_mode' to true  then provide a writable file by the web server on "debug_file"
        "debug_mode" => false,

        "debug_file" => ""
    );
}


/*handle sessions in wordpress*/
function blackfyre_myStartSession() {
    global $wpdb; // hook the wp db
    global $usermeta;
    if(!session_id()) { //if there's no session, start it
       @session_start();
    }
    $wordpress_user = wp_get_current_user();

    if (!((!isset ($wordpress_user)) OR ($wordpress_user->ID == 0))) {
        $usermeta = get_user_meta($wordpress_user->ID);
    }


}



/*ends session*/
function blackfyre_myEndSession() {
    session_destroy ();
}

//This function allows multiple same emails, to allow social accounts to be unlinked
function blackfyre_skip_email_exist($user_email){
    define( 'WP_IMPORTING', 'BLACKFYRE_SKIP_EMAIL_EXIST' );
    return $user_email;
}

function blackfyre_be_gravatar_filter($avatar, $id_or_email, $size, $default, $alt) {
    if (is_int($id_or_email)) {
        $custom_avatar = get_the_author_meta('profile_photo', $id_or_email);
    } else {
        $custom_avatar = get_the_author_meta('profile_photo');
    }

    if ($custom_avatar)
        $return = '<img src="'.$custom_avatar.'" width="'.$size.'" height="'.$size.'" alt="'.$alt.'" />';
    elseif ($avatar)
        $return = $avatar;
    else
        $return = '<img src="'.$default.'" width="'.$size.'" height="'.$size.'" alt="'.$alt.'" />';

    return $return;
}



//register custom pages, prep function
function blackfyre_get_ID_by_slug($page_slug) {
    $page = get_page_by_path($page_slug);
    if ($page) {
        return $page->ID;
    } else {
        return null;
    }
}


/***** add country option to profile *****/
add_action('after_setup_theme', 'blackfyre_country');
function blackfyre_country() {
      include_once(TEMPLATEPATH.'/themeOptions/admin/country/usercountry.php');
}

/** add country field to registration page **/
function blackfyre_registration_country_list() {
    global $wpdb;
    $table = $wpdb->prefix."user_countries";
    $countries = $wpdb->get_results( "SELECT * FROM $table ORDER BY `name`");
    return $countries;
}

/*remove profile tab from subnav*/
function blackfyre_remove_profile_subnav() {
    if ( is_plugin_active('buddypress/bp-loader.php') && function_exists( 'bp_core_remove_subnav_item' ) ) {
        global $bp;
        if ( $bp->current_component == $bp->settings->slug ) {
            bp_core_remove_subnav_item( $bp->settings->slug, 'profile' );
        }
    }
}


/*ajax call for user profile picture*/
function blackfyre_update_user_profile_pic_callback() {
    $url = $_POST['file'];
    update_user_meta(bp_displayed_user_id(), 'profile_photo', $url);
    _e("Profile picture updated successfully!", "blackfyre");
    wp_die(); // this is required to terminate immediately and return a proper response
}

/*ajax call for clan banner picture*/
function blackfyre_update_user_clan_bg_callback() {
    $url = $_POST['file'];
    $p_id = $_POST['idp'];
    update_post_meta($p_id, 'clan_bg', $url);
    _e("Clan banner updated successfully!", "blackfyre");
    wp_die(); // this is required to terminate immediately and return a proper response
}

/*ajax call for clan page background*/
function blackfyre_update_page_bg_callback() {
    $url = $_POST['file'];
    $p_id = $_POST['idp'];
    update_post_meta($p_id, 'clan_page_bg', $url);
    _e("Clan page background updated successfully!", "blackfyre");
    ?>
    <script>
        var bck_btn =  jQuery('#change_page_bg_pic');
        bck_btn.after(' <a class="ajaxdeletebck" href="javascript:void(0);" data-pid="<?php echo esc_attr($p_id); ?>" ><i data-original-title="<?php _e("Delete Background", "blackfyre");?>" data-toggle="tooltip" data-placement="right" class="fa fa-times"></i></a>');
    </script>
    <?php
    wp_die(); // this is required to terminate immediately and return a proper response
}


/*ajax call for user profile picture*/
function blackfyre_update_user_profile_bg_callback() {
    $url = $_POST['file'];
    update_user_meta(bp_displayed_user_id(), 'profile_bg', $url);
    _e("Profile background updated successfully!", "blackfyre");
    wp_die(); // this is required to terminate immediately and return a proper response
}


/*ajax call for user clan picture*/
function blackfyre_update_clan_pic_callback() {
    $url = $_POST['file'];
    $p_id = $_POST['idp'];
    update_post_meta($p_id, 'clan_photo', $url);
    _e("Clan photo updated successfully!", "blackfyre");
    wp_die(); // this is required to terminate immediately and return a proper response
}

/*Add friend button classes and text*/
function blackfyre_add_friend_link_text($button) {
    $fricon_remove = '<i class="fa fa-times" data-original-title="'.__("Remove friend", "blackfyre").'" data-toggle="tooltip"></i>';
    $fricon_add = '<i class="fa fa-user"></i>';
    $fricon_cancel = '<i class="fa fa-times" data-original-title="'.__("Cancel request!", "blackfyre").'" data-toggle="tooltip"></i>';

    switch ( $button['id'] ) {
        case 'pending' :
            $button['link_text'] = $fricon_cancel.__(' Cancel request!', 'blackfyre');
            $button['link_title'] = 'Cancel friend request';
            $button['link_class'] .= ' add-friend';
        break;

        case 'is_friend' :
            $button['link_text'] = $fricon_remove.__(' Remove friend!', 'blackfyre');;
            $button['link_class'] .= ' add-friend';
        break;

        default:
            $button['link_text'] = $fricon_add.__(' Add as a friend!', 'blackfyre');
            $button['link_title'] = 'Add as a friend';
            $button['link_class'] .= ' add-friend';
    }
    return $button;
}


/*add font awesome into buddypress navigation*/
function blackfyre_mb_profile_menu_tabs(){
global $bp;
$profile_icon = '<i class="fa fa-user"></i>';
$notifications_icon = '<i class="fa fa-flag"></i>';
$messages_icon = '<i class="fa fa-comments-o"></i>';
$friends_icon = '<i class="fa fa-users"></i>';
$settings_icon = '<i class="fa fa-cog"></i>';
$activity_icon = '<i class="fa fa-bolt"></i>';
$forums_icon = '<i class="fa fa-forumbee"></i>';
$groups_icon = '<i class="fa fa-users"></i>';

$bp->bp_nav['profile']['name'] = $profile_icon.__(' profile', 'blackfyre');
$bp->bp_nav['profile']['position'] = 10;
if ( bp_is_active( 'activity' ) )$bp->bp_nav['activity']['name'] = $activity_icon.__(' activity', 'blackfyre');
if ( bp_is_active( 'notifications' ) )$bp->bp_nav['notifications']['name'] = $notifications_icon.__(' notifications', 'blackfyre');
if ( bp_is_active( 'messages' ) )$bp->bp_nav['messages']['name'] = $messages_icon.__(' messages', 'blackfyre');
if ( bp_is_active( 'friends' ) )$bp->bp_nav['friends']['name'] = $friends_icon.__(' friends', 'blackfyre');
if ( bp_is_active( 'settings' ) )$bp->bp_nav['settings']['name'] = $settings_icon.__(' settings', 'blackfyre');
$bp->bp_nav['forums']['name'] = $forums_icon.__(' forums', 'blackfyre');
if ( bp_is_active( 'groups' ) )$bp->bp_nav['groups']['name'] = $groups_icon.__(' groups', 'blackfyre');

}


/*register clan custom post type*/
function blackfyre_clan_create_post_type() {
    register_post_type( 'clan',
        array(
            'labels' => array(
                'name' => __( 'Clans', 'blackfyre' ),
                'singular_name' => __( 'Clan', 'blackfyre' )
            ),
        'supports' => array( 'title', 'editor', 'shortlinks', 'comments' ),
        'public' => true,
        'publicly_queryable' => true,
        'rewrite' => true,
        'has_archive' => false,
        'query_var' => true,
        'menu_icon' => get_template_directory_uri() . '/img/clans.png',
        )
    );
}


/*create redirection for new post*/
function blackfyre_redirect(){
    $user_id = $_POST['idc'];
    $post_data = array(
    'post_title'    => 'Clan name',
    'post_type'     => 'clan',
    'post_content'  => '',
    'post_status'   => 'auto-draft',
    'post_author'   => $user_id
);

// insert the post into the database
$post_id = wp_insert_post( $post_data );
//$uid = array();
//$pid =  array();
//$uid['id'] = $user_id;
//$uid['status'] = 1;
//$pid[] = $post_id;
//add_post_meta($post_id, 'admin', $uid);
//add_user_meta($user_id, 'clan', $pid);

#--------- 1. varijanta ----------
$post_arr['super_admin'] = $user_id;
$post_arr['admins'] = array();
$arr['active'] = array();
$arr['pending'] = array();
$post_arr['users'] = $arr;
add_post_meta($post_id, 'clan', $post_arr);
add_user_meta($user_id, 'clan_post_id', $post_id);
#-------------------------------------------

echo json_encode($post_id);
exit();
}


/*on clan delete update metas*/
function blackfyre_onclan_delete($post_id) {
    global $wpClanWars;
    $post = get_post($post_id);
    $user = get_users(array('meta_key' => 'clan_post_id', 'meta_value' => $post_id));
    if ($post->post_type == 'clan') {
        delete_user_meta($user[0]->ID, 'clan_post_id', $post_id);
        $id = blackyfyre_return_team_id_by_post_id($post_id);
        $wpClanWars->delete_team($id[0]->id);
       }
}

/*on clan publish*/
function blackfyre_onclan_publish($post_id) {
    global $wpClanWars;
    $id = blackyfyre_return_team_id_by_post_id($post_id);
    $post = get_post($post_id);
    if ($post->post_type == 'clan') {
    $imgurl =  get_post_meta( $post_id, 'clan_photo', true );
    $arr = array(
            'title' => $post->post_title,
            'logo' => blackfyre_get_attachment_id($imgurl),
            'post_id' => $post_id
    );
          if(empty($id[0]->id)){$wpClanWars->add_team($arr);}else{ $wpClanWars->update_team($id[0]->id, $arr);}
       }
}

/*MATCHES FUNCTIONS*/
function blackyfyre_return_match_locked($post_id){
     global $wpdb;
     $matches = $wpdb->prefix."cw_matches";
     $rslt = $wpdb->get_results( $wpdb->prepare("SELECT locked FROM $matches where `post_id` = %s",$post_id ));
     return $rslt[0];
}
function blackyfyre_return_match_status($post_id){
     global $wpdb;
     $matches = $wpdb->prefix."cw_matches";
     $rslt = $wpdb->get_results($wpdb->prepare("SELECT status FROM $matches where `post_id` = %s",$post_id));
     return $rslt[0];
}
function blackyfyre_return_all_clan_matches($clan_id){
     global $wpdb;
     $matches = $wpdb->prefix."cw_matches";
     $rslt = $wpdb->get_results($wpdb->prepare("SELECT * FROM $matches where (`team1` = %s or `team2` = %s) and (`status` = 'active' or `status` = 'submitted1' or `status` = 'submitted2' or `status` = 'deleted1' or `status` = 'deleted2' or `status` = 'done') ORDER BY `date` DESC",$clan_id,$clan_id));
     return $rslt;
}

function blackyfyre_return_match_id_by_post_id($post_id){
     global $wpdb;
     $matches = $wpdb->prefix."cw_matches";
     $rslt = $wpdb->get_results($wpdb->prepare("SELECT `id` FROM $matches where `post_id` = %s",$post_id));
     return $rslt;
}

function blackyfyre_return_match_reported_by_match_id($match_id){
     global $wpdb;
     $matches = $wpdb->prefix."cw_matches";
     $rslt = $wpdb->get_results($wpdb->prepare("SELECT `reported_reason` FROM $matches where `id` = %s", $match_id));
     return $rslt[0];
}

function blackyfyre_return_post_id_by_match_id($match_id){
     global $wpdb;
     $teams = $wpdb->prefix."cw_teams";
     $rslt = $wpdb->get_results($wpdb->prepare("SELECT `post_id` FROM $teams where `id` = %s", $match_id));
     return $rslt[0];
}

function blackyfyre_return_match_score($match_id){
    global $wpdb;
    $rounds = $wpdb->prefix."cw_rounds";
    $teams = $wpdb->prefix."cw_teams";
    $matches = $wpdb->prefix."cw_matches";
    $games = $wpdb->prefix."cw_games";
    $rslt = $wpdb->get_results($wpdb->prepare(
                    "SELECT t1.id,
                            (SELECT SUM(sumt1.tickets1) FROM $rounds AS sumt1 WHERE sumt1.match_id = t1.id) AS team1_tickets,
                            (SELECT SUM(sumt2.tickets2) FROM $rounds AS sumt2 WHERE sumt2.match_id = t1.id) AS team2_tickets

                     FROM $matches AS t1
                     LEFT JOIN $games AS t2 ON t1.game_id=t2.id
                     LEFT JOIN $teams AS tt1 ON t1.team1=tt1.id
                     LEFT JOIN $teams AS tt2 ON t1.team2=tt2.id where t1.id = %s", $match_id));
     return $rslt;
}



/*CHALLENGES FUNCTIONS*/
function blackyfyre_return_all_clan_challenges($clan_id){
     global $wpdb;
     $matches = $wpdb->prefix."cw_matches";
     $rslt = $wpdb->get_results($wpdb->prepare("SELECT * FROM $matches where (`team1` = %s or `team2` = %s) and `status` = 'pending' ORDER BY `date` ASC", $clan_id, $clan_id));
     return $rslt;
}

function blackyfyre_return_challenge_matches_team2($clan_id){
     global $wpdb;
     $matches = $wpdb->prefix."cw_matches";
     $rslt = $wpdb->get_results($wpdb->prepare("SELECT * FROM $matches where `team2` = %s and `status` = 'pending' ORDER BY `date` ASC", $clan_id));
     return $rslt;
}

function blackyfyre_return_challenge_matches_team1($clan_id){
     global $wpdb;
     $matches = $wpdb->prefix."cw_matches";
     $rslt = $wpdb->get_results($wpdb->prepare("SELECT * FROM $matches where `team1` = %s and `status` = 'pending' ORDER BY `date` ASC",$clan_id ));
     return $rslt;
}


/*CLAN FUNCTIONS*/

function blackfyre_add_user_to_clan($user_id, $post_id){
    $post_arr = get_post_meta( $post_id, 'clan', true );
    $usr_meta = get_user_meta( $user_id, 'clan_post_id', true);

    $is_member = ($usr_meta==$post_id) ? true : false;
    if(!$is_member) {
        $post_arr['admins'][] = $user_id;
        update_post_meta($post_id, 'clan', $post_arr);
        update_user_meta($user_id, 'clan_post_id', $post_id);
    }
}

function blackfyre_clan_members($post_id=false, $currentPage=1){
    global $current_user;

    $membersa = array();
    $membersu = array();
    $members = array();
    $post_meta_arr = get_post_meta( $post_id, 'clan', true );

    $usr_meta = get_user_meta( $current_user->ID, 'clan_post_id', true);
    $su_admin = ( isset( $post_meta_arr['super_admin'] ) && $post_meta_arr['super_admin'] == $current_user->ID ) ? true : false;
    if ( $su_admin || ( ( isset( $post_meta_arr['admins'] ) && is_array( $post_meta_arr['admins'] ) && in_array( $current_user->ID, $post_meta_arr['admins'] ) ) || ( isset( $post_meta_arr['admins'] ) && $current_user->ID == $post_meta_arr['admins'] ) ) ) {
    	if ( is_array( $post_meta_arr['users']['pending'] ) ) {
	    	foreach( $post_meta_arr['users']['pending'] as $item ) {
	        	$membersu[] = $item;
	        }
    	} elseif ( ! empty( $post_meta_arr['users']['pending'] ) ) {
	    	$membersu[] = $post_meta_arr['users']['pending'];
    	}
    }
	
	if ( isset( $post_meta_arr['super_admin'] ) ) {
		$membersa[0] = $post_meta_arr['super_admin'];	
	}
    
    if ( isset( $post_meta_arr['admins'] ) ) {
    	if ( is_array( $post_meta_arr['admins'] ) ) {
		    foreach( $post_meta_arr['admins'] as $item ){
		    	$membersu[] = $item;
		    }
	    } elseif ( ! empty( $post_meta_arr['admins'] ) ) {
		    $membersu[] = $post_meta_arr['admins'];
	    }   
    }
    
    if ( isset( $post_meta_arr['users']['active'] ) ) {
    	if ( is_array( $post_meta_arr['users']['active'] ) ) {
		    foreach( $post_meta_arr['users']['active'] as $item ) {
		    	$membersu[] = $item;
		    }
	    } elseif ( ! empty( $post_meta_arr['users']['active'] ) ) {
		    $membersu[] = $post_meta_arr['users']['active'];
	    }   
    }

    $members = array_merge($membersa,$membersu);
    end($members);
    $last_key = key($members);
    reset($members);

    $members_count = count($members);
    $members_per_page = 20;

    if ($members_count==0) return false;

    include "addons/pagination/pagination.class.php";
    $p = new blackfyre_pagination;
    $p->items($members_count);
    $p->limit($members_per_page);
    $p->parameterName('members_list_page');
    $p->currentPage($currentPage);
    $p->nextLabel(__('Next','blackfyre'));
    $p->prevLabel(__('Previous','blackfyre'));
    ?>

    <?php if(blackfyre_is_admin($post_id,$current_user->id)){ ?>
    <ul id="members-list" class="item-list">
    <?php }else{ ?>
     <ul id="members-list" class="item-list third_user" >
    <?php } ?>
    <?php
        for ($x=0; $x<$members_per_page; $x++) {
            $position = (int) ($currentPage-1) * $members_per_page + $x;

            $member = get_userdata($members[$position]);

            blackfyre_clan_members_links($member,$post_meta_arr, $post_id, $su_admin);

            if ( $position >= $last_key ) break;
        }
    ?>


    </ul>
 <div class="clear"></div>
    <?php  if ($members_count > $members_per_page) : ?>
    <div id="pag-bottom" class="pagination">
            <?php $p->show(); ?>
    </div>
   <?php  endif ; ?>
<?php }

function blackfyre_clan_members_links($member, $post_meta_arr, $post_id, $su_admin){ global $current_user; ?>

    <?php if ( isset( $post_meta_arr['users']['pending'] ) && ( ( is_array( $post_meta_arr['users']['pending'] ) && in_array( $member->ID, $post_meta_arr['users']['pending'] ) ) || $member->ID == $post_meta_arr['users']['pending'] ) ) : ?>
        <li class="pending <?php echo esc_attr($member->ID); ?>">
    <?php else : ?>
           <?php if($member->ID == $current_user->ID || ( isset( $post_meta_arr['super_admin'] ) && $member->ID == $post_meta_arr['super_admin'] ) ){ ?>

           <li class="<?php echo esc_attr($member->ID); ?> third_user">

            <?php }else{ ?>
           <li class="<?php echo esc_attr($member->ID); ?>">
            <?php } ?>
    <?php endif;?>

        <?php    $url0 = get_user_meta($member->ID, 'profile_photo', true);
                 if(!empty($url0)){
                   $url1 = blackfyre_aq_resize( $url0, 50, 50, true, '', true );
                   $url = $url1[0];  //resize & crop img
                 }
                 if(empty($url)){ $url = '//gravatar.com/avatar/ccf2e856d472e2211ace58458850aaee?d=mm&amp;s=50&amp;r=G'; }

         ?>
        <div class="member-list-wrapper">
            <div class="item-avatar">
               <a href="<?php echo esc_url(bp_core_get_user_domain( $member->ID )); ?>">
                <img alt="img" src="<?php echo esc_url($url); ?>" class="avatar">
               </a>
            </div>

            <div class="item">
                <div class="item-title">
                    <a href="<?php echo esc_attr(bp_core_get_user_domain( $member->ID )); ?>"><?php echo esc_attr($member->display_name); ?></a>
                    <div class="item-meta"><span class="activity"><?php _e("Joined: ","blackfyre"); ?><?php echo floor((strtotime("now")-strtotime($member->user_registered))/3600/24)?><?php _e(" days ago","blackfyre"); ?></span></div>
                </div>
            </div>

            <?php if(in_array($member->ID, $post_meta_arr['admins']) or ($member->ID == $post_meta_arr['super_admin'])):?>
                <div class="is-admin" data-original-title="Admin" data-toggle="tooltip" ><i class="fa-star fa"></i></div>
            <?php endif;?>

            <?php if(in_array($member->ID, $post_meta_arr['users']['pending'])):?>
                <div class="pending-text"><?php _e("Pending","blackfyre"); ?></div>
            <?php endif;?>

            <div class="clear"></div>
        </div>

    <div class="member-list-more">

    <?php if($su_admin): ?>

        <?php /* SUPER ADMIN BEGIN */?>
        <?php if( in_array($member->ID, $post_meta_arr['admins']) || in_array($member->ID, $post_meta_arr['users']['active']) ):?>
            <div class="mlm1">
                <a class="ajaxloadremoveadmin" href="javascript:void(0);" data-req="remove_friend_admin" data-pid="<?php echo esc_attr($post_id); ?>" data-uid="<?php echo esc_attr($member->ID); ?>">
                    <i class="fa fa-times"></i> <?php _e('Remove user','blackfyre');?>
                </a>
            </div>
        <?php endif;?>

        <?php if(in_array($member->ID, $post_meta_arr['users']['active'])):?>
            <div class="mlm2 u">
                <a class="ajaxloadmakeadmin" href="javascript:void(0);" data-req="make_administrator" data-pid="<?php echo esc_attr($post_id); ?>" data-uid="<?php echo esc_attr($member->ID); ?>">
                    <i class="fa fa-chevron-up"></i> <?php _e('Make administrator','blackfyre');?>
                </a>
            </div>
        <?php elseif(in_array($member->ID, $post_meta_arr['admins'])): ?>
            <div class="mlm2">
                <a class="ajaxloaddowngrade" href="javascript:void(0);" data-req="downgrade_to_user" data-pid="<?php echo esc_attr($post_id); ?>" data-uid="<?php echo esc_attr($member->ID); ?>">
                    <i class="fa fa-chevron-down"></i> <?php _e('Downgrade to user','blackfyre');?>
                </a>
            </div>
        <?php endif;?>

        <?php if(in_array($member->ID, $post_meta_arr['users']['pending'])):?>
            <div class="mlm1 mj"><?php _e('Let this member join?','blackfyre');?>
                <a class="ajaxloadletjoin" href="javascript:void(0);" data-req="let_this_member_join" data-pid="<?php echo esc_attr($post_id); ?>" data-uid="<?php echo esc_attr($member->ID); ?>"><i class="fa fa-check"></i></a>
                <a class="ajaxloadremoveadmin" href="javascript:void(0);" data-req="remove_friend_admin" data-pid="<?php echo esc_attr($post_id); ?>" data-uid="<?php echo esc_attr($member->ID); ?>"><i class="fa fa-times"></i></a>
            </div>
        <?php endif;?>
        <?php /* SUPER ADMIN END */?>



    <?php elseif(!$su_admin && in_array($current_user->ID, $post_meta_arr['admins']) ):?>

        <?php /* ADMIN BEGIN */?>
        <?php if( in_array($member->ID, $post_meta_arr['users']['active']) ):?>
            <div class="mlm1">
                <a class="ajaxloadremoveadmin" href="javascript:void(0);" data-req="remove_friend_admin" data-pid="<?php echo esc_attr($post_id); ?>" data-uid="<?php echo esc_attr($member->ID); ?>">
                    <i class="fa fa-times"></i> <?php _e('Remove user','blackfyre');?>
                </a>
            </div>
            <div class="mlm2 u">
                <a class="ajaxloadmakeadmin" href="javascript:void(0);" data-req="make_administrator" data-pid="<?php echo esc_attr($post_id); ?>" data-uid="<?php echo esc_attr($member->ID); ?>">
                    <i class="fa fa-chevron-up"></i> <?php _e('Make administrator','blackfyre');?>
                </a>
            </div>
        <?php endif;?>


        <?php if(in_array($member->ID, $post_meta_arr['users']['pending'])):?>
            <div class="mlm1 mj"><?php _e('Let this member join?','blackfyre');?>
                <a class="ajaxloadletjoin" href="javascript:void(0);" data-req="let_this_member_join" data-pid="<?php echo esc_attr($post_id); ?>" data-uid="<?php echo esc_attr($member->ID); ?>"><i class="fa fa-check"></i></a>
                <a class="ajaxloadremoveadmin" href="javascript:void(0);" data-req="remove_friend_admin" data-pid="<?php echo esc_attr($post_id); ?>" data-uid="<?php echo esc_attr($member->ID); ?>"><i class="fa fa-times"></i></a>
            </div>
        <?php endif;?>
        <?php /* ADMIN END */?>


    <?php endif;?>
    </div>
    </li>
<?php }


function blackfyre_is_member($post_id=false, $user_id=false){
    if ($post_id==false && $user_id==false) return false;
    $post_meta_arr = get_post_meta( $post_id, 'clan', true );
    $usr_meta = get_user_meta( $user_id, 'clan_post_id');
    $is_member = (in_array($post_id,$usr_meta)) ? true : false;
    return $is_member;
}

function blackfyre_is_member_of_any_clan($user_id=false){
    if ($user_id==false) return false;
    $usr_meta = get_user_meta( $user_id, 'clan_post_id');
    foreach ($usr_meta as $usr_m) {
        if(blackfyre_is_super_admin($usr_m,$user_id) or blackfyre_is_user($usr_m,$user_id) or blackfyre_is_admin($usr_m,$user_id)){
            $clanje = true;
        }
    }
    $is_member = $clanje ? true : false;
    return $is_member;
}

function blackfyre_is_pending_member($post_id=false, $user_id=false){
    if ($post_id==false && $user_id==false) return false;
    $post_meta_arr = get_post_meta( $post_id, 'clan', true );
    if($post_meta_arr['users']['pending'] === NULL){
        $is_member = false;
    }else{
        $is_member = (in_array($user_id, $post_meta_arr['users']['pending'])) ? true : false;
    }
    return $is_member;
}

function blackfyre_is_user($post_id=false, $user_id=false){
    if ($post_id==false && $user_id==false) return false;
    if (in_array(blackfyre_membership_status($post_id,$user_id), array('user') ) ) return true;
    else return false;
}

function blackfyre_is_super_admin($post_id=false, $user_id=false){
    if ($post_id==false && $user_id==false) return false;
    if (in_array(blackfyre_membership_status($post_id,$user_id), array('super_admin') ) ) return true;
    else return false;
}

function blackfyre_is_admin($post_id=false, $user_id=false){
    if ($post_id==false && $user_id==false) return false;
    if (in_array(blackfyre_membership_status($post_id,$user_id), array('super_admin', 'admin') ) ) return true;
    else return false;
}


function blackfyre_membership_status($post_id=false, $user_id=false){
    if ($post_id==false && $user_id==false) return false;
    if ($post_id && $user_id) {
        $post_meta_arr = get_post_meta($post_id, 'clan', true);

        if ($post_meta_arr=='') return false;
        if($post_meta_arr['super_admin']==$user_id) return 'super_admin';

        if(!is_array($post_meta_arr['admins'])) $post_meta_arr['admins'] = (array) $post_meta_arr['admins'];
        if(in_array($user_id, $post_meta_arr['admins'])) return 'admin';

        if(!is_array($post_meta_arr['users']['active'])) $post_meta_arr['users']['active'] = (array) $post_meta_arr['users']['active'];
        if(in_array($user_id, $post_meta_arr['users']['active'])) return 'user';

        if(!is_array($post_meta_arr['users']['pending'])) $post_meta_arr['users']['pending'] = (array) $post_meta_arr['users']['pending'];
        if(in_array($user_id, $post_meta_arr['users']['pending'])) return 'user_pending';

    } else return false;

}

function blackfyre_clans_for_userid ($uid) { return get_user_meta( $uid, 'clan_post_id'); }

function blackfyre_games_for_postid ($pid) { return get_post_meta( $pid, 'games'); }

function blackfyre_get_user_clans($user_id){
    $clans = get_user_meta( $user_id, 'clan_post_id');
    $active_clans = array();
    foreach ($clans as $clan) {
        if(blackfyre_is_user($clan, $user_id) or blackfyre_is_super_admin($clan, $user_id) or blackfyre_is_admin($clan, $user_id)){
            $active_clans[]=$clan;
        }
    }
    return $active_clans;
}

function blackyfyre_return_clan_image($clan_id){
    global $wpdb;
    $teams = $wpdb->prefix."cw_teams";
    $logo = $wpdb->get_results($wpdb->prepare("SELECT logo FROM $teams WHERE `id`= %s ", $clan_id ));

    if(!empty($logo)){
    $thumb = $logo[0]->logo;
    $img_url = wp_get_attachment_url( $thumb,'full'); //get img URL
    $image = blackfyre_aq_resize( $img_url, 55, 55, true, true, true ); //resize & crop img
    }
    if(!$image){ $image = get_template_directory_uri().'/img/defaults/default_profile55x55.png';  }
    return $image;
}

function blackyfyre_return_clan_image_big($clan_id){
    global $wpdb;
    $teams = $wpdb->prefix."cw_teams";
    $logo = $wpdb->get_results($wpdb->prepare("SELECT logo FROM $teams WHERE `id`= %s", $clan_id));

    if(!empty($logo)){
    $thumb = $logo[0]->logo;
    $img_url = wp_get_attachment_url( $thumb,'full'); //get img URL
    $image = blackfyre_aq_resize( $img_url, 210, 178, true, true, true ); //resize & crop img
    }
    if(!$image){ $image = get_template_directory_uri().'/img/defaults/default-clan.jpg';  }
    return $image;
}
function blackyfyre_return_team_name_by_team_id($team_id){
    global $wpdb;
    $teams = $wpdb->prefix."cw_teams";
    $title = $wpdb->get_results($wpdb->prepare("SELECT title FROM $teams WHERE `id`= %s", $team_id));
    return $title;
}

function blackyfyre_return_team_post__by_team_id($team_id){
    global $wpdb;
    $teams = $wpdb->prefix."cw_teams";
    $post_id = $wpdb->get_results($wpdb->prepare("SELECT post_id FROM $teams WHERE `id`= %s", $team_id));
    return $post_id[0];
}

function blackyfyre_return_team_id_by_post_id($post_id){
    global $wpdb;
    $teams = $wpdb->prefix."cw_teams";
    $title = $wpdb->get_results($wpdb->prepare("SELECT id FROM $teams WHERE `post_id`= %s", $post_id));
    return $title;
}

function blackyfyre_return_teams_by_post_id($post_id){
    global $wpdb;
    $teams = $wpdb->prefix."cw_teams";
    $matches = $wpdb->prefix."cw_matches";
    $rslt = $wpdb->get_results($wpdb->prepare("SELECT team1,team2 FROM $matches as matches
                                INNER JOIN $teams as teams
                                ON matches.team1 = teams.id
                                WHERE matches.post_id= %s", $post_id));
    return $rslt[0];
}

function blackyfyre_return_teams_by_match_id($match_id){
    global $wpdb;
    $matches = $wpdb->prefix."cw_matches";
    $teams = $wpdb->prefix."cw_teams";
    $rslt = $wpdb->get_results($wpdb->prepare("SELECT team1,team2 FROM $matches as matches
                                INNER JOIN $teams as teams
                                ON matches.team1 = teams.id
                                WHERE matches.id= %s", $match_id));
    return $rslt[0];
}
function blackyfyre_return_post_id_by_team_id($team_id){
    global $wpdb;
    $teams = $wpdb->prefix."cw_teams";
    $rslt = $wpdb->get_results($wpdb->prepare("SELECT post_id FROM $teams WHERE `id`= %s",$team_id));
    return $rslt[0];
}


function blackyfyre_return_number_of_members($clan_id){
    $members = get_post_meta( $clan_id, 'clan', true );
    $ad = ( is_array( $members ) && isset( $members['admins'] ) ) ? $members['admins'] : array();
    $us = ( is_array( $members ) && isset( $members['users'] ) && is_array( $members['users'] ) && isset( $members['users']['active'] ) ) ? $members['users']['active'] : array();
    $total = count($ad) + count($us) + 1;
    return  $total;
}

/*MATCH FUNCTIONS*/
function blackyfyre_return_team_ids_from_match_by_post_id($post_id){
    global $wpdb;
    $matches = $wpdb->prefix."cw_matches";
    $rslt = $wpdb->get_results($wpdb->prepare("SELECT team1,team2 FROM $matches WHERE `post_id`= %s", $post_id));
    return $rslt[0];
}

function blackyfyre_return_team_ids_from_match_by_match_id($match_id){
    global $wpdb;
    $matches = $wpdb->prefix."cw_matches";
    $rslt = $wpdb->get_results($wpdb->prepare("SELECT team1,team2 FROM $matches WHERE `id`= %s", $match_id));
    return $rslt[0];
}

function blackyfyre_return_match_status_by_post_id($post_id){
    global $wpdb;
    $matches = $wpdb->prefix."cw_matches";
    $rslt = $wpdb->get_results($wpdb->prepare("SELECT status FROM $matches WHERE `post_id`= %s", $post_id));
    return $rslt[0];
}



/*OTHER CW FUNCTIONS*/


function blackyfyre_delete_usermeta_on_clan_delete($post_id){
     global $wpdb;
     $usermeta = $wpdb->prefix."usermeta";
     $wpdb->query($wpdb->prepare("DELETE FROM $usermeta WHERE `meta_key` = 'clan_post_id' && `meta_value` = %s", $post_id));
}

function blackyfyre_return_map_pic($map_id){
     global $wpdb;
     $maps = $wpdb->prefix."cw_maps";
     $rslt = $wpdb->get_results($wpdb->prepare("SELECT `screenshot` FROM $maps where `id` = %s", $map_id));
     $thumb = $rslt[0]->screenshot;
     $img_url = wp_get_attachment_url( $thumb,'full');
     return $img_url;
}

function blackyfyre_return_map_title($map_id){
     global $wpdb;
     $maps = $wpdb->prefix."cw_maps";
     $rslt = $wpdb->get_results($wpdb->prepare("SELECT `title` FROM $maps where `id` = %s", $map_id));
     return $rslt[0]->title;
}



function blackfyre_return_game_image($game_id){
    global $wpdb;
    $games = $wpdb->prefix."cw_games";
    $game_img = $wpdb->get_results($wpdb->prepare("SELECT `icon` FROM $games WHERE `id`= %s", $game_id));

    if(!empty($game_img)){
    $img_url = wp_get_attachment_url( $game_img[0]->icon,'full'); //get img URL
    $image = blackfyre_aq_resize( $img_url, 55, 55, true, true, true ); //resize & crop img
    }
    if(!$image){ $image = get_template_directory_uri().'/img/defaults/gamedefault.jpg';  }
    return $image;

}

function blackfyre_return_game_id_by_post_id($post_id){
    global $wpdb;
    $matches = $wpdb->prefix."cw_matches";
    $game_id = $wpdb->get_results($wpdb->prepare("SELECT `game_id` FROM $matches WHERE `post_id`= %s",$post_id));

    if(isset($game_id[0])){
         return $game_id[0];
    }else{
         return '';
    }

}

function blackfyre_return_game_banner($game_id){
    global $wpdb;
    $games = $wpdb->prefix."cw_games";
    $game_img = $wpdb->get_results($wpdb->prepare("SELECT g_banner_file FROM $games WHERE `id`= %s",$game_id));

     if(!empty($game_img)){
    $thumb = $game_img[0]->g_banner_file;
    $img_url = wp_get_attachment_url( $thumb,'full'); //get img URL
    $image = blackfyre_aq_resize( $img_url, 1168, 230, true, true, true ); //resize & crop img
    }
    if(!$image){ $image = get_template_directory_uri().'/img/defaults/default-banner.jpg';  }
    return $image;

}

function blackfyre_return_all_games($team_id){
    global $wpdb;
    $matches = $wpdb->prefix."cw_matches";
    $rslt = $wpdb->get_results($wpdb->prepare("SELECT `game_id` FROM $matches WHERE `team1`= %s or `team2`= %s ", $team_id,$team_id));
    $gids = array();
    foreach ($rslt as $rsl) {
        $gids[] = $rsl->game_id;
    }
    return $gids;
}

function blackfyre_return_all_games_string($team_id){
    global $wpdb;
    $matches = $wpdb->prefix."cw_matches";
    $rslt = $wpdb->get_results($wpdb->prepare("SELECT `game_id` FROM $matches WHERE `team1`= %s or `team2`= %s ",$team_id,$team_id));

    $gids = '';
    $i = 0;
    $len = count($rslt);
    foreach ($rslt as $rsl) {

        if(($i == $len - 1)){
            $gids = $gids . ', '. $rsl->game_id;
        }else{
            if ($i == 0) {
               $gids = $rsl->game_id;
            }else{
               $gids = $gids. ', '.$rsl->game_id;
            }
        }
     $i++;
    }
    return $gids;
}

function blackfyre_mutual_games_inter($team1, $team2){
    $games1 = blackfyre_games_for_postid($team1);
    $games2 = blackfyre_games_for_postid($team2);
    $wpClanWars = new WP_ClanWars();
    if( isset($games1[0]) && is_array($games1[0]) && isset($games2[0]) && is_array($games2[0]) ){
        foreach($games1[0] as $item) {
            if (in_array($item, $games2[0])) {
                $game = $wpClanWars->get_game(array('id'=>$item));
                $ret[$item]=$game[0]->title;
            }
        }
        if(empty($ret)){ ?>
            <option value=""><?php _e('No mutual games', 'blackfyre'); ?></option>
        <?php }else{
        foreach($ret as $key=>$val): ?>
            <option value="<?php echo esc_attr($key);?>"><?php echo esc_attr($val);?></option>
        <?php endforeach; }
    }else{ ?>
         <option value=""><?php _e('No mutual games', 'blackfyre'); ?></option>
   <?php }
}

function blackfyre_get_all_games($post_id){
    $wpClanWars = new WP_ClanWars();
    $arr =  array(
        'id' => false,
        'limit' => 0,
        'offset' => 0,
        'orderby' => 'id',
        'order' => 'ASC'
    );
    $tmp_arr = get_post_meta($post_id, 'games', true);
    $games_postmeta_arr = is_array($tmp_arr) ? $tmp_arr : array();
    $games = $wpClanWars->get_game($arr); ?>
    <form id="frm_matches">
    <?php foreach($games as $game){ ?>
        <div><label><input type="checkbox" class="chk_games" name="chk_games[]"
        <?php if(in_array($game->id, $games_postmeta_arr)):?>checked<?php endif;?>
        value="<?php echo esc_attr($game->id); ?>">&nbsp;<?php echo esc_attr($game->title); ?></label></div>
    <?php } ?>
    </form>
<?php }


/*AJAX CALLS*/
function blackfyre_delete_page_background(){
    $pid = $_POST['pid'];
    delete_post_meta($pid, 'clan_page_bg');
    die();
}


function blackfyre_change_membership_block(){
    $pid = $_POST['pid'];
    $req = $_POST['req'];
    $uid = $_POST['uid'];
    $post_meta_arr = get_post_meta($pid, 'clan', true );
    $data = array();


    if($req=="remove_friend_user"){
        $key = array_search($uid,$post_meta_arr['admins']);
        if($key!==false) unset($post_meta_arr['admins'][$key]);

        $key = array_search($uid,$post_meta_arr['users']['active']);
        if($key!==false) unset($post_meta_arr['users']['active'][$key]);

        $key = array_search($uid,$post_meta_arr['users']['pending']);
        if($key!==false) unset($post_meta_arr['users']['pending'][$key]);
        delete_user_meta($uid, 'clan_post_id', $pid);
        $data[0] = "remove_friend_user";
        $data[1] = $uid;
    }

     if($req=="join_clan"){
        $post_meta_arr['users']['pending'][] = $uid;
        add_user_meta($uid, 'clan_post_id', $pid);
        $data[0] = "join_clan";
    }


    if($req=="cancel_request"){
        $key = array_search($uid,$post_meta_arr['admins']);
        if($key!==false) unset($post_meta_arr['admins'][$key]);

        $key = array_search($uid,$post_meta_arr['users']['active']);
        if($key!==false) unset($post_meta_arr['users']['active'][$key]);

        $key = array_search($uid,$post_meta_arr['users']['pending']);
        if($key!==false) unset($post_meta_arr['users']['pending'][$key]);
        delete_user_meta($uid, 'clan_post_id', $pid);
        $data[0] = "cancel_request";
    }

    update_post_meta($pid, 'clan', $post_meta_arr);
    echo json_encode($data);
    die();
}


function blackfyre_change_membership_let_join(){
    $pid = $_POST['pid'];
    $req = $_POST['req'];
    $uid = $_POST['uid'];
    $post_meta_arr = get_post_meta($pid, 'clan', true );
    $data = array();
    if($req=="let_this_member_join"){
        $key = array_search($uid,$post_meta_arr['users']['pending']);
        if($key!==false) unset($post_meta_arr['users']['pending'][$key]);
        $post_meta_arr['users']['active'][] = $uid;
        $data[0] = "let_this_member_join";
        $data[1] = $uid;
    }
    update_post_meta($pid, 'clan', $post_meta_arr);
    echo json_encode($data);
    die();
}

function blackfyre_change_membership_remove_friend_admin(){
    $pid = $_POST['pid'];
    $req = $_POST['req'];
    $uid = $_POST['uid'];
    $post_meta_arr = get_post_meta($pid, 'clan', true );
    $data = array();
    if($req=="remove_friend_admin"){
        $key = array_search($uid,$post_meta_arr['admins']);
        if($key!==false) unset($post_meta_arr['admins'][$key]);

        $key = array_search($uid,$post_meta_arr['users']['active']);
        if($key!==false) unset($post_meta_arr['users']['active'][$key]);

        $key = array_search($uid,$post_meta_arr['users']['pending']);
        if($key!==false) unset($post_meta_arr['users']['pending'][$key]);
        delete_user_meta($uid, 'clan_post_id', $pid);
        $data[0] = "remove_friend_admin";
        $data[1] = $uid;
    }
    update_post_meta($pid, 'clan', $post_meta_arr);
    echo json_encode($data);
    die();
}


function blackfyre_change_membership_make_administrator(){
    $pid = $_POST['pid'];
    $req = $_POST['req'];
    $uid = $_POST['uid'];
    $post_meta_arr = get_post_meta($pid, 'clan', true );
    $data = array();
    if($req=="make_administrator"){
        $key = array_search($uid,$post_meta_arr['users']['active']);
        if($key!==false) unset($post_meta_arr['users']['active'][$key]);
        $post_meta_arr['admins'][] = $uid;
        $data[0] = "make_administrator";
        $data[1] = $uid;
    }
    update_post_meta($pid, 'clan', $post_meta_arr);
    echo json_encode($data);
    die();
}


function blackfyre_change_membership_downgrade_to_user(){
    $pid = $_POST['pid'];
    $req = $_POST['req'];
    $uid = $_POST['uid'];
    $post_meta_arr = get_post_meta($pid, 'clan', true );
    $data = array();
    if($req=="downgrade_to_user"){
        $key = array_search($uid,$post_meta_arr['admins']);
        if($key!==false) unset($post_meta_arr['admins'][$key]);
        $post_meta_arr['users']['active'][] = $uid;
        $data[0] = "downgrade_to_user";
        $data[1] = $uid;
    }
    update_post_meta($pid, 'clan', $post_meta_arr);
    echo json_encode($data);
    die();
}


function blackfyre_clan_members_ajax(){
    $_POST['page'] = str_replace('?','', $_POST['page']);
    parse_str($_POST['page'], $page);
    blackfyre_clan_members($_POST['pid'], $page['members_list_page'] );
    die();
}


function blackfyre_challenge_acc_rej(){
       global $wpClanWars;
        $req = $_POST['req'];
        $challenge_id = $_POST['cid'];
        $data = array();
        if($req=="accept_challenge"){
            $data[0] = $challenge_id;
            $data[1] = 'accepted';
            echo json_encode($data);
            $p = array('status' => 'active');
            $wpClanWars->update_match($challenge_id, $p);
        }

        if($req=="reject_challenge"){
            $data[0] = $challenge_id;
            $data[1] = 'rejected';
            echo json_encode($data);
            $p = array('status' => 'rejected_challenge');
            $wpClanWars->update_match($challenge_id, $p);
        }

die();
}

function blackfyre_challenge_acc_rej_single(){
        global $wpClanWars;
        $req = $_POST['req'];
        $challenge_id = $_POST['cid'];
        $data = '';
        if($req=="accept_challenge"){
            $data = 'accepted';
            echo json_encode($data);
            $p = array('status' => 'active');
            $wpClanWars->update_match($challenge_id, $p);
        }

        if($req=="reject_challenge"){
            $data = 'rejected';
            echo json_encode($data);
            $p = array('status' => 'rejected_challenge');
            $wpClanWars->update_match($challenge_id, $p);
        }
die();
}

function blackfyre_match_score_acc_rej(){
        global $wpClanWars;
        $req = $_POST['req'];
        $match_id = $_POST['mid'];
        if($req=="accept_score"){
            $data = 'accepted';
            $p = array('status' => 'done');
            $wpClanWars->update_match($match_id, $p);

        }

        if($req=="reject_score"){
            $data = 'rejected';
            $p = array('status' => 'active');
            $wpClanWars->update_match($match_id, $p);
        }
echo json_encode($data);
die();

}

function blackfyre_clan_delete(){
        global $wpClanWars;
        $post_id = $_POST['pid'];
        blackyfyre_delete_usermeta_on_clan_delete($post_id);
        wp_delete_post($post_id);

die();
}

function blackfyre_match_delete(){
        global $wpClanWars;
        $post_id = $_POST['pid'];
        $match_id = $_POST['mid'];
        $req = $_POST['req'];

        if($req=="delete_match"){
             $wpClanWars->delete_match($match_id);
        }else{
        $team1 = blackyfyre_return_post_id_by_match_id(blackyfyre_return_team_ids_from_match_by_post_id($post_id)->team1);
        $team2 = blackyfyre_return_post_id_by_match_id(blackyfyre_return_team_ids_from_match_by_post_id($post_id)->team2);
        $match_status = blackyfyre_return_match_status_by_post_id($post_id)->status;

        if(blackfyre_is_admin($team1->post_id, get_current_user_id())){
            $team_user = 'deleted1';
            $team = 'team1';
        }elseif(blackfyre_is_admin($team2->post_id, get_current_user_id())){
            $team_user = 'deleted2';
            $team = 'team2';
        }

        if($match_status == 'active' or $match_status == 'rejected_challenge' || $match_status == 'submitted1' || $match_status == 'submitted2' || $match_status == 'pending'){
        $p = array('status' => $team_user);
        $wpClanWars->update_match($match_id, $p);
        }

        if(($match_status == 'deleted1' && $team == 'team2') or ($match_status == 'deleted2' && $team == 'team1')){
         $wpClanWars->delete_match($match_id);
        }
        }
die();
}

function blackfyre_match_delete_notification(){
        global $wpClanWars;
        $match_id = $_POST['mid'];
        $req = $_POST['req'];

        if($req=="accept_delete"){
           $wpClanWars->delete_match($match_id);
        }

        if($req=="reject_delete"){
           $p = array('status' => '');
           $wpClanWars->update_match($match_id, $p);
        }
die();
}

function blackfyre_mutual_games(){
    if( $_POST['team1']=='' || $_POST['team2']=='' ) die();
    blackfyre_mutual_games_inter($_POST['team1'], $_POST['team2']);
    die();
}



/*fix publish permissions*/

function blackfyre_change_user_permissions() {
$role = get_role( 'contributor' ); // gets the author role
$role->add_cap('publish_posts');
$role->add_cap('edit_posts');
$role->add_cap('edit_published_posts');
$role->add_cap('upload_files');
}


function blackfyre_get_attachment_id( $image_url ) {
    global $wpdb;
    $attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM " . $wpdb->posts . " WHERE guid=%s", $image_url ) );
    return $attachment[0];
}

/******** force permalinks structure******/
add_action('after_setup_theme', 'blackfyre_force_permalinks');
function blackfyre_force_permalinks(){
if (get_option('permalink_structure') != '/%postname%/') {
    global $wp_rewrite;
    $wp_rewrite->set_permalink_structure('/%postname%/');
}
}

/*Set default role on new users register*/
function blackfyre_defaultrole($default_role){
    return 'contributor'; // This is changed
    return $default_role; // This allows default
}



 function blakcfyre_footer_manager(){
    global $user_ID;
    if ( !current_user_can( 'administrator' ) ) { ?>
    <script>
    jQuery(document).ready(function ($) {
       //header buttons
       var backend_button = $('.vc_btn-backend-editor');
       var draft_button = $('.vc_btn-save-draft');
       var css_field = $('#vc_post-settings-panel .vc_row .vc_col-sm-12');

       //buttons
       var raw_html = $('.wpb-content-layouts li[data-element="vc_raw_html"]');
       var raw_js = $('.wpb-content-layouts li[data-element="vc_raw_js"]');
       var news = $('.wpb-content-layouts li[data-element="vc_column_news"]');
       var news_horizontal = $('.wpb-content-layouts li[data-element="vc_column_news_horizontal"]');
       var news_tabbed = $('.wpb-content-layouts li[data-element="vc_column_news_tabbed"]');
       var blog = $('.wpb-content-layouts li[data-element="vc_column_blog"]');
       var clans = $('.wpb-content-layouts li[data-element="vc_clans"]');
       var contact = $('.wpb-content-layouts li[data-element="vc_contact"]');
       var post_grid = $('.wpb-content-layouts li[data-element="vc_posts_grid"]');
       var carousel = $('.wpb-content-layouts li[data-element="vc_carousel"]');
       var post_slider = $('.wpb-content-layouts li[data-element="vc_posts_slider"]');
       var widget_sidebar = $('.wpb-content-layouts li[data-element="vc_widget_sidebar"]');
       var cta_button = $('.wpb-content-layouts li[data-element="vc_cta_button"]');
       var cta_button2 = $('.wpb-content-layouts li[data-element="vc_cta_button2"]');
       var custom_heading = $('.wpb-content-layouts li[data-element="vc_custom_heading"]');
       var wp_search = $('.wpb-content-layouts li[data-element="vc_wp_search"]');
       var wp_meta = $('.wpb-content-layouts li[data-element="vc_wp_meta"]');
       var wp_recentcomments = $('.wpb-content-layouts li[data-element="vc_wp_recentcomments"]');
       var wp_calendar = $('.wpb-content-layouts li[data-element="vc_wp_calendar"]');
       var wp_pages = $('.wpb-content-layouts li[data-element="vc_wp_pages"]');
       var wp_tagcloud = $('.wpb-content-layouts li[data-element="vc_wp_tagcloud"]');
       var wp_custommenu = $('.wpb-content-layouts li[data-element="vc_wp_custommenu"]');
       var wp_text = $('.wpb-content-layouts li[data-element="vc_wp_text"]');
       var wp_posts = $('.wpb-content-layouts li[data-element="vc_wp_posts"]');
       var wp_categories = $('.wpb-content-layouts li[data-element="vc_wp_categories"]');
       var wp_archives = $('.wpb-content-layouts li[data-element="vc_wp_archives"]');
       var wp_rss = $('.wpb-content-layouts li[data-element="vc_wp_rss"]');
       var wp_categories = $('.wpb-content-layouts li[data-element="vc_wp_categories"]');

       //templates
       var landing = $('.vc_default-templates div[data-template_name=1]');
       var call_action = $('.vc_default-templates div[data-template_name=2]');
       var feature_list = $('.vc_default-templates div[data-template_name=3]');
       var description = $('.vc_default-templates div[data-template_name=4]');
       var service_list = $('.vc_default-templates div[data-template_name=5]');
       var product_page = $('.vc_default-templates div[data-template_name=6]');

       backend_button.remove();
       draft_button.remove();
       css_field.next().css('display', 'none');


       raw_html.remove();
       raw_js.remove();
       news.remove();
       news_horizontal.remove();
       news_tabbed.remove();
       blog.remove();
       clans.remove();
       contact.remove();
       post_grid.remove();
       carousel.remove();
       post_slider.remove();
       widget_sidebar.remove();
       wp_search.remove();
       wp_meta.remove();
       wp_recentcomments.remove();
       wp_calendar.remove();
       wp_pages.remove();
       wp_tagcloud.remove();
       wp_custommenu.remove();
       wp_text.remove();
       wp_posts.remove();
       wp_categories.remove();
       wp_archives.remove();
       wp_rss.remove();
       wp_categories.remove();
       cta_button.remove();
       cta_button2.remove();
       custom_heading.remove();


       landing.remove();
       call_action.remove();
       feature_list.remove();
       description.remove();
       service_list.remove();
       product_page.remove();


    });
    </script>
    <?php }
 }

 /***** limit media to logged in user *****/
function blackfyre_restrict_media_library( $wp_query_obj ) {
    global $current_user, $pagenow;
    if( !is_a( $current_user, 'WP_User') )
    return;
    if( 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' )
    return;
    if( !current_user_can('manage_media_library') )
    $wp_query_obj->set('author', $current_user->ID );
    return;
}

/*******open comments for clans *********/
function blackfyre_comments_open( $open, $post_id ) {
    $post = get_post( $post_id );
    if ( 'clan' == $post->post_type )
        $open = true;
    return $open;
}

function blackfyre_comments_on( $data ) {
    if( $data['post_type'] == 'clan' ) {
        $data['comment_status'] = 'open';
    }

    return $data;
}


/**default landing tab bpress**/
define('BP_DEFAULT_COMPONENT', 'profile' );

/**get string between two strings**/
function blackfyre_string_between($string, $start, $end){
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}

/****************************************All clans page pagination and search**********************************************/
function blackfyre_title_filter($where, &$wp_query){
    global $wpdb;

    if($search_term = $wp_query->get( 'clan_name' )){
        $search_term = $wpdb->esc_like($search_term);
        $search_term = ' \'%' . $search_term . '%\'';
        $where .= ' AND ' . $wpdb->posts . '.post_title LIKE '.$search_term;
    }

    return $where;
}

function blackfyre_all_clans_pagination(){
    global $post;
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args = array(
          'post_type' => 'clan',
          'orderby' => 'name',
          'order' => 'ASC',
          'showposts' => 1,
          'paged'  => $paged
          );

    if (isset($_POST['clan_name']) && $_POST['clan_name']!='') {
        $args['clan_name'] = $_POST['clan_name'];
        add_filter( 'posts_where', 'blackfyre_title_filter', 10, 2 );
        $the_query = new WP_Query($args);
        remove_filter( 'posts_where', 'blackfyre_title_filter', 10, 2 );
    } else {
        $the_query = new WP_Query($args);
    }


    if ( $the_query->have_posts() ) { ?>

       <ul id="members-list" class="item-list" >

       <?php while ( $the_query->have_posts() ) { $the_query->the_post(); ?>
            <li>
                    <div class="clan-list-wrapper">
                        <div class="item-avatar">
                           <a href="<?php echo esc_url(get_permalink($post->ID)); ?> ">
                             <?php $img = get_post_meta( $post->ID, 'clan_photo', true );
                                   $image = blackfyre_aq_resize( $img, 50, 50, true, true, true );
                                   if(!$image){
                                       $image = get_template_directory_uri().'/img/defaults/default-clan-50x50.jpg';
                                   }
                                   ?>
                            <img alt="img" src="<?php echo esc_url($image); ?>" class="avatar" >
                           </a>
                        </div>

                        <div class="item">
                            <div class="item-title">
                                <a href="<?php echo esc_url(get_permalink($post->ID)); ?> "> <?php echo esc_attr($post->post_title); ?></a>
                                <div class="item-meta"><span class="activity">
                                    <?php $members = blackyfyre_return_number_of_members($post->ID); ?>
            <?php if($members == 1){ echo esc_attr($members); ?>&nbsp;<?php _e('Member','blackfyre'); }else{ echo esc_attr($members); ?>&nbsp;<?php _e('Members','blackfyre'); } ?></span></div>
                            </div>
                        </div>
                        <div class="clear"></div>
                    </div>

                </li>
       <?php } ?>

       </ul>
<div class="clear"></div>
    <?php } else { ?>
        <div class="error_msg"><span><?php  _e('There are no clans at the moment!', 'blackfyre'); ?> </span></div>
    <?php } ?>

    <?php wp_reset_postdata(); ?>

    <?php previous_posts_link('&laquo; ' . __('Previous page', 'blackfyre')) ?>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <?php next_posts_link(__('Next page', 'blackfyre') . ' &raquo;', $the_query->max_num_pages) ?>

<?php }


function blackfyre_all_clans_pagination_v2_ajax(){
    $_POST['href'] = str_replace('?','', $_POST['href']);
    parse_str($_POST['href'], $_GET);
    blackfyre_all_clans_pagination_v2($_GET['page'], $_GET['term']);
    die();
}

function blackfyre_all_clans_pagination_v2($page=1, $term=''){
    global $wpdb;

    $post_per_page = 40;
    $offset = ($page -1) * $post_per_page;

    $query = "
    SELECT SQL_CALC_FOUND_ROWS *
    FROM {$wpdb->posts} WHERE 1=1
    AND post_type = 'clan'
    AND post_name LIKE '%{$term}%'
    AND (post_status = 'publish' OR post_status = 'closed')
    ORDER BY post_name ASC
    LIMIT {$offset}, {$post_per_page}
    ";

    $results = $wpdb->get_results( $query);

    $res_count = (int) $wpdb->get_var( "SELECT FOUND_ROWS()" );

    include "addons/pagination/pagination.class.php";
    $p = new blackfyre_pagination;
    $p->items($res_count);
    $p->limit($post_per_page);

    $p->parameterName("page");
    $p->currentPage(isset($_GET['page'])?$_GET['page']:1);
    unset($_GET['page']);
    $_GET['term'] = $term;
    $p->target("?".http_build_query($_GET));

    #$p->parameterName('paged');
    #$p->currentPage($paged);
    #$p->target("?term={$term}");


    $p->nextLabel(__('Next','blackfyre'));
    $p->prevLabel(__('Previous','blackfyre'));


    if ( $results ) { ?>

       <ul id="members-list" class="item-list" >
       <?php foreach ( $results as $post ) { ?>
            <li>
                    <div class="clan-list-wrapper">
                        <div class="item-avatar">
                           <a href="<?php echo esc_url(get_permalink($post->ID)); ?> ">
                             <?php $img = get_post_meta( $post->ID, 'clan_photo', true );
                                   $image = blackfyre_aq_resize( $img, 50, 50, true, true, true );
                                   if(!$image){
                                       $image = esc_url(get_template_directory_uri()).'/img/defaults/default-clan-50x50.jpg';
                                   }
                                   ?>
                            <img alt="img" src="<?php echo esc_url($image); ?>" class="avatar" >
                           </a>
                        </div>

                        <div class="item">
                            <div class="item-title">
                                <a href="<?php echo esc_url(get_permalink($post->ID)); ?> "> <?php echo esc_attr($post->post_title); ?></a>
                                <div class="item-meta">
                                    <span class="activity">
                                        <?php $members = blackyfyre_return_number_of_members($post->ID); ?>
                                        <?php if($members == 1){
                                            echo esc_attr($members); ?>&nbsp;<?php _e('Member','blackfyre');
                                        }else{
                                            echo esc_attr($members); ?>&nbsp;<?php _e('Members','blackfyre');
                                        } ?>
                                    </span></div>
                            </div>
                        </div>
                        <div class="clear"></div>
                    </div>

                </li>
       <?php } ?>

       </ul>
<div class="clear"></div>
    <?php } else { ?>
        <div class="error_msg"><span><?php _e('There are no clans at the moment!', 'blackfyre'); ?> </span></div>
    <?php } ?>


    <?php $p->show();

}


/*hide admin bar for all users except admin*/
function skywarrior_admin_bar(){
	
	if (!current_user_can('administrator') && !is_admin()) {
  		show_admin_bar(false);
	}

}
add_action( 'after_setup_theme' , 'skywarrior_admin_bar');

/*remove menus for non admins*/
function skywarrior_remove_menus(){

  if (!current_user_can('administrator')) {
  remove_menu_page( 'index.php' );                  	//Dashboard
  remove_menu_page( 'edit.php' );                   	//Posts
  remove_menu_page( 'upload.php' );                 	//Media
  remove_menu_page( 'edit.php?post_type=page' );    	//Pages
  remove_menu_page( 'edit.php?post_type=slider' );  	//Slider
  remove_menu_page( 'edit.php?post_type=clan' );    	//Clans
  remove_menu_page( 'edit.php?post_type=pricetable' );  //Pricetable
  remove_menu_page( 'edit-comments.php' );          	//Comments
  remove_menu_page( 'themes.php' );                 	//Appearance
  remove_menu_page( 'plugins.php' );                	//Plugins
  remove_menu_page( 'users.php' );                  	//Users
  remove_menu_page( 'tools.php' );                  	//Tools
  remove_menu_page( 'options-general.php' );        	//Settings
  }
}

/*disable update notifications*/
function skywarrior_update_nag() {
  if (!current_user_can('administrator')) {
    remove_action( 'admin_notices', 'update_nag', 3 ); 

  }
}

function skywarrior_buddypress_avatar( $url ){
	$uid = get_current_user_id();
 	$url0 = get_user_meta($uid, 'profile_photo', true);
     if(!empty($url0)){
       $url1 = blackfyre_aq_resize( $url0, 50, 50, true, '', true );
       $url = $url1[0];  //resize & crop img
     }
     if(empty($url)){ $url = '//gravatar.com/avatar/ccf2e856d472e2211ace58458850aaee?d=mm&amp;s=50&amp;r=G'; }
     return $url;

}

function skywarrior_bpfr_admin_bar_render() {
	global $wp_admin_bar;
	$wp_admin_bar->remove_menu('user-admin'); // change to your need
	}
 
 
/*buddypress friends ajax*/ 
function skywarrior_bp_legacy_theme_ajax_addremove_friend() {

	// Bail if not a POST action
	if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) )
		return;

	// Cast fid as an integer
	$friend_id = (int) $_POST['fid'];

	// Trying to cancel friendship
	if ( 'is_friend' == BP_Friends_Friendship::check_is_friend( bp_loggedin_user_id(), $friend_id ) ) {
		check_ajax_referer( 'friends_remove_friend' );

		if ( ! friends_remove_friend( bp_loggedin_user_id(), $friend_id ) ) {
			echo __( 'Friendship could not be canceled.', 'blackfyre' );
		} else {
			echo '<a id="friend-' . esc_attr( $friend_id ) . '" class="add friendship-button add-friend" rel="add" title="' . __( 'Add as a Friend', 'blackfyre' ) . '" href="' . wp_nonce_url( bp_loggedin_user_domain() . bp_get_friends_slug() . '/add-friend/' . $friend_id, 'friends_add_friend' ) . '"><i class="fa fa-user"></i>' . __( 'Add as a friend!', 'blackfyre' ) . '</a>';
		}

	// Trying to request friendship
	} elseif ( 'not_friends' == BP_Friends_Friendship::check_is_friend( bp_loggedin_user_id(), $friend_id ) ) {
		check_ajax_referer( 'friends_add_friend' );

		if ( ! friends_add_friend( bp_loggedin_user_id(), $friend_id ) ) {
			echo __(' Friendship could not be requested.', 'blackfyre' );
		} else {
			echo '<a id="friend-' . esc_attr( $friend_id ) . '" class="remove friendship-button pending_friend requested add-friend" rel="remove" title="' . __( 'Cancel Request', 'blackfyre' ) . '" href="' . wp_nonce_url( bp_loggedin_user_domain() . bp_get_friends_slug() . '/requests/cancel/' . $friend_id . '/', 'friends_withdraw_friendship' ) . '" class="requested"><i class="fa fa-times" data-original-title="'.__("Cancel request!", "blackfyre").'" data-toggle="tooltip"></i>'.__(' Cancel request!', 'blackfyre').'</a>';
		}

	// Trying to cancel pending request
	} elseif ( 'pending' == BP_Friends_Friendship::check_is_friend( bp_loggedin_user_id(), $friend_id ) ) {
		check_ajax_referer( 'friends_withdraw_friendship' );

		if ( friends_withdraw_friendship( bp_loggedin_user_id(), $friend_id ) ) {
			echo '<a id="friend-' . esc_attr( $friend_id ) . '" class="add friendship-button add-friend" rel="add" title="' . __( 'Add as a friend', 'blackfyre' ) . '" href="' . wp_nonce_url( bp_loggedin_user_domain() . bp_get_friends_slug() . '/add-friend/' . $friend_id, 'friends_add_friend' ) . '"><i class="fa fa-user"></i>' . __( 'Add as a friend!', 'blackfyre' ) . '</a>';
		} else {
			echo __("Friendship request could not be cancelled.", 'blackfyre');
		}

	// Request already pending
	} else {
		echo __( 'Request Pending', 'blackfyre' );
	}

	exit;
}


/*add clan creation field to user profile*/
function skywarrior_clan_extra_user_profile_fields( $user ) { ?>
<h3><?php _e("Clan creation", "blackfyre"); ?></h3>
<table class="form-table">
<tr>
<th><label for="clan_account"><?php _e("Allow user to create clans", 'blackfyre'); ?></label>
</th>
<td>
<input type="checkbox" name="_checkbox_clan_user" id="_checkbox_clan_user" value="yes" <?php if (esc_attr( get_the_author_meta( "_checkbox_clan_user", $user->ID )) == "yes") echo "checked"; ?> />
<br />
</td>
</tr>
</table>
<?php }


function save_skywarrior_clan_extra_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }
update_user_meta( $user_id, '_checkbox_clan_user', $_POST['_checkbox_clan_user'] );
}



/**************************************** /All clans page pagination and search**********************************************/

/* Custom code goes above this line. */
?>

Open in new window

Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

I suspect it be something in load_theme_textdomain() function: can you post here that code?
Please share the code of "functions.php" file located at:- wp-content/themes/blackfyre/themeOptions/functions.php
@Mukesh Yadav: functions.php is yet shared here
Avatar of jonathanduane2010
jonathanduane2010

ASKER

<?php
if ( !function_exists( 'optionsframework_init' ) ) {
/*-----------------------------------------------------------------------------------*/
/* Options Framework Theme
/*-----------------------------------------------------------------------------------*/
/* Set the file path based on whether the Options Framework Theme is a parent theme or child theme */
    define('OPTIONS_FRAMEWORK_URL', get_template_directory() . '/themeOptions/admin/');
    define('OPTIONS_FRAMEWORK_DIRECTORY', get_template_directory_uri() . '/themeOptions/admin/');
require_once (OPTIONS_FRAMEWORK_URL . 'options-framework.php');
}
/*
 * This is an example of how to add custom scripts to the options panel.
 * This one shows/hides the an option when a checkbox is clicked.
 */
add_action('optionsframework_custom_scripts', 'optionsframework_custom_scripts');
function optionsframework_custom_scripts() { ?>
<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery('#example_showhidden').click(function() {
          jQuery('#section-example_text_hidden').fadeToggle(400);
    });
    if (jQuery('#example_showhidden:checked').val() !== undefined) {
        jQuery('#section-example_text_hidden').show();
    }
});
</script>
<?php
}
/*
 * Turns off the default options panel from Twenty Eleven
 */
add_action('after_setup_theme','remove_twentyeleven_options', 100);
function remove_twentyeleven_options() {
    remove_action( 'admin_menu', 'twentyeleven_theme_options_add_page' );
}
?>


here it is here
Nothing bad. It could be in get_template_directory() function... But let me understand: did it worked until yesterday and now you get the issue or it's the first time you open the website after having uploaded it to the server?
yes...
Yes the former or the latter?
May you refresh this file on the server.
sorry Marco, this morning i made a backup of the theme folder then i uploaded update of new theme, i got that error, then i reverted to older version of theme and still got same error
@mukesh what do you mean refresh?
Sometimes when we upload files to server some part of file not uploaded may be because of connection timeout internet issue please crosscheck the content of this file on the server because you have it on local which is correct but there may be some issue with the code uploaded on the sever.
Are you sure we are looking at the failing script?  I see the parse error at your URL, but when I copy the script posted here and run it on my server, I do not get a parse error.

Example here, copied and pasted from the original post:
http://iconoun.com/demo/temp_johnathanduane2010.php

This leads me to believe that we may be looking at the wrong script, perhaps a directory organization error is leading you to a defective copy.  One way to test is to change something in the script - perhaps add a line that generates an HTML comment or that logs a message, then look for evidence of the change.  If you don't find it, you know that your script did not run and you can look elsewhere for the trouble.
I agree, we need to see what's on the server, not your local files.
This isn't your main problem but you need to delete lines 4 and 5 in that code you posted.  Putting back to back tags like that is an invitation to invisible white space that will disable headers and cookies and drive you crazy trying to find it.
Hi Guys,

this is definitely the function.php from

home/zenra937/public_html/lynx/wp-content/themes/blackfyre/themeOptions/functions.php

<?phpif ( !function_exists( 'optionsframework_init' ) ) {/*-----------------------------------------------------------------------------------*//* Options Framework Theme/*-----------------------------------------------------------------------------------*//* Set the file path based on whether the Options Framework Theme is a parent theme or child theme */	define('OPTIONS_FRAMEWORK_URL', get_template_directory() . '/themeOptions/admin/');	define('OPTIONS_FRAMEWORK_DIRECTORY', get_template_directory_uri() . '/themeOptions/admin/');require_once (OPTIONS_FRAMEWORK_URL . 'options-framework.php');}/* * This is an example of how to add custom scripts to the options panel. * This one shows/hides the an option when a checkbox is clicked. */add_action('optionsframework_custom_scripts', 'optionsframework_custom_scripts');function optionsframework_custom_scripts() { ?><script type="text/javascript">jQuery(document).ready(function() {	jQuery('#example_showhidden').click(function() {  		jQuery('#section-example_text_hidden').fadeToggle(400);	});	if (jQuery('#example_showhidden:checked').val() !== undefined) {		jQuery('#section-example_text_hidden').show();	}});</script><?php}/* * Turns off the default options panel from Twenty Eleven */add_action('after_setup_theme','remove_twentyeleven_options', 100);function remove_twentyeleven_options() {	remove_action( 'admin_menu', 'twentyeleven_theme_options_add_page' );}?>

Open in new window


I would be more than happy to give you ftp access to my server if you think its warranted?
Ok first thing is to reformat that code so it is not on one line. Getting a message that you have a parse error on one line when all your code is on one line is not really helpful.

If you save your functions.php like so and then try to access the site what error (if any) do you get
<?php
if ( !function_exists( 'optionsframework_init' ) ) {
  /*-----------------------------------------------------------------------------------*/
  /* Options Framework Theme/*-----------------------------------------------------------------------------------*/
  /* Set the file path based on whether the Options Framework Theme is a parent theme or child theme */  
  define('OPTIONS_FRAMEWORK_URL', get_template_directory() . '/themeOptions/admin/');
  define('OPTIONS_FRAMEWORK_DIRECTORY', get_template_directory_uri() . '/themeOptions/admin/');
  require_once (OPTIONS_FRAMEWORK_URL . 'options-framework.php');
}
/* * This is an example of how to add custom scripts to the options panel. * This one shows/hides the an option when a checkbox is clicked. */
add_action('optionsframework_custom_scripts', 'optionsframework_custom_scripts');
function optionsframework_custom_scripts() 
{ 
?>
<script type="text/javascript">
jQuery(document).ready(function() {  
  jQuery('#example_showhidden').click(function() { 
    jQuery('#section-example_text_hidden').fadeToggle(400);
  });

  if (jQuery('#example_showhidden:checked').val() !== undefined) {
    jQuery('#section-example_text_hidden').show();
  }
});
</script>
<?php
}
/* * Turns off the default options panel from Twenty Eleven */
add_action('after_setup_theme','remove_twentyeleven_options', 100);

function remove_twentyeleven_options() {
  remove_action( 'admin_menu', 'twentyeleven_theme_options_add_page' );
}
?>

Open in new window

Ok,

its slightly different error this time

Parse error: syntax error, unexpected 'define' (T_STRING) in /home/zenra937/public_html/lynx/wp-content/themes/blackfyre/themeOptions/admin/options-framework.php on line 1
Sounds like that it might be the same problem - has the options-framework.php file been formatted on one line?
<?phpif

Maybe try <?php if instead?  The space matters here.
ASKER CERTIFIED SOLUTION
Avatar of Mukesh Yadav
Mukesh Yadav
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial