<?php
if ( ! defined( 'ABSPATH' ) ) { die( '-1' );}
/**
 *Gets a value from a nested array using an address string.
 */
if ( ! function_exists( 'mh_array_get' ) ) :
function mh_array_get( $array, $address, $default = '' ) {
		$keys   = is_array( $address ) ? $address : explode( '.', $address );
		$value  = $array;

		foreach ( $keys as $key ) {
			if ( ! empty( $key ) && isset( $key[0] ) && '[' === $key[0] ) {
				$index = substr( $key, 1, -1 );

				if ( is_numeric( $index ) ) {
					$key = (int) $index;
				}
			}

			if ( ! isset( $value[ $key ] ) ) {
				return $default;
			}

			$value = $value[ $key ];
		}

		return $value;
}
endif;
/**
 * Listen to all GET mh_action
 */
function mh_get_actions() {
	$key = ! empty( $_GET['mh_action'] ) ? sanitize_key( $_GET['mh_action'] ) : false;

	if ( ! empty( $key ) ) {
		do_action( "mh_{$key}" , $_GET );
	}
}
add_action( 'init', 'mh_get_actions' );

/**
 * Listen to all POST mh_action
 */
function mh_post_actions() {
	$key = ! empty( $_POST['mh_action'] ) ? sanitize_key( $_POST['mh_action'] ) : false;


	if ( ! empty( $key ) ) {
		do_action( "mh_{$key}", $_POST );
	}
}
add_action( 'init', 'mh_post_actions' );

/**
 * Get an array of active required plugins and mharty plugins.
 * this is to check when installing plugins and applying layouts and sections etc.
 */
if ( ! function_exists( 'mharty_active_plugins' ) ) :
function mharty_active_plugins() {
    $plugins_array = array();
    
    if ( class_exists( 'MHComposer', false ) )
        $plugins_array[] = 'composer';
    if ( class_exists( 'MHShop', false ) )
        $plugins_array[] = 'shop';
	if ( class_exists( 'MHLoveitClass', false ) )
        $plugins_array[] = 'loveit';
    if ( class_exists( 'MHReviewsClass', false ) )
        $plugins_array[] = 'reviews';
    if( class_exists( 'MHMagazine', false ) )
        $plugins_array[] = 'magazine';
    if( class_exists( 'MHMoreIconsClass', false ) )
        $plugins_array[] = 'icons';
    if( class_exists( 'Mh_Author_Page_Cover', false ) )
        $plugins_array[] = 'author';
		if( is_plugin_active( 'mh-shortcodes/mh-shortcodes.php' ) )
        $plugins_array[] = 'shortcodes';
		if( is_plugin_active( 'mh-social-proof/mh-social-proof.php' ) )
				$plugins_array[] = 'socialproof';
    if( is_plugin_active( 'classic-editor/classic-editor.php' ) )
        $plugins_array[] = 'classiceditor';
    if( is_plugin_active( 'classic-widgets/classic-widgets.php' ) )
        $plugins_array[] = 'classicwidgets';
    
    return $plugins_array;
}
endif;
/**
 * Get default_color_scheme
 */
if ( ! function_exists( 'mh_default_color_scheme' ) ) :
function mh_default_color_scheme($post_id = 0) {
	$default_scheme = array(
		'#444444',
		'#cccccc',
		'#f2f2f2',
		'#E09900',
		'#EDF000',
		'#7CDA24',
		'#0C71C3',
		'#8300E9',
	);

	$saved_scheme = mh_get_option( 'mharty_color_scheme' );

	$scheme = $saved_scheme && '' !== str_replace( '|', '', $saved_scheme ) ? explode( '|', $saved_scheme ) : $default_scheme;
	
	return apply_filters( 'mh_default_color_scheme', $scheme, $post_id );
}
endif;

if ( ! function_exists( 'mh_use_responsive_images' ) ):
function mh_use_responsive_images() {

    $enable_responsive_images = mh_get_option( 'mharty_disable_responsive_images', false);
    if ( null === $enable_responsive_images ) {
      $enable_responsive_images = 'on';
    }
  
	return $enable_responsive_images;
}
endif;

if ( ! function_exists( 'mh_device_breakpoints' ) ) :
function mh_device_breakpoints() {
	return array(
		'desktop' => 1280,
		'tablet'  => 980,
		'phone'   => 480,
	);
}
endif;

if ( ! function_exists( 'mh_get_responsive_images' ) ) :
function mh_get_responsive_images( $orig_width, $orig_height, $breakpoint ) {
	$mh_device_breakpoints = mh_device_breakpoints();

	if ( ! isset( $mh_device_breakpoints[ $breakpoint ] ) ) {
		return false;
	}

	$new_width = $mh_device_breakpoints[ $breakpoint ];

	if ( $new_width >= $orig_width ) {
		return false;
	}

	$ratio = ( $orig_width * 1.0 ) / $orig_height;

	$new_height = round( ( $new_width / $ratio ) );

	return array(
		'width'  => $new_width,
		'height' => $new_height,
	);
}
endif;

// Add srcset and sizes to img
if ( ! function_exists( 'mh_images_add_srcset_and_sizes' ) ) :
function mh_images_add_srcset_and_sizes( $image, $echo = false ) {
	static $srcset_and_sizes_cached = array();

	if (!mh_use_responsive_images() ) {
		if ( $echo ) {
			echo mh_passthru_unescaped( $image, 'html' );
		}
		return $image;
	}

	$src = mh_get_src_from_img_tag( $image );

	$cache_key = $src ? $src : 'empty-src';

	if ( isset( $srcset_and_sizes_cached[ $cache_key ] ) ) {
		$image = $srcset_and_sizes_cached[ $cache_key ];
	} else {

		if ( $src ) {
			$attachment_id = mh_get_attachment_id_by_url( $src );
			$image_meta    = false;

			if ( $attachment_id ) {
				$image_meta = wp_get_attachment_metadata( $attachment_id );
			}

			if ( $image_meta ) {
				$image = wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
			}
		}

		$srcset_and_sizes_cached[ $cache_key ] = $image;
	}

	if ( $echo ) {
		echo mh_passthru_unescaped( $image, 'html' );
	}

	return $image;
}
endif;

if ( ! function_exists( 'mh_get_attachment_id_by_url_sql' ) ) :
	function mh_get_attachment_id_by_url_sql( $normalized_url ) {
		global $wpdb;
    
		$cleaned_url = preg_replace( '/^https?:/i', '', $normalized_url );
		$fallback_url = preg_replace( '/-(\d+)x(\d+)\.(jpg|jpeg|gif|png|svg|webp)$/', '.$3', $cleaned_url );

		if ( $cleaned_url === $fallback_url ) {
			$attachments_query = $wpdb->prepare(
				"SELECT id
				FROM $wpdb->posts
				WHERE `post_type` = %s
					AND `guid` IN ( %s, %s )",
				'attachment',
				esc_url_raw( "https:{$cleaned_url}" ),
				esc_url_raw( "http:{$cleaned_url}" )
			);
		} else {
			$attachments_query = $wpdb->prepare(
				"SELECT id
				FROM $wpdb->posts
				WHERE `post_type` = %s
					AND `guid` IN ( %s, %s, %s, %s )
				ORDER BY CHAR_LENGTH( `guid` ) DESC",
				'attachment',
				esc_url_raw( "https:{$cleaned_url}" ),
				esc_url_raw( "https:{$fallback_url}" ),
				esc_url_raw( "http:{$cleaned_url}" ),
				esc_url_raw( "http:{$fallback_url}" )
			);
		}

		return $attachments_query;
	}
endif;

if ( ! function_exists( 'mh_get_attachment_id_by_url' ) ) :
function mh_get_attachment_id_by_url( $url ) {
	global $wpdb;
	$attachment_id_pre = apply_filters( 'mh_get_attachment_id_by_url_pre', false, $url );

	if ( false !== $attachment_id_pre ) {
		return $attachment_id_pre;
	}

	$url = apply_filters( 'mh_get_attachment_id_by_url_guid', $url );
	$normalized_url = mh_attachment_normalize_url( $url );
  
	if ( ! $normalized_url ) {
		return 0;
	}

	$attachments_sql_query = mh_get_attachment_id_by_url_sql( $normalized_url );
	$attachment_id         = (int) $wpdb->get_var( $attachments_sql_query );

	if ( ! $attachment_id && false !== strpos( $normalized_url, '-scaled.' ) ) {
		$normalized_url_not_scaled = str_replace( '-scaled.', '.', $normalized_url );
		$attachments_sql_query     = mh_get_attachment_id_by_url_sql( $normalized_url_not_scaled );
		$attachment_id             = (int) $wpdb->get_var( $attachments_sql_query );
	}

	if ( ! $attachment_id ) {
		$uploads         = wp_get_upload_dir();
		$uploads_baseurl = trailingslashit( $uploads['baseurl'] );

		if ( 0 === strpos( $normalized_url, $uploads_baseurl ) ) {
			$file_path = str_replace( $uploads_baseurl, '', $normalized_url );
			$file_path_no_resize = preg_replace( '/-(\d+)x(\d+)\.(jpg|jpeg|gif|png|svg|webp)$/', '.$3', $file_path );

			if ( $file_path === $file_path_no_resize ) {
				$attachments_sql_query = $wpdb->prepare(
					"SELECT post_id
					FROM $wpdb->postmeta
					WHERE `meta_key` = %s
						AND `meta_value` = %s",
					'_wp_attached_file',
					$file_path
				);
			} else {
				$attachments_sql_query = $wpdb->prepare(
					"SELECT post_id
					FROM $wpdb->postmeta
					WHERE `meta_key` = %s
						AND `meta_value` IN ( %s, %s )
					ORDER BY CHAR_LENGTH( `meta_value` ) DESC",
					'_wp_attached_file',
					$file_path,
					$file_path_no_resize
				);
			}

			$attachment_id = (int) $wpdb->get_var( $attachments_sql_query );
		}
	}
  
	return $attachment_id;
}
endif;

if ( ! function_exists( 'mh_get_attachment_size_by_url' ) ) :
function mh_get_attachment_size_by_url( $url, $default_size = 'full' ) {
	$normalized_url = mh_attachment_normalize_url( $url );

	if ( ! $normalized_url ) {
		return $default_size;
	}

	$attachment_id = mh_get_attachment_id_by_url( $url );

	if ( ! $attachment_id ) {
		return $default_size;
	}

	$metadata = wp_get_attachment_metadata( $attachment_id );

	if ( ! $metadata ) {
		return $default_size;
	}

	$size = $default_size;

	if ( strpos( $url, $metadata['file'] ) === ( strlen( $url ) - strlen( $metadata['file'] ) ) ) {
		$size = array( $metadata['width'], $metadata['height'] );
	} elseif ( preg_match( '/-(\d+)x(\d+)\.(jpg|jpeg|gif|png|svg|webp)$/', $url, $match ) ) {
		$size = array( $match[1], $match[2] );
	}

	return $size;
}
endif;

if ( ! function_exists( 'mh_get_image_srcset_sizes' ) ) :
function mh_get_image_srcset_sizes( $url ) {
	$normalized_url = mh_attachment_normalize_url( $url );

	if ( ! $normalized_url ) {
		return array();
	}

	$attachment_id = mh_get_attachment_id_by_url( $url );
	if ( ! $attachment_id ) {
		return array();
	}

	$image_size = mh_get_attachment_size_by_url( $url );
	if ( ! $image_size ) {
		return array();
	}

	$srcset = wp_get_attachment_image_srcset( $attachment_id, $image_size );
	$sizes  = wp_get_attachment_image_sizes( $attachment_id, $image_size );

	if ( ! $srcset || ! $sizes ) {
		return array();
	}

	$data = array(
		'srcset' => $srcset,
		'sizes'  => $sizes,
	);

	return $data;
}
endif;

if ( ! function_exists( 'mh_attachment_normalize_url' ) ) :

function mh_attachment_normalize_url( $url ) {
	list( $url ) = explode( '?', $url );
  
	$url = str_replace( '%26%23215%3B', 'x', rawurlencode( $url ) );
	$url = rawurldecode( $url );

	if ( 0 !== strpos( $url, 'http' ) ) {
		$wp_upload_dir = wp_upload_dir( null, false );
		$upload_dir    = str_replace( site_url( '/' ), '', $wp_upload_dir['baseurl'] );
		$url_trimmed   = ltrim( $url, '/' );

		if ( 0 === strpos( $url_trimmed, $upload_dir ) || 0 === strpos( $url_trimmed, 'wp-content' ) ) {
			$url = site_url( $url_trimmed );
		} else {
			$url = $wp_upload_dir['baseurl'] . '/' . $url_trimmed;
		}
	}

	if ( ! filter_var( $url, FILTER_VALIDATE_URL ) || ! preg_match( '/^(.+)\.(jpg|jpeg|gif|png|svg|webp)$/', $url ) ) {
		return false;
	}

	return esc_url( $url );
}
endif;

if ( ! function_exists( 'mh_uploads_dir_url' ) ) :
function mh_uploads_dir_url( $url ) {
	$upload_dir = wp_upload_dir( null, false );

	return mh_starts_with( $url, $upload_dir['baseurl'] );
}
endif;

if ( ! function_exists( 'mh_get_src_from_img_tag' ) ) :
function mh_get_src_from_img_tag( $image ) {
	if ( preg_match( '/^<img.+src=[\'"](?P<src>.+?)[\'"].*>/', $image, $match ) ) {
		if ( isset( $match['src'] ) ) {
			return $match['src'];
		}
	}

	if ( class_exists( 'DOMDocument' ) && class_exists( 'DOMXPath' ) ) {
		$doc = new DOMDocument();
		$doc->loadHTML( $image );

		$xpath = new DOMXPath( $doc );
		return $xpath->evaluate( 'string(//img/@src)' );
	}

	return false;
}
endif;

if ( ! function_exists( 'mh_get_image_attachment_class' ) ):
function mh_get_image_attachment_class( $attrs, $source_key, $attachment_id = 0 ) {
		$attachment_class = '';
   if (!mh_use_responsive_images ()){
     if ( ! empty( $source_key ) ) {
			$attachment_src = mh_array_get( $attrs, $source_key, '' );
			$attachment_id  = mh_get_attachment_id_by_url( $attachment_src );
		}
  
		if ( $attachment_id > 0 ) {
			$attachment_class = "wp-image-{$attachment_id}";
		}
   }
  
		

		return $attachment_class;
	}
endif;

if ( ! function_exists( 'mh_get_image_width_height' ) ):
function mh_get_image_width_height($src, $size = 'width'){
    $image   = mh_get_attachment_size_by_url( $src );
    $output = '';
    if ('width' === $size){
        $output  = ( ! empty( $image ) && is_numeric( $image[0] ) ) ? $image[0] : '400'; // default logo width
    }
    if ('height' === $size){			
        $output = ( ! empty( $image ) && is_numeric( $image[1] ) ) ? $image[1] : '78'; // default logo height
    }
    return $output;
}
endif;

/**
 * Get post format with filterable output
 */
function mh_post_format() {
	return apply_filters( 'mh_post_format', get_post_format(), get_the_ID() );
}

if( !function_exists( 'get_cfield' ) ):
	function get_cfield($meta = NULL, $id = NULL) {
		if($meta === NULL) {
			return false;
		}
		if ($id === NULL) {
			$id = get_the_ID();
		}
		return get_post_meta( $id, '_mhartys_'.$meta, true );
	}
endif;

/**
 * auto-creation of post excerpts
 */
if ( ! function_exists( 'truncate_post' ) ) {

	function truncate_post( $amount, $echo = true, $post = '', $strip_shortcodes = false ) {

		if ( '' == $post ) global $post;

		$post_excerpt = '';
		$post_excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );

		if ( true == get_theme_mod( 'mharty_use_excerpt' ) && '' != $post_excerpt ) {
			if ( $echo ) echo $post_excerpt;
			else return $post_excerpt;
		} else {
			// get the post content
			$truncate = $post->post_content;

			// remove caption shortcode from post content
			$truncate = preg_replace( '@\[caption[^\]]*?\].*?\[\/caption]@si', '', $truncate );

			// remove audio shortcode from post content to prevent unwanted audio file on the excerpt
			// due to unparsed audio shortcode
			$truncate = preg_replace( '@\[audio[^\]]*?\].*?\[\/audio]@si', '', $truncate );

			// remove embed shortcode from post content
			$truncate = preg_replace( '@\[embed[^\]]*?\].*?\[\/embed]@si', '', $truncate );
			
			// remove breadcrumbs shortcode from post content
			$truncate = preg_replace( '@\[mh_breadcrumbs[^\]]*?\].*?\[\/mh_breadcrumbs]@si', '', $truncate );
			
			// Remove script from post content
			$truncate = preg_replace( '@\<script(.*?)>(.*?)</script>@si', '', html_entity_decode( $truncate ) );

			if ( $strip_shortcodes ) {
				$truncate = mh_strip_shortcodes( $truncate );
			} else {
				// apply content filters
				$truncate = apply_filters( 'the_content', $truncate );
			}

			// decide if we need to append dots at the end of the string
			if ( strlen( $truncate ) <= $amount ) {
				$echo_out = '';
			} else {
				$echo_out = '...';
				// $amount = $amount - 3;
			}

			// trim text to a certain number of characters, also remove spaces from the end of a string ( space counts as a character )
			$truncate = rtrim( mh_wp_trim_words( $truncate, $amount, '' ) );

			// remove the last word to make sure we display all words correctly
			if ( '' != $echo_out ) {
				$new_words_array = (array) explode( ' ', $truncate );
				array_pop( $new_words_array );

				$truncate = implode( ' ', $new_words_array );

				// append dots to the end of the string
				$truncate .= $echo_out;
			}

			if ( $echo ) echo $truncate;
			else return $truncate;
		};
	}

}

/**
 * Trim words in auto-cretead post excerpts
 */
if ( ! function_exists( 'mh_wp_trim_words' ) ){
	function mh_wp_trim_words( $text, $num_words = 55, $more = null ) {
		if ( null === $more )
		$more = esc_html__('&hellip;', 'mharty');
		$original_text = $text;
		$text = wp_strip_all_tags( $text );

		$text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
		preg_match_all( '/./u', $text, $words_array );
		$words_array = array_slice( $words_array[0], 0, $num_words + 1 );
		$sep = '';

		if ( count( $words_array ) > $num_words ) {
			array_pop( $words_array );
			$text = implode( $sep, $words_array );
			$text = $text . $more;
		} else {
			$text = implode( $sep, $words_array );
		}
        
		return $text;
	}
}

/**
 * truncates titles
 * @todo not used?
 */
if ( ! function_exists( 'truncate_title' ) ){
	function truncate_title( $amount, $echo = true, $post = '' ) {
		if ( $post == '' ) $truncate = get_the_title();
		else $truncate = $post->post_title;

		if ( strlen( $truncate ) <= $amount ) $echo_out = '';
		else $echo_out = '...';

		//$truncate = wp_trim_words( $truncate, $amount, '' );
		$truncate = mh_wp_trim_words( $truncate, $amount, '' );

		if ( '' != $echo_out ) $truncate .= $echo_out;

		if ( $echo )
			echo $truncate;
		else
			return $truncate;
	}
}

/**
 * thumbnail from first image in a post
 */
if ( ! function_exists( 'mh_first_image' ) ){
	function mh_first_image() {
		global $post;
		$img = '';
		
		if ( empty( $post->ID ) ) {
			return $img;
		}
		$unprocessed_content = $post->post_content;
		
		// truncate Post based shortcodes/composer to avoid infinite loops
		if ( function_exists( 'mh_strip_shortcodes' ) ) {
			$unprocessed_content = mh_strip_shortcodes( $post->post_content, true );
		}
		
		// apply the_content filter to execute all shortcodes and get the correct image from the processed content
		$processed_content = apply_filters( 'the_content', $unprocessed_content );

		$output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $processed_content, $matches );
		if ( isset( $matches[1][0] ) ) $img = $matches[1][0];

		return trim( $img );
	}
}

/**
 * gets thumbnail from Post Thumbnail or Custom field or First post image
 */
if ( ! function_exists( 'get_thumbnail' ) ) {
	function get_thumbnail($width=100, $height=100, $class='', $alttext='', $titletext='', $fullpath=false, $custom_field='', $post='') {
		if ( $post == '' ) global $post;

		$thumb_array['thumb'] = '';
		$thumb_array['use_timthumb'] = true;
		if ($fullpath) $thumb_array['fullpath'] = ''; //full image url for lightbox

		$new_method = true;

		if ( has_post_thumbnail( $post->ID  ) || 'attachment' === $post->post_type ) {
			$thumb_array['use_timthumb'] = false;

			$mh_fullpath = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
      
    if ( is_array( $mh_fullpath ) ) {
			$thumb_array['fullpath'] = $mh_fullpath[0];
			$thumb_array['thumb'] = $thumb_array['fullpath'];
		}
    }
		if (empty( $thumb_array['thumb'] )) {
			if (empty( $custom_field )) $thumb_array['thumb'] = esc_attr( get_post_meta($post->ID, 'Thumbnail', $single = true) );
			else {
				$thumb_array['thumb'] = esc_attr( get_post_meta($post->ID, $custom_field, $single = true) );
				if (empty( $thumb_array['thumb'] )) $thumb_array['thumb'] = esc_attr( get_post_meta($post->ID, 'Thumbnail', $single = true) );
			}

			if ('' == $thumb_array['thumb'] && mh_grab_image_option()) {
				$thumb_array['thumb'] = esc_attr( mh_first_image() );
				if ( $fullpath ) $thumb_array['fullpath'] = $thumb_array['thumb'];
			}

			#if custom field used for small pre-cropped image, open Thumbnail custom field image in lightbox
      if ($fullpath) {
				$thumb_array['fullpath'] = $thumb_array['thumb'];
				if ( empty( $custom_field ) ) $thumb_array['fullpath'] = apply_filters( 'mh_fullpath', mh_path_reltoabs( esc_attr( $thumb_array['thumb'] ) ) );
				elseif ( ! empty( $custom_field ) && get_post_meta( $post->ID, 'Thumbnail', $single = true ) ) $thumb_array['fullpath'] = apply_filters( 'mh_fullpath', mh_path_reltoabs( esc_attr( get_post_meta( $post->ID, 'Thumbnail', $single = true ) ) ) );
			}
		}

		return $thumb_array;
	}
}
if ( ! function_exists( 'mh_grab_image_option' ) ) :

/**
 * check for "mharty_grab_image" setting
 */
function mh_grab_image_option() {
	// Force disable "Grab the first post image" in BuddyPress component page
	$is_buddypress_component = function_exists( 'bp_current_component' ) && bp_current_component();

	$setting = true === get_theme_mod( 'mharty_grab_image' ) && ! $is_buddypress_component;

	return apply_filters( 'mh_grab_image_option', $setting );
}
endif;

/**
 * print thumbnail from Post Thumbnail or Custom field or First post image
 */
if ( ! function_exists( 'print_thumbnail' ) ) {
	function print_thumbnail($thumbnail = '', $use_timthumb = true, $alttext = '', $width = 100, $height = 100, $class = '', $echoout = true, $forstyle = false, $resize = true, $post='', $mh_post_id = '' ) {
		if ( is_array( $thumbnail ) ){
			extract( $thumbnail );
		}

		if ( empty( $post ) )  global $post, $mh_theme_image_sizes;

		$output = '';
        $raw = false;
        $thumbnail_orig = $thumbnail;
		$mh_post_id = '' != $mh_post_id ? (int) $mh_post_id : $post->ID;

		if ( has_post_thumbnail( $mh_post_id ) ) {
			$thumb_array['use_timthumb'] = false;

			$image_size_name = $width . 'x' . $height;
			$mh_size = isset( $mh_theme_image_sizes ) && array_key_exists( $image_size_name, $mh_theme_image_sizes ) ? $mh_theme_image_sizes[$image_size_name] : array( $width, $height );

			$mh_attachment_image_attributes = wp_get_attachment_image_src( get_post_thumbnail_id( $mh_post_id ), $mh_size );
			$thumbnail = !empty( $mh_attachment_image_attributes[0] ) ? $mh_attachment_image_attributes[0] : '';
		} else {
			$thumbnail = mh_multisite_thumbnail( $thumbnail );

			$cropPosition = '';

			$allow_new_thumb_method = false;

			$new_method = true;
			$new_method_thumb = '';
			$external_source = false;

			$allow_new_thumb_method = !$external_source && $new_method && $cropPosition == '';
            
      if ( $allow_new_thumb_method && !empty( $thumbnail ) ) {
				if ( 'data:image' === substr( $thumbnail, 0, 10 ) ) {
					$new_method_thumb = $thumbnail;
					$raw              = true;
				} else {
					$mh_crop          = get_post_meta( $post->ID, 'mh_nocrop', true );
					$mh_crop          = empty($mh_crop ) ? true : false;
					$new_method_thumb = mh_resize_image( mh_path_reltoabs( $thumbnail ), $width, $height, $mh_crop );
					if ( is_wp_error( $new_method_thumb ) ) {
						$new_method_thumb = '';
					}
				}
			}
            
            
			$thumbnail = $new_method_thumb;
		}
        
    if ( false === $forstyle && $resize ) {
			if ( $width < 480 && !mh_use_responsive_images() && ! $raw ) {
				$output = sprintf(
					'<img src="%1$s" alt="%2$s" class="%3$s" srcset="%4$s " sizes="%5$s " %6$s />',
					esc_url( $thumbnail ),
					esc_attr( wp_strip_all_tags( $alttext ) ),
					empty( $class ) ? '' : esc_attr( $class ),
					$thumbnail_orig . ' 479w, ' . $thumbnail . ' 480w',
					'(max-width:479px) 479px, 100vw',
					apply_filters( 'mh_print_thumbnail_dimensions', ' width="' . esc_attr( $width ) . '" height="' . esc_attr( $height ) . '"' )
				);
			} else {
				$output = sprintf(
					'<img src="%1$s" alt="%2$s" class="%3$s"%4$s />',
					$raw ? $thumbnail : esc_url( $thumbnail ),
					esc_attr( wp_strip_all_tags( $alttext ) ),
					empty( $class ) ? '' : esc_attr( $class ),
					apply_filters( 'mh_print_thumbnail_dimensions', ' width="' . esc_attr( $width ) . '" height="' . esc_attr( $height ) . '"' )
				);

				if ( ! $raw ) {
					$output = mh_images_add_srcset_and_sizes( $output );
				}
			}
		} else {
			$output = $thumbnail;
		}

		if ($echoout) echo $output;
		else return $output;
	}
}

/**
 * resize the new thumbnail
 */
if ( ! function_exists( 'mh_new_thumb_resize' ) ){
	function mh_new_thumb_resize( $thumbnail, $width, $height, $alt='', $forstyle = false ){

		$new_method = true;
		$new_method_thumb = '';
		$external_source = false;

		$allow_new_thumb_method = !$external_source && $new_method;

		if ( $allow_new_thumb_method && ! empty( $thumbnail ) ){
			$mh_crop = true;
			$new_method_thumb = mh_resize_image( $thumbnail, $width, $height, $mh_crop );
			if ( is_wp_error( $new_method_thumb ) ) $new_method_thumb = '';
		}

		$thumb = esc_attr( $new_method_thumb );
    
    if ( $forstyle ) {
			return $thumb;
		}
    
    $output = sprintf(
			'<img src="%1$s" alt="%2$s" width="%3$s" height="%4$s" />',
			esc_url( $thumb ),
			esc_attr( $alt ),
			esc_attr( $width ),
			esc_attr( $height )
		);
    
    return mh_images_add_srcset_and_sizes( $output );
	}
}

/**
 * multisite thumbnail
 */
if ( ! function_exists( 'mh_multisite_thumbnail' ) ){
	function mh_multisite_thumbnail( $thumbnail = '' ) {
		// do nothing if it's not a Multisite installation or current site is the main one
		if ( is_main_site() ) return $thumbnail;

		# get the real image url
		preg_match( '#([_0-9a-zA-Z-]+/)?files/(.+)#', $thumbnail, $matches );
		if ( isset( $matches[2] ) ){
			$file = rtrim( BLOGUPLOADDIR, '/' ) . '/' . str_replace( '..', '', $matches[2] );
			if ( is_file( $file ) ) $thumbnail = str_replace( ABSPATH, trailingslashit( get_site_url( 1 ) ), $file );
			else $thumbnail = '';
		}

		return $thumbnail;
	}
}

/**
 * is the image portrait?
 */
if ( ! function_exists( 'mh_is_portrait' ) ){
	function mh_is_portrait($imageurl, $post='', $ignore_cfields = false){
		if ( $post == '' ) global $post;

		if ( get_post_meta($post->ID,'mh_disable_portrait',true) == 1 ) return false;

		if ( !$ignore_cfields ) {
			if ( get_post_meta($post->ID,'mh_imagetype',true) == 'l' ) return false;
			if ( get_post_meta($post->ID,'mh_imagetype',true) == 'p' ) return true;
		}

		$imageurl = mh_path_reltoabs(mh_multisite_thumbnail($imageurl));

		$mh_thumb_size = @getimagesize($imageurl);
		if ( empty($mh_thumb_size) ) {
			$mh_thumb_size = @getimagesize( str_replace( WP_CONTENT_URL, WP_CONTENT_DIR, $imageurl ) );
			if ( empty($mh_thumb_size) ) return false;
		}
		$mh_thumb_width = $mh_thumb_size[0];
		$mh_thumb_height = $mh_thumb_size[1];

		$result = ($mh_thumb_width < $mh_thumb_height) ? true : false;

		return $result;
	}
}

/**
 * is the image portrait?
 */
if ( ! function_exists( 'mh_path_reltoabs' ) ){
	function mh_path_reltoabs( $imageurl ){
		if ( strpos(strtolower($imageurl), 'http://') !== false || strpos(strtolower($imageurl), 'https://') !== false ) return $imageurl;

		if ( strpos( strtolower($imageurl), $_SERVER['HTTP_HOST'] ) !== false )
			return $imageurl;
		else {
			$imageurl = esc_url( apply_filters( 'mh_path_relative_image', site_url() . '/' ) . $imageurl );
		}

		return $imageurl;
	}
}

/**
 * inject code in head via theme panel
 */
function integration_head(){
	if (mh_get_option('mharty_integration_head') <> '' && mh_get_option('mharty_integrate_header_enable') == true) echo( mh_get_option('mharty_integration_head') );
}
add_action('wp_head','integration_head',12);

/**
 * inject code in body via theme panel
 */
function integration_body(){
	if (mh_get_option('mharty_integration_body') <> '' && mh_get_option('mharty_integrate_body_enable') == true) echo( mh_get_option('mharty_integration_body') );
}
add_action('wp_footer','integration_body',12);

/**
 * inject code after main menu via theme panel
 */
function integration_after_menu(){
	 if (mh_get_option('mharty_integration_after_menu') <> '' && mh_get_option('mharty_integrate_after_menu_enable') == true) echo( mh_get_option('mharty_integration_after_menu') );
}
add_action('mh_before_content','integration_after_menu',1);


/**
 * inject code before footer via theme panel
 */
function integration_before_footer(){
 if (mh_get_option('mharty_integration_before_footer') <> '' && mh_get_option('mharty_integrate_before_footer_enable') == true) echo( mh_get_option('mharty_integration_before_footer') ); 
}
add_action('mh_after_content','integration_before_footer',1);


/**
 * if WPML plugin is installed transforms an array of posts, pages, post_tags or categories ids into corresponding "objects" ids
 */
if ( ! function_exists( 'mh_generate_wpml_ids' ) ){
	function mh_generate_wpml_ids( $ids_array, $type ) {
		if ( function_exists( 'icl_object_id' ) ){
			$wpml_ids = array();
			foreach ( $ids_array as $id ) {
				$translated_id = icl_object_id( $id, $type, false );
				if ( ! is_null( $translated_id ) ) $wpml_ids[] = $translated_id;
			}
			$ids_array = $wpml_ids;
		}

		return array_map( 'intval', $ids_array );
	}
}

/**
 * Returns true if static page is set in WP-Admin / Settings / Reading
 * and Posts page is displayed
 */
if ( ! function_exists( 'mharty_is_blog_posts_page' ) ){
	function mharty_is_blog_posts_page() {

		static $mh_is_blog_posts_cached = null;

		if ( null === $mh_is_blog_posts_cached ) {
			$mh_is_blog_posts_cached = (bool) is_home() && 0 !== intval( get_option( 'page_for_posts', '0' ) );
		}

		return $mh_is_blog_posts_cached;
	}
}

/**
 * backwards compatibility
 */
if ( ! function_exists( 'mharty_titles' ) ){
	function mharty_titles() {
		if ( ! function_exists( 'wp_get_document_title' ) ) {
			wp_title();
		} else {
			echo wp_get_document_title();
		}
	}
}


/**
 * add seo meta for titles
 */
if ( ! function_exists( 'mharty_titles_filter' ) ){
	function mharty_titles_filter( $custom_title){

		$custom_title = '';

		$sitename = get_bloginfo('name');
		$site_description = get_bloginfo('description');

		#if the title is being displayed on the homepage
		if ( ( is_home() || is_front_page() ) && ! mharty_is_blog_posts_page() ) {
			if ( true == mh_get_option( 'mharty_seo_home_title' ) ) {
				$custom_title = mh_get_option( 'mharty_seo_home_titletext' );
			} else {
				$seo_home_type = mh_get_option( 'mharty_seo_home_type' );
				$seo_home_separate = mh_get_option( 'mharty_seo_home_separate', ' | ' );

				if ( $seo_home_type == '0' ) {
					$custom_title = $sitename . esc_html( $seo_home_separate ) . $site_description;
				}
				if ( $seo_home_type == '1') {
					$custom_title = $site_description . esc_html( $seo_home_separate ) . $sitename;
				}
				if ( $seo_home_type == '2') {
					$custom_title = $sitename;
				}
			}
		}

		#if the title is being displayed on single posts/pages
		if ( ( ( is_single() || is_page() ) && ! is_front_page() ) || mharty_is_blog_posts_page() ) {
     
			global $wp_query;
			$postid = mharty_is_blog_posts_page() ? intval( get_option( 'page_for_posts' ) ) : $wp_query->post->ID;
			$key = mh_get_option('mharty_seo_single_field_title');
			$exists3 = get_post_meta($postid, ''.$key.'', true);
      
      
			if ( true == mh_get_option( 'mharty_seo_single_title' ) && '' !== $exists3 ) {
				$custom_title = $exists3;
			} else {
				$seo_single_type = mh_get_option( 'mharty_seo_single_type' );
				$seo_single_separate = mh_get_option( 'mharty_seo_single_separate', ' | ' );
				$page_title = single_post_title( '', false );

				if ( $seo_single_type == '0' ) {
					$custom_title = $sitename . esc_html( $seo_single_separate ) . $page_title;
				}

				if ( $seo_single_type == '1' ) {
					$custom_title = $page_title . esc_html( $seo_single_separate ) . $sitename;
				}

				if ( $seo_single_type == '2' ) {
					$custom_title = $page_title;
				}
			}
		}

		#if the title is being displayed on index pages (categories/archives/search results)
		if ( is_category() || is_archive() || is_search() || is_404() ) {
			$page_title = '';

			$seo_index_type = mh_get_option( 'mharty_seo_index_type' );
			$seo_index_separate = mh_get_option( 'mharty_seo_index_separate', ' | ' );

			if ( is_category() || is_tag() || is_tax() ) {
				$page_title = single_term_title( '', false );
			} else if ( is_post_type_archive() ) {
				$page_title = post_type_archive_title( '', false );
			} else if ( is_author() ) {
				$page_title = get_the_author_meta( 'display_name', get_query_var( 'author' ) );
			} else if ( is_date() ) {
				$page_title = esc_html__( 'Archives', 'mharty' );
			} else if ( is_search() ) {
				$page_title = sprintf( esc_html__( 'Search results for "%s"', 'mharty' ), esc_attr( get_search_query() ) );
			} else if ( is_404() ) {
				$page_title = esc_html__( '404 Not Found', 'mharty' );
			}

			if ( $seo_index_type == '0' ) {
				$custom_title = $sitename . esc_html( $seo_index_separate ) . $page_title;
			}

			if ( $seo_index_type == '1') {
				$custom_title = $page_title . esc_html( $seo_index_separate ) . $sitename;
			}

			if ( $seo_index_type == '2') {
				$custom_title = $page_title;
			}
		}

		// Improves compatibility with SEO plugins
		$custom_title = wp_strip_all_tags( $custom_title );
		return $custom_title;
	}
}
add_filter( 'pre_get_document_title', 'mharty_titles_filter');

/**
 * create image temp folder
 */
function mh_create_images_temp_folder(){
	#clean mh_temp folder once per week
	if ( false !== $last_time = get_option( 'mh_schedule_clean_images_last_time'  ) ){
		$timeout = 86400 * 7;
		if ( ( $timeout < ( time() - $last_time ) ) && '' != get_option( 'mh_images_temp_folder' ) ) mh_clean_temp_images( get_option( 'mh_images_temp_folder' ) );
	}

	if ( false !== get_option( 'mh_images_temp_folder' ) ) return;

	$uploads_dir = wp_upload_dir();
	$destination_dir = ( false === $uploads_dir['error'] ) ? path_join( $uploads_dir['basedir'], 'mh_temp' ) : null;

	if ( ! wp_mkdir_p( $destination_dir ) ) update_option( 'mh_images_temp_folder', '' );
	else {
		update_option( 'mh_images_temp_folder', preg_replace( '#\/\/#', '/', $destination_dir ) );
		update_option( 'mh_schedule_clean_images_last_time', time() );
	}
}
add_action( 'init', 'mh_create_images_temp_folder' );

/**
 * clean image temp folder every 7 days
 */
if ( ! function_exists( 'mh_clean_temp_images' ) ){
	function mh_clean_temp_images( $directory ){
		$dir_to_clean = @ opendir( $directory );

		if ( $dir_to_clean ) {
			while (($file = readdir( $dir_to_clean ) ) !== false ) {
				if ( substr($file, 0, 1) == '.' )
					continue;
				if ( is_dir( $directory.'/'.$file ) )
					mh_clean_temp_images( path_join( $directory, $file ) );

				else
					@ unlink( path_join( $directory, $file ) );
			}
			closedir( $dir_to_clean );
		}

		#set last time cleaning was performed
		update_option( 'mh_schedule_clean_images_last_time', time() );
	}
}
/**
 * check if 'mh_temp' folder exist within $uploads_dir['basedir'] directory. Otherwise try creating it. If it's not possible return null
 */
function mh_update_uploads_dir( $upload_path ){
	$destination_dir = '';
	$uploads_dir = wp_upload_dir();
	$mh_temp_dir = path_join( $uploads_dir['basedir'], 'mh_temp' );

	if ( is_dir( $mh_temp_dir ) || ( false === $uploads_dir['error'] && wp_mkdir_p( $mh_temp_dir ) ) ){
		$destination_dir = $mh_temp_dir;
		update_option( 'mh_schedule_clean_images_last_time', time() );
	}

	update_option( 'mh_images_temp_folder', preg_replace( '#\/\/#', '/', $destination_dir ) );

	return $upload_path;
}
add_filter( 'update_option_upload_path', 'mh_update_uploads_dir' );

/**
 * Fixes the issue with x in filenames e.g -400x400.png
 */
if ( ! function_exists( 'mh_resize_image' ) ){
	function mh_resize_image( $thumb, $new_width, $new_height, $crop ){
	
		$thumb = str_replace( '%26%23215%3B', 'x', rawurlencode( $thumb ) );
		$thumb = rawurldecode( $thumb );

		if ( is_ssl() ) $thumb = preg_replace( '#^http://#', 'https://', $thumb );
		$info = pathinfo($thumb);
		$ext = $info['extension'];
		$name = wp_basename($thumb, ".$ext");
		$is_jpeg = false;
		$site_uri = apply_filters( 'mh_resize_image_site_uri', site_url() );
		$site_dir = apply_filters( 'mh_resize_image_site_dir', ABSPATH );

		if ( is_multisite() && ! is_main_site() && ( ! function_exists( 'wp_get_mime_types' ) || get_site_option( 'ms_files_rewriting' ) ) ) {

			switch_to_blog( 1 );
			$site_uri = site_url();
			restore_current_blog();
		}

		if ( false === strpos( $thumb, $site_uri ) )
			return $thumb;

		if ( 'jpeg' == $ext ) {
			$ext = 'jpg';
			$name = preg_replace( '#.jpeg$#', '', $name );
			$is_jpeg = true;
		}

		$suffix = "{$new_width}x{$new_height}";

		$destination_dir = '' != get_option( 'mh_images_temp_folder' ) ? preg_replace( '#\/\/#', '/', get_option( 'mh_images_temp_folder' ) ) : null;

		$matches = apply_filters( 'mh_resize_image_site_dir', array(), $site_dir );
		if ( !empty($matches) ){
			preg_match( '#'.$matches[1].'$#', $site_uri, $site_uri_matches );
			if ( !empty($site_uri_matches) ){
				$site_uri = str_replace( $matches[1], '', $site_uri );
				$site_uri = preg_replace( '#/$#', '', $site_uri );
				$site_dir = str_replace( $matches[1], '', $site_dir );
				$site_dir = preg_replace( '#\\\/$#', '', $site_dir );
			}
		}

		$localfile = str_replace( apply_filters( 'mh_resize_image_localfile', $site_uri, $site_dir, mh_multisite_thumbnail($thumb) ), $site_dir, mh_multisite_thumbnail($thumb) );

		$add_to_suffix = '';
		if ( file_exists( $localfile ) ) $add_to_suffix = filesize( $localfile ) . '_';

		$suffix = $add_to_suffix . $suffix;
		$destfilename_attributes = '-' . $suffix . '.' . strtolower( $ext );

		$checkfilename = ( '' != $destination_dir && null !== $destination_dir ) ? path_join( $destination_dir, $name ) : path_join( dirname( $localfile ), $name );
		$checkfilename .= $destfilename_attributes;

		if ( $is_jpeg ) $checkfilename = preg_replace( '#.jpg$#', '.jpeg', $checkfilename );

		$uploads_dir = wp_upload_dir();
		$uploads_dir['basedir'] = preg_replace( '#\/\/#', '/', $uploads_dir['basedir'] );

		if ( null !== $destination_dir && '' != $destination_dir && apply_filters('mh_enable_uploads_detection', true) ){
			$site_dir = trailingslashit( preg_replace( '#\/\/#', '/', $uploads_dir['basedir'] ) );
			$site_uri = trailingslashit( $uploads_dir['baseurl'] );
		}

		if ( file_exists( $checkfilename ) ) return str_replace( $site_dir, trailingslashit( $site_uri ), $checkfilename );

		$size = @getimagesize( $localfile );
		if ( !$size ) return new WP_Error('invalid_image_path', esc_html__('Image doesn\'t exist', 'mharty'), $thumb);
		list($orig_width, $orig_height, $orig_type) = $size;

		if ( $orig_width > $new_width || $orig_height > $new_height ){
			if ( $orig_width < $new_width || $orig_height < $new_height ){
				if ( $orig_width < $new_width ) $new_width = $orig_width;
				if ( $orig_height < $new_height ) $new_height = $orig_height;

				$suffix = "{$add_to_suffix}{$new_width}x{$new_height}";
				$destfilename_attributes = '-' . $suffix . '.' . $ext;

				$checkfilename = ( '' != $destination_dir && null !== $destination_dir ) ? path_join( $destination_dir, $name ) : path_join( dirname( $localfile ), $name );
				$checkfilename .= $destfilename_attributes;
                
				if ( file_exists($checkfilename) ) return str_replace( $site_dir, trailingslashit( $site_uri ), $checkfilename );
			}
      
      $mh_image_editor = wp_get_image_editor( $localfile );

      if ( ! is_wp_error( $mh_image_editor ) ) {
        $mh_image_editor->resize( $new_width, $new_height, $crop );

        $mh_new_image_name = $mh_image_editor->generate_filename( $suffix, $destination_dir );

        do_action( 'mh_resize_image_before_save', $mh_image_editor, $mh_new_image_name );

        $mh_image_editor->save( $mh_new_image_name );

        $result = $mh_new_image_name;
      } else {
        $result = $mh_image_editor;
      }

			if ( ! is_wp_error( $result ) ) {
				if ( $is_jpeg ) $thumb = preg_replace( '#.jpeg$#', '.jpg', $thumb);
				$site_dir = str_replace( '\\', '/', $site_dir );
                
				$result = str_replace( '\\', '/', $result );
				$result = str_replace( '//', '/', $result );
				$result = str_replace( $site_dir, trailingslashit( $site_uri ), $result );
			}
            
			return $result;
		}
        
		return $thumb;
	}
}

/**
 * posts per page
 */
function mh_custom_posts_per_page( $query = false ) {

	if ( is_admin() ) return;

	if ( ! is_a( $query, 'WP_Query' ) || ! $query->is_main_query() ) return;

	if ( $query->is_category ) {
		$query->set( 'posts_per_page', (int) get_theme_mod( 'mharty_catnum_posts', '10' ) );
	} elseif ( $query->is_tag ) {
		$query->set( 'posts_per_page', (int) get_theme_mod( 'mharty_tagnum_posts', '10' ) );
	} elseif ( $query->is_search ) {
		if ( isset($_GET['mh_searchform_submit']) ) {
			$postTypes = array();
			if ( !isset($_GET['mh-inc-posts']) && !isset($_GET['mh-inc-pages']) ) $postTypes = array('post');
			if ( isset($_GET['mh-inc-pages']) ) $postTypes = array('page');
			if ( isset($_GET['mh-inc-posts']) ) $postTypes[] = 'post';
			$query->set( 'post_type', $postTypes );

			if ( isset( $_GET['mh-month-choice'] ) && $_GET['mh-month-choice'] != 'no-choice' ) {
				$mh_year = substr($_GET['mh-month-choice'],0,4);
				$mh_month = substr($_GET['mh-month-choice'], 4, strlen($_GET['mh-month-choice'])-4);

				$query->set( 'year', absint($mh_year) );
				$query->set( 'monthnum', absint($mh_month) );
			}

			if ( isset( $_GET['mh-cat'] ) && $_GET['mh-cat'] != 0 )
				$query->set( 'cat', absint($_GET['mh-cat']) );
		}
		$query->set( 'posts_per_page', (int) get_theme_mod( 'mharty_searchnum_posts', '10' ) );
	} elseif ( $query->is_archive ) {
		$query->set( 'posts_per_page', (int) get_theme_mod( 'mharty_archivenum_posts', '10' ) );
	}
}
add_action( 'pre_get_posts', 'mh_custom_posts_per_page' );

/**
 * make page and post hidden metaboxes show by default
 */
function mh_show_hidden_metaboxes( $hidden, $screen ){
	if ( 'post' == $screen->base || 'page' == $screen->base )
		$hidden = array('slugdiv', 'trackbacksdiv', 'commentstatusdiv', 'commentsdiv', 'authordiv', 'revisionsdiv');

	return $hidden;
}
add_filter( 'default_hidden_meta_boxes', 'mh_show_hidden_metaboxes', 10, 2 );

/**
 * add an empty title for widgets to avid breaking the page layout in some cases
 */
function mh_widget_force_title( $title ){
	if ( $title == '' ) $title = ' ';

	return $title;
}
add_filter('widget_title','mh_widget_force_title');

/**
 * modify the comment counts to only reflect the number of comments minus pings
 */
if( version_compare( phpversion(), '4.4', '>=' ) ) add_filter('get_comments_number', 'mh_comment_count', 0, 2 );
function mh_comment_count( $count, $post_id ) {
	$is_ajax_active = defined( 'DOING_AJAX' ) && DOING_AJAX ? true : false;
	if ( ! is_admin() || $is_ajax_active) {
		global $id;
		$post_id = $post_id ? $post_id : $id;
		$get_comments = get_comments( array('post_id' => $post_id, 'status' => 'approve') );
		$comments_by_type = separate_comments($get_comments);
		return count($comments_by_type['comment']);
	} else {
		return $count;
	}
}

/**
 * Adds Next/Previous post navigations to single posts
 */
if ( ! function_exists( 'mh_post_navigation' ) ) :
function mh_post_navigation( $same_category = false ) {
	// Don't print empty markup if there's nowhere to navigate.
$previous = ( is_attachment() ) ? get_post( get_post()->post_parent ) : get_adjacent_post( $same_category, '', true );
$next     = get_adjacent_post( $same_category, '', false );

	if ( ! $next && ! $previous ) {
		return;
	}
	?>
		<?php
		if ( is_attachment() ) :
			previous_post_link( '%link', mh_wp_kses( __( '<div class="mh-post-navigation">Go to article</div>', 'mharty' ) ) );
		else :
            if ($previous) {
				 $image = get_the_post_thumbnail($previous->ID, 'mhc-post-thumbnail');
				$class = $image ? "with-image" : "without-image";
				//$previous->post_title
                previous_post_link( '%link',  '<div class="mh-post-navigation mh-post-prev '.$class.'"><div class="postnav-wrapper"><div class="nav-info-container"><span class="postnav-top"><span class="postnav-title">' . $previous->post_title . '</span></span></div>
				<span class="postnav-bottom"><span class="mh-postnav-icon"><i class="mh-icon-arrow-right mh-icon-before"></i></span><span class="postnav-image">'.$image.'</span></span></div></div>', $same_category );
            } //<div class="mh-postnav-icon"><i class="mh-icon-arrow-right"></i></div>
            if ($next) {
				 $image = get_the_post_thumbnail($next->ID, 'mhc-post-thumbnail');
				$class = $image ? "with-image" : "without-image";
				//$next->post_title 
			    next_post_link( '%link', '<div class="mh-post-navigation mh-post-next '.$class.'"><div class="postnav-wrapper"><div class="nav-info-container"><span class="postnav-top"><span class="postnav-title">' . $next->post_title . '</span></span></div>
				<span class="postnav-bottom"><span class="mh-postnav-icon"><i class="mh-icon-arrow-left mh-icon-before"></i></span><span class="postnav-image">'.$image.'</span></span></div></div>', $same_category );
            }
        endif;
}
endif;


/**
 * Related posts
 */
if ( ! function_exists( 'mh_related_posts' ) ) :
function mh_related_posts() {
global $post;
if ( is_attachment() ) return;
if ( !is_singular(array('post', 'project')) ) return;
$current_post = get_the_ID();
$categories = is_singular('post') ? get_the_category() : get_the_terms($current_post, 'project_category');
$cat = $related_title = '';
if ( $categories && ! is_wp_error( $categories ) ) {
foreach ($categories as $category) :
$cat = $category->term_id;
endforeach;
}
if (is_singular('post')){
	$related_title = get_theme_mod( 'mharty_related_posts_title' );
	$related_count = get_theme_mod( 'mharty_related_posts_count', 3 );
	$args = array(
	'category__and' => $cat,
	'posts_per_page' => $related_count,
	'post__not_in' => array($post->ID),
	'ignore_sticky_posts' => 1,
	'post_status' => 'publish',
	);
}else{
	$related_title = get_theme_mod( 'mharty_related_projects_title' );
	$related_count = get_theme_mod( 'mharty_related_projects_count', 3 );
	$args = array(
	'post_type'      => 'project',
	'posts_per_page' => $related_count,
	'post__not_in' => array($post->ID),
	'ignore_sticky_posts' => 1,
	'post_status' => 'publish',
	'tax_query' => array( 
		array(
			'taxonomy' => 'project_category',
			'field' => 'id',
			'terms' => explode( ',', $cat ),
			'operator' => 'IN',
		)
	),
	);
}
 $related = new WP_Query( $args );
 	if ( $related-> have_posts() ) :?>
    <div id="mh-related-posts" class="mh_list_posts">
   <?php  if ( '' !== $related_title ) {
				echo '<h2>' . $related_title . '</h2>';
   } ?>
 <ul>
  <?php
		while ( $related-> have_posts() ) : $related -> the_post(); ?> 
  <li class="list-post">
  
  <?php 
	
	//get the thumbnail
	$thumb = '';
	$width = 80;
	$width = (int) apply_filters( 'mhc-post-thumbnail', $width );
	$height = 80;
	$height = (int) apply_filters( 'mhc-post-thumbnail', $height );
	$classtext = '';
	$titletext = get_the_title();
	$thumbnail = get_thumbnail( $width, $height, $classtext, $titletext, $titletext, false, 'Blogimage' );
	$thumb = $thumbnail["thumb"];
	$no_thumb_class = '';

	//thumbnail class
	if ( '' === $thumb ){
		$no_thumb_class = ' post-no-thumb';
	}
	
	if ( '' !== $thumb  ) : ?>
   <a class="list-post-thumb" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
   <?php print_thumbnail( $thumb, $thumbnail["use_timthumb"], $titletext, $width, $height ); ?>
   </a>
	<?php endif; ?>
        <div class="list-post-info <?php echo $no_thumb_class; ?>">
        
		<h4 class="list-post-title"><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a><?php mh_after_post_title(); ?></h4>
        <div class="list-post-content"><?php truncate_post( 120 ); ?>
        <?php
		$readbutton = get_theme_mod('mharty_readmore_button', false);
		$more = sprintf(
			'%5$s <a href="%1$s" class="more-link%4$s" title="%2$s">%3$s</a>%6$s',
				esc_url( get_permalink() ),
				the_title_attribute(),
				apply_filters( 'mh_read_more_text_filter', esc_html__( 'Read more', 'mharty' )),
				true === $readbutton ? ' mhc_contact_submit' : '',
				true === $readbutton ? '<div class="mhc_more_link">' : '',
				true === $readbutton ? '</div>' : ''
			);
			echo $more;
		?>
        </div>
     
       </div>
       </li>
<?php  endwhile;  ?>
</ul></div>
<?php endif; wp_reset_query(); 
} 
endif;

/**
 * Quick Contact Form
 * @todo move this to composer
 */
if ( ! function_exists( 'mh_quick_contact_exclude' ) ) :
function mh_quick_contact_exclude(){
  if (true === get_theme_mod( 'mharty_show_quick_contact', false ) || true === get_theme_mod( 'mharty_show_quick_social', false ) ){
    $output = sprintf('<div class="mh_quick_form%1$s">',
      ( true === get_theme_mod( 'mharty_show_quick_contact', false ) && true === get_theme_mod( 'mharty_show_quick_social', false ) ) ? ' mh_quick_two_buttons' : ''   
                      );
  
  //quick contact
	if ( ( defined( 'MHARTY_COMPOSER' ) && MHARTY_COMPOSER ) ){
		if (true === get_theme_mod( 'mharty_show_quick_contact', false ) ){
			$captcha = false === get_theme_mod( 'mharty_quick_contact_captcha', false ) ? 'off' : 'on';
			$email = get_theme_mod( 'mharty_quick_contact_email', '');
			$title = get_theme_mod( 'mharty_quick_contact_title', '');
			$blurb = get_theme_mod( 'mharty_quick_contact_blurb', '');
      $avatar = get_theme_mod( 'mharty_quick_contact_avatar', '');
      $button_text = get_theme_mod( 'mharty_quick_contact_button_text', '');
			$message = get_theme_mod( 'mharty_quick_contact_message', esc_html__( 'Thank you for contacting us.', 'mharty'));	
      $color = get_theme_mod( 'mharty_quick_contact_color', 'light' );
      $button_color = get_theme_mod( 'mharty_quick_contact_button_color', 'dark' );
			$use_redirect = false === get_theme_mod( 'mharty_quick_contact_use_redirect', false ) ? 'off' : 'on';
			$redirect_url = get_theme_mod( 'mharty_quick_contact_redirect_url', '');
			$class = ('' == $title && '' == $blurb ) ? ' mh_quick_form_no_header' : '';
      $class .= ('' !== $button_text ) ? ' mh_quick_form_button_has_text' : '';
      $class .= " mh_quick_form_{$color}";
      $class .= 'dark' !== $button_color ? ' mh_quick_form_button_light' : '';
			$output .= sprintf('<div class="mh_quick_form_item mh_quick_item_contact%1$s">
      <div class="mh_quick_form_button mh_adjust_corners mh-icon-before">%2$s</div>
      <div class="mh_quick_form_inner">
      <div class ="mh_quick_form_inner_header">
      %3$s
      %4$s
      %5$s
      </div>
      %6$s
      </div></div>',
        esc_attr($class),
        '' !== $button_text ? '<span class="mh_quick_form_button_text">' . esc_html( $button_text ) . '</span>' : '',
        '' !== $title ? '<h4>' . esc_html( $title ) . '</h4>' : '',
        '' !== $avatar ? '<div class="mh_quick_form_avatar"><img src="' . esc_url($avatar) . '" /></div>' : '',
        '' !== $blurb ? '<p>' . esc_html( $blurb ) . '</p>' : '',
        do_shortcode('[mhc_contact_form  email="' . $email . '" captcha="' . $captcha .'" title="" blurb="" message="' . esc_html($message) . '" use_redirect="' . $use_redirect . '" redirect_url="' . esc_url($redirect_url) . '" message_pattern="(%%Name%% - %%Email%%) : %%Message%%" background_layout="' . $color . '" button_style="solid" module_class=" mh-form-transparent-bordered"][mhc_contact_field field_title="" field_type="text" field_id="Message" required_mark="on"][/mhc_contact_field]
[mhc_contact_field field_title="' . esc_html__( 'Your Email', 'mharty') . '" field_type="email" field_id="Email" required_mark="on" fullwidth_field="on"][/mhc_contact_field]
[mhc_contact_field field_title="' . esc_html__( 'Your Name', 'mharty') . '" field_type="input" field_id="Name" required_mark="on" fullwidth_field="on"][/mhc_contact_field]
[/mhc_contact_form]')
        );
			
		}
	}
  // quick social
  if (true === get_theme_mod( 'mharty_show_quick_social', false ) ){
    $network = get_theme_mod( 'mharty_quick_social_list', 'twitter');
    $url = get_theme_mod( 'mharty_quick_social_url', '#');
    $output .= sprintf('<div class="mh_quick_form_item mh_quick_item_social mh-social-bg-color"><a href="%2$s" target="_blank"><div class="mh_quick_form_button mh_adjust_corners mh-icon-before mh-social-%1$s %1$s"><i></i></div></a></div>',
    '' !== $network ? $network : '',
    '' !== $url ? $url : ''
 );
  }
    
  echo $output;
  echo '</div>';
}
}
endif;
add_action('mh_before_end_container', 'mh_quick_contact_exclude');
 
/**
 * Display custom comments
 */
if ( ! function_exists( 'mh_custom_comments_display' ) ) :
function mh_custom_comments_display($comment, $args, $depth) {
	$GLOBALS['comment'] = $comment; ?>
	<li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
		<article id="comment-<?php comment_ID(); ?>" class="comment-body clearfix">
			<div class="comment_avatar">
                <?php echo get_avatar( $comment, $size = '80', 'mystery', esc_attr( get_comment_author() ) ); ?>
			</div>

			<div class="comment_postinfo">
				<?php printf( '<span class="fn">%s</span>', get_comment_author_link() ); ?>
				<span class="comment_date">
				<?php
					/* translators: 1: date, 2: time */
					printf( esc_html__( 'on %1$s at %2$s', 'mharty' ), get_comment_date(), get_comment_time() );
				?>
				</span>
				<?php edit_comment_link( '', ' ' ); ?>
			<?php
				$mh_comment_reply_link = get_comment_reply_link( array_merge( $args, array(
					'reply_text' => esc_attr__( 'Reply', 'mharty' ),
					'depth'      => (int) $depth,
					'max_depth'  => (int) $args['max_depth'],
				) ) );
			?>
			</div> <!-- .comment_postinfo -->

			<div class="comment_area">
				<?php if ( '0' == $comment->comment_approved ) : ?>
					<em class="moderation"><?php esc_html_e('Your comment is awaiting moderation.','mharty') ?></em>
					<br />
				<?php endif; ?>

				<div class="comment-content clearfix">
				<?php
					comment_text();
					if ( $mh_comment_reply_link ) echo '<span class="reply-container">' . $mh_comment_reply_link . '</span>';
				?>
				</div> <!-- end comment-content-->
			</div> <!-- end comment_area-->
		</article> <!-- .comment-body -->
<?php }
endif;

/**
 * change read more text via customizer
 */
function mh_custom_read_more_text_filter() {
    if ( '' !== get_theme_mod( 'mharty_readmore_text', esc_html__('Read more', 'mharty') ))
    return esc_attr( get_theme_mod( 'mharty_readmore_text', esc_html__('Read more', 'mharty') ) );
}
add_filter('mh_read_more_text_filter', 'mh_custom_read_more_text_filter');

/**
 * hex2rgb
 */
if ( !function_exists( 'hex2rgb' ) ) :
function hex2rgb( $color ) {
	if ( substr( $color, 0, 1 ) == '#' ) {
		$color = substr( $color, 1 );
	}
	
	if ( strlen( $color ) == 6 ) {
		list( $r, $g, $b ) = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
	} elseif ( strlen( $color ) == 3 ) {
		list( $r, $g, $b ) = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
	} else {
		return false;
	}
	
	$r = hexdec( $r );
	$g = hexdec( $g );
	$b = hexdec( $b );
	
	return implode( ', ', array( $r, $g, $b ) );
}
endif;

/**
 * get accent color
 */
if ( ! function_exists( 'mh_get_accent_color' ) ) :
function mh_get_accent_color() {
	$color = get_theme_mod( 'accent_color', '#4FD4FF' );
	if ( strpos( $color, "#" ) != false ) {
		$color = "#" . $color;
	}
	return $color;
}
endif;

/**
 * add Home link to menu
 */
function mh_add_home_link( $args ) {
	$args['show_home'] = true;
	return $args;
}
add_filter( 'wp_page_menu_args', 'mh_add_home_link' );

/**
 * Menu fallback. Link to the menu editor
 */
function link_to_menu_editor( $args ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    // see wp-includes/nav-menu-template.php for available arguments
    extract( $args );

    $link = $link_before
        . '<a href="' . admin_url( 'nav-menus.php' ) . '">' . $before . __('Manage Menus', 'mharty') . $after . '</a>'
        . $link_after;

    // We have a list
    if ( FALSE !== stripos( $items_wrap, '<ul' )
        or FALSE !== stripos( $items_wrap, '<ol' )
    )
    {
        $link = "<li>$link</li>";
    }

    $output = sprintf( $items_wrap, $menu_id, $menu_class, $link );
    if ( ! empty ( $container ) )
    {
        $output  = "<$container class='$container_class' id='$container_id'>$output</$container>";
    }

    if ( $echo )
    {
        echo $output;
    }

    return $output;
}

/**
 * list pings
 */
if ( ! function_exists( 'mh_list_pings' ) ) :
function mh_list_pings($comment, $args, $depth) {
	$GLOBALS['comment'] = $comment; ?>
	<li id="comment-<?php comment_ID(); ?>"><?php comment_author_link(); ?> - <?php comment_excerpt(); ?>
<?php }
endif;

/**
 * check for WP 5
 */
if ( ! function_exists( 'mhc_is_wp_5' ) ) :
	function mhc_is_wp_5() {
		if ( version_compare( $GLOBALS['wp_version'], '5.0-beta', '>' ) ) {
			return true;
		}
		return false;
	}
endif;

/**
 * check for WP 5.6 to update jquery
 */
if ( ! function_exists( 'mhc_is_wp_pre_5_6' ) ) :
function mhc_is_wp_pre_5_6() {
	global $wp_version;

	$wp_major_version = substr( $wp_version, 0, 3 );

	if ( version_compare( $wp_major_version, '5.6', '<' ) ) {
		return true;
	}

	return false;
}
endif;

/**
 * Fix ro scroll to anchor not working on chrome
 */
function mh_fix_scroll_to_anchor() {
	$add_scroll_to_anchor_fix = mh_get_option( 'mharty_scroll_to_anchor_fix' );

	if ( true === $add_scroll_to_anchor_fix ) {
		echo '<script>
				document.addEventListener( "DOMContentLoaded", function( event ) {
					window.mh_location_hash = window.location.hash;
					if ( "" !== window.mh_location_hash ) {
						// Prevent jump to anchor - Firefox
						window.scrollTo( 0, 0 );
						var mh_anchor_element = document.getElementById( window.mh_location_hash.substring( 1 ) );
						if( mh_anchor_element === null ) {
						    return;
						}
						window.mh_location_hash_style = mh_anchor_element.style.display;
						// Prevent jump to anchor - Other Browsers
						mh_anchor_element.style.display = "none";
					}
				} );
		</script>';
	}
}
add_action( 'wp_head', 'mh_fix_scroll_to_anchor', 9 );

/**
 * array of social network quick contact
 * @todo use this for social_icons.php
 */
function mh_social_network_list() {
  $networks = array(
    'twitter' => 'Twitter',
    'facebook' => 'Facebook',
    'instagram' => 'Instagram',
    'youtube' => 'YouTube',
    'linkedin' => 'LinkedIn',
    'behance' => 'Behance',
    'dribbble' => 'Dribbble',
    'flickr' => 'Flickr',
    'skype' => 'Skype',
    'soundcloud' => 'SoundCloud',
    'telegram' => 'Telegram',
    'mixlr' => 'Mixlr',
    'periscope' => 'Periscope',
    'younow' => 'YouNow',
    'snapchat' => 'Snapchat',
    'tripadvisor' => 'TripAdvisor',
    'pinterest' => 'Pinterest',
    'whatsapp' => 'WhatsApp',
    'slack' => 'Slack',
    'github' => 'Github',
    'wordpress' => 'WordPress',
    'tiktok' => 'TikTok',
    'clubhouse' => 'Clubhouse',
    'zoom' => 'Zoom',
    'rss' => 'RSS',
  );
  return $networks;
}

/**
 * bolck editor active?
 */
if ( ! function_exists( 'mh_is_gutenberg_active' ) ):
function mh_is_gutenberg_active() {
	global $wp_version;

	static $has_wp5_plus = null;

	if ( is_null( $has_wp5_plus ) ) {
		$has_wp5_plus = version_compare( $wp_version, '5.0-alpha1', '>=' );
	}

	return $has_wp5_plus || function_exists( 'is_gutenberg_page' );
}
endif;


/**
 * block editor active enabled for the current post
 */
if ( ! function_exists( 'mh_is_gutenberg_enabled' ) ):
function mh_is_gutenberg_enabled() {
	if ( function_exists( 'is_gutenberg_page' ) ) {
		return mh_is_gutenberg_active() && is_gutenberg_page() && has_filter( 'replace_editor', 'gutenberg_init' );
	}

	return mh_is_gutenberg_active() && function_exists( 'use_block_editor_for_post' ) && use_block_editor_for_post( null );
}
endif;