<?php if ( ! defined( 'ABSPATH' ) ) { die( 'Direct access forbidden.' ); }

/**
 * Return value from the database of an option from the framework’s settings page.
 * Settings options are located in framework-customizations/theme/options/settings.php.
 * @return string
 */
if ( ! function_exists( 'wishbone_option' ) ){
	function wishbone_option( $id, $default = null ){
		if( function_exists( 'fw_get_db_settings_option' ) ){
			$value = fw_get_db_settings_option( $id );
			if( '' !== $value ){
				return $value;
			} elseif( $value == false or $value === "" or $value == null or !$value or empty( $value ) ) {
				return $default;
			}
		}
        return $default;
	}
}

/**
 * Return value from the database of an option from Unyson Metabox/custom field.
 * Settings options are located in framework-customizations/theme/options/posts/page.php.
 * @return string
 * @var $post_id
 * @var $option_id
 * @var $default_value
 */
if ( ! function_exists( 'wishbone_meta' ) ){
	function wishbone_meta( $option_id, $default = null ){
		$post_id = get_the_id();
		if( function_exists( 'fw_get_db_post_option' ) ){
			$option = fw_get_db_post_option( $post_id, $option_id );
	        if (empty($option)) {
	            $option = $default;
	        }
	        return $option;
		} else {
			return null;
		}
	}
}

/**
 * Passing HTML
 * @return string
 */
function wishbone_pass_html( $string ){
	$output = $string;
	return $output;
}

/**
 * Register Droid Serif Google font.
 *
 * @return string
 */
function wishbone_theme_font_url() {
	$font_url = '';
    
    /*
    Translators: If there are characters in your language that are not supported
    by chosen font(s), translate this to 'off'. Do not translate into your own language.
     */
    if ( 'off' !== _x( 'on', 'Google font: on or off', 'jt-wishbone' ) ) {
        $font_url = add_query_arg( 'family', urlencode( 'Merriweather:400,300,300italic,400italic,700,700italic,900,900italic|Open Sans:400,300,300italic,400italic,600,600italic,700,800,700italic,800italic' ), "//fonts.googleapis.com/css" );
    }
    return $font_url;
}

/**
 * Getter function for Featured Content Plugin.
 *
 * @return array An array of WP_Post objects.
 */
function fw_theme_get_featured_posts() {
	/**
	 * @param array|bool $posts Array of featured posts, otherwise false.
	 */
	return apply_filters( 'fw_theme_get_featured_posts', array() );
}

/**
 * A helper conditional function that returns a boolean value.
 *
 * @return bool Whether there are featured posts.
 */
function fw_theme_has_featured_posts() {
	return ! is_paged() && (bool) fw_theme_get_featured_posts();
}

if ( ! function_exists( 'fw_theme_the_attached_image' ) ) : /**
 * Print the attached image with a link to the next attached image.
 */ {
	function fw_theme_the_attached_image() {
		$post = get_post();
		/**
		 * Filter the default attachment size.
		 *
		 * @param array $dimensions {
		 *     An array of height and width dimensions.
		 *
		 * @type int $height Height of the image in pixels. Default 810.
		 * @type int $width Width of the image in pixels. Default 810.
		 * }
		 */
		$attachment_size     = apply_filters( 'fw_theme_attachment_size', array( 810, 810 ) );
		$next_attachment_url = wp_get_attachment_url();

		/*
		 * Grab the IDs of all the image attachments in a gallery so we can get the URL
		 * of the next adjacent image in a gallery, or the first image (if we're
		 * looking at the last image in a gallery), or, in a gallery of one, just the
		 * link to that image file.
		 */
		$attachment_ids = get_posts( array(
			'post_parent'    => $post->post_parent,
			'fields'         => 'ids',
			'numberposts'    => - 1,
			'post_status'    => 'inherit',
			'post_type'      => 'attachment',
			'post_mime_type' => 'image',
			'order'          => 'ASC',
			'orderby'        => 'menu_order ID',
		) );

		// If there is more than 1 attachment in a gallery...
		if ( count( $attachment_ids ) > 1 ) {
			foreach ( $attachment_ids as $attachment_id ) {
				if ( $attachment_id == $post->ID ) {
					$next_id = current( $attachment_ids );
					break;
				}
			}

			// get the URL of the next image attachment...
			if ( $next_id ) {
				$next_attachment_url = get_attachment_link( $next_id );
			} // or get the URL of the first image attachment.
			else {
				$next_attachment_url = get_attachment_link( array_shift( $attachment_ids ) );
			}
		}

		printf( '<a href="%1$s" rel="attachment">%2$s</a>',
			esc_url( $next_attachment_url ),
			wp_get_attachment_image( $post->ID, $attachment_size )
		);
	}
}
endif;

if ( ! function_exists( 'fw_theme_list_authors' ) ) : /**
 * Print a list of all site contributors who published at least one post.
 */ {
	function fw_theme_list_authors() {
		$contributor_ids = get_users( array(
			'fields'  => 'ID',
			'orderby' => 'post_count',
			'order'   => 'DESC',
			'who'     => 'authors',
		) );

		foreach ( $contributor_ids as $contributor_id ) :
			$post_count = count_user_posts( $contributor_id );

			// Move on if user has not published a post (yet).
			if ( ! $post_count ) {
				continue;
			}
			?>

			<div class="contributor">
				<div class="contributor-info">
					<div class="contributor-avatar"><?php echo get_avatar( $contributor_id, 132 ); ?></div>
					<div class="contributor-summary">
						<h2 class="contributor-name"><?php echo get_the_author_meta( 'display_name',
								$contributor_id ); ?></h2>

						<p class="contributor-bio">
							<?php echo get_the_author_meta( 'description', $contributor_id ); ?>
						</p>
						<a class="button contributor-posts-link"
						   href="<?php echo esc_url( get_author_posts_url( $contributor_id ) ); ?>">
							<?php printf( _n( '%d Article', '%d Articles', $post_count, 'jt-wishbone' ), $post_count ); ?>
						</a>
					</div>
					<!-- .contributor-summary -->
				</div>
				<!-- .contributor-info -->
			</div><!-- .contributor -->

		<?php
		endforeach;
	}
}
endif;

/**
 * Minify CSS
 */
function wishbone_minify_css($input) {
    if(trim($input) === "") return $input;
    return preg_replace(
        array(
            // Remove comment(s)
            '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')|\/\*(?!\!)(?>.*?\*\/)|^\s*|\s*$#s',
            // Remove unused white-space(s)
            '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~+]|\s*+-(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si',
            // Replace `0(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)` with `0`
            '#(?<=[\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si',
            // Replace `:0 0 0 0` with `:0`
            '#:(0\s+0|0\s+0\s+0\s+0)(?=[;\}]|\!important)#i',
            // Replace `background-position:0` with `background-position:0 0`
            '#(background-position):0(?=[;\}])#si',
            // Replace `0.6` with `.6`, but only when preceded by `:`, `,`, `-` or a white-space
            '#(?<=[\s:,\-])0+\.(\d+)#s',
            // Minify string value
            '#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si',
            '#(\/\*(?>.*?\*\/))|(\burl\()([\'"])([^\s]+?)\3(\))#si',
            // Minify HEX color code
            '#(?<=[\s:,\-]\#)([a-f0-6]+)\1([a-f0-6]+)\2([a-f0-6]+)\3#i',
            // Replace `(border|outline):none` with `(border|outline):0`
            '#(?<=[\{;])(border|outline):none(?=[;\}\!])#',
            // Remove empty selector(s)
            '#(\/\*(?>.*?\*\/))|(^|[\{\}])(?:[^\s\{\}]+)\{\}#s'
        ),
        array(
            '$1',
            '$1$2$3$4$5$6$7',
            '$1',
            ':0',
            '$1:0 0',
            '.$1',
            '$1$3',
            '$1$2$4$5',
            '$1$2$3',
            '$1:0',
            '$1$2'
        ),
    $input);
}

/**
 * Primary or Secondary Chooser
 */
if(!function_exists('wishbone_famchoose')){
	function wishbone_famchoose( $which = null ){
		$fontpair1 = wishbone_option('font_pair_1');
		$fontpair2 = wishbone_option('font_pair_2');
		if( 'primary' == $which ){
			$family = $fontpair1['family'];
		} elseif( 'secondary' == $which ){
			$family = $fontpair2['family'];
		}
		return $family;
	}
}

/**
 * Render Font Family
 */
if(!function_exists('wishbone_fontfamily')){
	function wishbone_fontfamily( $whichfamily = null ){
		$family = wishbone_famchoose( $whichfamily ); ?>
		font-family: "<?php echo wishbone_pass_html( $family ) ?>";
	<?php
	}
}

/**
 * Get font weight
 */
if(!function_exists('wishbone_fontweight')){
	function wishbone_fontweight( $weight = null ){
		if( $weight ){
			echo "font-weight: " . $weight . ";\n";
		}
	}
}

/**
 * Get font weight
 */
if(!function_exists('wishbone_fontstyle')){
	function wishbone_fontstyle( $style = null ){
		if( !empty( $style ) && is_array( $style ) ){
			if( array_key_exists('italic', $style) ){
				echo "font-style: italic;\n";
			}
			if( array_key_exists('underline', $style) ){
				echo "text-decoration: underline!important;\n";
			}
		}
	}
}

/**
 * Render Font Size
 */
if(!function_exists('wishbone_fontsize')){
	function wishbone_fontsize($size = null){
		if($size && $size != '9' ){ /* 9 means default options */
			echo "font-size: " . $size . "px;\n";
		}
	}
}

/**
 * Render Line Height
 */
if(!function_exists('wishbone_lineheight')){
	function wishbone_lineheight($lineheight = null){
		if($lineheight){
			$final_lineheight = $lineheight;
			echo "line-height: " . $lineheight . "px;\n";
		}
	}
}

/**
 * Render Line Height
 */
if(!function_exists('wishbone_fontcolor')){
	function wishbone_fontcolor($wishbone_fontcolor = null){
		if($wishbone_fontcolor){
			$color = $wishbone_fontcolor;
			echo "color: " . $color . ";\n";
		}
	}
}

/**
 * GENERATE FONT CSS
 */
if(!function_exists('wishbone_fontcss')){
	function wishbone_fontcss( $family=null, $size=null, $weight=null, $style=null, $lineheight=null, $color=null ){
		wishbone_fontfamily( $family );
		wishbone_fontsize( $size );
		wishbone_fontweight( $weight );
		wishbone_fontstyle( $style );
		wishbone_lineheight( $lineheight );
		wishbone_fontcolor( $color );
	} // function wishbone_fontcss()
}

/**
 * Get post excerpt by post ID.
 *
 * @return string
 */
function wishbone_post_excerpt() {
    $post = get_the_ID();
    setup_postdata( $post );
    $the_excerpt = get_the_excerpt();
    wp_reset_postdata();
    return $the_excerpt;
}

/*
 * Get upload directory details
 */
function wishbone_upl(){

	$upload_dir = wp_upload_dir(); // Grab uploads folder array
	$cssdirname = 'wishbone-static'; // Set folder name
	$uploadurl = $upload_dir['baseurl'] . '/'. $cssdirname; // get wishbone directory url
	$uploaddir = trailingslashit( $upload_dir['basedir'] ) . $cssdirname . '/'; // Set storage directory path

	$out['url'] = $uploadurl;
	$out['dir'] = $uploaddir;

	return $out;
}

function HTMLToRGB($htmlCode){
    if($htmlCode[0] == '#')
      $htmlCode = substr($htmlCode, 1);

    if (strlen($htmlCode) == 3)
    {
      $htmlCode = $htmlCode[0] . $htmlCode[0] . $htmlCode[1] . $htmlCode[1] . $htmlCode[2] . $htmlCode[2];
    }

    $r = hexdec($htmlCode[0] . $htmlCode[1]);
    $g = hexdec($htmlCode[2] . $htmlCode[3]);
    $b = hexdec($htmlCode[4] . $htmlCode[5]);

    return $b + ($g << 0x8) + ($r << 0x10);
  }

function RGBToHSL($RGB) {
    $r = 0xFF & ($RGB >> 0x10);
    $g = 0xFF & ($RGB >> 0x8);
    $b = 0xFF & $RGB;

    $r = ((float)$r) / 255.0;
    $g = ((float)$g) / 255.0;
    $b = ((float)$b) / 255.0;

    $maxC = max($r, $g, $b);
    $minC = min($r, $g, $b);

    $l = ($maxC + $minC) / 2.0;

    if($maxC == $minC)
    {
      $s = 0;
      $h = 0;
    }
    else
    {
      if($l < .5)
      {
        $s = ($maxC - $minC) / ($maxC + $minC);
      }
      else
      {
        $s = ($maxC - $minC) / (2.0 - $maxC - $minC);
      }
      if($r == $maxC)
        $h = ($g - $b) / ($maxC - $minC);
      if($g == $maxC)
        $h = 2.0 + ($b - $r) / ($maxC - $minC);
      if($b == $maxC)
        $h = 4.0 + ($r - $g) / ($maxC - $minC);

      $h = $h / 6.0;
    }

    $h = (int)round(255.0 * $h);
    $s = (int)round(255.0 * $s);
    $l = (int)round(255.0 * $l);

    return (object) Array('hue' => $h, 'saturation' => $s, 'lightness' => $l);
}

/**
 * Decide how to display Post Thumbnail
 *
 * If standard post, quote, image, use featured image,
 * video and audio won't display featured image.
 */
if( !function_exists('wishbone_post_media') ){
	function wishbone_post_media(){
		global $post;
		$format = get_post_format();
		if ( false === $format || 'image' == $format ) {
			// do nothing
		}

		elseif( 'gallery' == $format ){
			$items = wishbone_meta('gallery');

			/* Slideshow */
			if( !empty( $items ) ){
				echo '<div class="owl-carousel post-gallery owl-theme">';
				foreach ($items as $item) {
					$item_id = $caption = '';

					$item_id =  $item['attachment_id'];
					$metadata =  get_post( $item_id );

					$image_size = 'wishbone_wide_featured';
					$rawurl = wp_get_attachment_image_src( $item_id, 'wishbone_wishbonewideslider' );
					$linkto = wp_get_attachment_url( $item_id );
					$image_url = $rawurl[0];
					echo '<div>';
					echo '<a href="'.$linkto.'">';
					echo '<img src="'.$image_url.'" alt="" />';
					echo '</a>';
					if($metadata->post_excerpt){
						echo '<div class="wishbone_post_gallery_caption">'.$metadata->post_excerpt.'</div>';
					}
					echo '</div>';
				}
				echo '</div>';
			}
		}

		elseif( 'audio' == $format ){
			$audio = wishbone_meta('audio');
			if( !empty($audio) ){
				$type = $url = $file = $iframe = '';

				if( !empty($audio['type']) ){
					$type = $audio['type'];
				}

				if( !empty($audio['url']['url']) ){
					$url = $audio['url']['url'];
				}

				if( !empty($audio['upload']['upload']['url']) ){
					$file = $audio['upload']['upload']['url'];
				}

				if( !empty($audio['iframe']['iframe']) ){
					$iframe = $audio['iframe']['iframe'];
				}

				/* URL EMBED */
				if( 'url' == $type && !empty($url) ){
					echo wp_oembed_get($url, array('width'=>840));
				}

				elseif( 'upload' == $type ){
					echo do_shortcode( '[audio src="'. $file .'" preload="metadata"]' );
				}

				elseif( 'iframe' == $type ){
					echo wishbone_pass_html( $iframe );
				}

			}
		}

		elseif( 'video' == $format ){
			$video = wishbone_meta('video');
			if( !empty($video) ){

				if( !empty($video['type']) ){
					$type = $video['type'];
				}

				if( !empty($video['url']['url']) ){
					$url = $video['url']['url'];
				}

				if( !empty($video['upload']['upload']['url']) ){
					$file = $video['upload']['upload']['url'];
				}

				if( !empty($video['iframe']['iframe']) ){
					$iframe = $video['iframe']['iframe'];
				}

				/* URL EMBED */
				if( 'url' == $type && !empty($url) ){
					echo wp_oembed_get($url);
				}

				/* Upload Fle */
				elseif( 'upload' == $type ){
					if( has_post_thumbnail() ){
			            $thumbid = get_post_thumbnail_id();
						$image_size = 'wishbone_post_thumb';
						$rawurl = wp_get_attachment_image_src( $thumbid, $image_size );
					}
					echo do_shortcode( '[video src="'. $file .'" preload="metadata" width="840"]' );
				}

				elseif( 'iframe' == $type ){
					echo wishbone_pass_html( $iframe );
				}

			}
		}

	    if( is_attachment() ){
	        $thumb = get_post_thumbnail_id();
	        $thispageid = get_the_ID();
	        $img_url = wp_get_attachment_url();
	        echo '<img src="'. $img_url .'" alt=""/>';
	    }
	}
}

/**
 * Human count dif
 * internal use only
 */
function wishbone_fancy_number($n, $precision = 1) {
    if ($n < 1000) {
        // Anything less than a thousand
        $n_format = number_format($n);
    } elseif ($n > 1000 && $n < 10000) {
    	$n_format = number_format($n / 1000, $precision) . 'K';
    } elseif ($n < 1000000000) {
        // Anything less than a billion
        $n_format = number_format($n / 1000000, $precision) . 'M';
    } else {
        // At least a billion
        $n_format = number_format($n / 1000000000, $precision) . 'B';
    }

    return $n_format;
}

/**
 * Validate Real Domain
 */
function wishbone_filter_var_domain($domain)
{
    if(stripos($domain, 'http://') === 0)
    {
        $domain = substr($domain, 7); 
    }
     
    ///Not even a single . this will eliminate things like abcd, since http://abcd is reported valid
    if(!substr_count($domain, '.'))
    {
        return false;
    }
     
    if(stripos($domain, 'www.') === 0)
    {
        $domain = substr($domain, 4); 
    }
     
    $again = 'http://' . $domain;
    return filter_var ($again, FILTER_VALIDATE_URL);
}

/**
 * Post share counter
 * is basically just retrieve the json data from faceboko API.
 */
if( !function_exists('wishbone_sharecount') ):
	function wishbone_sharecount( $url = null ){
		global $post;
		$json = $count = '';
		$facebooktotal = $linkedintotal = $googleplustotal = $grandtotal = 0;

		// If no url given, return 0;
		if( !isset( $url ) ) return "0";

		$args = array(
            'timeout' => 360,
            'httpversion' => '1.1'
        );

		$geturl = $url;
		$grandtotal = get_transient('zl_post_share_'.$post->ID);
		if (false === $grandtotal ){
			// if url has valid domain, return true
			if( wishbone_filter_var_domain( $geturl )){
				
				// encode first to use the graph API
				$encodedurl = urlencode( $geturl );

				// FACEBOOK
				$facebook = wp_remote_get("http://graph.facebook.com/?id=". $encodedurl , $args);
				if( !is_wp_error( $facebook ) ){
					// if an array, return true
					if( is_array( $facebook ) ){
						$facebook = wp_remote_retrieve_body( $facebook );
						$facebook = json_decode($facebook, true);
						//print_r($json);
						$facebooktotal = $facebook['share']['share_count']; 
					}
				}

				// LinkedIn
				$linkedin = wp_remote_get("https://www.linkedin.com/countserv/count/share?url=".$encodedurl."&format=json", $args);
				if( !is_wp_error( $linkedin ) ){
					// if an array, return true
					if( is_array( $linkedin ) ){
						$linkedin = wp_remote_retrieve_body( $linkedin );
						$linkedin = json_decode($linkedin, true);
						//print_r($json);
						$linkedintotal = $linkedin['count'];
					}
				}

				// Google
				$googleplus = wp_remote_request('https://clients6.google.com/rpc',
				array(
				    'method'    => 'POST',
				    'body'      => '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"'.rawurldecode($geturl).'","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]',
				    'headers' => array('Content-Type' => 'application/json')
				));
				if( !is_wp_error( $googleplus ) ){
					// if an array, return true
					if( is_array( $googleplus ) ){
						$googleplus = wp_remote_retrieve_body( $googleplus );
						$googleplus = json_decode($googleplus, true);
						if(isset($googleplus[0]['result']['metadata']['globalCounts']['count'])){
						   $googleplustotal = intval($googleplus[0]['result']['metadata']['globalCounts']['count']);
						}else{
						   $googleplustotal = 0;
						}
					}
				}
				
				$grandtotal = (int) $facebooktotal + $linkedintotal + $googleplustotal;

				$grandtotal = wishbone_fancy_number($grandtotal);

			} else {
				// if in localhost, generate fake number
				$grandtotal = wishbone_fancy_number( mt_rand(1000, 10000) );
			}
			set_transient( 'zl_post_share_'.$post->ID, $grandtotal, HOUR_IN_SECONDS );
		}
		
		return $grandtotal;
	}
endif;

function zl_theme_thumb($url, $width, $height=0, $align='') {
	if( function_exists('mr_image_resize') ){
		return mr_image_resize($url, $width, $height, true, $align, false);
	}
	return null;
}

/**
 * Automatic cropped thumb url
 */
if( !function_exists('wishbone_thumb_src') ):
	function wishbone_thumb_src( $width, $height, $markup = false ){
		global $post;
		if( function_exists('mr_image_resize') ){
			$thumb = get_post_thumbnail_id();
			$img_url = wp_get_attachment_url( $thumb );
			$image = zl_theme_thumb($img_url, $width, $height, 'c', false);
			if( false == $markup ){
				return $image;
			} elseif( true == $markup ){
				$imgtag = '<img src="'.$image.'" class="post-thumbnail" alt="" />';
				return $imgtag;
			}
		} else {
			return null;
		}
	}
endif;